{
  "name": "Message Drift Monitor",
  "nodes": [
    {
      "id": "c5a967e6-c502-4f8b-b34a-3eee17f2e021",
      "name": "Weekly Drift Check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "50 7 * * 1"
            }
          ]
        }
      }
    },
    {
      "id": "eeb3a4da-806c-4385-a432-8c6a0120459a",
      "name": "Get Messaging Guide",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "UIzbFgJrIa1Y9Rwb",
          "cachedResultName": "Messaging & Product Facts"
        },
        "returnAll": true
      },
      "executeOnce": true
    },
    {
      "id": "5ee4b143-9495-452b-8875-c6c700ca8455",
      "name": "Get Outbound Samples",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "YldXYaCcADvaw06y",
          "cachedResultName": "Rep Outbound Samples"
        },
        "returnAll": true
      },
      "executeOnce": true
    },
    {
      "id": "ad3ab5a6-945b-4362-bfb9-35790c9cb999",
      "name": "Prepare Guide & Emails",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Build the messaging guide and the review window in code. Claude only labels claims; it never decides which emails are in scope.\nconst runDate = $today.toFormat('yyyy-MM-dd');\nconst windowStart = $today.minus({ days: 14 }).toFormat('yyyy-MM-dd');\nconst rows = $('Get Messaging Guide').all().map(i => i.json).filter(r => r.factId);\nconst guide = {\n  currentFacts: rows.filter(r => r.kind === 'fact').map(r => ({ code: r.factId, topic: r.topic, current: r.statement, outdatedVersion: r.previousStatement })),\n  pillars: rows.filter(r => r.kind === 'pillar').map(r => ({ code: r.factId, topic: r.topic, point: r.statement })),\n  prohibited: rows.filter(r => r.kind === 'prohibited').map(r => ({ code: r.factId, topic: r.topic, rule: r.statement }))\n};\nconst emails = $('Get Outbound Samples').all().map(i => i.json).filter(e => e.sampleId && e.sentOn >= windowStart && e.sentOn <= runDate)\n  .map(e => ({ sampleId: e.sampleId, rep: e.rep, sentOn: e.sentOn, subject: e.subject, body: e.body, seedKey: e.seedKey || '' }));\nreturn [{ json: { runDate, windowStart, guide, emails } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "7e889a32-34bd-4ff4-a83a-89a2184c64ec",
      "name": "Message Classifier",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify({ guide: $json.guide, emails: $json.emails.map(e => ({ sampleId: e.sampleId, body: e.body })) }, null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You review outbound sales emails for Fortavault, Inc. (a fictional data protection company) against its messaging guide. The guide has current facts (each with the outdated version it replaced), messaging pillars and prohibited claims.\n\nFor each email, label every claim that:\n(a) states an outdated version of a fact, or anything else the current fact contradicts: use that fact's code;\n(b) breaks a prohibited rule as written: use that rule's code;\n(c) makes a pillar's point using current facts: use that pillar's code.\n\nA sentence that states an outdated fact counts only as the outdated fact, not as a pillar. A claim that agrees with the current fact is not a finding. A price, discount or timeline is only prohibited when it breaks the rule as written (a discount at or below the limit is fine). Use each code at most once per email.\n\nFor each label return sampleId, code and quote: the shortest exact span from the email that contains the claim, copied word for word. Never paraphrase or join sentences. Return an empty list if nothing applies."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "9fabf171-1c52-4ec2-8e08-292f8e333efc",
      "name": "Claude Sonnet",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "typeVersion": 1.3,
      "position": [
        100,
        450
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "claude-sonnet-4-6",
          "cachedResultName": "Claude Sonnet 4.6"
        },
        "options": {
          "temperature": 0
        }
      },
      "credentials": {
        "anthropicApi": {
          "id": "3d3ZiTi7BwnkFwqU",
          "name": "Anthropic account"
        }
      }
    },
    {
      "id": "01d1d6fd-c7e2-4105-8c28-a9458702a186",
      "name": "Claims Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "fromJson",
        "jsonSchemaExample": "{ \"claims\": [{ \"sampleId\": \"M1\", \"code\": \"P1\", \"quote\": \"exact words from the email\" }] }"
      }
    },
    {
      "id": "0009f7ed-78da-4cea-acd4-26ba5e0ee298",
      "name": "Verify & Score Drift",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Verify and score in code. A claim counts only if its quote appears word for word in that email and its code exists in the guide.\n// Per-rep drift, team pillar coverage and the digest are computed here; the seeded answer key measures the checker itself.\nconst p = $('Prepare Guide & Emails').first().json;\nconst out = $('Message Classifier').first().json.output || {};\nconst norm = s => String(s || '').replace(/[‘’]/g, \"'\").replace(/[“”]/g, '\"').replace(/\\s+/g, ' ').trim().toLowerCase();\nconst safe = t => String(t || '').replace(/~/g, '≈');\nconst G = {};\nfor (const f of p.guide.currentFacts) G[f.code] = { kind: 'outdated fact', guidance: 'Now: ' + f.current };\nfor (const x of p.guide.prohibited) G[x.code] = { kind: 'prohibited', guidance: 'Rule: ' + x.rule };\nfor (const q of p.guide.pillars) G[q.code] = { kind: 'pillar', guidance: q.topic };\nconst byId = {}; for (const e of p.emails) byId[e.sampleId] = e;\nconst kept = [], dropped = [], seen = new Set();\nfor (const c of (out.claims || [])) {\n  const e = byId[c.sampleId], g = G[c.code], key = c.sampleId + '|' + c.code;\n  const ok = e && g && c.quote && norm(c.quote).length >= 8 && norm(e.body).includes(norm(c.quote));\n  if (!ok || seen.has(key)) { dropped.push({ ...c, reason: !e ? 'unknown email' : !g ? 'unknown code' : seen.has(key) ? 'duplicate' : 'quote not found verbatim' }); continue; }\n  seen.add(key);\n  kept.push({ sampleId: e.sampleId, rep: e.rep, code: c.code, kind: g.kind, quote: c.quote.trim(), guidance: g.guidance });\n}\nconst issues = kept.filter(k => k.kind !== 'pillar'), pillarsUsed = kept.filter(k => k.kind === 'pillar');\n// Per rep\nconst reps = [...new Set(p.emails.map(e => e.rep))].map(rep => {\n  const n = p.emails.filter(e => e.rep === rep).length, iss = issues.filter(k => k.rep === rep);\n  const pil = [...new Set(pillarsUsed.filter(k => k.rep === rep).map(k => k.code))].sort();\n  return { rep, emails: n, outdated: iss.filter(k => k.kind === 'outdated fact').length, prohibited: iss.filter(k => k.kind === 'prohibited').length, pillars: pil };\n}).sort((a, b) => (b.outdated + b.prohibited) - (a.outdated + a.prohibited) || a.rep.localeCompare(b.rep));\nconst teamPillars = p.guide.pillars.map(q => ({ code: q.code, topic: q.topic, emails: pillarsUsed.filter(k => k.code === q.code).length }));\n// Checker accuracy against the seeded answer key (only possible because these emails are seeded).\nconst keySet = new Set(p.emails.flatMap(e => String(e.seedKey).split(',').map(s => s.trim()).filter(Boolean).map(c => e.sampleId + '|' + c)));\nconst isIssue = k => !k.split('|')[1].startsWith('P');\nconst found = new Set(kept.map(k => k.sampleId + '|' + k.code));\nconst acc = sel => { const keyN = [...keySet].filter(sel), foundN = [...found].filter(sel); const tp = foundN.filter(k => keySet.has(k)).length;\n  return { key: keyN.length, found: foundN.length, hits: tp, missed: keyN.filter(k => !found.has(k)), falseFlags: foundN.filter(k => !keySet.has(k)) }; };\nconst accuracy = { issues: acc(isIssue), pillars: acc(k => !isIssue(k)) };\n// Digest\nconst repLine = r => '*' + r.rep + '* · ' + r.emails + ' email' + (r.emails === 1 ? '' : 's') + ' · ' +\n  (r.outdated + r.prohibited ? (r.outdated ? r.outdated + ' outdated' : '') + (r.outdated && r.prohibited ? ', ' : '') + (r.prohibited ? r.prohibited + ' prohibited' : '') : 'on message') +\n  ' · pillars ' + (r.pillars.length ? r.pillars.join(' ') : 'none') + ' (' + r.pillars.length + ' of ' + p.guide.pillars.length + ')';\nconst fixLines = issues.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === 'prohibited' ? -1 : 1) || a.rep.localeCompare(b.rep))\n  .map(k => '• ' + (k.kind === 'prohibited' ? ':no_entry: ' : '') + k.rep.split(' ')[0] + ' (' + k.sampleId + '): “' + safe(k.quote) + '”\\n      _' + safe(k.guidance) + '_');\nconst minUse = Math.min(...teamPillars.map(t => t.emails)), weakest = teamPillars.filter(t => t.emails === minUse);\nlet text = ':satellite_antenna: *Message Drift Monitor* (' + p.windowStart + ' to ' + p.runDate + ')\\n' + p.emails.length + ' outbound emails from ' + reps.length + ' reps checked against ' + p.guide.currentFacts.length + ' current facts, ' + p.guide.pillars.length + ' pillars and ' + p.guide.prohibited.length + ' rules. Every quote below is word for word from the email.\\n\\n' +\n  '*By rep*\\n' + reps.map(repLine).join('\\n') + '\\n\\n' +\n  '*Fix before the next send* (' + issues.length + ')\\n' + (fixLines.length ? fixLines.join('\\n') : '• Nothing off message') + '\\n\\n' +\n  '*Team pillar coverage*: ' + teamPillars.map(t => t.code + ' ' + t.topic + ' ' + t.emails).join(' · ') + '. Least used: *' + weakest.map(t => t.topic).join(', ') + '*' + (weakest.length > 1 ? ' (tied at ' + minUse + ')' : '') + '.' +\n  (dropped.length ? '\\n_' + dropped.length + ' label(s) dropped: quote not found word for word._' : '') +\n  '\\n_Checker vs seeded answer key: ' + accuracy.issues.hits + ' of ' + accuracy.issues.key + ' issues found, ' + accuracy.issues.falseFlags.length + ' false flags; ' + accuracy.pillars.hits + ' of ' + accuracy.pillars.key + ' pillar uses, ' + accuracy.pillars.falseFlags.length + ' extra._';\nif (text.length > 2900) text = text.slice(0, 2850).slice(0, text.slice(0, 2850).lastIndexOf('\\n')) + '\\n_…cut to fit Slack; every finding is in the Message Drift Log._';\nconst now = $now.toISO();\nconst logs = kept.map(k => ({ runDate: p.runDate, sampleId: k.sampleId, rep: k.rep, code: k.code, kind: k.kind, quote: k.quote, guidance: k.guidance, loggedAt: now }));\nreturn [{ json: { runDate: p.runDate, reps, teamPillars, accuracy, dropped, logs, digestText: text, digestChars: text.length } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "d02c1c51-0594-4187-902a-f1433affb586",
      "name": "Post Drift Digest",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.7,
      "position": [
        700,
        450
      ],
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C0BQ3G96HL6",
          "cachedResultName": "general"
        },
        "text": "={{ $json.digestText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "0b8141a9-7aae-4624-a202-2bc62e7df4d5",
      "name": "Split Drift Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Verify & Score Drift').first().json.logs.map(json => ({ json }));"
      }
    },
    {
      "id": "e7f5a780-6ad8-4cb9-93d4-0ac80039482c",
      "name": "Log Drift Findings",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "IQUsiv2VTQYfZwmS",
          "cachedResultName": "Message Drift Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Weekly Drift Check": {
      "main": [
        [
          {
            "node": "Get Messaging Guide",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Messaging Guide": {
      "main": [
        [
          {
            "node": "Get Outbound Samples",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Outbound Samples": {
      "main": [
        [
          {
            "node": "Prepare Guide & Emails",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Guide & Emails": {
      "main": [
        [
          {
            "node": "Message Classifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message Classifier": {
      "main": [
        [
          {
            "node": "Verify & Score Drift",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Message Classifier",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Claims Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Message Classifier",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Verify & Score Drift": {
      "main": [
        [
          {
            "node": "Post Drift Digest",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Drift Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Drift Rows": {
      "main": [
        [
          {
            "node": "Log Drift Findings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}