Skip to content

fix(pi): clean up Calm transcript rendering - #895

Merged
kunchenguid merged 6 commits into
mainfrom
fm/fm-calm-transcript-cleanup
Jul 23, 2026
Merged

kunchenguid merged 6 commits into
mainfrom
fm/fm-calm-transcript-cleanup

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Implement and ship the captain-authorized Calm cleanup independently from Ahoy. When Calm is on, the Pi transcript must show only genuine original user prompts and genuine user-facing agent responses, using one centralized allowlist-style visibility policy across every reachable Pi transcript/render class and every authoritative Firstmate injection path. Hide repeated collapsed Thinking labels where supported, the fm_watch_arm_pi call/result shell, built-in text-tool rows, and all known synthetic Firstmate user-role messages while preserving actual delivery and handling, model context, session persistence, diagnostics, export/share, supervision, and the existing image and arbitrary custom-tool boundaries. Use conservative tested heuristics only where origin metadata is absent, with positive fixtures for every supported synthetic form and near-miss genuine-message negatives. Verify against real supported Pi 0.81.1 APIs and a genuine isolated interactive E2E at screenshot scale. Calm off must restore stock rendering and unchanged Ctrl+O behavior. Audit and document the complete transcript and injection taxonomy, visible trigger/masking/symptom distinctions, counterfactual and disconfirming evidence, and every exact supported-API boundary, without patching installed Pi internals or claiming unsupported generic custom-tool/thinking coverage. Review the real terminal for gaps, stale backgrounds, malformed redraws, and flicker, turn the reproduction into regression coverage, and keep presentation filtering separate from delivery/context/session/export/share/supervision behavior.

What Changed

  • Centralize Pi Calm visibility rules and hide supported thinking, working, built-in tool, watcher tool, and known synthetic Firstmate input rows.
  • Preserve synthetic input delivery, model context, session storage, diagnostics, stock Calm-off rendering, and export/share behavior while identifying Pi launch briefs at their source.
  • Document Pi 0.81.1 transcript boundaries and expand focused and interactive regression coverage for classification, redraw, restoration, and exported conversations.

Risk Assessment

✅ Low: The targeted synchronous mount followed by a supported expansion redraw resolves the live-arrival restoration defect without transcript reconstruction, diagnostic loss, residual spacing, or Ctrl+O state changes.

Testing

Targeted validation passed: repository inspection, strict Pi 0.81.1 API compilation, centralized visibility and classifier fixtures, watcher and launch-path tests, a real screenshot-scale Calm TUI round trip with rendered export and persistence checks, and a credentialed live watcher delivery/handling E2E all succeeded; reviewer-visible evidence was preserved and transient worktree artifacts were cleaned.

  • Evidence: Pi 0.81.1 Calm-on vs Calm-off terminal evidence (local file: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KY6MHEAQVVQNSWXVK8Q7T95B/calm-terminal-e2e.png)
Evidence: Rendered terminal comparison
<!doctype html><meta charset="utf-8"><title>Firstmate Calm Pi 0.81.1 E2E evidence</title><style>html{background:#111318;color:#e6e7eb;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}body{margin:0;padding:28px;display:grid;gap:28px}h1,h2,p{margin:0}h1{font:700 24px system-ui;color:#fff}section{border:1px solid #343943;border-radius:12px;overflow:hidden;background:#171a20}header{padding:18px 20px;border-bottom:1px solid #343943;display:grid;gap:8px}h2{font:700 17px system-ui;color:#fff}p{font:14px/1.45 system-ui;color:#aeb4c0}pre{margin:0;padding:18px 20px;white-space:pre;overflow:auto;font-size:12px;line-height:1.25;color:#e9ebef;background:#0d0f13}</style><body><h1>Firstmate Calm cleanup - genuine Pi 0.81.1, 180 x 44 TUI</h1><section><header><h2>Calm on - conversation-only transcript</h2><p>Tool calls, tool results, collapsed Thinking labels, fm_watch_arm_pi, and the authoritative watcher wake are absent. Genuine prompts and assistant text remain.</p></header><pre>
 pi v0.81.1
 escape to interrupt
 ctrl+c to clear
 ctrl+c twice to exit
 ctrl+d to exit (empty)
 ctrl+z to suspend
 ctrl+k to delete to end
 shift+tab to cycle thinking level
 ctrl+p/shift+ctrl+p to cycle models
 ctrl+l to select model
 ctrl+o to expand tools
 ctrl+t to expand thinking
 ctrl+g for external editor
 / for commands
 ! to run bash
 !! to run bash (no context)
 option+enter to queue follow-up
 option+up to edit all queued messages
 ctrl+v to paste image (with text fallback)
 drop files to attach

 Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.

[Extensions]
  project
    /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project/.pi/extensions/fm-calm-e2e-inject.ts
    /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project/.pi/extensions/fm-calm.ts
    /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project/.pi/extensions/fm-primary-pi-watch.ts


 Show a deterministic tool example.




 I will run one command.






 FIRSTMATE WATCHER WAKE: can you explain this phrase?


 The deterministic tool example is complete.

 Warning: No models available. Use /login to log into a provider via OAuth or API key. See:
   /Users/kunchen/.nvm/versions/node/v24.13.1/lib/node_modules/@earendil-works/pi-coding-agent/docs/providers.md
   /Users/kunchen/.nvm/versions/node/v24.13.1/lib/node_modules/@earendil-works/pi-coding-agent/docs/models.md

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project
↑7 ↓4 0.0%/0 (auto)                                                                                                                                                          unknown
calm transcript
</pre></section>
<section><header><h2>Calm off - stock transcript restored</h2><p>The original Pi rows return, including Thinking labels, tool shells, synthetic presentation, diagnostics, and the unchanged Ctrl+O expanded-state footer.</p></header><pre>
 pi v0.81.1
 escape to interrupt
 ctrl+c to clear
 ctrl+c twice to exit
 ctrl+d to exit (empty)
 ctrl+z to suspend
 ctrl+k to delete to end
 shift+tab to cycle thinking level
 ctrl+p/shift+ctrl+p to cycle models
 ctrl+l to select model
 ctrl+o to expand tools
 ctrl+t to expand thinking
 ctrl+g for external editor
 / for commands
 ! to run bash
 !! to run bash (no context)
 option+enter to queue follow-up
 option+up to edit all queued messages
 ctrl+v to paste image (with text fallback)
 drop files to attach

 Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.

[Extensions]
  project
    /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project/.pi/extensions/fm-calm-e2e-inject.ts
    /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project/.pi/extensions/fm-calm.ts
    /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project/.pi/extensions/fm-primary-pi-watch.ts


 Show a deterministic tool example.


 Thinking...

 I will run one command.


 $ printf 'CALM_E2E_OUTPUT
 '

 CALM_E2E_OUTPUT


 Thinking...


 grep /CALM_EXPORT_GREP/ in .

 sample.txt:1:CALM_EXPORT_GREP



 find CALM_EXPORT_FIND* in .

 CALM_EXPORT_FIND.txt


 Thinking...


 fm_watch_arm_pi
 watcher: started Pi extension arm child 1



 FIRSTMATE WATCHER WAKE: signal: /tmp/probe.status

 Run bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.



 FIRSTMATE WATCHER WAKE: can you explain this phrase?


 The deterministic tool example is complete.

 Warning: No models available. Use /login to log into a provider via OAuth or API key. See:
   /Users/kunchen/.nvm/versions/node/v24.13.1/lib/node_modules/@earendil-works/pi-coding-agent/docs/providers.md
   /Users/kunchen/.nvm/versions/node/v24.13.1/lib/node_modules/@earendil-works/pi-coding-agent/docs/models.md

 Warning: CALM_TRANSIENT_DIAGNOSTIC


 FIRSTMATE WATCHER WAKE: signal: /tmp/active-probe.status

 Run bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.


 Error: Unknown provider: unknown

 Session exported to: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T//fm-calm-pi-extension.cDpun3/calm-export.html

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-calm-pi-extension.cDpun3/e2e-project
↑7 ↓4 0.0%/0 (auto)                                                                                                                                                          unknown
</pre></section></body>
Evidence: Pi HTML export produced while Calm was active
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Session Export</title>
  <style>
    :root {
      --accent: #8abeb7;
      --border: #5f87ff;
      --borderAccent: #00d7ff;
      --borderMuted: #505050;
      --success: #b5bd68;
      --error: #cc6666;
      --warning: #ffff00;
      --muted: #808080;
      --dim: #666666;
      --text: #d4d4d4;
      --thinkingText: #808080;
      --selectedBg: #3a3a4a;
      --userMessageBg: #343541;
      --userMessageText: #d4d4d4;
      --customMessageBg: #2d2838;
      --customMessageText: #d4d4d4;
      --customMessageLabel: #9575cd;
      --toolPendingBg: #282832;
      --toolSuccessBg: #283228;
      --toolErrorBg: #3c2828;
      --toolTitle: #d4d4d4;
      --toolOutput: #808080;
      --mdHeading: #f0c674;
      --mdLink: #81a2be;
      --mdLinkUrl: #666666;
      --mdCode: #8abeb7;
      --mdCodeBlock: #b5bd68;
      --mdCodeBlockBorder: #808080;
      --mdQuote: #808080;
      --mdQuoteBorder: #808080;
      --mdHr: #808080;
      --mdListBullet: #8abeb7;
      --toolDiffAdded: #b5bd68;
      --toolDiffRemoved: #cc6666;
      --toolDiffContext: #808080;
      --syntaxComment: #6A9955;
      --syntaxKeyword: #569CD6;
      --syntaxFunction: #DCDCAA;
      --syntaxVariable: #9CDCFE;
      --syntaxString: #CE9178;
      --syntaxNumber: #B5CEA8;
      --syntaxType: #4EC9B0;
      --syntaxOperator: #D4D4D4;
      --syntaxPunctuation: #D4D4D4;
      --thinkingOff: #505050;
      --thinkingMinimal: #6e6e6e;
      --thinkingLow: #5f87af;
      --thinkingMedium: #81a2be;
      --thinkingHigh: #b294bb;
      --thinkingXhigh: #d183e8;
      --thinkingMax: #ff5fff;
      --bashMode: #b5bd68;
      --exportPageBg: #18181e;
      --exportCardBg: #1e1e24;
      --exportInfoBg: #3c3728;
      --body-bg: #18181e;
      --container-bg: #1e1e24;
      --info-bg: #3c3728;
    }

    * { margin: 0; padding: 0; box-sizing: border-box; }

    :root {
      --line-height: 18px; /* 12px font * 1.5 */
      --sidebar-width: 400px;
      --sidebar-min-width: 240px;
      --sidebar-max-width: 840px;
      --sidebar-resizer-width: 6px;
    }

    body {
      font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
      font-size: 12px;
      line-height: var(--line-height);
      color: var(--text);
      background: var(--body-bg);
    }

    body.sidebar-resizing {
      cursor: col-resize;
      user-select: none;
    }

    #app {
      display: flex;
      min-height: 100vh;
    }

    /* Sidebar */
    #sidebar {
      width: var(--sidebar-width);
      min-width: var(--sidebar-width);
      max-width: var(--sidebar-width);
      background: var(--container-bg);
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      position: sticky;
      top: 0;
      height: 100vh;
      border-right: 1px solid var(--dim);
    }

    #sidebar-resizer {
      width: var(--sidebar-resizer-width);
      flex-shrink: 0;
      position: sticky;
      top: 0;
      height: 100vh;
      cursor: col-resize;
      touch-action: none;
      background: transparent;
      border-right: 1px solid transparent;
    }

    #sidebar-resizer:hover,
    body.sidebar-resizing #sidebar-resizer {
      background: var(--selectedBg);
      border-right-color: var(--dim);
    }

    .sidebar-header {
      padding: 8px 12px;
      flex-shrink: 0;
    }

    .sidebar-controls {
      padding: 8px 8px 4px 8px;
    }

    .sidebar-search {
      width: 100%;
      box-sizing: border-box;
      padding: 4px 8px;
      font-size: 11px;
      font-family: inherit;
      background: var(--body-bg);
      color: var(--text);
      border: 1px solid var(--dim);
      border-radius: 3px;
    }

    .sidebar-filters {
      display: flex;
      padding: 4px 8px 8px 8px;
      gap: 4px;
      align-items: center;
      flex-wrap: wrap;
    }

    .sidebar-search:focus {
      outline: none;
      border-color: var(--accent);
    }

    .sidebar-search::placeholder {
      color: var(--muted);
    }

    .filter-btn {
      padding: 3px 8px;
      font-size: 10px;
      font-family: inherit;
      background: transparent;
      color: var(--muted);
      border: 1px solid var(--dim);
      border-radius: 3px;
      cursor: pointer;
    }

    .filter-btn:hover {
      color: var(--text);
      border-color: var(--text);
    }

    .filter-btn.active {
      background: var(--accent);
      color: var(--body-bg);
      border-color: var(--accent);
    }

    .sidebar-close {
      display: none;
      padding: 3px 8px;
      font-size: 12px;
      font-family: inherit;
      background: transparent;
      color: var(--muted);
      border: 1px solid var(--dim);
      border-radius: 3px;
      cursor: pointer;
      margin-left: auto;
    }

    .sidebar-close:hover {
      color: var(--text);
      border-color: var(--text);
    }

    .tree-container {
      flex: 1;
      overflow: auto;
      padding: 4px 0;
    }

    .tree-node {
      padding: 0 8px;
      cursor: pointer;
      display: flex;
      align-items: baseline;
      font-size: 11px;
      line-height: 13px;
      white-space: nowrap;
    }

    .tree-node:hover {
      background: var(--selectedBg);
    }

    .tree-node.active {
      background: var(--selectedBg);
    }

    .tree-node.active .tree-content {
      font-weight: bold;
    }

    .tree-node.in-path {
      background: color-mix(in srgb, var(--accent) 10%, transparent);
    }

    .tree-node:not(.in-path) {
      opacity: 0.5;
    }

    .tree-node:not(.in-path):hover {
      opacity: 1;
    }

    .tree-prefix {
      color: var(--muted);
      flex-shrink: 0;
      font-family: monospace;
      white-space: pre;
    }

    .tree-marker {
      color: var(--accent);
      flex-shrink: 0;
    }

    .tree-content {
      color: var(--text);
    }

    .tree-role-user {
      color: var(--accent);
    }

    .tree-role-skill {
      color: var(--customMessageLabel);
    }

    .tree-role-assistant {
      color: var(--success);
    }

    .tree-role-tool {
      color: var(--muted);
    }

    .tree-muted {
      color: var(--muted);
    }

    .tree-error {
      color: var(--error);
    }

    .tree-compaction {
      color: var(--borderAccent);
    }

    .tree-branch-summary {
      color: var(--warning);
    }

    .tree-custom-message {
      color: var(--customMessageLabel);
    }

    .tree-status {
      padding: 4px 12px;
      font-size: 10px;
      color: var(--muted);
      flex-shrink: 0;
    }

    /* Main content */
    #content {
      flex: 1;
      min-width: 0;
      overflow-y: auto;
      padding: var(--line-height) calc(var(--line-height) * 2);
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    #content > * {
      width: 100%;
      max-width: 800px;
    }

    /* Help bar */
    .help-bar {
      font-size: 11px;
      color: var(--warning);
      margin-bottom: var(--line-height);
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      gap: 12px;
    }

    .help-hint {
      flex: 1 1 240px;
    }

    .help-actions {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;
    }

    .header-toggle-btn,
    .download-json-btn {
      font-size: 10px;
      padding: 2px 8px;
      background: var(--container-bg);
      border: 1px solid var(--border);
      border-radius: 3px;
      color: var(--text);
      cursor: pointer;
      font-family: inherit;
    }

    .header-toggle-btn:hover,
    .download-json-btn:hover {
      background: var(--hover);
      border-color: var(--borderAccent);
    }

    /* Header */
    .header {
      background: var(--container-bg);
      border-radius: 4px;
      padding: var(--line-height);
      margin-bottom: var(--line-height);
    }

    .header h1 {
      font-size: 12px;
      font-weight: bold;
      color: var(--borderAccent);
      margin-bottom: var(--line-height);
    }

    .header-info {
      display: flex;
      flex-direction: column;
      gap: 0;
     

... [273190 bytes truncated] ...

ine code: escape HTML
          codespan(token) {
            return `<code>${escapeHtml(token.text)}</code>`;
          }
        }
      });

      // Simple marked parse (escaping handled in renderers)
      function safeMarkedParse(text) {
        return marked.parse(text);
      }

      // Search input
      const searchInput = document.getElementById('tree-search');
      searchInput.addEventListener('input', (e) => {
        searchQuery = e.target.value;
        forceTreeRerender();
      });

      // Filter buttons
      document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', () => {
          document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
          btn.classList.add('active');
          filterMode = btn.dataset.filter;
          forceTreeRerender();
        });
      });

      // Sidebar toggle
      const sidebar = document.getElementById('sidebar');
      const overlay = document.getElementById('sidebar-overlay');
      const hamburger = document.getElementById('hamburger');
      const sidebarResizer = document.getElementById('sidebar-resizer');
      const SIDEBAR_WIDTH_STORAGE_KEY = 'pi-share:v1:sidebar-width';
      const MIN_CONTENT_WIDTH = 320;

      function isMobileLayout() {
        return window.matchMedia('(max-width: 900px)').matches;
      }

      function getSidebarBounds() {
        const rootStyles = getComputedStyle(document.documentElement);
        const minWidth = parseFloat(rootStyles.getPropertyValue('--sidebar-min-width')) || 240;
        const maxWidth = parseFloat(rootStyles.getPropertyValue('--sidebar-max-width')) || 720;
        const viewportMaxWidth = window.innerWidth - MIN_CONTENT_WIDTH;
        return {
          minWidth,
          maxWidth: Math.max(minWidth, Math.min(maxWidth, viewportMaxWidth))
        };
      }

      function clampSidebarWidth(width) {
        const { minWidth, maxWidth } = getSidebarBounds();
        return Math.max(minWidth, Math.min(maxWidth, width));
      }

      function applySidebarWidth(width) {
        document.documentElement.style.setProperty('--sidebar-width', `${Math.round(clampSidebarWidth(width))}px`);
      }

      function loadSidebarWidth() {
        try {
          const raw = localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY);
          if (raw === null) return null;
          const width = Number(raw);
          return Number.isFinite(width) ? width : null;
        } catch {
          return null;
        }
      }

      function saveSidebarWidth(width) {
        try {
          localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(Math.round(clampSidebarWidth(width))));
        } catch {
          // Ignore storage failures (e.g. private browsing restrictions)
        }
      }

      function setupSidebarResize() {
        const savedWidth = loadSidebarWidth();
        if (savedWidth !== null) {
          applySidebarWidth(savedWidth);
        }

        if (!sidebarResizer) return;

        let cleanupDrag = null;

        const stopDrag = (pointerId) => {
          if (cleanupDrag) {
            cleanupDrag(pointerId);
            cleanupDrag = null;
          }
        };

        sidebarResizer.addEventListener('pointerdown', (e) => {
          if (isMobileLayout()) return;

          e.preventDefault();
          const startX = e.clientX;
          const startWidth = sidebar.getBoundingClientRect().width;
          document.body.classList.add('sidebar-resizing');
          sidebarResizer.setPointerCapture?.(e.pointerId);

          const onPointerMove = (event) => {
            applySidebarWidth(startWidth + (event.clientX - startX));
          };

          cleanupDrag = (pointerIdToRelease) => {
            document.body.classList.remove('sidebar-resizing');
            sidebarResizer.releasePointerCapture?.(pointerIdToRelease);
            window.removeEventListener('pointermove', onPointerMove);
            window.removeEventListener('pointerup', onPointerUp);
            window.removeEventListener('pointercancel', onPointerCancel);
            saveSidebarWidth(sidebar.getBoundingClientRect().width);
          };

          const onPointerUp = (event) => stopDrag(event.pointerId);
          const onPointerCancel = (event) => stopDrag(event.pointerId);

          window.addEventListener('pointermove', onPointerMove);
          window.addEventListener('pointerup', onPointerUp);
          window.addEventListener('pointercancel', onPointerCancel);
        });

        sidebarResizer.addEventListener('dblclick', () => {
          if (isMobileLayout()) return;
          applySidebarWidth(400);
          saveSidebarWidth(400);
        });

        window.addEventListener('resize', () => {
          if (isMobileLayout()) return;
          applySidebarWidth(sidebar.getBoundingClientRect().width);
        });
      }

      setupSidebarResize();

      hamburger.addEventListener('click', () => {
        sidebar.classList.add('open');
        overlay.classList.add('open');
        hamburger.style.display = 'none';
      });

      const closeSidebar = () => {
        sidebar.classList.remove('open');
        overlay.classList.remove('open');
        hamburger.style.display = '';
      };

      overlay.addEventListener('click', closeSidebar);
      document.getElementById('sidebar-close').addEventListener('click', closeSidebar);

      // Toggle states
      let thinkingExpanded = true;
      let toolOutputsExpanded = false;

      const toggleThinking = () => {
        thinkingExpanded = !thinkingExpanded;
        document.querySelectorAll('.thinking-text').forEach(el => {
          el.style.display = thinkingExpanded ? '' : 'none';
        });
        document.querySelectorAll('.thinking-collapsed').forEach(el => {
          el.style.display = thinkingExpanded ? 'none' : 'block';
        });
      };

      const toggleToolOutputs = () => {
        toolOutputsExpanded = !toolOutputsExpanded;
        document.querySelectorAll('.tool-output.expandable').forEach(el => {
          el.classList.toggle('expanded', toolOutputsExpanded);
        });
        document.querySelectorAll('.compaction').forEach(el => {
          el.classList.toggle('expanded', toolOutputsExpanded);
        });
        document.querySelectorAll('.skill-invocation').forEach(el => {
          el.classList.toggle('expanded', toolOutputsExpanded);
        });
      };

      const attachHeaderHandlers = () => {
        document.querySelector('[data-action="toggle-thinking"]')?.addEventListener('click', toggleThinking);
        document.querySelector('[data-action="toggle-tools"]')?.addEventListener('click', toggleToolOutputs);
      };

      const isEditableTarget = (element) => {
        if (!element) return false;
        const tagName = element.tagName;
        if (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT' || tagName === 'BUTTON') {
          return true;
        }
        return element.isContentEditable || Boolean(element.closest?.('[contenteditable="true"]'));
      };

      // Keyboard shortcuts
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
          searchInput.value = '';
          searchQuery = '';
          navigateTo(leafId, 'bottom');
        }

        if (isEditableTarget(document.activeElement)) {
          return;
        }

        const key = e.key.toLowerCase();
        if (key === 't') {
          e.preventDefault();
          toggleThinking();
        } else if (key === 'o') {
          e.preventDefault();
          toggleToolOutputs();
        }
      });

      // Initial render
      // If URL has targetId, scroll to that specific message; otherwise stay at top
      if (leafId) {
        if (urlTargetId && byId.has(urlTargetId)) {
          // Deep link: navigate to leaf and scroll to target message
          navigateTo(leafId, 'target', urlTargetId);
        } else {
          navigateTo(leafId, 'none');
        }
      } else if (entries.length > 0) {
        // Fallback: use last entry if no leafId
        navigateTo(entries[entries.length - 1].id, 'none');
      }
    })();

  </script>
</body>
</html>
Evidence: Gap-free hidden live-injection boundary

Warning: CALM_TRANSIENT_DIAGNOSTIC Error: Unknown provider: unknown

 Warning: CALM_TRANSIENT_DIAGNOSTIC

 Error: Unknown provider: unknown
Evidence: Persisted Pi session proving presentation-only filtering
{"type":"session","version":3,"id":"11111111-1111-4111-8111-111111111111","timestamp":"2026-07-23T05:26:37.000Z","cwd":"/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T//fm-calm-pi-extension.cDpun3/e2e-project"}
{"type":"message","id":"a0000001","parentId":null,"timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"user","content":[{"type":"text","text":"Show a deterministic tool example."}],"timestamp":1}}
{"type":"message","id":"a0000002","parentId":"a0000001","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"first internal reasoning block"},{"type":"text","text":"I will run one command."},{"type":"toolCall","id":"call_calm_e2e","name":"bash","arguments":{"command":"printf 'CALM_E2E_OUTPUT\n'"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{"input":1,"output":1,"cacheRead":0,"cacheWrite":0,"totalTokens":2,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"toolUse","timestamp":2}}
{"type":"message","id":"a0000003","parentId":"a0000002","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"toolResult","toolCallId":"call_calm_e2e","toolName":"bash","content":[{"type":"text","text":"CALM_E2E_OUTPUT"}],"details":{},"isError":false,"timestamp":3}}
{"type":"message","id":"a0000004","parentId":"a0000003","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"second internal reasoning block"},{"type":"toolCall","id":"call_grep_e2e","name":"grep","arguments":{"pattern":"CALM_EXPORT_GREP","path":"."}},{"type":"toolCall","id":"call_find_e2e","name":"find","arguments":{"pattern":"CALM_EXPORT_FIND*","path":"."}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{"input":2,"output":1,"cacheRead":0,"cacheWrite":0,"totalTokens":3,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"toolUse","timestamp":4}}
{"type":"message","id":"a0000005","parentId":"a0000004","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"toolResult","toolCallId":"call_grep_e2e","toolName":"grep","content":[{"type":"text","text":"sample.txt:1:CALM_EXPORT_GREP"}],"details":{},"isError":false,"timestamp":5}}
{"type":"message","id":"a0000006","parentId":"a0000005","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"toolResult","toolCallId":"call_find_e2e","toolName":"find","content":[{"type":"text","text":"CALM_EXPORT_FIND.txt"}],"details":{},"isError":false,"timestamp":6}}
{"type":"message","id":"a0000007","parentId":"a0000006","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"third internal reasoning block"},{"type":"toolCall","id":"call_watch_e2e","name":"fm_watch_arm_pi","arguments":{}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{"input":2,"output":1,"cacheRead":0,"cacheWrite":0,"totalTokens":3,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"toolUse","timestamp":7}}
{"type":"message","id":"a0000008","parentId":"a0000007","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"toolResult","toolCallId":"call_watch_e2e","toolName":"fm_watch_arm_pi","content":[{"type":"text","text":"watcher: started Pi extension arm child 1"}],"details":{"ok":true,"message":"watcher: started Pi extension arm child 1"},"isError":false,"timestamp":8}}
{"type":"custom","id":"a0000009","parentId":"a0000008","timestamp":"2026-07-23T05:26:37.000Z","customType":"firstmate-synthetic-input-presentation","data":{"content":"FIRSTMATE WATCHER WAKE: signal: /tmp/probe.status\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.","kind":"watcher"}}
{"type":"custom_message","id":"a0000010","parentId":"a0000009","timestamp":"2026-07-23T05:26:37.000Z","customType":"firstmate-synthetic-input","content":"FIRSTMATE WATCHER WAKE: signal: /tmp/probe.status\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.","display":false,"details":{"kind":"watcher"}}
{"type":"message","id":"a0000011","parentId":"a0000010","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"user","content":[{"type":"text","text":"FIRSTMATE WATCHER WAKE: can you explain this phrase?"}],"timestamp":11}}
{"type":"message","id":"a0000012","parentId":"a0000011","timestamp":"2026-07-23T05:26:37.000Z","message":{"role":"assistant","content":[{"type":"text","text":"The deterministic tool example is complete."}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{"input":2,"output":1,"cacheRead":0,"cacheWrite":0,"totalTokens":3,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":12}}
{"type":"thinking_level_change","id":"e0a7b259","parentId":"a0000012","timestamp":"2026-07-23T05:26:37.962Z","thinkingLevel":"off"}
{"type":"custom","customType":"firstmate-synthetic-input-presentation","data":{"content":"FIRSTMATE WATCHER WAKE: signal: /tmp/active-probe.status\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.","kind":"watcher"},"id":"bf05a175","parentId":"e0a7b259","timestamp":"2026-07-23T05:26:38.476Z"}
{"type":"custom_message","customType":"firstmate-synthetic-input","content":"FIRSTMATE WATCHER WAKE: signal: /tmp/active-probe.status\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.","display":false,"details":{"kind":"watcher"},"id":"d6e16da2","parentId":"bf05a175","timestamp":"2026-07-23T05:26:38.476Z"}
{"type":"message","id":"f934688b","parentId":"d6e16da2","timestamp":"2026-07-23T05:26:38.477Z","message":{"role":"assistant","content":[],"api":"unknown","provider":"unknown","model":"unknown","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"Unknown provider: unknown","timestamp":1784784398477}}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (4) ✅
  • 🚨 .pi/extensions/lib/fm-calm-visibility.ts:138 - The required criterion says /export and /share must remain unchanged. This reroutes synthetic user messages into a plain custom entry plus a display: false custom message. Pi 0.81.1's HTML exporter ignores plain custom entries and renders custom messages only when display is true, so watcher and guard prompts disappear from exported/shared conversations instead of retaining stock user-message rendering. Either preserve them in exports or explicitly approve this behavior change.
  • 🚨 .pi/extensions/lib/fm-calm-visibility.ts:58 - The intent requires hiding "all known synthetic Firstmate user-role messages" across "every authoritative Firstmate injection path." The exhaustive kind union and classifier omit the generated brief that fm-spawn.sh passes to Pi secondmates as a positional user prompt. Because seeded secondmate homes load Calm, /calm leaves that Firstmate-authored brief visible as though it were genuine captain input. Confirm whether briefs are deliberately excluded, or add an origin marker, classification, and positive/near-miss fixtures.

🔧 Fix: Captain, preserve Calm exports and classify Pi launch briefs
2 errors still open:

  • 🚨 .pi/extensions/lib/fm-calm-visibility.ts:148 - The requested fix requires stock synthetic user-message rendering in /export and /share, but display: true only makes Pi's HTML exporter emit a hook-message with a visible [firstmate-synthetic-input] label. Pi 0.81.1 does not apply the registered TUI message renderer during HTML export, so the exported/shared row still differs from the stock user row. The E2E checks only the persisted display flag and does not verify the exported DOM or appearance.
  • 🚨 .pi/extensions/lib/fm-calm-visibility.ts:125 - The intent explicitly requires reviewing and preventing transcript gaps. Returning an empty Container here does not remove the complete row because Pi's CustomMessageComponent unconditionally prepends a Spacer(1) before invoking this renderer. Every hidden synthetic input therefore leaves a blank transcript line under Calm, and the renderer-only test bypasses that outer component. Use a presentation path that can suppress the whole component or explicitly approve the residual gaps.

🔧 Fix: Captain, eliminate Calm gaps and verify exported conversations
1 error still open:

  • 🚨 .pi/extensions/lib/fm-calm-visibility.ts:130 - The requirement says "Calm off must restore stock rendering," including "for subsequently delivered inputs." If a synthetic input arrives while Calm is active, this renderer returns undefined, and Pi 0.81.1 permanently skips adding that CustomEntryComponent because it initially has no content. The later setToolsExpanded redraw only rebuilds mounted components, so disabling Calm cannot reveal the row until a session reload. The test constructs its component before enabling Calm and misses this path. Preserve a gapless mounted representation or explicitly rebuild persisted presentation entries when Calm is disabled.

🔧 Fix: Restore Calm rows received while active
1 error still open:

  • 🚨 .pi/extensions/fm-calm.ts:259 - The intent requires preserving diagnostics and restoring stock rendering. Pi 0.81.1's ctx.navigateTree() wrapper unconditionally clears the entire chat container, rebuilds only reconstructable session rows, and adds Navigated to selected point, even when core navigation no-ops for the current leaf. Disabling Calm therefore deletes transient errors, warnings, extension notices, and other non-persisted diagnostics while adding a new status row. The regression mock models only the desired component rebuild, not this real clear-and-replace behavior. Use a refresh path that preserves transient rows, or explicitly approve this diagnostic loss and altered Calm-off transcript.

🔧 Fix: Preserve diagnostics during Calm restoration
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • git status --short and git diff --stat 82a79439d1d6f4ce2c16e0a25a7fff027b6abe0d..7aec7b23b46f1cd1b87827c2e8a8282fed77e43e
  • tests/fm-calm-pi-extension.test.sh
  • tests/fm-pi-primary-types.test.sh
  • tests/fm-pi-watch-extension.test.sh
  • tests/fm-spawn-dispatch-profile.test.sh
  • FM_PI_LIVE_E2E=1 tests/fm-pi-primary-live-e2e.test.sh
  • Fresh Pi 0.81.1 180x44 TUI evidence rerun preserving Calm-on, live-injection boundary, Calm-off, rendered export, and persisted-session artifacts
  • Rendered and visually inspected calm-terminal-e2e.png
  • Verified testing left no tracked changes or .pi-live-e2e.* directory
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kunchenguid
kunchenguid merged commit 6db3b09 into main Jul 23, 2026
10 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-calm-transcript-cleanup branch July 23, 2026 05:52
ItsFlow referenced this pull request in ItsFlow/firstmate Jul 26, 2026
* fix: block primary-session delegation outside the fleet (#854)

* feat: fence primary-session delegation outside the fleet

A firstmate primary that delegates through Claude Code's built-in
delegation tools creates work with no state/<id>.meta. Because
fm-supervision-lib.sh counts *.meta and fm-turnend-guard.sh exits
silently at zero, such work does not merely go unsupervised: it makes
the whole guard stack structurally inert, and it dies with the primary
session. On 2026-07-22 that cost two workers mid-flight and left
supervision down for 73 minutes unnoticed.

Layer 1, the primary fix: a permissions.deny list in
.claude/settings.json removes the 18 delegation, scheduling, worktree,
and task-tracking tools from the model's schema, so they are never
offered. This is removal rather than interception, so there is no call
to intercept and no fail-open path. The list is flat and in one file so
its width stays reviewable; the captain owns that width.

Layer 2, bin/fm-subagent-pretool-check.sh: a deny list is fail-open
against tools that do not exist yet, and permissions.allow is a
pre-approval list rather than an availability list, so there is no
fail-closed allowlist to use instead. This backstop classifies the tool
NAME by shape rather than against a fixed list, so a delegation tool
that ships before the deny list is updated is still refused. It excludes
mcp__* names and observe-or-stop operations, scopes itself to a genuine
primary home via the shared fm_primary_scope_matches predicate so a
crewmate's task worktree is unaffected, and offers one deliberate
FM_ALLOW_SUBAGENT=1 escape hatch that must be set at launch.

Verified live against Claude Code 2.1.217, including a deny-key A/B with
a nonsense-name control, layer 2 denying an un-denied Workflow call, the
same call allowed in a linked worktree, and the escape hatch. Corrects a
prior finding: both Task and Agent work as deny keys, so both are
pinned. Codex 0.144.1 verified to expose no delegation tool; grok,
opencode, and pi are inspected and documented as not wired because those
binaries are absent from this host and the repo requires live validation
before trusting a harness hook. Evidence in docs/subagent-guard.md.

* no-mistakes(review): Ship scoped Claude delegation guard

* no-mistakes(test): Ship Claude delegation deny list

* no-mistakes(document): Clarify PreToolUse guard ownership

* no-mistakes(lint): Keep Claude deny list local

* fix: install tasks-axi in portable CI shards (#866)

Reproduction: portable-parallel-2 completed successfully without tasks-axi while fm-decision-hold-lifecycle emitted a gate skip in 30 ms. The pre-shard lane installed tasks-axi and exercised the test fully. Installing tasks-axi is the smallest counterfactual and makes the representative shard execute the test with gate_skip=false in about 20 seconds. Both parallel jobs receive symmetric setup, while the exact 91-test inventory and coverage guard remain unchanged.

* feat(bin): make dispatch profiles quota aware (#867)

* feat: make dispatch profiles quota aware

* no-mistakes(review): Fix quota window and Grok product scoping

* no-mistakes(document): Document implicit quota-aware dispatch accurately

* Add built-in ahoy recap skill (#873)

* fix: preserve trustworthy Bearings data in partial snapshots (#875)

* fix: preserve mixed Bearings projections

* no-mistakes(review): Enforce strict invalidity precedence for partial snapshots

* no-mistakes(review): Enforce ownership for unknown child metadata

* no-mistakes(document): Document partial structured Bearings projections

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* feat(pi): add session-local calm mode (#884)

* Add session-local Pi calm mode

* no-mistakes(review): Preserve Pi HTML exports during calm mode

* no-mistakes(review): Preserve calm exports across submit bindings and share

* no-mistakes(document): Document calm-mode feasibility across supported harnesses

* fix(pi): prevent redundant watcher re-arms (#885)

* fix(pi): limit watcher arm tool to recovery

* no-mistakes(review): Strengthen Pi live re-arm regression coverage

* no-mistakes(document): Document Pi first-cycle and recovery-only watcher arming

* fix(pi): clean up Calm transcript rendering (#895)

* fix(pi): clean up Calm transcript rendering

* no-mistakes(review): Captain, preserve Calm exports and classify Pi launch briefs

* no-mistakes(review): Captain, eliminate Calm gaps and verify exported conversations

* no-mistakes(review): Restore Calm rows received while active

* no-mistakes(review): Preserve diagnostics during Calm restoration

* no-mistakes(document): Clarify Calm transcript behavior and injection paths

* fix: execute every PR body compliance event (#898)

* fix: execute every PR body compliance event

* no-mistakes(document): Document independent PR compliance events

* fix: exclude operational injections from ahoy boundaries (#899)

* fix: distinguish operational input in ahoy

* no-mistakes(review): Handle legacy Ahoy operational boundaries

* no-mistakes(review): Narrow legacy Ahoy boundaries with live regressions

* no-mistakes(document): Document Ahoy operational marker ownership

* no-mistakes(lint): Suppress intentional literal fixture lint warnings

* fix: canonically classify operational inputs across harnesses (#909)

* fix: type canonical operational inputs

* no-mistakes(document): Correct canonical operational-input documentation ownership

* fix: avoid generic secondmate start acknowledgements (#926)

* fix: avoid generic secondmate acknowledgements

* no-mistakes(document): Document sparse secondmate acknowledgement behavior

* no-mistakes: apply CI fixes

* fix(pi): make calm mode persistent and gapless (#927)

* fix(pi): preserve calm presentation across sessions

* no-mistakes(review): Fix Calm home fallback persistence

* no-mistakes(document): Clarify Calm gapless and export contracts

* no-mistakes: apply CI fixes

* fix(watch): retire merged PR polls after durable notification (#932)

* fix: retire merged PR polls after notification

* no-mistakes(review): Decouple PR retirement recovery from template updates

* no-mistakes(review): Recover pending PR retirements before poll migration

* no-mistakes(document): Document merged PR poll retirement contracts

* fix: refine scout intake and parallel dispatch (#934)

* Clarify intake evidence and overlap handling

* no-mistakes(review): Align scout guard with intake classification

* no-mistakes(document): Clarify scout documentation and intake ownership

* fix(pi): prevent duplicate assistant replies in Calm (#936)

* fix(pi): preserve operational follow-up semantics in Calm

* no-mistakes(document): Correct Calm operational-row visibility documentation

* perf(bin): shrink the ShellCheck source graph (#939)

* perf(lint): shrink shell source graph

* no-mistakes(review): Ensure lint workers terminate fully on cancellation

* no-mistakes(document): Repair stale lint documentation ownership

* fix(pi): remove Calm hidden-block gaps (#942)

* fix(pi): remove Calm hidden-block gaps

* no-mistakes(review): Validate Calm geometry against current viewport

* no-mistakes(review): Synchronize Calm geometry checks with reload completion

* fix: enforce contract boundaries for ask-user findings (#945)

* fix: escalate ask-user contract expansion

* no-mistakes(document): Point project management to authority owner

* docs: prefer direct operational paths (#946)

* fix(pi): hide operational user rows in Calm mode (#948)

* fix(pi): hide Calm operational user rows

* no-mistakes(review): Narrow Calm operational input suppression

* no-mistakes(review): Avoid Calm replay classifier subprocesses

* no-mistakes(document): docs: point Pi verification to Calm owner

* fix: relaunch missing second mates at session start (#950)

* fix(session-start): relaunch missing second mates

* fix(test): detect completed parallel workers

* no-mistakes(review): Isolate session-start recovery test cleanup

* no-mistakes(review): Complete backend-safe secondmate session recovery

* no-mistakes(review): Resolve Zellij task ownership before recovery

* no-mistakes(review): Recover relocated Zellij ghost tabs safely

* no-mistakes(review): Restore conservative Zellij recovery boundary

* no-mistakes(review): Reject malformed tmux recovery targets

* no-mistakes(document): Align secondmate recovery documentation

* no-mistakes: apply CI fixes

* fix(herdr): reclaim resumed task projections after restart (#967)

* fix(herdr): reclaim resumed task projections safely

* no-mistakes(review): Enforce safe Herdr reclaim close boundaries

* no-mistakes(document): docs: clarify Herdr restart projection contract

* Teach Ahoy to surface open decisions (#968)

* Require shipshape routine acknowledgement (#969)

* docs: separate current guidance from verification evidence (#994)

* docs: separate current guides from verification

* no-mistakes(review): Restore Herdr 0.7.5 restart-reclaim verification evidence

* fix: preserve Claude watcher continuity across Stop hooks (#997)

* feat(claude): Stop-owned tokenless watcher continuity via asyncRewake auto-arm

Claude primaries (main home and marked secondmate homes) no longer depend
on the model remembering to re-arm the watcher after each wake. A tracked
Stop asyncRewake hook (bin/fm-claude-stop-autoarm.sh, timeout 28800s)
fires on every turn end, claims one home-scoped single-flight owner,
foregrounds bin/fm-watch-arm.sh inside the hook-owned process tree, and
translates an actionable close or typed watcher failure into exactly one
exit-2 rewake. The hook scopes to genuine primary checkouts, requires the
session lock to be held by its own harness ancestor, stays inert while
AFK owns triage or the home is idle, and hands AFK transitions mid-cycle
to the daemon without rewaking.

The synchronous turn-end guard gains a --claude cooperative mode: it
ignores stop_hook_active (true on every post-continuation stop, which is
what re-opened the 2026-07-21 blind window), waits briefly for a watcher
health proof, a live auto-arm owner claim, or a fresh rewake epoch, and
re-blocks only when the auto-arm genuinely failed to establish - bounded
to 3 consecutive blocks per session, safely below Claude Code's 8-block
override, then a degraded allow with a visible systemMessage. Codex
keeps the previous one-block loop guard byte-identically, and Pi,
OpenCode, and Grok adapters are untouched.

Continuity PreToolUse gate and durable wake queue are preserved; the
gate's recovery guidance now names the Stop-owned re-arm and reserves
manual background arms for auto-arm failure. Claude supervision protocol,
harness-adapters facts, architecture, configuration, and continuity docs
updated; docs/turnend-guard.md records the 2026-07-24 Claude 2.1.218
contract revalidation (tokenless multi-cycle rewake, no-dedup, timeout
process-group kill, 8-block cap, interactive non-stall) and the 2.1.219
product live E2Es.

Regression matrix: hermetic tests cover scope, identity, AFK, need,
single-flight, translation, guard cooperation, budget, and registration;
the new live E2E proves two full tokenless auto-arm rewake cycles with
zero model arm commands; Pi and OpenCode Option B live E2Es pass
unchanged.

* no-mistakes(review): Fix Claude X-mode auto-arm continuity backstop

* no-mistakes(review): Remove unsupported Claude contract-lab verification claims

* no-mistakes(document): Update Claude auto-arm continuity documentation

* fix(herdr): clean stale projections at session start (#996)

* Clean stale Herdr projections at session start

* no-mistakes(document): Document stale Herdr session-start projection cleanup

* no-mistakes(review): Enforce locked exact Herdr projection cleanup

* no-mistakes(review): Fail closed on unverified session lock ownership

* no-mistakes(review): Serialize session lock acquisition atomically

* no-mistakes(document): Align session-start and Herdr cleanup documentation

* no-mistakes(document): Generalize lock-refusal diagnostics

* no-mistakes(lint): Avoid reserved keyword in concurrency test

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* feat(inbox): add the captain's decision and review board generator

bin/fm-inbox-view.sh writes one self-contained HTML board from live fleet
state, so every open captain decision, review-ready pull request and stopped
task is answerable from a single surface instead of arriving one chat
interrupt at a time.

It is a read-only projection in the same shape as fm-fleet-view.sh: it shells
out to fm-fleet-snapshot.sh --json and `tasks-axi show --full`, and writes
nothing but the board file. A test proves state/ and data/ stay byte-identical
across a generation.

Three selection defects the existing aggregated surface has are fixed here.
Decisions are selected on the captain hold alone, because the snapshot's own
captain_actionable flag also requires kind == "captain" and therefore hides
every thread gated with `tasks-axi hold --kind captain`, which is where the
oldest waiting decisions live.
Decision text is read through tasks-axi, because the snapshot's metadata
capture stops at the first comma and silently drops the options from any hold
reason that lists them.
A recorded pull request renders as unverified unless --verify-prs live-checks
it, because locally recorded metadata cannot know a pull request was closed
and a closed one must never read as ready to merge.

Decision cards lead with plain English. An optional captain-private cards file
supplies the plain question, what the captain is actually choosing, where it
came from, firstmate's recommendation, a link to research a product or
service, and a collapsed technical section. An item that is firstmate's own
assumption rather than a choice the captain made is flagged as one. A decision
with no card still renders and says so rather than looking complete.

Answers use the Lavish input contract: native radios plus a free-text note,
with exactly one queued prompt per question on submit. This change delivers
the surface only; regenerating on a cadence, relaying answers back, and any
escalation-routing change remain separate captain decisions.

* feat(inbox): free-form answers, discuss path, reliable delivery, overflow fix

Fold in the captain's hard requirements from live use of the board.

Free-form answers are now first-class. A card's predefined options are
optional quick-picks with a clear-selection reset; the answer submits with
just free text and no option selected. Previously the submit required picking
an offered option, so a genuine free-form answer could not be sent at all.

Each card gains a discuss path that sends a question back (DISCUSS <id>: ...)
instead of an answer (DECISION <id>: ...), so a decision can be clarified
rather than forced.

Delivery is made reliable end to end. bin/fm-inbox-serve.sh is one operator
command that regenerates the board, arms the answer relay, serves it on the
Tailscale address, and verifies the link. bin/fm-inbox-arm.sh writes and
registers state/inbox.check.sh, a bounded lavish poll bound by
fm-check-register, so firstmate's supervision cycle relays answers on its
normal check cadence without anyone remembering to poll. The relay fails
closed: when the board is not served the poll errors fast and it stays silent.
Submitting also sends immediately with a visible confirmation, closing the
window where an answer looked silently eaten.

Long titles and ids now wrap instead of overflowing horizontally, which
Lavish's own layout audit flags as an error. No-project items get readable
area names derived from their origin or id instead of a generic badge.

Behavior is covered by tests/fm-inbox-view.test.sh (generator, read-only,
free-form, discuss, immediate send, area names, wrapping) and
tests/fm-inbox-arm.test.sh (the relay is a valid registered fail-closed
check, silent while unserved, rejected after tampering). docs/inbox-board.md
records the design and verification evidence.

* no-mistakes(review): Fix inbox relay safety and PR verification

* no-mistakes(review): Gate inbox relay before polling

* no-mistakes(document): Align inbox board docs

* no-mistakes: apply CI fixes

---------

Co-authored-by: Kun Chen <[email protected]>
rega10 added a commit to rega10/firstmate that referenced this pull request Jul 27, 2026
* fix(herdr): group projected children beneath owning parents (kunchenguid#821)

* feat(herdr): correct all-home child presentation topology

Inherit the presentation opt-in to secondmate homes, label new projected
spaces with the approved corner format, insert each child under its owning
parent under one session-scoped lock, and keep flat non-destructive fallback.

* no-mistakes(review): Exclude secondmates from Herdr presentation projection

* no-mistakes(review): Harden shared Herdr locks and ambiguous child ordering

* no-mistakes(review): Use adjacency-only Herdr child ownership

* no-mistakes(review): Reject foreign legacy projections safely

* no-mistakes(review): Validate Herdr session sockets before projection

* no-mistakes(test): Fix Herdr teardown fixture session socket metadata

* fix(herdr): canonicalize presentation lock socket paths

Always resolve the session socket parent directory so symlink parents
such as /tmp -> /private/tmp cannot split the shared cross-home lock
identity. Refuse relative socket paths. Clarify lock-unavailable warnings.

* no-mistakes(test): Fix Bash-compatible GitLab merge request URL parsing

* no-mistakes(document): Document all-home Herdr child topology

* no-mistakes(lint): Quote fallback provenance string for ShellCheck

* fix: keep local no-mistakes tests intent-targeted (kunchenguid#823)

* fix(no-mistakes): drop full-suite local Test override

Local no-mistakes Test is intent-targeted; CI Behavior keeps the broad
tests/*.test.sh suite. Keep commands.lint on bin/fm-lint.sh and add a
focused contract test so the override cannot silently return.

* no-mistakes(lint): Make CI contract assertion ShellCheck-clean

* feat: add canonical timed test runner (kunchenguid#825)

* feat(test): add canonical timed suite runner and honest CI timeout

Introduce bin/fm-test-run.sh as the single serial owner for selecting
one script, a family, a conservative changed-file set, or the explicit
complete suite, with per-script timing markers and a JSON artifact.
Wire CI Behavior through the runner, raise the hang-tripwire timeout to
25 minutes, and document entry points without restoring a full-suite
local no-mistakes Test command.

* no-mistakes(review): Captain: fix changed selection and empty summaries

* no-mistakes(review): Captain: fail closed on unmapped changed sources

* no-mistakes(document): Document canonical timed test entry points

* fix: surface main inventory gaps in Bearings (kunchenguid#830)

* fix: disclose main-home orphan and unstructured inventory gaps

Main Bearings could report an empty fleet while structured in-flight rows
lacked meta or current backlog rows were free-form. Emit main_inventory from
the fleet snapshot, map it into Bearings omitted surfaces and a Charted Next
gate, and keep meta as the only live Underway source.

* no-mistakes(document): Document Bearings inventory-integrity projection

* no-mistakes: apply CI fixes

* feat: add bounded concurrent test isolation proof (kunchenguid#832)

* feat: add concurrent test isolation proof for Phase 2

Prove an audited portable candidate set passes under concurrent
workers with private mode-0700 temp roots, without enabling
production CI sharding or fm-test-run --jobs.

* no-mistakes(review): Pin isolation proof to audited candidate manifest

* feat: guard against missed secondmate reports (kunchenguid#834)

* feat(secondmate): parent-owned guards for missed status reports

Marked parent-to-secondmate requests now create a durable pending-reply
expectation with a privacy-safe correlation id before delivery. Transport
success never resolves it; only a correlated parent status or document
pointer does. After a completed turn with no report, the parent sends one
recovery repost and escalates once if that turn is also missed, without
scraping the secondmate conversation or looping.

* no-mistakes(review): Deduplicate wrong-home pending-reply sightings

* no-mistakes(review): Harden pending-reply recovery and escalation guards

* no-mistakes(review): Bound pending-reply backend polling

* no-mistakes(review): Cache pending-reply status scans

* no-mistakes(review): Protect undelivered pending-reply records from scans

* no-mistakes(review): Close pending-reply delivery durability gaps

* no-mistakes(review): Separate pending-reply transport outcomes

* no-mistakes(review): Escalate stalled pending-reply deliveries once

* no-mistakes(review): Resolve attempted deliveries from correlated reports

* no-mistakes(review): Resolve late reports after delivery escalation

* no-mistakes(document): Document pending-reply grace and ownership

* no-mistakes(lint): Silence intentional pending-reply test fixture lint warnings

* feat: require pinned real-Herdr CI coverage (kunchenguid#838)

* feat: add required pinned Herdr CI lane

Install exact Herdr 0.7.4 and Treehouse 2.0.1 with official assets and
SHA-256 pins, run the real-herdr-gated family serially through
fm-test-run with hard-fail on herdr-not-found, and keep portable
Behavior free of claimed Herdr coverage.

* no-mistakes(document): Consolidate real-Herdr CI documentation ownership

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* feat: shard portable tests and add bounded local parallelism (kunchenguid#841)

* feat: shard portable CI tests after isolation proof

Balance the Phase 2 proven-isolated set into two LPT portable parallel
lanes from Phase 1 timing evidence, keep stateful work in a required
portable serial lane, exclude real Herdr to its dedicated required lane,
and prove complete inventory coverage with a deterministic guard.
Add bounded local --jobs only for the proven set, per-lane timing plus
aggregate artifacts, and reduce the interim portable hang tripwire now
that the serial remainder owns the long wall-clock path.

* no-mistakes(review): Captain, fix CI contracts and completion-order worker scheduling

* no-mistakes(review): Captain, preserve stderr gate-skip detection in parallel tests

* no-mistakes(document): Document portable sharding and timing aggregation

* no-mistakes: apply CI fixes

* fix: block primary-session delegation outside the fleet (kunchenguid#854)

* feat: fence primary-session delegation outside the fleet

A firstmate primary that delegates through Claude Code's built-in
delegation tools creates work with no state/<id>.meta. Because
fm-supervision-lib.sh counts *.meta and fm-turnend-guard.sh exits
silently at zero, such work does not merely go unsupervised: it makes
the whole guard stack structurally inert, and it dies with the primary
session. On 2026-07-22 that cost two workers mid-flight and left
supervision down for 73 minutes unnoticed.

Layer 1, the primary fix: a permissions.deny list in
.claude/settings.json removes the 18 delegation, scheduling, worktree,
and task-tracking tools from the model's schema, so they are never
offered. This is removal rather than interception, so there is no call
to intercept and no fail-open path. The list is flat and in one file so
its width stays reviewable; the captain owns that width.

Layer 2, bin/fm-subagent-pretool-check.sh: a deny list is fail-open
against tools that do not exist yet, and permissions.allow is a
pre-approval list rather than an availability list, so there is no
fail-closed allowlist to use instead. This backstop classifies the tool
NAME by shape rather than against a fixed list, so a delegation tool
that ships before the deny list is updated is still refused. It excludes
mcp__* names and observe-or-stop operations, scopes itself to a genuine
primary home via the shared fm_primary_scope_matches predicate so a
crewmate's task worktree is unaffected, and offers one deliberate
FM_ALLOW_SUBAGENT=1 escape hatch that must be set at launch.

Verified live against Claude Code 2.1.217, including a deny-key A/B with
a nonsense-name control, layer 2 denying an un-denied Workflow call, the
same call allowed in a linked worktree, and the escape hatch. Corrects a
prior finding: both Task and Agent work as deny keys, so both are
pinned. Codex 0.144.1 verified to expose no delegation tool; grok,
opencode, and pi are inspected and documented as not wired because those
binaries are absent from this host and the repo requires live validation
before trusting a harness hook. Evidence in docs/subagent-guard.md.

* no-mistakes(review): Ship scoped Claude delegation guard

* no-mistakes(test): Ship Claude delegation deny list

* no-mistakes(document): Clarify PreToolUse guard ownership

* no-mistakes(lint): Keep Claude deny list local

* fix: install tasks-axi in portable CI shards (kunchenguid#866)

Reproduction: portable-parallel-2 completed successfully without tasks-axi while fm-decision-hold-lifecycle emitted a gate skip in 30 ms. The pre-shard lane installed tasks-axi and exercised the test fully. Installing tasks-axi is the smallest counterfactual and makes the representative shard execute the test with gate_skip=false in about 20 seconds. Both parallel jobs receive symmetric setup, while the exact 91-test inventory and coverage guard remain unchanged.

* feat(bin): make dispatch profiles quota aware (kunchenguid#867)

* feat: make dispatch profiles quota aware

* no-mistakes(review): Fix quota window and Grok product scoping

* no-mistakes(document): Document implicit quota-aware dispatch accurately

* Add built-in ahoy recap skill (kunchenguid#873)

* fix: preserve trustworthy Bearings data in partial snapshots (kunchenguid#875)

* fix: preserve mixed Bearings projections

* no-mistakes(review): Enforce strict invalidity precedence for partial snapshots

* no-mistakes(review): Enforce ownership for unknown child metadata

* no-mistakes(document): Document partial structured Bearings projections

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* feat(pi): add session-local calm mode (kunchenguid#884)

* Add session-local Pi calm mode

* no-mistakes(review): Preserve Pi HTML exports during calm mode

* no-mistakes(review): Preserve calm exports