{
  "name": "Weekly n8n Health Check (template)",
  "nodes": [
    {
      "parameters": { "rule": { "interval": [{ "field": "weeks", "triggerAtDay": [1], "triggerAtHour": 8 }] } },
      "id": "e6b8e01e-43c1-4d2b-b964-ea46363b2fac",
      "name": "Every Monday 8 AM",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.4,
      "position": [0, 304]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "CREATE TABLE IF NOT EXISTS fix_queue (\n  id SERIAL PRIMARY KEY,\n  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n  workflow_id TEXT NOT NULL,\n  workflow_name TEXT,\n  failure_count INT,\n  latest_execution_id TEXT,\n  failing_node TEXT,\n  error_message TEXT,\n  diagnosis TEXT,\n  recommendation TEXT,\n  proposed_change TEXT,\n  risk TEXT,\n  status TEXT NOT NULL DEFAULT 'pending',\n  decided_at TIMESTAMPTZ,\n  applied_at TIMESTAMPTZ,\n  apply_result TEXT\n);\nSELECT 1 AS ready;",
        "options": {}
      },
      "id": "8a535843-3d30-48c8-8c43-b385246bd0e8",
      "name": "Ensure Fix Queue Table",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.7,
      "position": [240, 304],
      "executeOnce": true
    },
    {
      "parameters": { "resource": "execution", "limit": 250, "filters": { "status": "error" }, "options": {}, "requestOptions": {} },
      "id": "8da1ad18-93df-4c2b-a151-a0eae7726add",
      "name": "Get Failed Runs",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [480, 304],
      "executeOnce": true
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "loose", "version": 2 },
          "conditions": [
            {
              "leftValue": "={{ $json.startedAt }}",
              "rightValue": "={{ $now.minus({ days: 7 }).toISO() }}",
              "operator": { "type": "dateTime", "operation": "after" }
            }
          ]
        },
        "options": {}
      },
      "id": "853a3891-32ea-4f2a-a070-e83dd0482a3a",
      "name": "Keep Last 7 Days",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.3,
      "position": [720, 304]
    },
    {
      "parameters": {
        "fieldsToSummarize": { "values": [{ "field": "id" }, { "aggregation": "append", "field": "id" }] },
        "fieldsToSplitBy": "workflowId",
        "options": {}
      },
      "id": "4ee06645-d6b3-4a83-8c8c-c79d2912b632",
      "name": "Group By Workflow",
      "type": "n8n-nodes-base.summarize",
      "typeVersion": 1.1,
      "position": [960, 304]
    },
    {
      "parameters": { "sortFieldsUi": { "sortField": [{ "fieldName": "count_id", "order": "descending" }] }, "options": {} },
      "id": "62b63da4-4e05-4845-a5e5-e389f5b2f577",
      "name": "Most Failures First",
      "type": "n8n-nodes-base.sort",
      "typeVersion": 1,
      "position": [1200, 304]
    },
    {
      "parameters": { "maxItems": 5 },
      "id": "3eb014f2-0771-4971-a8bb-475377f2f95c",
      "name": "Top Failing Workflows",
      "type": "n8n-nodes-base.limit",
      "typeVersion": 1,
      "position": [1440, 304]
    },
    {
      "parameters": {
        "resource": "execution",
        "operation": "get",
        "executionId": "={{ $json.appended_id[0] }}",
        "options": { "activeWorkflows": true },
        "requestOptions": {}
      },
      "id": "e353d4ae-ed3f-4483-b36e-da7b71a399b5",
      "name": "Get Latest Failed Run",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [1680, 304]
    },
    {
      "parameters": {
        "operation": "get",
        "workflowId": { "__rl": true, "mode": "id", "value": "={{ $('Top Failing Workflows').item.json.workflowId }}" },
        "requestOptions": {}
      },
      "id": "7b10210d-84d5-4204-bd66-e715cf6656dd",
      "name": "Get Workflow",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [1920, 304]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            { "id": "ctx-wf-id", "name": "workflow_id", "value": "={{ $('Top Failing Workflows').item.json.workflowId }}", "type": "string" },
            { "id": "ctx-wf-name", "name": "workflow_name", "value": "={{ $json.name ?? 'Unknown workflow' }}", "type": "string" },
            { "id": "ctx-count", "name": "failure_count", "value": "={{ $('Top Failing Workflows').item.json.count_id }}", "type": "number" },
            { "id": "ctx-exec", "name": "latest_execution_id", "value": "={{ $('Get Latest Failed Run').item.json.id }}", "type": "string" },
            { "id": "ctx-node", "name": "failing_node", "value": "={{ $('Get Latest Failed Run').item.json.data?.resultData?.lastNodeExecuted ?? 'unknown' }}", "type": "string" },
            { "id": "ctx-error", "name": "error_message", "value": "={{ String($('Get Latest Failed Run').item.json.data?.resultData?.error?.message ?? $('Get Latest Failed Run').item.json.data?.resultData?.error?.description ?? 'No error message recorded').slice(0, 1500) }}", "type": "string" },
            { "id": "ctx-node-type", "name": "failing_node_type", "value": "={{ ($json.nodes ?? []).find(n => n.name === ($('Get Latest Failed Run').item.json.data?.resultData?.lastNodeExecuted ?? ''))?.type ?? 'unknown' }}", "type": "string" },
            { "id": "ctx-node-config", "name": "failing_node_config", "value": "={{ JSON.stringify(($json.nodes ?? []).find(n => n.name === ($('Get Latest Failed Run').item.json.data?.resultData?.lastNodeExecuted ?? ''))?.parameters ?? {}).slice(0, 4000) }}", "type": "string" },
            { "id": "ctx-node-list", "name": "node_list", "value": "={{ ($json.nodes ?? []).filter(n => !n.type.includes('stickyNote')).map(n => n.name + ' (' + n.type.split('.').pop() + ')').join(', ').slice(0, 2000) }}", "type": "string" }
          ]
        },
        "options": {}
      },
      "id": "6f17da0f-2250-4bc3-b4a2-1c5086850fa3",
      "name": "Build Failure Context",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [2160, 304]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=You review failing n8n workflows and recommend one specific, safe fix. Return JSON only.\n\nRules:\n- Prefer native n8n nodes. Do not suggest Code nodes unless nothing native can do it.\n- If the cause looks external or temporary (API outage, rate limit, network blip), say so and recommend the smallest fix, such as Retry On Fail.\n- Never recommend hiding a real failure just to make the run green. If a node deliberately fails the run to flag a problem, say what the underlying problem is.\n- proposed_change must name the exact node, the parameter, and the new value, so another agent could apply it.\n- risk is one of: low, medium, high. High means the change could alter what the workflow does to live data.\n- Keep diagnosis and recommendation short and plain.\n\nWorkflow: {{ $json.workflow_name }}\nFailed runs in the last 7 days: {{ $json.failure_count }}\nFailing node: {{ $json.failing_node }} ({{ $json.failing_node_type }})\nError: {{ $json.error_message }}\n\nFailing node parameters:\n{{ $json.failing_node_config }}\n\nAll nodes in the workflow:\n{{ $json.node_list }}",
        "hasOutputParser": true,
        "batching": {}
      },
      "id": "10a4246d-1140-4b20-8d95-1501e326e973",
      "name": "Recommend Fix",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.9,
      "position": [2400, 304]
    },
    {
      "parameters": {
        "model": { "__rl": true, "mode": "list", "value": "openai/gpt-oss-20b", "cachedResultName": "openai/gpt-oss-20b" },
        "responsesApiEnabled": false,
        "options": { "temperature": 0.2, "timeout": 180000 }
      },
      "id": "2449ed73-f693-4fe2-a902-a61bbbf74ad7",
      "name": "Local Model (LM Studio)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [2320, 544]
    },
    {
      "parameters": {
        "jsonSchemaExample": "{ \"diagnosis\": \"Plain-English explanation of why it fails\", \"recommendation\": \"What to change, in one or two sentences\", \"proposed_change\": \"Exact node name, parameter and new value\", \"risk\": \"low\" }"
      },
      "id": "790cba38-45cb-4d3e-b236-136cf0f8858e",
      "name": "Fix Format",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [2512, 544]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            { "id": "sr-wf-id", "name": "workflow_id", "value": "={{ $('Build Failure Context').item.json.workflow_id }}", "type": "string" },
            { "id": "sr-wf-name", "name": "workflow_name", "value": "={{ $('Build Failure Context').item.json.workflow_name }}", "type": "string" },
            { "id": "sr-count", "name": "failure_count", "value": "={{ $('Build Failure Context').item.json.failure_count }}", "type": "number" },
            { "id": "sr-exec", "name": "latest_execution_id", "value": "={{ $('Build Failure Context').item.json.latest_execution_id }}", "type": "string" },
            { "id": "sr-node", "name": "failing_node", "value": "={{ $('Build Failure Context').item.json.failing_node }}", "type": "string" },
            { "id": "sr-error", "name": "error_message", "value": "={{ $('Build Failure Context').item.json.error_message }}", "type": "string" },
            { "id": "sr-diag", "name": "diagnosis", "value": "={{ $json.output?.diagnosis ?? 'Model gave no diagnosis' }}", "type": "string" },
            { "id": "sr-rec", "name": "recommendation", "value": "={{ $json.output?.recommendation ?? '' }}", "type": "string" },
            { "id": "sr-change", "name": "proposed_change", "value": "={{ $json.output?.proposed_change ?? '' }}", "type": "string" },
            { "id": "sr-risk", "name": "risk", "value": "={{ $json.output?.risk ?? 'unknown' }}", "type": "string" }
          ]
        },
        "options": {}
      },
      "id": "49237d75-a80a-4dab-a873-947ce300e66f",
      "name": "Shape Recommendation",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [2720, 304]
    },
    {
      "parameters": { "options": {} },
      "id": "66ecd682-c417-4e36-a07c-a4b974dee96a",
      "name": "One At A Time",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [2960, 304]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO fix_queue (workflow_id, workflow_name, failure_count, latest_execution_id, failing_node, error_message, diagnosis, recommendation, proposed_change, risk)\nVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\nRETURNING *;",
        "options": {
          "queryReplacement": "={{ [$json.workflow_id, $json.workflow_name, $json.failure_count, $json.latest_execution_id, $json.failing_node, $json.error_message, $json.diagnosis, $json.recommendation, $json.proposed_change, $json.risk] }}"
        }
      },
      "id": "8075cf28-f162-46e2-8239-6b18d0662348",
      "name": "Save Recommendation",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.7,
      "position": [3200, 432]
    },
    {
      "parameters": {
        "operation": "sendAndWait",
        "chatId": "YOUR_TELEGRAM_CHAT_ID",
        "message": "=n8n weekly check, fix {{ $runIndex + 1 }} of {{ $('Shape Recommendation').all().length }}\n\nWorkflow: {{ $json.workflow_name }}\nFailed {{ $json.failure_count }} times this week\nNode: {{ $json.failing_node }}\nError: {{ String($json.error_message).slice(0, 400) }}\n\nWhat is wrong: {{ String($json.diagnosis).slice(0, 700) }}\n\nFix: {{ String($json.recommendation).slice(0, 700) }}\n\nChange: {{ String($json.proposed_change).slice(0, 500) }}\n\nRisk: {{ $json.risk }}",
        "approvalOptions": { "values": { "approvalType": "double", "disapproveLabel": "❌ Deny" } },
        "chatApproval": true,
        "approverIds": "YOUR_TELEGRAM_CHAT_ID",
        "options": { "limitWaitTime": { "values": { "resumeAmount": 3, "resumeUnit": "days" } }, "appendAttribution": false }
      },
      "id": "389f70d2-7a75-458f-8860-92bc53530ea6",
      "name": "Ask Me To Approve",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [3440, 432]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "UPDATE fix_queue SET status = $1, decided_at = now() WHERE id = $2 RETURNING id, status;",
        "options": {
          "queryReplacement": "={{ [$json.data?.approved === true ? 'approved' : ($json.data?.approved === false ? 'denied' : 'expired'), $('Save Recommendation').item.json.id] }}"
        }
      },
      "id": "d240f4b2-5282-4cca-88f3-e8694803cc5f",
      "name": "Record Decision",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.7,
      "position": [3680, 432]
    },
    {
      "parameters": {
        "content": "## Setup\n1. Open **Get Failed Runs**, **Get Latest Failed Run** and **Get Workflow** and pick your n8n API credential (create one from Settings > n8n API).\n2. Open both **Postgres** nodes and pick your Postgres credential.\n3. Open **Local Model (LM Studio)** and pick an OpenAI-compatible credential pointing at your local server (or swap in any chat model).\n4. Open **Ask Me To Approve** and pick a Telegram credential, then replace `YOUR_TELEGRAM_CHAT_ID` in both fields with your own chat ID.\n5. Run once manually to test, then activate.\n\nRuns Monday 8 AM. Looks at the last 7 days of failed runs, takes the 5 workflows that failed most, asks the model for one fix each, then sends them to Telegram one at a time. Approve or Deny is saved to the `fix_queue` table.\n\nNo failures that week means no messages.",
        "height": 380,
        "width": 520,
        "color": 3
      },
      "id": "b5cd2dcf-1d1b-4953-8a71-933e552fd98c",
      "name": "Sticky Note Setup",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [-48, -140]
    }
  ],
  "connections": {
    "Every Monday 8 AM": { "main": [[{ "node": "Ensure Fix Queue Table", "type": "main", "index": 0 }]] },
    "Ensure Fix Queue Table": { "main": [[{ "node": "Get Failed Runs", "type": "main", "index": 0 }]] },
    "Get Failed Runs": { "main": [[{ "node": "Keep Last 7 Days", "type": "main", "index": 0 }]] },
    "Keep Last 7 Days": { "main": [[{ "node": "Group By Workflow", "type": "main", "index": 0 }]] },
    "Group By Workflow": { "main": [[{ "node": "Most Failures First", "type": "main", "index": 0 }]] },
    "Most Failures First": { "main": [[{ "node": "Top Failing Workflows", "type": "main", "index": 0 }]] },
    "Top Failing Workflows": { "main": [[{ "node": "Get Latest Failed Run", "type": "main", "index": 0 }]] },
    "Get Latest Failed Run": { "main": [[{ "node": "Get Workflow", "type": "main", "index": 0 }]] },
    "Get Workflow": { "main": [[{ "node": "Build Failure Context", "type": "main", "index": 0 }]] },
    "Build Failure Context": { "main": [[{ "node": "Recommend Fix", "type": "main", "index": 0 }]] },
    "Recommend Fix": { "main": [[{ "node": "Shape Recommendation", "type": "main", "index": 0 }]] },
    "Local Model (LM Studio)": { "ai_languageModel": [[{ "node": "Recommend Fix", "type": "ai_languageModel", "index": 0 }]] },
    "Fix Format": { "ai_outputParser": [[{ "node": "Recommend Fix", "type": "ai_outputParser", "index": 0 }]] },
    "Shape Recommendation": { "main": [[{ "node": "One At A Time", "type": "main", "index": 0 }]] },
    "One At A Time": { "main": [[], [{ "node": "Save Recommendation", "type": "main", "index": 0 }]] },
    "Save Recommendation": { "main": [[{ "node": "Ask Me To Approve", "type": "main", "index": 0 }]] },
    "Ask Me To Approve": { "main": [[{ "node": "Record Decision", "type": "main", "index": 0 }]] },
    "Record Decision": { "main": [[{ "node": "One At A Time", "type": "main", "index": 0 }]] }
  },
  "settings": { "executionOrder": "v1", "timezone": "America/Chicago" },
  "pinData": {}
}
