{
  "name": "Goal Drift Detector",
  "nodes": [
    {
      "id": "962ea1ec-8d1a-4d1a-be1d-0f6f5b7d0460",
      "name": "Weekly Drift Review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "30 7 * * 2"
            }
          ]
        }
      }
    },
    {
      "id": "cf202c02-3c1b-4a4d-8a66-d1fb3328111a",
      "name": "Get Customer Revenue",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Amount, Account.Name FROM Opportunity WHERE IsWon = true"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "104147ea-ff2e-4070-a614-4ab9ffbcbc3a",
      "name": "Get Success Plans",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "fDGFq4ClAB31Npgk",
          "cachedResultName": "Success Plans"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "8fbc5e95-be72-47b0-bc19-9d9497861d1a",
      "name": "Get Touchpoints",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        700,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "4VwFmA1iJIEW3N3N",
          "cachedResultName": "Customer Touchpoints"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "a8ccccf8-8e3b-4383-bbef-5980a858171b",
      "name": "Get Contact Changes",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "54ypfHO2NiiZLdr1",
          "cachedResultName": "Customer Contact Changes"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "6ca8b6cf-a898-43e9-b05a-bc31c05f754f",
      "name": "Get Feature Usage",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1100,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "97AquJgSBJgMbNtj",
          "cachedResultName": "Feature Usage Monthly"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "3d7b907e-ff7e-4f53-9dab-150e67073ffa",
      "name": "Prepare Account Signals",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1300,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Gather everything since each account's last success-plan review, in code. Only real Salesforce customers are reviewed,\n// and ARR comes from their Closed Won deals. Claude later reads only the notes written since the last review.\nconst runDate = $today.toFormat('yyyy-MM-dd');\nconst won = $('Get Customer Revenue').all().map(i => i.json).filter(o => o.Account && o.Account.Name);\nconst arr = {}; for (const o of won) arr[o.Account.Name] = (arr[o.Account.Name] || 0) + (Number(o.Amount) || 0);\nconst plans = $('Get Success Plans').all().map(i => i.json).filter(p => p.accountName);\nconst notes = $('Get Touchpoints').all().map(i => i.json).filter(t => t.accountName);\nconst contacts = $('Get Contact Changes').all().map(i => i.json).filter(c => c.accountName);\nconst usage = $('Get Feature Usage').all().map(i => i.json).filter(u => u.accountName);\nconst avg = a => a.length ? a.reduce((s, x) => s + x, 0) / a.length : null;\nconst accounts = [], skipped = [];\nfor (const p of plans) {\n  if (!arr[p.accountName]) { skipped.push(p.accountName); continue; }   // not a Closed Won customer in Salesforce\n  const since = notes.filter(t => t.accountName === p.accountName && t.date > p.lastReviewed).sort((a, b) => a.date.localeCompare(b.date));\n  const execChanges = contacts.filter(c => c.accountName === p.accountName && c.date > p.lastReviewed && c.seniority === 'exec');\n  // Usage of the feature area tied to the goal: last 2 months vs the 3 months before them.\n  const u = usage.filter(x => x.accountName === p.accountName && x.featureArea === p.goalFeatureArea).sort((a, b) => a.month.localeCompare(b.month)).map(x => Number(x.uses));\n  const recent = avg(u.slice(-2)), base = avg(u.slice(-5, -2));\n  const usageChange = recent != null && base ? Math.round((recent / base - 1) * 100) : null;\n  accounts.push({ accountName: p.accountName, arr: arr[p.accountName], healthScore: p.healthScore, csm: p.csm, product: p.product, goal: p.goal,\n    goalFeatureArea: p.goalFeatureArea, agreedOn: p.agreedOn, lastReviewed: p.lastReviewed, daysSinceReview: Math.round((Date.parse(runDate) - Date.parse(p.lastReviewed)) / 86400000),\n    notesSinceReview: since.map(t => ({ date: t.date, type: t.type, attendees: t.attendees, notes: t.notes })), execChanges, usageChange });\n}\nreturn [{ json: { runDate, accounts, skipped } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "af77d07b-12ca-4d17-b314-73502110d8cd",
      "name": "Priority Reader",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify($json.accounts.map(a => ({ accountName: a.accountName, originalGoal: a.goal, notesSinceLastReview: a.notesSinceReview })), null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You read a customer's account notes for Fortavault, Inc. (a fictional data protection company) and decide whether the customer's priority has moved away from the goal they bought for. For each account you get the original success-plan goal and the meeting and email notes written since the plan was last reviewed.\n\nSet priorityChanged to true only when someone at the customer says, in the notes, that what they or their leadership now care about is different from the original goal (a new mandate, a new top priority, budget pressure that changes what the tool must prove). A customer who reaffirms the goal, adds a small extra interest while keeping the goal as the priority, explains a temporary dip, or simply changes staff has not changed priority.\n\nWhen priorityChanged is true, return currentPriority (one short plain sentence), quote (the exact words from the notes that show the change, one sentence or clause, copied word for word) and date (the note's date). When false, return empty strings. Return one entry per account, using the accountName exactly as given."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "d4d0246b-c151-48b5-bf24-b06b4efaff1c",
      "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": "5db07945-e040-4c0f-a213-9c8a91b292ad",
      "name": "Priority Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n \"type\": \"object\",\n \"properties\": {\n  \"accounts\": {\n   \"type\": \"array\",\n   \"items\": {\n    \"type\": \"object\",\n    \"properties\": {\n     \"accountName\": {\n      \"type\": \"string\"\n     },\n     \"priorityChanged\": {\n      \"type\": \"boolean\"\n     },\n     \"currentPriority\": {\n      \"type\": \"string\"\n     },\n     \"quote\": {\n      \"type\": \"string\"\n     },\n     \"date\": {\n      \"type\": \"string\"\n     }\n    },\n    \"required\": [\n     \"accountName\",\n     \"priorityChanged\",\n     \"currentPriority\",\n     \"quote\",\n     \"date\"\n    ]\n   }\n  }\n },\n \"required\": [\n  \"accounts\"\n ]\n}"
      }
    },
    {
      "id": "f57aed17-62e5-4068-a47a-0f62cf7f88fa",
      "name": "Score Drift",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Score drift in code. Three independent signals since the last success-plan review:\n//   stated shift (2): the customer said their priority changed — Claude's call, kept only if its quote is word for word in a note\n//   executive change (1): an executive joined or left\n//   goal usage drop (1): use of the feature tied to the goal fell 30% or more (last 2 months vs the 3 before)\n// Flag at 2+. One signal alone is not drift: a usage dip with a known reason, or a new junior contact, stays quiet.\nconst p = $('Prepare Account Signals').first().json;\nconst out = $('Priority Reader').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 read = {}; for (const r of (out.accounts || [])) read[r.accountName] = r;\nconst money = n => '$' + Math.round(n / 1000) + 'K';\nlet unverified = 0;\nconst rows = p.accounts.map(a => {\n  const r = read[a.accountName] || {};\n  const allNotes = norm(a.notesSinceReview.map(n => n.notes).join(' '));\n  const quoteOk = r.priorityChanged && r.quote && norm(r.quote).length >= 12 && allNotes.includes(norm(r.quote));\n  if (r.priorityChanged && !quoteOk) unverified++;\n  const signals = [];\n  if (quoteOk) signals.push({ kind: 'stated shift', points: 2, text: 'Now: ' + r.currentPriority });\n  if (a.execChanges.length) signals.push({ kind: 'executive change', points: 1, text: a.execChanges.map(c => c.contactName + ', ' + c.title + ', ' + c.change + ' ' + c.date).join('; ') });\n  if (a.usageChange != null && a.usageChange <= -30) signals.push({ kind: 'goal usage drop', points: 1, text: a.goalFeatureArea.replace('_', ' ') + ' ' + a.usageChange + '%' });\n  const score = signals.reduce((s, x) => s + x.points, 0);\n  return { ...a, score, flagged: score >= 2, signals, currentPriority: quoteOk ? r.currentPriority : '', quote: quoteOk ? r.quote.trim() : '', quoteDate: quoteOk ? r.date : '' };\n});\nconst greenDrift = rows.filter(r => r.flagged && r.healthScore === 'green').sort((a, b) => b.arr - a.arr);\nconst knownRisk = rows.filter(r => r.flagged && r.healthScore !== 'green');\nconst quiet = rows.filter(r => !r.flagged);\nconst block = r => '*' + r.accountName + '* (' + money(r.arr) + ' Closed Won, health ' + r.healthScore + ', CSM ' + r.csm + ', plan last reviewed ' + r.daysSinceReview + ' days ago) · drift ' + r.score + '\\n' +\n  '      Bought for: ' + safe(r.goal) + '\\n' +\n  (r.quote ? '      Now saying (' + r.quoteDate + '): _“' + safe(r.quote) + '”_\\n' : '') +\n  r.signals.filter(s => s.kind !== 'stated shift').map(s => '      ' + (s.kind === 'executive change' ? ':bust_in_silhouette: ' : ':chart_with_downwards_trend: ') + safe(s.text)).join('\\n');\nlet text = ':compass: *Goal Drift Detector* (' + p.runDate + '): ' + rows.length + ' customer success plans checked against what has happened since their last review.\\n\\n' +\n  (greenDrift.length ? '*Green but drifting* (' + greenDrift.length + '): the score says healthy, the customer is talking about something else\\n' + greenDrift.map(block).join('\\n\\n') + '\\n\\n' : '') +\n  (knownRisk.length ? '*Already at risk, and the goal has moved too* (' + knownRisk.length + ')\\n' + knownRisk.map(block).join('\\n\\n') + '\\n\\n' : '') +\n  '*No drift* (' + quiet.length + '): ' + quiet.map(r => r.accountName + (r.signals.length ? ' _(1 signal only: ' + r.signals.map(s => s.kind).join(', ') + ')_' : '')).join(' · ') + '\\n\\n' +\n  (greenDrift.length + knownRisk.length ? '*Before the next call, re-validate the plan:* does leadership still care about the original goal? What does your sponsor need to show their boss now? If the goal moved, rewrite the success plan with them.' : '') +\n  (unverified ? '\\n_' + unverified + ' stated shift(s) not counted: quote not found in the notes._' : '') +\n  (p.skipped.length ? '\\n_Skipped (no Closed Won deal in Salesforce): ' + p.skipped.join(', ') + '._' : '');\nif (text.length > 2900) text = text.slice(0, 2850).slice(0, text.slice(0, 2850).lastIndexOf('\\n')) + '\\n_…cut to fit Slack; every account is in the Goal Drift Log._';\nconst now = $now.toISO();\nconst logs = rows.map(r => ({ runDate: p.runDate, accountName: r.accountName, healthScore: r.healthScore, driftScore: r.score, flagged: r.flagged,\n  signals: r.signals.map(s => s.kind).join(', '), originalGoal: r.goal, currentPriority: r.currentPriority, quote: r.quote, loggedAt: now }));\nreturn [{ json: { runDate: p.runDate, digestText: text, logs, flagged: rows.filter(r => r.flagged).map(r => r.accountName), scores: rows.map(r => [r.accountName, r.score]) } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "a62a9991-776b-47e6-9a12-9eedf9f7c69f",
      "name": "Post Drift Review",
      "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": "982564a1-bc5d-48e4-90cc-f8b2f8374a62",
      "name": "Split Drift Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Score Drift').first().json.logs.map(json => ({ json }));"
      }
    },
    {
      "id": "13142cf5-4f92-448a-af74-4e5d74351d77",
      "name": "Log Drift Review",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "6KqiVeFiUb8jQuCn",
          "cachedResultName": "Goal Drift Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Weekly Drift Review": {
      "main": [
        [
          {
            "node": "Get Customer Revenue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Customer Revenue": {
      "main": [
        [
          {
            "node": "Get Success Plans",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Success Plans": {
      "main": [
        [
          {
            "node": "Get Touchpoints",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Touchpoints": {
      "main": [
        [
          {
            "node": "Get Contact Changes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Contact Changes": {
      "main": [
        [
          {
            "node": "Get Feature Usage",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Feature Usage": {
      "main": [
        [
          {
            "node": "Prepare Account Signals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Account Signals": {
      "main": [
        [
          {
            "node": "Priority Reader",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Priority Reader": {
      "main": [
        [
          {
            "node": "Score Drift",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Priority Reader",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Priority Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Priority Reader",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Score Drift": {
      "main": [
        [
          {
            "node": "Post Drift Review",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Drift Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Drift Rows": {
      "main": [
        [
          {
            "node": "Log Drift Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}