{
  "name": "Burrow Run Tracker",
  "nodes": [
    {
      "id": "every-10-minutes",
      "name": "Every 10 Minutes",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 10
            }
          ]
        }
      }
    },
    {
      "id": "clients",
      "name": "Clients",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1,
      "position": [
        220,
        0
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "burrow_destinations"
        },
        "returnAll": true
      }
    },
    {
      "id": "workflows",
      "name": "Workflows",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [
        440,
        0
      ],
      "parameters": {
        "resource": "workflow",
        "operation": "getAll",
        "returnAll": true,
        "filters": {}
      },
      "executeOnce": true
    },
    {
      "id": "executions",
      "name": "Executions",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [
        660,
        0
      ],
      "parameters": {
        "resource": "execution",
        "operation": "getAll",
        "returnAll": false,
        "limit": 250,
        "filters": {},
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "map-runs",
      "name": "Map Runs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        0
      ],
      "parameters": {
        "jsCode": "// Why Code: remembers which runs were already reported and a usage queue across cycles (workflow static data), and matches workflow names to client keys.\nconst sd = $getWorkflowStaticData('global');\n// Runs finish out of id order and a run in progress is not listed at all, so a \"last id\" cursor misses long runs.\n// Instead remember the ids already reported and report any finished run that is not among them.\nconst seen = new Set(Array.isArray(sd.reported) ? sd.reported : []);\nconst firstTime = !Array.isArray(sd.reported);\nconst since = Date.now() - 3 * 60 * 60 * 1000; // first cycle: look back three hours; Burrow drops repeats\n// A workflow belongs to a client when the part of its name before \" - \" equals the client's key, ignoring\n// letter case, spaces and punctuation: key \"acme\" matches \"Acme - Chat Agent\", \"northwind\" matches \"North Wind - Weekly Sync\".\nconst norm = s => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, '');\nconst clients = $('Clients').all().map(i => i.json).filter(r => r.key);\nconst wfs = $('Workflows').all().map(i => i.json);\nconst names = Object.fromEntries(wfs.map(w => [w.id, w.name]));\n// Workflows with a chat model node: their runs are also read for token usage.\nconst hasModel = Object.fromEntries(wfs.map(w => [w.id,\n  (w.nodes || []).some(n => !n.disabled && /langchain\\.lm/i.test(String(n.type)))]));\n// Workflows tagged purge-after-report handle private data: their successful runs are saved only long enough to be\n// reported, then deleted by the Delete Run node. Failed runs are kept for debugging, as before.\nconst PURGE_TAG = 'purge-after-report';\nconst purgeWf = Object.fromEntries(wfs.map(w => [w.id, (w.tags || []).some(t => (t.name || t) === PURGE_TAG)]));\nconst purge = new Set();\nconst hourAgo = Date.now() - 60 * 60 * 1000;\nconst all = $input.all().map(i => i.json).filter(e => e && e.id);\nconst done = e => e.stoppedAt && ['success', 'error', 'crashed'].includes(e.status);\nconst byClient = {};\nconst queue = Array.isArray(sd.usageQueue) ? sd.usageQueue : [];\nconst queued = new Set(queue.map(q => q.executionId));\nfor (const e of all) {\n  // Safety net: a successful run of a tagged workflow that is still here after an hour is deleted whatever happened to its report.\n  if (done(e) && e.status === 'success' && purgeWf[e.workflowId] && new Date(e.stoppedAt).getTime() < hourAgo) purge.add(String(e.id));\n  if (!done(e) || seen.has(String(e.id))) continue;\n  seen.add(String(e.id));\n  if (firstTime && new Date(e.stoppedAt).getTime() < since) continue;\n  const name = names[e.workflowId] || '';\n  if (!name) continue;\n  const c = name.includes(' - ') ? clients.find(r => norm(r.key) === norm(name.split(' - ')[0])) : null;\n  if (!c) continue;\n  if (hasModel[e.workflowId] && !queued.has(String(e.id))) {\n    queue.push({ executionId: String(e.id), client: c.key, workflowName: name, workflowId: String(e.workflowId), stoppedAt: e.stoppedAt,\n      purge: !!purgeWf[e.workflowId] && e.status === 'success' });\n  }\n  const failed = e.status !== 'success';\n  // No chat model: nothing more to read, so the run can go as soon as it is reported. With a model it goes once its tokens are read.\n  if (!failed && purgeWf[e.workflowId] && !hasModel[e.workflowId]) purge.add(String(e.id));\n  (byClient[c.key] = byClient[c.key] || []).push({\n    event: failed ? 'automations.workflow.failed' : 'automations.workflow.completed',\n    timestamp: e.stoppedAt,\n    externalEventId: 'n8n:run:' + e.id,\n    properties: { workflowName: name, externalRunId: String(e.id),\n      duration: Math.max(0, new Date(e.stoppedAt) - new Date(e.startedAt)),\n      ...(failed ? { errorMessage: 'Run ended with status ' + e.status + '. See execution ' + e.id + ' in n8n.' } : {}) },\n    tags: { workflowId: String(e.workflowId) },\n  });\n}\n// Keep the newest 2,000 ids; the list read each cycle is the newest 250.\nsd.reported = [...seen].sort((a, b) => Number(a) - Number(b)).slice(-2000);\n// Each usage read loads a whole execution, so take a few per cycle and keep the rest for the next one.\nconst take = queue.splice(0, 20);\nsd.usageQueue = queue.slice(0, 500);\nfor (const q of take) if (q.purge) purge.add(q.executionId);\nreturn [\n  ...Object.entries(byClient).map(([client, events]) => ({ json: { kind: 'events', client, events } })),\n  ...take.map(q => ({ json: { kind: 'usage', ...q } })),\n  ...[...purge].map(id => ({ json: { kind: 'purge', executionId: id } })),\n];\n"
      }
    },
    {
      "id": "route",
      "name": "Route",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1100,
        0
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "usage",
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "usage",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "usage"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "events",
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "events",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "events"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "purge",
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "purge",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "purge"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "execution-details",
      "name": "Execution Details",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [
        1320,
        -180
      ],
      "parameters": {
        "resource": "execution",
        "operation": "get",
        "executionId": "={{ $json.executionId }}",
        "options": {
          "activeWorkflows": true
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "map-usage",
      "name": "Map Usage",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        -180
      ],
      "parameters": {
        "jsCode": "// Why Code: walks an execution's node runs and sums the tokens each chat model reported; no native node reads that shape.\nconst wanted = Object.fromEntries($('Map Runs').all().map(i => i.json).filter(j => j.kind === 'usage').map(j => [j.executionId, j]));\nconst byClient = {};\nfor (const item of $input.all()) {\n  const ex = item.json || {};\n  const q = wanted[String(ex.id)];\n  const runData = ex.data && ex.data.resultData && ex.data.resultData.runData;\n  if (!q || !runData) continue; // not found, pruned, or saved without data\n  const models = {};\n  let sessionId = null;\n  for (const runs of Object.values(runData)) {\n    for (const run of runs || []) {\n      const d = run.data || {};\n      if (!sessionId) {\n        const first = d.main && d.main[0] && d.main[0][0] && d.main[0][0].json;\n        if (first && typeof first.sessionId === 'string') sessionId = first.sessionId;\n      }\n      for (const out of (d.ai_languageModel || [])) for (const it of (out || [])) {\n        const j = it.json || {};\n        const u = j.tokenUsage || j.tokenUsageEstimate;\n        if (!u) continue;\n        let model = 'unknown';\n        try {\n          const o = run.inputOverride.ai_languageModel[0][0].json.options || {};\n          model = o.model || o.model_name || o.modelName || model;\n        } catch (e) {}\n        const m = models[model] = models[model] || { input: 0, output: 0, calls: 0, estimated: false };\n        m.input += Number(u.promptTokens || 0);\n        m.output += Number(u.completionTokens || 0);\n        m.calls += 1;\n        if (!j.tokenUsage) m.estimated = true;\n      }\n    }\n  }\n  for (const [model, m] of Object.entries(models)) {\n    if (!m.input && !m.output) continue;\n    (byClient[q.client] = byClient[q.client] || []).push({\n      event: 'automations.usage.recorded',\n      timestamp: ex.stoppedAt || q.stoppedAt,\n      externalEventId: 'n8n:usage:' + ex.id + ':' + model,\n      properties: { inputTokens: m.input, outputTokens: m.output, totalTokens: m.input + m.output, model,\n        llmCalls: m.calls, workflowName: q.workflowName, externalRunId: String(ex.id) },\n      tags: { modality: sessionId ? 'chat' : 'workflow',\n        ...(sessionId ? { agentId: q.client + '-chat', sessionId } : {}),\n        workflowId: q.workflowId,\n        // estimated = the model node gave no real count, so n8n counted tokens itself\n        tokenSource: m.estimated ? 'estimated' : 'reported' },\n    });\n  }\n}\nreturn Object.entries(byClient).map(([client, events]) => ({ json: { kind: 'events', client, events } }));\n"
      }
    },
    {
      "id": "send-to-burrow",
      "name": "Send to Burrow",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        1760,
        0
      ],
      "parameters": {
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "Burrow Event"
        },
        "workflowInputs": {
          "mappingMode": "defineBelow",
          "value": {
            "client": "={{ $json.client }}",
            "events": "={{ $json.events }}"
          },
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false,
          "schema": [
            {
              "id": "client",
              "displayName": "client",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "string"
            },
            {
              "id": "events",
              "displayName": "events",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "array"
            }
          ]
        },
        "mode": "each",
        "options": {
          "waitForSubWorkflow": true
        }
      }
    },
    {
      "id": "runs-to-delete",
      "name": "Runs to Delete",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        200
      ],
      "parameters": {
        "jsCode": "// Why Code: picks the runs Map Runs marked for deletion and holds them back until their tokens have been read.\nconst items = $('Map Runs').all().map(i => i.json);\nconst wantsUsage = items.some(j => j.kind === 'usage');\n// This node is reached from Route and again from Execution Details. While tokens are still to be read, wait for the second pass.\nif (wantsUsage && !$('Execution Details').isExecuted) return [];\nreturn items.filter(j => j.kind === 'purge').map(j => ({ json: { executionId: j.executionId } }));\n"
      }
    },
    {
      "id": "delete-run",
      "name": "Delete Run",
      "type": "n8n-nodes-base.n8n",
      "typeVersion": 1,
      "position": [
        1760,
        200
      ],
      "parameters": {
        "resource": "execution",
        "operation": "delete",
        "executionId": "={{ $json.executionId }}"
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "sticky-note",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -520
      ],
      "parameters": {
        "width": 660,
        "height": 430,
        "content": "## Burrow Run Tracker\nReports every finished run of your clients' workflows to Burrow as `automations.workflow.completed` or `automations.workflow.failed`, so those workflows need no nodes for run health.\n\n**Set up once:**\n1. *Clients*: choose your **burrow_destinations** data table.\n2. *Workflows*, *Executions*, *Execution Details*, *Delete Run*: choose an n8n API credential for this instance.\n3. *Send to Burrow*: choose your **Burrow Event** workflow.\n\n- A workflow belongs to a client when the part of its name before ` - ` equals that client's `key`, ignoring letter case, spaces and punctuation (key `acme` matches `Acme - Chat Agent`). No match = not reported.\n- A workflow that does not save successful runs is invisible here; have it report its own run.\n- Tag a workflow `purge-after-report` to have its successful runs deleted once they are reported (private data).\n- Reads the 250 most recent executions each time and reports any finished run it has not reported before.\n- Runs of workflows with a chat model are also read for tokens and reported as `automations.usage.recorded`."
      }
    }
  ],
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "none"
  },
  "connections": {
    "Every 10 Minutes": {
      "main": [
        [
          {
            "node": "Clients",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clients": {
      "main": [
        [
          {
            "node": "Workflows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflows": {
      "main": [
        [
          {
            "node": "Executions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Executions": {
      "main": [
        [
          {
            "node": "Map Runs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map Runs": {
      "main": [
        [
          {
            "node": "Route",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route": {
      "main": [
        [
          {
            "node": "Execution Details",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send to Burrow",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Runs to Delete",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execution Details": {
      "main": [
        [
          {
            "node": "Map Usage",
            "type": "main",
            "index": 0
          },
          {
            "node": "Runs to Delete",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map Usage": {
      "main": [
        [
          {
            "node": "Send to Burrow",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Runs to Delete": {
      "main": [
        [
          {
            "node": "Delete Run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
