UNVERIFIED when Claude claims done without a check: a receipt line under every answer that claims done, naming the test or build that ran after the last edit…

A Claude Code mod that says UNVERIFIED when Claude claims done without a check. Under every answer that claims done, a receipt line names the command that verified the work after the last edit, with its exit code and the runner's own summary line, or says that nothing did. A second, read-only agent then tries to refute the claim. It also replaces the wall of tool calls with a progress band that shows Claude's own plan.
The name reads like a cost meter, and it isn't one. It's a verification receipt.
It does three jobs:
Tested with Claude Code 2.1.291. Mods need 2.1.287 or later.
claude --plugin-dir ~/projects/claude-receipts
That loads the mod for one session. Nothing opens by itself: the band appears above the prompt when you send a prompt. /receipts opens a pane with the long view if you want it.
Or install it from its marketplace:
claude plugin marketplace add shawnpetros/claude-receipts
claude plugin install receipts@claude-receipts
Use one or the other, not both. With --plugin-dir and the installed copy in one session, two copies of the mod draw the same band and keep separate state.
To check that it's learning, finish a turn and run /receipts stats. The count of finished tasks should go up by one.
While a turn runs, the band has an orange border and these rows:
~4 to 9 min · from 3 similar tasks, then the elapsed time.Step 2 of 4, a full-width bar of cells, and the percent done at the right end. The percent is weighted by how long each step is expected to take.Done, Working for the step under way (its own percent, such as 40%, once it has any), Next for the step after it, and Up next for the rest. At most six steps show, around the current one, then +n more.Under the band, just above the prompt, a rule reads ───── Clean View ─ while the rows level is Clean or Quiet. It shows when no turn is running too.
The steps are Claude's own, recorded with TaskCreate and TaskUpdate. If Claude records none, there are no steps: the second row reads working · 1m 13s with the estimate, and there's no percent to make up.
When the turn ends, the band always leaves the working state. It becomes one of six cards and stays until your next prompt:
| Card | Border | When | | :- | :- | :- | | Working | orange | The turn is running | | ■ Turn ended · 2 of 5 steps reached | grey | Steps were left, or work stopped without a claim of done. Unfinished steps read Not reached, never Done. | | ✓ All done | green | Every recorded step completed, a passing verify ran after the last edit, and the cross-check didn't refute it | | ⚠ Done, unverified | yellow | Claude claims done and nothing verified the work after the last edit. A failing verify reads ✗ Done, checks failed. | | ✗ Done, refuted | yellow | The cross-check refuted the claim. Its reason sits in the title row, word for word. | | ✓ Answered · 25s | green | The turn was an answer, not a job: no edit and no real command ran |
A grey ■ Stopped badge shows when you interrupt the turn.
After the steps, a finished card shows the receipt row, the same line printed under the answer, and the cross-check row: cross-check · running (opus)…, then cross-check · ✓ confirmed (opus, reran bun test exit 0) · 38s, cross-check · ✗ refuted: tests cover only the happy path, or cross-check · ? unclear.
If agents the turn started are still running when it ends, the title row says waiting on 2 agents. The count drops as each one finishes, and the next prompt clears it.
When the elapsed time passes the top of the range, the border and bar turn grey and the summary reads over by 2m 10s · ~1 to 4 min more. Running long isn't an error, so it's never red.
Below 110 columns the per-step bars drop and each step keeps its word. Nothing in the band is ever wider than the terminal.
The band draws no buttons of its own. Claude Code's [-] just outside the border hides it.
The footer at the right of the prompt shows ◆ Shawn's Tools ▲. Click it, or run /receipts tools, and a bordered panel opens at the right of the band. The button then reads ◆ Shawn's Tools ▼. Click it again, or run the command again, to close the panel.
◆ S H A W N ' S T O O L S, with the current model and effort at the right, such as Opus 5.5 · High./config model row when this build has one that takes it, and otherwise runs /model <name>./effort. The current level is highlighted once a model request has carried it./receipts check does./receipts stats as a toast. Mark receipt wrong marks this turn's receipt, as /receipts wrong does.Your plugin settings can't change while a session runs, so these choices override them for the rest of the session. /clear puts your settings back.
/receipts basis shows a one-line tooltip on the band with the estimate's basis and the calibration score.
Each mod's store is its own file, so the switches can't live in a shared store key. A mod publishes its list in its own session state instead, under the key switches, which any mod may read:
await $.state.set({ plugin: 'buddy', key: 'switches' }, [
{ id: 'buddy', label: 'Buddy', description: 'a companion in the corner', value: true },
])
The panel reads every mod it knows by name. A press on another mod's switch is written to receipts' own state key switchRequests as { [id]: value }, because only the owner may write its state. The owner reads that key and applies the change. The panel names each mod in its source, so a new mod is one line in hooks/register.ts.
These are the rules the mod follows. Each one exists because some tool, somewhere, broke it.
working and shows the clock. An earlier version guessed plans of 5 or 6 steps for prompts that needed one answer, then reported 1 of 6 reached.grep -i error over a log is flagged as grep-for-error, not a receipt, because a warning or a swallowed summary passes that grep.~4 to 9 min. A countdown never freezes. A range that would round to one value is widened until it shows two, and its low end is never 0.prior only.from 7 similar tasks, spike guess or prior only.b in the band, the pane and /receipts stats show a line such as calibration: 61% of 18 tasks ended inside the range. After 10 or more tasks, if the score falls below 50%, the band says plainly that the ranges have been missing. That warning can't be hidden.3:52 to 8:40 left appear only when confidence is 0.5 or higher.over by 2m 10s and the range widens with elapsed time as its floor. It never resets to indeterminate.The plan. When you submit a prompt, a small model labels its type, waiting at most 1 second. A build, debug, config or refactor prompt goes in with one extra line for Claude, the same bytes every time so the prompt cache holds: "Before non-trivial work, record your plan with TaskCreate as 2 to 8 short steps, mark each in_progress and completed with TaskUpdate as you go, and keep the list current if the plan changes." The band's steps are that list. A chat, research or writing prompt gets one "answer" step. A Read, Grep or a command that only looks around (git status, ls, cat) never changes that. An edit or a real command means work has started. From then on the plan comes from the task tools, or the band says working.
The estimate. Each task is filed under a shape: task type, step count (1, 2-3, 4-6 or 7+), a hash of the repository, whether it has tests, and the tool mix. Remaining time is the sum of the expected time of each step not yet done. The expectation comes from the most specific shape with at least 3 past tasks, then a coarser shape, then a global prior. Step durations come from Claude's TaskUpdate transitions, so what the mod learns is real. The spread counts only the steps left, so it shrinks as they finish.
For a build-type task with 3 or more recorded steps and no history, the mod asks one cheap, read-only subagent for minutes per step. It does this at most once per shape per session, with a 60-second limit, and counts the answer as half of one past task.
Time spent waiting on a permission prompt isn't learned as work. Claude Code reports each tool's own run time without the prompt, and the rest of the call comes out of the step before it's saved. Calibration is still scored on the wall clock, because that's what the range promised. History keeps the newest 500 tasks and stays under 1 MiB.
The receipt. Each turn keeps a ledger of edits, of verify commands with their exit codes and summary lines, and of greps for "error". The summary line is the runner's own, found by its known shape: bun's pass and fail lines, jest's Tests:, vitest's Tests, pytest's === … in 0.12s ===, cargo's test result: or error[E…], go's ok or FAIL, make's make: *** … Error N. A small model decides whether the answer claims done. If its label isn't back within 1.5 seconds, plain completion words decide instead.
| What happened | Line under the answer | | :- | :- | | Edited, claimed done, a passing verify after the last edit | receipt · bun test · exit 0 · 105 pass, 0 fail · 1m ago | | A failing verify after the last edit | FAILED · cargo test · exit 101 · test result: FAILED. 3 passed; 2 failed; … | | Edited, claimed done, nothing verified after the last edit | UNVERIFIED · claims done · last edit src/x.ts 14:02 · no verify since | | Only a grep for "error" after the last edit | the UNVERIFIED line, ending (grep-for-error, not a receipt) | | No edits, or the answer doesn't claim done | nothing |
When Claude Code reports usage, the line ends with what the turn cost:
| Who you are | What the line adds | | :- | :- | | A Claude plan user, with rate-limit windows | 5h window 6% used, resets 18:30 | | An API key user, with no windows | $0.42 this turn | | Neither is known | nothing, never a guess |
The cross-check. When a turn with edits claims done, the mod spawns one read-only agent of the Explore type, on opus unless you set crossCheckModel. It gets your request and Claude's claim, each up to 800 characters, plus every verify command with its exit code and summary line, and git diff of the edited files. A diff over 400 lines is sent as its --stat, and the agent is told so. It's told to refute the claim, re-run the verify command if there is one, and call it refuted if unsure. It answers confirmed, refuted or unclear with a short reason, and the card shows that word for word. No answer within 90 seconds counts as unclear. It never blocks the turn and never runs more than once per turn.
It's skipped when the turn made no edits, when crossCheck is off or /receipts check off ran, in -p mode, and when the five-hour window is over 85% used. /receipts stats counts confirmed, refuted and unclear verdicts.
If the current turn's receipt is wrong, for example it called an answer done when it wasn't, run /receipts wrong. Each receipt can be marked once, and /receipts stats shows claims-done false positives: 1 of 12 receipts (8%). That number is the precondition for ever letting the receipt block a turn. See the roadmap.
| Command | What it does | | :- | :- | | /receipts | Opens or closes the pane, the long view with the calibration line | | /receipts tools | Opens or closes the tools panel, as the footer button does | | /receipts rows [off\|clean\|quiet] | Sets the rows level, or steps to the next one with no argument | | /receipts clean | Switches the rows level to Off, and back to what it was | | /receipts basis | Shows or hides the basis tooltip, as b does | | /receipts stats | Shows the calibration history and task counts by type, with median durations | | /receipts wrong | Marks the current turn's receipt line as a false positive, for the count in stats | | /receipts check [on\|off] | Turns the cross-check on or off for this session, or says which it is | | /receipts reset-history | Forgets every learned task |
In the pane, c switches the rows level to Off and back, and b shows where the estimate comes from.
The rows level sets how much of the transcript the mod draws away. Quiet is the default.
| Level | What draws | | :- | :- | | Off | Every row exactly as Claude Code draws it | | Clean | Tool rows as one dim line each, such as ● Edit src/x.ts. Milestone rows in full. | | Quiet | See below |
Quiet goes further:
● Bash bun test ✓.↳ message from @Explore: Found 3 mods.Your own prompts always draw in full. Quiet never touches a question the assistant asks you or a permission prompt.
ctrl+o is the escape hatch. It shows the full transcript, and a hand-back row it expands draws in full. ctrl+o also expands a folded group of reads and searches. A single tool row or a block of assistant text can't be expanded past the level, because Claude Code doesn't tell a mod when one is expanded. Set the level to Off to see those in full.
Set these under pluginConfigs in your Claude Code settings. Use the key receipts@inline for a session started with --plugin-dir.
| Key | Default | What it does | | :- | :- | :- | | spike | true | Allows the sizing subagent for unfamiliar build-type tasks. Set it to false and the mod never spawns one. | | cleanView | true | Starts each session at the quiet rows level. Set it to false to start at Off. The tools panel and /receipts rows change it for the session. | | crossCheck | true | Spawns the read-only cross-check agent when a turn with edits claims done | | crossCheckModel | opus | The model the cross-check runs on, as an alias or a model id |
The mod calls the model API for its labels, spawns a subagent for the spike and one for the cross-check, and runs git diff on the files a turn edited. It makes no other network calls and sends no telemetry of its own. The only thing it writes is its own store.
/receipts and its subcommands aren't there. The band's keys still work.--plugin-dir) and the marketplace install in the same session. Both draw the same band and keep separate state, so the band you see may belong to the copy that missed the turn's end.hooks/hooks.json carries an empty hooks key beside modules, so an older build loads nothing instead of failing.Each release answers one question it can measure.
/receipts help.$.session.usage() already shipped in 0.2.2. The rest is an optional gate that turns UNVERIFIED from a mirror into a block, off by default. It ships only after the claims-done classifier's false-positive rate has been measured over enough live turns with /receipts wrong and /receipts stats. A gate that blocks a finished turn gets the mod uninstalled.Not planned: token meters, burn bars, or a rename.
claude plugin validate . --strict
claude plugin test
bun scripts/simulate.ts
bun scripts/mock-band.ts 155
bun scripts/check-manifest.ts
scripts/mock-band.ts prints the band as plain text: the six card states, then working with no task list, over the range, checks failed, narrow, collapsed, the tools panel and the footer button. Every band is followed by the Clean View rule. It uses the same pure view the mod draws from. The argument is the band's width, which is the terminal's width less 5.
src/ holds the logic as plain modules with no mods API dependency. These are the estimator, history, milestones, ledger, crosscheck, quiet, shape, spike, view and band modules, plus a session that talks to Claude Code through a small host interface. hooks/register.ts builds that host from $ and wires the hooks.
hooks/register.ts 646 lines1import type { ConfigRow, EngineInterface, On, PluginOptions, RenderElement } from 'claude-code'
2import { atom, read, update } from 'claude-code'
3
4import {
5 ACCENT,
6 bandView,
7 dividerRow,
8 EFFORT_CHOICES,
9 MODEL_CHOICES,
10 ROWS_LEVELS,
11 TOOLS_COLUMNS,
12 toolsView,
13 type Row,
14 type RowsLevel,
15 type Seg,
16} from '../src/band'
17import { PLAN_INSTRUCTION } from '../src/crosscheck'
18import type { Host } from '../src/host'
19import { firstLineOf, handbackLineOf, QuietLog } from '../src/quiet'
20import { RECEIPT_LINE_SWITCH, receiptsSwitches, switchesOf } from '../src/switches'
21import { BUILD_TYPES, PANE_ID, PANE_TITLE, ReceiptsSession } from '../src/session'
22import { paneLines, toolGroupText, toolResultText, toolRowText, type Line } from '../src/view'
23
24/**
25 * The rows level: `off` draws every row as Claude Code does; `clean` draws
26 * tool rows as one dim line and milestones in full; `quiet` (the default)
27 * draws tool rows as nothing and milestones as one dim line, during the turn
28 * and after it, and folds the chrome a turn scatters: the spinner, progress
29 * pills, notices and command output while working, subagent hand-backs, and
30 * interim assistant text down to its first line.
31 *
32 * Invariant 4, drawing only: these hooks return a drawing and never touch
33 * the transcript, so `off` shows every row as it was. Scar: the /buddy
34 * main-model leak; a mod rewriting content is a different and riskier thing
35 * than a mod redrawing it. Milestones always show (invariant 5).
36 */
37const rows = atom({ plugin: 'receipts', key: 'rows' }, 'quiet')
38
39/** The level `/receipts clean` and the pane's `c` go back to from `off`. */
40const rowsLast = atom({ plugin: 'receipts', key: 'rowsLast' }, 'quiet')
41
42/**
43 * Whether a main-loop turn is running. The quiet sites read it, so they draw
44 * again once at each turn edge, not on every tick.
45 */
46const working = atom({ plugin: 'receipts', key: 'working' }, false)
47
48/**
49 * The tools panel, drawn in the band at its right (frames 13 and 14 show it
50 * there: the band's own [-] beside it, its "n more" row under it), opened by
51 * the footer button.
52 */
53const toolsOpen = atom({ plugin: 'receipts', key: 'toolsOpen' }, false)
54
55/** Quiet folds subagent hand-backs and peer messages while this is on. */
56const chatter = atom({ plugin: 'receipts', key: 'chatter' }, true)
57
58/** The receipt line under an answer that claims done; receipts' own MODS switch. */
59const receiptLine = atom({ plugin: 'receipts', key: 'receiptLine' }, true)
60
61/** Receipts' switches as published for any panel to read (switches.ts). */
62const switches = atom({ plugin: 'receipts', key: 'switches' }, receiptsSwitches(true))
63
64/** Presses on other mods' switches: `{ [id]: value }`, for each owner to apply. */
65const switchRequests = atom({ plugin: 'receipts', key: 'switchRequests' }, {} as Record<string, boolean>)
66
67/**
68 * The spike switch as the person last set it. userConfig is read-only at
69 * runtime, so this state overrides it for the session; it starts from it.
70 */
71const spike = atom({ plugin: 'receipts', key: 'spike' }, true)
72
73/**
74 * Read by the pane and band only, so bumping it once a second redraws those
75 * two and not every tool row in the transcript.
76 */
77const tick = atom({ plugin: 'receipts', key: 'tick' }, 0)
78
79const USAGE =
80 'usage: /receipts (toggle the pane), /receipts tools, /receipts rows [off|clean|quiet], /receipts clean, /receipts basis, /receipts stats, /receipts wrong, /receipts check [on|off], /receipts reset-history'
81const PANE_MIN_ROWS = 6
82const PANE_MAX_ROWS = 24
83
84/**
85 * The mods API as the session logic sees it. Top level and handed `$`, so
86 * `claude plugin validate` lists every call through it.
87 */
88function hostOf($: EngineInterface): Host {
89 return {
90 now: () => $.clock.now(),
91 every: (ms, fn) => $.clock.every(ms, fn),
92 after: (ms, fn) => $.clock.after(ms, fn),
93 storeGet: key => $.store.get(key),
94 storeSet: (key, value) => $.store.set(key, value),
95 storeDelete: key => $.store.delete(key),
96 redraw: () => {
97 update($, tick, n => n + 1).catch(() => $.ui.invalidate('ui.render'))
98 },
99 classify: (text, labels) => $.model.classify(text, labels),
100 complete: request => $.model.complete(request),
101 spawn: args => $.agent.spawn(args),
102 cwd: () => $.session.cwd(),
103 repo: () => $.session.repo(),
104 list: path => $.fs.list(path),
105 agents: () => $.agent.list(),
106 usage: () => $.session.usage(),
107 run: (argv, cwd) => $.process.run(argv, { cwd, timeoutMs: 10_000 }),
108 }
109}
110
111/**
112 * `off` and back: to the level the person had before, quiet if none.
113 */
114async function toggleClean($: EngineInterface): Promise<RowsLevel> {
115 const level = (await read($, rows)) as RowsLevel
116 if (level === 'off') {
117 const back = (await read($, rowsLast)) as RowsLevel
118 await update($, rows, () => back)
119 return back
120 }
121 await update($, rowsLast, () => level)
122 await update($, rows, () => 'off')
123 return 'off'
124}
125
126async function setRows($: EngineInterface, level: RowsLevel): Promise<void> {
127 if (level !== 'off') await update($, rowsLast, () => level)
128 await update($, rows, () => level)
129}
130
131async function levelOf($: EngineInterface): Promise<RowsLevel> {
132 return (await read($, rows)) as RowsLevel
133}
134
135/**
136 * Sets the model or effort the way the person would: the `/config` row when
137 * the build has one that takes it, else the slash command. Top level and
138 * handed `$`, so validate lists the calls.
139 */
140async function choose($: EngineInterface, key: 'model' | 'effort', value: string): Promise<void> {
141 const rows: ConfigRow[] = await $.config.list().catch(() => [])
142 const row = rows.find(candidate => candidate.key === key)
143 if (row && !row.isLocked && row.kind !== 'boolean' && row.kind !== 'number') {
144 const result = await $.config.set({ key, value }).catch(() => ({ deny: 'failed' }))
145 if (result.deny === undefined) return
146 }
147 await $.command.run({ command: key, args: value })
148}
149
150/**
151 * The userConfig defaults into state, where the band's switches change them.
152 */
153async function applyDefaults($: EngineInterface, session: ReceiptsSession, isClean: boolean, isSpike: boolean): Promise<void> {
154 if (!isClean) await update($, rows, () => 'off')
155 if (!isSpike) await update($, spike, () => false)
156 session.setSpike(isSpike)
157}
158
159/** Receipts' own switch flipped: the atom, and the list it publishes. */
160async function setReceiptLine($: EngineInterface, isOn: boolean): Promise<void> {
161 await update($, receiptLine, () => isOn)
162 await update($, switches, () => receiptsSwitches(isOn))
163}
164
165/**
166 * Every known mod's published switches. `plugin` must be a literal, so each
167 * mod the panel knows is named here; one not loaded reads as nothing.
168 */
169async function modSwitchesOf($: EngineInterface): Promise<ReturnType<typeof switchesOf>> {
170 const buddy = await $.state.get({ plugin: 'buddy', key: 'switches' }).catch(() => ({ value: undefined }))
171 return switchesOf([
172 ['receipts', receiptsSwitches(await read($, receiptLine))],
173 ['buddy', buddy.value],
174 ])
175}
176
177async function sessionModelOf($: EngineInterface): Promise<string> {
178 return $.session.model().catch(() => '')
179}
180
181/**
182 * A line of the pane as Text props, leaving out the styles it does not set.
183 */
184function textPropsOf(line: Line) {
185 return {
186 key: line.key,
187 wrap: 'truncate-end' as const,
188 children: [line.text],
189 ...(line.dim ? { dimColor: true } : {}),
190 ...(line.bold ? { bold: true } : {}),
191 ...(line.color ? { color: line.color } : {}),
192 }
193}
194
195type Elements = ReturnType<EngineInterface['ui']['resolve']>
196type Presses = Record<string, () => unknown>
197
198/**
199 * A row of the band as elements: a Text per segment, a plain Button where a
200 * segment carries one. A Button whose key has no handler draws as text.
201 */
202function rowOf(el: Elements, row: Row, presses: Presses): RenderElement {
203 const children = row.segs.map((seg: Seg): RenderElement => {
204 const press = seg.button ? presses[seg.button.key] : undefined
205 if (seg.button && press) {
206 return el.Button({
207 key: seg.button.key,
208 label: seg.button.label,
209 plain: true,
210 ...(seg.button.hotkey ? { hotkey: seg.button.hotkey } : {}),
211 ...(seg.dim ? { dimColor: true } : {}),
212 onPress: () => press(),
213 })
214 }
215 return el.Text({
216 children: [seg.text],
217 ...(seg.color ? { color: seg.color } : {}),
218 ...(seg.dim ? { dimColor: true } : {}),
219 ...(seg.bold ? { bold: true } : {}),
220 ...(seg.inverse ? { inverse: true } : {}),
221 })
222 })
223 return el.Box({ key: row.key, flexDirection: 'row', children })
224}
225
226/**
227 * The one dim line a milestone row folds to while suppressed: the call and
228 * how it ended. A verify run's exit shows as ✓ or ✗ (invariant 5).
229 */
230function outcomeMarkOf(props: { isRunning?: boolean; isErrored?: boolean; isInterrupted?: boolean }): string {
231 if (props.isRunning) return ' …'
232 if (props.isInterrupted) return ' ■'
233 return props.isErrored ? ' ✗' : ' ✓'
234}
235
236export function register(on: On, options: PluginOptions): void {
237 const isSpikeByDefault = options.spike !== false
238 const session = new ReceiptsSession({
239 spike: isSpikeByDefault,
240 crossCheck: options.crossCheck !== false,
241 ...(typeof options.crossCheckModel === 'string' ? { crossCheckModel: options.crossCheckModel } : {}),
242 })
243 const quiet = new QuietLog()
244 const isCleanByDefault = options.cleanView !== false
245
246 on('session.start', async ($, e, next) => {
247 // -p and other headless runs: no cross-check, nobody is there to read it
248 session.setInteractive(e.isInteractive)
249 await session.start(hostOf($))
250 const stored = await $.state.get({ plugin: 'receipts', key: 'rows' })
251 if (stored.version === 0) await applyDefaults($, session, isCleanByDefault, isSpikeByDefault)
252 // Publish receipts' switches for any tools panel (switches.ts)
253 await update($, switches, () => receiptsSwitches(true))
254 try {
255 await $.command.register({
256 name: 'receipts',
257 description: 'Toggle the receipts pane, open its settings, or show calibration stats',
258 argumentHint: '[tools|rows|clean|basis|check|stats|wrong|reset-history]',
259 immediate: true,
260 })
261 } catch {
262 // A name clash leaves the mod running without its command
263 }
264 return next(e)
265 })
266
267 // /clear, /resume and /branch reset $.state: put the configured defaults back
268 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
269 await applyDefaults($, session, isCleanByDefault, isSpikeByDefault)
270 return next(e)
271 }).catch(($, e, next) => next(e))
272
273 // A build, debug, config or refactor prompt carries one byte-stable line
274 // asking Claude to record its plan with the task tools, so the band's steps
275 // are Claude's own (invariant 10). The label waits at most 1s; past that
276 // the prompt enters without the line rather than wait
277 on('prompt.submit', async ($, e, next) => {
278 const type = await session.submitType(hostOf($), e.text)
279 if (type === undefined || !BUILD_TYPES.includes(type)) return next(e)
280 return next({ ...e, context: [...(e.context ?? []), PLAN_INSTRUCTION] })
281 }).catch(($, e, next) => next(e))
282
283 on('turn.start', async ($, e, next) => {
284 await session.turnStart(hostOf($), e.turnId, e.text)
285 await update($, working, () => true)
286 return next(e)
287 })
288
289 on('turn.step', async function* ($, e, next) {
290 if (e.agentId === undefined) session.noteEffort(e.effort)
291 const result = yield* next(e)
292 session.stepResult(hostOf($), e, result)
293 return result
294 })
295
296 on('tool.call', async ($, e, next) => {
297 session.beforeTool(e, e)
298 session.toolStarted(e.tool_use_id, await $.clock.now())
299 const outcome = await next(e)
300 await session.afterTool(hostOf($), e, e, outcome).catch(() => undefined)
301 return outcome
302 }).catch(($, e, next) => next(e))
303
304 // The tool's own run time, which excludes the permission prompt: the rest
305 // of the call's span was waiting on the person, and is not learned as work
306 on('classic.PostToolUse', async ($, e, next) => {
307 session.toolRan(e.tool_use_id, e.duration_ms)
308 return next(e)
309 }).catch(($, e, next) => next(e))
310
311 // Under the answer: the receipt, or UNVERIFIED. A mirror, never a gate
312 on('turn.complete', async ($, e, next) => {
313 const result = await next(e)
314 if (e.agentId !== undefined) {
315 session.subagentComplete(hostOf($), e.agentId, e.answer)
316 return result
317 }
318 const line = await session.turnComplete(hostOf($), e)
319 await update($, working, () => false)
320 // The final answer, drawn as one dim line while it streamed, in full now
321 if (quiet.finish(e.answer)) $.ui.invalidate('ui.render')
322 if (!line || !(await read($, receiptLine))) return result
323 const isOwnText = result.text !== '' && result.text !== e.answer
324 return { ...result, text: isOwnText ? `${result.text}\n${line}` : line }
325 })
326
327 on('command.run', { command: 'receipts' }, async ($, e) => {
328 const arg = e.args.trim()
329 if (arg === 'stats') return { text: session.statsText() }
330 if (arg === 'tools') {
331 await update($, toolsOpen, value => !value)
332 return {}
333 }
334 if (arg === 'basis') {
335 session.toggleBasis()
336 $.ui.invalidate('ui.render')
337 return { text: session.isBasisShown ? 'basis shown on the band' : 'basis hidden' }
338 }
339 if (arg === 'check' || arg.startsWith('check ')) {
340 const wanted = arg.slice(5).trim()
341 if (wanted === 'on' || wanted === 'off') session.setCrossCheck(wanted === 'on')
342 else if (wanted !== '') return { text: USAGE }
343 return { text: `cross-check ${session.isCrossCheckOn ? 'on' : 'off'}` }
344 }
345 if (arg === 'wrong') return { text: await session.markWrong(hostOf($)) }
346 if (arg === 'clean') return { text: `rows: ${await toggleClean($)}` }
347 if (arg === 'rows' || arg.startsWith('rows ')) {
348 const wanted = arg.slice(4).trim()
349 if (wanted === '') {
350 const now = await levelOf($)
351 const next = ROWS_LEVELS[(ROWS_LEVELS.indexOf(now) + 1) % ROWS_LEVELS.length]!
352 await setRows($, next)
353 return { text: `rows: ${next}` }
354 }
355 if (!(ROWS_LEVELS as readonly string[]).includes(wanted)) return { text: USAGE }
356 await setRows($, wanted as RowsLevel)
357 return { text: `rows: ${wanted}` }
358 }
359 if (arg === 'reset-history') {
360 const count = await session.resetHistory(hostOf($))
361 return { text: `history cleared: ${count} ${count === 1 ? 'task' : 'tasks'} forgotten` }
362 }
363 if (arg !== '') return { text: USAGE }
364 if (session.paneOpen) {
365 await $.ui.close({ id: PANE_ID })
366 session.paneClosed()
367 return {}
368 }
369 // rows: inline (the main screen) it opens as tall as its content, not cut
370 // to a third; a dock ignores it and the render fits its rows instead
371 const wanted = paneLines(session.viewModel(await $.clock.now())).length + 1
372 const placed = await $.ui.open({ id: PANE_ID, title: PANE_TITLE, rows: Math.max(PANE_MIN_ROWS, Math.min(PANE_MAX_ROWS, wanted)) })
373 session.paneOpened(placed.isPlaced)
374 return {}
375 })
376
377 on('ui.close', { id: PANE_ID }, async ($, e, next) => {
378 session.paneClosed()
379 return next(e)
380 }).catch(($, e, next) => next(e))
381
382 // The pane: the long view, opened only by /receipts
383 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
384 if (e.requestId !== PANE_ID) return next(e)
385 const isClean = (await levelOf($)) !== 'off'
386 await read($, tick)
387 const now = await $.clock.now()
388 session.paneDrawn()
389 session.ensureTicking(hostOf($), now)
390 const { Box, Text, Button } = $.ui.resolve(e)
391 // Never more rows than the room has: the header, then the lines that fit
392 const all = paneLines(session.viewModel(now))
393 const room = Math.max(1, e.props.scroll.bodyRows - 1)
394 const lines =
395 all.length <= room ? all : [...all.slice(0, room - 1), { key: 'pane-more', text: `+${all.length - room + 1} more · /receipts stats`, dim: true }]
396 return Box({
397 flexDirection: 'column',
398 children: [
399 Box({
400 flexDirection: 'row',
401 columnGap: 2,
402 children: [
403 Text({ bold: true, children: ['receipts'] }),
404 Button({
405 key: 'clean-toggle',
406 label: isClean ? 'clean view on' : 'clean view off',
407 hotkey: 'c',
408 plain: true,
409 onPress: () => toggleClean($),
410 }),
411 Button({
412 key: 'basis',
413 label: session.isBasisShown ? 'hide basis' : 'estimate basis',
414 hotkey: 'b',
415 plain: true,
416 onPress: () => {
417 session.toggleBasis()
418 $.ui.invalidate('ui.render')
419 },
420 }),
421 ],
422 }),
423 ...lines.map(line => Text(textPropsOf(line))),
424 ],
425 })
426 })
427
428 // The band: the primary surface. Progress while working, the completion
429 // card after, the tools panel at its right when open, and the Clean View
430 // rule under it while the rows level is not off (frames 10, 18, 26)
431 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
432 if (e.props.hasSurvey) return next(e)
433 const level = await levelOf($)
434 const isToolsOpen = await read($, toolsOpen)
435 const isBandShown = session.isBandWanted()
436 if (!isBandShown && !isToolsOpen && level === 'off') return next(e)
437 await read($, tick)
438 const now = await $.clock.now()
439 session.ensureTicking(hostOf($), now)
440 const el = $.ui.resolve(e)
441 const mods = isToolsOpen ? await modSwitchesOf($) : []
442 const presses: Presses = {
443 'set-rows': () => setRows($, ROWS_LEVELS[(ROWS_LEVELS.indexOf(level) + 1) % ROWS_LEVELS.length]!),
444 'set-crosscheck': () => {
445 session.setCrossCheck(!session.isCrossCheckOn)
446 $.ui.invalidate('ui.render')
447 },
448 'set-spike': () =>
449 update($, spike, value => {
450 session.setSpike(!value)
451 return !value
452 }),
453 'set-chatter': () => update($, chatter, value => !value),
454 // Not $.command.run: it skips the calling plugin's own hooks, so this
455 // mod's /receipts would go unanswered. The session answers, as a toast
456 'launch-stats': () => $.ui.toast(session.statsText(), { timeoutMs: 15_000 }),
457 'launch-wrong': async () => $.ui.toast(await session.markWrong(hostOf($)), { timeoutMs: 8_000 }),
458 }
459 for (const entry of mods) {
460 presses[`mod-${entry.id}`] =
461 entry.mod === 'receipts' && entry.id === RECEIPT_LINE_SWITCH
462 ? () => setReceiptLine($, !entry.value)
463 : () => update($, switchRequests, requests => ({ ...requests, [entry.id]: !entry.value }))
464 }
465 for (const choice of MODEL_CHOICES) {
466 presses[`model-${choice.value}`] = async () => {
467 await choose($, 'model', choice.value)
468 $.ui.invalidate('ui.render')
469 }
470 }
471 for (const choice of EFFORT_CHOICES) {
472 presses[`effort-${choice.value}`] = async () => {
473 await choose($, 'effort', choice.value)
474 session.noteEffort(choice.value)
475 $.ui.invalidate('ui.render')
476 }
477 }
478
479 const columns = e.props.bodyColumns
480 const children: RenderElement[] = []
481 if (isBandShown) {
482 const view = bandView(session.viewModel(now), columns, { collapsed: false, showBasis: session.isBasisShown })
483 children.push(
484 el.Box({
485 key: 'band',
486 flexDirection: 'column',
487 borderStyle: 'round',
488 borderColor: view.border,
489 paddingX: 1,
490 width: columns,
491 children: view.rows.map(row => rowOf(el, row, presses)),
492 }),
493 )
494 }
495 if (isToolsOpen) {
496 const toolsWidth = Math.min(columns, TOOLS_COLUMNS)
497 const rows = toolsView(
498 {
499 model: await sessionModelOf($),
500 ...(session.effortLevel ? { effort: session.effortLevel } : {}),
501 rows: level,
502 crossCheck: session.isCrossCheckOn,
503 spike: await read($, spike),
504 chatter: await read($, chatter),
505 mods,
506 },
507 toolsWidth - 4,
508 )
509 const tools = el.Box({
510 key: 'tools',
511 flexDirection: 'column',
512 borderStyle: 'round',
513 borderColor: ACCENT,
514 paddingX: 1,
515 width: toolsWidth,
516 children: rows.map(row => rowOf(el, row, presses)),
517 })
518 children.push(el.Box({ flexDirection: 'row', justifyContent: 'flex-end', width: columns, children: [tools] }))
519 }
520 if (level !== 'off') children.push(rowOf(el, dividerRow(columns, 'Clean View'), presses))
521 return el.Box({ flexDirection: 'column', width: columns, children })
522 })
523
524 // The footer button that opens and closes the tools panel, beside the
525 // engine's mode labels at the right of the prompt footer (frames 10, 13)
526 on('ui.render', { component: 'SessionMode' }, async ($, e) => {
527 const isOpen = await read($, toolsOpen)
528 const { Box, Text, Button } = $.ui.resolve(e)
529 const modes = e.props.modes
530 return Box({
531 flexDirection: 'row',
532 columnGap: 2,
533 children: [
534 ...(modes.length > 0 ? [Text({ dimColor: true, children: [modes.join(' & ')] })] : []),
535 Box({
536 key: 'tools-footer-box',
537 ...(isOpen ? { backgroundColor: ACCENT } : {}),
538 children: [
539 Button({
540 key: 'tools-footer',
541 label: isOpen ? "◆ Shawn's Tools ▼" : "◆ Shawn's Tools ▲",
542 plain: true,
543 onPress: () => update($, toolsOpen, value => !value),
544 }),
545 ],
546 }),
547 ],
548 })
549 })
550
551 // ctrl+o: a ToolGroup's props say when it is expanded, so an expanded group
552 // draws in full. ToolUse and ToolResult props carry no such flag, so a
553 // single row cannot be expanded past the level; `/receipts rows off` can
554 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
555 const level = await levelOf($)
556 if (level === 'off') return next(e)
557 const isMilestone = session.isMilestoneRow(e.props.tool_use_id, e.props.tool, e.props.input)
558 const { Box, Text } = $.ui.resolve(e)
559 if (level === 'quiet') {
560 if (!isMilestone) return Box({})
561 const text = toolRowText(e.props.tool, e.props.input, session.workingDirectory) + outcomeMarkOf(e.props)
562 return Text({ dimColor: true, wrap: 'truncate-end', children: [text] })
563 }
564 if (isMilestone) return next(e)
565 return Text({ dimColor: true, wrap: 'truncate-end', children: [toolRowText(e.props.tool, e.props.input, session.workingDirectory)] })
566 })
567
568 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
569 const level = await levelOf($)
570 if (level === 'off') return next(e)
571 const { Box, Text } = $.ui.resolve(e)
572 // Quiet: a milestone's outcome is folded into its ToolUse line
573 if (level === 'quiet') return Box({})
574 if (session.isMilestoneRow(e.props.tool_use_id, e.props.tool, undefined)) return next(e)
575 return Text({ dimColor: true, wrap: 'truncate-end', children: [toolResultText(e.props.output, e.props.isErrored)] })
576 })
577
578 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
579 const level = await levelOf($)
580 if (e.props.isExpanded || level === 'off') return next(e)
581 const { Box, Text } = $.ui.resolve(e)
582 if (level === 'quiet') return Box({})
583 return Text({ dimColor: true, wrap: 'truncate-end', children: [toolGroupText(e.props.calls)] })
584 })
585
586 // ---- quiet: the chrome a turn scatters ------------------------------------
587 // Never hooked: AskUserQuestion and the permission dialogs. A question to
588 // the person is the one thing quiet must never fold.
589
590 // The band shows the elapsed time and the step; the spinner repeats it
591 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
592 if ((await levelOf($)) !== 'quiet') return next(e)
593 const { Box } = $.ui.resolve(e)
594 return Box({})
595 })
596
597 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
598 if ((await levelOf($)) !== 'quiet' || !(await read($, working))) return next(e)
599 const { Box } = $.ui.resolve(e)
600 return Box({})
601 })
602
603 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
604 if ((await levelOf($)) !== 'quiet' || !(await read($, working))) return next(e)
605 const { Box } = $.ui.resolve(e)
606 return Box({})
607 })
608
609 on('ui.render', { component: 'InfoNotice' }, async ($, e, next) => {
610 if ((await levelOf($)) !== 'quiet' || !(await read($, working))) return next(e)
611 const { Box } = $.ui.resolve(e)
612 return Box({})
613 })
614
615 // Another command's output mid-turn; this mod's own and any error line show
616 on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
617 if (e.props.command === 'receipts' || e.props.isErrored) return next(e)
618 if ((await levelOf($)) !== 'quiet' || !(await read($, working))) return next(e)
619 const { Box } = $.ui.resolve(e)
620 return Box({})
621 })
622
623 // A subagent's hand-back, a peer's message, a task notification: nothing
624 // while the turn runs, one dim line after. The person's own prompt and a
625 // ctrl+o expanded row are never touched
626 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
627 if (e.props.isExpanded || e.props.origin.kind === 'composer') return next(e)
628 if ((await levelOf($)) !== 'quiet' || !(await read($, chatter))) return next(e)
629 const { Box, Text } = $.ui.resolve(e)
630 if (await read($, working)) return Box({})
631 return Text({ dimColor: true, wrap: 'truncate-end', children: [handbackLineOf(e.props.text, e.props.from?.name)] })
632 })
633
634 // Interim text: its first line, dim. The final answer redraws in full when
635 // turn.complete names it (QuietLog). A block never seen mid-turn is left alone
636 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
637 if ((await levelOf($)) !== 'quiet') return next(e)
638 const isWorking = await read($, working)
639 if (isWorking) quiet.seen(e.requestId, e.props.text)
640 const kind = quiet.kindOf(e.requestId)
641 if (kind !== 'interim') return next(e)
642 const { Text } = $.ui.resolve(e)
643 return Text({ dimColor: true, wrap: 'truncate-end', children: [firstLineOf(e.props.text)] })
644 })
645}
646src/band.ts 582 lines1/**
2 * The band above the prompt and the tools panel, as rows of styled
3 * segments, each row exactly the width it is given. Pure: no `$`, no
4 * elements. `hooks/register.ts` turns a segment into a Text (or a Button
5 * when it carries one) and a row into a Box; tests and `scripts/mock-band.ts`
6 * read the same rows as plain text.
7 *
8 * Laying out to exact widths here, instead of trusting flex to right-align,
9 * keeps the right-hand column (elapsed, percent, the estimate) where the
10 * tests say it is at every width, and nothing ever wraps the band taller.
11 */
12
13import type { Color } from 'claude-code'
14
15import { crossCheckRowOf, type CrossCheck } from './crosscheck'
16import { basisLines, durationOf, estimateRow, type Estimate } from './estimator'
17import type { Milestone, Plan } from './milestones'
18import type { Switch } from './switches'
19import { truncate, type ViewModel } from './view'
20
21export const ACCENT: Color = 'claude'
22export const DONE: Color = 'success'
23export const WARN: Color = 'warning'
24/** Over the range: the bar and border go grey, never red. Running long is not an error. */
25export const OVER: Color = 'inactive'
26
27/**
28 * Below this many band body columns the per-step bars drop. The band's body
29 * is the terminal less the engine's five cells for its own `[-]`, so 105 is
30 * a 110-column terminal.
31 */
32export const NARROW_BODY = 105
33/** The round border and one cell of padding each side. */
34export const FRAME = 4
35export const MINI_BAR = 16
36/** The step labels' column, as a share of the band's width (frames 20, 26). */
37const LABEL_SHARE = 0.3
38/** The ask in the title row is cut here, room or not (frame 18). */
39export const TITLE_MAX = 39
40export const MAX_STEP_ROWS = 6
41const MIN_TAIL = 12
42
43export type SegButton = {
44 key: string
45 label: string
46 hotkey?: string
47}
48
49export type Seg = {
50 text: string
51 color?: Color
52 dim?: boolean
53 bold?: boolean
54 inverse?: boolean
55 /** Shrinks first when the row is too wide. */
56 grow?: boolean
57 /** Drawn as a plain Button; `text` is what the terminal draws for it. */
58 button?: SegButton
59}
60
61export type Row = {
62 key: string
63 segs: Seg[]
64}
65
66export type BandTone = 'working' | 'over' | 'done' | 'answered' | 'ended' | 'unverified' | 'refuted' | 'stopped'
67
68export type BandView = {
69 tone: BandTone
70 border: Color
71 rows: Row[]
72}
73
74export type BandOptions = {
75 collapsed: boolean
76 showBasis: boolean
77}
78
79export function innerWidthOf(columns: number): number {
80 return Math.max(1, columns - FRAME)
81}
82
83export function rowText(row: Row): string {
84 return row.segs.map(seg => seg.text).join('')
85}
86
87function widthOf(segs: readonly Seg[]): number {
88 return segs.reduce((sum, seg) => sum + [...seg.text].length, 0)
89}
90
91function space(n: number): Seg {
92 return { text: ' '.repeat(Math.max(0, n)) }
93}
94
95/**
96 * A plain Button as a segment: `b: basis` with a hotkey, the label alone without.
97 */
98function buttonSeg(key: string, label: string, hotkey?: string, dim = true): Seg {
99 return {
100 text: hotkey ? `${hotkey}: ${label}` : label,
101 ...(dim ? { dim: true } : {}),
102 button: { key, label, ...(hotkey ? { hotkey } : {}) },
103 }
104}
105
106/**
107 * Cuts segments to `width` cells from the right, keeping each one's style;
108 * a Button that no longer fits whole is dropped, never drawn half.
109 */
110function clip(segs: readonly Seg[], width: number): Seg[] {
111 const out: Seg[] = []
112 let left = width
113 for (const seg of segs) {
114 const length = [...seg.text].length
115 if (length <= left) {
116 out.push(seg)
117 left -= length
118 continue
119 }
120 if (left > 0 && !seg.button) out.push({ ...seg, text: truncate(seg.text, left) })
121 else if (left > 0) out.push(space(left))
122 left = 0
123 break
124 }
125 return out
126}
127
128/**
129 * One row of exactly `width` cells: `left` at the start, `right` at the end,
130 * at least `gap` spaces between. The `grow` segment of `left` gives way first.
131 */
132function line(width: number, left: readonly Seg[], right: readonly Seg[] = [], gap = 2): Seg[] {
133 const rightWidth = widthOf(right)
134 const room = width - rightWidth - (right.length > 0 ? gap : 0)
135 let segs = [...left]
136 const over = widthOf(segs) - room
137 if (over > 0) {
138 const i = segs.findIndex(seg => seg.grow)
139 if (i !== -1) {
140 const seg = segs[i]!
141 const keep = Math.max(0, [...seg.text].length - over)
142 segs[i] = { ...seg, text: keep === 0 ? '' : truncate(seg.text, keep) }
143 }
144 if (widthOf(segs) > Math.max(0, room)) segs = clip(segs, Math.max(0, room))
145 }
146 if (rightWidth > width) return clip([...right], width)
147 const pad = width - widthOf(segs) - rightWidth
148 return [...segs, space(pad), ...right]
149}
150
151function barSegs(progress: number, width: number, color: Color, isDim = false, full = '━', empty = '─'): Seg[] {
152 const filled = Math.max(0, Math.min(width, Math.round(progress * width)))
153 return [
154 { text: full.repeat(filled), color, ...(isDim ? { dim: true } : {}) },
155 { text: empty.repeat(width - filled), dim: true },
156 ]
157}
158
159// ---- the band ---------------------------------------------------------------
160
161function currentIndexOf(plan: Plan): number {
162 return plan.items.findIndex(item => item.state === 'current')
163}
164
165function reachedOf(plan: Plan | null): { done: number; total: number } {
166 const items = plan?.items ?? []
167 return { done: items.filter(item => item.state === 'done').length, total: items.length }
168}
169
170function hasSteps(plan: Plan | null): plan is Plan {
171 return plan !== null && plan.items.length > 0
172}
173
174function stepCounterOf(plan: Plan): string {
175 const n = plan.items.length
176 const current = currentIndexOf(plan)
177 const done = plan.items.filter(item => item.state === 'done').length
178 const i = current === -1 ? Math.min(done + 1, n) : current + 1
179 return `Step ${i} of ${n}` + (plan.source === 'answer' ? ' · answer' : '')
180}
181
182/**
183 * The ask as the title row shows it: one line, cut at TITLE_MAX with an
184 * ellipsis even when there is room, as the reference band does (frame 18).
185 */
186function askOf(title: string): string {
187 return truncate(title.replace(/\s+/g, ' ').trim() || 'continuing', TITLE_MAX)
188}
189
190function titleRow(model: ViewModel, width: number, tone: BandTone): Row {
191 const title = askOf(model.title)
192 if (tone === 'working' || tone === 'over') {
193 // The estimate keeps its place here, dim and with its basis (honesty
194 // contract), where the reference band leaves the row empty
195 const est = model.estimate ? estimateRow(model.estimate) : ''
196 const left: Seg[] = [{ text: '✶ ', color: ACCENT, bold: true }, { text: title, color: ACCENT, bold: true }]
197 const right: Seg[] = [...(est ? [{ text: est, dim: true, grow: true }, space(2)] : []), { text: durationOf(model.elapsedMs) }]
198 return { key: 'title', segs: lineRight(width, left, right) }
199 }
200 const finished = model.finished
201 const totalMs = finished?.totalMs ?? model.elapsedMs
202 const waiting = finished?.waitingAgents ?? 0
203 const tail: Seg[] = waiting > 0 ? [{ text: `waiting on ${waiting} ${waiting === 1 ? 'agent' : 'agents'}`, color: WARN }] : []
204 const took: Seg[] = [...(tail.length ? [...tail, space(2)] : []), { text: `took ${durationOf(totalMs)}` }]
205 const badgeOf = (text: string, color: Color): Seg => ({ text: ` ${text} `, color, inverse: true, bold: true })
206 let badge: Seg
207 let text: Seg = { text: title, grow: true }
208 let right = took
209 switch (tone) {
210 case 'stopped':
211 badge = badgeOf('■ Stopped', OVER)
212 text = { text: title, dim: true, grow: true }
213 break
214 case 'refuted':
215 // The cross-check's reason, verbatim (invariant 12)
216 badge = badgeOf('✗ Done, refuted', WARN)
217 text = { text: finished?.crossCheck && 'reason' in finished.crossCheck ? finished.crossCheck.reason || title : title, color: WARN, grow: true }
218 break
219 case 'unverified':
220 badge = finished?.ledger === 'failed' ? badgeOf('✗ Done, checks failed', WARN) : badgeOf('⚠ Done, unverified', WARN)
221 text = { text: title, color: WARN, grow: true }
222 break
223 case 'ended': {
224 // Steps left, or work with no claim of done: say how far it got.
225 // Scar: a green card over three steps that never ran, read as finished
226 const { done, total } = reachedOf(model.plan)
227 badge = badgeOf(hasSteps(model.plan) && model.plan.source === 'tasks' ? `■ Turn ended · ${done} of ${total} ${total === 1 ? 'step' : 'steps'} reached` : '■ Turn ended', OVER)
228 break
229 }
230 case 'answered':
231 // An answer, not a job: the badge carries the time
232 badge = badgeOf(`✓ Answered · ${durationOf(totalMs)}`, DONE)
233 text = { text: title, color: DONE, grow: true }
234 right = tail
235 break
236 default:
237 badge = badgeOf('✓ All done', DONE)
238 text = { text: title, color: DONE, grow: true }
239 }
240 return { key: 'title', segs: line(width, [badge, space(1), text], right) }
241}
242
243/**
244 * A row whose right side may give way: `right`'s grow segment shrinks first,
245 * so the elapsed time at the end is never cut.
246 */
247function lineRight(width: number, left: readonly Seg[], right: readonly Seg[]): Seg[] {
248 const room = width - widthOf(left) - 2
249 let segs = [...right]
250 const over = widthOf(segs) - room
251 if (over > 0) {
252 const i = segs.findIndex(seg => seg.grow)
253 if (i !== -1) {
254 const keep = Math.max(0, [...segs[i]!.text].length - over)
255 segs = keep < MIN_TAIL ? segs.filter((_, j) => j !== i && j !== i + 1) : segs.map((seg, j) => (j === i ? { ...seg, text: truncate(seg.text, keep) } : seg))
256 }
257 }
258 return line(width, left, segs)
259}
260
261/** A bar of cells, filled then empty, as the reference band draws its bars. */
262function cellsOf(progress: number, width: number, color: Color): Seg[] {
263 return barSegs(progress, width, color, false, '█', '░')
264}
265
266function summaryRow(model: ViewModel, width: number, tone: BandTone): Row {
267 const plan = model.plan
268 const barRow = (label: string, progress: number, color: Color, percentSeg: (text: string) => Seg): Row => {
269 const percent = `${Math.round(progress * 100)}%`
270 const barWidth = Math.max(1, width - [...label].length - 2 - percent.length)
271 return { key: 'summary', segs: line(width, [{ text: label }, space(1), ...cellsOf(progress, barWidth, color), space(1), percentSeg(percent)], [], 0) }
272 }
273 if (!model.isWorking) {
274 if (!hasSteps(plan)) return { key: 'summary', segs: line(width, [{ text: 'no steps recorded (Claude made no task list)', dim: true }], [], 0) }
275 const { done, total } = reachedOf(plan)
276 const label = `${done} of ${total} ${total === 1 ? 'step' : 'steps'}` + (plan.source === 'answer' ? ' · answer' : '')
277 const color = tone === 'done' || tone === 'answered' ? DONE : tone === 'stopped' || tone === 'ended' ? OVER : WARN
278 return barRow(label, done / total, color, text => ({ text, color, bold: true }))
279 }
280 if (!hasSteps(plan)) {
281 // No task list: no steps and no percent, only the clock
282 return { key: 'summary', segs: line(width, [{ text: `working · ${durationOf(model.elapsedMs)}`, color: ACCENT }], [], 0) }
283 }
284 const est: Estimate = model.estimate ?? { kind: 'indeterminate' }
285 const isOver = est.kind === 'range' && est.isOver
286 const progress = est.kind === 'range' ? est.progress : 0
287 return barRow(stepCounterOf(plan), progress, isOver ? OVER : ACCENT, text => (isOver ? { text, dim: true } : { text, color: ACCENT, bold: true }))
288}
289
290/**
291 * The word after a step's bar, as the reference draws them: Done; the step
292 * under way's own percent once it has any, else Working; Next for the step
293 * after it, Up next for the rest.
294 */
295function stateWordOf(item: Milestone, index: number, firstPending: number, isWorking: boolean, progress: number): Seg {
296 if (item.state === 'done') return { text: 'Done', ...(isWorking ? { dim: true } : {}) }
297 if (!isWorking) return { text: 'Not reached', dim: true }
298 if (item.state === 'current') return { text: progress > 0 ? `${Math.round(progress * 100)}%` : 'Working', color: ACCENT, bold: true }
299 return { text: index === firstPending ? 'Next' : 'Up next', dim: true }
300}
301
302function stepRows(model: ViewModel, width: number, tone: BandTone): Row[] {
303 const plan = model.plan
304 if (!plan || plan.items.length === 0) return []
305 const items = plan.items
306 const current = currentIndexOf(plan)
307 const firstPending = items.findIndex((item, i) => item.state === 'pending' && i > current)
308 const start = items.length <= MAX_STEP_ROWS ? 0 : Math.max(0, Math.min(current - 1, items.length - MAX_STEP_ROWS))
309 const shown = items.slice(start, start + MAX_STEP_ROWS)
310 const isWide = width + FRAME >= NARROW_BODY
311 const wordWidth = 'Not reached'.length
312 // The bars sit in one column, a fixed share of the width, whatever the
313 // labels' lengths (frames 20 and 26); a longer label is cut
314 const labelWidth = isWide
315 ? Math.max(8, Math.min(Math.floor(width * LABEL_SHARE), width - 2 - 2 - MINI_BAR - 2 - wordWidth))
316 : Math.max(4, Math.min(Math.max(...shown.map(item => [...item.label].length)), width - 2 - 2 - wordWidth))
317 const stepProgress = model.estimate?.kind === 'range' ? model.estimate.stepProgress : []
318
319 const rows = shown.map((item, offset): Row => {
320 const i = start + offset
321 const glyph: Seg =
322 item.state === 'done'
323 ? { text: '✓', color: DONE }
324 : item.state === 'current' && model.isWorking
325 ? { text: '●', color: ACCENT }
326 : { text: '○', dim: true }
327 const label = truncate(item.label, labelWidth).padEnd(labelWidth)
328 const labelSeg: Seg =
329 item.state === 'current' && model.isWorking ? { text: label, bold: true } : item.state === 'pending' ? { text: label, dim: true } : { text: label }
330 const progress = item.state === 'current' ? (stepProgress[i] ?? 0) : 0
331 const word = stateWordOf(item, i, firstPending, model.isWorking, progress)
332 let bar: Seg[] = []
333 if (isWide) {
334 const doneColor = tone === 'working' || tone === 'over' || tone === 'done' || tone === 'answered' ? DONE : OVER
335 bar =
336 item.state === 'done'
337 ? cellsOf(1, MINI_BAR, doneColor)
338 : item.state === 'current' && model.isWorking
339 ? cellsOf(progress, MINI_BAR, tone === 'over' ? OVER : ACCENT)
340 : cellsOf(0, MINI_BAR, OVER)
341 bar = [...bar, space(2)]
342 }
343 return { key: `step-${i}`, segs: line(width, [glyph, space(1), labelSeg, space(2), ...bar, word], [], 0) }
344 })
345 if (items.length > MAX_STEP_ROWS) {
346 rows.push({ key: 'more', segs: line(width, [{ text: `+${items.length - MAX_STEP_ROWS} more`, dim: true }], [], 0) })
347 }
348 return rows
349}
350
351/**
352 * The rule the reference draws just above the prompt with the view's name at
353 * its right end: `──────── Clean View ─`, the band's full width.
354 */
355export function dividerRow(columns: number, label: string): Row {
356 const tail = ` ${label} ─`
357 return { key: 'divider', segs: [{ text: '─'.repeat(Math.max(0, columns - [...tail].length)), dim: true }, { text: tail, dim: true }] }
358}
359
360/**
361 * The card a finished turn earns. Invariant 13: All done needs all three:
362 * every recorded step completed, a receipt after the last edit, and no
363 * refutation from the cross-check. Scar: green "All done" over 2 of 5 steps.
364 */
365function toneOf(model: ViewModel): BandTone {
366 if (model.isWorking) return model.estimate?.kind === 'range' && model.estimate.isOver ? 'over' : 'working'
367 const finished = model.finished
368 if (!finished) return 'done'
369 if (finished.isAborted) return 'stopped'
370 if (finished.crossCheck?.state === 'refuted') return 'refuted'
371 if (finished.ledger === 'failed') return 'unverified'
372 const plan = model.plan
373 if (plan && plan.source === 'tasks' && plan.items.some(item => item.state !== 'done')) return 'ended'
374 if (!finished.hasWork) return 'answered'
375 if (finished.ledger === 'unverified') return finished.claimsDone ? 'unverified' : 'ended'
376 return 'done'
377}
378
379const BORDER: Record<BandTone, Color> = {
380 working: ACCENT,
381 over: OVER,
382 done: DONE,
383 answered: DONE,
384 ended: OVER,
385 unverified: WARN,
386 refuted: WARN,
387 stopped: OVER,
388}
389
390/** The receipt row: the line under the answer, coloured by what it says. */
391function receiptRow(receipt: string, width: number): Row {
392 const color = receipt.startsWith('receipt') ? DONE : WARN
393 return { key: 'receipt', segs: line(width, [{ text: receipt, color, grow: true }], [], 0) }
394}
395
396function crossCheckRow(check: CrossCheck, width: number): Row {
397 const seg: Seg =
398 check.state === 'confirmed'
399 ? { text: crossCheckRowOf(check), color: DONE, grow: true }
400 : check.state === 'refuted'
401 ? { text: crossCheckRowOf(check), color: WARN, grow: true }
402 : { text: crossCheckRowOf(check), dim: true, grow: true }
403 return { key: 'cross-check', segs: line(width, [seg], [], 0) }
404}
405
406/**
407 * The band: title, summary, one row per step (six at most, then `+n more`),
408 * the receipt row and the cross-check row once the turn ended, the basis
409 * tooltip when asked, and a failing calibration score, which is never folded
410 * away (invariant 3). Collapsed, the title row alone. `columns` is the
411 * band's body width.
412 */
413export function bandView(model: ViewModel, columns: number, options: BandOptions): BandView {
414 const width = innerWidthOf(columns)
415 const tone = toneOf(model)
416 const rows: Row[] = [titleRow(model, width, tone)]
417 if (!options.collapsed) {
418 rows.push(summaryRow(model, width, tone), ...stepRows(model, width, tone))
419 const finished = model.isWorking ? null : model.finished
420 if (finished?.receipt) rows.push(receiptRow(finished.receipt, width))
421 if (finished?.crossCheck) rows.push(crossCheckRow(finished.crossCheck, width))
422 if (options.showBasis) {
423 const basis = model.isWorking && model.estimate ? (basisLines(model.estimate)[0] ?? '') : ''
424 const text = [basis, model.calibration[0] ?? ''].filter(Boolean).join(' · ')
425 rows.push({ key: 'basis', segs: line(width, [{ text, dim: true, grow: true }], [], 0) })
426 }
427 const warning = model.calibration[1]
428 if (warning) rows.push({ key: 'calibration', segs: line(width, [{ text: warning, color: WARN, grow: true }], [], 0) })
429 }
430 return { tone, border: BORDER[tone], rows }
431}
432
433// ---- the tools panel ------------------------------------------------------
434
435/** The model chips, labelled as the reference panel labels them (frame 14). */
436export const MODEL_CHOICES = [
437 { value: 'haiku', label: 'Haiku 4.5' },
438 { value: 'sonnet', label: 'Sonnet 5' },
439 { value: 'opus', label: 'Opus 5.5' },
440 { value: 'fable', label: 'Fable 5.1' },
441] as const
442
443export const EFFORT_CHOICES = [
444 { value: 'low', label: 'Low' },
445 { value: 'medium', label: 'Medium' },
446 { value: 'high', label: 'High' },
447 { value: 'xhigh', label: 'XHigh' },
448 { value: 'max', label: 'Max' },
449] as const
450
451/** The panel's widest, border and padding included (frame 14: about 67 columns). */
452export const TOOLS_COLUMNS = 67
453
454/**
455 * How much of the transcript the mod draws away. `off`: every row as Claude
456 * Code draws it. `clean`: tool rows one dim line, milestones in full.
457 * `quiet`: tool rows nothing, milestones one dim line, and the chrome a turn
458 * scatters (spinner, progress, notices, hand-backs, interim text) folded.
459 */
460export type RowsLevel = 'off' | 'clean' | 'quiet'
461export const ROWS_LEVELS: readonly RowsLevel[] = ['off', 'clean', 'quiet']
462const ROWS_LABEL: Record<RowsLevel, string> = { off: 'Off', clean: 'Clean', quiet: 'Quiet' }
463
464export type ToolsModel = {
465 /** What `$.session.model()` answered. */
466 model: string
467 /** The effort level last seen on a model request, if any. */
468 effort?: string
469 rows: RowsLevel
470 crossCheck: boolean
471 spike: boolean
472 /** Fold subagent hand-backs and peer messages at the quiet level. */
473 chatter: boolean
474 /** Every mod's published switches, receipts first. */
475 mods: readonly Switch[]
476}
477
478/**
479 * The alias a model name answers to: `claude-opus-5-5[1m]` is `opus`.
480 */
481export function aliasOf(model: string): string | undefined {
482 const name = model.toLowerCase()
483 return MODEL_CHOICES.find(choice => name.includes(choice.value))?.value
484}
485
486function spaced(text: string): string {
487 return [...text.toUpperCase()].join(' ')
488}
489
490function chipRow(key: string, header: string, choices: readonly { value: string; label: string }[], current: string | undefined, color: Color, width: number): Row {
491 const segs: Seg[] = [{ text: header.padEnd(10), dim: true }]
492 choices.forEach((choice, i) => {
493 if (i > 0) segs.push(space(2))
494 if (choice.value === current) segs.push({ text: ` ${choice.label} `, color, inverse: true, bold: true })
495 else segs.push(buttonSeg(`${key}-${choice.value}`, choice.label, undefined, false))
496 })
497 return { key, segs: line(width, segs, [], 0) }
498}
499
500/** A dot, a name, a dim description, and the toggle at the right end. */
501function settingRow(key: string, rowKey: string, name: string, help: string, isOn: boolean, toggle: string, width: number): Row {
502 const left: Seg[] = [isOn ? { text: '●', color: DONE } : { text: '○', dim: true }, space(1), { text: name, bold: true }, space(2), { text: help, dim: true, grow: true }]
503 return { key: rowKey, segs: line(width, left, [buttonSeg(key, toggle, undefined, !isOn)]) }
504}
505
506function ruleOf(title: string, width: number): Row {
507 const head = `── ${spaced(title)} `
508 return { key: `rule-${title}`, segs: [{ text: truncate(head, width), dim: true }, { text: '─'.repeat(Math.max(0, width - [...head].length)), dim: true }] }
509}
510
511function blank(key: string, width: number): Row {
512 return { key, segs: [space(width)] }
513}
514
515/**
516 * The tools panel, laid out as the reference panel (frame 14): a
517 * letter-spaced title with the model and effort at the right, MODEL and
518 * EFFORT chips with the current one highlighted and not pressable, SETTINGS
519 * rows, the MODS switches other mods publish, and LAUNCH actions.
520 * `width` is the panel's inner width.
521 */
522export function toolsView(model: ToolsModel, width: number): Row[] {
523 const alias = aliasOf(model.model)
524 const modelLabel = MODEL_CHOICES.find(choice => choice.value === alias)?.label ?? (model.model || 'model unknown')
525 const effort = model.effort?.toLowerCase()
526 const effortLabel = effort ? (EFFORT_CHOICES.find(choice => choice.value === effort)?.label ?? effort) : null
527 const status = [modelLabel, effortLabel].filter(Boolean).join(' · ')
528 const onOff = (isOn: boolean) => (isOn ? 'On' : 'Off')
529 const rows: Row[] = [
530 {
531 key: 'tools-head',
532 segs: lineRight(width, [{ text: '◆ ', color: ACCENT }, { text: `${spaced("Shawn's")} ${spaced('tools')}`, color: ACCENT, bold: true }], [{ text: status, dim: true, grow: true }]),
533 },
534 blank('tools-gap-1', width),
535 chipRow('model', 'MODEL', MODEL_CHOICES, alias, ACCENT, width),
536 chipRow('effort', 'EFFORT', EFFORT_CHOICES, effort, 'autoAccept', width),
537 blank('tools-gap-2', width),
538 ruleOf('settings', width),
539 blank('tools-gap-3', width),
540 settingRow('set-rows', 'set-rows-row', 'Clean View', 'simple checklist', model.rows !== 'off', ROWS_LABEL[model.rows], width),
541 settingRow('set-crosscheck', 'set-crosscheck-row', 'Receipts cross-check', 'a second agent re-checks done', model.crossCheck, onOff(model.crossCheck), width),
542 settingRow('set-spike', 'set-spike-row', 'Spike', 'sizing agent for new tasks', model.spike, onOff(model.spike), width),
543 settingRow('set-chatter', 'set-chatter-row', 'Suppress agent chatter', 'fold subagent hand-backs', model.chatter, onOff(model.chatter), width),
544 blank('tools-gap-4', width),
545 ruleOf('mods', width),
546 blank('tools-gap-5', width),
547 ...(model.mods.length > 0
548 ? model.mods.map(entry => settingRow(`mod-${entry.id}`, `mod-${entry.id}-row`, entry.label, entry.description, entry.value, onOff(entry.value), width))
549 : [{ key: 'mods-none', segs: line(width, [{ text: 'no switches registered', dim: true }], [], 0) }]),
550 blank('tools-gap-6', width),
551 ruleOf('launch', width),
552 blank('tools-gap-7', width),
553 {
554 key: 'launch',
555 segs: line(
556 width,
557 [
558 { text: '✦ ', color: ACCENT },
559 buttonSeg('launch-stats', 'Receipts stats', undefined, false),
560 space(6),
561 { text: '◆ ', color: 'autoAccept' },
562 buttonSeg('launch-wrong', 'Mark receipt wrong', undefined, false),
563 ],
564 [],
565 0,
566 ),
567 },
568 ]
569 return rows
570}
571
572/**
573 * Rows inside a round border, as the terminal draws them, for mocks and
574 * docs. Plain text has no fill, so an inverted ` cell ` shows as `[cell]`,
575 * the same width.
576 */
577export function framedText(rows: readonly Row[], width: number): string[] {
578 const plain = (row: Row) =>
579 row.segs.map(seg => (seg.inverse && /^ .* $/.test(seg.text) ? `[${seg.text.slice(1, -1)}]` : seg.text)).join('')
580 return [`╭${'─'.repeat(width + 2)}╮`, ...rows.map(row => `│ ${plain(row)} │`), `╰${'─'.repeat(width + 2)}╯`]
581}
582src/crosscheck.ts 119 lines1/**
2 * The adversarial cross-check (SPEC-0.3 section 4) and the plan instruction
3 * (section 1): pure text in and out, no `$`.
4 *
5 * Invariant 12: the cross-check is independent. A separate agent, read-only,
6 * that may re-run the gate; its verdict is displayed verbatim and never
7 * softened. Scar: "a subagent's 'it works' is a hypothesis", and the same holds
8 * for the main loop's own "done", which is why something else re-checks it.
9 */
10
11/**
12 * Attached beside a build, debug, config or refactor prompt. Byte-stable, so
13 * the prompt cache sees the same text every time.
14 */
15export const PLAN_INSTRUCTION =
16 'Before non-trivial work, record your plan with TaskCreate as 2 to 8 short steps, mark each in_progress and completed with TaskUpdate as you go, and keep the list current if the plan changes.'
17
18export const DIFF_MAX_LINES = 400
19export const CROSS_CHECK_CAP_MS = 90_000
20export const CROSS_CHECK_AGENT = 'Explore'
21/** Above this share of the five-hour window, no cross-check is spawned. */
22export const USAGE_GUARD_PERCENT = 85
23const CLIP = 800
24const REASON_MAX = 120
25
26export type Verdict = {
27 verdict: 'confirmed' | 'refuted' | 'unclear'
28 reason: string
29 reran: boolean
30 exit: number | null
31}
32
33export type CrossCheck =
34 | { state: 'running'; model: string }
35 | {
36 state: 'confirmed' | 'refuted' | 'unclear'
37 model: string
38 reason: string
39 reran: boolean
40 exit: number | null
41 /** The verify command it could have re-run, for the row. */
42 command?: string
43 ms: number
44 }
45
46function clip(text: string, max = CLIP): string {
47 return text.length <= max ? text : text.slice(0, max - 1) + '…'
48}
49
50/**
51 * The diff the agent reads: whole up to DIFF_MAX_LINES, else its stat and a
52 * note that it was too large, so the agent knows it read a summary.
53 */
54export function diffForCheck(diff: string, stat: string): string {
55 const lines = diff.replace(/\n+$/, '').split('\n')
56 if (lines.length <= DIFF_MAX_LINES) return diff
57 return `diff too large to read in full (${lines.length} lines); git diff --stat:\n${stat}`
58}
59
60export function crossCheckPromptOf(args: { ask: string; claim: string; ledger: readonly string[]; diff: string; files: readonly string[] }): string {
61 return [
62 'Try to refute the claim that this work is done and verified. Re-run the verify command if one exists (read-only otherwise). Default to refuted if uncertain.',
63 'Do not edit any file. Answer with JSON only:',
64 '{"verdict": "confirmed" | "refuted" | "unclear", "reason": "at most 120 characters", "reran": true | false, "exit": <exit code of your re-run, or null>}',
65 '',
66 'The request:',
67 clip(args.ask),
68 '',
69 'The claim:',
70 clip(args.claim),
71 '',
72 'What ran (command · exit code · summary line):',
73 ...(args.ledger.length > 0 ? args.ledger : ['(nothing that looks like a test, build or check)']),
74 '',
75 'Files edited:',
76 ...args.files,
77 '',
78 'The diff:',
79 args.diff.trim() || '(empty: the files may be new and untracked; read them)',
80 ].join('\n')
81}
82
83/**
84 * The agent's JSON, in a fence or bare. Anything that does not parse into a
85 * verdict is `unclear`, never a guess at what it meant.
86 */
87export function parseVerdict(answer: string): Verdict {
88 const unclear: Verdict = { verdict: 'unclear', reason: '', reran: false, exit: null }
89 const body = /\{[\s\S]*\}/.exec(answer)?.[0]
90 if (!body) return unclear
91 try {
92 const raw = JSON.parse(body) as Record<string, unknown>
93 const verdict = raw.verdict
94 if (verdict !== 'confirmed' && verdict !== 'refuted' && verdict !== 'unclear') return unclear
95 return {
96 verdict,
97 reason: typeof raw.reason === 'string' ? clip(raw.reason.replace(/\s+/g, ' ').trim(), REASON_MAX) : '',
98 reran: raw.reran === true,
99 exit: typeof raw.exit === 'number' ? raw.exit : null,
100 }
101 } catch {
102 return unclear
103 }
104}
105
106function secondsOf(ms: number): string {
107 const seconds = Math.round(ms / 1000)
108 return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`
109}
110
111/** The card's cross-check row, the agent's reason verbatim. */
112export function crossCheckRowOf(check: CrossCheck): string {
113 if (check.state === 'running') return `cross-check · running (${check.model})…`
114 if (check.state === 'refuted') return `cross-check · ✗ refuted: ${check.reason || 'no reason given'}`
115 if (check.state === 'unclear') return `cross-check · ? unclear${check.reason ? `: ${check.reason}` : ''}`
116 const how = check.reran ? `reran ${check.command ?? 'the gate'} exit ${check.exit ?? '?'}` : 'did not re-run'
117 return `cross-check · ✓ confirmed (${check.model}, ${how}) · ${secondsOf(check.ms)}`
118}
119src/host.ts 41 lines1import type {
2 AgentSpawnArgs,
3 AgentSpawnResult,
4 FsEntry,
5 ModelCompleteRequest,
6 ModelCompleteResult,
7 SessionRepo,
8 Timer,
9} from 'claude-code'
10
11/**
12 * Everything the session logic needs from Claude Code, as plain functions.
13 *
14 * `hooks/register.ts` builds one from `$` in a top-level `hostOf($)`, so
15 * every mods API call stays spelled out where `claude plugin validate` reads
16 * it, and nothing under `src/` touches `$`. A test can hand the session a
17 * fake host with a scripted clock and store.
18 */
19export type Host = {
20 now: () => Promise<number>
21 every: (ms: number, fn: () => void) => Timer
22 after: (ms: number, fn: () => void) => Timer
23 storeGet: (key: string) => Promise<unknown>
24 storeSet: (key: string, value: unknown) => Promise<void>
25 storeDelete: (key: string) => Promise<void>
26 /** Redraws the pane and the band (they read the tick); tool rows are left alone. */
27 redraw: () => void
28 classify: (text: string, labels: readonly string[]) => Promise<string | undefined>
29 complete: (request: ModelCompleteRequest) => Promise<ModelCompleteResult>
30 spawn: (args: AgentSpawnArgs) => Promise<AgentSpawnResult>
31 cwd: () => Promise<string>
32 repo: () => Promise<SessionRepo | null>
33 list: (path: string) => Promise<FsEntry[]>
34 /** The session's agents, as `$.agent.list()` answers. */
35 agents: () => Promise<readonly { id: string; status: string; parentId?: string; spawnedBy?: string }[]>
36 /** The session's usage, as `$.session.usage()` answers: rate-limit windows and cost. */
37 /** Runs a command for the cross-check's diff, as `$.process.run`. */
38 run: (argv: readonly string[], cwd: string) => Promise<{ exitCode: number; stdout: string }>
39 usage: () => Promise<{ rateLimits: readonly { kind: string; percentUsed: number; resetsAt?: string }[]; cost?: { usd: number } }>
40}
41src/quiet.ts 76 lines1/**
2 * The quiet level's memory of assistant text: which blocks were interim
3 * (drawn as their first line, dim) and which was the turn's final answer
4 * (redrawn in full when the turn completes). Keyed by the render's
5 * `requestId`, the block's own id, so a redraw finds the same verdict.
6 *
7 * Drawing only (invariant 4): nothing here touches the stored messages, and
8 * a block the mod never saw during a turn (history, a resumed session) is
9 * left to Claude Code.
10 */
11
12/** Ids kept per kind before the oldest are forgotten; a long session stays small. */
13const MAX_IDS = 2_000
14
15export class QuietLog {
16 private readonly turnBlocks = new Map<string, string>()
17 private readonly interim = new Set<string>()
18 private readonly final = new Set<string>()
19
20 /** A block drawn while a turn runs: interim until the turn says otherwise. */
21 seen(id: string, text: string): void {
22 if (this.final.has(id)) return
23 this.turnBlocks.set(id, text)
24 this.interim.add(id)
25 trim(this.interim)
26 }
27
28 /**
29 * The turn ended with `answer`: the blocks whose text is part of it are the
30 * final answer; failing any, the last block drawn. Returns whether any
31 * verdict changed, so the caller knows to redraw.
32 */
33 finish(answer: string): boolean {
34 const blocks = [...this.turnBlocks.entries()]
35 this.turnBlocks.clear()
36 const flat = answer.trim()
37 let finals = blocks.filter(([, text]) => text.trim() !== '' && flat.includes(text.trim())).map(([id]) => id)
38 if (finals.length === 0 && blocks.length > 0) finals = [blocks[blocks.length - 1]![0]]
39 for (const id of finals) {
40 this.interim.delete(id)
41 this.final.add(id)
42 }
43 trim(this.final)
44 return finals.length > 0
45 }
46
47 kindOf(id: string): 'interim' | 'final' | 'unknown' {
48 if (this.final.has(id)) return 'final'
49 if (this.interim.has(id)) return 'interim'
50 return 'unknown'
51 }
52}
53
54function trim(ids: Set<string>): void {
55 while (ids.size > MAX_IDS) {
56 const oldest = ids.values().next().value
57 if (oldest === undefined) return
58 ids.delete(oldest)
59 }
60}
61
62/** The first non-empty line of a block, markdown left as is. */
63export function firstLineOf(text: string): string {
64 return text.split('\n').find(line => line.trim() !== '')?.trim() ?? ''
65}
66
67/**
68 * The one dim line a hand-back or notification row becomes once its turn
69 * ended: `↳ message from @Explore: Found 3 mods`.
70 */
71export function handbackLineOf(text: string, from: string | undefined): string {
72 const head = firstLineOf(text)
73 const who = from ? `message from @${from}` : 'notification'
74 return head ? `↳ ${who}: ${head}` : `↳ ${who}`
75}
76src/switches.ts 47 lines1/**
2 * The tools panel's MODS section: on and off switches that our mods
3 * publish for the one panel to show.
4 *
5 * Each mod publishes its own list in its own `$.state` key `switches`
6 * (`$.store` is a file each plugin owns alone, so it cannot be shared;
7 * `$.state` lets any plugin read any value, its owner alone writes it). The
8 * panel reads every known mod's list. A press on another mod's switch is a
9 * request written to receipts' own `switchRequests` key, `{ [id]: value }`;
10 * the owner reads it and applies it. Receipts applies its own at once.
11 */
12
13export type Switch = {
14 /** The mod that owns the switch. */
15 mod: string
16 id: string
17 label: string
18 description: string
19 value: boolean
20}
21
22/** What a mod publishes: its switches, without the mod name. */
23export type PublishedSwitch = Omit<Switch, 'mod'>
24
25function isPublished(value: unknown): value is PublishedSwitch {
26 if (typeof value !== 'object' || value === null) return false
27 const entry = value as Record<string, unknown>
28 return typeof entry.id === 'string' && typeof entry.label === 'string' && typeof entry.description === 'string' && typeof entry.value === 'boolean'
29}
30
31/**
32 * Every mod's published list as one, receipts first, then the rest in the
33 * order given. A malformed entry, or a mod that published nothing, is
34 * skipped, never a crash in a render hook.
35 */
36export function switchesOf(published: readonly (readonly [mod: string, list: unknown])[]): Switch[] {
37 const ordered = [...published].sort((a, b) => (a[0] === 'receipts' ? -1 : b[0] === 'receipts' ? 1 : 0))
38 return ordered.flatMap(([mod, list]) => (Array.isArray(list) ? list.filter(isPublished).map(entry => ({ mod, ...entry })) : []))
39}
40
41/** Receipts' own switch: the line under an answer that claims done. */
42export const RECEIPT_LINE_SWITCH = 'receipts.line'
43
44export function receiptsSwitches(isLineOn: boolean): PublishedSwitch[] {
45 return [{ id: RECEIPT_LINE_SWITCH, label: 'Receipt line', description: 'under answers that claim done', value: isLineOn }]
46}
47src/session.ts 947 lines1/**
2 * One session's receipts: the task under way, the history it learns into,
3 * and the view model the pane and band draw. Hooks call in through a Host,
4 * never `$` (see host.ts).
5 *
6 * Invariant 6, hooks return fast: every model call here starts unawaited
7 * (the spike, the cross-check) except two labels with deadlines: the task
8 * type at prompt.submit (SUBMIT_DEADLINE_MS, cached for the turn) and the
9 * claims-done label on turn.complete (CLAIMS_DEADLINE_MS, then plain words).
10 *
11 * Invariant 10: the mod never invents plan steps (milestones.ts).
12 * Invariant 13: All done needs every step, a receipt and no refutation (band.ts).
13 */
14
15import {
16 CROSS_CHECK_AGENT,
17 CROSS_CHECK_CAP_MS,
18 crossCheckPromptOf,
19 diffForCheck,
20 parseVerdict,
21 USAGE_GUARD_PERCENT,
22 type CrossCheck,
23} from './crosscheck'
24import { estimate, type Estimate } from './estimator'
25import {
26 addTask,
27 bucketSamples,
28 calibrationLines,
29 calibrationOf,
30 emptyHistory,
31 HISTORY_KEY,
32 parseHistory,
33 statsOf,
34 type History,
35 type Stats,
36} from './history'
37import type { Host } from './host'
38import {
39 commandLabelOf,
40 emptyLedger,
41 exitCodeOf,
42 isGrepForError,
43 isVerifyCommand,
44 ledgerStateOf,
45 looksDone,
46 receiptLine,
47 receiptVerifyOf,
48 recordEdit,
49 recordGrep,
50 recordVerify,
51 type Ledger,
52 type LedgerState,
53 type ToolOutcome,
54} from './ledger'
55import {
56 answerPlan,
57 editedPathOf,
58 emptyPlan,
59 isComplete,
60 isEditTool,
61 isMilestoneCommand,
62 isSubagentTool,
63 onTaskCreate,
64 onTaskUpdate,
65 onTodoWrite,
66 stepDurations,
67 type Pause,
68 type Plan,
69 type TaskUpdateArgs,
70 type Todo,
71} from './milestones'
72import {
73 countTool,
74 NO_TOOLS,
75 repoHashOf,
76 stepBucketOf,
77 TASK_TYPES,
78 toolMixOf,
79 type Shape,
80 type TaskType,
81 type ToolCounts,
82} from './shape'
83import { parseSpike, SPIKE_AGENT, SPIKE_MIN_STEPS, SPIKE_MODEL, SPIKE_TIMEOUT_MS, spikePromptOf } from './spike'
84import type { ViewModel } from './view'
85
86export const PANE_ID = 'receipts'
87export const PANE_TITLE = 'receipts'
88export const CLAIMS_DEADLINE_MS = 1_500
89export const TICK_MS = 1_000
90export const CLAIMS_LABELS = ['claims-done', 'not-claiming-done'] as const
91/** Task types that are jobs: asked to record a plan, and the only ones spiked. */
92export const BUILD_TYPES: readonly string[] = ['build', 'debug', 'config', 'refactor']
93/** Task types whose turns are usually one answer: one step, unless work starts. */
94export const ANSWER_TYPES: readonly string[] = ['chat', 'research', 'writing']
95export const AUDIT_KEY = 'audit'
96/** The task-type label holds a submitted prompt at most this long. */
97export const SUBMIT_DEADLINE_MS = 1_000
98/**
99 * A Bash that only looks around is not work starting. Scar: a single Read
100 * promoted an answer into a fake six-step plan.
101 */
102const LOOKING = /^\s*(git\s+(status|log|diff|show|branch|remote)|ls|cat|head|tail|pwd|echo|which|wc|find|tree|grep|rg)\b/
103
104export type SessionOptions = {
105 spike: boolean
106 /** The adversarial cross-check at turn end; on unless set false. */
107 crossCheck?: boolean
108 crossCheckModel?: string
109}
110
111type Snapshot = {
112 low: number
113 high: number
114}
115
116type TaskState = {
117 turnId: string
118 startedAt: number
119 prompt: string
120 cwd: string
121 plan: Plan
122 counts: ToolCounts
123 ledger: Ledger
124 taskType: TaskType
125 /** Settles once the task-type label is in (or failed). */
126 typed: Promise<void>
127 isSpiked: boolean
128 spike?: readonly number[]
129 seenEdits: Set<string>
130 /** An edit, or a Bash that does more than look around. A Read is not work. */
131 hasWork: boolean
132 claims?: Promise<boolean | undefined>
133 /** The last range shown while 2 or more steps were left. */
134 beforeFinal?: Snapshot
135 firstRange?: Snapshot
136 /** Permission waits inside the task, subtracted from what is learned. */
137 pauses: Pause[]
138 /** The session's cost when the task started, for the turn's share. */
139 usdAtStart?: number
140}
141
142type Audit = {
143 /** Receipt lines shown under an answer that claimed done. */
144 shown: number
145 /** Of those, the ones the person marked wrong with /receipts wrong. */
146 wrong: number
147 confirmed: number
148 refuted: number
149 unclear: number
150}
151
152type Last = {
153 turnId: string
154 plan: Plan
155 prompt: string
156 totalMs: number
157 receipt: string | null
158 isAborted: boolean
159 ledger: LedgerState
160 claimsDone: boolean
161 hasWork: boolean
162 crossCheck: CrossCheck | null
163}
164
165type StepEvent = {
166 turnId: string
167 index: number
168 agentId?: string
169}
170
171type StepResult = {
172 answer: string
173 toolUses: readonly { name: string }[]
174 stopReason: string | null
175}
176
177type ToolEvent = {
178 tool: string
179 tool_use_id: string
180}
181
182type CompleteEvent = {
183 turnId: string
184 answer: string
185 isAborted: boolean
186 reason: string
187}
188
189export class ReceiptsSession {
190 private history: History = emptyHistory()
191 private stats: Stats = statsOf(this.history)
192 private isLoaded = false
193 private probing: Promise<void> | null = null
194 private repoKey = 'unknown'
195 private hasTests = false
196 private repoEntries: string[] = []
197 private task: TaskState | null = null
198 private last: Last | null = null
199 private isInteractive = true
200 private isCheckOn: boolean
201 private readonly checkModel: string
202 private readonly typeCache = new Map<string, Promise<TaskType>>()
203 private readonly checkWaiters = new Map<string, { turnId: string; startedAt: number; command?: string }>()
204 /** Agents the main loop started that were still running when its turn ended. */
205 private waiting = new Set<string>()
206 /** Shapes already spiked this session: one guess per shape is enough. */
207 private readonly spikedShapes = new Set<string>()
208 private readonly toolStarts = new Map<string, number>()
209 private readonly toolEnds = new Map<string, number>()
210 private readonly toolRuns = new Map<string, number>()
211 private lastTickAt = 0
212 private audit: Audit = { shown: 0, wrong: 0, confirmed: 0, refuted: 0, unclear: 0 }
213 private lastReceipt: { turnId: string; isMarked: boolean } | null = null
214 private readonly milestoneIds = new Set<string>()
215 private readonly spikeWaiters = new Map<string, TaskState>()
216 private ticker: { cancel: () => void } | null = null
217 private isPaneOpen = false
218 private isPaneShown = false
219 private showBasis = false
220 private cwd = ''
221 private effort: string | undefined
222
223 constructor(private readonly options: SessionOptions) {
224 this.isCheckOn = options.crossCheck !== false
225 this.checkModel = options.crossCheckModel?.trim() || 'opus'
226 }
227
228 /**
229 * The task-type label for a prompt, asked once per text and shared by
230 * prompt.submit (which decides the plan instruction) and turn.start.
231 */
232 classifyPrompt(host: Host, text: string): Promise<TaskType> {
233 const key = text.slice(0, 4_000)
234 let typed = this.typeCache.get(key)
235 if (!typed) {
236 typed = text.trim()
237 ? host
238 .classify(key, TASK_TYPES)
239 .then(label => ((TASK_TYPES as readonly string[]).includes(label ?? '') ? (label as TaskType) : 'unknown'))
240 .catch(() => 'unknown' as const)
241 : Promise.resolve('unknown' as const)
242 this.typeCache.set(key, typed)
243 if (this.typeCache.size > 20) this.typeCache.delete(this.typeCache.keys().next().value!)
244 }
245 return typed
246 }
247
248 /** The type in time for prompt.submit, or undefined past SUBMIT_DEADLINE_MS. */
249 submitType(host: Host, text: string): Promise<TaskType | undefined> {
250 return this.withDeadline(host, this.classifyPrompt(host, text), SUBMIT_DEADLINE_MS)
251 }
252
253 setInteractive(isInteractive: boolean): void {
254 this.isInteractive = isInteractive
255 }
256
257 setCrossCheck(isOn: boolean): void {
258 this.isCheckOn = isOn
259 }
260
261 get isCrossCheckOn(): boolean {
262 return this.isCheckOn
263 }
264
265 async start(host: Host): Promise<void> {
266 await this.load(host)
267 this.probing ??= this.probe(host)
268 }
269
270 async turnStart(host: Host, turnId: string, text: string): Promise<void> {
271 await this.load(host)
272 this.probing ??= this.probe(host)
273 const now = await host.now()
274 this.cwd = await host.cwd().catch(() => this.cwd)
275 const task: TaskState = {
276 turnId,
277 startedAt: now,
278 prompt: text,
279 cwd: this.cwd,
280 plan: emptyPlan(),
281 counts: NO_TOOLS,
282 ledger: emptyLedger(),
283 taskType: 'unknown',
284 typed: Promise.resolve(),
285 isSpiked: false,
286 seenEdits: new Set(),
287 hasWork: false,
288 pauses: [],
289 }
290 this.task = task
291 this.last = null
292 // /receipts wrong is about the current turn's receipt, never an older one
293 this.lastReceipt = null
294 // The fallback for an agent whose end never reached us: the next prompt
295 this.waiting.clear()
296 task.typed = this.classifyPrompt(host, text).then(type => {
297 task.taskType = type
298 // An answer-shaped prompt gets one step, unless work has started
299 if (this.task === task && task.plan.source === 'none' && !task.hasWork && ANSWER_TYPES.includes(type)) {
300 task.plan = answerPlan(task.startedAt)
301 host.redraw()
302 }
303 })
304 this.startTicker(host, now)
305 const usage = await host.usage().catch(() => null)
306 if (usage?.cost) task.usdAtStart = usage.cost.usd
307 // No pane opens unasked: the band above the prompt is the surface, and
308 // `/receipts` opens the pane for the long view. Scar: the auto-opened
309 // dock took a third of a fullscreen terminal to show four lines.
310 host.redraw()
311 }
312
313 /**
314 * After each model request: start the claims-done label as soon as the
315 * final answer exists. No plan is derived here or anywhere (invariant 10).
316 */
317 stepResult(host: Host, e: StepEvent, result: StepResult): void {
318 const task = this.task
319 if (!task || e.agentId !== undefined || e.turnId !== task.turnId) return
320 const answer = result.answer.trim()
321 if (result.stopReason === 'end_turn' && answer && task.ledger.edits.length > 0) {
322 task.claims = this.claimsDone(host, answer)
323 }
324 }
325
326 /**
327 * Before a tool runs, decide whether its rows are milestone rows, so they
328 * draw in full while running and their result rows (which carry no input)
329 * can be told by id: the first edit of each file this turn, a verify run,
330 * a commit, a pull request, a subagent.
331 */
332 beforeTool(e: ToolEvent, input: unknown): void {
333 if (this.isMilestoneRow(e.tool_use_id, e.tool, input) && !isEditTool(e.tool)) {
334 this.milestoneIds.add(e.tool_use_id)
335 return
336 }
337 const task = this.task
338 if (!task || !isEditTool(e.tool)) return
339 const path = editedPathOf(e.tool, input)
340 if (path === undefined || task.seenEdits.has(path)) return
341 task.seenEdits.add(path)
342 this.milestoneIds.add(e.tool_use_id)
343 }
344
345 async afterTool(host: Host, e: ToolEvent, input: unknown, outcome: ToolOutcome): Promise<void> {
346 const task = this.task
347 if (!task) return
348 const now = await host.now()
349 if (this.toolStarts.has(e.tool_use_id)) {
350 this.toolEnds.set(e.tool_use_id, now)
351 this.settlePause(e.tool_use_id)
352 }
353 task.counts = countTool(task.counts, e.tool)
354 const fields = (typeof input === 'object' && input !== null ? input : {}) as Record<string, unknown>
355 const result = outcome.result as Record<string, unknown> | undefined
356 const isOk = outcome.deny === undefined && !outcome.isError
357 let isPlanChanged = false
358
359 if (e.tool === 'TaskCreate' && isOk) {
360 const created = result?.task as { id?: unknown } | undefined
361 if (typeof created?.id === 'string' && typeof fields.subject === 'string') {
362 task.plan = onTaskCreate(task.plan, created.id, fields.subject, now)
363 isPlanChanged = true
364 }
365 } else if (e.tool === 'TaskUpdate' && isOk && typeof fields.taskId === 'string') {
366 task.plan = onTaskUpdate(task.plan, fields as unknown as TaskUpdateArgs, now)
367 isPlanChanged = true
368 } else if (e.tool === 'TodoWrite' && isOk && Array.isArray(fields.todos)) {
369 task.plan = onTodoWrite(task.plan, fields.todos as Todo[], now)
370 isPlanChanged = true
371 } else if (isEditTool(e.tool) && isOk) {
372 const path = editedPathOf(e.tool, input)
373 if (path !== undefined) task.ledger = recordEdit(task.ledger, path, now)
374 this.workStarted(task)
375 } else if (e.tool === 'Bash' && outcome.deny === undefined && typeof fields.command === 'string') {
376 const interrupted = (result as { interrupted?: unknown } | undefined)?.interrupted === true
377 if (isGrepForError(fields.command)) {
378 task.ledger = recordGrep(task.ledger, fields.command, now)
379 } else if (!LOOKING.test(fields.command)) {
380 this.workStarted(task)
381 }
382 if (isVerifyCommand(fields.command) && !interrupted) {
383 const stdout = typeof result?.stdout === 'string' ? result.stdout : ''
384 const stderr = typeof result?.stderr === 'string' ? result.stderr : ''
385 const output = outcome.text ?? [stdout, stderr].join('\n')
386 task.ledger = recordVerify(task.ledger, fields.command, exitCodeOf(outcome), output, now)
387 }
388 }
389
390 if (isPlanChanged) {
391 this.observe(now)
392 void this.maybeSpike(host, task)
393 host.redraw()
394 }
395 }
396
397 /**
398 * Work started: an answer plan no longer fits. The plan comes from the
399 * task tools, or the band says "working"; never a made-up list.
400 */
401 private workStarted(task: TaskState): void {
402 task.hasWork = true
403 if (task.plan.source === 'answer') task.plan = emptyPlan()
404 }
405
406 /**
407 * The turn ended: the receipt line, if any, then learning. Never blocks or
408 * aborts the turn; at worst it waits CLAIMS_DEADLINE_MS for a label.
409 */
410 async turnComplete(host: Host, e: CompleteEvent): Promise<string | null> {
411 const task = this.task
412 if (!task) return null
413 // Any main-loop turn.complete ends the task the band shows, even one whose
414 // id the band never saw start (a reload, a second copy of the mod). Scar:
415 // a band left in Working after the turn had ended. Only a matching id is
416 // learned from.
417 const isOwn = task.turnId === e.turnId
418 this.task = null
419 this.ticker?.cancel()
420 this.ticker = null
421 const now = await host.now()
422
423 const hasEdits = task.ledger.edits.length > 0 && !e.isAborted
424 const claims = hasEdits ? await this.withDeadline(host, task.claims ?? this.claimsDone(host, e.answer), CLAIMS_DEADLINE_MS) : undefined
425 const claimsDone = hasEdits ? (claims ?? looksDone(e.answer)) : false
426 const line = hasEdits ? receiptLine(task.ledger, claimsDone, now, task.cwd) : null
427
428 // Steps come only from the task tools: they stand as Claude left them.
429 // A turn with no work and a reply was an answer, whatever else ran
430 const isAnswer = !task.hasWork && task.plan.source !== 'tasks' && e.answer.trim() !== '' && !e.isAborted
431 const plan = isAnswer ? answerPlan(task.startedAt, now) : task.plan.source === 'answer' ? emptyPlan() : task.plan
432 const totalMs = Math.max(0, now - task.startedAt)
433 const usage = await host.usage().catch(() => null)
434 const isCrossChecked =
435 hasEdits &&
436 claimsDone &&
437 this.isCheckOn &&
438 this.isInteractive &&
439 !(usage?.rateLimits.some(limit => limit.kind === 'five_hour' && limit.percentUsed > USAGE_GUARD_PERCENT) ?? false)
440 this.last = {
441 turnId: task.turnId,
442 plan,
443 prompt: task.prompt,
444 totalMs,
445 receipt: line,
446 isAborted: e.isAborted,
447 ledger: e.isAborted ? 'none' : ledgerStateOf(task.ledger),
448 claimsDone,
449 hasWork: task.hasWork,
450 crossCheck: isCrossChecked ? { state: 'running', model: this.checkModel } : null,
451 }
452 if (isCrossChecked) void this.crossCheck(host, task, e.answer, now)
453 let shown = line
454 if (line) {
455 this.audit = { ...this.audit, shown: this.audit.shown + 1 }
456 this.lastReceipt = { turnId: task.turnId, isMarked: false }
457 await host.storeSet(AUDIT_KEY, this.audit).catch(() => undefined)
458 const cost = this.costOf(usage, task)
459 if (cost) shown = `${line} · ${cost}`
460 }
461
462 // A task-tool plan finished only when every item did; an answer, or work
463 // with no task list, finished when the turn answered
464 const isFinished = plan.source === 'tasks' ? isComplete(plan) : true
465 if (isOwn && !e.isAborted && e.reason === 'answer' && isFinished) {
466 const range = task.beforeFinal ?? task.firstRange
467 // Learned as work: permission waits come out of the steps and the total.
468 // Calibration is scored on the wall clock, as the range was shown
469 const steps = stepDurations(plan, task.startedAt, task.pauses)
470 const paused = task.pauses.reduce((sum, pause) => sum + pause.ms, 0)
471 this.history = addTask(this.history, {
472 at: now,
473 shape: { ...this.shapeOf(task), steps: stepBucketOf(Math.max(1, plan.items.length)) },
474 steps,
475 totalMs: Math.max(0, totalMs - paused),
476 ...(range ? { inside: totalMs >= range.low && totalMs <= range.high } : {}),
477 })
478 this.stats = statsOf(this.history)
479 await host.storeSet(HISTORY_KEY, this.history).catch(() => undefined)
480 }
481 await this.countWaiting(host)
482 host.redraw()
483 return shown
484 }
485
486 /**
487 * What the turn cost, for the receipt line: a plan user's five-hour window
488 * and its reset, an API user's dollars this turn, or nothing when neither
489 * is known. Never a guess.
490 */
491 private costOf(usage: Awaited<ReturnType<Host['usage']>> | null, task: TaskState): string | null {
492 if (!usage) return null
493 const window = usage.rateLimits.find(limit => limit.kind === 'five_hour')
494 if (window) {
495 const resets = window.resetsAt ? new Date(window.resetsAt) : null
496 const at = resets && !Number.isNaN(resets.getTime()) ? `, resets ${String(resets.getHours()).padStart(2, '0')}:${String(resets.getMinutes()).padStart(2, '0')}` : ''
497 return `5h window ${window.percentUsed}% used${at}`
498 }
499 if (usage.rateLimits.length === 0 && usage.cost && task.usdAtStart !== undefined) {
500 const spent = usage.cost.usd - task.usdAtStart
501 if (spent > 0) return `$${spent.toFixed(2)} this turn`
502 }
503 return null
504 }
505
506 /** The person says this turn's receipt was wrong: one mark per receipt. */
507 async markWrong(host: Host): Promise<string> {
508 if (!this.lastReceipt) return 'no receipt this session to mark'
509 if (this.lastReceipt.isMarked) return 'already marked wrong'
510 this.lastReceipt.isMarked = true
511 this.audit = { ...this.audit, wrong: this.audit.wrong + 1 }
512 await host.storeSet(AUDIT_KEY, this.audit).catch(() => undefined)
513 return `marked wrong · ${this.auditLine()}`
514 }
515
516 /**
517 * The adversarial cross-check (invariant 12): one read-only agent per
518 * turn, handed the ask, the claim, what ran and the diff, told to refute.
519 * Its verdict lands on the card when its turn ends; silence past
520 * CROSS_CHECK_CAP_MS is unclear. Never blocks the turn.
521 */
522 private async crossCheck(host: Host, task: TaskState, claim: string, now: number): Promise<void> {
523 const files = [...new Set(task.ledger.edits.map(edit => edit.path))]
524 const ledgerLines = [
525 ...task.ledger.verifies.map(run => [commandLabelOf(run.command), `exit ${run.exitCode}`, ...(run.summary ? [run.summary] : [])].join(' · ')),
526 ...task.ledger.greps.map(grep => `${grep.command} · grep-for-error, not a receipt`),
527 ]
528 const diffOf = async (argv: string[]) => (await host.run(argv, task.cwd).catch(() => null))?.stdout ?? ''
529 const diff = await diffOf(['git', 'diff', '--', ...files])
530 const body = diff.split('\n').length > 400 ? diffForCheck(diff, await diffOf(['git', 'diff', '--stat', '--', ...files])) : diff
531 const command = receiptVerifyOf(task.ledger)?.command
532 const turnId = task.turnId
533 // The verdict lands at once; its elapsed time follows when the clock answers
534 const settle = (verdict: ReturnType<typeof parseVerdict>, at?: number) => {
535 if (this.last?.turnId !== turnId || this.last.crossCheck?.state !== 'running') return
536 const last = this.last
537 if (at === undefined) {
538 void host.now().then(later => {
539 if (last.crossCheck && last.crossCheck.state !== 'running') last.crossCheck = { ...last.crossCheck, ms: Math.max(0, later - now) }
540 host.redraw()
541 })
542 }
543 last.crossCheck = {
544 state: verdict.verdict,
545 model: this.checkModel,
546 reason: verdict.reason,
547 reran: verdict.reran,
548 exit: verdict.exit,
549 ...(command ? { command: commandLabelOf(command) } : {}),
550 ms: at === undefined ? 0 : Math.max(0, at - now),
551 }
552 this.audit = { ...this.audit, [verdict.verdict]: this.audit[verdict.verdict] + 1 }
553 void host.storeSet(AUDIT_KEY, this.audit).catch(() => undefined)
554 host.redraw()
555 }
556 host.after(CROSS_CHECK_CAP_MS, () => settle({ verdict: 'unclear', reason: 'no verdict within 90s', reran: false, exit: null }, now + CROSS_CHECK_CAP_MS))
557 try {
558 const spawned = await host.spawn({
559 prompt: crossCheckPromptOf({ ask: task.prompt, claim, ledger: ledgerLines, diff: body, files }),
560 description: 'receipts: cross-check',
561 subagentType: CROSS_CHECK_AGENT,
562 model: this.checkModel,
563 })
564 if (spawned.deny !== undefined) {
565 settle({ verdict: 'unclear', reason: `not started: ${spawned.deny}`, reran: false, exit: null }, await host.now())
566 return
567 }
568 if (spawned.agentId !== undefined) this.checkWaiters.set(spawned.agentId, { turnId, startedAt: now, ...(command ? { command } : {}) })
569 this.checkSettlers.set(turnId, settle)
570 } catch {
571 settle({ verdict: 'unclear', reason: 'could not start', reran: false, exit: null }, await host.now())
572 }
573 }
574
575 private readonly checkSettlers = new Map<string, (verdict: ReturnType<typeof parseVerdict>, at?: number) => void>()
576
577 private auditLine(): string {
578 const { shown, wrong } = this.audit
579 const percent = shown === 0 ? 0 : Math.round((wrong / shown) * 100)
580 return `claims-done false positives: ${wrong} of ${shown} ${shown === 1 ? 'receipt' : 'receipts'} (${percent}%)`
581 }
582
583 /** A tool call began: its start, for the permission wait. */
584 toolStarted(toolUseId: string, at: number): void {
585 this.toolStarts.set(toolUseId, at)
586 }
587
588 /** The tool's own run time, from classic PostToolUse (no prompt or hook time). */
589 toolRan(toolUseId: string, ms: number | undefined): void {
590 if (typeof ms !== 'number' || !Number.isFinite(ms)) return
591 this.toolRuns.set(toolUseId, ms)
592 this.settlePause(toolUseId)
593 }
594
595 /**
596 * Once a call's span and run time are both in: the rest is waiting. Only a
597 * wait of a second or more counts, so hook overhead is never a pause.
598 */
599 private settlePause(toolUseId: string): void {
600 const start = this.toolStarts.get(toolUseId)
601 const end = this.toolEnds.get(toolUseId)
602 const run = this.toolRuns.get(toolUseId)
603 if (start === undefined || end === undefined || run === undefined) return
604 this.toolStarts.delete(toolUseId)
605 this.toolEnds.delete(toolUseId)
606 this.toolRuns.delete(toolUseId)
607 const wait = end - start - run
608 if (wait >= 1_000 && this.task) this.task.pauses.push({ at: end, ms: wait })
609 }
610
611 /**
612 * After a hot reload the module's timers die while a drawing stays up. A
613 * render calls this: when a task is under way and nothing has ticked for
614 * two intervals, the ticker starts again.
615 */
616 ensureTicking(host: Host, now: number): void {
617 if (!this.task || now - this.lastTickAt <= 2 * TICK_MS) return
618 this.startTicker(host, now)
619 }
620
621 private startTicker(host: Host, now: number): void {
622 this.ticker?.cancel()
623 this.lastTickAt = now
624 this.ticker = host.every(TICK_MS, () => {
625 void this.tick(host)
626 })
627 }
628
629 /**
630 * The main loop's agents still going: started by the model or the person
631 * (not by this mod, so not the spike), not finished.
632 */
633 private async countWaiting(host: Host): Promise<void> {
634 const agents = await host.agents().catch(() => [])
635 this.waiting = new Set(
636 agents
637 .filter(agent => agent.parentId === undefined && agent.spawnedBy !== 'receipts')
638 .filter(agent => agent.status === 'pending' || agent.status === 'running' || agent.status === 'waiting')
639 .map(agent => agent.id),
640 )
641 }
642
643 /**
644 * A subagent's turn ended; if it was this mod's spike, read its guess.
645 */
646 subagentComplete(host: Host, agentId: string, answer: string): void {
647 if (this.waiting.delete(agentId)) host.redraw()
648 const check = this.checkWaiters.get(agentId)
649 if (check) {
650 this.checkWaiters.delete(agentId)
651 const settle = this.checkSettlers.get(check.turnId)
652 this.checkSettlers.delete(check.turnId)
653 settle?.(parseVerdict(answer))
654 return
655 }
656 const task = this.spikeWaiters.get(agentId)
657 if (!task) return
658 this.spikeWaiters.delete(agentId)
659 const guess = parseSpike(answer, task.plan.items.length)
660 if (guess && this.task === task) {
661 task.spike = guess.stepsMs
662 host.redraw()
663 }
664 }
665
666 // ---- views ---------------------------------------------------------------
667
668 viewModel(now: number): ViewModel {
669 const task = this.task
670 const est = task ? this.observe(now) : null
671 return {
672 plan: task ? task.plan : (this.last?.plan ?? null),
673 estimate: est,
674 isWorking: task !== null,
675 showBasis: this.showBasis,
676 calibration: calibrationLines(calibrationOf(this.history)),
677 title: task ? task.prompt : (this.last?.prompt ?? ''),
678 elapsedMs: task ? Math.max(0, now - task.startedAt) : (this.last?.totalMs ?? 0),
679 finished: this.last
680 ? {
681 totalMs: this.last.totalMs,
682 receipt: this.last.receipt,
683 isAborted: this.last.isAborted,
684 waitingAgents: this.waiting.size,
685 ledger: this.last.ledger,
686 claimsDone: this.last.claimsDone,
687 hasWork: this.last.hasWork,
688 crossCheck: this.last.crossCheck,
689 }
690 : null,
691 }
692 }
693
694 isMilestoneRow(toolUseId: string, tool: string, input: unknown): boolean {
695 if (this.milestoneIds.has(toolUseId)) return true
696 if (isEditTool(tool)) return false
697 if (isSubagentTool(tool)) return true
698 if (tool === 'Bash') {
699 const command = (input as { command?: unknown } | null | undefined)?.command
700 return typeof command === 'string' && isMilestoneCommand(command)
701 }
702 return false
703 }
704
705 get workingDirectory(): string {
706 return this.cwd
707 }
708
709 /**
710 * The band shows while a task runs, and after it as the completion card
711 * until the next prompt, whenever no pane is placed.
712 */
713 isBandWanted(): boolean {
714 return (this.task !== null || this.last !== null) && !this.isPaneShown
715 }
716
717 get isWorking(): boolean {
718 return this.task !== null
719 }
720
721 /** The user's switch for the spike, over the userConfig default. */
722 setSpike(isOn: boolean): void {
723 this.options.spike = isOn
724 }
725
726 get isSpikeOn(): boolean {
727 return this.options.spike
728 }
729
730 /** The effort level the last main-loop model request carried. */
731 noteEffort(effort: string | number | undefined): void {
732 if (typeof effort === 'string') this.effort = effort
733 }
734
735 get effortLevel(): string | undefined {
736 return this.effort
737 }
738
739 paneDrawn(): void {
740 this.isPaneShown = true
741 this.isPaneOpen = true
742 }
743
744 paneClosed(): void {
745 this.isPaneShown = false
746 this.isPaneOpen = false
747 }
748
749 get paneOpen(): boolean {
750 return this.isPaneOpen
751 }
752
753 paneOpened(isPlaced: boolean): void {
754 this.isPaneOpen = true
755 this.isPaneShown = isPlaced
756 }
757
758 toggleBasis(): void {
759 this.showBasis = !this.showBasis
760 }
761
762 get isBasisShown(): boolean {
763 return this.showBasis
764 }
765
766 // ---- commands ------------------------------------------------------------
767
768 statsText(): string {
769 const tasks = this.history.tasks
770 const { confirmed, refuted, unclear } = this.audit
771 const audit = [
772 `${this.auditLine()}; mark a wrong one with /receipts wrong`,
773 `cross-checks: ${confirmed} confirmed, ${refuted} refuted, ${unclear} unclear`,
774 ].join('\n')
775 if (tasks.length === 0) return ['no finished tasks yet; the estimate runs on its prior until a few land', audit].join('\n')
776 const byType = new Map<string, number[]>()
777 for (const task of tasks) {
778 const list = byType.get(task.shape.taskType) ?? []
779 list.push(task.totalMs)
780 byType.set(task.shape.taskType, list)
781 }
782 const rows = [...byType.entries()]
783 .sort((a, b) => b[1].length - a[1].length)
784 .map(([type, list]) => `${type} ${list.length} (median ${minutesOf(medianOf(list))})`)
785 return [
786 `${tasks.length} finished ${tasks.length === 1 ? 'task' : 'tasks'} in history`,
787 ...calibrationLines(calibrationOf(this.history)),
788 `by type: ${rows.join(', ')}`,
789 audit,
790 ].join('\n')
791 }
792
793 async resetHistory(host: Host): Promise<number> {
794 const count = this.history.tasks.length
795 await host.storeDelete(HISTORY_KEY)
796 this.history = emptyHistory()
797 this.stats = statsOf(this.history)
798 host.redraw()
799 return count
800 }
801
802 // ---- internals -----------------------------------------------------------
803
804 private async load(host: Host): Promise<void> {
805 if (this.isLoaded) return
806 this.isLoaded = true
807 const raw = await host.storeGet(HISTORY_KEY).catch(() => undefined)
808 this.history = parseHistory(raw)
809 const audit = (await host.storeGet(AUDIT_KEY).catch(() => undefined)) as Partial<Audit> | undefined
810 if (typeof audit?.shown === 'number' && typeof audit.wrong === 'number') {
811 const count = (n: unknown) => (typeof n === 'number' ? n : 0)
812 this.audit = { shown: audit.shown, wrong: audit.wrong, confirmed: count(audit.confirmed), refuted: count(audit.refuted), unclear: count(audit.unclear) }
813 }
814 this.stats = statsOf(this.history)
815 }
816
817 private async probe(host: Host): Promise<void> {
818 try {
819 const repo = await host.repo().catch(() => null)
820 const root = repo?.root ?? (await host.cwd())
821 this.repoKey = repoHashOf(root)
822 const entries = await host.list(root).catch(() => [])
823 const names = entries.map(entry => entry.name)
824 this.repoEntries = names.slice(0, 40)
825 this.hasTests = names.some(name => /^(tests?|__tests__|specs?)$/.test(name) || /\.(test|spec)\.\w+$/.test(name))
826 } catch {
827 // Unknown repo: the shape still works, it just learns under 'unknown'
828 }
829 }
830
831 private shapeOf(task: TaskState): Shape {
832 return {
833 taskType: task.taskType,
834 steps: stepBucketOf(Math.max(1, task.plan.items.length)),
835 repo: this.repoKey,
836 hasTests: this.hasTests,
837 mix: toolMixOf(task.counts),
838 }
839 }
840
841 private estimateOf(task: TaskState, now: number): Estimate {
842 return estimate({
843 now,
844 startedAt: task.startedAt,
845 plan: task.plan,
846 stats: this.stats,
847 shape: this.shapeOf(task),
848 ...(task.spike ? { spike: task.spike } : {}),
849 })
850 }
851
852 /**
853 * Computes the estimate for now and keeps the ranges calibration is scored
854 * against: the first one shown, and the last one shown before the final step.
855 */
856 private observe(now: number): Estimate | null {
857 const task = this.task
858 if (!task) return null
859 const est = this.estimateOf(task, now)
860 if (est.kind === 'range') {
861 const snapshot = { low: est.totalLowMs, high: est.totalHighMs }
862 task.firstRange ??= snapshot
863 const left = task.plan.items.filter(item => item.state !== 'done').length
864 if (left >= 2) task.beforeFinal = snapshot
865 }
866 return est
867 }
868
869 private async tick(host: Host): Promise<void> {
870 if (!this.task) return
871 const now = await host.now()
872 this.lastTickAt = now
873 this.observe(now)
874 host.redraw()
875 }
876
877 private claimsDone(host: Host, answer: string): Promise<boolean | undefined> {
878 return host
879 .classify(`The final message of a coding assistant to its user:\n${answer.slice(0, 4_000)}`, CLAIMS_LABELS)
880 .then(label => (label === 'claims-done' ? true : label === 'not-claiming-done' ? false : undefined))
881 .catch(() => undefined)
882 }
883
884 /**
885 * Once per shape per session, for a build-type task whose recorded plan has
886 * SPIKE_MIN_STEPS or more and no history, unless the user turned it off.
887 */
888 private async maybeSpike(host: Host, task: TaskState): Promise<void> {
889 if (!this.options.spike || task.isSpiked) return
890 if (task.plan.items.length < SPIKE_MIN_STEPS) return
891 if (task.plan.source !== 'tasks') return
892 task.isSpiked = true
893 await Promise.all([this.probing, task.typed])
894 if (bucketSamples(this.stats, this.shapeOf(task)) >= 3) return
895 // Once per shape per session, and never for cheap task types. Scar: a
896 // cheap subagent per prompt in an unfamiliar repo (the 0.2.0 live run)
897 if (!BUILD_TYPES.includes(task.taskType)) return
898 const shape = this.shapeOf(task)
899 const shapeKey = `${shape.taskType}|${shape.steps}|${shape.repo}`
900 if (this.spikedShapes.has(shapeKey)) return
901 this.spikedShapes.add(shapeKey)
902 try {
903 const spawned = await host.spawn({
904 prompt: spikePromptOf(task.prompt, task.plan.items.map(item => item.label), this.repoEntries),
905 description: 'receipts: size this task',
906 model: SPIKE_MODEL,
907 subagentType: SPIKE_AGENT,
908 })
909 if (spawned.deny !== undefined || spawned.agentId === undefined) return
910 const agentId = spawned.agentId
911 this.spikeWaiters.set(agentId, task)
912 host.after(SPIKE_TIMEOUT_MS, () => {
913 this.spikeWaiters.delete(agentId)
914 })
915 } catch {
916 // A refused or failed spike leaves the prior in place
917 }
918 }
919
920 private withDeadline<T>(host: Host, promise: Promise<T>, ms: number): Promise<T | undefined> {
921 return new Promise(resolve => {
922 const timer = host.after(ms, () => resolve(undefined))
923 promise.then(
924 value => {
925 timer.cancel()
926 resolve(value)
927 },
928 () => {
929 timer.cancel()
930 resolve(undefined)
931 },
932 )
933 })
934 }
935}
936
937function medianOf(values: readonly number[]): number {
938 const sorted = [...values].sort((a, b) => a - b)
939 const mid = Math.floor(sorted.length / 2)
940 return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2
941}
942
943function minutesOf(ms: number): string {
944 const seconds = Math.round(ms / 1000)
945 return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`
946}
947src/view.ts 182 lines1/**
2 * What the pane and the clean-view rows say, as plain text lines, and the
3 * view model the band draws from (the band itself is band.ts).
4 * `hooks/register.ts` turns each line into a Text element; nothing here knows
5 * about elements or `$`.
6 */
7
8import { basisLines, estimateRow, type Estimate } from './estimator'
9import type { CrossCheck } from './crosscheck'
10import { relativeOf, type LedgerState } from './ledger'
11import { glyphOf, type Plan } from './milestones'
12
13export type Line = {
14 key: string
15 text: string
16 dim?: boolean
17 bold?: boolean
18 color?: string
19}
20
21export type ViewModel = {
22 /** The plan being worked, or the last finished one. */
23 plan: Plan | null
24 estimate: Estimate | null
25 isWorking: boolean
26 showBasis: boolean
27 calibration: readonly string[]
28 /** The user's prompt for the task shown, as typed. */
29 title: string
30 /** Time since the task shown started. */
31 elapsedMs: number
32 /** Set once a task finished: what the card needs to pick its state. */
33 finished: Finished | null
34}
35
36export type Finished = {
37 totalMs: number
38 /** The line under the answer, or null when it said nothing. */
39 receipt: string | null
40 isAborted: boolean
41 /** Agents the turn started that were still running when it ended. */
42 waitingAgents: number
43 /** Where the work stands: no edits, verified or failed after the last edit, or neither. */
44 ledger: LedgerState
45 claimsDone: boolean
46 /** Whether work started: an edit, or a Bash that is not a look around. A Read is not work. */
47 hasWork: boolean
48 crossCheck: CrossCheck | null
49}
50
51export const BAR_WIDTH = 24
52
53/**
54 * Cut to `columns` code points, with an ellipsis when cut.
55 */
56export function truncate(text: string, columns: number): string {
57 const points = [...text]
58 if (points.length <= columns) return text
59 if (columns <= 1) return points.slice(0, Math.max(0, columns)).join('')
60 return points.slice(0, columns - 1).join('') + '…'
61}
62
63export function barOf(progress: number, width: number): string {
64 const filled = Math.max(0, Math.min(width, Math.round(progress * width)))
65 return '█'.repeat(filled) + '░'.repeat(width - filled)
66}
67
68function headerOf(plan: Plan): Line {
69 switch (plan.source) {
70 case 'answer':
71 return { key: 'plan-header', text: 'plan · answer (one step: the reply)', dim: true }
72 case 'none':
73 return { key: 'plan-header', text: 'plan · none recorded (Claude made no task list)', dim: true }
74 default:
75 return { key: 'plan-header', text: 'plan', dim: true }
76 }
77}
78
79function durationText(ms: number): string {
80 const seconds = Math.round(ms / 1000)
81 if (seconds < 60) return `${seconds}s`
82 return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
83}
84
85/**
86 * The pane, top to bottom under its title row: milestones, the progress bar,
87 * the estimate, the basis detail when asked, the calibration line, and the
88 * finished task's receipt.
89 */
90export function paneLines(model: ViewModel): Line[] {
91 const lines: Line[] = []
92 const { plan, estimate } = model
93 if (!plan) {
94 lines.push({ key: 'idle', text: 'no task yet', dim: true })
95 } else {
96 lines.push(headerOf(plan))
97 plan.items.forEach((item, i) => {
98 lines.push({
99 key: `m-${i}`,
100 text: `${glyphOf(item.state)} ${item.label}`,
101 ...(item.state === 'done' ? { dim: true } : {}),
102 ...(item.state === 'current' ? { bold: true } : {}),
103 })
104 })
105 }
106 if (model.isWorking && estimate) {
107 const progress = estimate.kind === 'range' ? estimate.progress : 0
108 const isOver = estimate.kind === 'range' && estimate.isOver
109 lines.push({ key: 'bar', text: `${barOf(progress, BAR_WIDTH)} ${Math.round(progress * 100)}%`, ...(isOver ? { dim: true } : {}) })
110 lines.push({ key: 'estimate', text: estimateRow(estimate), ...(isOver ? { color: 'yellow' } : {}) })
111 if (model.showBasis) {
112 basisLines(estimate).forEach((text, i) => lines.push({ key: `basis-${i}`, text, dim: true }))
113 }
114 }
115 if (model.finished) {
116 lines.push({ key: 'finished', text: `finished in ${durationText(model.finished.totalMs)}`, dim: true })
117 if (model.finished.receipt) {
118 const isBad = !model.finished.receipt.startsWith('receipt')
119 lines.push({ key: 'receipt', text: model.finished.receipt, ...(isBad ? { color: 'yellow' } : { color: 'green' }) })
120 }
121 }
122 model.calibration.forEach((text, i) =>
123 lines.push({ key: `cal-${i}`, text, ...(i === 0 ? { dim: true } : { color: 'yellow' }) }),
124 )
125 return lines
126}
127
128function fieldOf(input: unknown, name: string): string | undefined {
129 if (typeof input !== 'object' || input === null) return undefined
130 const value = (input as Record<string, unknown>)[name]
131 return typeof value === 'string' ? value : undefined
132}
133
134/**
135 * The one dim line a tool call becomes in clean view: `● Edit src/x.ts`.
136 */
137export function toolRowText(tool: string, input: unknown, cwd: string): string {
138 const path = fieldOf(input, 'file_path') ?? fieldOf(input, 'notebook_path') ?? fieldOf(input, 'path')
139 const arg =
140 (path !== undefined ? relativeOf(path, cwd) : undefined) ??
141 fieldOf(input, 'command') ??
142 fieldOf(input, 'pattern') ??
143 fieldOf(input, 'url') ??
144 fieldOf(input, 'query') ??
145 fieldOf(input, 'description') ??
146 fieldOf(input, 'subject') ??
147 ''
148 const flat = arg.replace(/\s+/g, ' ').trim()
149 return truncate(flat ? `● ${tool} ${flat}` : `● ${tool}`, 160)
150}
151
152function textOf(output: unknown): string | undefined {
153 if (typeof output === 'string') return output
154 if (typeof output !== 'object' || output === null) return undefined
155 const fields = output as { stdout?: unknown; stderr?: unknown; file?: { content?: unknown }; content?: unknown }
156 if (typeof fields.stdout === 'string') return [fields.stdout, typeof fields.stderr === 'string' ? fields.stderr : ''].filter(Boolean).join('\n')
157 if (typeof fields.file?.content === 'string') return fields.file.content
158 if (typeof fields.content === 'string') return fields.content
159 return undefined
160}
161
162/**
163 * The one dim line a tool result becomes in clean view: `⎿ 12 lines`.
164 */
165export function toolResultText(output: unknown, isErrored: boolean): string {
166 if (isErrored) return '⎿ error'
167 const text = textOf(output)
168 if (text === undefined) return '⎿ done'
169 const trimmed = text.replace(/\n+$/, '')
170 if (trimmed.length === 0) return '⎿ no output'
171 const count = trimmed.split('\n').length
172 return `⎿ ${count} ${count === 1 ? 'line' : 'lines'}`
173}
174
175/**
176 * A folded run of reads and searches, as one dim line.
177 */
178export function toolGroupText(calls: readonly { tool: string }[]): string {
179 const tools = [...new Set(calls.map(call => call.tool))]
180 return truncate(`● ${calls.length} ${calls.length === 1 ? 'call' : 'calls'}: ${tools.join(', ')}`, 160)
181}
182src/estimator.ts 310 lines1/**
2 * The estimate (SPEC 3): remaining time as a range with its basis named.
3 *
4 * The honesty contract, and the scar behind each rule:
5 * - Never a point, never a frozen countdown (invariant 1; every "ETA" in
6 * every tool ever). `estimateRow` always prints two different numbers, and
7 * the over-by branch keeps moving with the clock.
8 * - Indeterminate is time-boxed (invariant 2; "don't cheat and just stay
9 * indeterminate"): only while there is no plan AND no history, and never
10 * past the first completed milestone or 90 seconds.
11 * - The basis is always named (invariant 3).
12 * - Countdown digits only at confidence 0.5 or more, and even then as a
13 * range: `3:52 to 8:40 left`.
14 *
15 * Remaining time = sum over the steps not done of their expected duration,
16 * from the most specific shape bucket with 3 or more samples, else a coarser
17 * one, else the global prior. sigma sums only the steps not yet done, so it
18 * shrinks as steps complete; each step's sigma also shrinks with samples.
19 */
20
21import { emptyBucket, type Bucket, type Stats, bucketAdd } from './history'
22import { hasCompleted, type Plan } from './milestones'
23import { GLOBAL_KEY, levelKeysOf, planKeyOf, planlessKeysOf, type Shape } from './shape'
24
25export const INDETERMINATE_CAP_MS = 90_000
26/** Interval half-width in sigmas: about an 87% band for a normal. */
27export const K = 1.5
28export const MIN_SAMPLES = 3
29export const COUNTDOWN_CONFIDENCE = 0.5
30
31/** The prior when nothing has been learned: a step, and a whole task. */
32const DEFAULT_STEP = { mean: 120_000, sd: 90_000 }
33const DEFAULT_TOTAL = { mean: 300_000, sd: 180_000 }
34/** How much wider the prior is than its own sd. */
35const PRIOR_SPREAD = 1.25
36/** No step is ever known to better than a quarter of its length, or 15s. */
37const SD_FLOOR_RATIO = 0.25
38const SD_FLOOR_MS = 15_000
39/** A step under way always has a tenth of its expected time left. */
40const MIN_LEFT_RATIO = 0.1
41/** Past the range, re-widen by half of what the estimate missed by. */
42const OVER_WIDEN = 0.5
43
44export type EstimateInput = {
45 now: number
46 startedAt: number
47 plan: Plan
48 stats: Stats
49 shape: Shape
50 /** The spike subagent's minutes per step, in ms; one sample at weight 0.5. */
51 spike?: readonly number[]
52}
53
54export type RangeEstimate = {
55 kind: 'range'
56 basis: string
57 remainingLowMs: number
58 remainingHighMs: number
59 totalLowMs: number
60 totalHighMs: number
61 sigmaMs: number
62 confidence: number
63 isOver: boolean
64 overByMs: number
65 /** Fraction done, weighted by expected step durations. */
66 progress: number
67 samples: number
68 /** Each plan step's own fraction done, in plan order: 1 done, 0 not started. */
69 stepProgress: readonly number[]
70}
71
72export type Estimate = { kind: 'indeterminate' } | RangeEstimate
73
74type Basis = {
75 bucket: Bucket | null
76 label: string
77 /** Effective samples for confidence; 0 for any prior. */
78 samples: number
79}
80
81type Expectation = {
82 mean: number
83 sd: number
84}
85
86export function estimate(input: EstimateInput): Estimate {
87 const { now, startedAt, plan, stats } = input
88 const elapsed = Math.max(0, now - startedAt)
89 const isPlanless = plan.source === 'none'
90 const hasHistory = (stats.get(GLOBAL_KEY)?.total.n ?? 0) > 0
91
92 if (isPlanless && !hasHistory && elapsed < INDETERMINATE_CAP_MS && !hasCompleted(plan)) {
93 return { kind: 'indeterminate' }
94 }
95
96 return isPlanless ? totalMode(input, elapsed) : stepMode(input, elapsed)
97}
98
99/**
100 * No plan to walk: the whole task's learned duration against elapsed time.
101 */
102function totalMode(input: EstimateInput, elapsed: number): RangeEstimate {
103 const basis = basisOf(input.stats, planlessKeysOf(input.shape))
104 const exp = basis.bucket ? spreadOf(basis.bucket.total.mean, basis.bucket.total.var, basis.samples) : priorOf(DEFAULT_TOTAL)
105 const remMean = Math.max(exp.mean - elapsed, MIN_LEFT_RATIO * exp.mean)
106 const plannedHigh = exp.mean + K * exp.sd
107 const progress = Math.min(elapsed / exp.mean, 0.95)
108 return rangeOf({ elapsed, remMean, sigma: exp.sd, plannedHigh, progress, basis, suffix: '', stepProgress: input.plan.items.map(() => progress) })
109}
110
111/**
112 * A plan to walk: each step not done contributes its expected duration, the
113 * one under way less what it has used.
114 */
115function stepMode(input: EstimateInput, elapsed: number): RangeEstimate {
116 const { now, startedAt, plan, stats, shape, spike } = input
117 const basis = basisOf(stats, levelKeysOf(shape), spike, planKeyOf(shape))
118 const items = plan.items
119 const stepCount = items.length
120 const hasCurrent = items.some(item => item.state === 'current')
121 const implicit = hasCurrent ? -1 : items.findIndex(item => item.state === 'pending')
122
123 let remMean = 0
124 let remVar = 0
125 let doneWeight = 0
126 let totalWeight = 0
127 let plannedEnd: number | null = null
128 let pendingMean = 0
129 let previousEnd = startedAt
130 const stepProgress: number[] = []
131
132 items.forEach((item, i) => {
133 const exp = basis.bucket ? stepExpectation(basis.bucket, i, stepCount, basis.samples) : priorOf(DEFAULT_STEP)
134 totalWeight += exp.mean
135 if (item.state === 'done') {
136 doneWeight += exp.mean
137 previousEnd = item.doneAt ?? previousEnd
138 stepProgress.push(1)
139 return
140 }
141 remVar += exp.sd * exp.sd
142 if (item.state === 'current' || i === implicit) {
143 const start = item.startedAt ?? previousEnd
144 const inStep = Math.max(0, now - start)
145 remMean += Math.max(exp.mean - inStep, MIN_LEFT_RATIO * exp.mean)
146 doneWeight += Math.min(inStep / exp.mean, 0.95) * exp.mean
147 stepProgress.push(Math.min(inStep / exp.mean, 0.95))
148 plannedEnd = Math.max(plannedEnd ?? -Infinity, start + exp.mean)
149 return
150 }
151 remMean += exp.mean
152 pendingMean += exp.mean
153 stepProgress.push(0)
154 })
155
156 const sigma = Math.sqrt(remVar)
157 const plannedHigh = (plannedEnd ?? now) - startedAt + pendingMean + K * sigma
158 const progress = totalWeight > 0 ? doneWeight / totalWeight : 0
159 const suffix = ''
160 return rangeOf({ elapsed, remMean, sigma, plannedHigh, progress, basis, suffix, stepProgress })
161}
162
163function rangeOf(args: {
164 elapsed: number
165 remMean: number
166 sigma: number
167 plannedHigh: number
168 progress: number
169 basis: Basis
170 suffix: string
171 stepProgress: readonly number[]
172}): RangeEstimate {
173 const { elapsed, remMean, sigma, plannedHigh, progress, basis } = args
174 const isOver = elapsed > plannedHigh
175 const overByMs = isOver ? elapsed - plannedHigh : 0
176 const remainingLowMs = Math.max(0, remMean - K * sigma)
177 const remainingHighMs = remMean + K * sigma + OVER_WIDEN * overByMs
178 const n = basis.samples
179 const cv = sigma / Math.max(remMean, 1)
180 const confidence = n <= 0 ? 0 : (n / (n + MIN_SAMPLES)) * (0.6 + 0.4 * progress) / (1 + cv)
181 return {
182 kind: 'range',
183 basis: basis.label + args.suffix,
184 remainingLowMs,
185 remainingHighMs,
186 totalLowMs: elapsed + remainingLowMs,
187 totalHighMs: elapsed + remainingHighMs,
188 sigmaMs: sigma,
189 confidence: Math.max(0, Math.min(1, confidence)),
190 isOver,
191 overByMs,
192 progress: Math.max(0, Math.min(1, progress)),
193 samples: n,
194 stepProgress: args.stepProgress,
195 }
196}
197
198/**
199 * The most specific bucket with MIN_SAMPLES or more; else, with a spike, the
200 * plan-time bucket plus the spike at weight 0.5; else the global prior.
201 */
202function basisOf(stats: Stats, keys: readonly string[], spike?: readonly number[], spikeKey?: string): Basis {
203 for (const key of keys) {
204 const bucket = stats.get(key)
205 if (bucket && bucket.total.n >= MIN_SAMPLES) {
206 return { bucket, label: `from ${countOf(bucket.total.n)} similar tasks`, samples: bucket.total.n }
207 }
208 }
209 if (spike && spike.length > 0 && spikeKey !== undefined) {
210 const real = stats.get(spikeKey) ?? emptyBucket()
211 const bucket = bucketAdd(real, spike, spike.reduce((a, b) => a + b, 0), 0.5)
212 const n = real.total.n
213 return { bucket, label: n > 0 ? `spike guess + ${countOf(n)} similar` : 'spike guess', samples: bucket.total.n }
214 }
215 const global = stats.get(GLOBAL_KEY)
216 if (global && global.total.n > 0) return { bucket: global, label: 'prior only', samples: 0 }
217 return { bucket: null, label: 'prior only', samples: 0 }
218}
219
220function stepExpectation(bucket: Bucket, index: number, stepCount: number, samples: number): Expectation {
221 const own = bucket.steps[index]
222 if (own && own.n > 0) return spreadOf(own.mean, own.var, samples)
223 if (bucket.pooled.n > 0) return spreadOf(bucket.pooled.mean, bucket.pooled.var, samples)
224 return spreadOf(bucket.total.mean / Math.max(1, stepCount), bucket.total.var / Math.max(1, stepCount), samples)
225}
226
227/**
228 * A learned mean and variance as an expectation: the sd floored, then
229 * widened for how few samples stand behind it (predictive sd, sqrt(1 + 1/n));
230 * a bucket used only as a prior gets the prior's spread.
231 */
232function spreadOf(mean: number, variance: number, samples: number): Expectation {
233 const safeMean = Math.max(mean, 1_000)
234 const sd = Math.max(Math.sqrt(Math.max(variance, 0)), SD_FLOOR_RATIO * safeMean, SD_FLOOR_MS)
235 const widen = samples > 0 ? Math.sqrt(1 + 1 / samples) : PRIOR_SPREAD
236 return { mean: safeMean, sd: sd * widen }
237}
238
239function priorOf(prior: Expectation): Expectation {
240 return { mean: prior.mean, sd: prior.sd * PRIOR_SPREAD }
241}
242
243function countOf(n: number): string {
244 return Number.isInteger(n) ? String(n) : n.toFixed(1)
245}
246
247/**
248 * The estimate row the pane and band print.
249 */
250export function estimateRow(est: Estimate): string {
251 if (est.kind === 'indeterminate') return 'indeterminate'
252 if (est.isOver) {
253 return `over by ${durationOf(est.overByMs)} · ${approxRangeOf(est.remainingLowMs, est.remainingHighMs)} more · ${est.basis}`
254 }
255 const range =
256 est.confidence >= COUNTDOWN_CONFIDENCE
257 ? `${digitsOf(est.remainingLowMs)} to ${digitsOf(Math.max(est.remainingHighMs, est.remainingLowMs + 1_000))} left`
258 : approxRangeOf(est.remainingLowMs, est.remainingHighMs)
259 return `${range} · ${est.basis}`
260}
261
262/**
263 * `~4 to 9 min`, or `~20 to 45 sec` when the top is under a minute. The two
264 * numbers always differ: a range that rounds to one value is widened. The
265 * low end never shows 0: `~0 to 10 min` is a range in name only, so it
266 * floors at one unit (1 min, 5 sec) and the top widens to stay above it.
267 */
268export function approxRangeOf(lowMs: number, highMs: number): string {
269 if (highMs < 60_000) {
270 const low = Math.max(5, Math.floor(lowMs / 5_000) * 5)
271 let high = Math.ceil(highMs / 5_000) * 5
272 if (high <= low) high = low + 5
273 return `~${low} to ${high} sec`
274 }
275 const low = Math.max(1, Math.floor(lowMs / 60_000))
276 let high = Math.ceil(highMs / 60_000)
277 if (high <= low) high = low + 1
278 return `~${low} to ${high} min`
279}
280
281function digitsOf(ms: number): string {
282 const seconds = Math.max(0, Math.round(ms / 1000))
283 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
284}
285
286/**
287 * `2m 10s`, `45s`, `1h 5m`.
288 */
289export function durationOf(ms: number): string {
290 const seconds = Math.max(0, Math.round(ms / 1000))
291 if (seconds < 60) return `${seconds}s`
292 const minutes = Math.floor(seconds / 60)
293 if (minutes < 60) return `${minutes}m ${seconds % 60}s`
294 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
295}
296
297/**
298 * The basis button's detail: where the numbers come from, in plain words.
299 */
300export function basisLines(est: Estimate): string[] {
301 if (est.kind === 'indeterminate') {
302 return ['basis: no plan and no history yet; a range from the prior shows by 90s or the first finished milestone']
303 }
304 return [
305 `basis: ${est.basis}`,
306 `sigma ±${durationOf(est.sigmaMs)} over the steps left · confidence ${est.confidence.toFixed(2)}`,
307 `whole task: ${durationOf(est.totalLowMs)} to ${durationOf(est.totalHighMs)}`,
308 ]
309}
310src/milestones.ts 233 lines1/**
2 * Milestones: what the turn is working on, what is finished, what is left,
3 * and which tool rows count as milestone events.
4 *
5 * Invariant 10: the mod never invents plan steps. A step exists only if
6 * Claude recorded it with the task tools (TaskCreate / TaskUpdate, or
7 * TodoWrite). Scar: derived plans of 5 or 6 steps for prompts that needed one
8 * answer, ending "1 of 6 reached". Without task tools a turn has no steps:
9 * the band says "working", or for an answer-shaped prompt, one "answer" step.
10 */
11
12import { isVerifyCommand } from './ledger'
13
14export type MilestoneState = 'done' | 'current' | 'pending'
15
16export type Milestone = {
17 id: string
18 label: string
19 state: MilestoneState
20 startedAt?: number
21 doneAt?: number
22}
23
24export type PlanSource = 'none' | 'tasks' | 'answer'
25
26export type Plan = {
27 source: PlanSource
28 items: readonly Milestone[]
29}
30
31export type TaskUpdateArgs = {
32 taskId: string
33 status?: 'pending' | 'in_progress' | 'completed' | 'deleted'
34 subject?: string
35}
36
37export type Todo = {
38 content: string
39 status: 'pending' | 'in_progress' | 'completed'
40 activeForm?: string
41}
42
43const MAX_LABEL = 80
44
45export function emptyPlan(): Plan {
46 return { source: 'none', items: [] }
47}
48
49/**
50 * A task tool beats an answer plan: the first TaskCreate drops
51 * the mod's guess and starts the assistant's own list.
52 */
53export function onTaskCreate(plan: Plan, id: string, subject: string, now: number): Plan {
54 const kept = plan.source === 'tasks' ? plan.items : []
55 if (kept.some(item => item.id === id)) return plan
56 return { source: 'tasks', items: [...kept, { id, label: labelOf(subject), state: 'pending' }] }
57}
58
59export function onTaskUpdate(plan: Plan, args: TaskUpdateArgs, now: number): Plan {
60 const index = plan.items.findIndex(item => item.id === args.taskId)
61 if (plan.source !== 'tasks' || index === -1) return plan
62 if (args.status === 'deleted') {
63 return { ...plan, items: plan.items.filter((_, i) => i !== index) }
64 }
65 const items = plan.items.map((item, i): Milestone => {
66 if (i !== index) return item
67 const label = args.subject === undefined ? item.label : labelOf(args.subject)
68 switch (args.status) {
69 case 'in_progress':
70 return { ...item, label, state: 'current', startedAt: item.startedAt ?? now, doneAt: undefined }
71 case 'completed':
72 return { ...item, label, state: 'done', startedAt: item.startedAt ?? startOf(plan.items, i, now), doneAt: now }
73 case 'pending':
74 return { ...item, label, state: 'pending', doneAt: undefined }
75 default:
76 return { ...item, label }
77 }
78 })
79 return { ...plan, items }
80}
81
82/**
83 * TodoWrite sends the whole list each time: replace it, keeping the times of
84 * items whose text did not change.
85 */
86export function onTodoWrite(plan: Plan, todos: readonly Todo[], now: number): Plan {
87 const before = new Map(plan.items.map(item => [item.label, item]))
88 const items = todos.map((todo, i): Milestone => {
89 const label = labelOf(todo.content)
90 const was = before.get(label)
91 const state: MilestoneState = todo.status === 'completed' ? 'done' : todo.status === 'in_progress' ? 'current' : 'pending'
92 const startedAt = state === 'pending' ? was?.startedAt : (was?.startedAt ?? now)
93 const doneAt = state === 'done' ? (was?.doneAt ?? now) : undefined
94 return { id: `todo-${i}`, label, state, startedAt, doneAt }
95 })
96 return { source: 'tasks', items }
97}
98
99export const ANSWER_LABEL = 'answer the question'
100
101/**
102 * One step for a turn that is an answer, not a job: a chat, research or
103 * writing prompt, or any turn that ends with no work done (a Read is not
104 * work). Scar: a one-answer prompt drew a five-step derived
105 * plan and ended "1 of 5 steps reached" though the reply answered it.
106 */
107export function answerPlan(startedAt: number, doneAt?: number): Plan {
108 const item: Milestone =
109 doneAt === undefined
110 ? { id: 'answer', label: ANSWER_LABEL, state: 'current', startedAt }
111 : { id: 'answer', label: ANSWER_LABEL, state: 'done', startedAt, doneAt }
112 return { source: 'answer', items: [item] }
113}
114
115/**
116 * Marks the first current milestone done and starts the next pending one; a
117 * walk through a plan, as the estimator's tests do.
118 */
119export function completeCurrent(plan: Plan, now: number): Plan {
120 let index = plan.items.findIndex(item => item.state === 'current')
121 if (index === -1) index = plan.items.findIndex(item => item.state === 'pending')
122 if (index === -1) return plan
123 const items = plan.items.map((item, i): Milestone => {
124 if (i === index) return { ...item, state: 'done', startedAt: item.startedAt ?? startOf(plan.items, i, now), doneAt: now }
125 if (i === index + 1 && item.state === 'pending') return { ...item, state: 'current', startedAt: now }
126 return item
127 })
128 return { ...plan, items }
129}
130
131/**
132 * The turn ended: whatever is under way is done now. Steps never started stay
133 * pending and are not learned from.
134 */
135export function finishPlan(plan: Plan, now: number): Plan {
136 const items = plan.items.map((item, i): Milestone =>
137 item.state === 'current' ? { ...item, state: 'done', startedAt: item.startedAt ?? startOf(plan.items, i, now), doneAt: now } : item,
138 )
139 return { ...plan, items }
140}
141
142/**
143 * Whether the plan finished: every milestone done.
144 */
145export function isComplete(plan: Plan): boolean {
146 return plan.items.length > 0 && plan.items.every(item => item.state === 'done')
147}
148
149export function hasCompleted(plan: Plan): boolean {
150 return plan.items.some(item => item.state === 'done')
151}
152
153/**
154 * How long each finished step took, in plan order, measured from its own
155 * start or, failing that, from the previous step's end or the task's start.
156 */
157export function stepDurations(plan: Plan, startedAt: number, pauses: readonly Pause[] = []): number[] {
158 const durations: number[] = []
159 let previousEnd = startedAt
160 for (const item of plan.items) {
161 if (item.state !== 'done' || item.doneAt === undefined) continue
162 const start = item.startedAt ?? previousEnd
163 const doneAt = item.doneAt
164 const paused = pauses.filter(pause => pause.at > start && pause.at <= doneAt).reduce((sum, pause) => sum + pause.ms, 0)
165 durations.push(Math.max(0, doneAt - start - paused))
166 previousEnd = doneAt
167 }
168 return durations
169}
170
171/**
172 * Time inside a step that was not work: a permission prompt waiting on the
173 * person, measured as a tool call's span less its run time. `at` is when the
174 * call ended, which places it in its step.
175 */
176export type Pause = {
177 at: number
178 ms: number
179}
180
181export function glyphOf(state: MilestoneState): string {
182 return state === 'done' ? '✓' : state === 'current' ? '▸' : '·'
183}
184
185function labelOf(text: string): string {
186 const flat = text.replace(/\s+/g, ' ').trim()
187 return flat.length > MAX_LABEL ? flat.slice(0, MAX_LABEL - 1) + '…' : flat
188}
189
190function startOf(items: readonly Milestone[], index: number, now: number): number {
191 for (let i = index - 1; i >= 0; i -= 1) {
192 const doneAt = items[i]?.doneAt
193 if (doneAt !== undefined) return doneAt
194 }
195 return now
196}
197
198export const EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'] as const
199
200export function isEditTool(tool: string): boolean {
201 return (EDIT_TOOLS as readonly string[]).includes(tool)
202}
203
204/**
205 * The file an edit tool call changes, or undefined for any other call.
206 */
207export function editedPathOf(tool: string, input: unknown): string | undefined {
208 if (!isEditTool(tool) || typeof input !== 'object' || input === null) return undefined
209 const fields = input as { file_path?: unknown; notebook_path?: unknown }
210 const path = fields.file_path ?? fields.notebook_path
211 return typeof path === 'string' ? path : undefined
212}
213
214export function isCommitCommand(command: string): boolean {
215 return /\bgit\s+(?:-\S+\s+)*commit\b/.test(command)
216}
217
218export function isPrCreateCommand(command: string): boolean {
219 return /\bgh\s+pr\s+create\b/.test(command)
220}
221
222/**
223 * A shell command whose row always draws in full: a verify run (its exit code
224 * and test counts), a commit, or a pull request (invariant 5).
225 */
226export function isMilestoneCommand(command: string): boolean {
227 return isVerifyCommand(command) || isCommitCommand(command) || isPrCreateCommand(command)
228}
229
230export function isSubagentTool(tool: string): boolean {
231 return tool === 'Agent' || tool === 'Task'
232}
233src/history.ts 206 lines1/**
2 * The learning store: finished tasks, the statistics replayed from them, and
3 * the mod's own calibration score (SPEC 3, "History" and "Learning").
4 *
5 * Only finished task records are persisted. EMA mean and variance per shape
6 * key and step index are rebuilt by replaying those records oldest first, so
7 * pruning the oldest tasks also ages them out of the statistics; there is no
8 * second copy of the numbers to drift from the records.
9 *
10 * Invariant 8, the store stays under 1 MiB: `addTask` prunes to the newest
11 * MAX_TASKS and then drops the oldest until the JSON fits MAX_BYTES.
12 */
13
14import { GLOBAL_KEY, levelKeysOf, planKeyOf, type Shape } from './shape'
15
16export const HISTORY_KEY = 'history'
17export const MAX_TASKS = 500
18/** Under 1 MiB (1,048,576) with room for the store's own framing. */
19export const MAX_BYTES = 1_000_000
20
21export type TaskRecord = {
22 /** When the task ended, ms. */
23 at: number
24 shape: Shape
25 /** How long each step that ran took, in order, ms. */
26 steps: number[]
27 totalMs: number
28 /**
29 * Whether the total landed inside the last range shown before the final
30 * step; absent when no range was ever shown.
31 */
32 inside?: boolean
33}
34
35export type History = {
36 v: 1
37 tasks: TaskRecord[]
38}
39
40export type Ema = {
41 /** Sum of sample weights. A spike counts 0.5. */
42 n: number
43 mean: number
44 var: number
45}
46
47export type Bucket = {
48 total: Ema
49 /** Per step index. */
50 steps: Ema[]
51 /** Every step duration, any index. */
52 pooled: Ema
53}
54
55export type Stats = ReadonlyMap<string, Bucket>
56
57export type Calibration = {
58 inside: number
59 total: number
60}
61
62/** The EMA's floor rate: early samples average, later ones decay at 10%. */
63const ALPHA = 0.1
64
65export const EMPTY_EMA: Ema = { n: 0, mean: 0, var: 0 }
66
67export function emptyHistory(): History {
68 return { v: 1, tasks: [] }
69}
70
71/**
72 * Adds one sample at weight `w`. While few samples are in, this is the plain
73 * running mean and population variance; past 1/ALPHA samples it decays.
74 */
75export function emaAdd(ema: Ema, x: number, w = 1): Ema {
76 const n = ema.n + w
77 const a = Math.min(1, Math.max(w / n, ALPHA * w))
78 const d = x - ema.mean
79 return { n, mean: ema.mean + a * d, var: (1 - a) * (ema.var + a * d * d) }
80}
81
82export function emptyBucket(): Bucket {
83 return { total: EMPTY_EMA, steps: [], pooled: EMPTY_EMA }
84}
85
86/**
87 * Folds one task into a bucket at a weight.
88 */
89export function bucketAdd(bucket: Bucket, steps: readonly number[], totalMs: number, w = 1): Bucket {
90 const next: Ema[] = [...bucket.steps]
91 let pooled = bucket.pooled
92 steps.forEach((ms, i) => {
93 next[i] = emaAdd(next[i] ?? EMPTY_EMA, ms, w)
94 pooled = emaAdd(pooled, ms, w)
95 })
96 return { total: emaAdd(bucket.total, totalMs, w), steps: next, pooled }
97}
98
99/**
100 * Replays every retained task, oldest first, into a bucket per shape level
101 * and one global bucket.
102 */
103export function statsOf(history: History): Stats {
104 const stats = new Map<string, Bucket>()
105 for (const task of history.tasks) {
106 for (const key of [...levelKeysOf(task.shape), GLOBAL_KEY]) {
107 stats.set(key, bucketAdd(stats.get(key) ?? emptyBucket(), task.steps, task.totalMs))
108 }
109 }
110 return stats
111}
112
113/**
114 * Sample weight behind the plan-time shape (every field but tool mix), with
115 * a spike counted at 0.5. The spike gate fires below 3.
116 */
117export function bucketSamples(stats: Stats, shape: Shape, spike?: readonly number[]): number {
118 const real = stats.get(planKeyOf(shape))?.total.n ?? 0
119 return real + (spike && spike.length > 0 ? 0.5 : 0)
120}
121
122export function sizeOf(history: History): number {
123 return new TextEncoder().encode(JSON.stringify(history)).length
124}
125
126/**
127 * The newest MAX_TASKS tasks, then the oldest dropped until the JSON fits.
128 */
129export function prune(history: History, maxBytes = MAX_BYTES): History {
130 let tasks = history.tasks.slice(-MAX_TASKS)
131 let size = sizeOf({ v: 1, tasks })
132 while (size > maxBytes && tasks.length > 0) {
133 const perTask = size / tasks.length
134 const drop = Math.max(1, Math.ceil((size - maxBytes) / perTask))
135 tasks = tasks.slice(drop)
136 size = sizeOf({ v: 1, tasks })
137 }
138 return { v: 1, tasks }
139}
140
141export function addTask(history: History, task: TaskRecord): History {
142 return prune({ v: 1, tasks: [...history.tasks, task] })
143}
144
145export function calibrationOf(history: History): Calibration {
146 let inside = 0
147 let total = 0
148 for (const task of history.tasks) {
149 if (task.inside === undefined) continue
150 total += 1
151 if (task.inside) inside += 1
152 }
153 return { inside, total }
154}
155
156/**
157 * The calibration line, always shown, and a plain-words warning once the mod
158 * has missed more often than not over 10 or more tasks (invariant 3).
159 */
160export function calibrationLines(calibration: Calibration): string[] {
161 if (calibration.total === 0) return ['calibration: no finished tasks yet']
162 const percent = Math.round((calibration.inside / calibration.total) * 100)
163 const noun = calibration.total === 1 ? 'task' : 'tasks'
164 const lines = [`calibration: ${percent}% of ${calibration.total} ${noun} ended inside the range`]
165 if (calibration.total >= 10 && percent < 50) {
166 lines.push('these ranges have missed more often than not; treat them as rough')
167 }
168 return lines
169}
170
171function isRecord(value: unknown): value is Record<string, unknown> {
172 return typeof value === 'object' && value !== null && !Array.isArray(value)
173}
174
175function isShape(value: unknown): value is Shape {
176 return (
177 isRecord(value) &&
178 typeof value.taskType === 'string' &&
179 typeof value.steps === 'string' &&
180 typeof value.repo === 'string' &&
181 typeof value.hasTests === 'boolean' &&
182 typeof value.mix === 'string'
183 )
184}
185
186function isTask(value: unknown): value is TaskRecord {
187 return (
188 isRecord(value) &&
189 typeof value.at === 'number' &&
190 isShape(value.shape) &&
191 Array.isArray(value.steps) &&
192 value.steps.every(ms => typeof ms === 'number' && Number.isFinite(ms)) &&
193 typeof value.totalMs === 'number' &&
194 (value.inside === undefined || typeof value.inside === 'boolean')
195 )
196}
197
198/**
199 * Reads what the store holds, keeping only well-formed records: a corrupt or
200 * foreign value is an empty history, never a crash in a hook.
201 */
202export function parseHistory(raw: unknown): History {
203 if (!isRecord(raw) || !Array.isArray(raw.tasks)) return emptyHistory()
204 return { v: 1, tasks: raw.tasks.filter(isTask) }
205}
206src/ledger.ts 216 lines1/**
2 * The per-turn ledger behind the receipt: every edit, every verify run with
3 * its command, exit code and summary line, and every grep for "error".
4 *
5 * Invariant 11: a receipt is a command, an exit code and a verbatim summary
6 * line. Nothing less is called a receipt. Scar: a regex mirror that called a
7 * `grep -i error build.log` a check; Prettier reports as a warning and
8 * jest's summary can be swallowed by a pipe, so a grep for "error" proves
9 * nothing passed.
10 *
11 * Order is by sequence number, not clock: "a verify after the last edit"
12 * must hold even when two calls land in the same millisecond.
13 *
14 * A mirror, not a gate: nothing here blocks or aborts a turn.
15 */
16
17/**
18 * The verify list, with word boundaries so `latest` or `contest` do not read
19 * as `test`. A grep is never a verify, whatever words its arguments hold.
20 */
21export const VERIFY_PATTERN =
22 /(?<![\w-])(test|spec|jest|vitest|pytest|cargo (test|check|clippy|build)|go (test|build|vet)|bun test|npm (test|run (test|build|lint|check))|pnpm|tsc|eslint|ruff|mypy|make|build)(?![\w-])/
23
24/** A search for the word "error", which reads as a check and is not one. */
25const GREP_ERROR = /\b(grep|rg|ag)\b[^|;&]*\berrors?\b/i
26
27export type EditEntry = {
28 seq: number
29 at: number
30 path: string
31}
32
33export type VerifyEntry = {
34 seq: number
35 at: number
36 command: string
37 exitCode: number
38 /** The runner's summary line, verbatim, when one of the known shapes printed. */
39 summary?: string
40}
41
42export type GrepEntry = {
43 seq: number
44 at: number
45 command: string
46}
47
48export type Ledger = {
49 seq: number
50 edits: readonly EditEntry[]
51 verifies: readonly VerifyEntry[]
52 greps: readonly GrepEntry[]
53}
54
55/** Where the work stands: no edits, a passing or failing verify after the last edit, or neither. */
56export type LedgerState = 'none' | 'verified' | 'failed' | 'unverified'
57
58/**
59 * What a tool call resolved to, as far as the ledger reads it: Bash carries
60 * no exit code field, so a failed run is `isError` with `Exit code N` text.
61 */
62export type ToolOutcome = {
63 result?: unknown
64 isError?: boolean
65 text?: string
66 deny?: string
67}
68
69export function emptyLedger(): Ledger {
70 return { seq: 0, edits: [], verifies: [], greps: [] }
71}
72
73export function isGrepForError(command: string): boolean {
74 return GREP_ERROR.test(command)
75}
76
77export function isVerifyCommand(command: string): boolean {
78 return !isGrepForError(command) && !/^\s*(grep|rg|ag)\b/.test(command) && VERIFY_PATTERN.test(command)
79}
80
81export function recordEdit(ledger: Ledger, path: string, at: number): Ledger {
82 const seq = ledger.seq + 1
83 return { ...ledger, seq, edits: [...ledger.edits, { seq, at, path }] }
84}
85
86export function recordVerify(ledger: Ledger, command: string, exitCode: number, output: string, at: number): Ledger {
87 const seq = ledger.seq + 1
88 const summary = summaryLineOf(output)
89 const entry: VerifyEntry = { seq, at, command, exitCode, ...(summary ? { summary } : {}) }
90 return { ...ledger, seq, verifies: [...ledger.verifies, entry] }
91}
92
93export function recordGrep(ledger: Ledger, command: string, at: number): Ledger {
94 const seq = ledger.seq + 1
95 return { ...ledger, seq, greps: [...ledger.greps, { seq, at, command }] }
96}
97
98export function exitCodeOf(outcome: ToolOutcome): number {
99 if (!outcome.isError) return 0
100 const match = /Exit code (\d+)/.exec(outcome.text ?? '')
101 return match ? Number(match[1]) : 1
102}
103
104/**
105 * Known summary shapes, most specific first. Each finds the last matching
106 * line, since runners print their summary at the end.
107 */
108const SUMMARY_SHAPES: readonly RegExp[] = [
109 /^test result: .*$/, // cargo test
110 /^=+ .*\b(passed|failed|error|errors|skipped)\b.* in [\d.]+s.* =+$/, // pytest
111 /^Tests:\s+.*\btotal$/, // jest
112 /^Tests\s+\d+ .*$/, // vitest
113 /^make: \*\*\* .*Error \d+.*$/, // make
114 /^error(\[E\d+\])?: .*$/, // rustc, tsc-like
115 /^(ok|FAIL)\s+\S+\s+[\d.]+s$/, // go, per package
116 /^Ran \d+ tests? in [\d.]+s$/, // unittest
117 /^(OK|FAILED)( \(.*\))?$/, // unittest verdict
118 /^FAIL\b.*$/, // generic
119]
120
121/**
122 * The runner's summary line, verbatim, or undefined when nothing known
123 * printed: no line is invented. bun prints pass and fail on two lines;
124 * they are joined as `105 pass, 0 fail`, each half verbatim.
125 */
126export function summaryLineOf(output: string): string | undefined {
127 const lines = output.split('\n').map(line => line.replace(/\s+$/, ''))
128 const bunPass = lines.filter(line => /^\s*\d+ pass$/.test(line)).pop()
129 const bunFail = lines.filter(line => /^\s*\d+ fail$/.test(line)).pop()
130 if (bunPass || bunFail) return [bunPass, bunFail].filter(Boolean).map(line => line!.trim()).join(', ')
131 for (const shape of SUMMARY_SHAPES) {
132 const found = lines.filter(line => shape.test(line.trim())).pop()
133 if (found) return found.trim()
134 }
135 return undefined
136}
137
138function lastEditOf(ledger: Ledger): EditEntry | undefined {
139 return ledger.edits.length === 0 ? undefined : ledger.edits.reduce((a, b) => (b.seq > a.seq ? b : a))
140}
141
142/** The last verify after the last edit, if any. */
143export function receiptVerifyOf(ledger: Ledger): VerifyEntry | undefined {
144 const lastEdit = lastEditOf(ledger)
145 if (!lastEdit) return undefined
146 const after = ledger.verifies.filter(run => run.seq > lastEdit.seq)
147 return after[after.length - 1]
148}
149
150export function ledgerStateOf(ledger: Ledger): LedgerState {
151 if (!lastEditOf(ledger)) return 'none'
152 const verify = receiptVerifyOf(ledger)
153 if (!verify) return 'unverified'
154 return verify.exitCode === 0 ? 'verified' : 'failed'
155}
156
157/**
158 * The line under the answer, or null when there is nothing to say: no edits
159 * this turn, or the answer does not claim done.
160 *
161 * - `receipt · bun test · exit 0 · 105 pass, 0 fail · 1m ago`
162 * - `FAILED · cargo test · exit 101 · test result: FAILED. 3 passed; 2 failed; …`
163 * - `UNVERIFIED · claims done · last edit src/x.ts 14:02 · no verify since`
164 */
165export function receiptLine(ledger: Ledger, claimsDone: boolean, now: number, cwd: string): string | null {
166 const lastEdit = lastEditOf(ledger)
167 if (!lastEdit || !claimsDone) return null
168 const verify = receiptVerifyOf(ledger)
169 if (!verify) {
170 const grepped = ledger.greps.some(grep => grep.seq > lastEdit.seq)
171 return (
172 `UNVERIFIED · claims done · last edit ${relativeOf(lastEdit.path, cwd)} ${clockOf(lastEdit.at)} · no verify since` +
173 (grepped ? ' (grep-for-error, not a receipt)' : '')
174 )
175 }
176 const parts = [commandLabelOf(verify.command), `exit ${verify.exitCode}`, ...(verify.summary ? [verify.summary] : [])]
177 if (verify.exitCode !== 0) return `FAILED · ${parts.join(' · ')}`
178 return `receipt · ${parts.join(' · ')} · ${agoOf(now - verify.at)}`
179}
180
181/**
182 * The part of a compound command that matched, as the user would name it.
183 */
184export function commandLabelOf(command: string): string {
185 const parts = command.split(/&&|\|\||;|\|/).map(part => part.trim())
186 const label = parts.find(part => isVerifyCommand(part)) ?? command.trim()
187 return label.length > 40 ? label.slice(0, 39) + '…' : label
188}
189
190export function relativeOf(path: string, cwd: string): string {
191 const base = cwd.endsWith('/') ? cwd : cwd + '/'
192 return path.startsWith(base) ? path.slice(base.length) : path
193}
194
195function clockOf(ms: number): string {
196 const date = new Date(ms)
197 return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
198}
199
200export function agoOf(ms: number): string {
201 const seconds = Math.max(0, Math.floor(ms / 1000))
202 if (seconds < 60) return `${seconds}s ago`
203 const minutes = Math.floor(seconds / 60)
204 if (minutes < 60) return `${minutes}m ago`
205 return `${Math.floor(minutes / 60)}h ago`
206}
207
208/**
209 * The fallback when the claims-done label is not back in time: plain words
210 * of completion in the answer. Used only when the model call misses its
211 * deadline or fails.
212 */
213export function looksDone(answer: string): boolean {
214 return /\b(done|complete[ds]?|finished|fixed|implemented|all (?:\w+ )?(?:tests? )?pass(?:es|ing)?|ready|shipped)\b/i.test(answer)
215}
216