const DIRECTIONS = {
  switchboard: {
    name: "Switchboard",
    short: "Complete causal circuits",
    thesis:
      "Every row carries consequence, proof, your word, machine work, and receipt in one scan.",
    tradeoff: "Fastest and densest; the visual identity must avoid feeling merely tabular.",
  },
  loom: {
    name: "Causal Loom",
    short: "One selected thread",
    thesis:
      "The field stays fixed while one consequence unfolds as a continuous causal thread.",
    tradeoff: "Strongest signature; selection carries more weight than broad parallel scanning.",
  },
  plot: {
    name: "Live Plot",
    short: "Change and consequence share time",
    thesis:
      "Current work and machine events occupy the same time field, making why-now immediately visible.",
    tradeoff: "Best at change awareness; the plot must not slow ordinary row actions.",
  },
};

const ITEMS = [
  {
    id: "t-14",
    band: "now",
    signal: "alert",
    age: "due 10:00",
    title: "Send Jullian the pilot pricing",
    why: "His yes landed at 06:41. Pricing is the only open number.",
    consequence: "The 10:00 call starts with terms in his hands.",
    proof: {
      type: "fact",
      label: "Exact reply",
      text: '"Let us do the pilot - send terms."',
      source: "Gmail thread, observed 06:41",
    },
    word: {
      question: "Which tier should the draft use?",
      options: ["3-property tier", "10-property tier"],
      tried: "June thread names three properties. No signed tier exists.",
    },
    machine: {
      state: "waiting",
      action: "Draft is ready in two variants",
      units: "2 variants / 5 sources",
    },
    outcome: "Nothing has been placed or sent.",
    receipt: "parse rcpt_2921 / no provider effect",
    verb: "Choose and draft",
  },
  {
    id: "t-15",
    band: "now",
    signal: "alert",
    age: "day 2",
    title: "Robert's term-sheet redline",
    why: "He changed clauses 4 and 7 and asked twice.",
    consequence: "Two board decisions remain blocked on your reading.",
    proof: {
      type: "fact",
      label: "Redline v3",
      text: "Clauses 4 and 7 differ from your accepted version.",
      source: "Drive, observed Wednesday",
    },
    word: null,
    machine: {
      state: "ready",
      action: "Marked both changes and checked prior approvals",
      units: "2 changes / 4 sources",
    },
    outcome: "A marked comparison is ready.",
    receipt: "read-only rcpt_2917 / no reply drafted",
    verb: "Open marked redline",
  },
  {
    id: "t-16",
    band: "now",
    signal: "gate",
    age: "23 min",
    title: "Churn brief is holding for your read",
    why: "Both checks passed after one named rejection.",
    consequence: "Your approval releases the brief to the board draft.",
    proof: {
      type: "fact",
      label: "Quality check",
      text: "Nine claims have receipts; two unsupported claims were repaired.",
      source: "eff_31 run 3, checked 08:39",
    },
    word: {
      question: "Use the repaired brief as the board draft?",
      options: ["Approve the brief", "Send it back"],
      tried: "Foreman rejected draft 1 for two missing receipts. Draft 2 passed.",
    },
    machine: {
      state: "waiting",
      action: "Holding at your gate",
      units: "7 / 7 steps complete",
    },
    outcome: "Board draft remains local.",
    receipt: "run rcpt_2894 / external draft not placed",
    verb: "Inspect the brief",
  },
  {
    id: "t-17",
    band: "ready",
    signal: "ok",
    age: "1 day",
    title: "Approve the dunning rewrite",
    why: "Only two sentences changed from the July version.",
    consequence: "The updated draft can be placed in Gmail for your send.",
    proof: {
      type: "maybe",
      label: "Machine read",
      text: "The public 31% recovery line may reveal internal performance.",
      source: "Pulled in because 0 of 4 prior sends used internal rates",
    },
    word: {
      question: "Include the 31% recovery line publicly?",
      options: ["Keep it internal", "Include the number"],
      tried: "Checked four prior sends; none shared the internal rate.",
    },
    machine: {
      state: "ready",
      action: "Tracked-change draft prepared",
      units: "2 changed sentences",
    },
    outcome: "No Gmail draft exists yet.",
    receipt: "prepare rcpt_2887 / send unavailable by design",
    verb: "Review the two changes",
  },
  {
    id: "t-18",
    band: "ready",
    signal: "ok",
    age: "3 days",
    title: "Book the Rentvine board slot for the 19th",
    why: "Three of four have said yes; the room decides it.",
    consequence: "The date becomes the working board slot.",
    proof: {
      type: "fact",
      label: "Calendar read",
      text: "Three accepted. Marcus has not replied.",
      source: "Calendar and Slack, observed 08:04",
    },
    word: {
      question: "Include Marcus even though he has not replied?",
      options: ["Include him", "Wait for his reply"],
      tried: "His assistant usually answers within a day; nothing yet.",
    },
    machine: {
      state: "ready",
      action: "Invite prepared with fallback on the 21st",
      units: "4 recipients / 2 dates",
    },
    outcome: "No calendar invite has been sent.",
    receipt: "prepare rcpt_2879 / calendar unchanged",
    verb: "Pick the slot",
  },
  {
    id: "t-19",
    band: "ready",
    signal: "ok",
    age: "4 hours",
    title: "Read the churn brief's sources",
    why: "Nine sources are gathered; two maybes want judgment.",
    consequence: "You can challenge the recommendation before the board sees it.",
    proof: {
      type: "maybe",
      label: "Machine read",
      text: "The March dip looks seasonal rather than product-driven.",
      source: "Pulled in because the same dip appears in 2025",
    },
    word: null,
    machine: {
      state: "working",
      action: "Comparing cancellation reasons to price changes",
      units: "9 sources / 3 cohorts",
    },
    outcome: "Working brief updated at 08:44.",
    receipt: "analysis rcpt_2868 / no board draft changed",
    verb: "Open gathered proof",
  },
  {
    id: "t-20",
    band: "waiting",
    signal: "wait",
    age: "Monday",
    title: "Dana's reimbursement sign-off",
    why: "You sent Tuesday; it resurfaces Monday if no reply.",
    consequence: "Policy rollout waits without creating another follow-up chore.",
    proof: {
      type: "fact",
      label: "Your send",
      text: "Policy request delivered Tuesday at 14:02.",
      source: "Slack receipt rcpt_2812",
    },
    word: null,
    machine: {
      state: "waiting",
      action: "Watching for Dana's reply",
      units: "resurface rule / Monday",
    },
    outcome: "No nudge has been drafted.",
    receipt: "watch rcpt_2812 / no repeated message",
    verb: "Draft a quiet nudge",
  },
  {
    id: "t-21",
    band: "waiting",
    signal: "wait",
    age: "day 5",
    title: "Rentvine API rate-limit ticket",
    why: "Their last word was escalated. They usually answer in three days.",
    consequence: "The integration remains capped until support responds.",
    proof: {
      type: "fact",
      label: "Support state",
      text: "Escalated to engineering; no new reply since Monday.",
      source: "Rentvine ticket 4471",
    },
    word: null,
    machine: {
      state: "failed",
      action: "Ticket poll failed closed at 07:58",
      units: "credential expired / no fallback",
    },
    outcome: "Last verified ticket state remains visible.",
    receipt: "failure rcpt_2804 / stale data not substituted",
    verb: "Research the missing access",
  },
  {
    id: "t-22",
    band: "changed",
    signal: "gate",
    age: "overnight",
    title: "Three churn notes changed the recommendation",
    why: "Two of three cancellations now name the June increase.",
    consequence: "The board brief should lead with price pressure, not product gaps.",
    proof: {
      type: "maybe",
      label: "Changed read",
      text: "Price-driven is better supported than product-driven.",
      source: "3 exit notes, observed since yesterday",
    },
    word: null,
    machine: {
      state: "completed",
      action: "Re-ranked the recommendation with reasons",
      units: "2 supporting / 1 neutral",
    },
    outcome: "The recommendation changed; prior wording remains struck through.",
    receipt: "judgment rcpt_2798 / prior read preserved",
    verb: "Show what changed",
  },
];

const BASE_EVENTS = [
  {
    id: "ev-1",
    itemId: "t-14",
    kind: "did",
    time: "09:12",
    text: "Prepared two Jullian pricing drafts from five sources.",
    didNot: "Did not place a Gmail draft. Did not send anything.",
  },
  {
    id: "ev-2",
    itemId: "t-19",
    kind: "thinks",
    time: "08:44",
    text: "Changed churn read from product-driven to price-driven.",
    didNot: "Did not replace the board recommendation without preserving the prior read.",
  },
  {
    id: "ev-3",
    itemId: "t-16",
    kind: "saw",
    time: "08:12",
    text: 'Foreman rejected draft 1: "no receipts on two claims."',
    didNot: "Did not accept a worker's done state as completion.",
  },
  {
    id: "ev-4",
    itemId: "t-21",
    kind: "did",
    time: "07:58",
    text: "Stopped the ticket poll after the credential failed.",
    didNot: "Did not substitute the last response as current.",
  },
];

const EFFORTS = {
  e31: {
    id: "eff_31",
    title: "Churn brief for the board thread",
    goal: "Figure out what is behind the cancellations and brief the board.",
    needs: "2 hours / Stripe and Rentvine read / no external sends",
    current: "Holding at your gate after draft 2 passed both checks.",
    runs: ["run 1 / 6 steps / 38s", "run 2 / 7 steps / 44s", "run 3 / 7 steps / 41m"],
    nodes: [
      ["Kick-off", "Your exact words", "08:02", "Goal preserved verbatim."],
      ["Plan attacked", "Foreman and second planner", "08:05", "Two weak assumptions removed."],
      ["Research", "Nine sources", "08:12", "Every claim linked to proof."],
      ["Sent back", "Draft 1 rejected", "08:12", "No receipts on two claims."],
      ["Checked", "Draft 2 passed", "08:39", "Seven of seven steps complete."],
      ["Your gate", "Use the repaired brief?", "now", "Nothing reaches the board without your word."],
    ],
  },
  e32: {
    id: "eff_32",
    title: "Pilot-pricing sensitivity check",
    goal: "Compare the three-property tier to the June quote.",
    needs: "12 minutes / pricing history / read-only",
    current: "Comparing the latest two quotes.",
    runs: ["run 1 / step 2 of 4 / 12m"],
    nodes: [
      ["Plan", "Bound the comparison", "09:01", "Three-property tier only."],
      ["Working", "Read four sources", "now", "No draft created yet."],
    ],
  },
};

const LEARNED_PATTERNS = [
  {
    id: "learn-1",
    claim: "Robert threads move up when he asks twice.",
    math: "7 of 8 replies landed within 11 minutes after a second ask.",
    consequence: "Robert-related consequences receive a 1.4x rank lift.",
    health: "healthy",
  },
  {
    id: "learn-2",
    claim: "A churn signal is usually checked against Stripe first.",
    math: "2 of 2 observed sequences. Needs one more example to hold.",
    consequence: "Offered as a move, never assumed.",
    health: "learning",
  },
];

const CAPABILITY = {
  title: "Keep the Rentvine ticket current without polling",
  failure: "The ticket credential expired at 07:58. Last verified state remains visible.",
  proposal: "Use a read-only webhook subscriber and retain polling only as a named fallback.",
  takes: "One scoped token / 35 minutes / one replay test / no write surface",
  rehearsal: [
    "Subscribed to the sandbox webhook in 210 ms.",
    "Replayed yesterday's 41 events with zero misses.",
    "Confirmed the token exposes read only.",
    "Produced receipts rcpt_2930 through rcpt_2933.",
  ],
};

const TOPIC_DIGS = {
  rentfinder: {
    name: "RentFinder",
    query: "rentfinder pricing",
    summary:
      "Pricing, pilot movement, and promises reconstructed from the permitted fixture record.",
    entries: [
      {
        id: "rf-1",
        time: "06:41",
        actor: "Jullian",
        text: "Replied yes to the pilot and asked for terms.",
        source: "Gmail thread / msg_741",
        observed: "today 06:41",
        reason: "This reply moved pilot pricing into Needs you now.",
        itemId: "t-14",
      },
      {
        id: "rf-2",
        time: "Jul 30",
        actor: "Work OS",
        text: "The promised July dunning draft was placed locally with a receipt.",
        source: "Tape receipt rcpt_2790",
        observed: "Jul 30 14:12",
        reason: "This is the nearest completed example of the same draft custody.",
        itemId: "t-17",
        kept: true,
      },
      {
        id: "rf-3",
        time: "Jul 18",
        actor: "You",
        text: 'Promised Jullian: "I will send terms this week." It never went out.',
        source: "Notion pricing v2 comment / block_118",
        observed: "Jul 18 11:06",
        reason: "No completion receipt exists in any permitted fixture source.",
        itemId: "t-14",
        undone: true,
      },
      {
        id: "rf-4",
        time: "Jun 02",
        actor: "Stripe",
        text: "Price changed from $49 to $59 per property.",
        source: "Stripe price event / price_59",
        observed: "Jun 02 09:00",
        reason: "This change defines the pricing window in the current pilot thread.",
        itemId: "t-14",
      },
    ],
    coverage: [
      ["Notion", "214 fixture pages scanned", "2 hits"],
      ["Slack", "4 permitted channels scanned", "11 hits"],
      ["Calendar", "96 fixture events scanned", "3 hits"],
      ["Stripe", "1,412 fixture events scanned", "4 hits"],
      ["The tape", "Work OS append-only record", "7 hits"],
    ],
    excluded: [
      "Two denied Drive documents were named but not read.",
      "Voice notes are not connected.",
      "This prototype uses fixtures and contacts no provider.",
    ],
  },
  rentvine: {
    name: "Rentvine board",
    query: "rentvine board",
    summary:
      "Board timing, Robert's redline, and the support ticket reconstructed together.",
    entries: [
      {
        id: "rv-1",
        time: "Wed",
        actor: "Robert",
        text: "Redline v3 changed clauses 4 and 7.",
        source: "Drive redline v3 / file_447",
        observed: "Wednesday 09:12",
        reason: "The changed clauses block two board decisions.",
        itemId: "t-15",
      },
      {
        id: "rv-2",
        time: "Mon",
        actor: "Rentvine",
        text: "Ticket 4471 was escalated to engineering.",
        source: "Support ticket 4471",
        observed: "Monday 13:44",
        reason: "This is the last verified state before the credential failed.",
        itemId: "t-21",
      },
      {
        id: "rv-3",
        time: "Tue",
        actor: "You",
        text: 'Promised Robert: "Clauses by Friday." It is still open.',
        source: "Slack board thread / msg_922",
        observed: "Tuesday 14:18",
        reason: "No reply receipt exists after the promise.",
        itemId: "t-15",
        undone: true,
      },
    ],
    coverage: [
      ["Drive", "18 permitted board files scanned", "5 hits"],
      ["Slack", "2 board channels scanned", "9 hits"],
      ["Calendar", "12 board events scanned", "4 hits"],
      ["The tape", "Work OS append-only record", "5 hits"],
    ],
    excluded: [
      "The live support endpoint is unavailable after credential expiry.",
      "This prototype does not substitute stale provider data.",
    ],
  },
  automation: {
    name: "Automation",
    query: "automation failures",
    summary:
      "Clean runs, named failures, and the capability proposal reconstructed together.",
    entries: [
      {
        id: "au-1",
        time: "07:58",
        actor: "Work OS",
        text: "Stopped the ticket poll after the credential failed.",
        source: "Failure receipt rcpt_2804",
        observed: "today 07:58",
        reason: "Failing closed preserved the last verified ticket state.",
        itemId: "t-21",
      },
      {
        id: "au-2",
        time: "08:12",
        actor: "Foreman",
        text: "Rejected churn brief draft 1 because two claims lacked receipts.",
        source: "Run eff_31 / node 4",
        observed: "today 08:12",
        reason: "The rejection proves returned work was judged before completion.",
        itemId: "t-16",
      },
    ],
    coverage: [
      ["Run events", "14 completed fixture runs scanned", "14 hits"],
      ["Failures", "1 named failure scanned", "1 hit"],
      ["The tape", "Work OS append-only record", "6 hits"],
    ],
    excluded: [
      "No provider write surface was inspected.",
      "This prototype contacts no automation runtime.",
    ],
  },
};

const PEOPLE = [
  {
    id: "dana",
    name: "Dana",
    court: "them",
    courtText: "Waiting on them - policy sign-off",
    age: "3d",
    relatedItem: "t-20",
    last: "Tuesday 14:02 - your policy request",
    open: "1 open item",
    promise: "No promise owed by you",
    change:
      "Work OS moved the court from unassigned to Dana and set a Monday resurface.",
    rule: 'If quiet past the weekend, prepare a nudge for review.',
  },
  {
    id: "robert",
    name: "Robert",
    court: "you",
    courtText: "You owe a reply - clauses 4 and 7",
    age: "2d",
    relatedItem: "t-15",
    last: "Wednesday 09:12 - his Slack ask",
    open: "2 board decisions",
    promise: '1 promise - "clauses by Friday"',
    change: "Redline v3 changed clauses 4 and 7 from the accepted version.",
    rule: "If no reply by Tuesday, the thread resurfaces with this draft receipt.",
  },
  {
    id: "sara",
    name: "Sara",
    court: "quiet",
    courtText: "Quiet - one meeting moved",
    age: "1d",
    relatedItem: "t-18",
    last: "Yesterday 16:20 - design review moved",
    open: "1 calendar item",
    promise: "No outstanding promise",
    change: "Design review moved to Thursday at 11:00.",
    rule: "No automatic follow-up is needed.",
  },
  {
    id: "jullian",
    name: "Jullian",
    court: "you",
    courtText: "His reply moved the ball to you",
    age: "2h",
    relatedItem: "t-14",
    last: "Today 06:41 - his pilot reply",
    open: "1 pilot-pricing item",
    promise: '1 promise - "terms this week"',
    change: "Waiting-on changed from Jullian to you; next step changed to pricing.",
    rule: "If no reply after a reviewed draft, resurface Wednesday.",
  },
];

const WEEK_SUMMARY = {
  label: "Week 32",
  window: "Mon Aug 3 - Fri Aug 7",
  decisions: 23,
  efforts: 14,
  gates: 9,
  promisesKept: 6,
  promisesTotal: 8,
  biggestReceipt:
    'Jullian said, "Let us do the pilot - send terms." Pricing went out the same morning.',
  carries: [
    "Intro Dana and Marcus - promised Tuesday, still undone.",
    "June reconciliation - failed closed on an expired token.",
    'Churn read "price-driven" - remains a maybe.',
    "Merchant rule - demonstrated rehearsal is ready for one-shot approval.",
  ],
};

const state = {
  direction: "switchboard",
  theme: localStorage.getItem("work-os-v2-theme") || "light",
  selected: "t-14",
  expanded: "t-14",
  answered: {},
  sayOpen: null,
  sayValues: {},
  actioned: {},
  commandReceipt: null,
  traceOpen: null,
  drawer: null,
  mobileMachine: false,
  notice: null,
  events: [...BASE_EVENTS],
  tapeFilter: "all",
  stoppedEfforts: {},
  selectedEffortNode: 3,
  proposedEffort: null,
  judgments: {},
  learned: {
    mathOpen: {},
    correctionOpen: null,
    corrections: {},
  },
  digRuns: {},
  selectedDigEntry: null,
  digFollowups: {},
  personDrafts: {},
  draft: {
    itemId: null,
    stage: "review",
    placed: false,
    receipt: null,
  },
  week: {
    status: "open",
    closeReceipt: null,
    history: [],
  },
  capability: {
    stage: "failed",
    oneShotUsed: false,
    grantReceipt: null,
    runReceipt: null,
  },
  undo: null,
};

const embedded = true;
let drawerOrigin = null;
let undoTimer = null;

function esc(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

function itemById(id) {
  return ITEMS.find((item) => item.id === id);
}

function answerFor(item) {
  return state.answered[item.id] || null;
}

function interpretationFor(item) {
  const answer = answerFor(item);
  if (!answer) return null;
  const known = {
    "3-property tier": "Use the three-property price in both local draft variants.",
    "10-property tier": "Use the ten-property price in both local draft variants.",
    "Approve the brief": "Release the repaired brief to the local board-draft stage.",
    "Send it back": "Return the brief to the foreman with Nathan's judgment attached.",
    "Keep it internal": "Remove the 31% recovery figure from the outbound draft.",
    "Include the number": "Keep the 31% recovery figure in the outbound draft for review.",
    "Include him": "Prepare Marcus as a recipient in the calendar draft.",
    "Wait for his reply": "Hold the calendar draft until Marcus answers.",
  };
  return known[answer] || `Treat "${answer}" as the governing judgment for ${item.id}.`;
}

function currentMachine(item) {
  if (state.actioned[item.id]) {
    return {
      state: "completed",
      action: state.actioned[item.id],
      units: "visible local prototype state",
    };
  }
  if (answerFor(item)) {
    return {
      state: "working",
      action: `Using your word: ${answerFor(item)}`,
      units: "resumed from the same checkpoint",
    };
  }
  return item.machine;
}

function receiptFor(item) {
  if (state.actioned[item.id]) {
    return `prototype rcpt_${item.id.replace("-", "")} / no external effect`;
  }
  if (answerFor(item)) {
    return `word rcpt_${item.id.replace("-", "")} / "${answerFor(item)}"`;
  }
  return item.receipt;
}

function directionBar() {
  return "";
}

function topLine() {
  return `
    <header class="os-line">
      <button class="brand" data-action="home" aria-label="Return to top item">
        <span class="status-lamp signal-alert"></span>
        <span>WORK OS</span>
      </button>
      <div class="command-wrap">
        <span class="command-mark">&gt;</span>
        <input
          id="command-input"
          value=""
          autocomplete="off"
          spellcheck="false"
          placeholder='type to act - "snooze t-15 until monday"'
          aria-label="Command line"
        />
        <div class="parse-readout" id="parse-readout" hidden></div>
      </div>
      <div class="line-state">
        <span><b>${ITEMS.filter((item) => currentMachine(item).state === "working").length}</b> working</span>
        <span><b>${ITEMS.filter((item) => item.word && !answerFor(item)).length}</b> need your word</span>
      </div>
      <button
        class="icon-button line-help"
        data-action="drawer"
        data-drawer="help"
        aria-label="Open keyboard map"
        title="Keyboard map"
      >?</button>
      <button class="icon-button theme-button" data-action="theme">
        ${state.theme === "light" ? "NIGHT" : "DAY"}
      </button>
    </header>
  `;
}

function watchStrip() {
  return `
    <nav class="watch-strip" aria-label="Standing topics">
      <span class="watch-label">WATCH</span>
      <button data-action="drawer" data-drawer="topic-rentfinder">
        <span class="status-lamp signal-alert"></span>
        <b>RentFinder</b>
        <span>churn +3 / pilot yes</span>
      </button>
      <button data-action="drawer" data-drawer="topic-rentvine">
        <span class="status-lamp signal-wait"></span>
        <b>Rentvine board</b>
        <span>redline v3 / 3 of 4 yes</span>
      </button>
      <button data-action="drawer" data-drawer="topic-automation">
        <span class="status-lamp signal-ok"></span>
        <b>Automation</b>
        <span>14 clean / 1 named failure</span>
      </button>
      <button data-action="drawer" data-drawer="people">
        <span class="status-lamp signal-gate"></span>
        <b>People</b>
        <span>2 your court / 1 waiting</span>
      </button>
      <button data-action="drawer" data-drawer="learned">
        <span class="status-lamp signal-gate"></span>
        <b>Learned</b>
        <span>1 healthy / 1 learning</span>
      </button>
    </nav>
  `;
}

function signalTag(signal, text) {
  return `<span class="signal-tag signal-${signal}">${esc(text)}</span>`;
}

function proofBlock(item, compact = false) {
  return `
    <button
      class="proof-block proof-${item.proof.type} ${compact ? "compact" : ""}"
      data-action="drawer"
      data-drawer="proof-${item.id}"
    >
      <span class="proof-kind">${esc(item.proof.label)}</span>
      <strong>${item.proof.text}</strong>
      <small>${esc(item.proof.source)}</small>
    </button>
  `;
}

function wordBlock(item, compact = false) {
  const answer = answerFor(item);
  if (!item.word) {
    return `
      <div class="word-block no-word ${compact ? "compact" : ""}">
        <span class="station-label">YOUR WORD</span>
        <strong>Not needed</strong>
        <small>The next move is reversible or read-only.</small>
      </div>
    `;
  }
  if (answer) {
    return `
      <div class="word-block answered ${compact ? "compact" : ""}">
        <span class="station-label">YOUR WORD</span>
        <strong>"${esc(answer)}"</strong>
        <small>Recorded verbatim.</small>
        <span class="machine-read">
          <b>MACHINE READ</b>
          ${esc(interpretationFor(item))}
        </span>
        <button class="text-action" data-action="reopen-word" data-id="${item.id}">Reopen</button>
      </div>
    `;
  }
  return `
    <div class="word-block needs-word ${compact ? "compact" : ""}">
      <span class="station-label">NEEDS YOUR WORD</span>
      <strong>${esc(item.word.question)}</strong>
      ${compact ? "" : `<small>Tried first: ${esc(item.word.tried)}</small>`}
      <div class="option-row">
        ${item.word.options
          .map(
            (option) => `
              <button data-action="answer" data-id="${item.id}" data-answer="${esc(option)}">
                ${esc(option)}
              </button>
            `,
          )
          .join("")}
        <button class="say-button" data-action="say-open" data-id="${item.id}">SAY IT</button>
      </div>
      ${
        state.sayOpen === item.id
          ? `
            <form class="say-form" data-say-form="${item.id}">
              <input
                name="say"
                value="${esc(state.sayValues[item.id] || "")}"
                placeholder="whatever you say"
                aria-label="Whatever you say"
              />
              <button type="submit">Record</button>
            </form>
          `
          : ""
      }
    </div>
  `;
}

function machineBlock(item, compact = false) {
  const machine = currentMachine(item);
  return `
    <button
      class="machine-block machine-${machine.state} ${compact ? "compact" : ""}"
      data-action="trace"
      data-id="${item.id}"
    >
      <span class="machine-state">${machine.state.replaceAll("_", " ")}</span>
      <strong>${esc(machine.action)}</strong>
      <small>${esc(machine.units)}</small>
      <span class="trace-link">Open trace</span>
    </button>
  `;
}

function outcomeBlock(item, compact = false) {
  return `
    <div class="outcome-block ${compact ? "compact" : ""}">
      <span class="station-label">OUTCOME</span>
      <strong>${esc(state.actioned[item.id] || item.outcome)}</strong>
      <small>${esc(receiptFor(item))}</small>
    </div>
  `;
}

function heroButton(item) {
  const shortVerb = item.verb.split(" ")[0];
  return `
    <button
      class="hero-verb"
      data-action="hero"
      data-id="${item.id}"
      data-short-verb="${esc(shortVerb)}"
    >
      ${esc(item.verb)}
    </button>
  `;
}

function stationChain(item) {
  return `
    <div class="station-chain">
      <div class="chain-station consequence-station">
        <span class="station-index">1</span>
        <span class="station-label">CONSEQUENCE</span>
        <strong>${esc(item.consequence)}</strong>
        <small>${esc(item.why)}</small>
      </div>
      <div class="chain-station">
        <span class="station-index">2</span>
        ${proofBlock(item, true)}
      </div>
      <div class="chain-station">
        <span class="station-index">3</span>
        ${wordBlock(item, true)}
      </div>
      <div class="chain-station">
        <span class="station-index">4</span>
        ${machineBlock(item, true)}
      </div>
      <div class="chain-station">
        <span class="station-index">5</span>
        ${outcomeBlock(item, true)}
      </div>
      <div class="chain-station receipt-station">
        <span class="station-index">6</span>
        <span class="station-label">RECEIPT</span>
        <strong>${esc(receiptFor(item))}</strong>
        <small>Requested and actual state remain separate.</small>
      </div>
    </div>
  `;
}

function bandTitle(band) {
  return {
    now: "NEEDS YOU NOW",
    ready: "READY",
    waiting: "WAITING",
    changed: "CHANGED",
  }[band];
}

function roomBrief() {
  return `
    <section class="room-brief">
      <p>
        Friday turns on <b>the Jullian pilot</b>. His yes landed overnight.
        Robert's redline is waiting on you, day two.
      </p>
      <div class="brief-counts">
        <button data-action="focus-first-word"><b>${ITEMS.filter((item) => item.word && !answerFor(item)).length}</b> decisions</button>
        <button data-action="drawer" data-drawer="effort-e31"><b>${Object.keys(EFFORTS).length}</b> working</button>
        <button data-action="drawer" data-drawer="capability"><b>${state.capability.stage === "expired" ? 0 : 1}</b> named failure</button>
        <button data-action="trace" data-id="${state.selected}"><b>${state.events.length}</b> receipts since 06:00</button>
      </div>
    </section>
  `;
}

function switchboardRoom() {
  const rows = ["now", "ready", "waiting", "changed"]
    .map((band) => {
      const bandItems = ITEMS.filter((item) => item.band === band);
      return `
        <section class="switch-band" data-band="${band}">
          <header class="band-header">
            <span class="status-lamp signal-${bandItems[0].signal}"></span>
            <b>${bandTitle(band)}</b>
            <span>${bandItems.length}</span>
          </header>
          ${bandItems
            .map((item) => {
              const selected = state.selected === item.id;
              return `
                <article class="switch-row" data-selected="${selected}" data-item="${item.id}">
                  <button class="row-select" data-action="select" data-id="${item.id}">
                    <span class="row-id">${item.id}</span>
                    ${signalTag(item.signal, item.age)}
                  </button>
                  <button class="consequence-cell" data-action="select" data-id="${item.id}">
                    <strong>${esc(item.title)}</strong>
                    <span>${esc(item.why)}</span>
                  </button>
                  <div class="row-proof">${proofBlock(item, true)}</div>
                  <div class="row-word">${wordBlock(item, true)}</div>
                  <div class="row-machine">${machineBlock(item, true)}</div>
                  <div class="row-verb">${heroButton(item)}</div>
                  ${
                    selected
                      ? `
                        <div class="switch-expanded">
                          ${stationChain(item)}
                        </div>
                      `
                      : ""
                  }
                </article>
              `;
            })
            .join("")}
        </section>
      `;
    })
    .join("");

  return `
    <main class="direction-room switchboard-room">
      ${roomBrief()}
      <section class="switch-field">
        <header class="switch-columns" aria-hidden="true">
          <span>STATE</span>
          <span>CONSEQUENCE / WHY NOW</span>
          <span>PROOF</span>
          <span>YOUR WORD</span>
          <span>MACHINE</span>
          <span>MOVE</span>
        </header>
        ${rows}
      </section>
      ${tape()}
    </main>
  `;
}

function compactLedger() {
  return ["now", "ready", "waiting", "changed"]
    .map((band) => {
      const items = ITEMS.filter((item) => item.band === band);
      return `
        <section class="loom-band">
          <header>
            <b>${bandTitle(band)}</b>
            <span>${items.length}</span>
          </header>
          ${items
            .map(
              (item) => `
                <button
                  class="loom-row"
                  data-action="select"
                  data-id="${item.id}"
                  aria-pressed="${state.selected === item.id}"
                >
                  <span class="loom-id">${item.id}</span>
                  <span class="loom-title">${esc(item.title)}</span>
                  <span class="loom-reason">${esc(item.why)}</span>
                  <span class="loom-state signal-${item.signal}">${esc(item.age)}</span>
                </button>
              `,
            )
            .join("")}
        </section>
      `;
    })
    .join("");
}

function loomRoom() {
  const item = itemById(state.selected);
  return `
    <main class="direction-room loom-room">
      <section class="loom-ledger">
        ${roomBrief()}
        ${compactLedger()}
      </section>
      <section class="loom-focus">
        <header class="focus-header">
          <div>
            <span class="focus-kicker">FOLLOWING ${item.id}</span>
            <h1>${esc(item.title)}</h1>
            <p>${esc(item.consequence)}</p>
          </div>
          ${heroButton(item)}
        </header>
        <div class="causal-thread" data-signal="${item.signal}">
          <article class="thread-node thread-left thread-consequence">
            <span class="thread-number">1</span>
            <span class="station-label">CONSEQUENCE / WHY NOW</span>
            <strong>${esc(item.consequence)}</strong>
            <p>${esc(item.why)}</p>
          </article>
          <article class="thread-node thread-right thread-proof">
            <span class="thread-number">2</span>
            ${proofBlock(item)}
          </article>
          <article class="thread-node thread-left thread-word">
            <span class="thread-number">3</span>
            ${wordBlock(item)}
          </article>
          <article class="thread-node thread-right thread-machine">
            <span class="thread-number">4</span>
            ${machineBlock(item)}
          </article>
          <article class="thread-node thread-left thread-outcome">
            <span class="thread-number">5</span>
            ${outcomeBlock(item)}
          </article>
          <article class="thread-node thread-right thread-receipt">
            <span class="thread-number">6</span>
            <span class="station-label">RECEIPT</span>
            <strong>${esc(receiptFor(item))}</strong>
            <p>Nothing external happens without your explicit word.</p>
            <button class="text-action" data-action="trace" data-id="${item.id}">Open raw receipt</button>
          </article>
        </div>
      </section>
      ${tape(true)}
    </main>
  `;
}

function plotMarkers(item) {
  const machine = currentMachine(item);
  const selected = state.selected === item.id;
  return `
    <button
      class="plot-row"
      data-action="select"
      data-id="${item.id}"
      data-selected="${selected}"
    >
      <span class="plot-label">
        <b>${item.id}</b>
        <strong>${esc(item.title)}</strong>
        <small>${esc(item.why)}</small>
      </span>
      <span class="plot-track">
        <i class="track-line"></i>
        <i class="plot-mark proof-mark" style="--x: 18%" title="Proof"></i>
        ${item.word ? `<i class="plot-mark word-mark" style="--x: 42%" title="Your word"></i>` : ""}
        <i class="plot-mark machine-mark machine-${machine.state}" style="--x: 66%" title="Machine work"></i>
        <i class="plot-mark receipt-mark" style="--x: 88%" title="Receipt"></i>
        <span class="plot-now" style="--x: 66%">${esc(machine.state)}</span>
      </span>
      <span class="plot-move">${esc(item.verb)}</span>
    </button>
  `;
}

function plotRoom() {
  const item = itemById(state.selected);
  return `
    <main class="direction-room plot-room">
      ${roomBrief()}
      <section class="plot-field">
        <header class="plot-axis">
          <span>CONSEQUENCE</span>
          <span class="axis-times">
            <i>06:00</i><i>08:00</i><i>NOW</i><i>NEXT</i>
          </span>
          <span>SAFE MOVE</span>
        </header>
        ${ITEMS.map(plotMarkers).join("")}
      </section>
      <section class="plot-inspector">
        <header>
          <div>
            <span class="focus-kicker">${item.id} / SELECTED CAUSAL LINE</span>
            <h1>${esc(item.title)}</h1>
          </div>
          ${heroButton(item)}
        </header>
        ${stationChain(item)}
      </section>
      ${tape()}
    </main>
  `;
}

function tape(compact = false) {
  const filteredEvents = state.events.filter(
    (event) => state.tapeFilter === "all" || event.kind === state.tapeFilter,
  );
  const selectedEvents = filteredEvents.filter(
    (event) =>
      !state.selected || event.itemId === state.selected || event.itemId === "room",
  );
  const visible = selectedEvents.length ? selectedEvents : filteredEvents;
  const counts = state.events.reduce(
    (result, event) => {
      result[event.kind] += 1;
      return result;
    },
    { did: 0, saw: 0, thinks: 0 },
  );
  return `
    <section class="tape ${compact ? "tape-compact" : ""}">
      <header>
        <span class="status-lamp signal-ok"></span>
        <b>THE TAPE</b>
        <span class="tape-count">${state.events.length} events today / showing ${visible.length} tied to ${state.selected} + room</span>
        <button
          class="tape-close-button"
          data-action="drawer"
          data-drawer="week"
        >${state.week.status === "open" ? "REVIEW CLOSE" : "OPEN WEEK RECEIPT"}</button>
      </header>
      <div class="tape-filters">
        ${["all", "did", "saw", "thinks"]
          .map(
            (kind) => `
              <button
                data-action="tape-filter"
                data-filter="${kind}"
                aria-pressed="${state.tapeFilter === kind}"
              >${kind} ${kind === "all" ? state.events.length : counts[kind]}</button>
            `,
          )
          .join("")}
      </div>
      <div class="tape-events">
        ${visible
          .map(
            (event) => `
              <article class="tape-event">
                <time>${event.time}</time>
                <span class="event-kind">${event.kind}</span>
                <p>${esc(event.text)}</p>
                <button data-action="event-trace" data-event="${event.id}">TRACE</button>
              </article>
            `,
          )
          .join("")}
      </div>
    </section>
  `;
}

function mobilePulse() {
  const item = itemById(state.selected);
  const machine = currentMachine(item);
  const needsWord = item.word && !answerFor(item);
  return `
    <div class="mobile-pulse">
      <button class="pulse-select" data-action="mobile-machine">
        <span class="status-lamp signal-${needsWord ? "gate" : machine.state === "failed" ? "alert" : "ok"}"></span>
        <span>
          <b>${needsWord ? "Your word needed" : machine.action}</b>
          <small>${item.id} / ${esc(receiptFor(item))}</small>
        </span>
        <strong>${state.mobileMachine ? "CLOSE" : "OPEN"}</strong>
      </button>
      ${
        state.mobileMachine
          ? `
            <section class="mobile-tray">
              <header>
                <span>MACHINE / ${item.id}</span>
                <button data-action="mobile-machine">Close</button>
              </header>
              ${wordBlock(item)}
              ${machineBlock(item)}
              ${outcomeBlock(item)}
              ${heroButton(item)}
            </section>
          `
          : ""
      }
    </div>
  `;
}

function parseCommand(value) {
  const normalized = value.trim().toLowerCase();
  if (!normalized) return null;
  if (normalized.startsWith("dig ")) {
    return {
      verb: "DIG",
      object: value.trim().slice(4),
      consequence:
        "Reconstructs sourced moments, promises kept or undone, and source coverage in the drawer.",
      nonEffect:
        "The prototype reads fixture state only. It contacts no provider and performs no external effect.",
    };
  }
  if (normalized === "people" || normalized === "open people") {
    return {
      verb: "OPEN PEOPLE",
      object: "people / whose court",
      consequence: "Opens court state, promises, and person records in the shared drawer.",
      nonEffect: "No message is drafted and no person record is changed.",
    };
  }
  const person = PEOPLE.find((entry) =>
    normalized.match(new RegExp(`^(open|show|pull)\\s+${entry.id}$`)),
  );
  if (person) {
    return {
      verb: "OPEN PERSON",
      object: `${person.name} / ${person.courtText}`,
      consequence: "Opens the person's court state, changeset, and local verbs.",
      nonEffect: "No message is drafted or sent.",
      personId: person.id,
    };
  }
  if (normalized === "close week" || normalized === "close week 32") {
    return {
      verb: "REVIEW CLOSE",
      object: `${WEEK_SUMMARY.label} / ${WEEK_SUMMARY.window}`,
      consequence: "Assembles the append-only week ledger in the drawer.",
      nonEffect: "The week does not close until you stamp it. Nothing is sent.",
    };
  }
  if (
    (normalized.includes("draft") || normalized.includes("review")) &&
    normalized.includes("t-17")
  ) {
    return {
      verb: "REVIEW DRAFT",
      object: "t-17 / dunning rewrite",
      consequence: "Opens tracked changes and the draft-only custody boundary.",
      nonEffect: "No Gmail connector is contacted and no email can send.",
    };
  }
  if (normalized.includes("snooze") && normalized.includes("t-15")) {
    return {
      verb: "SNOOZE",
      object: "t-15 / Robert's redline",
      consequence: "Moves out of Needs you now until Monday at 09:00.",
      nonEffect: "No message is sent. The source and receipt remain attached.",
    };
  }
  if (normalized.includes("open") && normalized.includes("t-")) {
    const match = normalized.match(/t-\d+/);
    const item = match ? itemById(match[0]) : null;
    return {
      verb: "OPEN",
      object: item ? `${item.id} / ${item.title}` : "the addressed item",
      consequence: "Selects and expands the object in this room.",
      nonEffect: "No work starts and no external system changes.",
    };
  }
  return {
    verb: "PROPOSE EFFORT",
    object: value.trim(),
    consequence: "Builds an editable plan before any worker starts.",
    nonEffect: "No action begins until you approve the proposal.",
  };
}

function effortDrawer(effort) {
  const stopped = Boolean(state.stoppedEfforts[effort.id]);
  const nodeIndex = Math.min(state.selectedEffortNode, effort.nodes.length - 1);
  const node = effort.nodes[nodeIndex];
  const rejection = node[0] === "Sent back";
  return `
    <section class="drawer-section effort-summary">
      <span class="drawer-label">EFFORT / ${esc(effort.id)}</span>
      <h2>${esc(effort.title)}</h2>
      <p>${esc(effort.goal)}</p>
      <dl class="drawer-facts">
        <div><dt>Needs</dt><dd>${esc(effort.needs)}</dd></div>
        <div><dt>Current</dt><dd>${stopped ? "Stopped by you. Partial work and receipts remain." : esc(effort.current)}</dd></div>
      </dl>
      <div class="drawer-actions">
        <button class="${stopped ? "drawer-primary" : "drawer-danger"}" data-action="toggle-effort" data-effort="${effort.id}">
          ${stopped ? "Resume from the checkpoint" : "Stop this effort"}
        </button>
        <button data-action="effort-result" data-effort="${effort.id}">Open current result</button>
      </div>
    </section>
    <section class="drawer-section">
      <span class="drawer-label">BLUEPRINT / RUN 3 REPLAYING</span>
      <div class="blueprint-list">
        ${effort.nodes
          .map(
            (entry, index) => `
              <button
                class="blueprint-node ${entry[0] === "Sent back" ? "rejected" : ""}"
                data-action="effort-node"
                data-effort="${effort.id}"
                data-node="${index}"
                aria-pressed="${index === nodeIndex}"
              >
                <span>${String(index + 1).padStart(2, "0")}</span>
                <strong>${esc(entry[0])}</strong>
                <small>${esc(entry[1])} / ${esc(entry[2])}</small>
              </button>
            `,
          )
          .join("")}
      </div>
      <div class="run-rail">
        ${effort.runs
          .map((run, index) => `<span data-current="${index === effort.runs.length - 1}">${esc(run)}</span>`)
          .join("")}
      </div>
    </section>
    <section class="drawer-section node-inspector ${rejection ? "named-rejection" : ""}">
      <span class="drawer-label">${rejection ? "NAMED REJECTION - KEPT ON THE RECORD" : "NODE TRACE"}</span>
      <h2>${esc(node[0])}</h2>
      <p><b>Actor:</b> ${esc(node[1])}</p>
      <p><b>When:</b> ${esc(node[2])}</p>
      <p><b>Returned:</b> ${esc(node[3])}</p>
      <div class="did-not">
        <b>DID NOT</b>
        <p>${
          rejection
            ? "Did not accept a worker's done state. Draft 1 remains visible beside the repaired draft."
            : "Did not hide the inputs, returned work, or checkpoint."
        }</p>
      </div>
    </section>
  `;
}

function proposedEffortDrawer() {
  const effort = state.proposedEffort;
  if (!effort) {
    return `
      <section class="drawer-section">
        <span class="drawer-label">EFFORT PROPOSAL</span>
        <h2>No proposal is open.</h2>
        <p>Type a sentence in the line. Unrecognized work becomes an editable proposal before anything starts.</p>
      </section>
    `;
  }
  return `
    <section class="drawer-section">
      <span class="drawer-label">EFFORT PROPOSAL / ${esc(effort.status)}</span>
      <h2>${esc(effort.goal)}</h2>
      <p>Nothing runs before you approve this plan.</p>
    </section>
    <form class="effort-form" data-effort-form>
      <label>
        Goal
        <textarea name="goal" rows="2">${esc(effort.goal)}</textarea>
      </label>
      <label>
        Plan - one step per line
        <textarea name="plan" rows="7">${esc(effort.plan.join("\n"))}</textarea>
      </label>
      <button class="drawer-primary" type="submit">Save the edited proposal</button>
    </form>
    <section class="drawer-section">
      <span class="drawer-label">BOUNDARY</span>
      <p>Read-only research and local artifact preparation. No message, provider write, or external effect.</p>
      <div class="drawer-actions">
        ${
          effort.status === "running"
            ? `<button class="drawer-danger" data-action="stop-proposed-effort">Stop and keep partial work</button>`
            : `<button class="drawer-primary" data-action="approve-effort-proposal">Approve and start locally</button>
               <button data-action="hold-effort-proposal">Not now</button>`
        }
      </div>
    </section>
  `;
}

function learnedDrawer() {
  return `
    <section class="drawer-section">
      <span class="drawer-label">WHAT IT HAS LEARNED</span>
      <h2>Receipts, not vibes</h2>
      <p>Patterns stay quiet in the room. Their arithmetic and corrections remain available here.</p>
    </section>
    <section class="learned-list">
      ${LEARNED_PATTERNS.map((pattern) => {
        const correction = state.learned.corrections[pattern.id];
        const mathOpen = Boolean(state.learned.mathOpen[pattern.id]);
        const correctionOpen = state.learned.correctionOpen === pattern.id;
        return `
          <article class="learned-pattern">
            <header>
              <span class="health-chip" data-health="${pattern.health}">${esc(pattern.health)}</span>
              <span>${esc(pattern.id)}</span>
            </header>
            <h3 class="${correction ? "struck-reading" : ""}">${esc(pattern.claim)}</h3>
            ${
              correction
                ? `<h3 class="corrected-reading">${esc(correction.text)}</h3>
                   <p class="correction-receipt">${esc(correction.receipt)} / prior read remains struck through</p>`
                : ""
            }
            <p>${esc(pattern.consequence)}</p>
            ${
              mathOpen
                ? `<div class="learned-math"><b>THE MATH</b><span>${esc(pattern.math)}</span></div>`
                : ""
            }
            <div class="drawer-actions">
              <button data-action="toggle-learned-math" data-pattern="${pattern.id}">
                ${mathOpen ? "Hide the math" : "Show the math"}
              </button>
              <button data-action="open-learned-correction" data-pattern="${pattern.id}">
                ${correctionOpen ? "Cancel correction" : "Correct this read"}
              </button>
            </div>
            ${
              correctionOpen
                ? `
                  <form class="correction-form" data-learned-form="${pattern.id}">
                    <label>
                      Your correction
                      <textarea name="correction" rows="3" placeholder="Say what the machine got wrong."></textarea>
                    </label>
                    <button class="drawer-primary" type="submit">Append the correction</button>
                  </form>
                `
                : ""
            }
          </article>
        `;
      }).join("")}
    </section>
  `;
}

function capabilityDrawer() {
  const stage = state.capability.stage;
  const stageCopy = {
    failed: "Named failure",
    researched: "Demonstrated proposal",
    armed: "One-shot authority armed",
    expired: "One-shot used - grant expired",
  }[stage];
  return `
    <section class="drawer-section">
      <span class="drawer-label">COULD DO MORE / ${esc(stageCopy)}</span>
      <h2>${esc(CAPABILITY.title)}</h2>
      <p>${esc(CAPABILITY.failure)}</p>
      <div class="did-not">
        <b>SAFE CURRENT STATE</b>
        <p>The last verified ticket state remains visible. No stale response is presented as current.</p>
      </div>
    </section>
    ${
      stage === "failed"
        ? `
          <section class="drawer-section">
            <span class="drawer-label">HOMEWORK STARTS HERE</span>
            <p>The machine can research a narrower path without receiving write authority.</p>
            <button class="drawer-primary" data-action="capability-research">Research what it takes</button>
          </section>
        `
        : ""
    }
    ${
      ["researched", "armed", "expired"].includes(stage)
        ? `
          <section class="drawer-section">
            <span class="drawer-label">PROPOSAL</span>
            <h2>${esc(CAPABILITY.proposal)}</h2>
            <p>${esc(CAPABILITY.takes)}</p>
          </section>
          <section class="drawer-section">
            <span class="drawer-label">DEMONSTRATED REHEARSAL</span>
            <div class="rehearsal-log">
              ${CAPABILITY.rehearsal.map((line) => `<p>${esc(line)}</p>`).join("")}
            </div>
          </section>
        `
        : ""
    }
    ${
      stage === "researched"
        ? `
          <section class="drawer-section">
            <span class="drawer-label">ONE-SHOT SCOPE</span>
            <p>Read one webhook replay, update this local ticket state once, then destroy the grant.</p>
            <button class="drawer-primary" data-action="capability-arm">Approve one demonstrated run</button>
          </section>
        `
        : ""
    }
    ${
      stage === "armed"
        ? `
          <section class="drawer-section one-shot-armed">
            <span class="drawer-label">YOUR WORD RECORDED</span>
            <h2>Run the demonstrated read once</h2>
            <p>${esc(state.capability.grantReceipt)} / authority expires on use</p>
            <button class="drawer-primary" data-action="capability-run-once">Use the one-shot grant</button>
          </section>
        `
        : ""
    }
    ${
      stage === "expired"
        ? `
          <section class="drawer-section verified-result">
            <span class="drawer-label">RESULT / GRANT EXPIRED</span>
            <h2>41 replay events read. Zero provider writes.</h2>
            <p>${esc(state.capability.runReceipt)}</p>
            <pre class="raw-receipt">requested: one read-only replay
actual: 41 events inspected / 0 missed
provider_write: none
grant_state: expired
reusable_authority: none</pre>
          </section>
        `
        : ""
    }
  `;
}

function draftDrawer() {
  const item = itemById(state.draft.itemId || "t-17");
  const answer = answerFor(item);
  const stage = state.draft.stage;
  return `
    <section class="drawer-section">
      <span class="drawer-label">DRAFT REVIEW / GMAIL CUSTODY</span>
      <h2>Dunning rewrite for Carla Martinez</h2>
      <p>Prototype only: this demonstrates the bridge contract. No Gmail connector is contacted.</p>
    </section>
    <section class="draft-custody" data-stage="${stage}">
      <div><span>1</span><b>Draft</b><small>v2 / two changed sentences</small></div>
      <div><span>2</span><b>Your word</b><small>${answer ? esc(answer) : "still needed"}</small></div>
      <div><span>3</span><b>Gmail draft</b><small>${state.draft.placed ? "prototype receipt verified" : "not placed"}</small></div>
    </section>
    <section class="drawer-section draft-copy">
      <span class="drawer-label">TRACKED CHANGES</span>
      <p><b>To:</b> carla@example.com</p>
      <p><b>Subject:</b> A clearer path back to current</p>
      <div class="draft-message">
        <p>Hi Carla,</p>
        <p>I tightened the plan around the two invoices you called out.</p>
        <p><del>Our 31% recovery rate shows the sequence works.</del></p>
        <p class="draft-addition">${
          answer === "Include the number"
            ? "The 31% recovery line remains in this review draft by your word."
            : "The internal recovery figure stays out of the customer-facing draft."
        }</p>
        <p>Nothing changes in the account until you choose the next step.</p>
      </div>
      <p class="machine-interpretation"><b>Machine read:</b> ${esc(interpretationFor(item) || "Waiting for your word.")}</p>
    </section>
    ${
      stage === "review"
        ? `
          <section class="drawer-section">
            <span class="drawer-label">EXACT EFFECT</span>
            <p>Place one editable draft in Nathan's Gmail mailbox. Do not send, label, move, archive, or delete mail.</p>
            <div class="drawer-actions">
              <button class="drawer-primary" data-action="draft-arm">Arm prototype draft placement</button>
              <button data-action="draft-keep-local">Keep it local</button>
            </div>
          </section>
        `
        : ""
    }
    ${
      stage === "confirm"
        ? `
          <section class="drawer-section effect-confirm">
            <span class="drawer-label">CONFIRM THE BOUNDARY</span>
            <h2>Place 1 draft for carla@example.com</h2>
            <p>Requested: create or update one Gmail draft. Non-effect: no email sends and no other mailbox state changes.</p>
            <div class="drawer-actions">
              <button class="drawer-primary" data-action="draft-place">Confirm prototype placement</button>
              <button data-action="draft-back">Back to review</button>
            </div>
          </section>
        `
        : ""
    }
    ${
      stage === "placed"
        ? `
          <section class="drawer-section verified-result">
            <span class="drawer-label">REQUESTED VS ACTUAL</span>
            <h2>Draft custody verified in prototype state</h2>
            <p>${esc(state.draft.receipt)}</p>
            <pre class="raw-receipt">requested: gmail.drafts.upsert
actual: prototype draft state accepted
recipient: carla@example.com
sent: false
other_mailbox_effects: none
production_provider_id: unavailable in prototype</pre>
          </section>
        `
        : ""
    }
  `;
}

function weekDrawer() {
  const history = state.week.history;
  const wasReopened = history.some((entry) => entry.kind === "reopened");
  return `
    <section class="drawer-section">
      <span class="drawer-label">WEEKLY CLOSE / ${esc(WEEK_SUMMARY.label)}</span>
      <h2>${esc(WEEK_SUMMARY.window)}</h2>
      <p>The ledger is assembled from the tape. Nothing closes until you stamp it.</p>
    </section>
    <section class="week-figures">
      <div><strong>${WEEK_SUMMARY.decisions}</strong><span>decisions</span></div>
      <div><strong>${WEEK_SUMMARY.efforts}</strong><span>efforts</span></div>
      <div><strong>${WEEK_SUMMARY.gates}</strong><span>gates</span></div>
      <div><strong>${WEEK_SUMMARY.promisesKept}/${WEEK_SUMMARY.promisesTotal}</strong><span>promises kept</span></div>
    </section>
    <section class="drawer-section">
      <span class="drawer-label">BIGGEST RECEIPT</span>
      <blockquote>${esc(WEEK_SUMMARY.biggestReceipt)}</blockquote>
    </section>
    <section class="drawer-section">
      <span class="drawer-label">CARRIES INTO WEEK 33</span>
      <div class="carry-list">
        ${WEEK_SUMMARY.carries.map((item) => `<p>${esc(item)}</p>`).join("")}
      </div>
    </section>
    ${
      state.week.status === "open"
        ? `
          <section class="drawer-section">
            <span class="drawer-label">${wasReopened ? "REOPENED - PRIOR CLOSE REMAINS BELOW" : "READY TO CLOSE"}</span>
            <p>Closing writes one room receipt and starts the next period. It sends nothing.</p>
            <button class="drawer-primary weekly-close-button" data-action="close-week">
              ${wasReopened ? "Re-stamp week 32" : "Stamp - close week 32"}
            </button>
          </section>
        `
        : `
          <section class="drawer-section verified-result">
            <span class="drawer-label">WEEK CLOSED</span>
            <h2>${esc(state.week.closeReceipt)}</h2>
            <p>The close remains permanent in the tape even if the working week is reopened.</p>
            <button data-action="reopen-week">Reopen until Monday 09:00</button>
          </section>
        `
    }
    ${
      history.length
        ? `
          <section class="drawer-section">
            <span class="drawer-label">APPEND-ONLY CLOSE HISTORY</span>
            <div class="close-history">
              ${history
                .map(
                  (entry) => `
                    <article data-kind="${entry.kind}">
                      <time>${esc(entry.time)}</time>
                      <p>${esc(entry.text)}</p>
                      <small>${esc(entry.receipt)}</small>
                    </article>
                  `,
                )
                .join("")}
            </div>
          </section>
        `
        : ""
    }
  `;
}

function topicDrawer(topicId) {
  const topic = TOPIC_DIGS[topicId] || TOPIC_DIGS.rentfinder;
  const hasRun = Boolean(state.digRuns[topicId]);
  const selected =
    state.selectedDigEntry?.topic === topicId
      ? topic.entries.find((entry) => entry.id === state.selectedDigEntry.id)
      : null;
  const undoneCount = topic.entries.filter((entry) => entry.undone).length;
  const keptCount = topic.entries.filter((entry) => entry.kept).length;
  const currentIds = [
    ...new Set(topic.entries.map((entry) => entry.itemId).filter(Boolean)),
  ];

  return `
    <section class="drawer-section">
      <span class="drawer-label">STANDING TOPIC / ${esc(topic.name)}</span>
      <h2>${esc(topic.name)}</h2>
      <p>${esc(topic.summary)}</p>
      <div class="topic-current">
        <span class="drawer-label">NOW / RELATED CAUSAL OBJECTS</span>
        <div class="drawer-actions">
          ${currentIds
            .map((id) => {
              const item = itemById(id);
              return `<button data-action="dig-related" data-id="${id}">${id} / ${esc(item.title)}</button>`;
            })
            .join("")}
        </div>
      </div>
      <div class="drawer-actions">
        <button class="drawer-primary" data-action="run-dig" data-topic="${topicId}">
          ${hasRun ? "Run the Dig again" : "Run the Dig"}
        </button>
      </div>
    </section>
    ${
      hasRun
        ? `
          <section class="drawer-section dig-summary">
            <span class="drawer-label">DIG / ${esc(topic.query)}</span>
            <h2>${topic.entries.length} sourced moments / ${keptCount} kept / ${undoneCount} promised and undone</h2>
            <p>Reconstructed from the permitted fixture record. Every line below opens its reason and source state.</p>
          </section>
          <section class="drawer-section">
            <span class="drawer-label">THE RECORD / NEWEST FIRST</span>
            <div class="dig-lines">
              ${topic.entries
                .map(
                  (entry) => `
                    <button
                      class="dig-line ${entry.undone ? "undone" : entry.kept ? "kept" : ""}"
                      data-action="dig-entry"
                      data-topic="${topicId}"
                      data-entry="${entry.id}"
                      aria-pressed="${selected?.id === entry.id}"
                    >
                      <time>${esc(entry.time)}</time>
                      <span>
                        <b>${esc(entry.actor)}</b>
                        <span>${esc(entry.text)}</span>
                        <small>${esc(entry.source)}</small>
                      </span>
                      <strong>${entry.undone ? "OPEN PROMISE" : entry.kept ? "KEPT RECEIPT" : "OPEN PROOF"}</strong>
                    </button>
                  `,
                )
                .join("")}
            </div>
          </section>
          ${
            selected
              ? `
                <section class="drawer-section dig-entry-detail ${selected.undone ? "undone" : selected.kept ? "kept" : ""}">
                  <span class="drawer-label">${selected.undone ? "PROMISED / UNDONE" : selected.kept ? "PROMISE / KEPT" : "SOURCED MOMENT"}</span>
                  <h2>${esc(selected.text)}</h2>
                  <p><b>Pulled in because:</b> ${esc(selected.reason)}</p>
                  <div class="source-record">
                    <b>Source identity</b>
                    <span>${esc(selected.source)}</span>
                    <b>Observed</b>
                    <span>${esc(selected.observed)}</span>
                    <b>Role</b>
                    <span>${selected.undone ? "verbatim promise / no completion receipt" : selected.kept ? "completed promise / receipt attached" : "fact inside the fixture boundary"}</span>
                    <b>Native pointer</b>
                    <button data-action="unavailable">Open native pointer</button>
                  </div>
                  <div class="drawer-actions">
                    <button data-action="dig-related" data-id="${selected.itemId}">Open related ${selected.itemId}</button>
                    ${
                      selected.undone
                        ? state.digFollowups[selected.id]
                          ? `<span class="local-result">Local follow-up prepared / receipt dig_${selected.id} / nothing sent</span>`
                          : `<button class="drawer-primary" data-action="dig-followup" data-topic="${topicId}" data-entry="${selected.id}">Prepare a local follow-up</button>`
                        : ""
                    }
                  </div>
                </section>
              `
              : ""
          }
          <section class="drawer-section dig-coverage">
            <span class="drawer-label">SOURCE COVERAGE</span>
            ${topic.coverage
              .map(
                ([name, scope, hits]) => `
                  <div class="coverage-row">
                    <b>${esc(name)}</b>
                    <span>${esc(scope)}</span>
                    <small>${esc(hits)}</small>
                  </div>
                `,
              )
              .join("")}
            <span class="drawer-label coverage-exclusion-label">NOT SEARCHED OR NOT AVAILABLE</span>
            ${topic.excluded
              .map((line) => `<p class="coverage-exclusion">${esc(line)}</p>`)
              .join("")}
          </section>
        `
        : `
          <section class="drawer-section">
            <span class="drawer-label">THE DIG IS READY</span>
            <p>Running it reconstructs sourced moments, promises kept or undone, and an honest coverage footer. It performs no external effect.</p>
          </section>
        `
    }
  `;
}

function peopleDrawer() {
  return `
    <section class="drawer-section">
      <span class="drawer-label">PEOPLE / WHOSE COURT</span>
      <h2>People</h2>
      <p>Sorted by age. Court state is the load-bearing column; each row opens the person's record and local verbs.</p>
    </section>
    <section class="people-table" aria-label="People and court state">
      <div class="people-head" aria-hidden="true">
        <span>WHO</span>
        <span>COURT</span>
        <span>PROMISE</span>
        <span>AGE</span>
      </div>
      ${PEOPLE.map(
        (person) => `
          <button
            class="people-row"
            data-action="person-open"
            data-person="${person.id}"
          >
            <b>${esc(person.name)}</b>
            <span class="court-state court-${person.court}">${esc(person.courtText)}</span>
            <span>${esc(person.promise)}</span>
            <strong>${esc(person.age)}</strong>
          </button>
        `,
      ).join("")}
    </section>
  `;
}

function personDrawer(personId) {
  const person = PEOPLE.find((entry) => entry.id === personId) || PEOPLE[0];
  const draftPrepared = Boolean(state.personDrafts[person.id]);
  return `
    <section class="drawer-section">
      <button class="drawer-back" data-action="people-back">Back to people</button>
      <span class="drawer-label">PERSON / ${esc(person.name)}</span>
      <h2>${esc(person.name)}</h2>
      <p class="court-state court-${person.court}">${esc(person.courtText)} / ${esc(person.age)}</p>
    </section>
    <section class="drawer-section person-facts">
      <div><b>Last interaction</b><span>${esc(person.last)}</span></div>
      <div><b>Open state</b><span>${esc(person.open)}</span></div>
      <div><b>Promise</b><span>${esc(person.promise)}</span></div>
    </section>
    <section class="drawer-section">
      <span class="drawer-label">CHANGESET RECORD</span>
      <p>${esc(person.change)}</p>
      <div class="did-not">
        <b>RESURFACE RULE</b>
        <p>${esc(person.rule)}</p>
      </div>
    </section>
    <section class="drawer-section">
      <span class="drawer-label">LOCAL VERBS</span>
      <div class="drawer-actions">
        <button data-action="person-related" data-id="${person.relatedItem}">Open related ${person.relatedItem}</button>
        <button class="drawer-primary" data-action="person-draft" data-person="${person.id}">
          ${draftPrepared ? "Local draft prepared" : `Prepare a local draft to ${esc(person.name)}`}
        </button>
      </div>
      ${
        draftPrepared
          ? `<div class="local-result">person_${person.id} / local reviewed draft / no provider contacted / nothing sent</div>`
          : ""
      }
    </section>
  `;
}

function helpDrawer() {
  const shortcuts = [
    ["Command-K", "Focus the line"],
    ["j / k", "Move the selected consequence"],
    ["Enter / e", "Run the printed safe move"],
    ["o", "Open the selected proof"],
    ["t", "Open the selected machine trace"],
    ["u", "Undo the live five-second recovery action"],
    ["?", "Open this map"],
    ["Esc", "Close one layer and return"],
  ];
  return `
    <section class="drawer-section">
      <span class="drawer-label">KEYBOARD</span>
      <h2>One room, one grammar</h2>
      <div class="shortcut-list">
        ${shortcuts.map(([key, label]) => `<p><kbd>${esc(key)}</kbd><span>${esc(label)}</span></p>`).join("")}
      </div>
    </section>
  `;
}

function drawer() {
  if (!state.drawer && !state.traceOpen) return "";
  let title = "Everything gathered";
  let body = "";

  if (state.traceOpen) {
    const item = itemById(state.traceOpen);
    const event = state.events.find((entry) => entry.itemId === item.id);
    title = `How ${item.id} ran`;
    body = `
      <section class="drawer-section">
        <span class="drawer-label">CURRENT CLAIM</span>
        <h2>${esc(currentMachine(item).action)}</h2>
        <p>${esc(currentMachine(item).units)}</p>
      </section>
      <section class="trace-steps">
        <article><time>09:11</time><p>Read the exact source and checked its observed time.</p></article>
        <article><time>09:12</time><p>Compared the current object with the prior accepted state.</p></article>
        <article><time>09:12</time><p>Prepared the bounded result and wrote the receipt.</p></article>
      </section>
      <section class="did-not">
        <b>DID NOT</b>
        <p>${esc(event?.didNot || "Did not perform an external effect.")}</p>
      </section>
      <pre class="raw-receipt">intent: ${esc(item.verb)}
object: ${item.id}
requested: local_prototype_change
actual: visible_state_changed
external_effect: none
receipt: ${esc(receiptFor(item))}</pre>
    `;
  } else if (state.drawer.startsWith("proof-")) {
    const id = state.drawer.replace("proof-", "");
    const item = itemById(id);
    title = `${item.id} proof`;
    body = `
      <section class="drawer-section">
        <span class="drawer-label">${esc(item.proof.label)}</span>
        <h2>${esc(item.proof.text)}</h2>
        <p>${esc(item.proof.source)}</p>
      </section>
      <section class="drawer-section">
        <span class="drawer-label">PULLED IN BECAUSE</span>
        <p>${esc(item.why)}</p>
      </section>
      <section class="drawer-section source-record">
        <b>Source identity</b>
        <span>src_${item.id.replace("-", "")}_primary</span>
        <b>Observed</b>
        <span>${esc(item.proof.source)}</span>
        <b>Freshness</b>
        <span>Inside the action boundary</span>
        <b>Native pointer</b>
        <button data-action="unavailable">Open source preview</button>
      </section>
      ${
        item.proof.type === "maybe"
          ? `
            <section class="drawer-section">
              <span class="drawer-label">YOUR JUDGMENT</span>
              ${
                state.judgments[item.id]
                  ? `<p><b>${esc(state.judgments[item.id].decision)}</b> - recorded without changing the claim's maybe origin.</p>
                     <button data-action="reopen-proof-judgment" data-id="${item.id}">Reopen the judgment</button>`
                  : `<div class="drawer-actions">
                       <button class="drawer-primary" data-action="judge-proof" data-id="${item.id}" data-decision="Hold as a maybe">Hold as a maybe</button>
                       <button data-action="judge-proof" data-id="${item.id}" data-decision="Does not apply">Does not apply</button>
                     </div>`
              }
            </section>
          `
          : ""
      }
    `;
  } else if (state.drawer.startsWith("topic-")) {
    const topic = state.drawer.replace("topic-", "");
    title = TOPIC_DIGS[topic]?.name || topic.replaceAll("-", " ");
    body = topicDrawer(topic);
  } else if (state.drawer === "people") {
    title = "People";
    body = peopleDrawer();
  } else if (state.drawer.startsWith("person-")) {
    const personId = state.drawer.replace("person-", "");
    const person = PEOPLE.find((entry) => entry.id === personId);
    title = person?.name || "Person";
    body = personDrawer(personId);
  } else if (state.drawer === "effort-proposal") {
    title = "Editable effort proposal";
    body = proposedEffortDrawer();
  } else if (state.drawer.startsWith("effort-")) {
    const id = state.drawer.replace("effort-", "");
    const effort = EFFORTS[id] || EFFORTS.e31;
    title = `${effort.id} blueprint`;
    body = effortDrawer(effort);
  } else if (state.drawer === "learned") {
    title = "What it has learned";
    body = learnedDrawer();
  } else if (state.drawer === "capability") {
    title = "Could do more";
    body = capabilityDrawer();
  } else if (state.drawer.startsWith("draft-")) {
    title = "Draft review";
    body = draftDrawer();
  } else if (state.drawer === "week") {
    title = `${WEEK_SUMMARY.label} close`;
    body = weekDrawer();
  } else if (state.drawer === "help") {
    title = "Keyboard map";
    body = helpDrawer();
  }

  return `
    <div class="drawer-scrim" data-action="close-drawer"></div>
    <aside class="drawer" aria-label="${esc(title)}">
      <header>
        <span>${esc(title).toUpperCase()}</span>
        <button class="icon-button" data-action="close-drawer">CLOSE</button>
      </header>
      <div class="drawer-body">${body}</div>
    </aside>
  `;
}

function notice() {
  if (!state.notice) return "";
  return `
    <div class="notice" role="status">
      <span>${esc(state.notice)}</span>
      <div class="notice-actions">
        ${
          state.undo
            ? `<button class="undo-button" data-action="undo">Undo <b data-undo-count>${state.undo.remaining}</b></button>`
            : ""
        }
        <button data-action="dismiss-notice">Dismiss</button>
      </div>
    </div>
  `;
}

function render() {
  const room = switchboardRoom();

  document.getElementById("app").innerHTML = `
    ${directionBar()}
    <div
      class="prototype"
      data-direction="${state.direction}"
      data-theme="${state.theme}"
      data-embedded="${embedded}"
    >
      ${topLine()}
      ${watchStrip()}
      ${room}
      ${mobilePulse()}
      ${drawer()}
      ${notice()}
    </div>
  `;
}

function setDirection(direction) {
  state.direction = direction;
  const next = new URL(window.location.href);
  next.searchParams.set("direction", direction);
  window.history.replaceState({}, "", next);
  render();
}

function addEvent(itemId, kind, text, didNot, drawerTarget = null) {
  state.events.unshift({
    id: `ev-${Date.now()}`,
    itemId,
    kind,
    time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
    text,
    didNot,
    drawerTarget,
  });
}

function clearUndo() {
  if (undoTimer) window.clearInterval(undoTimer);
  undoTimer = null;
  state.undo = null;
}

function armUndo(undo) {
  clearUndo();
  state.undo = { ...undo, remaining: 5 };
  undoTimer = window.setInterval(() => {
    if (!state.undo) return;
    state.undo.remaining -= 1;
    const count = document.querySelector("[data-undo-count]");
    if (count) count.textContent = String(Math.max(state.undo.remaining, 0));
    if (state.undo.remaining <= 0) {
      window.clearInterval(undoTimer);
      undoTimer = null;
      state.undo = null;
      document.querySelector('[data-action="undo"]')?.remove();
    }
  }, 1000);
}

function undoLiveAction() {
  const undo = state.undo;
  if (!undo) return;
  clearUndo();
  if (undo.type === "snooze") {
    if (undo.hadPreviousAction) {
      state.actioned[undo.itemId] = undo.previousAction;
    } else {
      delete state.actioned[undo.itemId];
    }
    addEvent(
      undo.itemId,
      "did",
      `Undid the snooze for ${undo.itemId}.`,
      "Did not erase the original snooze receipt.",
    );
    state.notice = `The snooze for ${undo.itemId} was undone. Both events remain on the tape.`;
  }
  render();
}

function actOnHero(item) {
  if (item.word && !answerFor(item)) {
    state.selected = item.id;
    state.expanded = item.id;
    state.notice = `${item.id} needs your word first. The options and their consequences are now in view.`;
    return;
  }
  if (item.id === "t-17") {
    state.draft.itemId = item.id;
    state.drawer = "draft-t17";
    state.traceOpen = null;
    state.notice = "The draft is open for review. No Gmail connector is contacted by this prototype.";
    return;
  }
  if (item.id === "t-21") {
    state.drawer = "capability";
    state.traceOpen = null;
    state.notice = "The named failure and its researched path are open. The stale ticket state remains visible.";
    return;
  }
  const result =
    item.id === "t-15"
      ? "Opened the marked redline in this prototype. Nothing was sent."
      : item.id === "t-21"
        ? "Started a capability research proposal. The failed source remains named."
        : `Prepared "${item.verb}" as a local prototype result. Nothing external changed.`;
  state.actioned[item.id] = result;
  addEvent(
    item.id,
    "did",
    result,
    "Did not contact an external provider. Did not hide the prior state.",
  );
  state.notice = result;
}

function rememberDrawerOrigin(target) {
  drawerOrigin = {
    action: target.dataset.action,
    drawer: target.dataset.drawer || null,
    id: target.dataset.id || null,
    selector: null,
  };
}

function rememberCommandOrigin() {
  drawerOrigin = {
    action: null,
    drawer: null,
    id: null,
    selector: "#command-input",
  };
}

function restoreDrawerOrigin() {
  const origin = drawerOrigin;
  drawerOrigin = null;
  if (!origin) return;
  const selectors = origin.selector ? [origin.selector] : [];
  if (origin.action) selectors.push(`[data-action="${origin.action}"]`);
  if (origin.drawer) selectors.push(`[data-drawer="${origin.drawer}"]`);
  if (origin.id) selectors.push(`[data-id="${origin.id}"]`);
  document.querySelector(selectors.join(""))?.focus();
}

function rememberSelectionOrigin() {
  drawerOrigin = {
    action: "select",
    drawer: null,
    id: state.selected,
    selector: null,
  };
}

document.addEventListener("click", (event) => {
  const target = event.target.closest("[data-action]");
  if (!target) return;
  const action = target.dataset.action;

  if (action === "direction") setDirection(target.dataset.direction);
  if (action === "select") {
    state.selected = target.dataset.id;
    state.expanded = target.dataset.id;
    render();
  }
  if (action === "home") {
    state.selected = "t-14";
    state.expanded = "t-14";
    window.scrollTo({ top: 0, behavior: "smooth" });
    render();
  }
  if (action === "theme") {
    state.theme = state.theme === "light" ? "dark" : "light";
    localStorage.setItem("work-os-v2-theme", state.theme);
    render();
  }
  if (action === "answer") {
    const item = itemById(target.dataset.id);
    state.answered[item.id] = target.dataset.answer;
    state.sayOpen = null;
    addEvent(
      item.id,
      "did",
      `Recorded your word verbatim: "${target.dataset.answer}". Resumed the same effort.`,
      "Did not execute an external effect.",
    );
    state.notice = `Your word was recorded for ${item.id}. The machine resumed from the same checkpoint.`;
    render();
  }
  if (action === "reopen-word") {
    delete state.answered[target.dataset.id];
    state.notice = `Reopened ${target.dataset.id}. The earlier answer remains in the append-only tape.`;
    addEvent(
      target.dataset.id,
      "did",
      "Reopened the prior judgment for correction.",
      "Did not erase the earlier answer.",
    );
    render();
  }
  if (action === "say-open") {
    rememberDrawerOrigin(target);
    state.sayOpen = target.dataset.id;
    render();
    document.querySelector(`[data-say-form="${target.dataset.id}"] input`)?.focus();
  }
  if (action === "hero") {
    actOnHero(itemById(target.dataset.id));
    if (state.drawer) rememberDrawerOrigin(target);
    render();
  }
  if (action === "trace") {
    rememberDrawerOrigin(target);
    state.traceOpen = target.dataset.id;
    state.drawer = null;
    render();
  }
  if (action === "event-trace") {
    const entry = state.events.find((item) => item.id === target.dataset.event);
    rememberDrawerOrigin(target);
    if (entry?.drawerTarget) {
      state.drawer = entry.drawerTarget;
      state.traceOpen = null;
    } else {
      state.traceOpen = entry?.itemId || state.selected;
      state.drawer = null;
    }
    render();
  }
  if (action === "drawer") {
    rememberDrawerOrigin(target);
    state.drawer = target.dataset.drawer;
    state.traceOpen = null;
    render();
  }
  if (action === "run-dig") {
    const topicId = target.dataset.topic;
    const topic = TOPIC_DIGS[topicId];
    state.digRuns[topicId] = true;
    state.selectedDigEntry = null;
    addEvent(
      "room",
      "saw",
      `Ran the ${topic.name} Dig across ${topic.coverage.length} named fixture source groups.`,
      "Did not contact a provider or claim excluded sources were searched.",
      `topic-${topicId}`,
    );
    state.notice = `${topic.name} reconstructed with coverage and exclusions attached.`;
    render();
  }
  if (action === "dig-entry") {
    state.selectedDigEntry = {
      topic: target.dataset.topic,
      id: target.dataset.entry,
    };
    render();
  }
  if (action === "dig-followup") {
    const topicId = target.dataset.topic;
    const entryId = target.dataset.entry;
    state.digFollowups[entryId] = true;
    addEvent(
      "room",
      "did",
      `Prepared a local follow-up for undone promise ${entryId}.`,
      "Did not contact the named person or change the source record.",
      `topic-${topicId}`,
    );
    state.notice = "A local follow-up is prepared beside the original promise. Nothing was sent.";
    render();
  }
  if (action === "dig-related") {
    state.selected = target.dataset.id;
    state.expanded = target.dataset.id;
    state.drawer = null;
    state.traceOpen = null;
    state.notice = `Opened ${target.dataset.id} from its sourced Dig moment.`;
    render();
    window.requestAnimationFrame(() => {
      document
        .querySelector(`[data-item="${target.dataset.id}"]`)
        ?.scrollIntoView({ block: "center", behavior: "smooth" });
    });
  }
  if (action === "person-open") {
    state.drawer = `person-${target.dataset.person}`;
    render();
  }
  if (action === "people-back") {
    state.drawer = "people";
    render();
  }
  if (action === "person-draft") {
    const person = PEOPLE.find((entry) => entry.id === target.dataset.person);
    state.personDrafts[person.id] = true;
    addEvent(
      person.relatedItem,
      "did",
      `Prepared a local reviewed draft to ${person.name}.`,
      "Did not contact a mail provider or send anything.",
      `person-${person.id}`,
    );
    state.notice = `A local draft to ${person.name} is ready. Nothing was sent.`;
    render();
  }
  if (action === "person-related") {
    state.selected = target.dataset.id;
    state.expanded = target.dataset.id;
    state.drawer = null;
    state.traceOpen = null;
    state.notice = `Opened ${target.dataset.id} from the person record.`;
    render();
    window.requestAnimationFrame(() => {
      document
        .querySelector(`[data-item="${target.dataset.id}"]`)
        ?.scrollIntoView({ block: "center", behavior: "smooth" });
    });
  }
  if (action === "close-drawer") {
    state.drawer = null;
    state.traceOpen = null;
    render();
    restoreDrawerOrigin();
  }
  if (action === "focus-first-word") {
    const item = ITEMS.find((entry) => entry.word && !answerFor(entry));
    if (item) {
      state.selected = item.id;
      state.expanded = item.id;
      render();
      window.requestAnimationFrame(() => {
        document.querySelector(`[data-item="${item.id}"]`)?.scrollIntoView({
          block: "center",
          behavior: "smooth",
        });
      });
    }
  }
  if (action === "tape-filter") {
    state.tapeFilter = target.dataset.filter;
    render();
  }
  if (action === "judge-proof") {
    const item = itemById(target.dataset.id);
    state.judgments[item.id] = {
      decision: target.dataset.decision,
      time: new Date().toISOString(),
    };
    addEvent(
      item.id,
      "did",
      `Recorded judgment: "${target.dataset.decision}". The claim remains a maybe.`,
      "Did not rewrite the claim as a fact.",
      `proof-${item.id}`,
    );
    state.notice = `Judgment recorded for ${item.id}. Its original maybe state remains visible.`;
    render();
  }
  if (action === "reopen-proof-judgment") {
    const prior = state.judgments[target.dataset.id];
    delete state.judgments[target.dataset.id];
    addEvent(
      target.dataset.id,
      "did",
      `Reopened judgment "${prior?.decision || "prior judgment"}".`,
      "Did not erase the prior judgment event.",
      `proof-${target.dataset.id}`,
    );
    state.notice = `Reopened ${target.dataset.id}; the earlier judgment remains in the tape.`;
    render();
  }
  if (action === "effort-node") {
    state.selectedEffortNode = Number(target.dataset.node);
    render();
  }
  if (action === "toggle-effort") {
    const effortId = target.dataset.effort;
    const wasStopped = Boolean(state.stoppedEfforts[effortId]);
    state.stoppedEfforts[effortId] = !wasStopped;
    addEvent(
      "t-16",
      "did",
      wasStopped
        ? `Resumed ${effortId} from the same checkpoint.`
        : `Stopped ${effortId}; partial work and receipts were kept.`,
      wasStopped
        ? "Did not restart completed nodes."
        : "Did not discard partial work or erase the named rejection.",
      `effort-${effortId.replace("eff_", "e")}`,
    );
    state.notice = wasStopped
      ? `${effortId} resumed from its checkpoint.`
      : `${effortId} stopped. Its map and receipts remain.`;
    render();
  }
  if (action === "effort-result") {
    const effort = Object.values(EFFORTS).find((entry) => entry.id === target.dataset.effort);
    if (effort) state.selectedEffortNode = effort.nodes.length - 1;
    state.notice = "The latest returned node is selected. The rejection and repair remain side by side.";
    render();
  }
  if (action === "approve-effort-proposal") {
    if (!state.proposedEffort) return;
    state.proposedEffort.status = "running";
    addEvent(
      "room",
      "did",
      `Approved effort proposal: "${state.proposedEffort.goal}".`,
      "Did not start any external effect. The local prototype run remains inspectable.",
      "effort-proposal",
    );
    state.notice = "The effort is running locally from the approved plan.";
    render();
  }
  if (action === "hold-effort-proposal") {
    if (!state.proposedEffort) return;
    state.proposedEffort.status = "held";
    addEvent(
      "room",
      "did",
      `Held effort proposal: "${state.proposedEffort.goal}".`,
      "Did not discard the proposal or start work.",
      "effort-proposal",
    );
    state.notice = "The proposal is held. Its plan remains editable.";
    render();
  }
  if (action === "stop-proposed-effort") {
    if (!state.proposedEffort) return;
    state.proposedEffort.status = "stopped";
    addEvent(
      "room",
      "did",
      `Stopped effort: "${state.proposedEffort.goal}".`,
      "Did not discard the plan or partial local work.",
      "effort-proposal",
    );
    state.notice = "The effort stopped; its proposal and partial work remain.";
    render();
  }
  if (action === "toggle-learned-math") {
    const patternId = target.dataset.pattern;
    state.learned.mathOpen[patternId] = !state.learned.mathOpen[patternId];
    render();
  }
  if (action === "open-learned-correction") {
    const patternId = target.dataset.pattern;
    state.learned.correctionOpen =
      state.learned.correctionOpen === patternId ? null : patternId;
    render();
    window.requestAnimationFrame(() => {
      document.querySelector(`[data-learned-form="${patternId}"] textarea`)?.focus();
    });
  }
  if (action === "capability-research") {
    state.capability.stage = "researched";
    addEvent(
      "t-21",
      "saw",
      "Researched a read-only webhook path and replayed the sandbox evidence.",
      "Did not request a write token or present the rehearsal as production proof.",
      "capability",
    );
    state.notice = "The gap is now a demonstrated, scoped proposal.";
    render();
  }
  if (action === "capability-arm") {
    state.capability.stage = "armed";
    state.capability.grantReceipt = "grant rcpt_2934 / one read-only replay / expires on use";
    addEvent(
      "t-21",
      "did",
      "Approved one demonstrated read-only replay.",
      "Did not grant standing authority or a provider write surface.",
      "capability",
    );
    state.notice = "One-shot authority is armed and will expire after one use.";
    render();
  }
  if (action === "capability-run-once") {
    if (state.capability.oneShotUsed) return;
    state.capability.oneShotUsed = true;
    state.capability.stage = "expired";
    state.capability.runReceipt = "run rcpt_2935 / 41 replay events / grant expired";
    addEvent(
      "t-21",
      "did",
      "Used the one-shot replay grant and expired it immediately.",
      "Did not write to Rentvine, retain the grant, or hide the prior credential failure.",
      "capability",
    );
    state.notice = "The demonstrated replay ran once. The grant is now dead.";
    render();
  }
  if (action === "draft-arm") {
    state.draft.stage = "confirm";
    state.notice = "The exact draft-only effect is armed. A second explicit word is still required.";
    render();
  }
  if (action === "draft-back") {
    state.draft.stage = "review";
    render();
  }
  if (action === "draft-keep-local") {
    const item = itemById(state.draft.itemId || "t-17");
    state.actioned[item.id] = "Kept the reviewed draft local. Gmail remains unchanged.";
    addEvent(
      item.id,
      "did",
      "Kept the dunning rewrite as a local reviewed draft.",
      "Did not contact Gmail and did not send anything.",
      "draft-t17",
    );
    state.notice = "The reviewed draft remains local; Gmail is unchanged.";
    render();
  }
  if (action === "draft-place") {
    const item = itemById(state.draft.itemId || "t-17");
    state.draft.stage = "placed";
    state.draft.placed = true;
    state.draft.receipt =
      "prototype rcpt_2941 / requested draft placement / simulated actual accepted / sent false";
    state.actioned[item.id] =
      "Prototype Gmail-draft custody recorded. No email was sent.";
    addEvent(
      item.id,
      "did",
      "Recorded prototype custody for one Gmail draft.",
      "Did not contact Gmail, send email, or change any other mailbox state.",
      "draft-t17",
    );
    state.notice = "Requested and actual prototype state are now shown separately. Sent remains false.";
    render();
  }
  if (action === "close-week") {
    const time = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
    const receipt =
      state.week.closeReceipt || "week rcpt_2939 / 23 decisions / 14 efforts / 6 of 8 promises";
    state.week.status = "closed";
    state.week.closeReceipt = receipt;
    state.week.history.unshift({
      kind: "closed",
      time,
      text: `${WEEK_SUMMARY.label} closed. Four seeds carried into the next period.`,
      receipt,
    });
    addEvent(
      "room",
      "did",
      `Closed ${WEEK_SUMMARY.label}; the ledger and carries were stamped.`,
      "Did not send anything or erase the open-week history.",
      "week",
    );
    state.notice = `${WEEK_SUMMARY.label} closed. Its receipt is now permanent in the history.`;
    render();
  }
  if (action === "reopen-week") {
    const time = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
    const receipt = "reopen rcpt_2940 / prior close retained";
    state.week.status = "open";
    state.week.history.unshift({
      kind: "reopened",
      time,
      text: `${WEEK_SUMMARY.label} reopened for correction. The prior close remains struck, not erased.`,
      receipt,
    });
    addEvent(
      "room",
      "did",
      `Reopened ${WEEK_SUMMARY.label} for correction.`,
      "Did not erase or replace the original close receipt.",
      "week",
    );
    state.notice = `${WEEK_SUMMARY.label} reopened. The original close remains in the append-only history.`;
    render();
  }
  if (action === "mobile-machine") {
    if (!state.mobileMachine) rememberDrawerOrigin(target);
    state.mobileMachine = !state.mobileMachine;
    render();
  }
  if (action === "undo") {
    undoLiveAction();
  }
  if (action === "unavailable") {
    state.notice =
      "This comparison prototype has no live source connector. The production control must open the exact native pointer.";
    render();
  }
  if (action === "dismiss-notice") {
    clearUndo();
    state.notice = null;
    render();
  }
});

document.addEventListener("submit", (event) => {
  const sayForm = event.target.closest("[data-say-form]");
  if (sayForm) {
    event.preventDefault();
    const id = sayForm.dataset.sayForm;
    const value = new FormData(sayForm).get("say")?.toString().trim();
    if (!value) return;
    state.answered[id] = value;
    state.sayValues[id] = value;
    state.sayOpen = null;
    addEvent(
      id,
      "did",
      `Recorded your exact words: "${value}". The machine interpretation is shown separately.`,
      "Did not rewrite your words. Did not execute an external effect.",
    );
    state.notice = `Recorded your words for ${id}.`;
    render();
    return;
  }

  const effortForm = event.target.closest("[data-effort-form]");
  if (effortForm) {
    event.preventDefault();
    if (!state.proposedEffort) return;
    const data = new FormData(effortForm);
    const goal = data.get("goal")?.toString().trim();
    const plan = data
      .get("plan")
      ?.toString()
      .split("\n")
      .map((line) => line.trim())
      .filter(Boolean);
    if (!goal || !plan?.length) return;
    state.proposedEffort.goal = goal;
    state.proposedEffort.plan = plan;
    addEvent(
      "room",
      "did",
      `Edited the effort proposal: "${goal}".`,
      "Did not start work while the proposal changed.",
      "effort-proposal",
    );
    state.notice = "The proposal changed. It still waits for approval.";
    render();
    return;
  }

  const learnedForm = event.target.closest("[data-learned-form]");
  if (learnedForm) {
    event.preventDefault();
    const patternId = learnedForm.dataset.learnedForm;
    const value = new FormData(learnedForm)
      .get("correction")
      ?.toString()
      .trim();
    if (!value) return;
    const receipt = `correction rcpt_${Date.now().toString().slice(-6)}`;
    state.learned.corrections[patternId] = {
      text: value,
      receipt,
    };
    state.learned.correctionOpen = null;
    addEvent(
      "room",
      "did",
      `Corrected learned pattern ${patternId}: "${value}".`,
      "Did not erase the machine's prior read or its denominator.",
      "learned",
    );
    state.notice = "The correction was appended. The old read remains struck through.";
    render();
  }
});

document.addEventListener("input", (event) => {
  if (event.target.id !== "command-input") return;
  const parse = parseCommand(event.target.value);
  const readout = document.getElementById("parse-readout");
  if (!parse || !readout) {
    if (readout) readout.hidden = true;
    return;
  }
  readout.hidden = false;
  readout.innerHTML = `
    <span>${esc(parse.verb)}</span>
    <strong>${esc(parse.object)}</strong>
    <p>${esc(parse.consequence)}</p>
    <small>${esc(parse.nonEffect)}</small>
  `;
});

document.addEventListener("keydown", (event) => {
  if (event.key === "Escape") {
    const shouldRestoreFocus = Boolean(
      state.drawer || state.traceOpen || state.mobileMachine || state.sayOpen,
    );
    state.drawer = null;
    state.traceOpen = null;
    state.mobileMachine = false;
    state.sayOpen = null;
    render();
    if (shouldRestoreFocus) restoreDrawerOrigin();
    return;
  }
  if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
    event.preventDefault();
    document.getElementById("command-input")?.focus();
    return;
  }
  if (
    event.target.id === "command-input" &&
    !event.target.value &&
    (event.key === "?" || (event.key === "/" && event.shiftKey))
  ) {
    event.preventDefault();
    rememberCommandOrigin();
    state.drawer = "help";
    state.traceOpen = null;
    render();
    return;
  }
  if (event.target.id === "command-input" && event.key === "Enter") {
    event.preventDefault();
    const parse = parseCommand(event.target.value);
    if (!parse) return;
    if (parse.verb === "SNOOZE") {
      const hadPreviousAction = Object.hasOwn(state.actioned, "t-15");
      const previousAction = state.actioned["t-15"];
      state.actioned["t-15"] =
        "Snoozed until Monday at 09:00. The source and receipt remain attached.";
      addEvent(
        "t-15",
        "did",
        "Snoozed Robert's redline until Monday at 09:00.",
        "Did not send a message or remove the item from history.",
      );
      state.selected = "t-15";
      armUndo({
        type: "snooze",
        itemId: "t-15",
        hadPreviousAction,
        previousAction,
      });
    } else if (parse.verb === "OPEN") {
      const match = event.target.value.toLowerCase().match(/t-\d+/);
      if (match && itemById(match[0])) state.selected = match[0];
    } else if (parse.verb === "DIG") {
      const query = parse.object.toLowerCase();
      const topicId = query.includes("rentvine")
        ? "rentvine"
        : query.includes("automation")
          ? "automation"
          : "rentfinder";
      const topic = TOPIC_DIGS[topicId];
      rememberCommandOrigin();
      state.digRuns[topicId] = true;
      state.selectedDigEntry = null;
      state.drawer = `topic-${topicId}`;
      state.traceOpen = null;
      addEvent(
        "room",
        "saw",
        `Ran the ${topic.name} Dig from the line.`,
        "Did not contact a provider or include excluded sources.",
        `topic-${topicId}`,
      );
    } else if (parse.verb === "OPEN PEOPLE") {
      rememberCommandOrigin();
      state.drawer = "people";
      state.traceOpen = null;
    } else if (parse.verb === "OPEN PERSON") {
      rememberCommandOrigin();
      state.drawer = `person-${parse.personId}`;
      state.traceOpen = null;
    } else if (parse.verb === "REVIEW CLOSE") {
      rememberCommandOrigin();
      state.drawer = "week";
      state.traceOpen = null;
    } else if (parse.verb === "REVIEW DRAFT") {
      rememberCommandOrigin();
      state.selected = "t-17";
      state.draft.itemId = "t-17";
      state.drawer = "draft-t17";
      state.traceOpen = null;
    } else {
      rememberCommandOrigin();
      state.commandReceipt = parse.object;
      state.proposedEffort = {
        goal: parse.object,
        status: "proposed",
        plan: [
          "Bound the goal and name the evidence needed.",
          "Attack the plan and remove unsupported assumptions.",
          "Read the permitted sources and preserve their pointers.",
          "Stop for Nathan where judgment or authority is required.",
          "Return a checked work product with a receipt.",
        ],
      };
      addEvent(
        "room",
        "did",
        `Created an editable effort proposal: "${parse.object}".`,
        "Did not start a worker before approval.",
        "effort-proposal",
      );
      state.drawer = "effort-proposal";
      state.traceOpen = null;
    }
    state.notice = `${parse.verb}: ${parse.consequence} ${parse.nonEffect}`;
    render();
    return;
  }
  if (
    !["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName) &&
    event.key.toLowerCase() === "u" &&
    state.undo
  ) {
    event.preventDefault();
    undoLiveAction();
    return;
  }
  if (
    !["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName) &&
    ["j", "k"].includes(event.key.toLowerCase())
  ) {
    event.preventDefault();
    const index = ITEMS.findIndex((item) => item.id === state.selected);
    const delta = event.key.toLowerCase() === "j" ? 1 : -1;
    const next = (index + delta + ITEMS.length) % ITEMS.length;
    state.selected = ITEMS[next].id;
    render();
  }
  if (
    !["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName) &&
    event.key.toLowerCase() === "o"
  ) {
    event.preventDefault();
    rememberSelectionOrigin();
    state.drawer = `proof-${state.selected}`;
    state.traceOpen = null;
    render();
  }
  if (
    !["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName) &&
    event.key.toLowerCase() === "t"
  ) {
    event.preventDefault();
    rememberSelectionOrigin();
    state.traceOpen = state.selected;
    state.drawer = null;
    render();
  }
  if (
    !["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName) &&
    (event.key === "?" || (event.key === "/" && event.shiftKey))
  ) {
    event.preventDefault();
    rememberSelectionOrigin();
    state.drawer = "help";
    state.traceOpen = null;
    render();
  }
  if (
    !["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName) &&
    ["Enter", "e", "E"].includes(event.key)
  ) {
    event.preventDefault();
    rememberSelectionOrigin();
    actOnHero(itemById(state.selected));
    render();
  }
});

render();
