SLOPSHOPPER

mandrel-status

Beta, read-only: shows the current /mandrel-deliver Story above the prompt

panebandtoasttimer
★ 7v0.1.0MITupdated 2026-10-26dsj1984/mandrel/.agents/mods/mandrel-status
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · mandrel-status
│ ┃ mandrel-status ✕ › fix the failing auth test and add an audit log call │ ┃ No /mandrel-deliver Story in flight or rece… │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · mandrel-status
No /mandrel-deliver Story in flight or recent.
README

Mandrel

CI / CD

Mandrel gives your AI coding assistant a disciplined software process. Out of the box, an assistant like Claude Code will happily write code, but it has no shared idea of how work gets planned, verified, reviewed, and shipped. Mandrel supplies that: a system prompt, rules, skills, and slash-command workflows that turn "build me X" into a planned GitHub Story, an isolated branch, a tested change, and a reviewed pull request that merges itself once CI is green.

It is Claude Code-first and GitHub-native: planning, execution state, and history all live in GitHub Issues, Labels, Pull Requests, and Projects V2, so there is no extra service to run and every step leaves a visible record.

Mandrel ships as the mandrel npm package. mandrel sync copies its payload into your project's .agents/ directory, where your assistant reads it.

What's in .agents/

PathWhat it is
instructions.mdThe always-loaded system prompt — the assistant's core operating protocol.
rules/Non-negotiable standards. A small core (security baseline, git conventions) is always on; the rest (testing, API, CI remediation, Gherkin) load when the work calls for them.
skills/Focused guidance loaded on demand: core/ for universal practice (code review, security, documentation, quality gates), stack/ for specific tools (Playwright, Gherkin, the QA harness).
workflows/The slash commands — /mandrel-plan, /mandrel-deliver, the /audit-* lenses, QA, and housekeeping. Projected into .claude/commands/.
agents/Role-scoped sub-agent contexts (story worker, auditor, critics). Projected into .claude/agents/.
scripts/Deterministic Node.js CLIs that do the mechanical work — GitHub state changes, worktrees, quality gates — so the model judges and the scripts execute.
schemas/, templates/JSON Schema contracts and the prompt/planning templates the workflows fill in.
docs/Consumer reference: configuration (every .agentrc.json key), the workflow index, and operator runbooks.
audit-checklists/Generated per-lens authoring checklists, threaded into a Story's write-time checklist when its change set matches an audit lens.
mods/Beta, opt-in Claude Code mods — see the mods runbook.
local/Yours. mandrel sync never touches it, so project-specific skills and workflow fragments survive upgrades.

Project settings live in .agentrc.json at your repo root. The table above is a partial list (it omits single files such as starter-agentrc.json); the full tour of the bundle is in .agents/README.md.

The core loop: plan, then deliver

Two commands carry almost all of the work.

/mandrel-plan

/mandrel-plan turns an idea into a ready-to-execute GitHub Story. There are no flags to remember — it works out what you meant from what you typed and tells you what it inferred:

/mandrel-plan let users export their reports as CSV   # plan from a description
/mandrel-plan 4712                                    # plan an existing issue

It gathers context from your repo, then authors a Story whose ## Spec holds the technical plan and whose acceptance[] / verify[] lists are the contract the delivery is held to. It writes one Story by default, splitting only when the pieces are truly independent; larger efforts can be grouped under a container Epic.

/mandrel-deliver

/mandrel-deliver lands the work:

/mandrel-deliver 4712                    # a single Story
/mandrel-deliver 4700                    # an Epic — delivers its open child Stories
/mandrel-deliver 4712 - 4716             # a range of Stories
/mandrel-deliver fix the typo in the login page header   # direct text, no plan

Each Story gets its own story-<id> branch in an isolated worktree; the assistant implements it, checks its work against the acceptance criteria, runs the test suite and quality gates, opens a PR, gets it reviewed, and arms auto-merge. Multiple Stories are sequenced by their dependencies, with independent ones running in parallel sub-agents. Direct text is for small, unplanned work: it authors a receipt Story on the fly and escalates to /mandrel-plan if the work turns out bigger than it looked.

The full process — labels, state, review, troubleshooting — is in docs/SDLC.md.

Audits

The /audit-* workflows are read-only lenses that examine the codebase along one dimension and write a findings report (severity, location, recommendation, acceptance signal) under temp/audits/audit-results/. They never change code — fixing is a separate, planned pass.

AreaLenses
Code & designarchitecture, clean-code, adrs, data-model, documentation, exceptions, lean
Quality & opsquality, baselines, performance, devops, sre, dependencies
Security & privacysecurity, privacy
Product & UXux-ui, accessibility, mobile, navigability, seo

Run one manually (e.g. /audit-security) for a codebase-wide pass, then run /audit-to-stories to group the findings, deduplicate them against open issues, and turn them into Stories — feeding them back into /mandrel-plan → /mandrel-deliver. Multi-Story deliveries can also run the relevant cross-cutting lenses over the combined change when they finish.

Other workflows cover QA (/qa-explore, /qa-assist, /qa-run), UI prototyping (/prototype), ad-hoc commits (/git-deliver), and housekeeping (/clean-git, /clean-worktrees, /clean-temp). See the workflow index for the full list.

Getting started

Prerequisites

  • Node.js >=22.22.1 <25
  • git on your PATH
  • GitHub CLI gh >= 2.40, authenticated with gh auth login. To let bootstrap create a Projects V2 board, also grant the project scope with gh auth refresh -s project; without it, bootstrap warns and skips the board.

You do not need an existing git repo or GitHub remote — bootstrap creates both if they're missing.

Install

npx mandrel init

This installs mandrel (if .agents/ is absent), materializes .agents/, and asks whether to configure now or stop at just the files. Configuring runs bootstrap.js — which seeds .agentrc.json, wires the system prompt, and provisions the GitHub side (repo, labels, branch protection, board) — then detects your stack, offers to scaffold docs, runs mandrel doctor, and hands you off to /mandrel-plan. Use --assume-yes for a non-interactive run.

Bootstrap infers owner, repo, base branch, and operator handle from your git remote and config, prompting only for what it can't infer. Override with --owner, --repo, --base-branch, --operator-handle, or --visibility private|public|internal for a newly created repo. It is idempotent — safe to re-run.

npm install mandrel                 # pins an exact, provenance-signed version
npx mandrel sync                    # materialize ./.agents/ (postinstall usually does this)
node .agents/scripts/bootstrap.js   # wire the project and GitHub
npx mandrel doctor                  # verify the install

Bootstrap adds a guarded prepare script that regenerates .claude/commands/ and .claude/agents/ from .agents/. Both are generated and gitignored — never commit them.

pnpm users: the .agents/scripts/ CLIs resolve their dependencies from your top-level node_modules, which pnpm's isolated layout doesn't populate. Add shamefully-hoist=true to .npmrc (or a public-hoist-pattern[]= line per package in .agents/runtime-deps.json). If mandrel doctor reports runtime-deps missing, this is the fix.

Updating

Inside Claude Code, run:

/mandrel-update

It upgrades to the newest published mandrel, re-syncs .agents/, applies migrations, checks the install, and walks you through reconciling your config and committing the bump.

Contributing

Only .agents/, bin/, lib/, and docs/CHANGELOG.md are published (see the files array in package.json); everything else here is development tooling for Mandrel itself.

npm run lint           # biome + markdownlint + repo ratchets + generated-doc drift
npm run format         # biome format (JS/JSON only)
npm test               # framework tests
npm run test:coverage  # tests with the coverage gate

A few things to know:

  • Quality gates are blocking at four sites — pre-commit (staged files), pre-push (diff vs origin/main), Story close, and CI — using the CRAP and maintainability thresholds in delivery.quality.*. A green lint/test run does not predict them.
  • Install scripts are off — the committed .npmrc sets ignore-scripts=true as supply-chain defense. Use npm install --ignore-scripts=false for a one-off exception.
  • Releases are automated by release-please from Conventional Commits on main.

Further reading: AGENTS.md (repo orientation), docs/onboarding.md (layout, commands, standards), docs/architecture.md (module map, tech stack), docs/release-operations.md, and docs/CHANGELOG.md.

License

MIT

Source 2 files
hooks/register.tsx 1444 lines
1// mandrel-status — a beta, read-only Claude Code mod. It reads the state files
2// /mandrel-deliver already writes and draws a short band above the prompt, plus
3// a Details pane. Nothing in Mandrel depends on it; see
4// .agents/docs/runbooks/mods.md.
5
6import type { EngineInterface, FsEntry, Register } from 'claude-code';
7import { atom, read, update } from 'claude-code';
8
9import type {
10  Attention,
11  ChipState,
12  Focus,
13  Learned,
14  PhaseRow,
15  RunLine,
16  Snapshot,
17  StageName,
18  StageRow,
19  Tracked,
20} from '../types';
21
22const REFRESH_MS = 15_000;
23const LEARN_MS = 10 * 60_000;
24const STALL_MS = 10 * 60_000;
25const MIN_STALL_MS = 2 * 60_000;
26/** How long a run ledger, or a result that did not land, stays on the band. */
27const RECENT_MS = 2 * 60 * 60_000;
28/** How long a landed result stays on the band. */
29const LANDED_MS = 10 * 60_000;
30const MIN_SAMPLES = 3;
31const MAX_SAMPLES = 30;
32/** Under this many body columns the band keeps only its first line. */
33const NARROW = 80;
34/** Cells the Hide and Details buttons take at the end of line 1. */
35const BUTTON_CELLS = 18;
36/** Cells the Copy button and the Open PR link take at the end of line 2. */
37const ACTION_CELLS = 18;
38/** The title's share of line 1. */
39const TITLE_CELLS = 30;
40/** Unmet acceptance ids named before `+N`. */
41const MAX_UNMET = 4;
42/** The longest bar in the Details pane. */
43const BAR_CELLS = 16;
44const PANE = 'mandrel-status';
45
46const STAGES: StageName[] = [
47  'start',
48  'build',
49  'check',
50  'handoff',
51  'close',
52  'merge',
53];
54const CLOSE_PHASES = [
55  'wrong-tree-guard',
56  'base-sync',
57  'close-validation',
58  'push',
59  'pull-request',
60  'code-review',
61  'auto-merge',
62  'confirm-merge',
63  'post-land',
64];
65const MERGE_PHASES = new Set(['auto-merge', 'confirm-merge']);
66/** Stages the mod times itself; close and merge come from envelope phases. */
67const LEARNED_STAGES = new Set<StageName>([
68  'start',
69  'build',
70  'check',
71  'handoff',
72]);
73const FAILED = new Set(['failed', 'escalated']);
74const TERMINAL = new Set(['landed', 'blocked', 'failed', 'escalated']);
75
76const WORKTREE = /^story-(\d+)$/;
77const ENVELOPE = /^story-deliver-terminal-(\d+)\.json$/;
78const VERDICT = /^acceptance-verdict-round-(\d+)\.json$/;
79const RUN_DIR = /^run-[\w-]+$/;
80const GITDIR = /^gitdir:\s*(.+?)\s*$/m;
81const MAIN_OF = /^(.+)\/\.git\/worktrees\/[^/]+$/;
82const INIT_MARKER = '--- STORY INIT RESULT ---';
83const TITLE = /"storyTitle"\s*:\s*("(?:[^"\\]|\\.)*")/;
84const GATE = /^\[([^\]]+)\]/;
85const REFLOG_TIME = /\s(\d+)\s[+-]\d{4}$/;
86const BULLET = /^\s*[-*]\s+\S/;
87
88const EMPTY: Snapshot = { focus: null, run: null, scannedAt: 0 };
89const snapshot = atom(
90  { plugin: 'mandrel-status', key: 'snapshot' } as const,
91  EMPTY,
92);
93const seen = atom(
94  { plugin: 'mandrel-status', key: 'seen' } as const,
95  [] as string[],
96);
97const isSeeded = atom(
98  { plugin: 'mandrel-status', key: 'isSeeded' } as const,
99  false,
100);
101const learnedAtom = atom(
102  { plugin: 'mandrel-status', key: 'learned' } as const,
103  { at: 0, phases: {} } as Learned,
104);
105const stageSamples = atom(
106  { plugin: 'mandrel-status', key: 'stageSamples' } as const,
107  {} as Partial<Record<StageName, number[]>>,
108);
109const tracked = atom(
110  { plugin: 'mandrel-status', key: 'tracked' } as const,
111  null as Tracked | null,
112);
113const hiddenFor = atom(
114  { plugin: 'mandrel-status', key: 'hiddenFor' } as const,
115  null as string | null,
116);
117
118type Stamped = { storyId: number; mtimeMs: number };
119
120/** Where a scan reads: the main checkout, its tempRoot, the orchestration listing. */
121type Ctx = {
122  root: string;
123  temp: string;
124  orchestration: string;
125  files: FsEntry[];
126  now: number;
127  /** `https://github.com/<owner>/<repo>` from the merged config, when it names both. */
128  repoUrl: string | null;
129};
130
131type Envelope = {
132  storyId: number;
133  at: number;
134  status: string;
135  /** Where the delivery stopped, as the envelope's `phase` names it. */
136  phase: string | null;
137  prNumber: number | null;
138  prUrl: string | null;
139  checksStatus: string | null;
140  elapsedSeconds: number | null;
141  phaseDurations: Record<string, number>;
142  problem: string | null;
143  nextCommand: string | null;
144};
145
146type Progress = {
147  stage: string;
148  phase: string | null;
149  stageStartedAt: number | null;
150  phaseStartedAt: number | null;
151  prNumber: number | null;
152  updatedAt: number;
153};
154
155type Commits = { at: number; firstAt: number; count: number; subject: string };
156type Verdict = {
157  at: number;
158  firstAt: number;
159  round: number;
160  met: number;
161  total: number;
162  /** 1-based ids of the criteria not `met`. */
163  unmet: number[];
164};
165type Handoff = {
166  at: number;
167  firstAt: number;
168  step: string | null;
169  steps: { name: string; at: number }[];
170  doneAt: number | null;
171};
172
173/** Everything on disk about one Story, each piece stamped with its time. */
174type Evidence = {
175  init: { at: number; title: string | null } | null;
176  build: Commits | null;
177  check: Verdict | null;
178  handoff: Handoff | null;
179  close: { at: number; gate: string | null } | null;
180  progress: Progress | null;
181  envelope: Envelope | null;
182  followUps: number | null;
183};
184
185// ---------------------------------------------------------------- reading
186
187const num = (value: unknown): number | null =>
188  typeof value === 'number' && Number.isFinite(value) ? value : null;
189const str = (value: unknown): string | null =>
190  typeof value === 'string' && value.length > 0 ? value : null;
191
192/** An epoch-ms number or an ISO string, as the progress file and ledger write them. */
193function toMs(value: unknown): number | null {
194  if (typeof value === 'number') return num(value);
195  if (typeof value !== 'string') return null;
196  const parsed = Date.parse(value);
197  return Number.isNaN(parsed) ? null : parsed;
198}
199
200const join = (root: string, path: string): string =>
201  root === '.' || path.startsWith('/') ? path : `${root}/${path}`;
202
203async function readText(
204  $: EngineInterface,
205  path: string,
206): Promise<string | null> {
207  try {
208    return await $.fs.read(path);
209  } catch {
210    return null;
211  }
212}
213
214async function readJson($: EngineInterface, path: string): Promise<unknown> {
215  const text = await readText($, path);
216  if (text === null) return undefined;
217  try {
218    return JSON.parse(text);
219  } catch {
220    return undefined;
221  }
222}
223
224/**
225 * The main checkout: a linked worktree's `.git` file names it as
226 * `gitdir: <main>/.git/worktrees/<name>`; anywhere else it is `.`.
227 */
228async function resolveRoot($: EngineInterface): Promise<string> {
229  const gitdir = GITDIR.exec((await readText($, '.git')) ?? '')?.[1];
230  const main = gitdir
231    ? MAIN_OF.exec(gitdir.replace(/\\/g, '/'))?.[1]
232    : undefined;
233  return main ?? '.';
234}
235
236type Config = {
237  project?: { paths?: { tempRoot?: unknown } };
238  github?: { owner?: unknown; repo?: unknown };
239};
240
241/**
242 * `.agentrc.local.json` wins over `.agentrc.json`, key by key; tempRoot is
243 * `temp` when neither sets it, and the repo address needs both owner and repo.
244 */
245async function resolveConfig(
246  $: EngineInterface,
247  root: string,
248): Promise<{ temp: string; repoUrl: string | null }> {
249  const configs = [
250    (await readJson($, join(root, '.agentrc.local.json'))) as Config,
251    (await readJson($, join(root, '.agentrc.json'))) as Config,
252  ];
253  const first = (pick: (config: Config) => unknown): string | null =>
254    configs.map((config) => str(pick(config ?? {}))).find(Boolean) ?? null;
255  const owner = first((config) => config?.github?.owner);
256  const repo = first((config) => config?.github?.repo);
257  return {
258    temp: join(
259      root,
260      first((config) => config?.project?.paths?.tempRoot) ?? 'temp',
261    ),
262    repoUrl: owner && repo ? `https://github.com/${owner}/${repo}` : null,
263  };
264}
265
266async function listMatching(
267  $: EngineInterface,
268  dir: string,
269  pattern: RegExp,
270): Promise<Stamped[]> {
271  const entries = await $.fs.list(dir).catch(() => []);
272  const found: Stamped[] = [];
273  for (const entry of entries) {
274    const match = pattern.exec(entry.name);
275    if (!match || entry.kind !== 'dir') continue;
276    const mtimeMs = await $.fs
277      .stat(`${dir}/${entry.name}`)
278      .then((stat) => stat.mtimeMs)
279      .catch(() => 0);
280    found.push({ storyId: Number(match[1]), mtimeMs });
281  }
282  return found;
283}
284
285function stampFiles(files: FsEntry[], pattern: RegExp): Stamped[] {
286  return files.flatMap((entry) => {
287    const match = pattern.exec(entry.name);
288    return match && entry.kind === 'file'
289      ? [{ storyId: Number(match[1]), mtimeMs: entry.mtimeMs }]
290      : [];
291  });
292}
293
294const fileNamed = (ctx: Ctx, name: string): FsEntry | undefined =>
295  ctx.files.find((entry) => entry.name === name && entry.kind === 'file');
296
297const newest = (list: Stamped[]): Stamped | undefined =>
298  [...list].sort((a, b) => b.mtimeMs - a.mtimeMs)[0];
299
300function toEnvelope(
301  storyId: number,
302  at: number,
303  raw: unknown,
304): Envelope | null {
305  const body = raw as {
306    status?: unknown;
307    phase?: unknown;
308    elapsedSeconds?: unknown;
309    nextCommand?: unknown;
310    phaseDurations?: unknown;
311    pr?: { number?: unknown; url?: unknown; checksStatus?: unknown } | null;
312    blocked?: { blockClass?: unknown } | null;
313    failure?: { reason?: unknown } | null;
314  };
315  const status = str(body?.status);
316  if (status === null) return null;
317  const pr = body.pr ?? {};
318  return {
319    storyId,
320    at,
321    status,
322    phase: str(body.phase),
323    prNumber: num(pr.number),
324    prUrl: str(pr.url),
325    checksStatus: str(pr.checksStatus),
326    elapsedSeconds: num(body.elapsedSeconds),
327    phaseDurations: durationsOf(body.phaseDurations),
328    problem: str(body.blocked?.blockClass) ?? str(body.failure?.reason),
329    nextCommand: str(body.nextCommand),
330  };
331}
332
333function durationsOf(raw: unknown): Record<string, number> {
334  if (!raw || typeof raw !== 'object') return {};
335  return Object.fromEntries(
336    Object.entries(raw).filter(
337      (pair): pair is [string, number] => num(pair[1]) !== null && pair[1] >= 0,
338    ),
339  );
340}
341
342async function readEnvelope(
343  $: EngineInterface,
344  ctx: Ctx,
345  stamp: Stamped,
346): Promise<Envelope | null> {
347  const raw = await readJson(
348    $,
349    `${ctx.orchestration}/story-deliver-terminal-${stamp.storyId}.json`,
350  );
351  return toEnvelope(stamp.storyId, stamp.mtimeMs, raw);
352}
353
354async function readInit(
355  $: EngineInterface,
356  ctx: Ctx,
357  id: number,
358): Promise<Evidence['init']> {
359  const entry = fileNamed(ctx, `story-init-result-${id}.log`);
360  if (!entry) return null;
361  const text = (await readText($, `${ctx.orchestration}/${entry.name}`)) ?? '';
362  const body = text.slice(Math.max(0, text.indexOf(INIT_MARKER)));
363  const quoted = TITLE.exec(body)?.[1];
364  let title: string | null = null;
365  try {
366    title = quoted ? str(JSON.parse(quoted)) : null;
367  } catch {
368    title = null;
369  }
370  return { at: entry.mtimeMs, title };
371}
372
373/** The `commit…` lines of a reflog: count, last subject, first and last time. */
374function parseReflog(text: string): Commits | null {
375  const commits = text.split('\n').flatMap((line) => {
376    const tab = line.indexOf('\t');
377    const message = tab < 0 ? '' : line.slice(tab + 1);
378    if (!message.startsWith('commit')) return [];
379    const seconds = Number(REFLOG_TIME.exec(line.slice(0, tab))?.[1]);
380    return [
381      {
382        subject: message.replace(/^commit[^:]*:\s*/, ''),
383        at: Number.isFinite(seconds) ? seconds * 1000 : 0,
384      },
385    ];
386  });
387  const last = commits.at(-1);
388  if (!last) return null;
389  return {
390    at: last.at,
391    firstAt: commits[0].at,
392    count: commits.length,
393    subject: last.subject,
394  };
395}
396
397async function readBuild(
398  $: EngineInterface,
399  ctx: Ctx,
400  id: number,
401): Promise<Commits | null> {
402  const pointer = await readText(
403    $,
404    join(ctx.root, `.worktrees/story-${id}/.git`),
405  );
406  const gitdir =
407    GITDIR.exec(pointer ?? '')?.[1] ??
408    join(ctx.root, `.git/worktrees/story-${id}`);
409  const reflog = await readText($, `${gitdir}/logs/HEAD`);
410  return reflog === null ? null : parseReflog(reflog);
411}
412
413async function readCheck(
414  $: EngineInterface,
415  ctx: Ctx,
416  id: number,
417): Promise<Verdict | null> {
418  const dir = `${ctx.temp}/scratch/story-${id}`;
419  const rounds = (await $.fs.list(dir).catch(() => [])).flatMap((entry) => {
420    const match = VERDICT.exec(entry.name);
421    return match && entry.kind === 'file'
422      ? [{ round: Number(match[1]), entry }]
423      : [];
424  });
425  if (rounds.length === 0) return null;
426  const last = rounds.reduce((a, b) => (b.round > a.round ? b : a));
427  const raw = (await readJson($, `${dir}/${last.entry.name}`)) as {
428    criteria?: { index?: unknown; verdict?: unknown }[];
429  };
430  const criteria = Array.isArray(raw?.criteria) ? raw.criteria : [];
431  const unmet = criteria.flatMap((one, at) =>
432    one?.verdict === 'met' ? [] : [(num(one?.index) ?? at) + 1],
433  );
434  return {
435    at: last.entry.mtimeMs,
436    firstAt: Math.min(...rounds.map((one) => one.entry.mtimeMs)),
437    round: last.round,
438    met: criteria.filter((one) => one?.verdict === 'met').length,
439    total: criteria.length,
440    unmet,
441  };
442}
443
444function readHandoff(ctx: Ctx, id: number): Handoff | null {
445  const prefix = `story-handoff-${id}-`;
446  const steps = ctx.files
447    .filter(
448      (entry) =>
449        entry.kind === 'file' &&
450        entry.name.startsWith(prefix) &&
451        entry.name.endsWith('.log'),
452    )
453    .map((entry) => ({
454      name: entry.name.slice(prefix.length, -'.log'.length),
455      at: entry.mtimeMs,
456    }))
457    .sort((a, b) => a.at - b.at);
458  const doneAt = fileNamed(ctx, `story-handoff-${id}.json`)?.mtimeMs ?? null;
459  const times = [...steps.map((one) => one.at), doneAt ?? 0];
460  if (steps.length === 0 && doneAt === null) return null;
461  return {
462    at: Math.max(...times),
463    firstAt: steps[0]?.at ?? doneAt ?? 0,
464    step: steps.at(-1)?.name ?? null,
465    steps,
466    doneAt,
467  };
468}
469
470async function readClose(
471  $: EngineInterface,
472  ctx: Ctx,
473  id: number,
474): Promise<Evidence['close']> {
475  const entry = fileNamed(ctx, `close-gates-${id}.log`);
476  if (!entry) return null;
477  const text = (await readText($, `${ctx.orchestration}/${entry.name}`)) ?? '';
478  const last = text
479    .split('\n')
480    .filter((line) => line.trim().length > 0)
481    .at(-1);
482  return { at: entry.mtimeMs, gate: GATE.exec(last ?? '')?.[1] ?? null };
483}
484
485/** The sibling Story's progress file; read when present, never required. */
486async function readProgress(
487  $: EngineInterface,
488  ctx: Ctx,
489  id: number,
490): Promise<Progress | null> {
491  if (!fileNamed(ctx, `story-progress-${id}.json`)) return null;
492  const raw = (await readJson(
493    $,
494    `${ctx.orchestration}/story-progress-${id}.json`,
495  )) as Record<string, unknown> | undefined;
496  const updatedAt = toMs(raw?.updatedAt);
497  const stage = str(raw?.stage);
498  if (raw?.kind !== 'story-progress' || updatedAt === null || stage === null)
499    return null;
500  return {
501    stage,
502    phase: str(raw.phase),
503    stageStartedAt: toMs(raw.stageStartedAt),
504    phaseStartedAt: toMs(raw.phaseStartedAt),
505    prNumber: num(raw.prNumber),
506    updatedAt,
507  };
508}
509
510async function readFollowUps(
511  $: EngineInterface,
512  ctx: Ctx,
513  id: number,
514): Promise<number | null> {
515  const name = `follow-ups-rollup-${id}.md`;
516  if (!fileNamed(ctx, name)) return null;
517  const text = await readText($, `${ctx.orchestration}/${name}`);
518  return text === null
519    ? null
520    : text.split('\n').filter((line) => BULLET.test(line)).length;
521}
522
523async function gather(
524  $: EngineInterface,
525  ctx: Ctx,
526  id: number,
527  envelope: Envelope | null,
528): Promise<Evidence> {
529  const [init, build, check, close, progress, followUps] = await Promise.all([
530    readInit($, ctx, id),
531    readBuild($, ctx, id),
532    readCheck($, ctx, id),
533    readClose($, ctx, id),
534    readProgress($, ctx, id),
535    readFollowUps($, ctx, id),
536  ]);
537  return {
538    init,
539    build,
540    check,
541    handoff: readHandoff(ctx, id),
542    close,
543    progress,
544    envelope,
545    followUps,
546  };
547}
548
549// --------------------------------------------------------------- learning
550
551function median(list: number[]): number {
552  const sorted = [...list].sort((a, b) => a - b);
553  const mid = Math.floor(sorted.length / 2);
554  return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
555}
556
557/** Medians of each close phase over the newest 30 envelopes; at most every 10 minutes. */
558async function learn(
559  $: EngineInterface,
560  ctx: Ctx,
561  envelopes: Stamped[],
562): Promise<Learned> {
563  const held = await read($, learnedAtom);
564  if (held.at > 0 && ctx.now - held.at < LEARN_MS) return held;
565  const samples: Record<string, number[]> = {};
566  const recent = [...envelopes]
567    .sort((a, b) => b.mtimeMs - a.mtimeMs)
568    .slice(0, MAX_SAMPLES);
569  for (const stamp of recent) {
570    const envelope = await readEnvelope($, ctx, stamp);
571    for (const [name, seconds] of Object.entries(
572      envelope?.phaseDurations ?? {},
573    )) {
574      samples[name] = [...(samples[name] ?? []), seconds];
575    }
576  }
577  const phases = Object.fromEntries(
578    Object.entries(samples).map(([name, list]) => [
579      name,
580      { medianSeconds: median(list), samples: list.length },
581    ]),
582  );
583  const next: Learned = { at: ctx.now, phases };
584  await update($, learnedAtom, () => next);
585  return next;
586}
587
588// ---------------------------------------------------------------- deriving
589
590function stageTimes(ev: Evidence): Partial<Record<StageName, number>> {
591  const handoff = ev.handoff
592    ? Math.max(ev.handoff.at, ev.handoff.doneAt ?? 0)
593    : undefined;
594  return {
595    start: ev.init?.at,
596    build: ev.build?.at,
597    check: ev.check?.at,
598    handoff,
599    close: ev.close?.at,
600    merge: ev.envelope?.status === 'pending' ? ev.envelope.at : undefined,
601  };
602}
603
604/**
605 * The current stage: the furthest one with evidence, back to build when a
606 * commit follows the last verdict round; a progress file newer than every
607 * other piece of evidence decides instead.
608 */
609function pickStage(ev: Evidence): {
610  stage: StageName;
611  progress: Progress | null;
612} {
613  const times = stageTimes(ev);
614  let stage: StageName = 'start';
615  for (const name of STAGES) if (times[name] !== undefined) stage = name;
616  if (stage === 'check' && (times.build ?? 0) > (times.check ?? 0))
617    stage = 'build';
618  const latest = Math.max(0, ...Object.values(times).map((at) => at ?? 0));
619  const progress =
620    ev.progress && ev.progress.updatedAt >= latest ? ev.progress : null;
621  if (progress?.phase && MERGE_PHASES.has(progress.phase))
622    return { stage: 'merge', progress };
623  if (progress?.stage === 'handoff' || progress?.stage === 'close')
624    return { stage: progress.stage, progress };
625  return { stage, progress: null };
626}
627
628function stageStarts(ev: Evidence): Record<StageName, number | null> {
629  const known = ev.progress;
630  const mergeStart =
631    known?.phase && MERGE_PHASES.has(known.phase) ? known.phaseStartedAt : null;
632  return {
633    start: ev.init?.at ?? null,
634    build: ev.build?.firstAt ?? null,
635    check: ev.check?.firstAt ?? null,
636    handoff: ev.handoff?.firstAt ?? null,
637    close:
638      (known?.stage === 'close' ? known.stageStartedAt : null) ??
639      ev.handoff?.doneAt ??
640      ev.close?.at ??
641      null,
642    merge:
643      mergeStart ?? (ev.envelope?.status === 'pending' ? ev.envelope.at : null),
644  };
645}
646
647/** The learned median of a stage the mod times itself, once it has 3+ samples. */
648function stageUsualMs(
649  samples: Partial<Record<StageName, number[]>>,
650  stage: StageName,
651): number | null {
652  const list = LEARNED_STAGES.has(stage) ? (samples[stage] ?? []) : [];
653  return list.length >= MIN_SAMPLES ? median(list) * 1000 : null;
654}
655
656function stageRows(
657  ev: Evidence,
658  current: StageName,
659  samples: Partial<Record<StageName, number[]>>,
660): StageRow[] {
661  const starts = stageStarts(ev);
662  const at = STAGES.indexOf(current);
663  return STAGES.map((name, index) => {
664    const later = STAGES.slice(index + 1, at + 1)
665      .map((next) => starts[next])
666      .find((value) => value !== null);
667    return {
668      name,
669      startedAt: index <= at ? starts[name] : null,
670      endedAt: index < at ? (later ?? null) : null,
671      usualMs: stageUsualMs(samples, name),
672    };
673  });
674}
675
676/** The close phase the band times, when the stage has one. */
677function phaseOf(stage: StageName, progress: Progress | null): string | null {
678  if (stage === 'close') return progress?.phase ?? 'close-validation';
679  if (stage === 'merge') return progress?.phase ?? 'confirm-merge';
680  return null;
681}
682
683const plural = (count: number, word: string): string =>
684  `${count} ${word}${count === 1 ? '' : 's'}`;
685
686/** The stage name, or the stage and what it is doing: `check · round 2 · 5/6 met`. */
687function stepOf(
688  stage: StageName,
689  ev: Evidence,
690  progress: Progress | null,
691  prNumber: number | null,
692): string {
693  const parts: (string | null)[] = [stage];
694  switch (stage) {
695    case 'build':
696      if (ev.build) parts.push(plural(ev.build.count, 'commit'));
697      break;
698    case 'check':
699      if (ev.check)
700        parts.push(
701          `round ${ev.check.round}`,
702          `${ev.check.met}/${ev.check.total} met`,
703        );
704      break;
705    case 'handoff':
706      parts.push(progress?.phase ?? ev.handoff?.step ?? null);
707      break;
708    case 'close': {
709      const phase = progress?.phase ?? 'close-validation';
710      const gate = ev.close?.gate;
711      parts.push(phase === 'close-validation' && gate ? `gate ${gate}` : phase);
712      break;
713    }
714    case 'merge':
715      parts.push(
716        prNumber === null ? 'PR' : `PR #${prNumber}`,
717        progress?.phase ??
718          (ev.envelope?.status === 'pending' ? 'waiting on merge' : null),
719      );
720      break;
721  }
722  return parts.filter(Boolean).join(' · ');
723}
724
725/** The stall verdict: learned medians first, else the 10-minute gate-log rule. */
726function stallOf(
727  stage: StageName,
728  ev: Evidence,
729  elapsedMs: number | null,
730  usualMs: number | null,
731  now: number,
732): boolean {
733  if (usualMs !== null && elapsedMs !== null)
734    return elapsedMs > Math.max(2 * usualMs, MIN_STALL_MS);
735  const idleMs = stage === 'close' && ev.close ? now - ev.close.at : 0;
736  return idleMs > STALL_MS;
737}
738
739function attentionOf(
740  status: string,
741  checksStatus: string | null,
742  isStalled: boolean,
743): Attention {
744  if (status === 'landed') return 'landed';
745  if (status === 'blocked') return 'needs-you';
746  if (FAILED.has(status)) return 'failed';
747  if (checksStatus === 'failure') return 'failed';
748  return isStalled ? 'slow' : 'working';
749}
750
751function deriveFocus(
752  storyId: number,
753  ev: Evidence,
754  learned: Learned,
755  samples: Partial<Record<StageName, number[]>>,
756  ctx: Ctx,
757): Focus {
758  const isInFlight = ev.envelope === null;
759  const { stage, progress } = pickStage(ev);
760  const phase = phaseOf(stage, progress);
761  const learnedPhase = phase ? learned.phases[phase] : undefined;
762  const usualMs = phase
763    ? learnedPhase && learnedPhase.samples >= MIN_SAMPLES
764      ? learnedPhase.medianSeconds * 1000
765      : null
766    : stageUsualMs(samples, stage);
767  const phaseStart = progress?.phaseStartedAt ?? stageStarts(ev)[stage];
768  const phaseElapsedMs =
769    isInFlight && phaseStart !== null
770      ? Math.max(0, ctx.now - phaseStart)
771      : null;
772  const isStalled =
773    isInFlight && stallOf(stage, ev, phaseElapsedMs, usualMs, ctx.now);
774  const prNumber = ev.progress?.prNumber ?? ev.envelope?.prNumber ?? null;
775  const status = ev.envelope?.status ?? 'in-flight';
776  const checksStatus = ev.envelope?.checksStatus ?? null;
777  const inClose = stage === 'close' && ev.close !== null;
778  return {
779    storyId,
780    title: ev.init?.title ?? null,
781    status,
782    attention: attentionOf(status, checksStatus, isStalled),
783    stage,
784    step: stepOf(stage, ev, progress, prNumber),
785    subject: ev.build?.subject ?? null,
786    stages: stageRows(ev, stage, samples),
787    closePhases: CLOSE_PHASES.map(
788      (name): PhaseRow => ({
789        name,
790        seconds: ev.envelope?.phaseDurations[name] ?? null,
791        usualSeconds: learned.phases[name]?.medianSeconds ?? null,
792      }),
793    ),
794    prNumber,
795    prUrl:
796      ev.envelope?.prUrl ??
797      (prNumber !== null && ctx.repoUrl
798        ? `${ctx.repoUrl}/pull/${prNumber}`
799        : null),
800    checksStatus,
801    elapsedSeconds: ev.envelope?.elapsedSeconds ?? null,
802    phaseElapsedMs,
803    usualMs,
804    phase,
805    quietMinutes:
806      inClose && ev.close
807        ? Math.floor(Math.max(0, ctx.now - ev.close.at) / 60_000)
808        : null,
809    lastGate: inClose ? (ev.close?.gate ?? null) : null,
810    unmet: ev.check?.unmet ?? [],
811    problem: ev.envelope?.problem ?? null,
812    nextCommand: ev.envelope?.nextCommand ?? null,
813    followUps: ev.followUps,
814  };
815}
816
817/** A Story whose worktree exists with no newer terminal envelope; the newest. */
818function pickInFlight(
819  worktrees: Stamped[],
820  envelopes: Stamped[],
821): Stamped | undefined {
822  return newest(
823    worktrees.filter((tree) => {
824      const envelope = envelopes.find((one) => one.storyId === tree.storyId);
825      return !envelope || envelope.mtimeMs < tree.mtimeMs;
826    }),
827  );
828}
829
830type Ledger = { stories: number[]; dispatched: number[]; updatedAt: number };
831
832function toLedger(raw: unknown): Ledger | null {
833  const body = raw as Record<string, unknown> | undefined;
834  const ids = (value: unknown): number[] =>
835    Array.isArray(value) ? value.filter((id) => num(id) !== null) : [];
836  const updatedAt = toMs(body?.updatedAt);
837  if (body?.kind !== 'deliver-run-ledger' || updatedAt === null) return null;
838  return {
839    stories: ids(body.stories),
840    dispatched: ids(body.dispatched),
841    updatedAt,
842  };
843}
844
845async function readLedgers($: EngineInterface, ctx: Ctx): Promise<Ledger[]> {
846  const entries = await $.fs.list(ctx.temp).catch(() => []);
847  const ledgers: Ledger[] = [];
848  for (const entry of entries) {
849    if (entry.kind !== 'dir' || !RUN_DIR.test(entry.name)) continue;
850    const ledger = toLedger(
851      await readJson($, `${ctx.temp}/${entry.name}/ledger.json`),
852    );
853    if (ledger && ctx.now - ledger.updatedAt <= RECENT_MS) ledgers.push(ledger);
854  }
855  return ledgers.sort((a, b) => b.updatedAt - a.updatedAt);
856}
857
858function chipOf(
859  id: number,
860  envelope: Envelope | undefined,
861  ledger: Ledger,
862  focus: Focus | null,
863): ChipState {
864  const status = envelope?.status;
865  if (status === 'landed') return 'landed';
866  if (status === 'blocked') return 'needs-you';
867  if (status && FAILED.has(status)) return 'failed';
868  if (id === focus?.storyId) return 'focus';
869  return ledger.dispatched.includes(id) ? 'in-flight' : 'undispatched';
870}
871
872/**
873 * The newest live run ledger: chips while it runs; a roll-up once every Story
874 * has a result, kept while one did not land, else for 10 minutes.
875 */
876async function readRun(
877  $: EngineInterface,
878  ctx: Ctx,
879  envelopes: Stamped[],
880  focus: Focus | null,
881): Promise<RunLine | null> {
882  for (const ledger of await readLedgers($, ctx)) {
883    const results = new Map<number, Envelope>();
884    for (const stamp of envelopes.filter((one) =>
885      ledger.stories.includes(one.storyId),
886    )) {
887      const envelope = await readEnvelope($, ctx, stamp);
888      if (envelope) results.set(stamp.storyId, envelope);
889    }
890    const chips = ledger.stories.map((storyId) => ({
891      storyId,
892      state: chipOf(storyId, results.get(storyId), ledger, focus),
893    }));
894    const isDone = ledger.stories.every((id) =>
895      TERMINAL.has(results.get(id)?.status ?? ''),
896    );
897    const stragglerId = ledger.stories.find(
898      (id) => results.get(id)?.status !== 'landed',
899    );
900    const ended = [...results.values()];
901    const lastAt = Math.max(0, ...ended.map((one) => one.at));
902    if (isDone && stragglerId === undefined && ctx.now - lastAt > LANDED_MS)
903      continue;
904    const straggled =
905      isDone && stragglerId !== undefined ? results.get(stragglerId) : null;
906    return {
907      landed: chips.filter((chip) => chip.state === 'landed').length,
908      total: ledger.stories.length,
909      chips,
910      isDone,
911      spanMs: isDone
912        ? lastAt -
913          Math.min(
914            ...ended.map((one) => one.at - (one.elapsedSeconds ?? 0) * 1000),
915          )
916        : null,
917      straggler:
918        straggled && stragglerId !== undefined
919          ? {
920              storyId: stragglerId,
921              attention:
922                straggled.status === 'blocked' ? 'needs-you' : 'failed',
923              phase: straggled.phase,
924            }
925          : null,
926    };
927  }
928  return null;
929}
930
931/** A landed result shows for 10 minutes; any other result for 2 hours. */
932const isShown = (envelope: Envelope, now: number): boolean =>
933  now - envelope.at <= (envelope.status === 'landed' ? LANDED_MS : RECENT_MS);
934
935async function scan(
936  $: EngineInterface,
937): Promise<{ next: Snapshot; latest: Envelope | null }> {
938  const root = await resolveRoot($);
939  if (!(await $.fs.exists(join(root, '.agents')).catch(() => false)))
940    return { next: EMPTY, latest: null };
941  const { temp, repoUrl } = await resolveConfig($, root);
942  const orchestration = `${temp}/orchestration`;
943  const now = await $.clock.now();
944  const [worktrees, files] = await Promise.all([
945    listMatching($, join(root, '.worktrees'), WORKTREE),
946    $.fs.list(orchestration).catch(() => []),
947  ]);
948  const ctx: Ctx = { root, temp, orchestration, files, now, repoUrl };
949  const envelopes = stampFiles(files, ENVELOPE);
950  const learned = await learn($, ctx, envelopes);
951  const recent = newest(
952    envelopes.filter((one) => now - one.mtimeMs <= RECENT_MS),
953  );
954  const latest = recent ? await readEnvelope($, ctx, recent) : null;
955  const inFlight = pickInFlight(worktrees, envelopes);
956  const shown = latest && isShown(latest, now) ? latest : null;
957  const focusId = inFlight?.storyId ?? shown?.storyId;
958  const focus =
959    focusId === undefined
960      ? null
961      : deriveFocus(
962          focusId,
963          await gather($, ctx, focusId, inFlight ? null : shown),
964          learned,
965          await read($, stageSamples),
966          ctx,
967        );
968  await track($, focus);
969  const run = await readRun($, ctx, envelopes, focus);
970  return { next: { focus, run, scannedAt: now }, latest };
971}
972
973/**
974 * When the followed Story moves past a stage the mod times itself, keep how
975 * long that stage took; the medians of these give build, check and handoff
976 * their usual time.
977 */
978async function track($: EngineInterface, focus: Focus | null): Promise<void> {
979  if (focus?.status !== 'in-flight') return;
980  const held = await read($, tracked);
981  const was = held?.storyId === focus.storyId ? held.stage : null;
982  if (was === focus.stage) return;
983  await update($, tracked, () => ({
984    storyId: focus.storyId,
985    stage: focus.stage,
986  }));
987  if (was === null || STAGES.indexOf(was) > STAGES.indexOf(focus.stage)) return;
988  const row = focus.stages.find((one) => one.name === was);
989  if (!row || !LEARNED_STAGES.has(was)) return;
990  if (row.startedAt === null || row.endedAt === null) return;
991  const seconds = (row.endedAt - row.startedAt) / 1000;
992  if (seconds < 0) return;
993  await update($, stageSamples, (held) => ({
994    ...held,
995    [was]: [...(held[was] ?? []), seconds].slice(-MAX_SAMPLES),
996  }));
997}
998
999/** The toast for a Story turning slow, once per Story. */
1000function slowToast(focus: Focus): string {
1001  const where = focus.phase ?? focus.stage;
1002  const took =
1003    focus.phaseElapsedMs === null ? '' : ` ${clock(focus.phaseElapsedMs)}`;
1004  const usual =
1005    focus.usualMs === null ? '' : ` of usual ~${clock(focus.usualMs)}`;
1006  return `Story #${focus.storyId} is slow: ${where}${took}${usual}`;
1007}
1008
1009/** Toasts each result and each first slow verdict once; the first scan only records. */
1010async function announce(
1011  $: EngineInterface,
1012  latest: Envelope | null,
1013  focus: Focus | null,
1014): Promise<void> {
1015  const seeded = await read($, isSeeded);
1016  if (!seeded) await update($, isSeeded, () => true);
1017  const pending: { key: string; text: string }[] = [];
1018  if (latest && TERMINAL.has(latest.status)) {
1019    const pr = latest.prNumber ? ` (PR #${latest.prNumber})` : '';
1020    pending.push({
1021      key: `${latest.storyId}:${latest.at}`,
1022      text: `Story #${latest.storyId} ${latest.status}${pr}`,
1023    });
1024  }
1025  if (focus?.attention === 'slow')
1026    pending.push({ key: `${focus.storyId}:slow`, text: slowToast(focus) });
1027  for (const one of pending) {
1028    if ((await read($, seen)).includes(one.key)) continue;
1029    await update($, seen, (list) => [...list, one.key].slice(-50));
1030    if (seeded) $.ui.toast(one.text);
1031  }
1032}
1033
1034async function refresh($: EngineInterface): Promise<void> {
1035  try {
1036    const { next, latest } = await scan($);
1037    await update($, snapshot, () => next);
1038    await announce($, latest, next.focus);
1039  } catch {
1040    // Read-only and best effort: a failed scan leaves the last drawing up.
1041  }
1042}
1043
1044// --------------------------------------------------------------- drawing
1045
1046const GLYPH: Record<Attention, string> = {
1047  working: '●',
1048  slow: '▲',
1049  'needs-you': '◆',
1050  failed: '✗',
1051  landed: '✓',
1052};
1053const COLOR: Record<Attention, string | null> = {
1054  working: null,
1055  slow: 'yellow',
1056  'needs-you': 'magenta',
1057  failed: 'red',
1058  landed: 'green',
1059};
1060const LABEL: Record<Attention, string> = {
1061  working: 'in flight',
1062  slow: 'slow',
1063  'needs-you': 'needs you',
1064  failed: 'failed',
1065  landed: 'landed',
1066};
1067const CHIP: Record<ChipState, string> = {
1068  landed: '✓',
1069  'needs-you': '◆',
1070  failed: '✗',
1071  focus: '●',
1072  'in-flight': '◐',
1073  undispatched: '○',
1074};
1075
1076/** `0:45`, `5:39`, `1:05:00`. */
1077function clock(ms: number): string {
1078  const total = Math.max(0, Math.round(ms / 1000));
1079  const seconds = String(total % 60).padStart(2, '0');
1080  const minutes = Math.floor(total / 60);
1081  if (minutes < 60) return `${minutes}:${seconds}`;
1082  return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}:${seconds}`;
1083}
1084
1085/** Cut short with an ellipsis, never wrapped. */
1086function cut(text: string, width: number): string {
1087  if (text.length <= width) return text;
1088  return width <= 1 ? '…' : `${text.slice(0, width - 1)}…`;
1089}
1090
1091/** Six cells: one filled per finished or current stage. */
1092const meter = (stage: StageName): string =>
1093  STAGES.map((_, index) => (index <= STAGES.indexOf(stage) ? '▰' : '▱')).join(
1094    '',
1095  );
1096
1097const ratioOf = (focus: Focus): string | null =>
1098  focus.usualMs && focus.phaseElapsedMs !== null
1099    ? `${(focus.phaseElapsedMs / focus.usualMs).toFixed(1)}×`
1100    : null;
1101
1102/** A result that stopped the Story, as opposed to red checks on a live PR. */
1103const isStopped = (focus: Focus): boolean =>
1104  focus.status === 'blocked' || FAILED.has(focus.status);
1105
1106const isChecksRed = (focus: Focus): boolean =>
1107  focus.attention === 'failed' && !isStopped(focus);
1108
1109function timeOf(focus: Focus): string {
1110  if (focus.phaseElapsedMs === null)
1111    return focus.status === 'in-flight' ? '' : focus.status;
1112  const usual = focus.usualMs === null ? '' : ` / ~${clock(focus.usualMs)}`;
1113  return `${clock(focus.phaseElapsedMs)}${usual}`;
1114}
1115
1116/** Line 1 after the Story: the outcome, the stopping point, or progress and time. */
1117function progressOf(focus: Focus): string {
1118  if (focus.attention === 'landed') {
1119    return [
1120      `landed in ${focus.elapsedSeconds === null ? '?' : clock(focus.elapsedSeconds * 1000)}`,
1121      focus.prNumber === null ? null : `PR #${focus.prNumber}`,
1122      focus.followUps === null ? null : plural(focus.followUps, 'follow-up'),
1123    ]
1124      .filter(Boolean)
1125      .join(' · ');
1126  }
1127  if (isStopped(focus))
1128    return `${LABEL[focus.attention]} at ${focus.stage} · ${focus.problem ?? 'see the Story'}`;
1129  const step = isChecksRed(focus)
1130    ? `merge · PR #${focus.prNumber ?? '?'} · checks failing`
1131    : focus.step;
1132  return [`${meter(focus.stage)} ${step}`, timeOf(focus)]
1133    .filter(Boolean)
1134    .join('   ');
1135}
1136
1137const chipsOf = (run: RunLine): string =>
1138  `run ${run.landed}/${run.total}  ${run.chips
1139    .map((chip) => `${CHIP[chip.state]}${chip.storyId}`)
1140    .join(' ')}`;
1141
1142function headline(
1143  focus: Focus,
1144  run: RunLine | null,
1145  isNarrow: boolean,
1146): string {
1147  const title =
1148    !isNarrow && focus.title ? ` ${cut(focus.title, TITLE_CELLS)}` : '';
1149  return [
1150    `${GLYPH[focus.attention]} #${focus.storyId}${title}`,
1151    progressOf(focus),
1152    !isNarrow && run && !run.isDone ? chipsOf(run) : null,
1153  ]
1154    .filter(Boolean)
1155    .join('   ');
1156}
1157
1158const unmetOf = (unmet: number[]): string => {
1159  const named = unmet.slice(0, MAX_UNMET).map((id) => `AC-${id}`);
1160  const more = unmet.length - named.length;
1161  return [...named, ...(more > 0 ? [`+${more}`] : [])].join(', ');
1162};
1163
1164/** Line 2: only when the Story needs a look, and never repeating line 1. */
1165function attentionLine(focus: Focus): string | null {
1166  if (focus.attention === 'slow') {
1167    const parts = [
1168      ratioOf(focus) && `${ratioOf(focus)} usual`,
1169      focus.quietMinutes ? `gate log quiet ${focus.quietMinutes}m` : null,
1170      focus.lastGate ? `last gate ${focus.lastGate}` : null,
1171    ].filter(Boolean);
1172    return `↳ ${parts.length ? parts.join(' · ') : `${focus.stage} is past its usual time`}`;
1173  }
1174  if (isChecksRed(focus))
1175    return `↳ PR #${focus.prNumber ?? '?'} checks failing`;
1176  if (!isStopped(focus)) return null;
1177  const unmet =
1178    focus.stage === 'check' && focus.unmet.length
1179      ? `   ${unmetOf(focus.unmet)}`
1180      : '';
1181  return `↳ ${focus.nextCommand ?? `see Story #${focus.storyId}`}${unmet}`;
1182}
1183
1184function rollupOf(run: RunLine): string {
1185  const straggler = run.straggler;
1186  const glyph = GLYPH[straggler?.attention ?? 'landed'];
1187  const span = run.spanMs === null ? '' : ` in ${clock(run.spanMs)}`;
1188  const stopped = straggler
1189    ? ` · #${straggler.storyId} ${LABEL[straggler.attention]}${straggler.phase ? ` at ${straggler.phase}` : ''}`
1190    : '';
1191  return `${glyph} run ${run.landed}/${run.total} landed${span}${stopped}   ${chipsOf(
1192    run,
1193  )
1194    .split('  ')
1195    .slice(1)
1196    .join('  ')}`;
1197}
1198
1199type Line = { text: string; color: string | null };
1200
types/index.d.ts 136 lines
1/** The six stages of a /mandrel-deliver Story, in order. */
2export type StageName =
3  | 'start'
4  | 'build'
5  | 'check'
6  | 'handoff'
7  | 'close'
8  | 'merge';
9
10/**
11 * What the band says about a Story; it picks the glyph, the color and whether
12 * a second line shows. `needs-you` is a `blocked` result (the HITL pause);
13 * `failed` is a `failed` / `escalated` result or a PR whose checks are red.
14 */
15export type Attention = 'working' | 'slow' | 'needs-you' | 'failed' | 'landed';
16
17/** One stage as the Details pane lists it; times in epoch milliseconds. */
18export type StageRow = {
19  name: StageName;
20  startedAt: number | null;
21  /** The next stage's start, or null while this one is current or pending. */
22  endedAt: number | null;
23  /** The learned median of the stage, once it has 3+ samples. */
24  usualMs: number | null;
25};
26
27/** One close phase: its recorded duration and the learned median, in seconds. */
28export type PhaseRow = {
29  name: string;
30  seconds: number | null;
31  usualSeconds: number | null;
32};
33
34/** The Story the band follows: in flight, or the newest recent result. */
35export type Focus = {
36  storyId: number;
37  title: string | null;
38  /** `in-flight`, or the terminal envelope's `status`. */
39  status: string;
40  attention: Attention;
41  stage: StageName;
42  /** The current stage's step, already worded: `check · round 2 · 5/6 met`. */
43  step: string;
44  /** The last commit subject, shown only in the Details pane. */
45  subject: string | null;
46  stages: StageRow[];
47  closePhases: PhaseRow[];
48  prNumber: number | null;
49  /** The PR's web address: the envelope's `pr.url`, else built from `github`. */
50  prUrl: string | null;
51  checksStatus: string | null;
52  /** The envelope's `elapsedSeconds`, for a finished result. */
53  elapsedSeconds: number | null;
54  /** Milliseconds into the current phase, while in flight. */
55  phaseElapsedMs: number | null;
56  /** The learned median of the current phase or stage, once it has 3+ samples. */
57  usualMs: number | null;
58  /** The close phase being timed, when the stage has one. */
59  phase: string | null;
60  /** Minutes the close-gates log has been quiet, while in close. */
61  quietMinutes: number | null;
62  /** The gate named by the close-gates log's last line, while in close. */
63  lastGate: string | null;
64  /** 1-based ids of the newest verdict round's criteria not `met`. */
65  unmet: number[];
66  /** `blocked.blockClass` or `failure.reason`. */
67  problem: string | null;
68  nextCommand: string | null;
69  /** Bullets in `follow-ups-rollup-<id>.md`, when it exists. */
70  followUps: number | null;
71};
72
73/** How one ledger Story reads as a run chip. */
74export type ChipState =
75  | 'landed'
76  | 'needs-you'
77  | 'failed'
78  | 'focus'
79  | 'in-flight'
80  | 'undispatched';
81
82/** A Story that ended without landing, named by the run roll-up. */
83export type Straggler = {
84  storyId: number;
85  attention: 'needs-you' | 'failed';
86  /** The envelope's `phase`: where it stopped. */
87  phase: string | null;
88};
89
90/** The newest live multi-Story run ledger. */
91export type RunLine = {
92  landed: number;
93  total: number;
94  chips: { storyId: number; state: ChipState }[];
95  /** True once every ledger Story has a terminal envelope. */
96  isDone: boolean;
97  /** From the earliest start to the newest result, once done. */
98  spanMs: number | null;
99  straggler: Straggler | null;
100};
101
102export type Snapshot = {
103  focus: Focus | null;
104  run: RunLine | null;
105  /** When the scan ran, epoch milliseconds; 0 before the first. */
106  scannedAt: number;
107};
108
109/** Per close phase: the median of the newest terminal envelopes' timings. */
110export type Learned = {
111  /** When the medians were last computed; 0 before the first pass. */
112  at: number;
113  phases: Record<string, { medianSeconds: number; samples: number }>;
114};
115
116/** The followed Story and stage of the last scan, to see a stage finish. */
117export type Tracked = { storyId: number; stage: StageName };
118
119declare module 'claude-code' {
120  interface PluginState {
121    'mandrel-status': {
122      snapshot: Snapshot;
123      /** Envelope keys and `<storyId>:slow` of everything already toasted or recorded. */
124      seen: string[];
125      /** False until the first scan, which records without a toast. */
126      isSeeded: boolean;
127      learned: Learned;
128      /** Durations in seconds of finished stages this mod watched, newest 30 each. */
129      stageSamples: Partial<Record<StageName, number[]>>;
130      tracked: Tracked | null;
131      /** `<band key>:<attention>` the person hid; any change shows the band again. */
132      hiddenFor: string | null;
133    };
134  }
135}
136