/* Madison Renewal Engine — prototype dataset.
   Fictional Madison Insurance Group renewal book: 350 policies, ~50 advisors,
   24 deep records with full conditions / evidence / timeline / artifacts / close state. */

const TODAY = new Date('2026-11-17T08:12:00-05:00');
const DAY = 864e5;
const iso = (d) => new Date(d).toISOString();
const ago = (n) => iso(+TODAY - n * DAY);
const CYCLE = {
  label: 'Cycle 2026',
  term: 'Dec 1 2026 – Nov 30 2027',
  deadlines: { submission: '2026-10-31', selection: '2026-11-30', payment: '2026-12-31' },
};
const dl = (k) => CYCLE.deadlines[k];
const daysTo = (dateStr) => Math.round((new Date(dateStr + 'T23:59:00-05:00') - TODAY) / DAY);
const pressureOf = (k) => { const d = daysTo(dl(k)); return d < 0 ? 'overdue' : d <= 14 ? 'crit' : d <= 30 ? 'tight' : 'ok'; };

/* ---------- small authoring helpers ---------- */
let evSeq = 0;
const ev = (src, label, detail, type, at) => ({ id: 'E' + ++evSeq, src, label, detail, type, at });
const tl = (at, src, title, detail, kind) => ({ at, src, title, detail: detail || '', kind: kind || '' });
const art = (o) => Object.assign({ source: 'Email', filing: 'filed', authoritative: false, version: 'v1', confidence: null }, o);

let cSeq = 0;
function cond(cat, label, item, owing, opened, o = {}) {
  const deadlineKey = o.dl || 'selection';
  const dd = o.dueIn === undefined ? daysTo(dl(deadlineKey)) : o.dueIn;
  return Object.assign({
    id: 'C' + ++cSeq, cat, label, item, owing, opened,
    age: opened, lastAttempt: o.last === undefined ? null : o.last, attempts: o.att || 0,
    dl: deadlineKey, pressure: dd < 0 ? 'overdue' : dd <= 14 ? 'crit' : dd <= 30 ? 'tight' : 'ok', daysTo: dd,
    status: o.status || 'open', next: o.next || '', lastAction: o.lastAction || '',
    evidence: o.ev || [], confidence: o.conf || 'complete', internal: !!o.internal,
    override: o.override || null, resolved: o.resolved || null,
  }, o.extra || {});
}

const B = {
  B1: 'RAQ not started', B2: 'RAQ in progress, incomplete', B3: 'Required document outstanding',
  B4: 'Affidavit or signature outstanding', B5: 'Underwriter information request outstanding',
  B6: 'Awaiting underwriting review', B7: 'Awaiting actuarial output', B8: 'Pricing with client, selection outstanding',
  B9: 'Change request with AmRisk', B10: 'NKLL owed and outstanding', B11: 'Selection returned, lock outstanding',
  B12: 'Onboarding form outstanding', B13: 'Financing signature outstanding', B14: 'Payment outstanding',
  B15: 'Dormant or closing',
};

const ADVISORS = [
  { id: 'A1', name: 'Dana Halbrook', firm: 'Halbrook Risk Partners', email: 'dana.halbrook@halbrookrisk.com', target: 43, lastTouch: ago(6), portal: 'active' },
  { id: 'A2', name: 'Marcus Ferris', firm: 'Ferris & Lowe Advisory', email: 'mferris@ferrislowe.com', target: 17, lastTouch: ago(2), portal: 'active' },
  { id: 'A3', name: 'Priya Raghunathan', firm: 'Cedar Point Benefits', email: 'priya@cedarpointbenefits.com', target: 11, lastTouch: ago(9), portal: 'active' },
  { id: 'A4', name: 'Tom Ainsworth', firm: 'Ainsworth Group', email: 'tom@ainsworthgroup.net', target: 2, lastTouch: ago(21), portal: 'active' },
  { id: 'A5', name: 'Elaine Vossberg', firm: 'Kestrel Financial', email: 'e.vossberg@kestrelfin.com', target: 6, lastTouch: ago(4), portal: 'active' },
  { id: 'A6', name: 'Ruben Sandoval', firm: 'Sandoval Wealth', email: 'ruben@sandovalwealth.com', target: 3, lastTouch: ago(13), portal: 'active' },
  { id: 'A7', name: 'Christine Boateng', firm: 'Northgate Advisory', email: 'cboateng@northgateadv.com', target: 9, lastTouch: ago(3), portal: 'active' },
  { id: 'A8', name: 'Errol Whitlock', firm: 'Whitlock & Sons', email: 'errol@whitlockandsons.com', target: 2, lastTouch: ago(412), portal: 'stale' },
  { id: 'A9', name: 'Sonya Kapoor', firm: 'Meridian Trust Advisors', email: 'skapoor@meridiantrust.com', target: 14, lastTouch: ago(5), portal: 'active' },
  { id: 'A10', name: 'Gil Petrossian', firm: 'Petrossian Benefit Group', email: 'gil@petrossianbg.com', target: 8, lastTouch: ago(16), portal: 'expired' },
];

/* ---------- deep renewals ---------- */
const DEEP = [];
const R = (o) => { DEEP.push(o); return o; };

R({
  id: 'R-2026-0147', account: 'Vance Aggregates Holdings', policy: 'POL-88214', advisor: 'A1',
  contact: { name: 'Joel Mercer', title: 'CFO', email: 'j.mercer@vanceaggregates.com' },
  stage: 'Sent to Underwriting', stageSince: ago(9), priority: 'Critical', engine: 'Draft ready',
  lastEval: ago(0.02), lastActivity: ago(3), lastTouch: ago(5), premiumPrior: 214800,
  conditions: [
    cond('B3', B.B3, '2025 P&L statement', 'Client', 14, {
      last: 5, att: 3, dl: 'submission', next: 'Targeted document reminder to advisor, client copied',
      lastAction: 'Reminder sent to advisor Nov 12',
      ev: [
        ev('salesforce', 'Supporting Documents field', 'RAQ marked complete; 2025 P&L slot empty as of last read 08:10', 'observed', ago(0.02)),
        ev('email', 'Outbound Nov 12 08:41', '"Following up on the 2025 P&L for Vance" — sent to Dana Halbrook, Joel Mercer copied', 'observed', ago(5)),
        ev('email', 'Inbound Nov 14 16:02', 'Joel Mercer: "Our controller is pulling it together this week."', 'observed', ago(3)),
        ev('engine', 'Condition held open', 'No attachment matching a 2025 P&L has been observed on any thread for this renewal', 'derived', ago(0.02)),
      ],
    }),
    cond('B5', B.B5, 'Ownership clarification — 2024 entity restructure', 'Advisor', 3, {
      last: 3, att: 1, dl: 'submission', next: 'Chase advisor with the underwriter question verbatim',
      lastAction: 'Question relayed to advisor Nov 14',
      ev: [
        ev('salesforce', 'Underwriting note Nov 14', 'K. Osei: "Need confirmation of which entity holds the Fulton pit lease after the 2024 restructure."', 'observed', ago(3)),
        ev('email', 'Outbound Nov 14 09:20', 'Question relayed to Dana Halbrook; no reply observed', 'observed', ago(3)),
      ],
    }),
    cond('B7', B.B7, 'Actuarial output for revised schedule', 'AmRisk', 6, {
      last: 6, att: 1, dl: 'selection', internal: true, next: 'Internal ageing — underwriter follow-up draft available',
      lastAction: 'Submitted to AmRisk Nov 11',
      ev: [
        ev('email', 'Outbound Nov 11 15:12', 'Schedule sent to AmRisk intake (actuarial@amrisk.example)', 'observed', ago(6)),
        ev('amrisk', 'No return observed', 'Neither delivery path has produced output; typical turnaround 4 business days', 'derived', ago(0.02)),
      ],
    }),
  ],
  resolvedConds: [cond('B2', B.B2, 'Renewal questionnaire', 'Client', 31, { status: 'resolved', resolved: { at: ago(11), by: 'Engine', how: 'RAQ submission observed in Salesforce' } })],
  rec: {
    action: 'Draft outreach', target: 'Dana Halbrook (advisor) · Joel Mercer copied', urgency: 'Today',
    why: [
      'Two client-owed conditions are open on the same renewal and the submission deadline passed 17 days ago.',
      'Last outreach was 5 days ago and the client reply on Nov 14 acknowledged the request without delivering the document.',
      'The ownership clarification has never been chased on its own — the underwriter question was relayed once and not followed up.',
      'One message covering both items avoids a second unrelated email to this advisor today.',
    ],
    approval: 'Review required', consolidate: true,
    ifNothing: 'Actuarial output cannot price a complete submission; the Nov 30 selection deadline is at risk for this account.',
  },
  timeline: [
    tl(ago(0.02), 'engine', 'Renewal evaluated', 'Three conditions open · disposition: draft'),
    tl(ago(3), 'email', 'Inbound email — Joel Mercer', '"Our controller is pulling it together this week."'),
    tl(ago(3), 'salesforce', 'Underwriting note added', 'K. Osei: ownership clarification required'),
    tl(ago(3), 'engine', 'Blocking condition opened', 'B5 · Ownership clarification — owing Advisor'),
    tl(ago(5), 'user', 'Draft approved and sent', 'A. Reyes edited recipient, then sent'),
    tl(ago(5), 'engine', 'Draft created', 'B3 document reminder · category: Document request'),
    tl(ago(6), 'amrisk', 'Sent to AmRisk', 'Revised schedule submitted for actuarial output'),
    tl(ago(9), 'salesforce', 'Stage changed', 'Submission Prep → Sent to Underwriting'),
    tl(ago(11), 'engine', 'Blocking condition resolved', 'B2 · RAQ submission observed'),
    tl(ago(14), 'engine', 'Blocking condition opened', 'B3 · 2025 P&L statement — owing Client'),
  ],
  artifacts: [
    art({ type: 'RAQ', name: 'Vance_RAQ_2026.pdf', source: 'Salesforce', at: ago(11) }),
    art({ type: 'Tax return', name: 'Vance_1120_2024.pdf', at: ago(24) }),
    art({ type: 'Financial statement', name: 'Vance_Balance_Sheet_2025Q3.xlsx', at: ago(18), confidence: 0.91 }),
  ],
});

R({
  id: 'R-2026-0212', account: 'Kilroy Structural Steel', policy: 'POL-88410', advisor: 'A2',
  contact: { name: 'Renata Kilroy', title: 'President', email: 'renata@kilroysteel.com' },
  stage: 'Pricing With Client', stageSince: ago(12), priority: 'High', engine: 'Hold — conflicting evidence',
  lastEval: ago(0.03), lastActivity: ago(3), lastTouch: ago(7), premiumPrior: 96400, conflict: true,
  conditions: [cond('B8', B.B8, 'Completed selection worksheet', 'Client', 9, {
    last: 7, att: 2, next: 'Held — inbound email may already satisfy this condition', conf: 'conflicting',
    lastAction: 'Selection nudge sent Nov 10',
    ev: [
      ev('salesforce', 'Stage', 'Pricing With Client since Nov 5 — no selection recorded', 'observed', ago(0.03)),
      ev('email', 'Inbound Nov 14 11:47', 'Renata Kilroy: "Selections attached, let me know if the layout is wrong." · 1 attachment', 'uncertain', ago(3)),
      ev('engine', 'Contradiction detected', 'Correspondence indicates a returned selection; Salesforce position does not reflect it', 'derived', ago(3)),
    ],
  })],
  rec: {
    action: 'Hold', target: 'No outreach', urgency: 'Blocked pending exception',
    why: [
      'An inbound email on Nov 14 appears to carry the selection worksheet, but the attachment could not be matched with confidence.',
      'Salesforce still shows the renewal at Pricing With Client, so the two sources disagree.',
      'Sending a selection reminder now would contradict a document the client believes they already returned.',
    ],
    approval: 'Human resolution required', exception: 'X2',
    ifNothing: 'If the attachment is the selection, the renewal is being held out of the Close Chain; if it is not, the Nov 30 deadline is unprotected.',
  },
  timeline: [
    tl(ago(0.03), 'engine', 'Renewal evaluated', 'Disposition: hold · reason: source contradiction'),
    tl(ago(3), 'engine', 'Exception opened', 'Salesforce / email contradiction — X2'),
    tl(ago(3), 'email', 'Inbound email — Renata Kilroy', '"Selections attached…" · Kilroy_Selections_FINAL.xlsx'),
    tl(ago(7), 'user', 'Draft approved and sent', 'A. Reyes sent selection nudge unchanged'),
    tl(ago(12), 'salesforce', 'Stage changed', 'Sent to Actuarial → Pricing With Client'),
  ],
  artifacts: [art({ type: 'Client Selection Worksheet', name: 'Kilroy_Selections_FINAL.xlsx', at: ago(3), filing: 'awaiting-match', confidence: 0.44 })],
});

R({
  id: 'R-2026-0189', account: 'Brightlin Foods', policy: 'POL-88301', advisor: 'A1',
  contact: { name: 'Devon Ashby', title: 'Controller', email: 'dashby@brightlinfoods.com' },
  stage: 'With Underwriting', stageSince: ago(11), priority: 'Normal', engine: 'Internal ageing',
  lastEval: ago(0.03), lastActivity: ago(11), lastTouch: ago(11), premiumPrior: 143200,
  conditions: [cond('B6', B.B6, 'Underwriting review of complete submission', 'Underwriting', 11, {
    internal: true, next: 'Internal escalation note to underwriting queue owner', att: 0,
    ev: [
      ev('salesforce', 'Stage', 'With Underwriting since Nov 6; no decision or information request recorded', 'observed', ago(0.03)),
      ev('engine', 'Submission complete', 'All required documents filed; nothing outstanding from the client', 'derived', ago(11)),
    ],
  })],
  rec: {
    action: 'Internal escalation', target: 'K. Osei (underwriting)', urgency: 'This week',
    why: ['The submission has been complete and waiting 11 days, above the 7-day internal threshold for this stage.', 'No client-owed condition exists, so no external chase is appropriate.'],
    approval: 'Review required',
    ifNothing: 'Actuarial submission slips, compressing the selection window for a renewal with no client-side problems.',
  },
  timeline: [
    tl(ago(0.03), 'engine', 'Renewal evaluated', 'Disposition: surface internally'),
    tl(ago(11), 'salesforce', 'Stage changed', 'Sent to Underwriting → With Underwriting'),
    tl(ago(13), 'engine', 'Blocking condition resolved', 'B3 · 2025 P&L observed and filed'),
  ],
  artifacts: [art({ type: 'P&L', name: 'Brightlin_PL_2025.pdf', at: ago(13) }), art({ type: 'RAQ', name: 'Brightlin_RAQ_2026.pdf', source: 'Salesforce', at: ago(26) })],
});

R({
  id: 'R-2026-0233', account: 'Palomar Dental Group', policy: 'POL-88462', advisor: 'A3',
  contact: { name: 'Hollis Trager', title: 'Practice Administrator', email: 'htrager@palomardental.com' },
  stage: 'Sent to Actuarial', stageSince: ago(8), priority: 'High', engine: 'Draft ready',
  lastEval: ago(0.03), lastActivity: ago(2), lastTouch: ago(8), premiumPrior: 61300,
  conditions: [
    cond('B10', B.B10, 'Next-of-kin liability letter (coverage addition)', 'Client', 5, {
      last: 5, att: 1, next: 'Letter request with template attached',
      ev: [
        ev('salesforce', 'Coverage addition flagged', 'Cyber liability added at renewal — NKLL rule evaluates true', 'observed', ago(5)),
        ev('engine', 'No NKLL observed', 'No matching letter on any thread for this renewal', 'derived', ago(0.03)),
      ],
    }),
    cond('B7', B.B7, 'Actuarial output', 'AmRisk', 8, { internal: true, next: 'Internal ageing', att: 1, ev: [ev('email', 'Outbound Nov 9', 'Submission delivered to AmRisk intake', 'observed', ago(8))] }),
  ],
  rec: {
    action: 'Draft outreach', target: 'Hollis Trager (client) · Priya Raghunathan copied', urgency: 'Today',
    why: ['The NKLL requirement was triggered by the cyber liability addition and has been open 5 days with one attempt.', 'The letter is a client signature item and cannot be satisfied by the advisor.'],
    approval: 'Review required',
    ifNothing: 'The letter is a release prerequisite; a late letter blocks the close sequence after selection returns.',
  },
  timeline: [
    tl(ago(0.03), 'engine', 'Renewal evaluated', 'Disposition: draft'),
    tl(ago(2), 'engine', 'Document filing failed', 'Palomar_ID_Trager.pdf matched but Salesforce Files write was rejected — X9'),
    tl(ago(5), 'engine', 'Blocking condition opened', 'B10 · NKLL owed'),
    tl(ago(8), 'salesforce', 'Stage changed', 'With Underwriting → Sent to Actuarial'),
  ],
  artifacts: [art({ type: 'ID document', name: 'Palomar_ID_Trager.pdf', at: ago(2), filing: 'failed', confidence: 0.88 }), art({ type: 'P&L', name: 'Palomar_PL_2025.xlsx', at: ago(20) })],
});

R({
  id: 'R-2026-0301', account: 'Tessellate Analytics', policy: 'POL-88520', advisor: 'A4',
  contact: { name: 'Ivo Brandt', title: 'COO', email: 'ivo@tessellate.io' },
  stage: 'RAQ In Progress', stageSince: ago(21), priority: 'High', engine: 'Draft ready · source stale',
  lastEval: ago(0.03), lastActivity: ago(9), lastTouch: ago(6), premiumPrior: 38900, staleSource: true,
  conditions: [cond('B2', B.B2, 'Questionnaire sections 4–6 incomplete', 'Client', 21, {
    last: 6, att: 3, dl: 'submission', next: 'Completion nudge naming the outstanding sections', conf: 'stale-source',
    ev: [
      ev('salesforce', 'RAQ status', 'Started Oct 27; sections 4–6 incomplete at last read', 'observed', ago(0.03)),
      ev('email', 'Observation stale', 'Advisor Services shared mailbox last observed 5h 40m ago — inbound replies since then are not visible', 'uncertain', ago(0.24)),
    ],
  })],
  rec: {
    action: 'Draft outreach', target: 'Ivo Brandt (client) · Tom Ainsworth copied', urgency: 'Today',
    why: ['Three sections have been outstanding for 21 days and the submission deadline has passed.', 'Response status is currently unverified — email observation for this mailbox group is stale, so a reply may exist that the engine cannot see.'],
    approval: 'Review required · verify no reply before sending',
    ifNothing: 'Submission cannot be built at all for this renewal; it is the oldest incomplete questionnaire in the book.',
  },
  timeline: [
    tl(ago(0.03), 'engine', 'Renewal evaluated', 'Disposition: draft · flagged stale email observation'),
    tl(ago(6), 'user', 'Draft approved and sent', 'A. Reyes sent completion nudge'),
    tl(ago(21), 'salesforce', 'Stage changed', 'RAQ Sent → RAQ In Progress'),
  ],
  artifacts: [art({ type: 'RAQ', name: 'Tessellate_RAQ_2026 (partial)', source: 'Salesforce', at: ago(21), filing: 'filed' })],
});

R({
  id: 'R-2026-0311', account: 'Yarrow Biotech', policy: 'POL-88533', advisor: 'A1',
  contact: { name: 'Simone Achterberg', title: 'CFO', email: 's.achterberg@yarrowbio.com' },
  stage: 'Renewal Created', stageSince: ago(26), priority: 'Critical', engine: 'Escalated',
  lastEval: ago(0.03), lastActivity: ago(26), lastTouch: ago(4), premiumPrior: 74500, escalated: true,
  conditions: [cond('B1', B.B1, 'Questionnaire not started', 'Client', 26, {
    last: 4, att: 4, dl: 'submission', next: 'Advisor escalation — fourth attempt unanswered',
    ev: [ev('salesforce', 'RAQ status', 'No RAQ activity recorded since renewal creation Oct 22', 'observed', ago(0.03)), ev('email', 'Four outbound attempts', 'Oct 27, Nov 3, Nov 9, Nov 13 — no inbound reply observed', 'observed', ago(4))],
  })],
  rec: {
    action: 'Internal escalation', target: 'Dana Halbrook (advisor) · escalation rung 4 of 5', urgency: 'Today',
    why: ['Four attempts across 26 days have produced no observed response from either client or advisor.', 'Submission is already overdue and selection is 13 days away.', 'The next rung is a routing recommendation, which requires a person to decide.'],
    approval: 'Review required',
    ifNothing: 'The renewal reaches the dormant threshold in 8 days and will require concierge routing.',
  },
  timeline: [
    tl(ago(0.03), 'engine', 'Renewal evaluated', 'Escalation rung raised to Advisor consolidation'),
    tl(ago(4), 'user', 'Draft approved and sent', 'A. Reyes · fourth attempt'),
    tl(ago(26), 'salesforce', 'Renewal created', 'Cycle 2026 renewal opened'),
  ],
  artifacts: [],
});

R({
  id: 'R-2026-0166', account: 'Northbay Marine Services', policy: 'POL-88266', advisor: 'A5',
  contact: { name: 'Karsten Bly', title: 'Owner', email: 'karsten@northbaymarine.com' },
  stage: 'Selection Received', stageSince: ago(4), priority: 'Normal', engine: 'Close Chain · awaiting lock',
  lastEval: ago(0.03), lastActivity: ago(4), lastTouch: ago(4), premiumPrior: 52700,
  conditions: [cond('B11', B.B11, 'AmRisk locked selection PDF', 'AmRisk', 4, {
    internal: true, att: 1, next: 'Internal follow-up to AmRisk on day 5',
    ev: [ev('email', 'Inbound Nov 13', 'Client Selection Worksheet received and matched (0.97)', 'observed', ago(4)), ev('amrisk', 'Lock not observed', 'No authoritative locked selection PDF received', 'derived', ago(0.03))],
  })],
  rec: { action: 'Await external response', target: 'AmRisk', urgency: 'Monitor', why: ['The lock is 4 days out, inside the normal 5-day AmRisk turnaround.', 'No client-side action is available or useful.'], approval: 'No action required', ifNothing: 'Verification cannot begin until the authoritative lock arrives.' },
  timeline: [tl(ago(4), 'email', 'Selection worksheet received', 'Northbay_Selection_2026.xlsx · matched to renewal'), tl(ago(4), 'engine', 'Close Chain state', 'SELECTION_RECEIVED → LOCK_PENDING'), tl(ago(4), 'engine', 'Blocking condition resolved', 'B8 · selection returned')],
  artifacts: [art({ type: 'Client Selection Worksheet', name: 'Northbay_Selection_2026.xlsx', at: ago(4), confidence: 0.97 })],
  close: {
    state: 'LOCK_PENDING', worksheet: { name: 'Northbay_Selection_2026.xlsx', at: ago(4), version: 'v1', parse: 'ok' }, lock: null,
    rows: [], billing: { funding: 'Unknown', expected: null, invoice: 'Not ready', financing: 'Not applicable', qb: 'Manual external entry' },
    receipt: null, gates: { grid: 'pending', policy: 'unverified', billing: 'pending', receipt: 'pending', exceptions: 'clear' },
  },
});

R({
  id: 'R-2026-0178', account: 'Quinault Timber Co.', policy: 'POL-88288', advisor: 'A9',
  contact: { name: 'Marta Quinault', title: 'CEO', email: 'marta@quinaulttimber.com' },
  stage: 'Selection Received', stageSince: ago(6), priority: 'High', engine: 'Close Chain · verification failed',
  lastEval: ago(0.03), lastActivity: ago(2), lastTouch: ago(6), premiumPrior: 118900, exception: true,
  conditions: [],
  rec: { action: 'Review exception', target: 'Coverage approver', urgency: 'Today', why: ['Verification against the AmRisk lock produced one unmapped coverage and one premium mismatch.', 'A grid cannot stage until both are resolved.'], approval: 'Coverage approver required', exception: 'X3', ifNothing: 'The renewal cannot enter grid approval and will hold up the close sequence.' },
  timeline: [
    tl(ago(2), 'engine', 'Selection verification failed', '1 unknown coverage mapping · 1 premium mismatch'),
    tl(ago(2), 'amrisk', 'Locked selection PDF received', 'Quinault_AmRisk_Lock_2026.pdf · matched to renewal'),
    tl(ago(6), 'email', 'Selection worksheet received', 'Quinault_Selection.xlsx'),
  ],
  artifacts: [
    art({ type: 'Client Selection Worksheet', name: 'Quinault_Selection.xlsx', at: ago(6), confidence: 0.82 }),
    art({ type: 'AmRisk Locked Selection PDF', name: 'Quinault_AmRisk_Lock_2026.pdf', source: 'AmRisk', at: ago(2), authoritative: true, confidence: 0.99 }),
  ],
  close: {
    state: 'SELECTION_VERIFYING',
    worksheet: { name: 'Quinault_Selection.xlsx', at: ago(6), version: 'v1', parse: 'ok' },
    lock: { name: 'Quinault_AmRisk_Lock_2026.pdf', at: ago(2), version: 'v1', parse: 'ok' },
    rows: [
      { id: 'q1', coverage: 'General liability', code: '1310', limit: '$2,000,000', prem: 38400, term: '12 mo', ws: 38400, lk: 38400, st: 'exact', loc: 'Sheet1!C12' },
      { id: 'q2', coverage: 'Commercial property', code: '1520', limit: '$8,500,000', prem: 44120, term: '12 mo', ws: 44120, lk: 44120, st: 'exact', loc: 'Sheet1!C13' },
      { id: 'q3', coverage: 'Inland marine — logging equipment', code: '1744', limit: '$1,250,000', prem: 12660, term: '12 mo', ws: 12660, lk: 12660, st: 'exact', loc: 'Sheet1!C14' },
      { id: 'q4', coverage: 'Equipment breakdown — contingent', code: null, limit: '$500,000', prem: 6180, term: '12 mo', ws: 6180, lk: 6180, st: 'map', loc: 'Sheet1!C15', note: 'Label not present in the coverage mapping registry' },
      { id: 'q5', coverage: 'Excess liability', code: '1390', limit: '$5,000,000', prem: 41880, term: '12 mo', ws: 41880, lk: 41180, st: 'mismatch', loc: 'Sheet1!C16', note: 'Worksheet total reflects a pre-revision quote' },
      { id: 'q6', coverage: 'Employment practices liability', code: '1622', limit: '$1,000,000', prem: 9740, term: '12 mo', ws: 9740, lk: 9740, st: 'exact', loc: 'Sheet1!C17' },
    ],
    billing: { funding: 'Pay in full', expected: null, invoice: 'Not ready', financing: 'Not applicable', qb: 'Manual external entry' },
    receipt: null, gates: { grid: 'pending', policy: 'exists', billing: 'pending', receipt: 'pending', exceptions: 'blocking' },
  },
});

R({
  id: 'R-2026-0158', account: 'Harlow & Reese LLP', policy: 'POL-88240', advisor: 'A7',
  contact: { name: 'Beatriz Reese', title: 'Managing Partner', email: 'breese@harlowreese.com' },
  stage: 'Selection Received', stageSince: ago(7), priority: 'High', engine: 'Close Chain · grid staged',
  lastEval: ago(0.03), lastActivity: ago(1), lastTouch: ago(7), premiumPrior: 121300,
  conditions: [],
  rec: { action: 'Review exception', target: 'Coverage approver', urgency: 'Today', why: ['Worksheet and AmRisk lock reconcile exactly across 7 coverages and $128,450 of premium.', 'A staged shadow grid is waiting for approval; approval records a comparison only.'], approval: 'Coverage approver required', ifNothing: 'Shadow evidence for this renewal is incomplete for the 2027 cutover comparison.' },
  timeline: [
    tl(ago(1), 'engine', 'Coverage grid staged', '7 rows · exact match against locked selection'),
    tl(ago(1), 'engine', 'Selection verified', 'All required values reconcile'),
    tl(ago(2), 'amrisk', 'Locked selection PDF received', 'HarlowReese_AmRisk_Lock.pdf'),
    tl(ago(7), 'email', 'Selection worksheet received', 'HarlowReese_Selection_2026.xlsx'),
  ],
  artifacts: [
    art({ type: 'Client Selection Worksheet', name: 'HarlowReese_Selection_2026.xlsx', at: ago(7), confidence: 0.96 }),
    art({ type: 'AmRisk Locked Selection PDF', name: 'HarlowReese_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(2), authoritative: true }),
  ],
  close: {
    state: 'GRID_STAGED',
    worksheet: { name: 'HarlowReese_Selection_2026.xlsx', at: ago(7), version: 'v1', parse: 'ok' },
    lock: { name: 'HarlowReese_AmRisk_Lock.pdf', at: ago(2), version: 'v1', parse: 'ok' },
    rows: [
      { id: 'h1', coverage: 'Professional liability', code: '1418', limit: '$5,000,000', prem: 52300, term: '12 mo', ws: 52300, lk: 52300, st: 'exact', loc: 'Selections!D9' },
      { id: 'h2', coverage: 'General liability', code: '1310', limit: '$2,000,000', prem: 18900, term: '12 mo', ws: 18900, lk: 18900, st: 'exact', loc: 'Selections!D10' },
      { id: 'h3', coverage: 'Commercial property', code: '1520', limit: '$3,200,000', prem: 21450, term: '12 mo', ws: 21450, lk: 21450, st: 'exact', loc: 'Selections!D11' },
      { id: 'h4', coverage: 'Cyber liability', code: '1836', limit: '$2,000,000', prem: 14600, term: '12 mo', ws: 14600, lk: 14600, st: 'exact', loc: 'Selections!D12' },
      { id: 'h5', coverage: 'Employment practices liability', code: '1622', limit: '$1,000,000', prem: 9800, term: '12 mo', ws: 9800, lk: 9800, st: 'exact', loc: 'Selections!D13' },
      { id: 'h6', coverage: 'Fiduciary liability', code: '1640', limit: '$1,000,000', prem: 6200, term: '12 mo', ws: 6200, lk: 6200, st: 'exact', loc: 'Selections!D14' },
      { id: 'h7', coverage: 'Crime', code: '1712', limit: '$500,000', prem: 5200, term: '12 mo', ws: 5200, lk: 5200, st: 'exact', loc: 'Selections!D15' },
    ],
    billing: { funding: 'Pay in full', expected: 128450, invoice: 'Not ready', financing: 'Not applicable', qb: 'Manual external entry' },
    receipt: null, gates: { grid: 'pending', policy: 'exists', billing: 'pending', receipt: 'pending', exceptions: 'clear' },
  },
});

R({
  id: 'R-2026-0143', account: 'Sunbelt Poultry', policy: 'POL-88208', advisor: 'A1',
  contact: { name: 'Curtis Vandermeer', title: 'CFO', email: 'cvandermeer@sunbeltpoultry.com' },
  stage: 'Invoiced', stageSince: ago(11), priority: 'High', engine: 'Close Chain · receipt ambiguous',
  lastEval: ago(0.03), lastActivity: ago(1), lastTouch: ago(6), premiumPrior: 92300, exception: true,
  conditions: [cond('B14', B.B14, 'Premium payment $92,300', 'Client', 6, {
    last: 6, att: 1, dl: 'payment', next: 'Payment reminder — hold pending receipt match',
    ev: [ev('salesforce', 'Invoice observed', 'Invoice INV-4471 recorded manually Nov 6', 'observed', ago(11)), ev('accounting', 'Receipt not confirmed', 'A wire arrived Nov 16 that may or may not belong to this renewal', 'uncertain', ago(1))],
  })],
  rec: { action: 'Review exception', target: 'Accounting', urgency: 'Today', why: ['A $92,300 wire from "SBP Holdings LLC" matches the expected amount on two renewals in the book.', 'Automatic confirmation is blocked; a person must choose the renewal.', 'A payment reminder is held until the receipt question resolves.'], approval: 'Accounting required', exception: 'X6', ifNothing: 'Either the renewal is chased for money it has already paid, or a paid renewal stays blocked at the release gate.' },
  timeline: [
    tl(ago(1), 'accounting', 'Receipt observed', '$92,300 wire · remitter "SBP Holdings LLC" · ambiguous match'),
    tl(ago(6), 'user', 'Draft approved and sent', 'A. Reyes sent payment reminder'),
    tl(ago(11), 'salesforce', 'Invoice recorded', 'INV-4471 · $92,300 · entered manually'),
    tl(ago(14), 'engine', 'Coverage grid approved (shadow)', 'Approved by M. Duclos · comparison recorded'),
  ],
  artifacts: [
    art({ type: 'AmRisk Locked Selection PDF', name: 'Sunbelt_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(17), authoritative: true }),
    art({ type: 'Invoice', name: 'INV-4471.pdf', source: 'Salesforce', at: ago(11) }),
    art({ type: 'Onboarding form', name: 'Sunbelt_Onboarding_2026.pdf', at: ago(15) }),
  ],
  close: {
    state: 'PAYMENT_PENDING',
    worksheet: { name: 'Sunbelt_Selection.xlsx', at: ago(21), version: 'v1', parse: 'ok' },
    lock: { name: 'Sunbelt_AmRisk_Lock.pdf', at: ago(17), version: 'v1', parse: 'ok' },
    rows: [
      { id: 's1', coverage: 'General liability', code: '1310', limit: '$2,000,000', prem: 31200, term: '12 mo', ws: 31200, lk: 31200, st: 'exact' },
      { id: 's2', coverage: 'Commercial property', code: '1520', limit: '$6,000,000', prem: 38700, term: '12 mo', ws: 38700, lk: 38700, st: 'exact' },
      { id: 's3', coverage: 'Product recall', code: '1780', limit: '$1,000,000', prem: 14200, term: '12 mo', ws: 14200, lk: 14200, st: 'exact' },
      { id: 's4', coverage: 'Auto liability', code: '1350', limit: '$1,000,000', prem: 8200, term: '12 mo', ws: 8200, lk: 8200, st: 'exact' },
    ],
    approved: { by: 'M. Duclos', at: ago(14), version: 'grid v1' },
    billing: { funding: 'Pay in full', expected: 92300, invoice: 'Observed', invoiceRef: 'INV-4471', financing: 'Not applicable', qb: 'Manual external entry', branch: 'invoice-first' },
    receipt: {
      expected: 92300, observed: 92300, remitter: 'SBP Holdings LLC', at: ago(1), ref: 'WIRE-77120', match: 'ambiguous',
      candidates: [{ id: 'R-2026-0143', why: 'Expected amount exact · account name similarity 0.71 · invoice open' }, { id: 'R-2026-0257', why: 'Expected amount exact · shared remitter on 2025 payment' }],
    },
    gates: { grid: 'approved', policy: 'exists', billing: 'valid', receipt: 'pending', exceptions: 'blocking' },
  },
});

R({
  id: 'R-2026-0139', account: 'Fairmount Metal Finishing', policy: 'POL-88201', advisor: 'A2',
  contact: { name: 'Alma Fairmount', title: 'President', email: 'alma@fairmountmetal.com' },
  stage: 'Invoiced', stageSince: ago(13), priority: 'Normal', engine: 'Close Chain · release eligible',
  lastEval: ago(0.03), lastActivity: ago(2), lastTouch: ago(9), premiumPrior: 67800,
  conditions: [],
  resolvedConds: [cond('B14', B.B14, 'Premium payment $67,800', 'Client', 9, { status: 'resolved', dl: 'payment', resolved: { at: ago(2), by: 'L. Okonjo (accounting)', how: 'Receipt confirmed — check 20114' } })],
  rec: { action: 'No action required', target: '—', urgency: 'Monitor', why: ['All five release gates are satisfied and the renewal would be eligible to proceed at cutover.', 'Phase One records eligibility only; no policy action is taken.'], approval: 'None', ifNothing: 'Nothing — this renewal is complete for the shadow cycle.' },
  timeline: [
    tl(ago(2), 'engine', 'Release gate opened (shadow)', 'All gates satisfied · no production action taken'),
    tl(ago(2), 'accounting', 'Receipt confirmed', '$67,800 · check 20114 · L. Okonjo'),
    tl(ago(9), 'salesforce', 'Invoice recorded', 'INV-4462 · $67,800'),
    tl(ago(13), 'engine', 'Coverage grid approved (shadow)', 'Approved by M. Duclos'),
  ],
  artifacts: [art({ type: 'AmRisk Locked Selection PDF', name: 'Fairmount_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(19), authoritative: true }), art({ type: 'Receipt confirmation', name: 'Receipt_20114', source: 'Accounting', at: ago(2) })],
  close: {
    state: 'RELEASE_ELIGIBLE',
    worksheet: { name: 'Fairmount_Selection.xlsx', at: ago(23), version: 'v1', parse: 'ok' },
    lock: { name: 'Fairmount_AmRisk_Lock.pdf', at: ago(19), version: 'v1', parse: 'ok' },
    rows: [
      { id: 'f1', coverage: 'General liability', code: '1310', limit: '$1,000,000', prem: 22400, term: '12 mo', ws: 22400, lk: 22400, st: 'exact' },
      { id: 'f2', coverage: 'Commercial property', code: '1520', limit: '$2,400,000', prem: 26100, term: '12 mo', ws: 26100, lk: 26100, st: 'exact' },
      { id: 'f3', coverage: 'Pollution liability', code: '1690', limit: '$1,000,000', prem: 19300, term: '12 mo', ws: 19300, lk: 19300, st: 'exact' },
    ],
    approved: { by: 'M. Duclos', at: ago(13), version: 'grid v1' },
    billing: { funding: 'Pay in full', expected: 67800, invoice: 'Observed', invoiceRef: 'INV-4462', financing: 'Not applicable', qb: 'Manual external entry', branch: 'invoice-first' },
    receipt: { expected: 67800, observed: 67800, remitter: 'Fairmount Metal Finishing Inc', at: ago(2), ref: 'CHK-20114', match: 'confirmed', by: 'L. Okonjo', confirmedAt: ago(2) },
    gates: { grid: 'approved', policy: 'exists', billing: 'valid', receipt: 'confirmed', exceptions: 'clear' },
    recon: { coverageMatch: 'exact', premiumEngine: 67800, premiumManual: 67800, engineReadyAt: ago(13), manualDoneAt: ago(11), gateEngine: 'Release eligible', gateManual: 'Awaiting policy issue', discrepancies: [] },
  },
});

R({
  id: 'R-2026-0151', account: 'Cobalt Ridge Mining', policy: 'POL-88228', advisor: 'A9',
  contact: { name: 'Whit Damaris', title: 'VP Finance', email: 'wdamaris@cobaltridge.com' },
  stage: 'COI Sent', stageSince: ago(5), priority: 'High', engine: 'Close Chain · financing pending',
  lastEval: ago(0.03), lastActivity: ago(3), lastTouch: ago(3), premiumPrior: 184600,
  conditions: [cond('B13', B.B13, 'Installment agreement and DEB form signatures', 'Client', 7, {
    last: 3, att: 2, dl: 'payment', next: 'Signature nudge with DocuSign link',
    ev: [ev('salesforce', 'Funding choice', 'Onboarding form returned Nov 6 selecting financing', 'observed', ago(11)), ev('email', 'DocuSign envelope', 'Sent Nov 10; installment agreement signed, DEB form outstanding', 'observed', ago(7))],
  })],
  rec: { action: 'Draft outreach', target: 'Whit Damaris (client) · Sonya Kapoor copied', urgency: 'This week', why: ['One of two financing documents remains unsigned 7 days after the envelope was issued.', 'The billing state cannot complete and the release gate stays blocked until both signatures land.'], approval: 'Review required', ifNothing: 'Financing cannot be set up before the Dec 31 payment deadline.' },
  timeline: [
    tl(ago(3), 'engine', 'Financing documents observed', 'Installment agreement signed · DEB form pending'),
    tl(ago(5), 'salesforce', 'Stage changed', 'Invoiced → COI Sent · process definition pending'),
    tl(ago(9), 'engine', 'Coverage grid approved (shadow)', 'Approved by M. Duclos'),
    tl(ago(11), 'email', 'Onboarding form received', 'Financing selected'),
  ],
  artifacts: [
    art({ type: 'AmRisk Locked Selection PDF', name: 'CobaltRidge_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(14), authoritative: true }),
    art({ type: 'Installment agreement', name: 'CobaltRidge_Installment.pdf', at: ago(3) }),
    art({ type: 'DEB form', name: 'CobaltRidge_DEB (unsigned)', at: ago(7), filing: 'awaiting-match' }),
  ],
  close: {
    state: 'BILLING_STATE_READY',
    worksheet: { name: 'CobaltRidge_Selection.xlsx', at: ago(18), version: 'v1', parse: 'ok' },
    lock: { name: 'CobaltRidge_AmRisk_Lock.pdf', at: ago(14), version: 'v1', parse: 'ok' },
    rows: [
      { id: 'c1', coverage: 'General liability', code: '1310', limit: '$5,000,000', prem: 61200, term: '12 mo', ws: 61200, lk: 61200, st: 'exact' },
      { id: 'c2', coverage: 'Commercial property', code: '1520', limit: '$18,000,000', prem: 78400, term: '12 mo', ws: 78400, lk: 78400, st: 'exact' },
      { id: 'c3', coverage: 'Inland marine — mining equipment', code: '1744', limit: '$4,000,000', prem: 31100, term: '12 mo', ws: 31100, lk: 31100, st: 'exact' },
      { id: 'c4', coverage: 'Pollution liability', code: '1690', limit: '$2,000,000', prem: 13900, term: '12 mo', ws: 13900, lk: 13900, st: 'exact' },
    ],
    approved: { by: 'M. Duclos', at: ago(9), version: 'grid v1' },
    billing: { funding: 'Financing', expected: 184600, invoice: 'Staged', financing: 'Signature pending', financingDetail: 'Installment agreement signed Nov 14 · DEB form outstanding', qb: 'Manual external entry', branch: 'unresolved' },
    receipt: null,
    gates: { grid: 'approved', policy: 'expected-later', billing: 'pending', receipt: 'pending', exceptions: 'clear' },
    coi: { entered: ago(5), artifact: null, owner: 'Unknown', status: 'Process definition pending' },
  },
});

R({
  id: 'R-2026-0205', account: 'Delacroix Vineyards', policy: 'POL-88388', advisor: 'A6',
  contact: { name: 'Perrine Delacroix', title: 'Owner', email: 'perrine@delacroixvineyards.com' },
  stage: 'Invoiced', stageSince: ago(8), priority: 'Normal', engine: 'Close Chain · shadow discrepancy',
  lastEval: ago(0.03), lastActivity: ago(4), lastTouch: ago(12), premiumPrior: 58900, exception: true,
  conditions: [],
  rec: { action: 'Review exception', target: 'Coverage approver', urgency: 'This week', why: ['The engine grid and the manually entered Salesforce coverage disagree on one risk code and one premium.', 'Classifying the cause builds the evidence base for the 2027 cutover decision.'], approval: 'Coverage approver required', exception: 'X10', ifNothing: 'A manual-entry error stays uncorrected in the system of record and the cycle comparison is incomplete.' },
  timeline: [
    tl(ago(4), 'engine', 'Shadow discrepancy detected', '2 differences against manual Salesforce coverage'),
    tl(ago(8), 'salesforce', 'Coverage entered manually', '4 coverage records created by S. Whitfield'),
    tl(ago(9), 'engine', 'Coverage grid approved (shadow)', 'Approved by M. Duclos'),
  ],
  artifacts: [art({ type: 'AmRisk Locked Selection PDF', name: 'Delacroix_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(13), authoritative: true })],
  close: {
    state: 'PAYMENT_PENDING',
    worksheet: { name: 'Delacroix_Selection.xlsx', at: ago(16), version: 'v1', parse: 'ok' },
    lock: { name: 'Delacroix_AmRisk_Lock.pdf', at: ago(13), version: 'v1', parse: 'ok' },
    rows: [
      { id: 'd1', coverage: 'General liability', code: '1310', limit: '$2,000,000', prem: 19800, term: '12 mo', ws: 19800, lk: 19800, st: 'exact' },
      { id: 'd2', coverage: 'Commercial property', code: '1520', limit: '$4,100,000', prem: 24400, term: '12 mo', ws: 24400, lk: 24400, st: 'exact' },
      { id: 'd3', coverage: 'Crop / agricultural', code: '1442', limit: '$1,500,000', prem: 11300, term: '12 mo', ws: 11300, lk: 11300, st: 'exact' },
      { id: 'd4', coverage: 'Liquor liability', code: '1366', limit: '$1,000,000', prem: 3400, term: '12 mo', ws: 3400, lk: 3400, st: 'exact' },
    ],
    approved: { by: 'M. Duclos', at: ago(9), version: 'grid v1' },
    billing: { funding: 'Pay in full', expected: 58900, invoice: 'Observed', invoiceRef: 'INV-4468', financing: 'Not applicable', qb: 'Manual external entry', branch: 'invoice-first' },
    receipt: null,
    gates: { grid: 'approved', policy: 'exists', billing: 'valid', receipt: 'pending', exceptions: 'blocking' },
    recon: {
      coverageMatch: 'discrepancy', premiumEngine: 58900, premiumManual: 59900, engineReadyAt: ago(11), manualDoneAt: ago(8),
      gateEngine: 'Blocked — receipt pending', gateManual: 'Awaiting payment',
      discrepancies: [
        { id: 'd-1', field: 'Risk code · Crop / agricultural', engine: '1442', manual: '1424', cls: null, note: 'Transposed digits in manual entry' },
        { id: 'd-2', field: 'Premium · Commercial property', engine: '$24,400', manual: '$25,400', cls: null, note: 'Manual figure does not appear in either source artifact' },
      ],
    },
  },
});

R({
  id: 'R-2026-0163', account: 'Pinnacle Orthopedics', policy: 'POL-88251', advisor: 'A3',
  contact: { name: 'Dr. Ingrid Salas', title: 'Managing Partner', email: 'isalas@pinnacleortho.com' },
  stage: 'Selection Received', stageSince: ago(9), priority: 'Normal', engine: 'Close Chain · grid restaged',
  lastEval: ago(0.03), lastActivity: ago(2), lastTouch: ago(9), premiumPrior: 88200,
  conditions: [],
  rec: { action: 'Review exception', target: 'Coverage approver', urgency: 'This week', why: ['The first staged grid was rejected for a wrong coverage mapping and has been restaged with the corrected registry entry.', 'Two locked PDFs exist for this renewal; the later version is treated as authoritative and the duplicate is flagged.'], approval: 'Coverage approver required', exception: 'X13', ifNothing: 'Approval evidence for this renewal remains incomplete.' },
  timeline: [
    tl(ago(2), 'engine', 'Coverage grid staged', 'v2 · 5 rows · mapping corrected'),
    tl(ago(3), 'user', 'Coverage grid rejected', 'M. Duclos · reason: wrong coverage mapping'),
    tl(ago(4), 'engine', 'Duplicate source artifact', 'Second locked PDF received — X13'),
  ],
  artifacts: [
    art({ type: 'AmRisk Locked Selection PDF', name: 'Pinnacle_AmRisk_Lock_v2.pdf', source: 'AmRisk', at: ago(4), authoritative: true, version: 'v2' }),
    art({ type: 'AmRisk Locked Selection PDF', name: 'Pinnacle_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(8), authoritative: false, version: 'v1', filing: 'conflict' }),
  ],
  close: {
    state: 'GRID_STAGED',
    worksheet: { name: 'Pinnacle_Selection.xlsx', at: ago(9), version: 'v1', parse: 'ok' },
    lock: { name: 'Pinnacle_AmRisk_Lock_v2.pdf', at: ago(4), version: 'v2', parse: 'ok' },
    rows: [
      { id: 'p1', coverage: 'Medical professional liability', code: '1424', limit: '$3,000,000', prem: 49800, term: '12 mo', ws: 49800, lk: 49800, st: 'exact' },
      { id: 'p2', coverage: 'General liability', code: '1310', limit: '$1,000,000', prem: 14200, term: '12 mo', ws: 14200, lk: 14200, st: 'exact' },
      { id: 'p3', coverage: 'Commercial property', code: '1520', limit: '$2,000,000', prem: 12900, term: '12 mo', ws: 12900, lk: 12900, st: 'exact' },
      { id: 'p4', coverage: 'Cyber liability', code: '1836', limit: '$1,000,000', prem: 7900, term: '12 mo', ws: 7900, lk: 7900, st: 'exact' },
      { id: 'p5', coverage: 'Employment practices liability', code: '1622', limit: '$1,000,000', prem: 3400, term: '12 mo', ws: 3400, lk: 3400, st: 'exact' },
    ],
    rejections: [{ by: 'M. Duclos', at: ago(3), reason: 'Wrong coverage mapping', detail: 'Medical professional liability had mapped to 1418 (professional liability)' }],
    billing: { funding: 'Unknown', expected: 88200, invoice: 'Not ready', financing: 'Not applicable', qb: 'Manual external entry' },
    receipt: null, gates: { grid: 'pending', policy: 'exists', billing: 'pending', receipt: 'pending', exceptions: 'warn' },
  },
});

R({
  id: 'R-2026-0175', account: 'Cordova Cold Storage', policy: 'POL-88279', advisor: 'A5',
  contact: { name: 'Yusuf Cordova', title: 'Owner', email: 'yusuf@cordovacold.com' },
  stage: 'Selection Received', stageSince: ago(3), priority: 'High', engine: 'Close Chain · parse failed',
  lastEval: ago(0.03), lastActivity: ago(3), lastTouch: ago(3), premiumPrior: 76400, exception: true,
  conditions: [],
  rec: { action: 'Review exception', target: 'Coverage approver', urgency: 'Today', why: ['The returned worksheet uses a layout the parser does not support, so no coverage lines could be extracted.', 'No partial grid is staged — a partial parse never becomes a partial grid.'], approval: 'Coverage approver required', exception: 'X5', ifNothing: 'The renewal sits outside the close sequence with a returned selection nobody has read.' },
  timeline: [tl(ago(3), 'engine', 'Worksheet parse failed', 'Unsupported layout — no rows extracted'), tl(ago(3), 'email', 'Selection worksheet received', 'Cordova_2026_selections_v3.xlsx')],
  artifacts: [art({ type: 'Client Selection Worksheet', name: 'Cordova_2026_selections_v3.xlsx', at: ago(3), filing: 'unsupported', confidence: 0.31 })],
  close: {
    state: 'SELECTION_VERIFYING',
    worksheet: { name: 'Cordova_2026_selections_v3.xlsx', at: ago(3), version: 'v3', parse: 'failed' }, lock: null, rows: [],
    billing: { funding: 'Unknown', expected: null, invoice: 'Not ready', financing: 'Not applicable', qb: 'Manual external entry' },
    receipt: null, gates: { grid: 'pending', policy: 'unverified', billing: 'pending', receipt: 'pending', exceptions: 'blocking' },
  },
});

R({
  id: 'R-2026-0222', account: 'Ashfield Plastics', policy: 'POL-88425', advisor: 'A7',
  contact: { name: 'Nora Ashfield', title: 'CFO', email: 'nora@ashfieldplastics.com' },
  stage: 'Selection Received', stageSince: ago(10), priority: 'Normal', engine: 'Draft ready',
  lastEval: ago(0.03), lastActivity: ago(5), lastTouch: ago(5), premiumPrior: 44100,
  conditions: [cond('B12', B.B12, 'Renewal onboarding form', 'Client', 8, {
    last: 5, att: 2, dl: 'payment', next: 'Return nudge — funding choice cannot be determined without it',
    ev: [ev('email', 'Outbound Nov 9', 'Onboarding form issued after selection', 'observed', ago(8)), ev('engine', 'No return observed', 'Funding choice unknown; billing path cannot be staged', 'derived', ago(0.03))],
  })],
  rec: { action: 'Draft outreach', target: 'Nora Ashfield (client) · Christine Boateng copied', urgency: 'This week', why: ['The onboarding form carries the funding choice, and without it the billing state cannot be staged.', 'Two attempts in 8 days; the grid is already approved and waiting.'], approval: 'Review required', ifNothing: 'Billing cannot be prepared under either invoice sequence.' },
  timeline: [tl(ago(5), 'user', 'Draft approved and sent', 'A. Reyes · onboarding reminder'), tl(ago(6), 'engine', 'Coverage grid approved (shadow)', 'Approved by M. Duclos')],
  artifacts: [art({ type: 'AmRisk Locked Selection PDF', name: 'Ashfield_AmRisk_Lock.pdf', source: 'AmRisk', at: ago(12), authoritative: true })],
  close: {
    state: 'GRID_APPROVED',
    worksheet: { name: 'Ashfield_Selection.xlsx', at: ago(14), version: 'v1', parse: 'ok' },
    lock: { name: 'Ashfield_AmRisk_Lock.pdf', at: ago(12), version: 'v1', parse: 'ok' },
    rows: [
      { id: 'a1', coverage: 'General liability', code: '1310', limit: '$1,000,000', prem: 17600, term: '12 mo', ws: 17600, lk: 17600, st: 'exact' },
      { id: 'a2', coverage: 'Commercial property', code: '1520', limit: '$3,000,000', prem: 21300, term: '12 mo', ws: 21300, lk: 21300, st: 'exact' },
      { id: 'a3', coverage: 'Equipment breakdown', code: '1748', limit: '$750,000', prem: 5200, term: '12 mo', ws: 5200, lk: 5200, st: 'exact' },
    ],
    approved: { by: 'M. Duclos', at: ago(6), version: 'grid v1' },
    billing: { funding: 'Unknown', expected: 44100, invoice: 'Not ready', financing: 'Not applicable', qb: 'Manual external entry', note: 'Onboarding form outstanding — funding choice unknown' },
    receipt: null, gates: { grid: 'approved', policy: 'exists', billing: 'pending', receipt: 'pending', exceptions: 'clear' },
  },
});

R({
  id: 'R-2026-0260', account: 'Larkspur Senior Living', policy: 'POL-88470', advisor: 'A10',
  contact: { name: 'Merrill Bane', title: 'Administrator', email: 'mbane@larkspursl.com' },
  stage: 'RAQ In Progress', stageSince: ago(34), priority: 'Critical', engine: 'Routing recommended',
  lastEval: ago(0.03), lastActivity: ago(34), lastTouch: ago(7), premiumPrior: 132700, dormant: true,
  conditions: [cond('B15', B.B15, 'Sustained non-response across 5 attempts', 'Madison judgment', 34, {
    last: 7, att: 5, dl: 'submission', next: 'Recommend concierge routing — human decision',
    ev: [ev('email', 'Five outbound attempts', 'Oct 14 through Nov 10 — no inbound response observed', 'observed', ago(7)), ev('engine', 'Dormant threshold reached', '34 days without client or advisor activity with submission overdue', 'derived', ago(0.03)), ev('salesforce', 'Advisor portal status', 'Petrossian Benefit Group portal access expired Sep 2026', 'observed', ago(0.03))],
  })],
  rec: { action: 'Recommend routing', target: 'Operations lead', urgency: 'Today', why: ['Five attempts over 34 days have produced no observed response from client or advisor.', 'The advisor portal account is expired, so advisor-side reminder jobs are not reaching anyone.', 'The engine does not route renewals — a person decides whether this becomes a concierge case.'], approval: 'Human decision required', ifNothing: 'A $132,700 renewal lapses without anyone having made a decision about it.' },
  timeline: [tl(ago(0.03), 'engine', 'Routing recommended', 'Dormant threshold reached'), tl(ago(7), 'user', 'Draft approved and sent', 'A. Reyes · fifth attempt'), tl(ago(34), 'salesforce', 'Stage changed', 'RAQ Sent → RAQ In Progress')],
  artifacts: [],
});

R({
  id: 'R-2026-0271', account: 'Vantage Freight Systems', policy: 'POL-88489', advisor: 'A2',
  contact: { name: 'Odalys Vantage', title: 'CFO', email: 'ovantage@vantagefreight.com' },
  stage: 'Submission Prep', stageSince: ago(6), priority: 'High', engine: 'Draft ready',
  lastEval: ago(0.03), lastActivity: ago(6), lastTouch: ago(6), premiumPrior: 97300, portalIssue: true,
  conditions: [cond('B4', B.B4, 'Signer affidavit — Odalys Vantage', 'Client', 6, {
    last: 6, att: 1, dl: 'submission', next: 'Signature nudge to advisor — client has no portal account',
    ev: [ev('salesforce', 'Signer Details', 'Affidavit required; no completion recorded', 'observed', ago(0.03)), ev('salesforce', 'Portal account', 'Primary contact has no active portal account — reminder jobs cannot reach them', 'observed', ago(6))],
  })],
  rec: { action: 'Draft outreach', target: 'Marcus Ferris (advisor) — client not reachable by portal', urgency: 'Today', why: ['The affidavit is a client signature item, but the primary contact has no active portal account.', 'Native Salesforce reminder jobs do not cover this contact, so the advisor is the only reliable path.'], approval: 'Review required',
    ifNothing: 'The submission cannot be signed and the renewal will not reach underwriting.' },
  timeline: [tl(ago(6), 'engine', 'Blocking condition opened', 'B4 · affidavit outstanding'), tl(ago(6), 'engine', 'Standing audit flag', 'Portal account eligibility — primary contact')],
  artifacts: [art({ type: 'RAQ', name: 'Vantage_RAQ_2026.pdf', source: 'Salesforce', at: ago(8) })],
});

R({
  id: 'R-2026-0288', account: 'Merit Ambulance Group', policy: 'POL-88505', advisor: null,
  contact: { name: 'Casey Merit', title: 'Director of Finance', email: 'cmerit@meritambulance.com' },
  stage: 'Submission Prep', stageSince: ago(7), priority: 'High', engine: 'Draft ready · advisor missing',
  lastEval: ago(0.03), lastActivity: ago(7), lastTouch: ago(10), premiumPrior: 71200, exception: true,
  conditions: [cond('B3', B.B3, '2025 federal tax return', 'Client', 12, {
    last: 10, att: 2, dl: 'submission', next: 'Direct client request — no referring advisor on record',
    ev: [ev('salesforce', 'Referring Advisor', 'Field is empty — 5% of the book is direct, but this account had an advisor in 2025', 'uncertain', ago(0.03)), ev('email', 'Outbound Nov 7', 'Document request sent directly to client', 'observed', ago(10))],
  })],
  rec: { action: 'Draft outreach', target: 'Casey Merit (client) · no advisor to copy', urgency: 'Today', why: ['The tax return has been outstanding 12 days with the submission deadline passed.', 'No referring advisor is on record, so the normal advisor-first path is unavailable and outreach goes direct.'], approval: 'Review required', exception: 'X7', ifNothing: 'The submission stays incomplete and the missing advisor relationship stays unresolved.' },
  timeline: [tl(ago(7), 'engine', 'Exception opened', 'Missing advisor — X7'), tl(ago(12), 'engine', 'Blocking condition opened', 'B3 · 2025 tax return')],
  artifacts: [],
});

R({
  id: 'R-2026-0294', account: 'Iron Kettle Brewing', policy: 'POL-88512', advisor: 'A8',
  contact: { name: 'Fenn Marsalis', title: 'Owner', email: 'fenn@ironkettlebrew.com' },
  stage: 'RAQ Sent', stageSince: ago(19), priority: 'Normal', engine: 'Hold — advisor currency',
  lastEval: ago(0.03), lastActivity: ago(19), lastTouch: ago(19), premiumPrior: 29400, exception: true,
  conditions: [cond('B1', B.B1, 'Questionnaire not started', 'Client', 19, {
    last: 19, att: 1, dl: 'submission', next: 'Held — advisor relationship may be stale', conf: 'conflicting',
    ev: [ev('salesforce', 'Referring Advisor', 'Whitlock & Sons — last advisor activity 412 days ago', 'uncertain', ago(0.03)), ev('email', 'Bounce observed', 'Nov 1 message to errol@whitlockandsons.com returned undeliverable', 'observed', ago(16))],
  })],
  rec: { action: 'Hold', target: 'No outreach until the advisor relationship is confirmed', urgency: 'This week', why: ['The advisor address bounced and no advisor activity has been observed in over a year.', 'Chasing through a stale advisor wastes the attempt and leaves the client unaware.'], approval: 'Human resolution required', exception: 'X8', ifNothing: 'The renewal quietly ages with no working outreach path.' },
  timeline: [tl(ago(16), 'email', 'Delivery failure', 'errol@whitlockandsons.com — undeliverable'), tl(ago(19), 'salesforce', 'Stage changed', 'Renewal Created → RAQ Sent')],
  artifacts: [],
});

R({
  id: 'R-2026-0198', account: 'Grayson Precision', policy: 'POL-88355', advisor: 'A9',
  contact: { name: 'Lex Grayson', title: 'Owner', email: 'lex@graysonprecision.com' },
  stage: 'Invoiced', stageSince: ago(9), priority: 'Normal', engine: 'Suppressed',
  lastEval: ago(0.03), lastActivity: ago(2), lastTouch: ago(2), premiumPrior: 41800, suppressed: true,
  conditions: [cond('B14', B.B14, 'Premium payment $41,800', 'Client', 5, {
    last: 2, att: 1, dl: 'payment', next: 'Suppressed — native Salesforce reminder sent 2 days ago',
    ev: [ev('salesforce', 'Native reminder job', 'Salesforce payment reminder sent Nov 15 09:00', 'observed', ago(2)), ev('engine', 'Suppression applied', 'One outstanding touch per renewal per party', 'derived', ago(0.03))],
  })],
  rec: { action: 'Suppress', target: 'No outreach', urgency: 'Held 3 more days', why: ['A native Salesforce payment reminder reached the same contact 2 days ago.', 'A second reminder inside the 5-day suppression window would duplicate an in-flight message.'], approval: 'Automatic — visible in history', ifNothing: 'Nothing; the suppression lifts on Nov 20 and the condition is re-evaluated.' },
  timeline: [tl(ago(0.03), 'engine', 'Draft suppressed', 'Competing native reminder Nov 15 09:00'), tl(ago(2), 'salesforce', 'Native reminder sent', 'Payment reminder — Salesforce automation')],
  artifacts: [art({ type: 'Invoice', name: 'INV-4459.pdf', source: 'Salesforce', at: ago(9) })],
});

R({
  id: 'R-2026-0246', account: 'Stonecrest Property Group', policy: 'POL-88451', advisor: 'A3',
  contact: { name: 'Adaeze Stonecrest', title: 'Principal', email: 'adaeze@stonecrestpg.com' },
  stage: 'Sent to Actuarial', stageSince: ago(15), priority: 'Normal', engine: 'Internal ageing',
  lastEval: ago(0.03), lastActivity: ago(4), lastTouch: ago(4), premiumPrior: 108500,
  conditions: [cond('B9', B.B9, 'Revised actuarial output after limit change', 'AmRisk', 4, { internal: true, att: 1, next: 'Internal ageing — underwriter follow-up available', ev: [ev('email', 'Change request Nov 13', 'Umbrella limit raised to $10M; revision requested from AmRisk', 'observed', ago(4))] })],
  rec: { action: 'Await external response', target: 'AmRisk', urgency: 'Monitor', why: ['The change request is 4 days old, inside normal turnaround.', 'Client-side chase would be premature and unhelpful.'], approval: 'No action required', ifNothing: 'Selection materials cannot be issued until revised pricing returns.' },
  timeline: [tl(ago(4), 'amrisk', 'Change request sent', 'Umbrella limit revision')],
  artifacts: [],
});

R({
  id: 'R-2026-0257', account: 'Bellweather Textiles', policy: 'POL-88466', advisor: 'A6',
  contact: { name: 'Sable Bellweather', title: 'CFO', email: 'sable@bellweathertx.com' },
  stage: 'Pricing With Client', stageSince: ago(17), priority: 'Normal', engine: 'On hold',
  lastEval: ago(0.03), lastActivity: ago(17), lastTouch: ago(17), premiumPrior: 92300, hold: true,
  conditions: [cond('B8', B.B8, 'Completed selection worksheet', 'Client', 17, {
    last: 17, att: 1, next: 'Held by A. Reyes', status: 'held',
    override: { by: 'A. Reyes', at: ago(6), reason: 'Client in chapter 11 review — counsel asked for no outreach until Dec 1' },
    ev: [ev('salesforce', 'Stage', 'Pricing With Client since Oct 31', 'observed', ago(0.03))],
  })],
  rec: { action: 'Hold', target: 'No outreach until Dec 1', urgency: 'Held', why: ['A. Reyes placed this renewal on hold on Nov 11 with a recorded reason.', 'The hold expires Dec 1, after which the selection condition returns to normal chase.'], approval: 'Human decision recorded', ifNothing: 'Nothing until Dec 1; the renewal stays visible in the On hold view.' },
  timeline: [tl(ago(6), 'user', 'Renewal held', 'A. Reyes · reason: chapter 11 review, counsel request')],
  artifacts: [],
});

R({
  id: 'R-2026-0283', account: 'Redfern Logistics', policy: 'POL-88498', advisor: 'A1',
  contact: { name: 'Isaiah Redfern', title: 'President', email: 'iredfern@redfernlogistics.com' },
  stage: 'With Underwriting', stageSince: ago(13), priority: 'High', engine: 'Escalated',
  lastEval: ago(0.03), lastActivity: ago(2), lastTouch: ago(4), premiumPrior: 156400, escalated: true, exception: true,
  conditions: [
    cond('B5', B.B5, 'Fleet schedule with VIN-level detail', 'Client', 13, {
      last: 4, att: 3, dl: 'submission', next: 'Intensified follow-up — advisor consolidation next rung',
      ev: [ev('salesforce', 'Underwriting request Nov 4', 'VIN-level fleet schedule required before pricing', 'observed', ago(13)), ev('email', 'Three attempts', 'Nov 5, Nov 9, Nov 13 — partial schedule received Nov 15, VINs missing', 'observed', ago(2))],
    }),
    cond('B3', B.B3, 'Driver MVR summary', 'Client', 6, { last: 4, att: 1, dl: 'submission', next: 'Include in the same advisor message', ev: [ev('email', 'Inbound Nov 15', 'Partial fleet documents received; MVR summary not included', 'observed', ago(2))] }),
  ],
  rec: { action: 'Consolidate', target: 'Dana Halbrook (advisor) — 4 renewals today', urgency: 'Today', why: ['Two documents are outstanding on the same renewal and both belong in one message.', 'Three other Halbrook renewals also need advisor contact today, so a book brief is the appropriate vehicle.', 'An inbound partial delivery on Nov 15 means the message must acknowledge what did arrive.'], approval: 'Review required', consolidate: true, ifNothing: 'Underwriting cannot price the fleet and the submission stays incomplete past its deadline.' },
  timeline: [tl(ago(2), 'email', 'Inbound email — Isaiah Redfern', 'Partial fleet schedule attached'), tl(ago(2), 'engine', 'Unclassified condition', 'Inbound message references a bond requirement outside the taxonomy — X12'), tl(ago(13), 'salesforce', 'Underwriting request recorded', 'VIN-level fleet schedule')],
  artifacts: [art({ type: 'Fleet schedule', name: 'Redfern_Fleet_partial.xlsx', at: ago(2), filing: 'filed', confidence: 0.93 })],
});

/* ---------- generated book (fills to 350 policies / ~50 advisors) ---------- */
let seed = 20261117;
const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
const pick = (a) => a[Math.floor(rnd() * a.length)];
const FIRST = ['Alma', 'Bryce', 'Colette', 'Dmitri', 'Esme', 'Franklin', 'Greta', 'Hugh', 'Ines', 'Jonas', 'Kelsey', 'Liam', 'Mira', 'Nadir', 'Opal', 'Pilar', 'Quentin', 'Rosalind', 'Silas', 'Tova', 'Ulric', 'Verena', 'Wesley', 'Xiomara', 'Yves', 'Zora'];
const LAST = ['Abernathy', 'Bracken', 'Castellanos', 'Duvall', 'Eastwick', 'Fontaine', 'Gilliard', 'Hensley', 'Ivers', 'Jarreau', 'Kowalczyk', 'Lindqvist', 'Moreau', 'Nakashima', 'Oyelaran', 'Prentiss', 'Quiroga', 'Rasmussen', 'Sotelo', 'Thackeray', 'Underwood', 'Vasquez', 'Wexler', 'Yamashita'];
const CO_A = ['Northfield', 'Harborline', 'Kestrel', 'Ridgeway', 'Wexford', 'Ambleside', 'Cardinal', 'Dunmore', 'Elmgrove', 'Foxhall', 'Granite', 'Hollow Creek', 'Ironwood', 'Juniper', 'Lakemont', 'Marchmont', 'Oakridge', 'Prairie', 'Quarry', 'Rockvale', 'Sable', 'Thornbury', 'Union Point', 'Verdant', 'Westhaven'];
const CO_B = ['Manufacturing', 'Logistics', 'Dental Group', 'Medical Partners', 'Foods', 'Fabrication', 'Property Group', 'Senior Care', 'Analytics', 'Machining', 'Distribution', 'Beverage Co.', 'Contractors', 'Orthopedics', 'Plastics', 'Cold Chain', 'Marine', 'Timber', 'Freight', 'Electric'];
const FIRMS = ['Cardinal Benefit Advisors', 'Talbot Risk Group', 'Sinclair & Pike', 'Overton Financial', 'Bramble Advisory', 'Hale Insurance Partners', 'Ferndale Wealth', 'Corbin Risk', 'Aspen Line Advisors', 'Duquesne Benefits', 'Marrow & Kent', 'Pinehurst Advisory', 'Ravel Financial Group', 'Sutter Peak Advisors', 'Tamarind Benefits', 'Ulmer Risk Services', 'Voss & Ardent', 'Wren Capital Advisory', 'Yardley Group', 'Zephyr Benefit Co.', 'Applegate Risk', 'Bexley Advisory', 'Coldwater Partners', 'Drayton Benefit Group', 'Eastbrook Advisors', 'Fielding Risk', 'Glenroy Advisory', 'Hartwell & Co.', 'Ingersoll Benefits', 'Kessler Line', 'Lomond Advisory', 'Merrow Risk Partners', 'Neville Benefit Group', 'Oakhurst Advisors', 'Pemberton Risk', 'Quill Financial', 'Rothwell Advisory', 'Stanhope Benefits', 'Trellis Risk Group', 'Ventnor Advisory'];
const STAGES = ['Renewal Created', 'RAQ Sent', 'RAQ In Progress', 'Submission Prep', 'Sent to Underwriting', 'With Underwriting', 'Sent to Actuarial', 'Pricing With Client', 'Selection Received', 'COI Sent', 'Invoiced', 'Renewed'];
const STAGE_B = {
  'Renewal Created': ['B1'], 'RAQ Sent': ['B1'], 'RAQ In Progress': ['B2'], 'Submission Prep': ['B3', 'B4'],
  'Sent to Underwriting': ['B3', 'B5'], 'With Underwriting': ['B6', 'B5'], 'Sent to Actuarial': ['B7', 'B10'],
  'Pricing With Client': ['B8'], 'Selection Received': ['B11', 'B12'], 'COI Sent': ['B13'], 'Invoiced': ['B14'], Renewed: [],
};
const ITEM = { B1: 'Questionnaire not started', B2: 'Questionnaire incomplete', B3: '2025 P&L statement', B4: 'Signer affidavit', B5: 'Underwriter question unanswered', B6: 'Underwriting review', B7: 'Actuarial output', B8: 'Completed selection worksheet', B9: 'Revised actuarial output', B10: 'Next-of-kin liability letter', B11: 'AmRisk locked selection PDF', B12: 'Renewal onboarding form', B13: 'Financing signatures', B14: 'Premium payment' };
const OWNER = { B1: 'Client', B2: 'Client', B3: 'Client', B4: 'Client', B5: 'Advisor', B6: 'Underwriting', B7: 'AmRisk', B8: 'Client', B9: 'AmRisk', B10: 'Client', B11: 'AmRisk', B12: 'Client', B13: 'Client', B14: 'Client' };
const DOCS = ['2025 P&L statement', '2024 tax return', 'Certificate of formation', 'Photo ID — signer', 'Audited financial statement', 'Current-year P&L'];

const advisors = ADVISORS.map((a) => Object.assign({}, a));
FIRMS.forEach((firm, i) => {
  const name = pick(FIRST) + ' ' + pick(LAST);
  advisors.push({ id: 'A' + (11 + i), name, firm, email: name.split(' ')[1].toLowerCase() + '@' + firm.toLowerCase().replace(/[^a-z]/g, '').slice(0, 12) + '.com', target: 2 + Math.floor(rnd() * 8), lastTouch: ago(1 + Math.floor(rnd() * 40)), portal: rnd() > 0.93 ? 'expired' : 'active' });
});

const renewals = DEEP.map((r) => Object.assign({
  conditions: [], resolvedConds: [], artifacts: [], timeline: [], close: null,
  deadlines: CYCLE.deadlines, term: CYCLE.term,
}, r));

let pid = 89000, rid = 400;
const counts = {};
renewals.forEach((r) => { counts[r.advisor] = (counts[r.advisor] || 0) + 1; });
advisors.forEach((a) => {
  const need = Math.max(0, a.target - (counts[a.id] || 0));
  for (let i = 0; i < need; i++) {
    const stage = pick(STAGES.slice(0, 11).concat(['Renewed', 'Renewed']));
    const cats = STAGE_B[stage] || [];
    const cat = cats.length ? pick(cats) : null;
    const opened = 2 + Math.floor(rnd() * 26);
    const account = pick(CO_A) + ' ' + pick(CO_B);
    const dlKey = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6'].includes(cat) ? 'submission' : ['B13', 'B14'].includes(cat) ? 'payment' : 'selection';
    const conds = cat ? [cond(cat, B[cat], cat === 'B3' ? pick(DOCS) : ITEM[cat] || B[cat], OWNER[cat], opened, {
      last: Math.floor(rnd() * 9), att: Math.floor(rnd() * 4), dl: dlKey, internal: ['B6', 'B7', 'B9', 'B11'].includes(cat),
      dueIn: daysTo(dl(dlKey)) + pick([0, 0, 7, 14, 14, 21, 35, 49]),
      next: 'Standard follow-up for this condition', ev: [ev('salesforce', 'Stage and field state', 'Derived from the last full-book evaluation', 'observed', ago(0.03))],
    })] : [];
    const multi = cat && rnd() > 0.86;
    if (multi) { const c2 = pick(['B3', 'B4', 'B5']); conds.push(cond(c2, B[c2], c2 === 'B3' ? pick(DOCS) : ITEM[c2], OWNER[c2], 1 + Math.floor(rnd() * 12), { last: Math.floor(rnd() * 6), att: Math.floor(rnd() * 3), dl: 'submission', dueIn: daysTo(dl('submission')) + pick([0, 14, 21, 35]), next: 'Include in the next message', ev: [ev('salesforce', 'Field state', 'Observed at last evaluation', 'observed', ago(0.03))] })); }
    const disp = !cat ? 'No action required' : conds[0].internal ? 'Internal ageing' : conds[0].last < 3 ? 'Await external response' : rnd() > 0.7 ? 'Draft ready' : 'Await external response';
    renewals.push({
      id: 'R-2026-0' + ++rid, account, policy: 'POL-' + ++pid, advisor: a.id,
      contact: { name: pick(FIRST) + ' ' + pick(LAST), title: pick(['CFO', 'Controller', 'Owner', 'President', 'Director of Finance']), email: 'contact@' + account.toLowerCase().replace(/[^a-z]/g, '').slice(0, 14) + '.com' },
      stage, stageSince: ago(1 + Math.floor(rnd() * 20)), priority: conds.length && conds[0].pressure === 'overdue' ? 'High' : pick(['Normal', 'Normal', 'High']),
      engine: stage === 'Renewed' ? 'Closed' : disp, lastEval: ago(0.03), lastActivity: ago(1 + Math.floor(rnd() * 15)), lastTouch: ago(1 + Math.floor(rnd() * 14)),
      premiumPrior: 20000 + Math.floor(rnd() * 180000), conditions: conds, resolvedConds: [], deadlines: CYCLE.deadlines, term: CYCLE.term,
      rec: { action: !cat ? 'No action required' : disp === 'Draft ready' ? 'Draft outreach' : disp === 'Internal ageing' ? 'Internal escalation' : 'Await external response', target: conds.length ? (conds[0].owing === 'Client' ? 'Client · advisor copied' : conds[0].owing) : '—', urgency: conds.length && conds[0].pressure === 'crit' ? 'This week' : 'Monitor', why: conds.length ? ['Condition open ' + conds[0].age + ' days with ' + conds[0].attempts + ' prior attempts.', 'Deadline pressure: ' + conds[0].daysTo + ' days to the ' + conds[0].dl + ' deadline.'] : ['No open conditions.'], approval: cat ? 'Review required' : 'None', ifNothing: 'The condition ages toward its deadline without a new attempt.' },
      timeline: [tl(ago(0.03), 'engine', 'Renewal evaluated', 'Disposition: ' + disp), tl(ago(2 + Math.floor(rnd() * 9)), 'salesforce', 'Stage changed', 'Entered ' + stage)],
      artifacts: [], close: null,
    });
  }
});
const byId = {};
renewals.forEach((r) => { byId[r.id] = r; });
advisors.forEach((a) => { a.policies = renewals.filter((r) => r.advisor === a.id).map((r) => r.id); });

/* ---------- drafts ---------- */
const D = (id, rid_, o) => Object.assign({ id, renewal: rid_, state: 'ready', createdAt: ago(0.02), edits: [], corrections: [] }, o);
const drafts = [
  D('DR-1', 'R-2026-0147', {
    to: 'dana.halbrook@halbrookrisk.com', cc: 'j.mercer@vanceaggregates.com', category: 'Document request',
    subject: 'Vance Aggregates renewal — 2025 P&L and ownership confirmation',
    body: 'Dana,\n\nTwo items are still open on the Vance Aggregates renewal and both are holding the submission.\n\n1. 2025 P&L statement — requested Oct 30, last chased Nov 12. Joel confirmed on Nov 14 that his controller is preparing it.\n2. Ownership confirmation — underwriting needs to know which entity holds the Fulton pit lease after the 2024 restructure. This was relayed on Nov 14 and has not come back.\n\nSelection closes Nov 30. If the P&L is going to take longer than this week, let me know and we will work out what underwriting can proceed on in the meantime.\n\nThank you,\nAlex Reyes\nMadison Insurance Group',
    reason: 'B3 open 14 days · B5 open 3 days · submission overdue · 5 days since last touch', consolidateWith: ['DR-2', 'DR-3', 'DR-4'],
  }),
  D('DR-2', 'R-2026-0189', { to: 'k.osei@madisonins.example', cc: '', category: 'Internal escalation note', subject: 'Brightlin Foods — 11 days at With Underwriting', body: 'Kwame,\n\nBrightlin Foods (POL-88301) has been at With Underwriting for 11 days with a complete submission and nothing outstanding from the client. Flagging for the queue review.\n\nAlex', reason: 'B6 internal ageing above 7-day threshold', internal: true }),
  D('DR-3', 'R-2026-0143', { to: 'cvandermeer@sunbeltpoultry.com', cc: 'dana.halbrook@halbrookrisk.com', category: 'Payment reminder', subject: 'Sunbelt Poultry — premium payment', body: 'Curtis,\n\nInvoice INV-4471 for $92,300 remains open on the Sunbelt Poultry renewal. Payment is due Dec 31.\n\nIf payment has already been sent, please send the wire reference and we will match it on our side.\n\nThank you,\nAlex Reyes', reason: 'B14 open 6 days · payment deadline in 44 days', state: 'held', heldReason: 'A $92,300 wire is awaiting receipt matching (X6). Reminder held until accounting resolves it.', consolidateWith: ['DR-1'] }),
  D('DR-4', 'R-2026-0311', { to: 'dana.halbrook@halbrookrisk.com', cc: '', category: 'RAQ start nudge', subject: 'Yarrow Biotech — questionnaire not started (4th attempt)', body: 'Dana,\n\nYarrow Biotech has not started the renewal questionnaire. This is the fourth request since Oct 27 and we have had no response from Simone or from your office.\n\nSubmission is already past due and selection closes Nov 30. If there is a reason this renewal is not moving, I would rather know now than keep sending reminders.\n\nAlex Reyes', reason: 'B1 open 26 days · 4 attempts · escalation rung 4', consolidateWith: ['DR-1'] }),
  D('DR-5', 'R-2026-0233', { to: 'htrager@palomardental.com', cc: 'priya@cedarpointbenefits.com', category: 'NKLL request', subject: 'Palomar Dental — next-of-kin liability letter required', body: 'Hollis,\n\nBecause cyber liability is being added at this renewal, we need a next-of-kin liability letter on file before the policy can be issued. The template is attached — it needs a signature from an authorized officer.\n\nSelection closes Nov 30 and the letter is a prerequisite for release, so earlier is better.\n\nThank you,\nAlex Reyes', reason: 'B10 open 5 days · coverage addition triggered the requirement' }),
  D('DR-6', 'R-2026-0301', { to: 'ivo@tessellate.io', cc: 'tom@ainsworthgroup.net', category: 'RAQ completion nudge', subject: 'Tessellate Analytics — questionnaire sections 4–6', body: 'Ivo,\n\nSections 4 through 6 of the renewal questionnaire are still outstanding. Everything else is complete.\n\nCould you finish those three sections this week? Submission is already past due for this renewal.\n\nThank you,\nAlex Reyes', reason: 'B2 open 21 days · 3 attempts', warn: 'Email observation for the Advisor Services mailbox is stale (5h 40m). A reply may exist that the engine cannot see.' }),
  D('DR-7', 'R-2026-0212', { to: 'renata@kilroysteel.com', cc: 'mferris@ferrislowe.com', category: 'Selection nudge', subject: 'Kilroy Structural Steel — selection worksheet', body: 'Renata,\n\nWe have not received your completed selection worksheet…', reason: 'B8 open 9 days · selection deadline in 13 days', state: 'suppressed', suppressedBy: 'Inbound email Nov 14 11:47 from Renata Kilroy appears to contain the selection worksheet. Sending this reminder would contradict a document the client believes they returned. Exception X2 is open.' }),
  D('DR-8', 'R-2026-0198', { to: 'lex@graysonprecision.com', cc: '', category: 'Payment reminder', subject: 'Grayson Precision — premium payment', body: 'Lex,\n\nInvoice INV-4459 for $41,800 remains open…', reason: 'B14 open 5 days', state: 'suppressed', suppressedBy: 'Native Salesforce payment reminder sent Nov 15 09:00 to the same contact. Engine suppression window: 5 days. Lifts Nov 20.' }),
  D('DR-9', 'R-2026-0271', { to: 'mferris@ferrislowe.com', cc: '', category: 'Signature nudge', subject: 'Vantage Freight — signer affidavit', body: 'Marcus,\n\nThe signer affidavit for Vantage Freight is still outstanding. Odalys does not have an active portal account, so the automated reminders are not reaching her — could you walk it through directly?\n\nSubmission is past due on this one.\n\nThank you,\nAlex Reyes', reason: 'B4 open 6 days · client not portal-eligible' }),
  D('DR-10', 'R-2026-0222', { to: 'nora@ashfieldplastics.com', cc: 'cboateng@northgateadv.com', category: 'Onboarding form return', subject: 'Ashfield Plastics — onboarding form', body: 'Nora,\n\nThe renewal onboarding form is still outstanding. We need it to know whether you are paying in full or financing, which determines what we send you next.\n\nThank you,\nAlex Reyes', reason: 'B12 open 8 days · funding choice unknown blocks billing' }),
  D('DR-11', 'R-2026-0151', { to: 'wdamaris@cobaltridge.com', cc: 'skapoor@meridiantrust.com', category: 'Signature nudge', subject: 'Cobalt Ridge — DEB form signature', body: 'Whit,\n\nThe installment agreement came back signed on Nov 14, but the DEB form is still unsigned in the same envelope. Financing cannot be set up until both are complete.\n\nThank you,\nAlex Reyes', reason: 'B13 open 7 days · 1 of 2 financing documents signed' }),
  D('DR-12', 'R-2026-0288', { to: 'cmerit@meritambulance.com', cc: '', category: 'Document request', subject: 'Merit Ambulance — 2025 federal tax return', body: 'Casey,\n\nThe 2025 federal tax return is the last document outstanding on your renewal submission.\n\nThank you,\nAlex Reyes', reason: 'B3 open 12 days · no advisor on record', warn: 'No referring advisor on record (X7). This message goes direct to the client with nobody copied.' }),
  D('DR-13', 'R-2026-0283', { to: 'dana.halbrook@halbrookrisk.com', cc: 'iredfern@redfernlogistics.com', category: 'Document request', subject: 'Redfern Logistics — VIN detail and MVR summary', body: 'Dana,\n\nThe partial fleet schedule arrived Nov 15 — thank you. Two things are still missing before underwriting can price it:\n\n1. VIN-level detail for the 14 units added in September.\n2. Driver MVR summary.\n\nAlex Reyes', reason: 'B5 open 13 days · B3 open 6 days · partial delivery Nov 15', consolidateWith: ['DR-1'] }),
  D('DR-14', 'R-2026-0166', { to: 'actuarial@amrisk.example', cc: 'k.osei@madisonins.example', category: 'Internal escalation note', subject: 'Northbay Marine — locked selection follow-up', body: 'Following up on the locked selection for Northbay Marine Services (POL-88266). Client selection returned Nov 13.\n\nAlex Reyes\nMadison Insurance Group', reason: 'B11 open 4 days · day 5 of normal turnaround', internal: true, state: 'held', heldReason: 'Inside the normal 5-day AmRisk turnaround. Releases tomorrow.' }),
];

/* ---------- exceptions ---------- */
const exceptions = [
  { id: 'X1', cat: 'Unmatched correspondence', sev: 'high', renewal: null, age: 0.6, status: 'open', owner: 'Unassigned', summary: 'Inbound email with two attachments could not be matched to a renewal with confidence',
    email: { from: 'j.mercer@vanceaggregates.com', name: 'Joel Mercer', to: 'renewals@madisonins.example', cc: 'dana.halbrook@halbrookrisk.com', subject: 'FY2025 financials attached', at: ago(0.6), preview: 'Alex — attached are the 2025 P&L and the balance sheet your team asked for. Let me know if the format works. Also copying Dana.\n\nJoel Mercer\nCFO, Vance Aggregates', attachments: ['Vance_PL_FY2025.pdf', 'Vance_BS_FY2025.xlsx'] },
    candidates: [
      { renewal: 'R-2026-0147', score: 0.72, why: ['Sender domain matches the primary contact on this renewal', 'Advisor on copy is the referring advisor', 'Open condition B3 expects a 2025 P&L'] },
      { renewal: 'R-2026-0271', score: 0.19, why: ['Similar account name ("Vantage" / "Vance")', 'Also has an open document condition'] },
      { renewal: 'R-2026-0198', score: 0.09, why: ['Same advisor firm on a different renewal'] },
    ],
    reason: 'Sender is a known contact, but the subject line carries no renewal or account reference and the thread is new. Two candidate renewals share document-shaped conditions.' },
  { id: 'X2', cat: 'Salesforce / email contradiction', sev: 'high', renewal: 'R-2026-0212', age: 3, status: 'open', owner: 'A. Reyes', summary: 'Email indicates the selection worksheet returned Nov 14; Salesforce still shows Pricing With Client', resolution: 'Confirm whether Kilroy_Selections_FINAL.xlsx is the selection worksheet, then match it or mark it unrelated.' },
  { id: 'X3', cat: 'Unknown coverage mapping', sev: 'high', renewal: 'R-2026-0178', age: 2, status: 'open', owner: 'M. Duclos', summary: '"Equipment breakdown — contingent" is not present in the coverage mapping registry', resolution: 'Select the correct risk code, or add a registry alias. Staging stays blocked until the mapping is known.' },
  { id: 'X4', cat: 'Worksheet / lock mismatch', sev: 'high', renewal: 'R-2026-0178', age: 2, status: 'open', owner: 'M. Duclos', summary: 'Excess liability premium: worksheet $41,880 vs locked $41,180', resolution: 'The locked PDF is authoritative. Correct the line to the locked value or resolve the source conflict with AmRisk.' },
  { id: 'X5', cat: 'Worksheet parse failure', sev: 'high', renewal: 'R-2026-0175', age: 3, status: 'open', owner: 'Unassigned', summary: 'Unsupported worksheet layout — no coverage rows extracted', resolution: 'Re-request the worksheet on the standard template, or key the selection manually for shadow comparison.' },
  { id: 'X6', cat: 'Ambiguous receipt', sev: 'high', renewal: 'R-2026-0143', age: 1, status: 'open', owner: 'L. Okonjo', summary: '$92,300 wire from "SBP Holdings LLC" matches the expected amount on two renewals', resolution: 'Accounting selects the correct renewal. Automatic confirmation is blocked.' },
  { id: 'X7', cat: 'Missing advisor', sev: 'medium', renewal: 'R-2026-0288', age: 7, status: 'open', owner: 'Unassigned', summary: 'No referring advisor on a renewal that had one in the 2025 cycle', resolution: 'Confirm whether this is now a direct account or restore the advisor relationship.' },
  { id: 'X8', cat: 'Stale advisor', sev: 'medium', renewal: 'R-2026-0294', age: 16, status: 'open', owner: 'Unassigned', summary: 'Advisor address undeliverable; no advisor activity in 412 days', resolution: 'Confirm the advisor relationship or reassign before any further outreach.' },
  { id: 'X9', cat: 'Filing failure', sev: 'medium', renewal: 'R-2026-0233', age: 2, status: 'open', owner: 'System', summary: 'Document matched but the Salesforce Files write was rejected', resolution: 'Retry the filing write. The document is held in the engine and the condition stays resolved.' },
  { id: 'X10', cat: 'Manual / engine discrepancy', sev: 'medium', renewal: 'R-2026-0205', age: 4, status: 'open', owner: 'M. Duclos', summary: 'Two differences between the engine grid and the manually entered coverage', resolution: 'Classify each discrepancy. Classification feeds the 2027 cutover evidence base.' },
  { id: 'X11', cat: 'Source stale', sev: 'high', renewal: null, age: 0.24, status: 'open', owner: 'System', summary: 'Advisor Services shared mailbox last observed 5h 40m ago — 6 renewals affected', affected: ['R-2026-0301', 'R-2026-0311', 'R-2026-0246', 'R-2026-0271', 'R-2026-0294', 'R-2026-0288'], resolution: 'Absence of a reply is not treated as fact on affected renewals until observation resumes.' },
  { id: 'X12', cat: 'Unclassified condition', sev: 'low', renewal: 'R-2026-0283', age: 2, status: 'open', owner: 'Unassigned', summary: 'Inbound message references a surety bond requirement that no B-category covers', resolution: 'Label the condition or confirm it is outside the renewal process. The engine will not force it into an existing category.' },
  { id: 'X13', cat: 'Duplicate source artifact', sev: 'medium', renewal: 'R-2026-0163', age: 4, status: 'open', owner: 'M. Duclos', summary: 'Two AmRisk locked selection PDFs received for the same renewal', resolution: 'Confirm v2 is authoritative and mark v1 superseded.' },
];

/* ---------- standing audits ---------- */
const audits = {
  portal: [
    { renewal: 'R-2026-0271', account: 'Vantage Freight Systems', who: 'Odalys Vantage (contact)', issue: 'No portal account', exposure: 'Reminder jobs do not reach this contact', chase: 'Covered via advisor' },
    { renewal: 'R-2026-0288', account: 'Merit Ambulance Group', who: 'Casey Merit (contact)', issue: 'Portal account inactive since Aug 2026', exposure: 'Reminder jobs silently skipped', chase: 'Direct client outreach' },
    { renewal: 'R-2026-0260', account: 'Larkspur Senior Living', who: 'Petrossian Benefit Group (advisor)', issue: 'Advisor portal access expired Sep 2026', exposure: 'Advisor-side reminders not delivered', chase: 'Routing recommended' },
    { renewal: 'R-2026-0294', account: 'Iron Kettle Brewing', who: 'Whitlock & Sons (advisor)', issue: 'Advisor address undeliverable', exposure: 'No working outreach path', chase: 'On hold' },
    { renewal: 'R-2026-0446', account: 'Foxhall Machining', who: 'Contact (unnamed)', issue: 'No portal account', exposure: 'Reminder jobs do not reach this contact', chase: 'Covered via advisor' },
    { renewal: 'R-2026-0468', account: 'Quarry Distribution', who: 'Contact (unnamed)', issue: 'Portal account pending activation', exposure: 'Partial coverage', chase: 'Covered via advisor' },
    { renewal: 'R-2026-0492', account: 'Verdant Foods', who: 'Advisor', issue: 'Portal account expired', exposure: 'Advisor-side reminders not delivered', chase: 'Covered by engine chase' },
  ],
  referrer: [
    { advisor: 'A8', issue: 'No advisor activity in 412 days; address undeliverable', policies: 2, sev: 'high' },
    { advisor: 'A10', issue: 'Portal access expired Sep 2026', policies: 8, sev: 'high' },
    { advisor: 'A4', issue: 'No advisor communication in 21 days on 2 open renewals', policies: 2, sev: 'low' },
    { advisor: 'A6', issue: 'Advisor of record differs from the 2025 cycle on 1 renewal', policies: 3, sev: 'medium' },
    { advisor: 'A19', issue: 'Firm name changed; contact record not updated', policies: 4, sev: 'low' },
  ],
  links: [
    { renewal: 'R-2026-0288', issue: 'Expiring policy link missing — no prior-term policy related to this renewal', sev: 'high' },
    { renewal: 'R-2026-0421', issue: 'Renewal related to a policy that expired in 2024', sev: 'medium' },
    { renewal: 'R-2026-0503', issue: 'Two renewals related to the same expiring policy', sev: 'high' },
  ],
};

/* ---------- automation ---------- */
const automation = [
  { cat: 'RAQ start nudge', b: 'B1', mode: 'Autopilot Enabled', volume: 61, edit: 0.06, discard: 0.02, exc: 0.01, inReview: '11 weeks', owner: 'R. Alvarez', changedAt: ago(46), note: 'Enabled Oct 2 after 11 weeks in review', trend: [0.31, 0.24, 0.18, 0.12, 0.09, 0.06] },
  { cat: 'RAQ completion nudge', b: 'B2', mode: 'Eligible for Consideration', volume: 48, edit: 0.09, discard: 0.02, exc: 0.02, inReview: '9 weeks', owner: 'Review queue', changedAt: ago(63), note: 'Edit rate under 10% for 5 consecutive weeks', trend: [0.34, 0.28, 0.21, 0.14, 0.11, 0.09] },
  { cat: 'Document request', b: 'B3', mode: 'Eligible for Consideration', volume: 137, edit: 0.11, discard: 0.03, exc: 0.02, inReview: '10 weeks', owner: 'Review queue', changedAt: ago(70), note: 'Highest volume category; recommendation pending an administrator decision', trend: [0.38, 0.31, 0.24, 0.17, 0.13, 0.11] },
  { cat: 'Signature nudge', b: 'B4 · B13', mode: 'Review Required', volume: 42, edit: 0.19, discard: 0.05, exc: 0.03, inReview: '10 weeks', owner: 'Review queue', changedAt: ago(70), note: 'Recipient corrections still common where portal eligibility is missing', trend: [0.4, 0.36, 0.29, 0.25, 0.22, 0.19] },
  { cat: 'Selection nudge', b: 'B8', mode: 'Autopilot Suspended', volume: 74, edit: 0.27, discard: 0.09, exc: 0.06, inReview: '—', owner: 'R. Alvarez', changedAt: ago(14), note: 'Suspended Nov 3 after edit rate rose during the selection window', trend: [0.12, 0.14, 0.19, 0.23, 0.26, 0.27] },
  { cat: 'NKLL request', b: 'B10', mode: 'Review Required', volume: 12, edit: 0.33, discard: 0.08, exc: 0.0, inReview: '10 weeks', owner: 'Review queue', changedAt: ago(70), note: 'Low volume; compliance language reviewed every send', trend: [0.5, 0.44, 0.4, 0.38, 0.35, 0.33] },
  { cat: 'Onboarding form return', b: 'B12', mode: 'Review Required', volume: 29, edit: 0.14, discard: 0.03, exc: 0.01, inReview: '6 weeks', owner: 'Review queue', changedAt: ago(42), note: 'Approaching eligibility; 4 more weeks at this rate', trend: [0.29, 0.24, 0.2, 0.17, 0.15, 0.14] },
  { cat: 'Payment reminder', b: 'B14', mode: 'Review Required', volume: 33, edit: 0.21, discard: 0.06, exc: 0.03, inReview: '10 weeks', owner: 'Locked by policy', changedAt: ago(70), note: 'Contains monetary figures — remains under review by communications control', trend: [0.3, 0.27, 0.25, 0.24, 0.22, 0.21], locked: true },
  { cat: 'Advisor book brief', b: 'Multi', mode: 'Review Required', volume: 26, edit: 0.42, discard: 0.04, exc: 0.02, inReview: '7 weeks', owner: 'Review queue', changedAt: ago(49), note: 'Consolidated messages are edited most often; human judgment on grouping', trend: [0.55, 0.52, 0.48, 0.45, 0.44, 0.42] },
  { cat: 'Internal escalation note', b: 'B6 · B7 · B9 · B11', mode: 'Review Required', volume: 58, edit: 0.12, discard: 0.02, exc: 0.01, inReview: '10 weeks', owner: 'Review queue', changedAt: ago(70), note: 'Internal recipients only', trend: [0.26, 0.22, 0.18, 0.15, 0.13, 0.12] },
];
const automationLog = [
  { at: ago(14), who: 'R. Alvarez', what: 'Selection nudge → Autopilot Suspended', why: 'Edit rate rose from 14% to 26% during the selection window' },
  { at: ago(46), who: 'R. Alvarez', what: 'RAQ start nudge → Autopilot Enabled', why: '11 weeks in review · edit rate 6% · discard rate 2%' },
  { at: ago(70), who: 'System', what: 'All categories initialised to Review Required', why: 'Phase One start' },
];

/* ---------- coverage mapping registry ---------- */
const mappings = [
  { coverage: 'General liability', aliases: 'GL, Commercial general liability, CGL', code: '1310', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Auto liability', aliases: 'Commercial auto, Fleet liability', code: '1350', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Liquor liability', aliases: 'Host liquor', code: '1366', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Excess liability', aliases: 'Umbrella, Excess umbrella', code: '1390', sub: 'A', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Professional liability', aliases: 'E&O, Errors and omissions', code: '1418', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Medical professional liability', aliases: 'Medical malpractice, MPL', code: '1424', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v5', status: 'Active', reviewed: ago(3) },
  { coverage: 'Crop / agricultural', aliases: 'Crop, Agricultural output', code: '1442', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Commercial property', aliases: 'Property, Building and contents', code: '1520', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Employment practices liability', aliases: 'EPLI', code: '1622', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Fiduciary liability', aliases: 'Fiduciary', code: '1640', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Pollution liability', aliases: 'Environmental impairment', code: '1690', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Crime', aliases: 'Fidelity, Employee dishonesty', code: '1712', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Inland marine', aliases: 'Equipment floater, Contractors equipment', code: '1744', sub: 'B', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Equipment breakdown', aliases: 'Boiler and machinery', code: '1748', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Product recall', aliases: 'Recall expense', code: '1780', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Cyber liability', aliases: 'Cyber, Data breach', code: '1836', sub: '—', target: 'Coverage__c.RiskCode__c', ver: 'v4', status: 'Active', reviewed: ago(58) },
  { coverage: 'Equipment breakdown — contingent', aliases: '—', code: null, sub: '—', target: '—', ver: '—', status: 'Unmapped', reviewed: null, exception: 'X3' },
];

/* ---------- cycle reconciliation ---------- */
const cycle = {
  staged: 62, exact: 47, discrepancy: 15, parseErr: 4, mapErr: 3, manualErr: 6, timing: 9, missingSrc: 2, unresolved: 5,
  engineReadyAvg: 0.4, manualDoneAvg: 2.8, approvedGrids: 38, receiptsConfirmed: 21, releaseEligible: 14,
  weeks: [{ w: 'Wk 40', exact: 2, disc: 2 }, { w: 'Wk 41', exact: 5, disc: 3 }, { w: 'Wk 42', exact: 8, disc: 4 }, { w: 'Wk 43', exact: 11, disc: 3 }, { w: 'Wk 44', exact: 9, disc: 2 }, { w: 'Wk 45', exact: 12, disc: 1 }],
};

/* ---------- source health ---------- */
const health = {
  salesforce: { status: 'connected', lastRead: ago(0.0014), lastWrite: ago(0.004), writes: 'available', freshness: 'current', queued: 0 },
  email: { status: 'partial', lastReceived: ago(0.0021), lastSent: ago(0.0035), groups: [
    { name: 'Client Relations shared mailbox', last: ago(0.0021), state: 'current' },
    { name: 'Underwriting shared mailbox', last: ago(0.0028), state: 'current' },
    { name: 'Advisor Services shared mailbox', last: ago(0.236), state: 'stale' },
    { name: 'Accounting shared mailbox', last: ago(0.0042), state: 'current' },
  ] },
  engine: { lastFull: ago(0.019), current: 'idle', failed24: 2, queue: 0, evaluated: renewals.length },
};

const ROLES = [
  { id: 'cr', name: 'Alex Reyes', role: 'Client Relations', can: ['review', 'send', 'edit', 'discard', 'redirect', 'suppress', 'hold', 'resume', 'classify', 'match'] },
  { id: 'uw', name: 'Kwame Osei', role: 'Underwriting', can: ['review', 'classify', 'uw'] },
  { id: 'ca', name: 'Margot Duclos', role: 'Coverage Approver', can: ['grid', 'correct', 'reject', 'approve', 'map', 'classify'] },
  { id: 'ac', name: 'Lin Okonjo', role: 'Accounting', can: ['receipt', 'classify'] },
  { id: 'aa', name: 'Rae Alvarez', role: 'Automation Administrator', can: ['automation', 'review'] },
  { id: 'sa', name: 'Devin Park', role: 'System Administrator', can: ['system'] },
];

Object.assign(window, {
  MD: { TODAY, CYCLE, renewals, byId, advisors, drafts, exceptions, audits, automation, automationLog, mappings, cycle, health, ROLES, B, DAY, ago, daysTo, dl },
});
