{
  "name": "Single-Thread Risk Radar",
  "nodes": [
    {
      "id": "ea49d33e-9994-474a-8715-f90fe82cf1fd",
      "name": "Weekly Thread Check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "50 7 * * 1"
            }
          ]
        }
      }
    },
    {
      "id": "9bc5a087-4882-4cd3-a94a-5ac79242cbe5",
      "name": "Get Closed Won",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Amount, CloseDate, Account.Name FROM Opportunity WHERE IsWon = true"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "96746c1c-eb31-43d4-b592-1d191c209323",
      "name": "Get Contacts",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Name, Title, Account.Name FROM Contact WHERE AccountId != null"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "86fd7f5f-fc8f-446f-a809-42d82b36694c",
      "name": "Get Renewals",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        700,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "u4NacxnJMzPER3wt",
          "cachedResultName": "Customer Renewals"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "04db81d8-4b70-4d63-b17e-326dd7f395a7",
      "name": "Get Account Team",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "2kpKzQwXkV4jVof7",
          "cachedResultName": "Account Team"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "e6644695-f7db-4261-85ab-e794c71800b6",
      "name": "Get Touchpoints",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1100,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "4VwFmA1iJIEW3N3N",
          "cachedResultName": "Customer Touchpoints"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "3a7db18d-d6d3-4be2-b015-ab1f70225d8b",
      "name": "Get Contact Changes",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1300,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "54ypfHO2NiiZLdr1",
          "cachedResultName": "Customer Contact Changes"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "194f7403-612c-4fa0-9101-df9a18e8f6d9",
      "name": "Count Threads",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1500,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Count the live threads into each account renewing in the next 180 days. A thread is a named person at the customer\n// (attendee with a title) who joined a call, meeting or email in the last 90 days and has not left the company.\n// Departures come from the contact-change feed; notes from the last 180 days go to Claude for departures nobody logged.\nconst runDate = $today.toFormat('yyyy-MM-dd');\nconst days = (a, b) => Math.round((Date.parse(String(b).slice(0, 10) + 'T00:00:00Z') - Date.parse(String(a).slice(0, 10) + 'T00:00:00Z')) / 86400000);\nconst value = {};\nfor (const o of $('Get Closed Won').all().map(i => i.json).filter(o => o.Account && o.Account.Name)) value[o.Account.Name] = (value[o.Account.Name] || 0) + (Number(o.Amount) || 0);\nconst sfContacts = {};\nfor (const c of $('Get Contacts').all().map(i => i.json).filter(c => c.Account && c.Account.Name)) (sfContacts[c.Account.Name] = sfContacts[c.Account.Name] || []).push(c.Name + (c.Title ? ' (' + c.Title + ')' : ''));\nconst team = {}; for (const t of $('Get Account Team').all().map(i => i.json).filter(t => t.accountName)) team[t.accountName] = t;\nconst left = {}; for (const c of $('Get Contact Changes').all().map(i => i.json).filter(c => c.accountName && c.change === 'left' && c.date <= runDate)) left[c.accountName + '|' + c.contactName] = c;\nconst touches = $('Get Touchpoints').all().map(i => i.json).filter(t => t.accountName && t.date && t.date <= runDate);\nconst people = s => { const out = []; const re = /([^,()]+?)\\s*\\(([^)]*)\\)/g; let m; while ((m = re.exec(String(s || '')))) out.push({ name: m[1].trim(), title: m[2].trim() }); return out; };\nconst accounts = [], outside = [];\nfor (const r of $('Get Renewals').all().map(i => i.json).filter(r => r.accountName && r.renewalDate)) {\n  const d = days(runDate, r.renewalDate);\n  if (d < 0 || d > 180) { outside.push(r.accountName + ' (' + r.renewalDate + ')'); continue; }\n  const mine = touches.filter(t => t.accountName === r.accountName);\n  const seen = {};\n  for (const t of mine) for (const p of people(t.attendees)) {\n    const s = seen[p.name] = seen[p.name] || { name: p.name, title: p.title, last: '', count90: 0 };\n    if (t.date > s.last) s.last = t.date;\n    if (days(t.date, runDate) <= 90) s.count90++;\n  }\n  const all = Object.values(seen);\n  const departed = all.filter(p => left[r.accountName + '|' + p.name]).map(p => ({ name: p.name, title: p.title, leftOn: left[r.accountName + '|' + p.name].date }));\n  const active = all.filter(p => p.count90 > 0 && !left[r.accountName + '|' + p.name]).sort((a, b) => b.last.localeCompare(a.last));\n  const quiet = all.filter(p => p.count90 === 0 && !left[r.accountName + '|' + p.name]);\n  accounts.push({ accountName: r.accountName, renewalDate: r.renewalDate, daysToRenewal: d, value: value[r.accountName] || 0,\n    csm: (team[r.accountName] || {}).csm || 'unassigned', active: active.map(p => ({ name: p.name, title: p.title, last: p.last, touches90: p.count90 })),\n    departed, quiet: quiet.map(p => p.name + ' (' + p.title + ', last ' + p.last + ')'), sfContacts: sfContacts[r.accountName] || [],\n    notes: mine.filter(t => days(t.date, runDate) <= 180).sort((a, b) => a.date.localeCompare(b.date)).map(t => ({ date: t.date, attendees: t.attendees, text: t.notes })) });\n}\nconst forClaude = accounts.map(a => ({ accountName: a.accountName, activeContacts: a.active.map(p => p.name + ' (' + p.title + ')'), notes: a.notes.map(n => n.date + ': ' + n.text) }));\nreturn [{ json: { runDate, accounts, outside, forClaude } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "f122eaf0-40cf-4cff-ac27-75790bfd75cd",
      "name": "Thread Reader",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify($json.forClaude, null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You read customer success notes for Fortavault, Inc. (a fictional data protection company) to find how many people at each customer we still have a relationship with before their renewal. For each account you get its active contacts (customer people who joined a call, meeting or email in the last 90 days) and the notes from the last 180 days.\n\n1. departures: an active contact who the notes say has left, is leaving, is changing role, or is handing their responsibility for us to someone else. Return contactName exactly as it appears in activeContacts (name only, without the title) and quote: the exact words from one note that say so, copied word for word and including the person's name. Do not report someone who is only going on holiday, and do not report a departure of anyone who is not in activeContacts (a predecessor, a former employee, an unnamed person).\n\n2. suggested: people at the customer who are named in the notes but are not in activeContacts and could become a new relationship (for example someone who now signs off on spend, a deputy, a day-to-day administrator). Return name (full name as written), role (as the note describes it, short) and quote: the exact words from one note, word for word, that include the name. Never suggest Fortavault employees, people who have left, or anyone not named in a note.\n\nReturn one entry per account with accountName exactly as given; use empty lists when nothing qualifies. Never invent names or paraphrase quotes."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "0da07f97-579d-4c96-b9ad-c6604058bc83",
      "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": "4dac654d-4487-4043-bd0a-84e2a1e16f4c",
      "name": "Thread Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\"type\":\"object\",\"properties\":{\"accounts\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"accountName\":{\"type\":\"string\"},\"departures\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"contactName\":{\"type\":\"string\"},\"quote\":{\"type\":\"string\"}},\"required\":[\"contactName\",\"quote\"]}},\"suggested\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"role\":{\"type\":\"string\"},\"quote\":{\"type\":\"string\"}},\"required\":[\"name\",\"role\",\"quote\"]}}},\"required\":[\"accountName\",\"departures\",\"suggested\"]}}},\"required\":[\"accounts\"]}"
      }
    },
    {
      "id": "87b687be-dd91-4e41-9c4f-1c7785e24ddb",
      "name": "Build Radar",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Keep a departure only if its quote is word for word in the notes and names an active contact; keep a suggested\n// contact only if the quote names them and they are not already a thread. Then rank and build the radar.\nconst c = $('Count Threads').first().json;\nconst out = $('Thread 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;\nlet dropped = 0;\nconst rows = c.accounts.map(a => {\n  const r = read[a.accountName] || {}, all = norm(a.notes.map(n => n.text).join(' '));\n  const activeNames = a.active.map(p => p.name), knownNames = activeNames.concat(a.departed.map(p => p.name));\n  const namePart = (q, name) => name.replace(/^dr\\.?\\s+/i, '').split(/\\s+/).some(w => w.length > 2 && norm(q).includes(norm(w)));\n  const departures = [];\n  for (const d of (r.departures || [])) {\n    const ok = d.quote && norm(d.quote).length >= 15 && all.includes(norm(d.quote)) && activeNames.includes(d.contactName) && namePart(d.quote, d.contactName);\n    if (ok) departures.push({ name: d.contactName, quote: d.quote.trim() }); else dropped++;\n  }\n  const suggested = [];\n  for (const s of (r.suggested || [])) {\n    const ok = s.quote && all.includes(norm(s.quote)) && norm(s.quote).includes(norm(s.name)) && s.name.trim().split(/\\s+/).length >= 2 && !knownNames.includes(s.name);\n    if (ok) suggested.push({ name: s.name, role: s.role, quote: s.quote.trim() }); else dropped++;\n  }\n  const leaving = departures.map(d => d.name);\n  const threads = a.active.filter(p => !leaving.includes(p.name));\n  const tier = threads.length === 0 ? 'no thread left' : threads.length === 1 ? 'single-threaded' : 'covered';\n  return { ...a, departures, suggested, threads: threads.map(p => p.name), tier };\n});\nconst money = n => '$' + Math.round((n || 0) / 1000) + 'K';\nconst flagged = rows.filter(r => r.tier !== 'covered').sort((a, b) => (a.tier === b.tier ? a.daysToRenewal - b.daysToRenewal : a.tier === 'no thread left' ? -1 : 1));\nconst covered = rows.filter(r => r.tier === 'covered');\nconst block = a => '*' + a.accountName + '* · renews ' + a.renewalDate + ' (' + a.daysToRenewal + ' days) · ' + money(a.value) + ' Closed Won · CSM ' + a.csm + '\\n' +\n  '      Active in the last 90 days: ' + (a.active.length ? a.active.map(p => p.name + ' (' + p.title + ', ' + p.touches90 + ' touch' + (p.touches90 > 1 ? 'es' : '') + ')').join(', ') : 'nobody') +\n  (a.departed.length ? '\\n      Left the company: ' + a.departed.map(p => p.name + ' (' + p.title + ', ' + p.leftOn + ')').join(', ') : '') +\n  a.departures.map(d => '\\n      :warning: ' + d.name + ' is moving on: _“' + safe(d.quote) + '”_').join('') +\n  (a.suggested.length ? a.suggested.map(s => '\\n      Bring in *' + s.name + '*' + (s.role ? ' (' + s.role + ')' : '') + ': _“' + safe(s.quote) + '”_').join('') : '\\n      Bring in: _nobody named in the notes yet; the CSM should ask who else signs off on the renewal_');\nlet text = ':thread: *Single-Thread Risk Radar* (' + c.runDate + '): ' + rows.length + ' accounts renew in the next 180 days. A thread is a named customer contact on a call, meeting or email in the last 90 days who has not left.\\n' +\n  (flagged.length ? '\\n*At risk* (' + flagged.length + ')\\n' + flagged.map(a => '_' + a.tier + '_ ' + block(a)).join('\\n\\n') + '\\n' : '\\nNo account is single-threaded.\\n') +\n  '\\n*Covered* (' + covered.length + '): ' + covered.map(a => a.accountName + ' (' + a.threads.length + ' threads, renews ' + a.renewalDate + ')').join(' · ') +\n  (dropped ? '\\n_' + dropped + ' finding(s) from Claude dropped: quote not found in the notes or name not on the account._' : '') +\n  (c.outside.length ? '\\n_Renewing after the 180-day window: ' + c.outside.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 Thread Coverage Log._';\nconst now = $now.toISO();\nconst logs = rows.map(r => ({ runDate: c.runDate, accountName: r.accountName, renewalDate: r.renewalDate, daysToRenewal: r.daysToRenewal, arr: r.value,\n  activeContacts: r.active.map(p => p.name).join('; '), effectiveThreads: r.threads.length, tier: r.tier,\n  departures: r.departures.map(d => d.name + ': ' + d.quote).join(' | '), suggested: r.suggested.map(s => s.name + ': ' + s.quote).join(' | '), loggedAt: now }));\nreturn [{ json: { radarText: text, logs, summary: rows.map(r => [r.accountName, r.tier, r.threads, r.departures.map(d => d.name), r.suggested.map(s => s.name)]), dropped } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "73ac51e4-4a01-41cf-a9c4-185ecc0795e3",
      "name": "Post Thread Radar",
      "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.radarText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "fc91eb16-02e0-454e-8aba-5b2288696197",
      "name": "Split Log Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Build Radar').first().json.logs.map(json => ({ json }));"
      }
    },
    {
      "id": "01417806-a5a5-42bd-80e2-123f99ebf67f",
      "name": "Log Thread Coverage",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "TDNaHmXKFlnkU8Ve",
          "cachedResultName": "Thread Coverage Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Weekly Thread Check": {
      "main": [
        [
          {
            "node": "Get Closed Won",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Closed Won": {
      "main": [
        [
          {
            "node": "Get Contacts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Contacts": {
      "main": [
        [
          {
            "node": "Get Renewals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Renewals": {
      "main": [
        [
          {
            "node": "Get Account Team",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Account Team": {
      "main": [
        [
          {
            "node": "Get Touchpoints",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Touchpoints": {
      "main": [
        [
          {
            "node": "Get Contact Changes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Contact Changes": {
      "main": [
        [
          {
            "node": "Count Threads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Count Threads": {
      "main": [
        [
          {
            "node": "Thread Reader",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Thread Reader": {
      "main": [
        [
          {
            "node": "Build Radar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Thread Reader",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Thread Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Thread Reader",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Build Radar": {
      "main": [
        [
          {
            "node": "Post Thread Radar",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Log Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Log Rows": {
      "main": [
        [
          {
            "node": "Log Thread Coverage",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}