{
  "id": "suslabsRedditWatchdogV1",
  "name": "SusLabs - optional independent Reddit collection watchdog",
  "active": false,
  "nodes": [
    {
      "id": "manual",
      "name": "Manual test",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "schedule",
      "name": "Independent five-minute check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        180
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 5
            }
          ]
        }
      },
      "disabled": true
    },
    {
      "id": "config",
      "name": "Configure watchdog",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "parameters": {
        "jsCode": "'use strict';\n// Pure, offline-testable policy. Embedded verbatim in the n8n Code nodes.\nfunction stable(value) {\n  if (Array.isArray(value)) return '[' + value.map(stable).join(',') + ']';\n  if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + stable(value[k])).join(',') + '}';\n  return JSON.stringify(value);\n}\nfunction validateConfig(c) {\n  for (const k of ['taskId', 'actorId', 'monitorName', 'watchdogKey', 'stateTableName']) {\n    if (typeof c[k] !== 'string' || !c[k].trim() || /REPLACE|YOUR_/i.test(c[k])) throw Error('Configure ' + k + ' before running.');\n  }\n  for (const k of ['taskId', 'actorId']) if (!/^[A-Za-z0-9]+$/.test(c[k])) throw Error(k + ' must be an Apify ID, not a URL.');\n  for (const [k, min, max] of [['expectedIntervalMinutes', 1, 10080], ['graceMinutes', 0, 1440], ['maxRunMinutes', 1, 1440], ['reminderHours', 0, 720]]) {\n    if (!Number.isFinite(c[k]) || c[k] < min || c[k] > max) throw Error('Invalid ' + k);\n  }\n  if (!Number.isInteger(c.gapAlertAfterRuns ?? 2) || (c.gapAlertAfterRuns ?? 2) < 1 || (c.gapAlertAfterRuns ?? 2) > 100) throw Error('gapAlertAfterRuns must be an integer from 1 to 100.');\n  if (!Array.isArray(c.expectedSources) || !c.expectedSources.length || c.expectedSources.length > 100) throw Error('Configure 1–100 exact expected source descriptors.');\n  if (c.expectedSources.some(s => !s || typeof s !== 'object' || Array.isArray(s) || !s.kind)) throw Error('Expected sources must be SUMMARY source descriptor objects.');\n  if (new Set(c.expectedSources.map(stable)).size !== c.expectedSources.length) throw Error('Duplicate expected source.');\n  if (typeof c.deliveryEnabled !== 'boolean') throw Error('deliveryEnabled must be boolean.');\n  if (c.deliveryEnabled && (!/^https:\\/\\//.test(c.alertUrl) || /example\\.(com|invalid)|REPLACE/i.test(c.alertUrl))) throw Error('Configure your HTTPS notification receiver.');\n  return c;\n}\nfunction timestamp(value, now) {\n  const n = typeof value === 'string' && value ? Date.parse(value) : NaN;\n  return Number.isFinite(n) && n <= now + 300000 ? n : null;\n}\nfunction responseBody(response) {\n  if (!response || response.error || response.statusCode !== 200 || !response.body || typeof response.body !== 'object') return null;\n  return response.body;\n}\nfunction selectRuns(c, response, now) {\n  const body = responseBody(response);\n  const runs = body?.data?.items;\n  if (!Array.isArray(runs)) return { apiOk: false, readRecords: false };\n  // The task endpoint is the scope boundary; never scan all Actor runs.\n  if (runs.some(r => r.actId !== c.actorId || r.actorTaskId !== c.taskId || !timestamp(r.startedAt, now) || !/^[A-Za-z0-9]+$/.test(r.id))) {\n    return { apiOk: false, readRecords: false, identityError: true };\n  }\n  runs.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));\n  const terminal = runs.find(r => ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(r.status)) || null;\n  return { apiOk: true, latest: runs[0] || null, terminal,\n    readRecords: Boolean(terminal?.status === 'SUCCEEDED' && /^[A-Za-z0-9]+$/.test(terminal.defaultKeyValueStoreId)) };\n}\nfunction evaluate(c, oldState, observation, now) {\n  validateConfig(c);\n  if (!Number.isFinite(now)) throw Error('Invalid clock.');\n  const signature = stable({ taskId: c.taskId, actorId: c.actorId, monitorName: c.monitorName, sources: c.expectedSources.map(stable).sort() });\n  const state = JSON.parse(JSON.stringify(oldState || {}));\n  if (state.signature && state.signature !== signature) throw Error('Watchdog scope changed: use a fresh seeded watchdogKey.');\n  if (state.version && state.version !== 1) throw Error('Unsupported watchdog state version.');\n  Object.assign(state, { version: 1, signature, initializedAt: state.initializedAt || now, checkedAt: now });\n  state.incidents ||= {};\n  state.outbox ||= [];\n  state.pendingGaps ||= {};\n  if (!Array.isArray(state.outbox) || state.outbox.length > 100) throw Error('Inspect watchdog outbox before continuing.');\n  const known = new Map();\n  const set = (key, reason) => known.set(key, reason || null);\n  const deadline = (2 * c.expectedIntervalMinutes + c.graceMinutes) * 60000;\n  const run = observation.terminal;\n  let status = 'HEALTHY';\n  if (!observation.apiOk) {\n    set('observability', observation.identityError ? 'Task/Actor identity mismatch in run metadata.' : 'Cannot read task run metadata; collection health is unknown.');\n    status = 'UNKNOWN';\n  } else {\n    set('observability', null);\n    const latest = observation.latest;\n    const lastStart = latest ? timestamp(latest.startedAt, now) : state.initializedAt;\n    set('missed-run', now - lastStart > deadline ? 'No collector run started within two expected intervals plus grace.' : null);\n    const active = latest && ['READY', 'RUNNING', 'ABORTING', 'TIMING-OUT'].includes(latest.status);\n    const recognized = !latest || active || ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(latest.status);\n    set('run-status-unknown', !recognized ? 'Latest run status is unknown.' : null);\n    set('stalled-run', active && now - lastStart > (c.maxRunMinutes + c.graceMinutes) * 60000 ? 'Latest collector run exceeds its expected runtime plus grace.' : null);\n    if (!latest) status = 'INITIALIZING';\n    if (run) {\n      set('collector-failed', run.status !== 'SUCCEEDED' ? 'Latest completed collector run is ' + run.status + '.' : null);\n      if (run.status === 'SUCCEEDED') {\n        const summary = responseBody(observation.summaryResponse);\n        const monitor = responseBody(observation.monitorResponse);\n        const valid = summary && Array.isArray(summary.sourceHealth) && monitor?.name === c.monitorName;\n        set('summary-unknown', !valid ? 'Missing health record or unexpected MONITOR_STATE name; source health is unknown.' : null);\n        if (!valid) status = 'UNKNOWN';\n        else {\n          const requiredRuns = c.gapAlertAfterRuns ?? 2;\n          const runStart = timestamp(run.startedAt, now);\n          // Re-reading one completed run never advances the gap threshold. Older\n          // evidence must not clear a newer incident if an API returns stale data.\n          const gapEvidenceCurrent = !state.gapEvidenceRun || run.id === state.gapEvidenceRun.runId || runStart >= state.gapEvidenceRun.startedAt;\n          const observeGap = (key, interrupted, label) => {\n            if (!gapEvidenceCurrent) return;\n            if (!interrupted) {\n              delete state.pendingGaps[key];\n              set(key, null); // RECOVERY only exists if an ALERT was opened.\n              return;\n            }\n            const gap = state.pendingGaps[key] ||= { firstSeenRunId: run.id, lastSeenRunId: run.id, runIds: [] };\n            if (!gap.runIds.includes(run.id) && gap.runIds.length < requiredRuns) gap.runIds.push(run.id);\n            gap.lastSeenRunId = run.id;\n            if (gap.runIds.length >= requiredRuns || state.incidents[key]?.active) {\n              const advice = summary.stopReason === 'item-limit' ? 'raise maxItems or run more often.' : 'inspect continuation/retry guidance.';\n              set(key, label + (requiredRuns === 1 ? ' was reported by a completed collector run; ' : ' persists across completed collector runs; ') + advice);\n            }\n            // An unconfirmed gap is pending evidence, not an incident. It can\n            // disappear on the next successful run without ALERT/RECOVERY noise.\n          };\n          if (typeof summary.possibleGap === 'boolean') observeGap('coverage-gap', summary.possibleGap, 'SUMMARY coverage gap');\n          for (const source of c.expectedSources) {\n            const key = 'source:' + stable(source);\n            const matches = summary.sourceHealth.filter(s => stable(s.source) === stable(source));\n            const s = matches[0];\n            let reason = null;\n            if (matches.length !== 1) reason = 'Expected source is missing or duplicated in SUMMARY.';\n            else {\n              const success = timestamp(s.lastSuccessfulCheckAt, now);\n              const attempt = timestamp(s.lastAttemptAt, now);\n              const start = timestamp(run.startedAt, now);\n              if (!Number.isInteger(s.consecutiveFailures) || s.consecutiveFailures < 0 || typeof s.coverageInterrupted !== 'boolean') reason = 'Source health fields are invalid or unknown.';\n              else if (s.consecutiveFailures > 0) reason = 'Source collection failed; other sources may still have succeeded.';\n              else if (!success || !attempt) reason = 'Source has no valid successful check timestamp.';\n              else if (now - success > deadline) reason = 'Source successful check is stale.';\n              else if (attempt < start - 5000 || success < attempt - 1000) reason = 'Latest run does not prove a successful check for this source.';\n              if (!reason) observeGap('coverage-gap:source:' + stable(source), s.coverageInterrupted, 'Source coverage gap');\n            }\n            set(key, reason);\n          }\n          if (gapEvidenceCurrent) state.gapEvidenceRun = { runId: run.id, startedAt: runStart };\n        }\n      }\n      // A crash/failed run or unreadable API must never clear existing source incidents.\n    } else if (latest) status = 'WAITING';\n  }\n  const enqueue = (key, incident, kind, reason) => {\n    const sequence = (incident.sequence || 0) + 1;\n    const eventId = c.watchdogKey + ':' + encodeURIComponent(key) + ':' + incident.openedAt + ':' + sequence + ':' + kind;\n    state.outbox.push({ eventId, kind, incidentKey: key, reason, occurredAt: new Date(now).toISOString(), monitorName: c.monitorName, taskId: c.taskId,\n      runId: observation.latest?.id || null, text: '[SusLabs watchdog] ' + kind + ': ' + c.monitorName + ' — ' + reason + ' Event: ' + eventId });\n    incident.sequence = sequence;\n    incident.lastQueuedAt = now;\n  };\n  for (const [key, reason] of known) {\n    let incident = state.incidents[key];\n    if (reason) {\n      if (!incident?.active) {\n        incident = { active: true, openedAt: Math.max(now, (incident?.openedAt || 0) + 1), sequence: 0 };\n        state.incidents[key] = incident;\n        enqueue(key, incident, 'ALERT', reason);\n      } else if (c.reminderHours > 0 && now - incident.lastQueuedAt >= c.reminderHours * 3600000 && !state.outbox.some(e => e.incidentKey === key)) {\n        enqueue(key, incident, 'REMINDER', reason);\n      }\n      incident.reason = reason;\n    } else if (incident?.active) {\n      enqueue(key, incident, 'RECOVERY', 'Health checks resumed for ' + key + '.');\n      incident.active = false;\n      incident.closedAt = now;\n    }\n  }\n  if (state.outbox.length > 100) throw Error('Outbox limit reached; inspect receiver and state table.');\n  const activeIssues = Object.entries(state.incidents).filter(([, v]) => v.active).map(([key, v]) => ({ key, reason: v.reason }));\n  if (activeIssues.length) status = 'ATTENTION';\n  const pendingCoverageGaps = Object.entries(state.pendingGaps).filter(([key]) => !state.incidents[key]?.active).map(([key, gap]) => ({ key, firstSeenRunId: gap.firstSeenRunId, lastSeenRunId: gap.lastSeenRunId, observedRuns: gap.runIds.length, requiredRuns: c.gapAlertAfterRuns ?? 2 }));\n  if (!activeIssues.length && pendingCoverageGaps.length) status = 'GAP_PENDING';\n  return { state, status, activeIssues, pendingCoverageGaps, pending: state.outbox.length, event: state.outbox[0] || null };\n}\nfunction acknowledge(state, eventIds, accepted, now) {\n  const next = JSON.parse(JSON.stringify(state));\n  if (accepted) {\n    if (!Array.isArray(eventIds) || !eventIds.length || eventIds.some((id, i) => next.outbox[i]?.eventId !== id)) throw Error('Outbox acknowledgement does not match head.');\n    next.outbox.splice(0, eventIds.length);\n    next.lastDelivered = { eventIds, at: now };\n  }\n  return next;\n}\n\n\nconst c={\n  \"taskId\": \"REPLACE_WITH_DEDICATED_TASK_ID\",\n  \"actorId\": \"c3pZJBbpVUNkRNsWS\",\n  \"monitorName\": \"REPLACE_WITH_MONITOR_NAME\",\n  \"watchdogKey\": \"reddit-hourly-watchdog\",\n  \"stateTableName\": \"suslabs_watchdog_state\",\n  \"expectedSources\": [\n    {\n      \"kind\": \"subreddit\",\n      \"name\": \"saas\"\n    }\n  ],\n  \"expectedIntervalMinutes\": 60,\n  \"graceMinutes\": 15,\n  \"maxRunMinutes\": 10,\n  \"reminderHours\": 0,\n  \"gapAlertAfterRuns\": 2,\n  \"deliveryEnabled\": false,\n  \"alertUrl\": \"https://example.invalid/REPLACE_WITH_YOUR_RECEIVER\"\n};\nvalidateConfig(c); return [{json:c}];"
      }
    },
    {
      "id": "read",
      "name": "Read persistent state",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        440,
        0
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Configure watchdog').first().json.stateTableName }}"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "watchdogKey",
              "condition": "eq",
              "keyValue": "={{ $('Configure watchdog').first().json.watchdogKey }}"
            }
          ]
        },
        "returnAll": true
      },
      "alwaysOutputData": true
    },
    {
      "id": "prepare",
      "name": "Prepare exclusive lease",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        0
      ],
      "parameters": {
        "jsCode": "const c=$('Configure watchdog').first().json;\nconst rows=$input.all().map(i=>i.json).filter(r=>r.id!==undefined);\nif(rows.length!==1) throw new Error('Seed exactly one state row for watchdogKey; see README.');\nconst row=rows[0], now=Date.now();\nif(row.watchdogKey!==c.watchdogKey || !Number.isFinite(row.leaseUntil) || typeof row.leaseId!=='string') throw new Error('Invalid state table row.');\nif(row.leaseUntil>now) return [];\nconst state=JSON.parse(row.stateJson || '{}');\nreturn [{json:{c,rowId:row.id,oldLeaseId:row.leaseId,oldLeaseUntil:row.leaseUntil,leaseId:String($execution.id)+':'+now,leaseUntil:now+300000,state}}];"
      }
    },
    {
      "id": "claim",
      "name": "Claim exclusive lease",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        880,
        0
      ],
      "parameters": {
        "resource": "row",
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Configure watchdog').first().json.stateTableName }}"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "id",
              "condition": "eq",
              "keyValue": "={{ $json.rowId }}"
            },
            {
              "keyName": "leaseId",
              "condition": "eq",
              "keyValue": "={{ $json.oldLeaseId }}"
            },
            {
              "keyName": "leaseUntil",
              "condition": "eq",
              "keyValue": "={{ $json.oldLeaseUntil }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "leaseId": "={{ $json.leaseId }}",
            "leaseUntil": "={{ $json.leaseUntil }}"
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "guard",
      "name": "Verify lease",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        0
      ],
      "parameters": {
        "jsCode": "const p=$('Prepare exclusive lease').first().json;\nif($json.leaseId!==p.leaseId || $json.id!==p.rowId) return [];\nreturn [{json:p}];"
      }
    },
    {
      "id": "runs",
      "name": "Read dedicated task runs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1320,
        0
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/actor-tasks/' + $('Configure watchdog').first().json.taskId + '/runs?desc=true&limit=5' }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          }
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth"
      },
      "onError": "continueRegularOutput",
      "notes": "Choose Header Auth: Authorization / Bearer YOUR_APIFY_TOKEN. Read-only API calls; no Actor runs started."
    },
    {
      "id": "select",
      "name": "Select collector evidence",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        0
      ],
      "parameters": {
        "jsCode": "'use strict';\n// Pure, offline-testable policy. Embedded verbatim in the n8n Code nodes.\nfunction stable(value) {\n  if (Array.isArray(value)) return '[' + value.map(stable).join(',') + ']';\n  if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + stable(value[k])).join(',') + '}';\n  return JSON.stringify(value);\n}\nfunction validateConfig(c) {\n  for (const k of ['taskId', 'actorId', 'monitorName', 'watchdogKey', 'stateTableName']) {\n    if (typeof c[k] !== 'string' || !c[k].trim() || /REPLACE|YOUR_/i.test(c[k])) throw Error('Configure ' + k + ' before running.');\n  }\n  for (const k of ['taskId', 'actorId']) if (!/^[A-Za-z0-9]+$/.test(c[k])) throw Error(k + ' must be an Apify ID, not a URL.');\n  for (const [k, min, max] of [['expectedIntervalMinutes', 1, 10080], ['graceMinutes', 0, 1440], ['maxRunMinutes', 1, 1440], ['reminderHours', 0, 720]]) {\n    if (!Number.isFinite(c[k]) || c[k] < min || c[k] > max) throw Error('Invalid ' + k);\n  }\n  if (!Number.isInteger(c.gapAlertAfterRuns ?? 2) || (c.gapAlertAfterRuns ?? 2) < 1 || (c.gapAlertAfterRuns ?? 2) > 100) throw Error('gapAlertAfterRuns must be an integer from 1 to 100.');\n  if (!Array.isArray(c.expectedSources) || !c.expectedSources.length || c.expectedSources.length > 100) throw Error('Configure 1–100 exact expected source descriptors.');\n  if (c.expectedSources.some(s => !s || typeof s !== 'object' || Array.isArray(s) || !s.kind)) throw Error('Expected sources must be SUMMARY source descriptor objects.');\n  if (new Set(c.expectedSources.map(stable)).size !== c.expectedSources.length) throw Error('Duplicate expected source.');\n  if (typeof c.deliveryEnabled !== 'boolean') throw Error('deliveryEnabled must be boolean.');\n  if (c.deliveryEnabled && (!/^https:\\/\\//.test(c.alertUrl) || /example\\.(com|invalid)|REPLACE/i.test(c.alertUrl))) throw Error('Configure your HTTPS notification receiver.');\n  return c;\n}\nfunction timestamp(value, now) {\n  const n = typeof value === 'string' && value ? Date.parse(value) : NaN;\n  return Number.isFinite(n) && n <= now + 300000 ? n : null;\n}\nfunction responseBody(response) {\n  if (!response || response.error || response.statusCode !== 200 || !response.body || typeof response.body !== 'object') return null;\n  return response.body;\n}\nfunction selectRuns(c, response, now) {\n  const body = responseBody(response);\n  const runs = body?.data?.items;\n  if (!Array.isArray(runs)) return { apiOk: false, readRecords: false };\n  // The task endpoint is the scope boundary; never scan all Actor runs.\n  if (runs.some(r => r.actId !== c.actorId || r.actorTaskId !== c.taskId || !timestamp(r.startedAt, now) || !/^[A-Za-z0-9]+$/.test(r.id))) {\n    return { apiOk: false, readRecords: false, identityError: true };\n  }\n  runs.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));\n  const terminal = runs.find(r => ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(r.status)) || null;\n  return { apiOk: true, latest: runs[0] || null, terminal,\n    readRecords: Boolean(terminal?.status === 'SUCCEEDED' && /^[A-Za-z0-9]+$/.test(terminal.defaultKeyValueStoreId)) };\n}\nfunction evaluate(c, oldState, observation, now) {\n  validateConfig(c);\n  if (!Number.isFinite(now)) throw Error('Invalid clock.');\n  const signature = stable({ taskId: c.taskId, actorId: c.actorId, monitorName: c.monitorName, sources: c.expectedSources.map(stable).sort() });\n  const state = JSON.parse(JSON.stringify(oldState || {}));\n  if (state.signature && state.signature !== signature) throw Error('Watchdog scope changed: use a fresh seeded watchdogKey.');\n  if (state.version && state.version !== 1) throw Error('Unsupported watchdog state version.');\n  Object.assign(state, { version: 1, signature, initializedAt: state.initializedAt || now, checkedAt: now });\n  state.incidents ||= {};\n  state.outbox ||= [];\n  state.pendingGaps ||= {};\n  if (!Array.isArray(state.outbox) || state.outbox.length > 100) throw Error('Inspect watchdog outbox before continuing.');\n  const known = new Map();\n  const set = (key, reason) => known.set(key, reason || null);\n  const deadline = (2 * c.expectedIntervalMinutes + c.graceMinutes) * 60000;\n  const run = observation.terminal;\n  let status = 'HEALTHY';\n  if (!observation.apiOk) {\n    set('observability', observation.identityError ? 'Task/Actor identity mismatch in run metadata.' : 'Cannot read task run metadata; collection health is unknown.');\n    status = 'UNKNOWN';\n  } else {\n    set('observability', null);\n    const latest = observation.latest;\n    const lastStart = latest ? timestamp(latest.startedAt, now) : state.initializedAt;\n    set('missed-run', now - lastStart > deadline ? 'No collector run started within two expected intervals plus grace.' : null);\n    const active = latest && ['READY', 'RUNNING', 'ABORTING', 'TIMING-OUT'].includes(latest.status);\n    const recognized = !latest || active || ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(latest.status);\n    set('run-status-unknown', !recognized ? 'Latest run status is unknown.' : null);\n    set('stalled-run', active && now - lastStart > (c.maxRunMinutes + c.graceMinutes) * 60000 ? 'Latest collector run exceeds its expected runtime plus grace.' : null);\n    if (!latest) status = 'INITIALIZING';\n    if (run) {\n      set('collector-failed', run.status !== 'SUCCEEDED' ? 'Latest completed collector run is ' + run.status + '.' : null);\n      if (run.status === 'SUCCEEDED') {\n        const summary = responseBody(observation.summaryResponse);\n        const monitor = responseBody(observation.monitorResponse);\n        const valid = summary && Array.isArray(summary.sourceHealth) && monitor?.name === c.monitorName;\n        set('summary-unknown', !valid ? 'Missing health record or unexpected MONITOR_STATE name; source health is unknown.' : null);\n        if (!valid) status = 'UNKNOWN';\n        else {\n          const requiredRuns = c.gapAlertAfterRuns ?? 2;\n          const runStart = timestamp(run.startedAt, now);\n          // Re-reading one completed run never advances the gap threshold. Older\n          // evidence must not clear a newer incident if an API returns stale data.\n          const gapEvidenceCurrent = !state.gapEvidenceRun || run.id === state.gapEvidenceRun.runId || runStart >= state.gapEvidenceRun.startedAt;\n          const observeGap = (key, interrupted, label) => {\n            if (!gapEvidenceCurrent) return;\n            if (!interrupted) {\n              delete state.pendingGaps[key];\n              set(key, null); // RECOVERY only exists if an ALERT was opened.\n              return;\n            }\n            const gap = state.pendingGaps[key] ||= { firstSeenRunId: run.id, lastSeenRunId: run.id, runIds: [] };\n            if (!gap.runIds.includes(run.id) && gap.runIds.length < requiredRuns) gap.runIds.push(run.id);\n            gap.lastSeenRunId = run.id;\n            if (gap.runIds.length >= requiredRuns || state.incidents[key]?.active) {\n              const advice = summary.stopReason === 'item-limit' ? 'raise maxItems or run more often.' : 'inspect continuation/retry guidance.';\n              set(key, label + (requiredRuns === 1 ? ' was reported by a completed collector run; ' : ' persists across completed collector runs; ') + advice);\n            }\n            // An unconfirmed gap is pending evidence, not an incident. It can\n            // disappear on the next successful run without ALERT/RECOVERY noise.\n          };\n          if (typeof summary.possibleGap === 'boolean') observeGap('coverage-gap', summary.possibleGap, 'SUMMARY coverage gap');\n          for (const source of c.expectedSources) {\n            const key = 'source:' + stable(source);\n            const matches = summary.sourceHealth.filter(s => stable(s.source) === stable(source));\n            const s = matches[0];\n            let reason = null;\n            if (matches.length !== 1) reason = 'Expected source is missing or duplicated in SUMMARY.';\n            else {\n              const success = timestamp(s.lastSuccessfulCheckAt, now);\n              const attempt = timestamp(s.lastAttemptAt, now);\n              const start = timestamp(run.startedAt, now);\n              if (!Number.isInteger(s.consecutiveFailures) || s.consecutiveFailures < 0 || typeof s.coverageInterrupted !== 'boolean') reason = 'Source health fields are invalid or unknown.';\n              else if (s.consecutiveFailures > 0) reason = 'Source collection failed; other sources may still have succeeded.';\n              else if (!success || !attempt) reason = 'Source has no valid successful check timestamp.';\n              else if (now - success > deadline) reason = 'Source successful check is stale.';\n              else if (attempt < start - 5000 || success < attempt - 1000) reason = 'Latest run does not prove a successful check for this source.';\n              if (!reason) observeGap('coverage-gap:source:' + stable(source), s.coverageInterrupted, 'Source coverage gap');\n            }\n            set(key, reason);\n          }\n          if (gapEvidenceCurrent) state.gapEvidenceRun = { runId: run.id, startedAt: runStart };\n        }\n      }\n      // A crash/failed run or unreadable API must never clear existing source incidents.\n    } else if (latest) status = 'WAITING';\n  }\n  const enqueue = (key, incident, kind, reason) => {\n    const sequence = (incident.sequence || 0) + 1;\n    const eventId = c.watchdogKey + ':' + encodeURIComponent(key) + ':' + incident.openedAt + ':' + sequence + ':' + kind;\n    state.outbox.push({ eventId, kind, incidentKey: key, reason, occurredAt: new Date(now).toISOString(), monitorName: c.monitorName, taskId: c.taskId,\n      runId: observation.latest?.id || null, text: '[SusLabs watchdog] ' + kind + ': ' + c.monitorName + ' — ' + reason + ' Event: ' + eventId });\n    incident.sequence = sequence;\n    incident.lastQueuedAt = now;\n  };\n  for (const [key, reason] of known) {\n    let incident = state.incidents[key];\n    if (reason) {\n      if (!incident?.active) {\n        incident = { active: true, openedAt: Math.max(now, (incident?.openedAt || 0) + 1), sequence: 0 };\n        state.incidents[key] = incident;\n        enqueue(key, incident, 'ALERT', reason);\n      } else if (c.reminderHours > 0 && now - incident.lastQueuedAt >= c.reminderHours * 3600000 && !state.outbox.some(e => e.incidentKey === key)) {\n        enqueue(key, incident, 'REMINDER', reason);\n      }\n      incident.reason = reason;\n    } else if (incident?.active) {\n      enqueue(key, incident, 'RECOVERY', 'Health checks resumed for ' + key + '.');\n      incident.active = false;\n      incident.closedAt = now;\n    }\n  }\n  if (state.outbox.length > 100) throw Error('Outbox limit reached; inspect receiver and state table.');\n  const activeIssues = Object.entries(state.incidents).filter(([, v]) => v.active).map(([key, v]) => ({ key, reason: v.reason }));\n  if (activeIssues.length) status = 'ATTENTION';\n  const pendingCoverageGaps = Object.entries(state.pendingGaps).filter(([key]) => !state.incidents[key]?.active).map(([key, gap]) => ({ key, firstSeenRunId: gap.firstSeenRunId, lastSeenRunId: gap.lastSeenRunId, observedRuns: gap.runIds.length, requiredRuns: c.gapAlertAfterRuns ?? 2 }));\n  if (!activeIssues.length && pendingCoverageGaps.length) status = 'GAP_PENDING';\n  return { state, status, activeIssues, pendingCoverageGaps, pending: state.outbox.length, event: state.outbox[0] || null };\n}\nfunction acknowledge(state, eventIds, accepted, now) {\n  const next = JSON.parse(JSON.stringify(state));\n  if (accepted) {\n    if (!Array.isArray(eventIds) || !eventIds.length || eventIds.some((id, i) => next.outbox[i]?.eventId !== id)) throw Error('Outbox acknowledgement does not match head.');\n    next.outbox.splice(0, eventIds.length);\n    next.lastDelivered = { eventIds, at: now };\n  }\n  return next;\n}\n\n\nconst p=$('Verify lease').first().json;\nconst observation=selectRuns(p.c,$json,Date.now());\nreturn [{json:{...p,observation}}];"
      }
    },
    {
      "id": "records-if",
      "name": "Completed success to inspect",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1760,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "read-records",
              "leftValue": "={{ $json.observation.readRecords }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "monitor",
      "name": "Read exact MONITOR_STATE",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1980,
        -140
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $('Select collector evidence').first().json.observation.terminal.defaultKeyValueStoreId + '/records/MONITOR_STATE' }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          }
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth"
      },
      "onError": "continueRegularOutput",
      "notes": "Choose Header Auth: Authorization / Bearer YOUR_APIFY_TOKEN. Read-only API calls; no Actor runs started."
    },
    {
      "id": "monitor-result",
      "name": "Keep monitor evidence",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2200,
        -140
      ],
      "parameters": {
        "jsCode": "const p=$('Select collector evidence').first().json;\nreturn [{json:{...p,observation:{...p.observation,monitorResponse:$json}}}];"
      }
    },
    {
      "id": "summary",
      "name": "Read exact SUMMARY",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2420,
        -140
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $('Select collector evidence').first().json.observation.terminal.defaultKeyValueStoreId + '/records/SUMMARY' }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          }
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth"
      },
      "onError": "continueRegularOutput",
      "notes": "Choose Header Auth: Authorization / Bearer YOUR_APIFY_TOKEN. Read-only API calls; no Actor runs started."
    },
    {
      "id": "assemble",
      "name": "Keep summary evidence",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2640,
        -140
      ],
      "parameters": {
        "jsCode": "const p=$('Keep monitor evidence').first().json;\nreturn [{json:{...p,observation:{...p.observation,summaryResponse:$json}}}];"
      }
    },
    {
      "id": "evaluate",
      "name": "Evaluate health and stage events",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2860,
        0
      ],
      "parameters": {
        "jsCode": "'use strict';\n// Pure, offline-testable policy. Embedded verbatim in the n8n Code nodes.\nfunction stable(value) {\n  if (Array.isArray(value)) return '[' + value.map(stable).join(',') + ']';\n  if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + stable(value[k])).join(',') + '}';\n  return JSON.stringify(value);\n}\nfunction validateConfig(c) {\n  for (const k of ['taskId', 'actorId', 'monitorName', 'watchdogKey', 'stateTableName']) {\n    if (typeof c[k] !== 'string' || !c[k].trim() || /REPLACE|YOUR_/i.test(c[k])) throw Error('Configure ' + k + ' before running.');\n  }\n  for (const k of ['taskId', 'actorId']) if (!/^[A-Za-z0-9]+$/.test(c[k])) throw Error(k + ' must be an Apify ID, not a URL.');\n  for (const [k, min, max] of [['expectedIntervalMinutes', 1, 10080], ['graceMinutes', 0, 1440], ['maxRunMinutes', 1, 1440], ['reminderHours', 0, 720]]) {\n    if (!Number.isFinite(c[k]) || c[k] < min || c[k] > max) throw Error('Invalid ' + k);\n  }\n  if (!Number.isInteger(c.gapAlertAfterRuns ?? 2) || (c.gapAlertAfterRuns ?? 2) < 1 || (c.gapAlertAfterRuns ?? 2) > 100) throw Error('gapAlertAfterRuns must be an integer from 1 to 100.');\n  if (!Array.isArray(c.expectedSources) || !c.expectedSources.length || c.expectedSources.length > 100) throw Error('Configure 1–100 exact expected source descriptors.');\n  if (c.expectedSources.some(s => !s || typeof s !== 'object' || Array.isArray(s) || !s.kind)) throw Error('Expected sources must be SUMMARY source descriptor objects.');\n  if (new Set(c.expectedSources.map(stable)).size !== c.expectedSources.length) throw Error('Duplicate expected source.');\n  if (typeof c.deliveryEnabled !== 'boolean') throw Error('deliveryEnabled must be boolean.');\n  if (c.deliveryEnabled && (!/^https:\\/\\//.test(c.alertUrl) || /example\\.(com|invalid)|REPLACE/i.test(c.alertUrl))) throw Error('Configure your HTTPS notification receiver.');\n  return c;\n}\nfunction timestamp(value, now) {\n  const n = typeof value === 'string' && value ? Date.parse(value) : NaN;\n  return Number.isFinite(n) && n <= now + 300000 ? n : null;\n}\nfunction responseBody(response) {\n  if (!response || response.error || response.statusCode !== 200 || !response.body || typeof response.body !== 'object') return null;\n  return response.body;\n}\nfunction selectRuns(c, response, now) {\n  const body = responseBody(response);\n  const runs = body?.data?.items;\n  if (!Array.isArray(runs)) return { apiOk: false, readRecords: false };\n  // The task endpoint is the scope boundary; never scan all Actor runs.\n  if (runs.some(r => r.actId !== c.actorId || r.actorTaskId !== c.taskId || !timestamp(r.startedAt, now) || !/^[A-Za-z0-9]+$/.test(r.id))) {\n    return { apiOk: false, readRecords: false, identityError: true };\n  }\n  runs.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));\n  const terminal = runs.find(r => ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(r.status)) || null;\n  return { apiOk: true, latest: runs[0] || null, terminal,\n    readRecords: Boolean(terminal?.status === 'SUCCEEDED' && /^[A-Za-z0-9]+$/.test(terminal.defaultKeyValueStoreId)) };\n}\nfunction evaluate(c, oldState, observation, now) {\n  validateConfig(c);\n  if (!Number.isFinite(now)) throw Error('Invalid clock.');\n  const signature = stable({ taskId: c.taskId, actorId: c.actorId, monitorName: c.monitorName, sources: c.expectedSources.map(stable).sort() });\n  const state = JSON.parse(JSON.stringify(oldState || {}));\n  if (state.signature && state.signature !== signature) throw Error('Watchdog scope changed: use a fresh seeded watchdogKey.');\n  if (state.version && state.version !== 1) throw Error('Unsupported watchdog state version.');\n  Object.assign(state, { version: 1, signature, initializedAt: state.initializedAt || now, checkedAt: now });\n  state.incidents ||= {};\n  state.outbox ||= [];\n  state.pendingGaps ||= {};\n  if (!Array.isArray(state.outbox) || state.outbox.length > 100) throw Error('Inspect watchdog outbox before continuing.');\n  const known = new Map();\n  const set = (key, reason) => known.set(key, reason || null);\n  const deadline = (2 * c.expectedIntervalMinutes + c.graceMinutes) * 60000;\n  const run = observation.terminal;\n  let status = 'HEALTHY';\n  if (!observation.apiOk) {\n    set('observability', observation.identityError ? 'Task/Actor identity mismatch in run metadata.' : 'Cannot read task run metadata; collection health is unknown.');\n    status = 'UNKNOWN';\n  } else {\n    set('observability', null);\n    const latest = observation.latest;\n    const lastStart = latest ? timestamp(latest.startedAt, now) : state.initializedAt;\n    set('missed-run', now - lastStart > deadline ? 'No collector run started within two expected intervals plus grace.' : null);\n    const active = latest && ['READY', 'RUNNING', 'ABORTING', 'TIMING-OUT'].includes(latest.status);\n    const recognized = !latest || active || ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(latest.status);\n    set('run-status-unknown', !recognized ? 'Latest run status is unknown.' : null);\n    set('stalled-run', active && now - lastStart > (c.maxRunMinutes + c.graceMinutes) * 60000 ? 'Latest collector run exceeds its expected runtime plus grace.' : null);\n    if (!latest) status = 'INITIALIZING';\n    if (run) {\n      set('collector-failed', run.status !== 'SUCCEEDED' ? 'Latest completed collector run is ' + run.status + '.' : null);\n      if (run.status === 'SUCCEEDED') {\n        const summary = responseBody(observation.summaryResponse);\n        const monitor = responseBody(observation.monitorResponse);\n        const valid = summary && Array.isArray(summary.sourceHealth) && monitor?.name === c.monitorName;\n        set('summary-unknown', !valid ? 'Missing health record or unexpected MONITOR_STATE name; source health is unknown.' : null);\n        if (!valid) status = 'UNKNOWN';\n        else {\n          const requiredRuns = c.gapAlertAfterRuns ?? 2;\n          const runStart = timestamp(run.startedAt, now);\n          // Re-reading one completed run never advances the gap threshold. Older\n          // evidence must not clear a newer incident if an API returns stale data.\n          const gapEvidenceCurrent = !state.gapEvidenceRun || run.id === state.gapEvidenceRun.runId || runStart >= state.gapEvidenceRun.startedAt;\n          const observeGap = (key, interrupted, label) => {\n            if (!gapEvidenceCurrent) return;\n            if (!interrupted) {\n              delete state.pendingGaps[key];\n              set(key, null); // RECOVERY only exists if an ALERT was opened.\n              return;\n            }\n            const gap = state.pendingGaps[key] ||= { firstSeenRunId: run.id, lastSeenRunId: run.id, runIds: [] };\n            if (!gap.runIds.includes(run.id) && gap.runIds.length < requiredRuns) gap.runIds.push(run.id);\n            gap.lastSeenRunId = run.id;\n            if (gap.runIds.length >= requiredRuns || state.incidents[key]?.active) {\n              const advice = summary.stopReason === 'item-limit' ? 'raise maxItems or run more often.' : 'inspect continuation/retry guidance.';\n              set(key, label + (requiredRuns === 1 ? ' was reported by a completed collector run; ' : ' persists across completed collector runs; ') + advice);\n            }\n            // An unconfirmed gap is pending evidence, not an incident. It can\n            // disappear on the next successful run without ALERT/RECOVERY noise.\n          };\n          if (typeof summary.possibleGap === 'boolean') observeGap('coverage-gap', summary.possibleGap, 'SUMMARY coverage gap');\n          for (const source of c.expectedSources) {\n            const key = 'source:' + stable(source);\n            const matches = summary.sourceHealth.filter(s => stable(s.source) === stable(source));\n            const s = matches[0];\n            let reason = null;\n            if (matches.length !== 1) reason = 'Expected source is missing or duplicated in SUMMARY.';\n            else {\n              const success = timestamp(s.lastSuccessfulCheckAt, now);\n              const attempt = timestamp(s.lastAttemptAt, now);\n              const start = timestamp(run.startedAt, now);\n              if (!Number.isInteger(s.consecutiveFailures) || s.consecutiveFailures < 0 || typeof s.coverageInterrupted !== 'boolean') reason = 'Source health fields are invalid or unknown.';\n              else if (s.consecutiveFailures > 0) reason = 'Source collection failed; other sources may still have succeeded.';\n              else if (!success || !attempt) reason = 'Source has no valid successful check timestamp.';\n              else if (now - success > deadline) reason = 'Source successful check is stale.';\n              else if (attempt < start - 5000 || success < attempt - 1000) reason = 'Latest run does not prove a successful check for this source.';\n              if (!reason) observeGap('coverage-gap:source:' + stable(source), s.coverageInterrupted, 'Source coverage gap');\n            }\n            set(key, reason);\n          }\n          if (gapEvidenceCurrent) state.gapEvidenceRun = { runId: run.id, startedAt: runStart };\n        }\n      }\n      // A crash/failed run or unreadable API must never clear existing source incidents.\n    } else if (latest) status = 'WAITING';\n  }\n  const enqueue = (key, incident, kind, reason) => {\n    const sequence = (incident.sequence || 0) + 1;\n    const eventId = c.watchdogKey + ':' + encodeURIComponent(key) + ':' + incident.openedAt + ':' + sequence + ':' + kind;\n    state.outbox.push({ eventId, kind, incidentKey: key, reason, occurredAt: new Date(now).toISOString(), monitorName: c.monitorName, taskId: c.taskId,\n      runId: observation.latest?.id || null, text: '[SusLabs watchdog] ' + kind + ': ' + c.monitorName + ' — ' + reason + ' Event: ' + eventId });\n    incident.sequence = sequence;\n    incident.lastQueuedAt = now;\n  };\n  for (const [key, reason] of known) {\n    let incident = state.incidents[key];\n    if (reason) {\n      if (!incident?.active) {\n        incident = { active: true, openedAt: Math.max(now, (incident?.openedAt || 0) + 1), sequence: 0 };\n        state.incidents[key] = incident;\n        enqueue(key, incident, 'ALERT', reason);\n      } else if (c.reminderHours > 0 && now - incident.lastQueuedAt >= c.reminderHours * 3600000 && !state.outbox.some(e => e.incidentKey === key)) {\n        enqueue(key, incident, 'REMINDER', reason);\n      }\n      incident.reason = reason;\n    } else if (incident?.active) {\n      enqueue(key, incident, 'RECOVERY', 'Health checks resumed for ' + key + '.');\n      incident.active = false;\n      incident.closedAt = now;\n    }\n  }\n  if (state.outbox.length > 100) throw Error('Outbox limit reached; inspect receiver and state table.');\n  const activeIssues = Object.entries(state.incidents).filter(([, v]) => v.active).map(([key, v]) => ({ key, reason: v.reason }));\n  if (activeIssues.length) status = 'ATTENTION';\n  const pendingCoverageGaps = Object.entries(state.pendingGaps).filter(([key]) => !state.incidents[key]?.active).map(([key, gap]) => ({ key, firstSeenRunId: gap.firstSeenRunId, lastSeenRunId: gap.lastSeenRunId, observedRuns: gap.runIds.length, requiredRuns: c.gapAlertAfterRuns ?? 2 }));\n  if (!activeIssues.length && pendingCoverageGaps.length) status = 'GAP_PENDING';\n  return { state, status, activeIssues, pendingCoverageGaps, pending: state.outbox.length, event: state.outbox[0] || null };\n}\nfunction acknowledge(state, eventIds, accepted, now) {\n  const next = JSON.parse(JSON.stringify(state));\n  if (accepted) {\n    if (!Array.isArray(eventIds) || !eventIds.length || eventIds.some((id, i) => next.outbox[i]?.eventId !== id)) throw Error('Outbox acknowledgement does not match head.');\n    next.outbox.splice(0, eventIds.length);\n    next.lastDelivered = { eventIds, at: now };\n  }\n  return next;\n}\n\n\nconst p=$json;\nif(Date.now()>p.leaseUntil-30000) throw new Error('Lease nearly expired; do not deliver.');\nconst result=evaluate(p.c,p.state,p.observation,Date.now());\nreturn [{json:{...p,...result}}];"
      }
    },
    {
      "id": "stage",
      "name": "Persist outbox before sending",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        3080,
        0
      ],
      "parameters": {
        "resource": "row",
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Configure watchdog').first().json.stateTableName }}"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "id",
              "condition": "eq",
              "keyValue": "={{ $('Verify lease').first().json.rowId }}"
            },
            {
              "keyName": "leaseId",
              "condition": "eq",
              "keyValue": "={{ $('Verify lease').first().json.leaseId }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "stateJson": "={{ JSON.stringify($json.state) }}"
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "stage-verify",
      "name": "Verify staged events",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3300,
        0
      ],
      "parameters": {
        "jsCode": "const p=$('Evaluate health and stage events').first().json;\nif($json.leaseId!==p.leaseId || $json.stateJson!==JSON.stringify(p.state)) throw new Error('Outbox was not saved under our lease.');\nconst enabled=p.c.deliveryEnabled && p.state.outbox.length>0;\nreturn [{json:{...p,send:enabled,batch:p.state.outbox,eventIds:p.state.outbox.map(e=>e.eventId)}}];"
      }
    },
    {
      "id": "send-if",
      "name": "Notification enabled and pending",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3520,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "send",
              "leftValue": "={{ $json.send }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "send-guard",
      "name": "Check delivery lease",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3740,
        -140
      ],
      "parameters": {
        "jsCode": "const p=$json;\nif(Date.now()>p.leaseUntil-30000) throw new Error('Lease nearly expired; leave outbox for next execution.');\nreturn [{json:p}];"
      }
    },
    {
      "id": "notify",
      "name": "Send notification batch",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3960,
        -140
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Configure watchdog').first().json.alertUrl }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          }
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $('Check delivery lease').first().json.eventIds[0] + '..' + $('Check delivery lease').first().json.eventIds.slice(-1)[0] }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {events: $('Check delivery lease').first().json.batch, text: $('Check delivery lease').first().json.batch.map(e=>e.text).join('\\n')} }}"
      },
      "onError": "continueRegularOutput",
      "notes": "Choose a separate receiver credential if required. Never send the Apify credential to your receiver."
    },
    {
      "id": "ack",
      "name": "Acknowledge accepted batch",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4180,
        -140
      ],
      "parameters": {
        "jsCode": "'use strict';\n// Pure, offline-testable policy. Embedded verbatim in the n8n Code nodes.\nfunction stable(value) {\n  if (Array.isArray(value)) return '[' + value.map(stable).join(',') + ']';\n  if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + stable(value[k])).join(',') + '}';\n  return JSON.stringify(value);\n}\nfunction validateConfig(c) {\n  for (const k of ['taskId', 'actorId', 'monitorName', 'watchdogKey', 'stateTableName']) {\n    if (typeof c[k] !== 'string' || !c[k].trim() || /REPLACE|YOUR_/i.test(c[k])) throw Error('Configure ' + k + ' before running.');\n  }\n  for (const k of ['taskId', 'actorId']) if (!/^[A-Za-z0-9]+$/.test(c[k])) throw Error(k + ' must be an Apify ID, not a URL.');\n  for (const [k, min, max] of [['expectedIntervalMinutes', 1, 10080], ['graceMinutes', 0, 1440], ['maxRunMinutes', 1, 1440], ['reminderHours', 0, 720]]) {\n    if (!Number.isFinite(c[k]) || c[k] < min || c[k] > max) throw Error('Invalid ' + k);\n  }\n  if (!Number.isInteger(c.gapAlertAfterRuns ?? 2) || (c.gapAlertAfterRuns ?? 2) < 1 || (c.gapAlertAfterRuns ?? 2) > 100) throw Error('gapAlertAfterRuns must be an integer from 1 to 100.');\n  if (!Array.isArray(c.expectedSources) || !c.expectedSources.length || c.expectedSources.length > 100) throw Error('Configure 1–100 exact expected source descriptors.');\n  if (c.expectedSources.some(s => !s || typeof s !== 'object' || Array.isArray(s) || !s.kind)) throw Error('Expected sources must be SUMMARY source descriptor objects.');\n  if (new Set(c.expectedSources.map(stable)).size !== c.expectedSources.length) throw Error('Duplicate expected source.');\n  if (typeof c.deliveryEnabled !== 'boolean') throw Error('deliveryEnabled must be boolean.');\n  if (c.deliveryEnabled && (!/^https:\\/\\//.test(c.alertUrl) || /example\\.(com|invalid)|REPLACE/i.test(c.alertUrl))) throw Error('Configure your HTTPS notification receiver.');\n  return c;\n}\nfunction timestamp(value, now) {\n  const n = typeof value === 'string' && value ? Date.parse(value) : NaN;\n  return Number.isFinite(n) && n <= now + 300000 ? n : null;\n}\nfunction responseBody(response) {\n  if (!response || response.error || response.statusCode !== 200 || !response.body || typeof response.body !== 'object') return null;\n  return response.body;\n}\nfunction selectRuns(c, response, now) {\n  const body = responseBody(response);\n  const runs = body?.data?.items;\n  if (!Array.isArray(runs)) return { apiOk: false, readRecords: false };\n  // The task endpoint is the scope boundary; never scan all Actor runs.\n  if (runs.some(r => r.actId !== c.actorId || r.actorTaskId !== c.taskId || !timestamp(r.startedAt, now) || !/^[A-Za-z0-9]+$/.test(r.id))) {\n    return { apiOk: false, readRecords: false, identityError: true };\n  }\n  runs.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));\n  const terminal = runs.find(r => ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(r.status)) || null;\n  return { apiOk: true, latest: runs[0] || null, terminal,\n    readRecords: Boolean(terminal?.status === 'SUCCEEDED' && /^[A-Za-z0-9]+$/.test(terminal.defaultKeyValueStoreId)) };\n}\nfunction evaluate(c, oldState, observation, now) {\n  validateConfig(c);\n  if (!Number.isFinite(now)) throw Error('Invalid clock.');\n  const signature = stable({ taskId: c.taskId, actorId: c.actorId, monitorName: c.monitorName, sources: c.expectedSources.map(stable).sort() });\n  const state = JSON.parse(JSON.stringify(oldState || {}));\n  if (state.signature && state.signature !== signature) throw Error('Watchdog scope changed: use a fresh seeded watchdogKey.');\n  if (state.version && state.version !== 1) throw Error('Unsupported watchdog state version.');\n  Object.assign(state, { version: 1, signature, initializedAt: state.initializedAt || now, checkedAt: now });\n  state.incidents ||= {};\n  state.outbox ||= [];\n  state.pendingGaps ||= {};\n  if (!Array.isArray(state.outbox) || state.outbox.length > 100) throw Error('Inspect watchdog outbox before continuing.');\n  const known = new Map();\n  const set = (key, reason) => known.set(key, reason || null);\n  const deadline = (2 * c.expectedIntervalMinutes + c.graceMinutes) * 60000;\n  const run = observation.terminal;\n  let status = 'HEALTHY';\n  if (!observation.apiOk) {\n    set('observability', observation.identityError ? 'Task/Actor identity mismatch in run metadata.' : 'Cannot read task run metadata; collection health is unknown.');\n    status = 'UNKNOWN';\n  } else {\n    set('observability', null);\n    const latest = observation.latest;\n    const lastStart = latest ? timestamp(latest.startedAt, now) : state.initializedAt;\n    set('missed-run', now - lastStart > deadline ? 'No collector run started within two expected intervals plus grace.' : null);\n    const active = latest && ['READY', 'RUNNING', 'ABORTING', 'TIMING-OUT'].includes(latest.status);\n    const recognized = !latest || active || ['SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED'].includes(latest.status);\n    set('run-status-unknown', !recognized ? 'Latest run status is unknown.' : null);\n    set('stalled-run', active && now - lastStart > (c.maxRunMinutes + c.graceMinutes) * 60000 ? 'Latest collector run exceeds its expected runtime plus grace.' : null);\n    if (!latest) status = 'INITIALIZING';\n    if (run) {\n      set('collector-failed', run.status !== 'SUCCEEDED' ? 'Latest completed collector run is ' + run.status + '.' : null);\n      if (run.status === 'SUCCEEDED') {\n        const summary = responseBody(observation.summaryResponse);\n        const monitor = responseBody(observation.monitorResponse);\n        const valid = summary && Array.isArray(summary.sourceHealth) && monitor?.name === c.monitorName;\n        set('summary-unknown', !valid ? 'Missing health record or unexpected MONITOR_STATE name; source health is unknown.' : null);\n        if (!valid) status = 'UNKNOWN';\n        else {\n          const requiredRuns = c.gapAlertAfterRuns ?? 2;\n          const runStart = timestamp(run.startedAt, now);\n          // Re-reading one completed run never advances the gap threshold. Older\n          // evidence must not clear a newer incident if an API returns stale data.\n          const gapEvidenceCurrent = !state.gapEvidenceRun || run.id === state.gapEvidenceRun.runId || runStart >= state.gapEvidenceRun.startedAt;\n          const observeGap = (key, interrupted, label) => {\n            if (!gapEvidenceCurrent) return;\n            if (!interrupted) {\n              delete state.pendingGaps[key];\n              set(key, null); // RECOVERY only exists if an ALERT was opened.\n              return;\n            }\n            const gap = state.pendingGaps[key] ||= { firstSeenRunId: run.id, lastSeenRunId: run.id, runIds: [] };\n            if (!gap.runIds.includes(run.id) && gap.runIds.length < requiredRuns) gap.runIds.push(run.id);\n            gap.lastSeenRunId = run.id;\n            if (gap.runIds.length >= requiredRuns || state.incidents[key]?.active) {\n              const advice = summary.stopReason === 'item-limit' ? 'raise maxItems or run more often.' : 'inspect continuation/retry guidance.';\n              set(key, label + (requiredRuns === 1 ? ' was reported by a completed collector run; ' : ' persists across completed collector runs; ') + advice);\n            }\n            // An unconfirmed gap is pending evidence, not an incident. It can\n            // disappear on the next successful run without ALERT/RECOVERY noise.\n          };\n          if (typeof summary.possibleGap === 'boolean') observeGap('coverage-gap', summary.possibleGap, 'SUMMARY coverage gap');\n          for (const source of c.expectedSources) {\n            const key = 'source:' + stable(source);\n            const matches = summary.sourceHealth.filter(s => stable(s.source) === stable(source));\n            const s = matches[0];\n            let reason = null;\n            if (matches.length !== 1) reason = 'Expected source is missing or duplicated in SUMMARY.';\n            else {\n              const success = timestamp(s.lastSuccessfulCheckAt, now);\n              const attempt = timestamp(s.lastAttemptAt, now);\n              const start = timestamp(run.startedAt, now);\n              if (!Number.isInteger(s.consecutiveFailures) || s.consecutiveFailures < 0 || typeof s.coverageInterrupted !== 'boolean') reason = 'Source health fields are invalid or unknown.';\n              else if (s.consecutiveFailures > 0) reason = 'Source collection failed; other sources may still have succeeded.';\n              else if (!success || !attempt) reason = 'Source has no valid successful check timestamp.';\n              else if (now - success > deadline) reason = 'Source successful check is stale.';\n              else if (attempt < start - 5000 || success < attempt - 1000) reason = 'Latest run does not prove a successful check for this source.';\n              if (!reason) observeGap('coverage-gap:source:' + stable(source), s.coverageInterrupted, 'Source coverage gap');\n            }\n            set(key, reason);\n          }\n          if (gapEvidenceCurrent) state.gapEvidenceRun = { runId: run.id, startedAt: runStart };\n        }\n      }\n      // A crash/failed run or unreadable API must never clear existing source incidents.\n    } else if (latest) status = 'WAITING';\n  }\n  const enqueue = (key, incident, kind, reason) => {\n    const sequence = (incident.sequence || 0) + 1;\n    const eventId = c.watchdogKey + ':' + encodeURIComponent(key) + ':' + incident.openedAt + ':' + sequence + ':' + kind;\n    state.outbox.push({ eventId, kind, incidentKey: key, reason, occurredAt: new Date(now).toISOString(), monitorName: c.monitorName, taskId: c.taskId,\n      runId: observation.latest?.id || null, text: '[SusLabs watchdog] ' + kind + ': ' + c.monitorName + ' — ' + reason + ' Event: ' + eventId });\n    incident.sequence = sequence;\n    incident.lastQueuedAt = now;\n  };\n  for (const [key, reason] of known) {\n    let incident = state.incidents[key];\n    if (reason) {\n      if (!incident?.active) {\n        incident = { active: true, openedAt: Math.max(now, (incident?.openedAt || 0) + 1), sequence: 0 };\n        state.incidents[key] = incident;\n        enqueue(key, incident, 'ALERT', reason);\n      } else if (c.reminderHours > 0 && now - incident.lastQueuedAt >= c.reminderHours * 3600000 && !state.outbox.some(e => e.incidentKey === key)) {\n        enqueue(key, incident, 'REMINDER', reason);\n      }\n      incident.reason = reason;\n    } else if (incident?.active) {\n      enqueue(key, incident, 'RECOVERY', 'Health checks resumed for ' + key + '.');\n      incident.active = false;\n      incident.closedAt = now;\n    }\n  }\n  if (state.outbox.length > 100) throw Error('Outbox limit reached; inspect receiver and state table.');\n  const activeIssues = Object.entries(state.incidents).filter(([, v]) => v.active).map(([key, v]) => ({ key, reason: v.reason }));\n  if (activeIssues.length) status = 'ATTENTION';\n  const pendingCoverageGaps = Object.entries(state.pendingGaps).filter(([key]) => !state.incidents[key]?.active).map(([key, gap]) => ({ key, firstSeenRunId: gap.firstSeenRunId, lastSeenRunId: gap.lastSeenRunId, observedRuns: gap.runIds.length, requiredRuns: c.gapAlertAfterRuns ?? 2 }));\n  if (!activeIssues.length && pendingCoverageGaps.length) status = 'GAP_PENDING';\n  return { state, status, activeIssues, pendingCoverageGaps, pending: state.outbox.length, event: state.outbox[0] || null };\n}\nfunction acknowledge(state, eventIds, accepted, now) {\n  const next = JSON.parse(JSON.stringify(state));\n  if (accepted) {\n    if (!Array.isArray(eventIds) || !eventIds.length || eventIds.some((id, i) => next.outbox[i]?.eventId !== id)) throw Error('Outbox acknowledgement does not match head.');\n    next.outbox.splice(0, eventIds.length);\n    next.lastDelivered = { eventIds, at: now };\n  }\n  return next;\n}\n\n\nconst p=$('Check delivery lease').first().json;\nconst accepted=Number.isInteger($json.statusCode) && $json.statusCode>=200 && $json.statusCode<300 && !$json.error;\nreturn [{json:{...p,state:acknowledge(p.state,p.eventIds,accepted,Date.now()),delivery:accepted?'accepted':'pending-retry'}}];"
      }
    },
    {
      "id": "release",
      "name": "Save state and release lease",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        4400,
        0
      ],
      "parameters": {
        "resource": "row",
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Configure watchdog').first().json.stateTableName }}"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "id",
              "condition": "eq",
              "keyValue": "={{ $('Verify lease').first().json.rowId }}"
            },
            {
              "keyName": "leaseId",
              "condition": "eq",
              "keyValue": "={{ $('Verify lease').first().json.leaseId }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "stateJson": "={{ JSON.stringify($json.state) }}",
            "leaseId": "",
            "leaseUntil": 0
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "finish",
      "name": "Watchdog result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4620,
        0
      ],
      "parameters": {
        "jsCode": "if($json.leaseId!=='' || $json.leaseUntil!==0) throw new Error('Lease release not confirmed.');\nconst state=JSON.parse($json.stateJson);\nif($('Configure watchdog').first().json.deliveryEnabled && state.outbox.length>0) throw new Error('Notification delivery was not accepted. Pending events are persisted and the lease is released; next check retries the same event IDs.');\nreturn [{json:{watchdogKey:$json.watchdogKey,checkedAt:new Date(state.checkedAt).toISOString(),activeIssues:Object.entries(state.incidents).filter(([,v])=>v.active).map(([key,v])=>({key,reason:v.reason})),pendingCoverageGaps:Object.entries(state.pendingGaps || {}).filter(([key])=>!state.incidents[key]?.active).map(([key,g])=>({key,firstSeenRunId:g.firstSeenRunId,lastSeenRunId:g.lastSeenRunId,observedRuns:g.runIds.length,requiredRuns:$('Configure watchdog').first().json.gapAlertAfterRuns ?? 2})),pendingNotifications:state.outbox.length,lastDelivered:state.lastDelivered || null,deliveryEnabled:$('Configure watchdog').first().json.deliveryEnabled}}];"
      }
    },
    {
      "id": "notes",
      "name": "Read before enabling",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -420
      ],
      "parameters": {
        "width": 760,
        "height": 340,
        "content": "## Optional independent Reddit watchdog\nInactive; schedule disabled; deliveryEnabled=false.\n1. Follow README; create state table and seed one row per key.\n2. Configure dedicated collector task ID, monitor name and exact source descriptors.\n3. Select Header Auth on the THREE Apify GET nodes.\n4. Test fixtures and a destination manually before enabling.\n5. Use separate hosting if you need to detect an n8n host outage.\nNo collector starts, pricing changes or raw-silence warnings. Stable event IDs; receiver deduplication needed for crash-safe notification handling."
      }
    }
  ],
  "connections": {
    "Manual test": {
      "main": [
        [
          {
            "node": "Configure watchdog",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Independent five-minute check": {
      "main": [
        [
          {
            "node": "Configure watchdog",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configure watchdog": {
      "main": [
        [
          {
            "node": "Read persistent state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read persistent state": {
      "main": [
        [
          {
            "node": "Prepare exclusive lease",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare exclusive lease": {
      "main": [
        [
          {
            "node": "Claim exclusive lease",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claim exclusive lease": {
      "main": [
        [
          {
            "node": "Verify lease",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify lease": {
      "main": [
        [
          {
            "node": "Read dedicated task runs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read dedicated task runs": {
      "main": [
        [
          {
            "node": "Select collector evidence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Select collector evidence": {
      "main": [
        [
          {
            "node": "Completed success to inspect",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read exact MONITOR_STATE": {
      "main": [
        [
          {
            "node": "Keep monitor evidence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Keep monitor evidence": {
      "main": [
        [
          {
            "node": "Read exact SUMMARY",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read exact SUMMARY": {
      "main": [
        [
          {
            "node": "Keep summary evidence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Keep summary evidence": {
      "main": [
        [
          {
            "node": "Evaluate health and stage events",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Evaluate health and stage events": {
      "main": [
        [
          {
            "node": "Persist outbox before sending",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Persist outbox before sending": {
      "main": [
        [
          {
            "node": "Verify staged events",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify staged events": {
      "main": [
        [
          {
            "node": "Notification enabled and pending",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check delivery lease": {
      "main": [
        [
          {
            "node": "Send notification batch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send notification batch": {
      "main": [
        [
          {
            "node": "Acknowledge accepted batch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Acknowledge accepted batch": {
      "main": [
        [
          {
            "node": "Save state and release lease",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save state and release lease": {
      "main": [
        [
          {
            "node": "Watchdog result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Completed success to inspect": {
      "main": [
        [
          {
            "node": "Read exact MONITOR_STATE",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Evaluate health and stage events",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notification enabled and pending": {
      "main": [
        [
          {
            "node": "Check delivery lease",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Save state and release lease",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "executionTimeout": 120,
    "timezone": "UTC"
  },
  "pinData": {},
  "tags": []
}
