Spec-driven development for Claude Code, layered on OpenSpec. You read one spec; parallel agents ship it to a tested commit.

Spec-driven development for Claude Code. You read one spec; parallel agents ship it to a tested commit.
<img src="docs/assets/spec-and-ship.gif" alt="One real run, 34 seconds: /interlock:spec asks one question, writes the change and stops at the checkpoint; /interlock:ship runs two waves of parallel agents, the suite passes 180 of 180, one commit." width="838">
/interlock:spec "<idea>" # explores your repo, writes a reviewed spec, then stops
# ← you read it. The only place a human is required.
/interlock:ship # parallel agents implement → your tests pass → commit. Nobody is asked.
ship is a Claude Code workflow, and the workflow runtime has no channel for mid-run input. It cannot ask you anything, so it never does.Interlock is a Claude Code plugin layered on OpenSpec, which owns the spec format. You need:
| Claude Code v2.1.154+ with dynamic workflows enabled | /interlock:ship runs as a workflow. If workflows are turned off, by your settings, an org policy or a Pro plan that has not enabled them in /config, the command exists but the run cannot start |
| Node.js 20.19+ | OpenSpec needs 20.19+. Interlock's own CLIs need only 18 |
| A git repository with code in it | Bootstrap describes what already exists |
The full table, including two environment variables that must stay unset, is in the first hour.
1. Install the OpenSpec CLI. In your terminal, once per machine:
npm install -g @fission-ai/openspec@latest
openspec --version # prints a version when it worked
2. Install the plugin. In Claude Code, once per machine:
/plugin marketplace add renzrollon/interlock
/plugin install interlock@interlock
3. Onboard your project. Start a new session in the project from your terminal (cd your-project && claude), then in Claude Code, once per repo:
/interlock:bootstrap
Bootstrap runs openspec init if the repo has never been initialized. It reads your code, asks you to confirm the list of features it found, then writes one spec per feature describing what the code does today, and builds the graph agents navigate by. It never changes source code.
4. Read the first line of each session. Every time a session starts in your project, the plugin checks that an unattended run could finish and prints either interlock preflight OK or a list of problems, each with its fix. The most common problem is a command your permission settings do not allow yet. During ship nobody is there to approve a prompt, so the run would stop at it. /permissions is the quickest way to add what the check names.
interlock doctoris optional. The session-start check isinterlock doctor, run for you. Run it yourself only for the full report, which includes a ready-to-paste settings snippet that allowlists every command a run needs:! interlock doctorThe
!runs it from the Claude Code prompt, because the plugin puts the CLI on thePATHof Claude Code's shell, not your own terminal's. For your terminal too, install the npm package (07), and keep that copy at the plugin's version:doctorsays when it is not (16). It exits 1 when it finds something that would stop a zero-touch run.
Your first shipped change, step by step: 01 — The first hour.
<a href="https://renzrollon.github.io/interlock/#flow"> <img src="docs/assets/flow-light.svg" alt="The Interlock flow: bootstrap once per repo; for every change, spec, then you read the spec, then ship; when you want them, settle and archive. Two commands, one human checkpoint." width="1120"> </a>
You type two commands for every change and read the spec between them. The rest is there when you want it.
| When | Command | What you get |
|---|---|---|
| once per repo | /interlock:bootstrap | Your repo, described in specs |
| every change | <kbd>/interlock:spec "idea"</kbd> | A reviewed, implementation-ready change. Then it stops |
| every change | You read the spec | Ten minutes, with a checklist. The only place a human is required |
| every change | <kbd>/interlock:ship</kbd> | Parallel agents, your tests, one commit. Asks nothing |
| when you want it | /interlock:settle | The pull request, with the merge verdict on it |
| after the merge | openspec archive <change> | The living specs catch up |
After a ship, /interlock:settle --create --review pushes the branch, opens the pull request as a draft, reviews it (the lean default set of review dimensions, or the wider set with --strict, with the blast-radius dimension when the repository has a graph; it is skipped, and says so, without one), posts the findings as a comment, remediates what it can, posts a reply comment saying which findings are fixed, open or new, and marks it ready with the merge verdict and the head-bound evidence in its description. It never merges and never approves; a person still presses the button. The GitHub loop is not exercised end to end until a first run on a real pull request is recorded. Details.
Shape and gates on ship. --review runs the adversarial review before the commit. --strict adds remediation, handoff artifacts and a conformance check. --solo and --waves force the plan shape the classifier would otherwise choose. --tdd runs the change's failing-test section first. spec --continue skips the checkpoint when the readiness gate passes; 05 says what that cannot catch.
Any time, on their own. /interlock:explore (reconnaissance with parallel investigators), /interlock:review-code (the adversarial review, standalone), /interlock:fix-tests (repair a red suite by root cause, without weakening a test), /interlock:graph (build and query the code graph), /interlock:report (indicators over the run corpora, gating nothing), /interlock:manual-test-plan, /interlock:explain-code, /interlock:evals, /interlock:docs-digest, /interlock:dispatch, /interlock:commit.
Watching. /interlock-meter is the ship run as a pane; /interlock-spec the spec run; /interlock-preflight the session's doctor report; /interlock-handoff the resume card after a halt.
In the terminal. interlock doctor, interlock limits, interlock drift, interlock merge-confidence. Every subcommand: 07.
| Change | One unit of work: a folder under openspec/changes/<name>/ holding proposal.md, design.md, tasks.md and delta specs |
| Delta spec | The behaviour a change adds or alters, written as Given/When/Then scenarios |
| Living spec | openspec/specs/: what the system does today. Archiving a change folds its delta specs in |
| Checkpoint | Your read of the spec, between spec and ship. The one step a human must do |
| Skill / workflow | A skill is instructions Claude follows in the conversation, and it can ask you questions. A workflow is a script the Claude Code runtime executes, and it cannot |
| Wave / lane | A wave is a batch of tasks that run in parallel; a lane is one agent's slot in it |
| Halt | ship stopped, said what finished and what it needs from you. 04 decodes each one |
Every term, defined from the ground up: 09 — From prompt to workflow.
<img src="docs/assets/ship-meter.png" alt="The ship meter pane during the recorded run: wave 1 with three lanes marked ok and the model that served each, the verify checkpoint between the waves, wave 2 with two lanes running and one pending, then verify-final, commit and close." width="760">
On Claude Code 2.1.287 and later the plugin draws both runs live: a status line that stops at the checkpoint, a pane of every wave, lane and agent, and each degradation banner as a toast the moment it is raised. The pane observes; the CLI decides. On an older host the run is the same, without the pane. The ship meter →
Default ship trusts your test suite: a green suite, one commit, nothing else. None of the rows below is needed for your first change. Add them one at a time as the loop earns it; each costs what its last column says.
| Add | What it does | Cost |
|---|---|---|
ship --review | Up to seven review dimensions in parallel, then two skeptics who must cite a file:line in the diff to dismiss anything. You see only what survived, and how many did not | The expensive part of a run. 06 |
ship --strict | The review, plus remediation, a manual test plan when UI changed, a walkthrough of the commit, and a conformance check of the diff against the spec's scenarios | The previous default. 01 |
/interlock:settle | Opens or updates the PR with a MERGE, HUMAN or BLOCK verdict in its labels and description, and what would lift it. Never merges, never approves | Needs gh or glab signed in. 15 |
interlock merge-confidence --require-merge in CI | The same verdict as a required check. It re-reads the evidence a run left and runs no review of its own. Exits 1 unless MERGE | Some setup. 15 |
REVIEW.md | Your repo's own policy: paths out of review scope, paths that always need a human | One file. 12 |
Most of the category competes on how much structure you write before coding: Spec Kit adds phases, BMAD adds roles, Kiro adds an IDE. Interlock competes on how many decisions the model is not allowed to make.
--isolate-waves, every parallel task runs in its own git worktree and a collision is a named halt, never a lost write.PreToolUse hooks, inert outside a run. 13file:line in the diff, or it dismisses nothing. 06interlock drift reports unarchived changes, specs citing missing files and code no spec describes, each at its own confidence, and never blocks. 03| Competes on | Where the rules live | |
|---|---|---|
| Spec Kit | phases you write before code | prompt templates, portable across thirty agents |
| BMAD | roles you assign | prompt templates |
| Kiro | an IDE with specs built in | the IDE |
| OpenSpec | the artifact loop and its CLI | the CLI validates artifacts; skills run the loop |
| Interlock | how many decisions the model may not make | a CLI with exit codes, and a runtime with no channel for a question |
It composes OpenSpec rather than replacing it: /interlock:spec drives the openspec CLI, and the stock OpenSpec skills stay available for the plain artifact loop. 03 says when each is the right call; 08 sets the harness beside OpenClaw, Hermes Agent and DeepSeek Harness. The trade is portability: Claude Code is the default and supported host, and Cursor and Copilot are not supported, because the guarantees come from Claude Code's workflow runtime.
Other hosts (experimental). interlock-run drives the same loop over the Claude Code CLI, any Agent Client Protocol (ACP) agent, OpenAI Codex or Qwen Code. You start it yourself; no slash command does, and /interlock:ship never falls back to it. Two caveats, both bannered by the runner. claude -p, the Agent SDK and ACP are the usage Anthropic flagged for separate metered credit, while the Workflow runtime behind /interlock:ship is the exempted path. And Codex and Qwen need the planner's model tiers mapped with INTERLOCK_MODEL_MAP; an unmapped tier is bannered, never silently run on your default. The older interlock-ship-acp still works, prints a deprecation line, and is removed in the next minor. Code Mode is out of scope. Host table, banners and configuration: 07.
The network. Everything runs without a model and without the network, with one opt-in exception: interlock notify pushes one message, so a run or a checkpoint reached while nobody was watching can still reach you.
run close --notify sends the close summary's first line, the change name and the run id. The spec checkpoint sends the change name. An interlock notify you type sends the title and body you give it.ntfy server option or by INTERLOCK_NTFY_URL (the public https://ntfy.sh by default), under the topic in the plugin's ntfy topic option or INTERLOCK_NTFY_TOPIC. With no topic set, no request is ever made./interlock:settle has the model run gh, glab and git fetch under your own sign-in; those requests are those tools'. interlock doctor reports whether ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is set, by name and never by value. The vendor CLIs a run spawns inherit the environment as any child process does; what they send is theirs.Interlock makes no other request.
The CLIs on their own. interlock (the policy engine), interlock-graph (a local, deterministic code graph; no vector store, no network) and interlock-run (the runner above) are three zero-dependency Node binaries. The plugin puts them on Claude Code's PATH; npm install -g @renzrollon/interlock puts them on yours. Every gating subcommand exits 1 when it blocks. Reference and every environment variable: 07.
New here? Start with 01 — The first hour, and keep 04 — When it stops open during your first ship. Only ever prompted a coding agent? 09 defines every term once, ending at why ship is a script and not a prompt.
| 01 — The first hour | Install to first shipped change |
| 02 — The checkpoint | How to read a spec in ten minutes |
| 03 — OpenSpec vs Interlock | What composes with what |
| 04 — When it stops | Every halt and banner, and what to do |
| 05 — Continuity | When --continue may skip the human read |
| 06 — Why it works | The mechanisms, low-level, with the costs stated |
| 07 — CLI and configuration | Every subcommand, environment variable and host |
| 08 — The Interlock harness | The parts of the harness, what holds on each host, and a short comparison with other harnesses |
| 09 — From prompt to workflow | New to agentic workflows? Every term defined, then why ship is a script |
| 10 — Ship and spec for prompt-only engineers | Primer, review of spec+ship, token and quality tactics |
| 11 — The indicators | What interlock report measures and why it gates nothing; whether to commit the run corpora |
| 12 — Repository review policy | The optional REVIEW.md: what it can change and what it cannot |
| 13 — The guards | The hooks, the stage marker's lifecycle, and the fail-open rule |
| 14 — Evals | What a consumer's run is checked by, why no model evals run in your CI, how to file a failure |
| 15 — Merge confidence | What the MERGE / HUMAN / BLOCK verdict reads, signal by signal, and how it reaches a pull request or a CI job |
| 16 — Upgrading | What an upgrade keeps, what a resume across versions does, and how to keep the CLI at the plugin's version |
git clone https://github.com/renzrollon/interlock && cd interlock
npm test # no dependencies to install first
claude --plugin-dir . # load it without installing
More in CONTRIBUTING.md. Report vulnerabilities privately (SECURITY.md); ACCESSIBILITY.md and the code of conduct cover the rest. Built on OpenSpec by Fission AI, and on the wave-execution pattern for parallel task application. MIT.
hooks/mod.mjs 2201 lines1// The ship meter: a hooks module that draws a ship run while it runs, and the
2// in-process form of the launch guard.
3//
4// Every hook here observes but one branch. The CLI decides; this module shows
5// what the CLI already said, the moment it says it: the step each `interlock`
6// call printed (read off the ping's Bash result), the per-agent figures each
7// model request reported, and the plan windows the session reports. It joins
8// nothing into any record, and recognises no banner by its wording: it shows
9// the `banners` list the CLI emitted. The close summary and the receipt are
10// the record; the pane says so.
11//
12// THE ONE BRANCH THAT DECIDES (guard-ship-relaunch-in-process design D3). The
13// Workflow hook refuses a ship launch when the session recorded one newer than
14// its last human prompt: the settings hook `hooks/guard-relaunch.mjs` reads the
15// same rule over a file, and this reads it over the engine's own prompt origin
16// and session state, before the engine or the settings layer sees the call.
17// The verdict and its words are `lib/launch-rule.mjs`'s, never this file's;
18// `test/spine/mod-pins.test.mjs` pins that the refusal is that verdict, once.
19// A guard that cannot read its facts allows, says so on the debug log, and
20// leaves the settings form to decide.
21//
22// It runs in the engine's own environment, with no Node and `$` as its only
23// way out, so it imports nothing from the plugin that reaches `node:`:
24// `lib/launch-rule.mjs` is Node-free by design, and the briefing-hash
25// expression is restated below rather than imported, because
26// `lib/agent-usage.mjs` imports `node:fs` (design D4, D5). It imports nothing
27// from `claude-code` either: Claude Code 2.1.274 refuses a module that passes
28// `$` into a function imported from there, so the state is read and written
29// with `$.state` directly. What it may call and must never contain is pinned
30// by `test/spine/mod-pins.test.mjs` (design D8); its behaviour by
31// `test/mod/meter.test.ts` and `test/mod/relaunch.test.ts` under
32// `claude plugin test`.
33//
34// The meter's state is module-level (design D3): a reload starts it over, a run
35// launched before the reload is not drawn again, and the first of its steps to
36// cross the module is named once on the debug log. The guard's record is the session's (`$.state`, declared in
37// types/index.d.ts): it survives a reload, and /clear, /resume and /branch
38// empty it, which allows the next launch. The meter's run ends on that same
39// boundary, the classic session-start event with a `clear`, `resume` or `fork`
40// source, so the two things the module keeps are reset together
41// (show-quiet-time-and-reset-the-meter-on-clear design D4).
42//
43// THE QUIET FIGURE (same change, design D1-D3, D5). While a run is live the
44// module stamps the engine's time of each thing the run does, and one interval
45// the host runs for it recomputes how long the run has been quiet. Once that
46// reaches the published threshold, `quiet <n> min` follows the position on the
47// status line, the spinner and the pane. The word names no cause, and the
48// threshold and the period are `lib/meter-quiet.mjs`'s, read from
49// `interlock limits`; this file holds neither number.
50//
51// THE GUARDS' REFUSALS (speak-permission-prompts-and-guard-denials design D4,
52// D5). A settings guard that refuses a tool call ends it with an errored result
53// whose text carries the guard's own sentence behind an engine prefix. The
54// tool hooks on Bash, Edit, Write and Workflow read that result, and when it
55// names one of the four guards the sentence is toasted once and counted on the
56// pane. The in-process launch guard's own refusal is toasted in the rule's
57// words, and the pane shows the rule's ruling over the session's record. The
58// names and the words are `lib/meter-refusals.mjs`'s and the guards'; the
59// permission prompts are not spoken, because no classic event reaches a hooks
60// module on the engines probed (design D1, D9).
61//
62// THE WAVE BOARD (draw-the-wave-board-in-the-meter-pane design D5-D8). The
63// pane's waves section is the board `lib/draw-plan.mjs` draws for the CLI,
64// drawn from one source: the plan summary the adoption and replan steps carry,
65// with an overlay built from the steps alone (the cursor, the ids each recorded
66// batch names, the skipped verifications, the halt). No file is read for it.
67// The module lays those rows as one bordered card per wave, wraps the gist,
68// and colours the state word the renderer chose and the lane's label. It keys the lanes,
69// appends what the host observed of a lane, and speaks every fallback: a CLI
70// that relays no plan, a pane narrower than the board, a renderer that throws.
71//
72// THE AGENTS' NAMES AND THE PALETTE. The
73// Workflow host raises no `agent.spawn` for a Workflow agent, so the spawn
74// event's join never fires there. Every run agent's first act is to read its
75// own briefing, and that Read or Bash call names the spawn's briefing path:
76// the module joins the agent to the spawn's row by it, through the same
77// briefing hash. A driver line from an agent no row names marks a relay; any
78// other agent reads `unmatched agent`, said once beneath the rows. A ping wraps
79// the relay: another command first, a heredoc, then `interlock … --json`, then
80// an echoed exit status. The driver is the `interlock` that begins a command,
81// and the step is the JSON object in that result, so the wrap still registers
82// its lanes. Every colour is a theme key from `lib/meter-palette.mjs` and
83// names a meaning, never a threshold: the engine's own figures carry none.
84//
85// THE STEP TIMELINE. The agents list's place is a timeline: one line per step
86// as it crossed, the agent whose Bash call printed it folded into that line,
87// the agents a step spawned one indent beneath it in the order they started,
88// relays no step names at their own time, and the agents nothing names last.
89// Every timed line carries the local `HH:MM:SS` of a reading the module took
90// itself (the launch's, a step's stamp, an agent's first request), blank
91// where the clock gave none; durations are humanised. The order and the
92// step's words are `lib/meter-timeline.mjs`'s, the time words
93// `lib/meter-time.mjs`'s. Within a wave card the lanes sit beneath their
94// batch's sub-header, timed by when that batch was first dispatched.
95//
96// THE SESSION START (show-preflight-and-interrupted-runs-at-session-start
97// design D5-D8). Outside a run the module draws two things, both from the
98// report `hooks/preflight.mjs` leaves at `.claude/ship/preflight.json`: the
99// `AbovePrompt` band with `/interlock-preflight`, and `/interlock-handoff`,
100// which renders a halt resume card the report names. That file and a card it
101// names are the module's one file read, `$.fs.read`, and nothing else: never a
102// run's trajectory, its manifest or its wave state, and no listing or
103// existence check (the hook lists, in Node). It reads at each prompt a person
104// submits, the one event that reaches a module after the preflight wrote, and
105// when one of the two commands is run. It never reads at the classic
106// session-start event: the settings hook that writes the file runs inside that
107// event's chain, and the module's hook there resets the meter and returns the
108// chain's call as it is, so after a boundary the module holds no report until
109// the next prompt (clear-the-plugin-directory-holds design D1). A report is
110// known by its own written time, so a re-read changes nothing and the band
111// stays hidden once hidden; the lines, the hide rule and the card's cap are
112// `lib/preflight-file.mjs`'s.
113//
114// THE SPEC METER (observe-the-spec-run-live design D1-D7). The same module
115// draws an `/interlock:spec` run, which has no CLI spine of its own, from what
116// already crossed it: the spec skill's load, read off a submitted prompt's
117// first word or a Skill tool call (the engine raised no `skill.prompt` for a
118// plugin skill on 2.1.291, so that event is not hooked), the Bash results of
119// the flow's keyed `openspec` and `interlock` lines, the paths of Edit and
120// Write calls, and the Explore spawns. A prompt, a Skill call and every result
121// are passed on as they came. It writes nothing and reads no file: the
122// artifacts on disk, the findings file and the gate's exit are the record,
123// and the pane says so. Its record is module state, ended at the checkpoint,
124// at an accepted ship launch and at the session boundary. The module owns one
125// status line, written by `setStatus` alone: the ship position while a ship
126// run is live, else the spec line. Every rule and word is
127// `lib/spec-meter.mjs`'s.
128
129import { drawPlanBoardRows } from '../lib/draw-plan.mjs'
130import { decideLaunch, emptyRecord, isAcceptedLaunch, isShipLaunch, withLaunch, withPrompt } from '../lib/launch-rule.mjs'
131import { LIMITS } from '../lib/limits.mjs'
132import { PALETTE, stateProps, turnProps } from '../lib/meter-palette.mjs'
133import { TICK_MS, quietMs, quietWord } from '../lib/meter-quiet.mjs'
134import { clockText, durationText, stampText } from '../lib/meter-time.mjs'
135import { BATCH_ACTIONS, batchText, laneCountText, planWaveCount, stepText, timeline } from '../lib/meter-timeline.mjs'
136import { guardDenialLine, guardOf, guardReason, launchGuardLine } from '../lib/meter-refusals.mjs'
137import {
138 adoptPreflight,
139 bandLines,
140 cardLine,
141 clampCard,
142 freshStart,
143 noCardText,
144 noReportText,
145 orderCards,
146 preflightFilePath,
147 preflightPaneLines,
148 readPreflightReport
149} from '../lib/preflight-file.mjs'
150import {
151 SPEC_REPLACED_LINE,
152 SPEC_TITLE,
153 SPEC_UNPLACED_TOAST,
154 TEXT_KINDS,
155 addAdvisorEntries,
156 changeOf,
157 freshSpec,
158 lateLineText,
159 promptSkill,
160 readResult,
161 skillRole,
162 specLines,
163 specPaneLines,
164 specStatusText,
165 unparsedEntry,
166 unreadLineText,
167 writeOf
168} from '../lib/spec-meter.mjs'
169
170const PANE = 'interlock-meter'
171const TITLE = 'Interlock'
172const RECORD_LINE = 'live figures; the close summary and the receipt are the record'
173const NO_RUN_LINE = 'no ship run is live in this session'
174const UNPLACED_TOAST = '/interlock-meter opens the ship meter'
175// The wave section's spoken lines (draw-the-wave-board-in-the-meter-pane design D8).
176const NO_LANES_LINE = 'no lanes dispatched yet'
177const UNRELAYED_LINE = 'plan structure not relayed by this CLI'
178const BOARD_FAILED_LINE = 'wave board could not be drawn'
179// The session start's two panes, each opened by the command of its name (design D6).
180const PREFLIGHT_PANE = 'interlock-preflight'
181const HANDOFF_PANE = 'interlock-handoff'
182// The spec meter's pane and command (observe-the-spec-run-live design D6), spelled
183// here so the validator records it; pinned equal to lib/spec-meter.mjs's.
184const SPEC_PANE = 'interlock-spec'
185
186// The launch guard's record in the session's state: the one key the plugin's
187// type contract declares (types/index.d.ts; guard-ship-relaunch-in-process D2).
188const LEDGER = { plugin: 'interlock', key: 'ledger' }
189// The prompt origins a person stands behind: their own Enter, the Remote
190// Control bridge, the SDK host's turn (design D3). The completion wake, a
191// schedule, a peer, a channel, a coordinator, an observer, a plugin's own and
192// a missing origin count nothing.
193const HUMAN_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
194const GUARD = 'interlock guard'
195// The line `cli()` in workflows/ship.js hands the ping (design D2). A ping
196// wraps it, so the driver is found by `driverInvocation`, not a line start.
197// The bootstrap line a lane's spawn prompt carries (as `lib/agent-usage.mjs` reads it).
198const BRIEFING_SHA = /Expected sha256: ([0-9a-f]{64})/g
199// What an agent row and a turn-end toast read for an agent no row and no driver line names.
200const UNMATCHED = 'unmatched agent'
201const UNMATCHED_LINE = 'unmatched: no briefing read or interlock line seen from this agent yet'
202// The characters a briefing path may stand behind in a Read path or a command,
203// and the ones that would make it part of a longer file name after it.
204const PATH_BEFORE = /[\s\/'"=]/
205const PATH_AFTER = /[\w.+-]/
206/** The props a name is drawn with: a lane label, a spawn's title, a joined agent's name. */
207const NAME_PROPS = { bold: true, color: PALETTE.identity }
208const DIM = { dimColor: true }
209// The timeline's gutter: `HH:MM:SS` and two spaces, and how far a section body
210// and a child line sit in from what holds them (layout probe P3, Claude Code 2.1.295).
211const GUTTER_COLUMNS = 10
212const INDENT = 2
213// One column, so a frame never moves the line. Stepped while a run is in
214// flight, on the interval that already recomputes the quiet word.
215const PULSE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
216const NO_STEP_LINE = 'no step has crossed yet'
217/** The props the run header and each section heading are drawn with. */
218const HEADING_PROPS = { bold: true, color: PALETTE.accent }
219const TOKEN_FIELDS = ['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens']
220// The classic session-start sources that start the session over, as the person
221// typed them (design D4). `startup` and `compact` are not among them.
222const BOUNDARIES = new Map([
223 ['clear', '/clear'],
224 ['resume', '/resume'],
225 ['fork', '/branch']
226])
227
228let session = { interactive: false, surface: null, cwd: null }
229let run = freshRun()
230// The session start's report, as last read (design D8): module state, reset
231// with the run on a reload and on the session boundary.
232let start = freshStart()
233// Counts every interval this environment started, so a period can tell its own (design D2).
234let generations = 0
235// The spec run, as module state (observe-the-spec-run-live design D7): reset
236// on a reload and at the session boundary, like the ship run.
237let spec = freshSpec()
238
239function freshRun() {
240 return {
241 // idle → live (accepted launch) → closing (a close or halt step) → closed (the close record)
242 phase: 'idle',
243 runId: null,
244 workflowName: null,
245 transcriptDir: null,
246 change: null,
247 action: null,
248 wave: undefined,
249 batchIndex: undefined,
250 batchCount: undefined,
251 rows: new Map(),
252 banners: [],
253 toasted: new Set(),
254 agents: new Map(),
255 summary: null,
256 exitCode: null,
257 // The quiet figure (design D1, D2): the engine's time of the run's last
258 // activity (null until the clock answers), the word it makes, and the one
259 // interval that recomputes it, known by its handle and its generation.
260 lastActivityAt: null,
261 // The reading the last stamp took (null when the clock failed), and the
262 // launch's own: the timeline's times, never guessed.
263 stampedAt: null,
264 launchedAt: null,
265 // Every step applied, in crossing order, and the time each batch was first dispatched, by `<waveIndex>:<batchIndex>`.
266 steps: [],
267 batchAt: new Map(),
268 quietWord: null,
269 tick: null,
270 generation: 0,
271 clockFailed: false,
272 // Whether a step that crossed with no live run has been named on the debug log.
273 idleStepNamed: false,
274 // Each settings guard's refusals this run, by guard, in first-seen order (design D4).
275 guardDenials: new Map(),
276 // The wave board (draw-the-wave-board-in-the-meter-pane design D6), every
277 // field taken off a step: the latest plan summary, the ids each recorded
278 // batch named (and, for a failed id, the wave it was recorded at), the
279 // skipped verifications by position, where the run is, the last batch
280 // dispatched, the halt, and whether a malformed field was named yet.
281 plan: null,
282 recorded: { ok: [], failed: [], notAttempted: [] },
283 failedAt: new Map(),
284 skips: [],
285 cursor: null,
286 dispatched: null,
287 halt: null,
288 planNamed: false,
289 recordedNamed: false,
290 // The in-flight mark, stepped by the one quiet interval, and whether this
291 // run has asked the pane to follow its latest line.
292 pulse: 0,
293 followed: false
294 }
295}
296
297const watching = () => session.interactive && (run.phase === 'live' || run.phase === 'closing')
298const specWatching = () => session.interactive && spec.phase === 'live'
299const isInt = v => Number.isInteger(v)
300const str = v => (typeof v === 'string' && v ? v : null)
301
302const messageOf = err => (err && err.message) || String(err)
303const asRecord = value => (value && typeof value === 'object' && Array.isArray(value.launches) ? value : emptyRecord())
304
305/**
306 * What the launch guard decides over: the session's record and the time now. A
307 * missing or malformed record is empty; one that cannot be read at all is
308 * empty too, and named on the debug log. An empty record allows (design D5).
309 */
310async function guardFacts($) {
311 try {
312 const held = await $.state.get(LEDGER)
313 return { record: asRecord(held.value), now: await $.clock.now() }
314 } catch (err) {
315 $.ui.log(`${GUARD}: cannot establish this session's launches, allowing: ${messageOf(err)}`, { to: 'debug' })
316 // No time, not a made-up one: the empty record allows before the rule reads
317 // it, and the meter stamps no launch time it does not have (design D1).
318 return { record: emptyRecord(), now: null }
319 }
320}
321
322/**
323 * Change the session's record with `change(record, at)`, `at` the time now as
324 * ISO. Written only over the version it read and read again when another write
325 * landed first, as the engine's `update` does. A write that fails is named on
326 * the debug log and never thrown: it runs after the call it records did.
327 */
328async function changeRecord($, what, change) {
329 try {
330 const at = new Date(await $.clock.now()).toISOString()
331 let held = await $.state.get(LEDGER)
332 for (;;) {
333 const written = await $.state.set(LEDGER, change(asRecord(held.value), at), { ifVersion: held.version })
334 if (written.isSet) return
335 const again = await $.state.get(LEDGER)
336 if (again.version === held.version) throw new Error(`the write missed at version ${held.version} with no other write`)
337 held = again
338 }
339 } catch (err) {
340 $.ui.log(`${GUARD}: ${what} not recorded: ${messageOf(err)}`, { to: 'debug' })
341 }
342}
343
344/** `<change> · <action> · wave <w> · batch <j>/<k>`, each position omitted when the step carries none (design D6). */
345function position() {
346 const parts = []
347 if (run.change) parts.push(run.change)
348 if (run.action) parts.push(run.action)
349 if (run.wave !== undefined && run.wave !== null) parts.push(`wave ${run.wave}`)
350 const batch = batchText(run.batchIndex, run.batchCount)
351 if (batch) parts.push(batch)
352 return parts.join(' · ')
353}
354
355/** The position, then the quiet word while it is set: what the status line and the spinner say (design D5). */
356const shown = () => [position(), run.quietWord].filter(Boolean).join(' · ')
357
358function statusText() {
359 const text = shown()
360 return text ? `interlock: ${text}` : undefined
361}
362
363/**
364 * The module's one status line, composed in one place (observe-the-spec-run-live
365 * design D7): the ship position while a ship run is live, else the spec line
366 * while a spec run is live or stopped at its checkpoint, else nothing. The
367 * engine keeps one line per plugin and each call replaces it (probe 4), so
368 * this is the only writer.
369 */
370function setStatus($) {
371 const shownSpec = spec.phase === 'live' || spec.phase === 'checkpoint'
372 $.ui.status(run.phase === 'live' ? statusText() : shownSpec ? specStatusText(spec) : undefined)
373}
374
375/**
376 * The engine's time now, or `null` when the clock cannot be read. A read that
377 * fails is named once per run on the debug log and never thrown (design D1).
378 */
379async function clockNow($) {
380 const held = run
381 try {
382 const now = await $.clock.now()
383 if (Number.isFinite(now)) return now
384 throw new Error(`the clock answered ${String(now)}`)
385 } catch (err) {
386 if (!held.clockFailed) {
387 held.clockFailed = true
388 $.ui.log(
389 `interlock meter: the clock cannot be read; the last activity time stands and no quiet figure is shown: ${messageOf(err)}`,
390 { to: 'debug' }
391 )
392 }
393 return null
394 }
395}
396
397/** Sets the quiet word; true when it changed. */
398function setWord(word) {
399 if (run.quietWord === word) return false
400 run.quietWord = word
401 return true
402}
403
404/** Draws the word where it shows: the status line while the run is live, the pane and the spinner. */
405function redrawWord($) {
406 if (run.phase === 'live') setStatus($)
407 $.ui.invalidate('ui.render')
408}
409
410/**
411 * Activity (design D1): the run's last activity is now, and the quiet word is
412 * gone. A clock that cannot be read leaves the stamp as it was and the word
413 * absent, never a guessed time. True when the word changed, so the caller redraws.
414 */
415async function stamp($) {
416 const held = run
417 const now = await clockNow($)
418 if (held !== run) return false
419 run.stampedAt = now
420 if (now !== null) run.lastActivityAt = run.lastActivityAt === null ? now : Math.max(run.lastActivityAt, now)
421 return setWord(null)
422}
423
424/**
425 * Starts the run's one interval (design D2), the host's own timer: each period
426 * reads the clock and recomputes the word, draws when the word changed, and
427 * steps the in-flight mark. A period that finds another run or another
428 * interval in its place returns at once. A host that will not start one leaves
429 * the pane, which recomputes the word whenever it is drawn.
430 */
431function startTick($) {
432 const generation = ++generations
433 run.generation = generation
434 const isMine = tick => run.generation === generation && run.tick === tick
435 try {
436 const tick = $.clock.every(TICK_MS, async () => {
437 if (!isMine(tick)) return
438 try {
439 const now = await clockNow($)
440 if (!isMine(tick)) return
441 const changed = setWord(quietWord(quietMs(run.lastActivityAt, now)))
442 const pulsed = inFlight()
443 if (pulsed) run.pulse++
444 if (!isMine(tick)) return
445 if (changed) redrawWord($)
446 else if (pulsed) $.ui.invalidate('ui.render')
447 await followBottom($)
448 } catch (err) {
449 $.ui.log(`interlock meter: a quiet-figure period failed: ${messageOf(err)}`, { to: 'debug' })
450 }
451 })
452 run.tick = tick
453 } catch (err) {
454 $.ui.log(`interlock meter: no interval for the quiet figure; the pane computes it when drawn: ${messageOf(err)}`, {
455 to: 'debug'
456 })
457 }
458}
459
460/**
461 * Asks the pane to follow its latest line, once, so a run that grows keeps the
462 * tail in view until the person scrolls. A host that will not scroll yet is
463 * asked again on the next step or tick. Never throws.
464 */
465async function followBottom($) {
466 if (!session.interactive || run.phase !== 'live' || run.followed) return
467 const held = run
468 try {
469 const moved = await $.ui.scroll({ to: 'end', in: PANE })
470 if (held === run && scrollAccepted(moved)) held.followed = true
471 } catch {
472 // The pane may not be placed yet; the next step or tick asks again.
473 }
474}
475
476/** A scroll landed when the host answered an object and did not refuse it. */
477function scrollAccepted(moved) {
478 if (!moved || typeof moved !== 'object') return false
479 return !Object.prototype.hasOwnProperty.call(moved, 'den' + 'y')
480}
481
482/** Ends the run's interval, if it has one: a cancelled timer never fires again. */
483function stopTick() {
484 if (run.tick) run.tick.cancel()
485 run.tick = null
486 run.quietWord = null
487}
488
489/**
490 * A settings guard's refusal, read off the result the engine handed a tool hook
491 * (design D4): the text from the guard's name on is toasted once per distinct
492 * text per run and counted by guard. A result that is not errored, or names no
493 * guard, is not this module's to speak: nothing is drawn and nothing logged.
494 */
495function speakRefusal($, r) {
496 try {
497 const reason = r && r.isError === true ? guardReason(r.text) : null
498 if (!reason) return
499 const guard = guardOf(reason)
500 run.guardDenials.set(guard, (run.guardDenials.get(guard) || 0) + 1)
501 if (!run.toasted.has(reason)) {
502 run.toasted.add(reason)
503 $.ui.toast(reason)
504 }
505 $.ui.invalidate('ui.render')
506 } catch (err) {
507 $.ui.log(`interlock meter: a guard's refusal was not drawn: ${messageOf(err)}`, { to: 'debug' })
508 }
509}
510
511/**
512 * An edit during a live ship run, its result read for a guard's refusal
513 * (guard-tests, guard-tasks); during a live spec run, its path filed as a
514 * write when the engine did not mark it errored (observe-the-spec-run-live
515 * design D4). Returned as it came.
516 */
517async function editCall($, e, next) {
518 const ship = watching()
519 if (!ship && !specWatching()) return next(e)
520 const held = run
521 const heldSpec = spec
522 const r = await next(e)
523 if (ship && held === run) speakRefusal($, r)
524 if (heldSpec === spec && specWatching() && !(r && r.isError === true)) await fileWrite($, e.file_path)
525 return r
526}
527
528/**
529 * The engine's time now for the spec record, or `null` when the clock cannot
530 * be read: the ship meter's rule (design D6), named once per spec run.
531 */
532async function specNow($) {
533 const held = spec
534 try {
535 const now = await $.clock.now()
536 if (Number.isFinite(now)) return now
537 throw new Error(`the clock answered ${String(now)}`)
538 } catch (err) {
539 if (!held.clockFailed) {
540 held.clockFailed = true
541 $.ui.log(`interlock spec: the clock cannot be read; the last activity time stands: ${messageOf(err)}`, { to: 'debug' })
542 }
543 return null
544 }
545}
546
547/** Activity on the spec record: its last activity is now, when the clock answers. */
548async function specStamp($) {
549 const held = spec
550 const now = await specNow($)
551 if (held === spec && now !== null) spec.lastActivityAt = now
552 return now
553}
554
555/** Redraws what the spec run shows: the status line through the composer, and the panes. */
556function redrawSpec($) {
557 setStatus($)
558 $.ui.invalidate('ui.render')
559}
560
561/**
562 * The spec skill's load (design D1): `spec` starts a run over whatever was
563 * held, `explore` and `review-artifacts` set the stage of a live one, and
564 * anything else is not this meter's. Never throws.
565 */
566async function observeLoad($, name) {
567 try {
568 const role = skillRole(name)
569 if (role === 'spec') await startSpec($)
570 else if (role && specWatching()) {
571 spec.stage = { kind: role }
572 await specStamp($)
573 redrawSpec($)
574 }
575 } catch (err) {
576 $.ui.log(`interlock spec: a skill load was not drawn: ${messageOf(err)}`, { to: 'debug' })
577 }
578}
579
580/** A fresh spec run, live, its pane opened unasked; one toast when the engine will not seat it. */
581async function startSpec($) {
582 if (spec.phase !== 'idle') $.ui.log(SPEC_REPLACED_LINE, { to: 'debug' })
583 spec = freshSpec()
584 const started = spec
585 spec.phase = 'live'
586 spec.startedAt = await specStamp($)
587 if (started !== spec) return
588 redrawSpec($)
589 const placed = await openPane($, SPEC_PANE, SPEC_TITLE)
590 if (!placed || placed.isPlaced !== true) $.ui.toast(SPEC_UNPLACED_TOAST)
591}
592
593/**
594 * The spec record that will read a keyed command, or `null` (design D3). With
595 * no live spec run the first keyed line after the checkpoint or a session
596 * boundary is named once on the debug log, and none is read.
597 */
598function specReader($, lines) {
599 if (specWatching()) return spec
600 const keyed = lines.find(l => l.kind !== 'naming-only')
601 if (keyed && !spec.lateNamed && (spec.phase === 'checkpoint' || spec.afterBoundary)) {
602 spec.lateNamed = true
603 $.ui.log(lateLineText(keyed.kind, spec.phase), { to: 'debug' })
604 }
605 return null
606}
607
608/** The results kept for a change, `null` being the unnamed slot the pane never draws (design D2). */
609function changeSlot(name) {
610 if (!spec.changes.has(name)) spec.changes.set(name, {})
611 return spec.changes.get(name)
612}
613
614/**
615 * Files one keyed segment's entry (design D2, D3, D7): the change it names
616 * becomes the one drawn, its result is kept under that change (or the current
617 * one), and the stage is the entry. A checkpoint ends the run at its checkpoint.
618 */
619function fileEntry(entry, now) {
620 if (entry.name) {
621 spec.current = entry.name
622 if (!spec.order.includes(entry.name)) spec.order.push(entry.name)
623 }
624 if (entry.kind === 'naming-only') return
625 const slot = changeSlot(entry.name || spec.current)
626 if (entry.kind === 'drift') spec.drift = entry
627 else if (entry.kind === 'autonomy') spec.autonomy = entry.command
628 else if (TEXT_KINDS.includes(entry.kind)) slot[entry.kind] = entry
629 if (entry.kind === 'checkpoint') {
630 spec.phase = 'checkpoint'
631 spec.checkpointCrossed = true
632 spec.checkpointAt = now
633 }
634 spec.stage = entry
635}
636
637/**
638 * Reads a command's keyed segments into the spec record (design D3). Every
639 * entry is read before any is filed, so a reader that throws leaves the record
640 * as it was. Two segments whose results are read share one output, so each is
641 * kept unparsed. An unparsed result leaves one debug line. Never throws.
642 */
643async function applySpecLines($, held, lines, r) {
644 try {
645 const texts = lines.filter(l => TEXT_KINDS.includes(l.kind)).length
646 const text = r && typeof r.text === 'string' ? r.text : ''
647 const entries = lines.map(({ kind, segment }) => {
648 if (kind === 'naming-only') return { entry: { kind, name: changeOf(kind, segment, null) }, segment }
649 if (texts > 1 && TEXT_KINDS.includes(kind)) {
650 return { entry: { ...unparsedEntry(kind, text, 'compound command'), name: changeOf(kind, segment, null) }, segment }
651 }
652 return { entry: readResult(kind, segment, r), segment }
653 })
654 const now = await specNow($)
655 if (held !== spec || !specWatching()) return
656 for (const { entry, segment } of entries) {
657 if (!entry) continue
658 fileEntry(entry, now)
659 if (typeof entry.unparsed === 'string') $.ui.log(unreadLineText(entry, segment), { to: 'debug' })
660 }
661 if (now !== null) spec.lastActivityAt = now
662 redrawSpec($)
663 } catch (err) {
664 $.ui.log(`interlock spec: a keyed line was not read: ${messageOf(err)}`, { to: 'debug' })
665 }
666}
667
668/** A write during a live spec run, filed by its path (design D4). A path never names the change. Never throws. */
669async function fileWrite($, path) {
670 try {
671 const w = writeOf(path)
672 if (!w) return
673 const held = spec
674 const now = await specNow($)
675 if (held !== spec) return
676 if (w.kind === 'artifact') {
677 if (!spec.writes.has(w.change)) spec.writes.set(w.change, new Map())
678 const files = spec.writes.get(w.change)
679 const before = files.get(w.file)
680 files.set(w.file, { count: (before ? before.count : 0) + 1, at: now === null && before ? before.at : now })
681 } else if (w.kind === 'brief') spec.explore.brief = w.path
682 else if (w.kind === 'findings') spec.findings.set(w.change, w.path)
683 if (now !== null) spec.lastActivityAt = now
684 $.ui.invalidate('ui.render')
685 } catch (err) {
686 $.ui.log(`interlock spec: a write was not filed: ${messageOf(err)}`, { to: 'debug' })
687 }
688}
689
690/** What an `agent.spawn` chain returned, read for the meter and handed back unchanged. */
691async function noteSpawn($, input, spawned) {
692 if (session.interactive && run.phase === 'live') {
693 if (spawned && str(spawned.agentId) && input && typeof input.prompt === 'string') {
694 const found = [...input.prompt.matchAll(BRIEFING_SHA)]
695 if (found.length) agentOf(spawned.agentId).sha = found[found.length - 1][1]
696 }
697 if (await stamp($)) redrawWord($)
698 }
699 // An Explore investigator the chain let through (observe-the-spec-run-live design D5).
700 if (specWatching() && input && input.subagentType === 'Explore' && spawned && typeof spawned.model === 'string') {
701 await countInvestigator($)
702 }
703 return spawned
704}
705
706/** Whether `text` names `path` whole: behind its start or a separator, and not followed by more of a file name. */
707function namesPath(text, path) {
708 for (let at = text.indexOf(path); at !== -1; at = text.indexOf(path, at + 1)) {
709 const before = at === 0 ? '' : text[at - 1]
710 const after = text[at + path.length] ?? ''
711 if ((before === '' || PATH_BEFORE.test(before)) && (after === '' || !PATH_AFTER.test(after))) return true
712 }
713 return false
714}
715
716/**
717 * The Workflow host's join: it raises no
718 * `agent.spawn` for a Workflow agent, but every run agent's first act is to
719 * read its own briefing. A Read path or a Bash command that names a
720 * dispatched spawn's briefing path joins the agent to that spawn's row,
721 * through the same briefing hash the spawn event joins on. The first briefing
722 * an agent reads wins; an agent that names none is left as it was, and no
723 * agent record is made for it. Never throws.
724 */
725function noteBriefing($, agentId, text) {
726 try {
727 const id = str(agentId)
728 if (!id || typeof text !== 'string') return
729 const known = run.agents.get(id)
730 if (known && known.sha) return
731 const said = text.split('\\').join('/')
732 for (const r of run.rows.values()) {
733 if (!r.sha || !r.promptPath) continue
734 if (!namesPath(said, r.promptPath.split('\\').join('/'))) continue
735 agentOf(id).sha = r.sha
736 $.ui.invalidate('ui.render')
737 return
738 }
739 } catch (err) {
740 $.ui.log(`interlock meter: a briefing read was not joined to its lane: ${messageOf(err)}`, { to: 'debug' })
741 }
742}
743
744/** Whether `i` is the end of a command token. */
745function tokenBoundary(command, i) {
746 if (i >= command.length) return true
747 const c = command[i]
748 return c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === ';' || c === '&' || c === '|' || c === '<' || c === '>'
749}
750
751/**
752 * The index just after a heredoc that opens at `at` (`<<` or `<<-`), or `at`
753 * when that is not a heredoc. An unclosed body consumes the rest of the line,
754 * the way the shell does, so a word inside it is not a command.
755 */
756function skipHeredoc(command, at) {
757 let i = at + 2
758 let strip = false
759 if (command[i] === '-') {
760 strip = true
761 i++
762 }
763 while (command[i] === ' ' || command[i] === '\t') i++
764 let quote = null
765 if (command[i] === "'" || command[i] === '"') {
766 quote = command[i]
767 i++
768 }
769 const start = i
770 while (i < command.length && /[A-Za-z0-9_-]/.test(command[i])) i++
771 const word = command.slice(start, i)
772 if (!word) return at
773 if (quote && command[i] === quote) i++
774 const nl = command.indexOf('\n', i)
775 if (nl < 0) return command.length
776 let pos = nl + 1
777 while (pos <= command.length) {
778 const next = command.indexOf('\n', pos)
779 const end = next < 0 ? command.length : next
780 let line = command.slice(pos, end)
781 if (line.endsWith('\r')) line = line.slice(0, -1)
782 if (strip) line = line.replace(/^\t+/, '')
783 if (line === word) return next < 0 ? command.length : next + 1
784 if (next < 0) return command.length
785 pos = next + 1
786 }
787 return command.length
788}
789
790/** `command` from `start` through the invocation, stopping at the next unquoted separator. */
791function sliceInvocation(command, start) {
792 let quote = null
793 let i = start
794 while (i < command.length) {
795 const c = command[i]
796 if (quote) {
797 if (c === '\\' && quote === '"') {
798 i += 2
799 continue
800 }
801 if (c === quote) quote = null
802 i++
803 continue
804 }
805 if (c === "'" || c === '"') {
806 quote = c
807 i++
808 continue
809 }
810 if (c === '\n' || c === ';' || c === '|' || c === '&') break
811 i++
812 }
813 return command.slice(start, i).trim()
814}
815
816/**
817 * The `interlock` invocation a shell line actually runs, or null.
818 *
819 * A ping writes a file, then runs `interlock … --json`, then echoes an exit
820 * status. The invocation is the `interlock` token that begins a command (the
821 * line, or after `;`, `&`, `|` or a newline), not one quoted or sitting inside
822 * a heredoc. The slice stops at the next separator, so the relay name is the
823 * subcommand and not the rest of the script.
824 */
825function driverInvocation(command) {
826 if (typeof command !== 'string' || !command) return null
827 let quote = null
828 let ready = true
829 for (let i = 0; i < command.length; i++) {
830 const c = command[i]
831 if (quote) {
832 if (c === '\\' && quote === '"') {
833 i++
834 continue
835 }
836 if (c === quote) quote = null
837 continue
838 }
839 if (c === "'" || c === '"') {
840 quote = c
841 continue
842 }
843 if (c === '<' && command[i + 1] === '<') {
844 const skipped = skipHeredoc(command, i)
845 if (skipped > i) {
846 i = skipped - 1
847 ready = true
848 continue
849 }
850 }
851 if (c === ' ' || c === '\t' || c === '\r') continue
852 if (c === '\n' || c === ';' || c === '|' || c === '&') {
853 ready = true
854 continue
855 }
856 if (ready && command.startsWith('interlock', i) && tokenBoundary(command, i + 'interlock'.length)) {
857 return sliceInvocation(command, i)
858 }
859 ready = false
860 }
861 return null
862}
863
864/**
865 * `run next` for `interlock run next --results … --json`: the subcommand a
866 * driver line relays, as `workflows/ship.js` names its relay (`argv.slice(0, 2)`),
867 * the second word dropped when it is a flag or a shell operator.
868 */
869function relayOf(command) {
870 const words = command.trim().split(/\s+/).slice(1, 3)
871 if (!words.length || !words[0]) return null
872 const second = words[1]
873 return second && !/^(--|[;&|<>])/.test(second) ? `${words[0]} ${second}` : words[0]
874}
875
876/** An agent that ran a driver line before any briefing named it is a relay, shown by what it relayed. Never throws. */
877function noteRelay($, agentId, command) {
878 try {
879 const id = str(agentId)
880 if (!id) return
881 const known = run.agents.get(id)
882 if (known && known.sha) return
883 const relay = relayOf(command)
884 if (!relay || (known && known.relay === relay)) return
885 agentOf(id).relay = relay
886 $.ui.invalidate('ui.render')
887 } catch (err) {
888 $.ui.log(`interlock meter: a driver line was not read for its agent: ${messageOf(err)}`, { to: 'debug' })
889 }
890}
891
892/**
893 * A clear, resume or fork ends the run the meter holds, before the chain
894 * beneath runs. Any other source, and a non-interactive session, changes
895 * nothing. Never throws.
896 */
897function endRunAtBoundary($, input) {
898 if (!session.interactive) return
899 try {
900 const boundary = BOUNDARIES.get(input.source)
901 if (!boundary) return
902 const ended = run
903 stopTick()
904 run = freshRun()
905 start = freshStart()
906 spec = freshSpec({ afterBoundary: true })
907 setStatus($)
908 $.ui.invalidate('ui.render')
909 const what = ended.phase === 'idle' ? 'no run was held' : `run ${ended.runId || '(no id)'} is no longer drawn`
910 $.ui.log(`interlock meter: ${boundary} started the session over; ${what}`, { to: 'debug' })
911 } catch (err) {
912 $.ui.log(`interlock meter: the session boundary was not applied: ${messageOf(err)}`, { to: 'debug' })
913 }
914}
915
916/**
917 * The advisor entries one `turn.step` result reports in `serverToolUses`,
918 * counted toward the session when the event has no `agentId` and toward
919 * subagents when it has one (replace-subagent-advisors-with-advisor-tool,
920 * "Counting consults"). Observes only; the step is the engine's. Never throws.
921 */
922function countAdvisorEntries($, e, result) {
923 try {
924 const uses = result && typeof result === 'object' ? result.serverToolUses : undefined
925 if (addAdvisorEntries(spec.advisor, uses, Boolean(e && e.agentId)) > 0) $.ui.invalidate('ui.render')
926 } catch (err) {
927 $.ui.log(`interlock spec: an advisor entry was not counted: ${messageOf(err)}`, { to: 'debug' })
928 }
929}
930
931/** One Explore investigator the chain let through (design D5). Never throws. */
932async function countInvestigator($) {
933 try {
934 spec.explore.spawned++
935 await specStamp($)
936 redrawSpec($)
937 } catch (err) {
938 $.ui.log(`interlock spec: an investigator was not counted: ${messageOf(err)}`, { to: 'debug' })
939 }
940}
941
942/** `/interlock-spec` (design D6): the pure module's keyed lines on `Box` and `Text`, and nothing else. */
943function drawSpecPane($, e) {
944 const { Box, Text } = $.ui.resolve(e)
945 const props = l => (l.bold ? { bold: true } : l.dim ? { dimColor: true } : null)
946 return h(Box, { flexDirection: 'column' }, ...specPaneLines(spec).map(l => h(Box, { key: l.key }, h(Text, props(l), l.text))))
947}
948
949/**
950 * The launch guard's ruling now, over the record its branch would read, in the
951 * rule's words (design D5), and whether that ruling refuses the next launch.
952 */
953async function launchGuardText($) {
954 const { record, now } = await guardFacts($)
955 const ruling = decideLaunch(record, now)
956 return { text: launchGuardLine(ruling, now), refused: now !== null && ruling.decision !== 'allow' && Boolean(ruling.reason) }
957}
958
959/** Names, once per run record, a step that crossed with no live run (design D4). */
960function nameIdleStep($) {
961 run.idleStepNamed = true
962 $.ui.log(
963 'interlock meter: a step crossed with no live run and is not drawn ' +
964 "(a run launched before a /clear, /resume or /branch, or before this module reloaded, is no longer this session's)",
965 { to: 'debug' }
966 )
967}
968
969/** A driver-line call with no live run: passed on whole, its result read only to name the first step (design D4). */
970async function idleStep($, e, next) {
971 if (run.phase !== 'idle' || run.idleStepNamed) return next(e)
972 const r = await next(e)
973 noteIdleStep($, r)
974 return r
975}
976
977/** Names the first step record a result carries while no run is live; reads nothing else. */
978function noteIdleStep($, r) {
979 try {
980 if (run.phase === 'idle' && !run.idleStepNamed && readRecord(r.text).record) nameIdleStep($)
981 } catch {
982 // Reading the result is all this does; the call and its result are the engine's.
983 }
984}
985
986/** A step record: an object with a string `action`, as the driver guards it. */
987function isStep(value) {
988 return Boolean(value) && typeof value === 'object' && !Array.isArray(value) && typeof value.action === 'string'
989}
990
991/** The index just after the JSON object that opens at `start`, or -1. */
992function jsonEnd(text, start) {
993 let depth = 0
994 let quote = null
995 for (let i = start; i < text.length; i++) {
996 const c = text[i]
997 if (quote) {
998 if (c === '\\') {
999 i++
1000 continue
1001 }
1002 if (c === quote) quote = null
1003 continue
1004 }
1005 if (c === '"' || c === "'") {
1006 quote = c
1007 continue
1008 }
1009 if (c === '{') depth++
1010 else if (c === '}') {
1011 depth--
1012 if (depth === 0) return i + 1
1013 }
1014 }
1015 return -1
1016}
1017
1018/**
1019 * The step object in a result that is not itself JSON: a ping prints a line,
1020 * then the step, then an exit status. A stamped step wins; otherwise the
1021 * first object with an action.
1022 */
1023function findStep(text) {
1024 let fallback = null
1025 for (let i = 0; i < text.length; i++) {
1026 if (text[i] !== '{') continue
1027 const end = jsonEnd(text, i)
1028 if (end < 0) continue
1029 let value
1030 try {
1031 value = JSON.parse(text.slice(i, end))
1032 } catch {
1033 continue
1034 }
1035 if (!isStep(value)) continue
1036 if (value.schema === 'interlock.run-step/1') return value
1037 if (!fallback) fallback = value
1038 }
1039 return fallback
1040}
1041
1042/** The step record in a Bash result's text, guarded as the driver guards it: an object with a string `action`. */
1043function readRecord(text) {
1044 if (typeof text !== 'string' || !text.trim()) return { problem: 'no result text' }
1045 const trimmed = text.trim()
1046 try {
1047 const value = JSON.parse(trimmed)
1048 if (isStep(value)) return { record: value }
1049 if (!value || typeof value !== 'object' || Array.isArray(value)) return { problem: 'not an object' }
1050 return { problem: 'no action' }
1051 } catch {
1052 const found = findStep(trimmed)
1053 return found ? { record: found } : { problem: 'not JSON' }
1054 }
1055}
1056
1057function agentOf(id) {
1058 let a = run.agents.get(id)
1059 if (!a) {
1060 a = {
1061 id,
1062 requests: 0,
1063 known: 0,
1064 partial: false,
1065 sums: null,
1066 models: [],
1067 reason: null,
1068 durationMs: null,
1069 sha: null,
1070 // The two words after `interlock` in the first driver line it ran while no row named it.
1071 relay: null,
1072 // Whether its turn end has been spoken: once per agent per run (speak-lane-turn-ends design D1).
1073 endToasted: false,
1074 // The reading at its first request, taken once (null when the clock failed then), and at its turn end.
1075 stepped: false,
1076 firstAt: null,
1077 endAt: null
1078 }
1079 run.agents.set(id, a)
1080 }
1081 return a
1082}
1083
1084/** The agent's first request, timed once by the stamp just taken: a later reading never moves it. */
1085function firstRequest(a) {
1086 if (a.stepped) return
1087 a.stepped = true
1088 a.firstAt = run.stampedAt
1089}
1090
1091/** Field by field: a field one request omitted leaves that figure unknown (`null`), never a guessed zero (design D5). */
1092function addUsage(a, usage) {
1093 a.requests++
1094 if (!usage || typeof usage !== 'object') {
1095 a.partial = true
1096 return
1097 }
1098 a.known++
1099 if (!a.sums) a.sums = Object.fromEntries(TOKEN_FIELDS.map(f => [f, 0]))
1100 for (const f of TOKEN_FIELDS) {
1101 a.sums[f] = a.sums[f] === null || typeof usage[f] !== 'number' ? null : a.sums[f] + usage[f]
1102 }
1103 if (str(usage.model) && !a.models.includes(usage.model)) a.models.push(usage.model)
1104}
1105
1106/** What a malformed field is, for its debug line: never its content. */
1107const shapeOf = value => (value === null ? 'null' : Array.isArray(value) ? 'an array' : `a ${typeof value}`)
1108
1109/** A plan summary as the run program states it: an object with an array of waves. */
1110const isPlanSummary = value => value !== null && typeof value === 'object' && Array.isArray(value.waves)
1111
1112/** A `recorded` block as the run program states it: three lists of ids. */
1113const isRecordedIds = value =>
1114 value !== null &&
1115 typeof value === 'object' &&
1116 ['ok', 'failed', 'notAttempted'].every(list => Array.isArray(value[list]))
1117
1118/** The summary's wave at a position, as a failure record names it: its group and its kind. */
1119function waveAt(plan, index) {
1120 if (!plan || !isInt(index)) return { wave: null, waveKind: null }
1121 const wave = plan.waves[index]
1122 if (wave && typeof wave === 'object') return { wave: wave.group ?? null, waveKind: str(wave.kind) }
1123 return plan.testWave && index === plan.waves.length ? { wave: null, waveKind: 'test' } : { wave: null, waveKind: null }
1124}
1125
1126/**
1127 * What the wave board keeps from a step (draw-the-wave-board-in-the-meter-pane
1128 * design D6). A `plan` or `recorded` without the shape the run program states
1129 * is named once per run on the debug log and ignored; the rest of the step
1130 * applies. The recorded ids are taken before the step's own position, because
1131 * the step record-batch returns already names the next batch.
1132 */
1133function takeBoard($, record) {
1134 if (record.plan !== undefined) {
1135 if (isPlanSummary(record.plan)) run.plan = record.plan
1136 else if (!run.planNamed) {
1137 run.planNamed = true
1138 $.ui.log(`interlock meter: a step's plan is ${shapeOf(record.plan)}, not a plan summary; ignored, the board keeps what it held`, {
1139 to: 'debug'
1140 })
1141 }
1142 }
1143 if (record.recorded !== undefined) {
1144 if (isRecordedIds(record.recorded)) {
1145 for (const list of ['ok', 'failed', 'notAttempted']) {
1146 for (const id of record.recorded[list]) {
1147 if (!str(id) || run.recorded[list].includes(id)) continue
1148 run.recorded[list].push(id)
1149 if (list === 'failed') run.failedAt.set(id, waveAt(run.plan, run.dispatched && run.dispatched.waveIndex))
1150 }
1151 }
1152 } else if (!run.recordedNamed) {
1153 run.recordedNamed = true
1154 $.ui.log(
1155 `interlock meter: a step's recorded is ${shapeOf(record.recorded)}, not three id lists; ignored, the board keeps the ids it held`,
1156 { to: 'debug' }
1157 )
1158 }
1159 }
1160 if (isInt(record.waveIndex)) {
1161 const at = { waveIndex: record.waveIndex, batchIndex: isInt(record.batchIndex) ? record.batchIndex : null }
1162 if (BATCH_ACTIONS.has(record.action)) {
1163 run.cursor = { ...at, phase: 'batch' }
1164 run.dispatched = at
1165 } else if (record.action === 'verify') {
1166 run.cursor = { ...at, phase: 'verify' }
1167 const reason = str(record.reason)
1168 const seen = run.skips.some(skip => skip.waveIndex === at.waveIndex && skip.reason === reason)
1169 if (record.skipped === true && !seen) run.skips.push({ waveIndex: at.waveIndex, wave: record.wave ?? null, reason })
1170 }
1171 }
1172 // The close record repeats the action without the reason; the halt step's stands.
1173 if (record.action === 'halt') run.halt = { reason: str(record.reason) || (run.halt ? run.halt.reason : null) }
1174}
1175
1176/**
1177 * One step as the timeline draws it, its fields the record's own: the time the
1178 * stamp read, its position, a skip or halt reason, the size of a plan summary
1179 * it carried, the agent whose Bash call printed it, and the spawns it named.
1180 */
1181function noteStep(record, relayId, spawns) {
1182 const step = {
1183 n: run.steps.length,
1184 at: run.stampedAt,
1185 action: record.action,
1186 wave: record.wave,
1187 waveIndex: record.waveIndex,
1188 batchIndex: record.batchIndex,
1189 batchCount: record.batchCount,
1190 skipped: record.skipped,
1191 reason: record.reason,
1192 planWaves: isPlanSummary(record.plan) ? planWaveCount(record.plan) : null,
1193 relayId: str(relayId),
1194 spawns
1195 }
1196 run.steps.push(step)
1197 if (BATCH_ACTIONS.has(record.action) && isInt(record.waveIndex) && isInt(record.batchIndex)) {
1198 const at = `${record.waveIndex}:${record.batchIndex}`
1199 if (!run.batchAt.has(at)) run.batchAt.set(at, step.at)
1200 }lib/draw-plan.mjs 516 lines1// The wave board and the Mermaid plan (draw-wave-plan-and-handoff-graph-from-the-cli,
2// spec ship/diagrams): a plan drawn as lines, with an optional overlay from the
3// wave state.
4//
5// Every word on the board is one field of one record. Waves are keyed by
6// position, never by group: dependency layering emits a later layer under the
7// same section number, so a board keyed by group would fold two waves into one.
8// Lanes are named by `lib/lane.mjs`, the rule their spawn titles, briefing files
9// and trajectory lines are named by. Where the state does not force an
10// attribution — a skip recorded by group over two waves of that group, a
11// failure id no lane carries — the board says so rather than guess.
12//
13// Pure and Node-free: no file, no environment, no terminal, no clock. The CLI
14// reads the plan and the state and resolves the width; the ship meter's hooks
15// module can import this file because its closure is `lib/lane.mjs` and
16// `lib/limits.mjs` only (`test/spine/draw-plan.test.mjs` walks it). The widths
17// are `interlock limits`'s.
18
19import { TITLE_SEPARATOR, fitRow, laneEffort, laneGist, laneLabel, laneModel, laneTier, laneTitle } from './lane.mjs'
20import { LIMITS } from './limits.mjs'
21
22/** The words a lane's state cell may read, each the state's own record. */
23export const STATE_WORDS = Object.freeze(['ok', 'failed', 'current', 'pending', 'not reached', 'not recorded'])
24
25const [OK, FAILED, CURRENT, PENDING, NOT_REACHED, NOT_RECORDED] = STATE_WORDS
26const PER_TASK = 'per task'
27const TAIL = 'then: verify-final → commit → close'
28
29// Cell widths, so a board's columns align: the longest model name, the longest
30// effort word (`inherit`) and the longest state word (`not recorded`).
31const MODEL_CELL = 6
32const EFFORT_CELL = 7
33const STATE_CELL = 12
34
35const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
36const list = value => (Array.isArray(value) ? value : [])
37const isText = value => typeof value === 'string' && value !== ''
38const plural = (n, word) => `${n} ${word}${n === 1 ? '' : /(ch|sh|s|x)$/.test(word) ? 'es' : 's'}`
39
40/** A width the board draws at: a positive integer, else the published default. */
41function boardWidth(columns) {
42 return Number.isInteger(columns) && columns > 0 ? columns : LIMITS.waveBoardDefaultColumns
43}
44
45/** A lane as drawn: an array of task objects, never empty. */
46function lanesOfBatch(batch) {
47 return list(batch)
48 .map(lane => list(lane).filter(isObject))
49 .filter(lane => lane.length > 0)
50}
51
52/**
53 * The plan's positions: every wave holding a batch, in plan order, then the
54 * test wave — the waves `createRunState` keeps, so position `i` here is
55 * `state.waves[i]` there.
56 */
57function positionsOf(plan) {
58 if (!isObject(plan)) return []
59 const waves = list(plan.waves).filter(isObject).map(wave => ({ wave, test: false }))
60 if (isObject(plan.testWave)) waves.push({ wave: plan.testWave, test: true })
61 return waves
62 .map(({ wave, test }) => ({
63 test,
64 group: wave.group ?? null,
65 // A plan written before waves carried a kind is an implementation plan.
66 kind: test ? 'test' : wave.kind === 'test' ? 'test' : 'impl',
67 red: wave.red === true,
68 batches: list(wave.batches).map(lanesOfBatch).filter(batch => batch.length > 0)
69 }))
70 .filter(position => position.batches.length > 0)
71 .map((position, index) => ({ ...position, index }))
72}
73
74/** The text a wave's top rule carries. */
75function waveTitle(position) {
76 const batches = plural(position.batches.length, 'batch')
77 if (position.test) return `test wave · idx ${position.index} · test · ${batches}`
78 const group = position.group === null ? '?' : position.group
79 return (
80 `wave ${position.index + 1} · idx ${position.index} · group ${group} · ${position.kind} · ${batches}` +
81 (position.red ? ' · RED' : '')
82 )
83}
84
85/**
86 * The ids a lane was ordered after: the union of the `after` ids of the plan's
87 * own deferral records for the lane's tasks, minus the lane's own ids, in
88 * record order. Never recomputed from a task's `dependsOn`.
89 */
90function orderedAfter(lane, deferred) {
91 const own = new Set(lane.map(task => task.id))
92 const out = []
93 for (const record of deferred) {
94 if (!own.has(record.id)) continue
95 for (const id of list(record.after)) if (isText(id) && !own.has(id) && !out.includes(id)) out.push(id)
96 }
97 return out
98}
99
100/** A skip that carries the wave position its verify step ran at. */
101const isPositioned = skip => Number.isInteger(skip.waveIndex) && skip.waveIndex >= 0
102
103/** What the overlay can say, read once from the state. */
104function overlayOf(state, positions) {
105 if (!isObject(state)) return null
106 const stateWaves = list(state.waves)
107 const cursor = isObject(state.cursor) ? state.cursor : {}
108 const halt = isObject(state.halt) ? state.halt : null
109 return {
110 runId: isText(state.runId) ? state.runId : null,
111 waveCount: stateWaves.length,
112 // Applied by position only when the state walks the plan's own positions.
113 positional: stateWaves.length === positions.length,
114 completed: new Set(list(state.completed).filter(isText)),
115 failures: list(state.failures).filter(f => isObject(f) && isText(f.id)),
116 skips: list(state.skippedVerifications).filter(isObject),
117 positionedSkips: list(state.skippedVerifications)
118 .filter(skip => isObject(skip) && isPositioned(skip))
119 .map(skip => ({ index: skip.waveIndex, reason: isText(skip.reason) ? skip.reason : 'no reason recorded' })),
120 unresolved: list(state.unresolved).filter(isObject),
121 cursor: {
122 wave: Number.isInteger(cursor.waveIndex) ? cursor.waveIndex : null,
123 batch: Number.isInteger(cursor.batchIndex) ? cursor.batchIndex : null,
124 phase: typeof cursor.phase === 'string' ? cursor.phase : null
125 },
126 halted: halt !== null,
127 haltReason: halt && isText(halt.reason) ? halt.reason : null
128 }
129}
130
131/** The word the state records for one task at `position`, `batch`; '' for none. */
132function taskWord(overlay, id, position, batch) {
133 if (overlay.failures.some(f => f.id === id)) return FAILED
134 if (overlay.completed.has(id)) return OK
135 const { cursor } = overlay
136 if (!overlay.positional || cursor.wave === null) return ''
137 const inBatch = cursor.phase === 'batch'
138 if (position < cursor.wave || (position === cursor.wave && (!inBatch || (cursor.batch !== null && batch < cursor.batch)))) {
139 return NOT_RECORDED
140 }
141 if (position === cursor.wave && inBatch && batch === cursor.batch) return CURRENT
142 return overlay.halted ? NOT_REACHED : PENDING
143}
144
145/** A lane's state cell and ids cell: one word when its tasks agree, else per task. */
146function laneCells(overlay, lane, position, batch) {
147 const ids = lane.map(task => task.id)
148 if (!overlay) return { word: null, ids: ids.length > 1 ? ids.join(', ') : null, tasks: null }
149 const words = lane.map(task => taskWord(overlay, task.id, position, batch))
150 const tasks = ids.map((id, i) => ({ id, word: words[i] }))
151 if (words.every(word => word === words[0])) {
152 return { word: words[0], ids: ids.length > 1 ? ids.join(', ') : null, tasks }
153 }
154 return { word: PER_TASK, ids: ids.map((id, i) => (words[i] ? `${id} ${words[i]}` : id)).join(', '), tasks }
155}
156
157/**
158 * The overlay's text for each verify boundary (boundary `i` sits between
159 * position `i` and `i + 1`), plus what it could not place.
160 *
161 * Skips and unresolved checks are recorded by group, so they are placed by
162 * group: on the one boundary whose left wave carries that group, or, when two
163 * or more do, as an ambiguity on the first that says which boundaries the state
164 * does not tell apart. The cursor is not used to break the tie.
165 */
166function verifyTexts(overlay, positions) {
167 const texts = positions.slice(0, -1).map(() => [])
168 const unplaced = []
169 if (!overlay || !overlay.positional) return { texts, unplaced }
170 const { cursor } = overlay
171 const after = overlay.halted ? NOT_REACHED : PENDING
172 if (cursor.wave !== null) {
173 texts.forEach((text, i) => {
174 if (i === cursor.wave && cursor.phase === 'verify') text.push(CURRENT)
175 else if (i >= cursor.wave) text.push(after)
176 })
177 }
178
179 const groups = []
180 const byGroup = new Map()
181 const entry = group => {
182 if (!byGroup.has(group)) {
183 byGroup.set(group, { skips: [], unresolved: [] })
184 groups.push(group)
185 }
186 return byGroup.get(group)
187 }
188 for (const skip of overlay.skips.filter(skip => !isPositioned(skip))) {
189 entry(skip.wave ?? null).skips.push(isText(skip.reason) ? skip.reason : 'no reason recorded')
190 }
191 for (const u of overlay.unresolved) {
192 entry(u.wave ?? null).unresolved.push(`unresolved after ${Number.isInteger(u.attempts) ? u.attempts : '?'} attempts`)
193 }
194
195 // A skip the overlay recorded with its wave position — the ship meter's,
196 // read off the verify step (draw-the-wave-board-in-the-meter-pane D6) — is
197 // placed by it: the position says which boundary, so no group is guessed.
198 const touched = new Set()
199 for (const { index, reason } of overlay.positionedSkips) {
200 if (index < texts.length) {
201 texts[index].push(`skipped: ${reason}`)
202 touched.add(index)
203 } else unplaced.push(` unplaced: skip at idx ${index} · no verify boundary follows that position · ${reason}`)
204 }
205 for (const group of groups) {
206 const { skips, unresolved } = byGroup.get(group)
207 const recorded = [...skips.map(reason => `skipped: ${reason}`), ...unresolved]
208 const boundaries = texts.map((_, i) => i).filter(i => positions[i].group === group)
209 if (boundaries.length === 1) {
210 texts[boundaries[0]].push(...recorded)
211 touched.add(boundaries[0])
212 continue
213 }
214 const counted = [
215 ...(skips.length ? [`${skips.length} skip${skips.length === 1 ? '' : 's'}`] : []),
216 ...(unresolved.length ? [`${unresolved.length} unresolved`] : [])
217 ].join(' and ')
218 const reasons = [...skips, ...unresolved]
219 if (boundaries.length === 0) {
220 unplaced.push(` unplaced: ${counted} for group ${group} · no boundary carries that group · ${reasons.join(' · ')}`)
221 continue
222 }
223 const [first, ...later] = boundaries
224 const named = boundaries.map(i => `idx ${i}`)
225 const which = `${named.slice(0, -1).join(', ')} or ${named.at(-1)}`
226 texts[first].push(`${counted} for group ${group} · state does not say ${which}`, ...reasons)
227 touched.add(first)
228 for (const i of later) {
229 texts[i].push(`group ${group} skips: see idx ${first}`)
230 touched.add(i)
231 }
232 }
233
234 // A check that passed leaves no record, so a reached boundary with nothing
235 // recorded says exactly that, never `passed`.
236 if (cursor.wave !== null) {
237 texts.forEach((text, i) => {
238 if (i < cursor.wave && !touched.has(i)) text.push('no skip recorded')
239 })
240 }
241 return { texts, unplaced }
242}
243
244/** Each failure whose id no planned lane carries, by the wave the state recorded. */
245function unplacedFailures(overlay, planned) {
246 if (!overlay) return []
247 return overlay.failures
248 .filter(f => !planned.has(f.id))
249 .map(f => {
250 const where = `wave ${f.wave ?? '?'}${isText(f.waveKind) ? ` ${f.waveKind}` : ''}`
251 const error = isText(f.error) ? `error: ${f.error}` : 'no error recorded'
252 return ` unplaced: ${f.id} · ${where} · ${error}`
253 })
254}
255
256/** The overlay's part of the header (and of the Mermaid source comment). */
257function overlayHeader(overlay, positions, stateNote, { short = false } = {}) {
258 if (!overlay) return `plan only${isText(stateNote) ? ` (${stateNote})` : ''}`
259 if (!overlay.positional) {
260 return short
261 ? 'overlay by task id only'
262 : `overlay by task id only: state has ${overlay.waveCount} waves, plan has ${positions.length}`
263 }
264 const run = `run ${overlay.runId ? overlay.runId.slice(0, 8) : '?'}`
265 if (short) return run
266 const { cursor } = overlay
267 const at =
268 cursor.wave === null
269 ? ' · cursor not recorded'
270 : ` · cursor idx ${cursor.wave}${cursor.phase === 'batch' && cursor.batch !== null ? ` b${cursor.batch}` : ''}` +
271 (cursor.phase === 'verify' ? ' · verify' : '')
272 return `${run}${at}${overlay.halted ? ' · halted' : ''}`
273}
274
275/** Every lane of every position, with what a row or a node draws of it. */
276function lanesOf(positions, plan) {
277 const deferred = list(isObject(plan) ? plan.deferred : null).filter(r => isObject(r) && isText(r.id))
278 const out = []
279 for (const position of positions) {
280 position.batches.forEach((batch, b) => {
281 for (const lane of batch) {
282 const label = laneLabel(lane)
283 const title = laneTitle(lane)
284 const tier = laneTier(lane)
285 out.push({
286 lane,
287 position: position.index,
288 batch: b,
289 label,
290 title,
291 gist: laneGist(lane),
292 model: laneModel(lane),
293 tier: tier > 0 ? String(tier) : '?',
294 effort: laneEffort(lane) ?? 'inherit',
295 after: orderedAfter(lane, deferred)
296 })
297 }
298 })
299 }
300 return out
301}
302
303/** A top rule: its text, then `─` to exactly the width. */
304function topRule(text, width) {
305 const head = `┌─ ${text} `
306 const length = [...head].length
307 return length >= width ? fitRow(head, width) : `${head}${'─'.repeat(width - length)}`
308}
309
310/**
311 * The plan as rows of `{ key, text }`: `header`, `wave:<i>`, `lane:<label>`,
312 * `wave:<i>:end`, `verify:<i>`, `unplaced:<n>`, `tail`. Lane and wave-header
313 * rows also carry `parts`, so a drawer can colour a state word without
314 * searching the cut line; `text` is still the CLI line.
315 */
316function boardRows(plan, opts) {
317 const width = boardWidth(opts.columns)
318 if (width < LIMITS.waveBoardMinColumns) {
319 return [{ key: 'header', text: `wave board needs at least ${LIMITS.waveBoardMinColumns} columns; ${width} given` }]
320 }
321 const positions = positionsOf(plan)
322 const overlay = overlayOf(opts.state, positions)
323 const lanes = lanesOf(positions, plan)
324 const planned = new Set(lanes.flatMap(l => l.lane.map(task => task.id)))
325 const notes = new Map(Object.entries(isObject(opts.notes) ? opts.notes : {}).filter(([, text]) => isText(text)))
326 const mode = overlayHeader(overlay, positions, opts.stateNote)
327 const rows = []
328 const push = (key, text, parts) => {
329 const row = { key, text: fitRow(text, width) }
330 if (parts) row.parts = parts
331 rows.push(row)
332 }
333
334 push(
335 'header',
336 positions.length === 0
337 ? `plan · holds no waves · ${mode}`
338 : `plan · ${plural(positions.length, 'wave')} · ${plural(planned.size, 'task')} · ${mode}`
339 )
340
341 const labelCell = Math.max(0, ...lanes.map(l => l.label.length))
342 const batchCell = Math.max(0, ...lanes.map(l => `b${l.batch}`.length))
343 const { texts, unplaced } = verifyTexts(overlay, positions)
344 for (const position of positions) {
345 if (position.index > 0) {
346 const i = position.index - 1
347 push(`verify:${i}`, [` verify after idx ${i}`, ...texts[i]].join(' · '))
348 }
349 const title = waveTitle(position)
350 push(`wave:${position.index}`, topRule(title, width), { title })
351 for (const l of lanes.filter(l => l.position === position.index)) {
352 const { word, ids, tasks } = laneCells(overlay, l.lane, l.position, l.batch)
353 const cells = [
354 '│',
355 `b${l.batch}`.padEnd(batchCell),
356 l.label.padEnd(labelCell),
357 l.model.padEnd(MODEL_CELL),
358 `T${l.tier}`,
359 l.effort.padEnd(EFFORT_CELL)
360 ]
361 // A note is what a host observed of this lane, appended verbatim after the
362 // state word; the gist after it gives way first when the row is cut.
363 const note = notes.get(l.label)
364 if (overlay) cells.push(note ? `${word || ''} ${note}`.trimStart() : (word || '').padEnd(STATE_CELL))
365 else if (note) cells.push(note)
366 if (ids) cells.push(`[${ids}]`)
367 if (l.after.length) cells.push(`←${l.after.join(',')}`)
368 const head = cells.join(' ')
369 push(`lane:${l.label}`, l.gist ? `${head}${TITLE_SEPARATOR}${l.gist}` : head.trimEnd(), {
370 batch: `b${l.batch}`,
371 label: l.label,
372 model: l.model,
373 tier: `T${l.tier}`,
374 effort: l.effort,
375 state: word,
376 gist: l.gist,
377 note: note || '',
378 ids: ids || '',
379 after: l.after,
380 tasks
381 })
382 }
383 push(`wave:${position.index}:end`, `└${'─'.repeat(width - 1)}`)
384 }
385
386 const spoken = [...unplacedFailures(overlay, planned), ...unplaced]
387 spoken.forEach((text, n) => push(`unplaced:${n}`, text))
388 const halted = overlay && overlay.halted ? ` · halted${overlay.haltReason ? `: ${overlay.haltReason}` : ''}` : ''
389 push('tail', `${TAIL}${halted}`)
390 return rows
391}
392
393/**
394 * The wave board as keyed rows, for a drawer that keys what it draws — the ship
395 * meter's pane (draw-the-wave-board-in-the-meter-pane design D7, D10). Keys:
396 * `header`, `wave:<i>`, `lane:<label>` (the label its spawn, briefing and
397 * trajectory line carry), `wave:<i>:end`, `verify:<i>`, `unplaced:<n>` and
398 * `tail`. Below the published minimum width, the one spoken row, keyed
399 * `header`: a board always ends in `tail`, and the spoken line never does.
400 *
401 * `opts.notes` maps a lane label to text a host observed of that lane; it is
402 * appended verbatim after the lane's state word and cut with the row. A label
403 * no lane carries is drawn nowhere.
404 *
405 * @param {unknown} plan what `planWaves` emits, or a plan summary; any value draws
406 * @param {{columns?: number, state?: object|null, stateNote?: string, notes?: Record<string, string>}} [opts]
407 * @returns {{key: string, text: string, parts?: object}[]}
408 */
409export function drawPlanBoardRows(plan, opts = {}) {
410 return boardRows(plan, isObject(opts) ? opts : {})
411}
412
413/**
414 * The wave board: one bordered block per wave position, one row per lane, a
415 * verify cell at each boundary and a tail, every line at most `opts.columns`
416 * code points. Below the published minimum width, one spoken line. The texts
417 * of `drawPlanBoardRows`, in order.
418 *
419 * @param {unknown} plan what `planWaves` emits; any value draws, a non-plan as no waves
420 * @param {{columns?: number, state?: object|null, stateNote?: string, notes?: Record<string, string>}} [opts]
421 * @returns {string[]}
422 */
423export function drawPlanBoard(plan, opts = {}) {
424 return drawPlanBoardRows(plan, opts).map(row => row.text)
425}
426
427/** A Mermaid label, quoted: `"` is the one character a quoted label cannot hold. */
428const label = text => `"${String(text).replace(/"/g, '#quot;')}"`
429
430/** Node ids from lane labels, so the same plan renders to the same text. */
431function laneIds(lanes) {
432 const used = new Map()
433 return lanes.map(l => {
434 const base = `L${l.label.replace(/\./g, '_').replace(/\+/g, 'p').replace(/[^A-Za-z0-9_]/g, '_')}`
435 const n = (used.get(base) ?? 0) + 1
436 used.set(base, n)
437 return n === 1 ? base : `${base}_${n}`
438 })
439}
440
441/**
442 * The plan as a Mermaid `flowchart LR`: a subgraph per wave position (and per
443 * batch of a multi-batch wave), a node per lane, dotted `dependsOn` edges from
444 * the plan's deferral records, hexagon verify gates and subroutine closing
445 * gates. Never cut, and never styled.
446 *
447 * @param {unknown} plan
448 * @param {{state?: object|null, stateNote?: string, source?: string}} [opts]
449 * @returns {string[]}
450 */
451export function drawPlanMermaid(plan, opts = {}) {
452 const options = isObject(opts) ? opts : {}
453 const positions = positionsOf(plan)
454 const overlay = overlayOf(options.state, positions)
455 const lanes = lanesOf(positions, plan)
456 const ids = laneIds(lanes)
457 const source = isText(options.source) ? options.source : 'plan'
458 const out = ['flowchart LR', ` %% source: ${source} · ${overlayHeader(overlay, positions, options.stateNote, { short: true })}`]
459
460 const node = (l, i, indent) => {
461 const { word, ids: cell } = laneCells(overlay, l.lane, l.position, l.batch)
462 const state = word === PER_TASK ? ` · ${PER_TASK} [${cell}]` : word ? ` · ${word}` : ''
463 return `${indent}${ids[i]}[${label(`${l.title} · ${l.model} T${l.tier} ${l.effort}${state}`)}]`
464 }
465
466 for (const position of positions) {
467 out.push(` subgraph W${position.index}[${label(waveTitle(position))}]`)
468 const members = lanes.map((l, i) => ({ l, i })).filter(({ l }) => l.position === position.index)
469 if (position.batches.length === 1) {
470 for (const { l, i } of members) out.push(node(l, i, ' '))
471 } else {
472 position.batches.forEach((_, b) => {
473 out.push(` subgraph W${position.index}B${b}[${label(`b${b}`)}]`)
474 for (const { l, i } of members.filter(({ l }) => l.batch === b)) out.push(node(l, i, ' '))
475 out.push(' end')
476 })
477 out.push(` ${position.batches.map((_, b) => `W${position.index}B${b}`).join(' --> ')}`)
478 }
479 out.push(' end')
480 }
481
482 const { texts } = verifyTexts(overlay, positions)
483 const chain = []
484 for (const position of positions) {
485 if (position.index > 0) {
486 const i = position.index - 1
487 chain.push(`V${i}{{${label([`verify after idx ${i}`, ...texts[i]].join(' · '))}}}`)
488 }
489 chain.push(`W${position.index}`)
490 }
491 chain.push(`VF[[${label('verify-final')}]]`, `C[[${label('commit')}]]`, `X[[${label('close')}]]`)
492 out.push(` ${chain.join(' --> ')}`)
493
494 const laneOf = new Map()
495 lanes.forEach((l, i) => {
496 for (const task of l.lane) if (!laneOf.has(task.id)) laneOf.set(task.id, ids[i])
497 })
498 const seen = new Set()
499 const deferred = list(isObject(plan) ? plan.deferred : null).filter(r => isObject(r) && isText(r.id))
500 for (const record of deferred) {
501 for (const after of list(record.after).filter(isText)) {
502 const from = laneOf.get(after)
503 const to = laneOf.get(record.id)
504 let line
505 if (!to) line = ` %% dependsOn ${record.id} ← ${after}: ${record.id} is in no lane of this plan`
506 else if (!from) line = ` %% dependsOn ${record.id} ← ${after}: ${after} is in no lane of this plan`
507 else if (from === to) continue
508 else line = ` ${from} -. dependsOn .-> ${to}`
509 if (seen.has(line)) continue
510 seen.add(line)
511 out.push(line)
512 }
513 }
514 return out
515}
516lib/launch-rule.mjs 175 lines1// The launch rule: what a ship launch is, what a human prompt is, and whether
2// the next launch has a human behind it (guard-ship-relaunch design D1, D3;
3// guard-ship-relaunch-in-process design D1).
4//
5// The one recorded twenty-agent mistake was a parent chat calling Workflow again
6// over leftover checkboxes, with no human message in between. The skill forbids
7// it in prose; this is the rule that lets a hook refuse it: a launch newer than
8// the session's last human prompt means the next launch has no human behind it.
9//
10// ONE RULE, TWO TRANSPORTS. Two guards read this module: the settings hook
11// (`hooks/guard-relaunch.mjs`, through `lib/launch-ledger.mjs`, which keeps the
12// record in a file per session and re-exports everything here unchanged) and
13// the hooks module (`hooks/mod.mjs`, which keeps the same record in the
14// engine's session state). The decision and its words are defined once, so a
15// reword of the skill sentence moves both guards and both pins together.
16//
17// NO NODE. The hooks module runs in the engine with no Node, so this file
18// imports nothing but the published age, and `test/spine/launch-ledger.test.mjs`
19// pins that. A record here is plain data: `{ schema, launches: [{ at, runId,
20// workflowName, scriptPath }], lastHumanPromptAt }`, times as ISO strings.
21//
22// EVERY UNKNOWN ALLOWS. A launch time that does not parse is no launch, a
23// record that is not one is empty, an age past `LIMITS.launchLedgerMaxAgeMs` is
24// absent. A false refusal costs one typed message; a rule whose own parse
25// error blocked a launch would be the worse failure.
26
27import { LIMITS } from './limits.mjs'
28
29export const LEDGER_SCHEMA = 'interlock.launch-ledger/1'
30
31/**
32 * The skill sentence the deny quotes, verbatim, so one string is pinned in both
33 * places: `test/hooks.test.mjs` asserts `skills/ship/SKILL.md` still contains it.
34 */
35export const SKILL_QUOTE = 'Leftover `- [ ]` boxes after a run are a report, not authorization to call Workflow again'
36
37/** The leading marker of the host's completion wake (guard-ship-relaunch design D4, task-1 capture). */
38export const WAKE_MARKER = '<task-notification>'
39
40// The plugin's own ship workflow, by either handle the host passes: the script
41// path the skill trampoline names, or the command name the manifest's
42// `workflows` entry registers (`interlock:ship`, possibly marketplace-prefixed).
43const SHIP_SCRIPT = /(^|\/)workflows\/ship\.js$/
44const SHIP_NAME = /(^|[^A-Za-z0-9_])interlock:ship$/
45const LAUNCHED = new Set(['async_launched', 'remote_launched'])
46
47const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
48const posix = path => path.replace(/\\/g, '/')
49const str = value => (typeof value === 'string' && value ? value : null)
50const timeOf = launch => (isObject(launch) && typeof launch.at === 'string' ? Date.parse(launch.at) : NaN)
51const isRecord = value => isObject(value) && Array.isArray(value.launches)
52
53/**
54 * Is this Workflow input a launch of the plugin's ship workflow? A call
55 * carrying `resumeFromRunId` is still a launch: a resume replays every agent
56 * after the failed one. With the session's record, a call that resumes a run it
57 * recorded — by `runId`, or by the persisted `scriptPath` the completion wake
58 * suggests passing back — is one too, though it names neither handle above.
59 */
60export function isShipLaunch(toolInput, ledger = null) {
61 if (!isObject(toolInput)) return false
62 const scriptPath = typeof toolInput.scriptPath === 'string' ? posix(toolInput.scriptPath) : ''
63 if (scriptPath && SHIP_SCRIPT.test(scriptPath)) return true
64 if (typeof toolInput.name === 'string' && SHIP_NAME.test(toolInput.name)) return true
65 if (!isRecord(ledger)) return false
66 return ledger.launches.some(
67 launch =>
68 isObject(launch) &&
69 ((str(launch.runId) && toolInput.resumeFromRunId === launch.runId) ||
70 (str(launch.scriptPath) && scriptPath && scriptPath === posix(launch.scriptPath)))
71 )
72}
73
74/**
75 * Did the runtime accept this launch? Positive, not negative: only a response
76 * object whose `status` says it launched, carrying no error mark, counts. The
77 * capture found a refused launch never reaches PostToolUse at all — the engine
78 * rejects it at input validation — so this is the second line, and anything it
79 * cannot recognise records nothing, which is the allow direction.
80 */
81export function isAcceptedLaunch(toolResponse) {
82 if (!isObject(toolResponse)) return false
83 if (toolResponse.is_error === true || toolResponse.isError === true || toolResponse.error !== undefined) return false
84 return LAUNCHED.has(toolResponse.status)
85}
86
87/**
88 * A prompt a person sent, as opposed to the host's completion wake, read off
89 * the prompt's text: the settings form's test, which has no origin to read. No
90 * text is still a prompt. The hooks module reads the engine's stamped origin
91 * instead (guard-ship-relaunch-in-process design D3).
92 */
93export function isHumanPrompt(prompt) {
94 if (typeof prompt !== 'string') return true
95 return !prompt.trimStart().startsWith(WAKE_MARKER)
96}
97
98/** The newest launch with a readable time, or null. */
99export function newestLaunch(ledger) {
100 if (!isRecord(ledger)) return null
101 let newest = null
102 for (const launch of ledger.launches) {
103 const ms = timeOf(launch)
104 if (Number.isFinite(ms) && (!newest || ms > newest.ms)) newest = { at: launch.at, ms }
105 }
106 return newest
107}
108
109/** `lastHumanPromptAt` as milliseconds: null when none was recorded, NaN when it cannot be read. */
110export function promptMs(ledger) {
111 if (ledger.lastHumanPromptAt === null || ledger.lastHumanPromptAt === undefined) return null
112 return typeof ledger.lastHumanPromptAt === 'string' ? Date.parse(ledger.lastHumanPromptAt) : NaN
113}
114
115/** A record with no launch and no prompt: what a session starts from. A new object on every call. */
116export function emptyRecord() {
117 return { schema: LEDGER_SCHEMA, launches: [], lastHumanPromptAt: null }
118}
119
120/**
121 * The record with one more launch. Launches older than the published age
122 * (measured back from this one) and launches with no readable time are
123 * dropped, so the record stays bounded in either transport. Anything that is
124 * not a record starts from `emptyRecord()`. The input is never mutated.
125 */
126export function withLaunch(record, launch, maxAgeMs = LIMITS.launchLedgerMaxAgeMs) {
127 const base = isRecord(record) ? record : emptyRecord()
128 const ms = timeOf(launch)
129 const kept = base.launches.filter(prior => {
130 const at = timeOf(prior)
131 return Number.isFinite(at) && (!Number.isFinite(ms) || ms - at <= maxAgeMs)
132 })
133 return { ...base, launches: [...kept, launch] }
134}
135
136/**
137 * The record with a human prompt at `at` (an ISO time). Keeps the later of the
138 * recorded time and `at`: an earlier clock never moves the prompt back. Anything
139 * that is not a record starts from `emptyRecord()`. The input is never mutated.
140 */
141export function withPrompt(record, at) {
142 const base = isRecord(record) ? record : emptyRecord()
143 const next = typeof at === 'string' ? Date.parse(at) : NaN
144 if (!Number.isFinite(next)) return base
145 const previous = promptMs(base)
146 if (previous !== null && Number.isFinite(previous) && previous >= next) return base
147 return { ...base, lastHumanPromptAt: at }
148}
149
150/** The deny's words (guard-ship-relaunch design D3): what happened, the skill's rule, and the remedy. */
151export function denyReason(lastLaunchAt) {
152 return (
153 `guard-relaunch: a ship workflow was already launched in this session at ${lastLaunchAt} ` +
154 `and no human prompt has arrived since. skills/ship/SKILL.md: "${SKILL_QUOTE}." ` +
155 `Send a new message that asks to ship the leftovers, or type /interlock:ship again, ` +
156 `and the next launch is allowed.`
157 )
158}
159
160/**
161 * The rule. No record, or a stale one → allow. A launch newer than the last
162 * human prompt — including every launch when no prompt was recorded → deny.
163 * Anything this cannot read a time from → allow.
164 */
165export function decideLaunch(ledger, now = Date.now(), maxAgeMs = LIMITS.launchLedgerMaxAgeMs) {
166 const allow = { decision: 'allow', reason: null, lastLaunchAt: null, lastHumanPromptAt: null }
167 const newest = newestLaunch(ledger)
168 if (!newest) return allow
169 const prompt = promptMs(ledger)
170 const seen = { lastLaunchAt: newest.at, lastHumanPromptAt: prompt === null ? null : ledger.lastHumanPromptAt }
171 if (now - newest.ms > maxAgeMs) return { ...allow, ...seen }
172 if (prompt !== null && (!Number.isFinite(prompt) || prompt >= newest.ms)) return { ...allow, ...seen }
173 return { decision: 'deny', reason: denyReason(newest.at), ...seen }
174}
175lib/limits.mjs 846 lines1// Every cap the ship loop obeys, in one place.
2//
3// These numbers used to live in `skills/ship/SKILL.md` as prose — "cap two
4// attempts", "cap five root-cause iterations", "more than two task failures".
5// Prose caps drift: a number written in one heading gets restated differently
6// three headings later, and nothing catches it. Worse, a model reading a cap in
7// prose treats it as guidance, and the whole point of a cap is that it is not.
8//
9// So the loop engines read them from here, the CLI prints them, and the skills
10// cite the CLI rather than restating the number. When a cap changes it changes
11// once.
12//
13// Pure: no fs, no agent, no I/O.
14// Exposed to skills as `interlock limits [--json]`.
15
16/**
17 * Ceilings that come from the dynamic-workflow runtime rather than from
18 * Interlock policy. The runtime caps concurrency at 16 and total agents at 1000
19 * per run; exceeding either is the runtime's error, not ours, so the planner
20 * clamps below them rather than discovering them the hard way.
21 * @see https://code.claude.com/docs/en/workflows
22 */
23export const RUNTIME = {
24 maxConcurrentAgents: 16,
25 maxAgentsPerRun: 1000
26}
27
28export const LIMITS = {
29 /** Agents spawned per batch. Waves wider than this are split. */
30 maxParallel: 8,
31
32 // `maxTasksPerAgent` — the single scalar lane cap — was REMOVED here rather
33 // than aliased to the tier table that replaced it (`LANE_CAPS.byTier` below).
34 // It had six readers: the planner, `makeWave`, `createRunState`, the plan
35 // fingerprint's canonical text, `formatFingerprint` and `formatLimits`. A
36 // deprecated alias would have let any one of them keep reading a scalar while
37 // the rest read the table, and the two would disagree silently about how long
38 // a lane may get — which is the drift this module exists to prevent. Removing
39 // it makes the sweep enforceable instead: a stale reader fails at import.
40
41 /**
42 * Targeted fix attempts after a failed inter-wave check, per wave. After
43 * this the errors are recorded, warned about and handed to the next wave's
44 * briefings, and the run continues — whatever the verdict said about them
45 * blocking the next wave. The final verification still gates the commit.
46 */
47 interWaveFixAttempts: 2,
48
49 /** Revisions of not-yet-executed wave groups, per run. */
50 replansPerRun: 2,
51
52 /** Review → fix → re-review cycles. Surviving blockers after this halt. */
53 remediationRounds: 2,
54
55 /**
56 * Root-cause repair iterations against a red unit suite, across the whole
57 * run. Repairing by root cause is slow by design; this bounds it before the
58 * run turns into an open-ended debugging session.
59 */
60 rootCauseIterations: 5,
61
62 /**
63 * Task failures tolerated across all waves. Strictly more than this halts —
64 * a run losing three tasks is not producing a coherent change.
65 */
66 taskFailureHalt: 2,
67
68 /**
69 * Steps one run of the ship program may take before it halts. A step is one
70 * CLI call that yields a step record; a run that has taken this many without
71 * reaching a terminal state is not converging.
72 *
73 * This was `MAX_LOOP_STEPS`, a literal restated in both drivers — a loop bound
74 * the cap-authority spec forbids stating anywhere but here. It is enforced by
75 * `lib/run.mjs`, which counts on the run manifest and returns a `halt` step
76 * naming this cap once it is exceeded. A driver's own `RUNAWAY_BACKSTOP` is a
77 * different thing: the host runtime's agent ceiling, not a policy cap.
78 */
79 maxRunSteps: 200,
80
81 // `memoryEntriesPerRun` was removed here rather than wired. It had no reader
82 // anywhere outside this file and its own value-pinning test, and memory
83 // writing is not implemented as a counted operation — so wiring it would have
84 // meant inventing an enforcement point to justify a number. A cap this module
85 // prints but nothing obeys is the same failure as a cap written in prose,
86 // which is the failure this module exists to end.
87
88 /**
89 * Soft budget for inter-wave verification. Past this, drop to typecheck only
90 * rather than letting the checks outweigh the work they guard.
91 *
92 * This is a floor, not the budget every run gets: a test profile whose
93 * `unit.timeout_ms` is a positive integer raises it to `interWaveVerifications`
94 * times that allowance (`interWaveVerifyBudget` in `lib/verify.mjs`), and
95 * nothing a profile says can lower it. A caller's explicit `--budget-ms` still
96 * overrides both.
97 */
98 interWaveVerifyBudgetMs: 60_000,
99
100 /**
101 * Combined stdout/stderr byte threshold past which a verify step's output is
102 * spilled to disk (`lib/spill.mjs`) instead of returned inline. See
103 * add-ship-run-inspectability design.md §3.
104 */
105 verifySpillBytes: 8192,
106
107 /**
108 * Character budget for a spilled step's head-and-tail preview, and the
109 * ceiling every other verify-result text field must stay under. A result
110 * field larger than this is rejected as an oversized-result leak rather than
111 * judged.
112 */
113 verifyPreviewChars: 4096,
114
115 /**
116 * Inter-wave verification checkpoints allowed per run. A wave boundary is
117 * ordering; a checkpoint is an agent. Ordering is free, so the cap is on
118 * checkpoints, not on waves. Docs-only waves skip without consuming a slot.
119 */
120 interWaveVerifications: 3,
121
122 /**
123 * Character budget for one task's wave handoff — `summary`, `next`,
124 * `blocker` and the joined `evidence` locators added together. A packet over
125 * this is rejected whole rather than truncated: silent truncation is the
126 * degradation the schema exists to forbid, and a next wave reading half a
127 * sentence is worse off than one told the report was rejected. The task that
128 * filed it stays done; the paths a rejected report hands on are held to this
129 * same cap.
130 * See add-wave-handoff-and-prompt-snapshots design.md §2.
131 */
132 maxHandoffChars: 2000,
133
134 /**
135 * Byte ceiling for the repo-root `REVIEW.md` policy file. A file larger than
136 * this is not scanned: it is reported as a problem and the run proceeds under
137 * default policy (fail-open, add-interlock-review-policy design.md D3). The
138 * bound exists so a pathological or accidental (a committed build log named
139 * `REVIEW.md`) file cannot make the policy reader do unbounded work — the same
140 * reason every other scan in this loop is bounded rather than trusting.
141 * Read by `readReviewPolicy` in `lib/review-core.mjs`.
142 */
143 maxReviewPolicyBytes: 65_536,
144
145 /**
146 * Character budget for the living-requirement text one review prompt carries
147 * in its `domain` dimension. Whole requirement blocks are added in capability
148 * then spec order until the next would exceed this; every block left out is
149 * counted in the text and named in the result, never cut mid-requirement. It
150 * bounds a prompt, not a merge decision, so it lives here and not in
151 * `MERGE_BANDS`. Read by `assembleDomainContext` in
152 * `lib/prompts/domain-context.mjs`.
153 * See judge-against-base-and-living-specs design.md D4.
154 */
155 maxDomainSpecChars: 12_000,
156
157 /**
158 * Most compound-note rows `interlock note match` prints before it names the
159 * omitted count. Read by `matchNotes` in `lib/notes.mjs`.
160 */
161 maxNoteMatchRows: 20,
162
163 /**
164 * Milliseconds a close's push to the ntfy relay may take before it is
165 * abandoned as a failed push. A hanging network call must not stall the
166 * close itself (design D5, add-harden-unattended-ship-runs). Read by
167 * `postNtfy` in `lib/notify.mjs` via `AbortController`.
168 */
169 notifyTimeoutMs: 5000,
170
171 /**
172 * Rows of any one list — leftover task ids, wave tallies, degradation banners
173 * — the halt resume card prints before it says how many it left out and names
174 * the command that prints them all. The card is a pointer a person reads in
175 * one sitting, not a second copy of the trajectory, so it is bounded; but a
176 * silent head would make it lie, so the truncation is always stated. Read by
177 * `lib/resume-card.mjs`.
178 */
179 resumeCardListRows: 40,
180
181 /**
182 * Milliseconds a session's launch ledger stays readable (guard-ship-relaunch
183 * design D5). A ledger whose newest launch is older than this reads as absent,
184 * and every ledger write sweeps sibling files past it, so the directory does
185 * not grow one file per session forever and no stale session can deny a live
186 * one. 24 hours is longer than any run `maxRunSteps` and the drivers' runaway
187 * backstop allow, so a live session's launch is never aged out while its run
188 * could still be in flight; it is shorter than the host's transcript
189 * retention, so the directory never outlives the sessions it names. Ageing out
190 * only ever turns a deny into an allow. Read by `lib/launch-ledger.mjs`.
191 */
192 launchLedgerMaxAgeMs: 24 * 60 * 60 * 1000,
193
194 /**
195 * Milliseconds a live ship run may go with no activity the engine reports
196 * (a step, a run agent's request or answer, a turn end, a spawn) before the
197 * ship meter appends `quiet <n> min` to its status line, spinner and pane
198 * (show-quiet-time-and-reset-the-meter-on-clear design D3). Longer than one
199 * model request at the deepest effort ordinarily takes to answer, so a lane
200 * that is thinking is not called quiet on the strength of one slow request;
201 * short enough that a person who looks during a run learns within one wave's
202 * time that nothing has moved. A display threshold with no verdict behind it:
203 * a wrong value costs an early or a late word, never a halt. Read by
204 * `lib/meter-quiet.mjs`, which the hooks module imports.
205 */
206 meterQuietAfterMs: 5 * 60 * 1000,
207
208 /**
209 * Milliseconds between the ship meter's recomputations of the quiet figure: the
210 * period of the one interval the hooks module asks the host for while a run is
211 * live (design D2, D3). The word is in whole minutes, so this keeps the shown
212 * minute at most this stale, at a few hundred dispatches an hour, which is
213 * nothing beside the run's own traffic. Read by `lib/meter-quiet.mjs`.
214 */
215 meterTickMs: 15 * 1000,
216
217 /**
218 * The most characters of a halt resume card the `/interlock-handoff` pane
219 * renders (show-preflight-and-interrupted-runs-at-session-start design D7).
220 * Not a choice: it is the `Markdown` element's own bound on Claude Code
221 * 2.1.286, which refuses a longer `text`. A card over it is cut with a line
222 * inside the rendered text naming the characters left out and the card's
223 * path, so the pane shows a head of the card instead of nothing. Read by
224 * `lib/preflight-file.mjs`, which the hooks module imports; restated nowhere
225 * in the module.
226 */
227 handoffPaneChars: 10_000,
228
229 /**
230 * The narrowest width, in columns, the wave board and the handoff board draw
231 * at (draw-wave-plan-and-handoff-graph-from-the-cli design D8). The fixed
232 * cells of a lane row — border, a two-digit batch, a five-character label,
233 * model, tier, effort and the longest state word — come to 41 columns, and
234 * seven more hold one ordered-after id. Below it a board would cut ids, so
235 * the renderer returns one spoken line instead. Read by `lib/draw-plan.mjs`
236 * and `lib/draw-run.mjs`.
237 */
238 waveBoardMinColumns: 48,
239
240 /**
241 * The width, in columns, a board is drawn at when neither `--columns` nor a
242 * terminal says (design D8). The widest uncut lane row of the real halted
243 * run's plan is 89 columns, so a piped board of a real plan keeps its gists.
244 * Read by both renderers, for a width they were not given, and by
245 * `bin/interlock`, which resolves the width before it draws.
246 */
247 waveBoardDefaultColumns: 100
248}
249
250/**
251 * Caps the eval suite obeys, published here so nothing restates them in
252 * `.github/workflows/evals.yml` — a cost written in workflow YAML and echoed in
253 * a skill drifts exactly like a prose cap does. The CI job reads them from
254 * `interlock limits` (add-interlock-evals design.md D8), following the same
255 * precedent the implementer prompt sets at `workflows/ship.js:194-195`.
256 *
257 * These are deliberately a separate object from LIMITS rather than more entries
258 * in it: LIMITS counts loop iterations, whereas a cost ceiling is a dollar
259 * amount. They are held to the same reader invariant all the same — the
260 * cap-authority test walks `.github/workflows/` alongside `lib/`, `bin/` and
261 * `workflows/`, and a CI reader counts when it names the published field
262 * (`evals.<cap>`) rather than the export. There is no exemption: a cap here with
263 * no reader fails the same test a cap in LIMITS would.
264 *
265 * `reportingThreshold` was removed rather than wired, following the
266 * `memoryEntriesPerRun` precedent above. It described a score at or above which
267 * a case reported as passing, but `lib/evals-triage.mjs` reads no score at all —
268 * `classifyCase` branches on each grader's `passed` boolean — so there was no
269 * path it could govern without inventing one. Publishing it told a contributor
270 * that a scoring rule existed which did not.
271 *
272 * The two cost ceilings are first guesses to be tuned from the `cost_usd` the
273 * first runs actually report (design.md D15), not numbers the specs depend on.
274 */
275export const EVAL_CAPS = {
276 /** US dollars. Ceiling for the per-pull-request smoke subset. */
277 smokeCostUsd: 2,
278
279 /** US dollars. Ceiling for the scheduled full-suite run. */
280 fullRunCostUsd: 15,
281
282 /**
283 * US dollars. Ceiling for the scheduled **outcome** eval — the one that ships
284 * a committed fixture through the real loop and grades what is on disk
285 * (`evals/ship/run.mjs`), not the transcript-grading case suite above.
286 *
287 * Its two readers exist on the day it lands, which is the whole reason it may
288 * be published at all: `evals/ship/run.mjs` reads it from `interlock limits
289 * --json` before it starts a fixture, and `.github/workflows/ship-outcome-
290 * eval.yml` reads the same field to bound the job. The number appears nowhere
291 * else — not in the workflow YAML, not in the eval's README.
292 *
293 * Enforced at fixture and arm boundaries only. It stops the runner from
294 * STARTING the next arm; it never kills a run in flight, because a
295 * half-killed run cannot be graded and would be recorded as a failure it did
296 * not earn (design D6). A sweep that reaches it is reported partial.
297 *
298 * A first guess, to be tuned from the spend the first rows actually report —
299 * the same posture as the two ceilings above.
300 */
301 shipEvalCostUsd: 20,
302
303 /**
304 * US dollars. Ceiling for one invocation of the **cost-per-task sweep**
305 * (`evals/ship/matrix.mjs`): the committed fixtures crossed with model and
306 * effort, each cell run by the control-arm procedure. A different run from the
307 * outcome eval, with its own ceiling, so neither can spend the other's budget.
308 *
309 * Its reader is the sweep, which reads it from `interlock limits --json` before
310 * starting each cell. It is run by hand and gates nothing: no workflow reads
311 * it, and no pull request starts the sweep. The number appears nowhere else.
312 *
313 * Enforced between cells only — a cell in flight is never killed, an unpriced
314 * cell adds nothing to the total, and a sweep that reaches it is partial.
315 *
316 * A first guess in the posture of `shipEvalCostUsd`: twice that ceiling, for a
317 * grid of control-arm cells rather than a handful of full loops, to be tuned
318 * from the dollars the first rows report.
319 */
320 matrixCostUsd: 40,
321
322 /**
323 * Agent runs per case. Passed as `--runs` by the full-suite job (started by
324 * hand; it carries no schedule), which overrides each case's own value: those
325 * were chosen for the fast per-change subset, and the full arm is the one that
326 * can afford repetition. The smoke job's `--runs 1` is that subset's single-run posture,
327 * not a restatement of this cap.
328 */
329 runsPerCase: 3,
330
331 // --- the promotion rule (spec: evals/promotion) --------------------------
332 //
333 // These three are the whole rule that decides whether an eval case may fail a
334 // build. They live here, with readers, for the reason the module header gives:
335 // a promotion threshold written in a specification is a sentence a reviewer
336 // re-argues once per proposal. `lib/evals-promote.mjs` reads all three by
337 // name, and nothing restates them in a skill, a spec, a doc, or the workflow
338 // YAML.
339 //
340 // Landing them WITH readers is deliberate: `runsPerCase` sat here printed and
341 // unread, and `reportingThreshold` was removed for the same reason. A fourth
342 // unread cap is the one thing this group must not gain.
343
344 /**
345 * Consecutive qualifying runs a case must pass across before it may be
346 * promoted from advisory to blocking. A run triage classified no-signal or
347 * configuration does not qualify, is named, and does not break the chain.
348 * Read by `promote()` in `lib/evals-promote.mjs`.
349 */
350 promotionRuns: 3,
351
352 /**
353 * Trials of a case a run must carry to count as evidence for promotion. Below
354 * this the run is real but too thin to prove repeatability, and the case is
355 * refused naming the run rather than promoted on it.
356 * Read by `promote()` in `lib/evals-promote.mjs`.
357 */
358 promotionTrialsPerRun: 3,
359
360 /**
361 * Minimum measured judge/human agreement, as a fraction, for each judged
362 * grader of a case being promoted. `interlock evals calibrate` measures;
363 * this is the floor it is measured against, applied only here — the
364 * calibration report itself issues no verdict.
365 *
366 * The one non-integer in this group, which is why the positive-integer
367 * invariant is over LIMITS rather than over every cap group.
368 * Read by `promote()` in `lib/evals-promote.mjs`.
369 */
370 judgeAgreementFloor: 0.8
371}
372
373/**
374 * The price table the outcome eval converts measured tokens into dollars with,
375 * so `EVAL_CAPS.shipEvalCostUsd` can be a ceiling on money rather than on a
376 * token count nobody can compare across models (design D6).
377 *
378 * A separate export from EVAL_CAPS for the reason EFFORT and LANE_CAPS are: the
379 * cap groups hold scalars a code path obeys, and this is a table. It lives here
380 * all the same, because a price written in the runner and echoed in a workflow
381 * would drift exactly like a prose cap.
382 *
383 * `id` IS THE LOAD-BEARING FIELD. It travels on every recorded result row, so a
384 * later price revision cannot silently reinterpret rows written under the old
385 * one. Revising a price therefore means a NEW id, never an edit to a number
386 * under the existing one — old rows keep meaning what they meant, and a reader
387 * comparing across a revision can see that it happened.
388 *
389 * The figures are the published list prices for each tier, in US dollars per
390 * million tokens, as of the date in the id. They are an input to a ceiling and
391 * to a recorded estimate — never to a bill, and never to a gate.
392 *
393 * A model that is not in the table yields NO cost figure: the runner records the
394 * spend as absent with that reason rather than pricing it at zero or guessing a
395 * tier from the name. An unpriced run still runs; it just cannot be counted
396 * against the ceiling, and the sweep says so.
397 *
398 * Read by `evals/ship/run.mjs` through `interlock limits --json`; printed by
399 * `formatLimits()` below.
400 */
401export const MODEL_PRICES = {
402 // A NEW id, not an edit under `anthropic-list-2026-09b`. These are the rates
403 // confirmed against the published list in October 2026 — a later list, not a
404 // revision of the September one — so rows recorded under either September id
405 // keep the id, and the meaning, they were written with. The 5.5 models replace
406 // `claude-opus-5` and `claude-sonnet-5` rather than sitting beside them: a row
407 // naming an old model is unpriced under this id, never priced at a guessed rate.
408 id: 'anthropic-list-2026-10',
409 perMillionTokens: {
410 'claude-opus-5-5': { input: 4, output: 20 },
411 'claude-sonnet-5-5': { input: 2, output: 10 },
412 'claude-haiku-4-5': { input: 1, output: 5 }
413 },
414 /**
415 * What a cached prefix costs, as multipliers on the model's own `input` rate.
416 *
417 * `read` is keyed by MODEL, by the same ids as `perMillionTokens`, because the
418 * published read multiplier is not one figure: Opus 5.5 reads at 0.05x while
419 * Sonnet 5.5 and Haiku 4.5 read at 0.1x. A model in `perMillionTokens` with no
420 * entry here is unpriced — the pricer never falls back to some other model's
421 * read multiplier.
422 *
423 * `write` is keyed by LIFETIME TIER, shared across every model the table
424 * prices, and is never flattened: a prefix written for five minutes and one
425 * written for an hour are different prices, and a total that added them could
426 * not be priced back apart. The keys are the tier names the host's usage
427 * envelope reports them under, so a recorded figure and its multiplier are
428 * looked up by the same string.
429 *
430 * Read by `priceUsage` in `evals/ship/arms.mjs`, by these names
431 * (`cacheMultipliers.read[model]`, `cacheMultipliers.write[tier]`). They live
432 * in the table rather than beside it so the two cannot drift — a run priced
433 * against one id and multiplied by a differently versioned constant is
434 * attributable to nothing.
435 */
436 cacheMultipliers: {
437 read: {
438 'claude-opus-5-5': 0.05,
439 'claude-sonnet-5-5': 0.1,
440 'claude-haiku-4-5': 0.1
441 },
442 write: { ephemeral_5m: 1.25, ephemeral_1h: 2 }
443 }
444}
445
446/**
447 * Reasoning-effort defaults for the wave planner and the two adversarial steps.
448 *
449 * Deliberately a separate object from LIMITS, exactly like EVAL_CAPS/REPORT_CAPS:
450 * LIMITS holds positive-integer iteration counts (its invariant test asserts
451 * every entry is one, and every entry must be read as `LIMITS.<cap>` by a
452 * code path). These are a tier→effort table and two fixed effort strings —
453 * neither an integer nor a loop count. Keeping them here still satisfies the one
454 * property that matters: the mapping is read from a single source and surfaced
455 * by `interlock limits`, never restated in code that can drift.
456 *
457 * `byTier` maps a lane's hardest tier to a workflow-runtime effort. `null` means
458 * "inherit the session default — do not force": tiers 3–4 inherit by policy so
459 * the run keeps whatever the session/model default is (xhigh for coding since
460 * w16); an untiered lane inherits by fallback. `verify` pins both verify
461 * checks — the inter-wave one and the final one, which one spawn site emits —
462 * and `skeptic` pins the review skeptics, regardless of any lane tier: the two
463 * steps whose whole job is catching what an implementer missed.
464 */
465export const EFFORT = {
466 byTier: { 1: 'low', 2: 'low', 3: null, 4: null, 5: 'xhigh' },
467 verify: 'xhigh',
468 skeptic: 'xhigh'
469}
470
471/**
472 * Model and effort for the subagents the prose skills spawn — the ones
473 * `/interlock:spec` and `/interlock:settle` reach — one row per role.
474 *
475 * A separate export from LIMITS for the reason `EFFORT` is: the LIMITS invariant
476 * asserts positive integers and this is a table. Ship's own spawns are not here;
477 * `lib/run.mjs` reads `EFFORT` for those.
478 *
479 * `model` is `haiku`, `sonnet`, `opus` or `null`; `effort` is a level or `null`.
480 * `null` means the parameter is omitted and the host's default applies (the
481 * session's model, the session's effort), the same meaning `EFFORT.byTier` gives
482 * it. `review-skeptic` and `settle-fixer` carry `EFFORT.skeptic` by reference —
483 * read at module load, never a second constant — so one change to the skeptic
484 * effort moves ship's review step, the review-code skeptics and the settle fixer
485 * together. A row's `strict` override applies when the review depth is `strict`
486 * (see `REVIEW_DEPTH`): `review-dimension` hands the session's model and effort
487 * back to the reviewers, as they ran before this table existed.
488 *
489 * Read by `lib/routing.mjs`; printed by `interlock limits` and emitted as
490 * `routing` by `interlock limits --json`.
491 */
492export const SPAWN_ROUTING = {
493 'explore-investigator': { model: 'sonnet', effort: 'medium' },
494 'review-dimension': { model: 'sonnet', effort: 'medium', strict: { model: null, effort: null } },
495 'review-skeptic': { model: null, effort: EFFORT.skeptic },
496 'settle-fixer': { model: null, effort: EFFORT.skeptic },
497 'settle-conformance': { model: 'sonnet', effort: null }
498}
499
500/**
501 * What a review pass runs at each depth: which dimensions are always on and how
502 * the skeptics are spawned.
503 *
504 * `dimensions` is the always-on set only. The conditional dimensions keep their
505 * own triggers at both depths — `devops` on `needsDevopsReview`, `security` on an
506 * auth, input or data surface, `domain` when `interlock domain-context` selects,
507 * `blast-radius` when the graph exists — and are not listed here.
508 *
509 * `skeptics` is `per-review` (two skeptic agents, each judging every blocker and
510 * warning) or `per-finding` (two skeptic agents per blocker and warning, each
511 * running the check the finding claims). `default` is the depth that applies
512 * when no `--strict` is given; the skills never name it.
513 *
514 * Frozen, rows included. Read by `lib/routing.mjs` and `lib/review-core.mjs`;
515 * printed by `interlock limits` and emitted as `reviewDepth` by
516 * `interlock limits --json`.
517 */
518export const REVIEW_DEPTH = Object.freeze({
519 default: 'lean',
520 lean: Object.freeze({
521 dimensions: Object.freeze(['language', 'technical-lead']),
522 skeptics: 'per-review'
523 }),
524 strict: Object.freeze({
525 dimensions: Object.freeze(['language', 'architecture', 'qa', 'technical-lead']),
526 skeptics: 'per-finding'
527 })
528})
529
530/**
531 * How long a lane may get, per tier, and which tiers may be packed together.
532 *
533 * A lane is an ordered task list one agent executes start to finish. Until this
534 * table existed the bound was one scalar for every lane in the run, which forced
535 * one number to answer two different questions: how much sequential trivia one
536 * agent may hold, and how much judgement-heavy work it may hold. Those have
537 * different answers, so this is a table.
538 *
539 * `byTier` is keyed by the lane's HARDEST task tier (`laneTier`). An untiered
540 * lane (tier 0) uses the tier-1 entry. Tier 4 keeps the old scalar's 4 —
541 * cross-file pattern-following is where a fresh context per task still pays.
542 * Tier 5 stays at 8. Chain lanes are bounded by this same table: the cap is the
543 * entry for the chain's hardest tier, packed next-fit.
544 *
545 * `opusMinTier` is the floor at which a multi-task lane (collision, cohesion or
546 * chain) dispatches on opus. Below it the lane runs on sonnet. Single-task lanes
547 * and solo promotions are not gated by this floor — see `laneModel`. The value
548 * sits next to the cohesion ceiling because both answer "how hard must the work
549 * be before this dial moves."
550 *
551 * `cohesionMaxTier` is the ceiling for COHESION: path-disjoint components in one
552 * dependency layer whose hardest tier is at or below it may be packed into one
553 * lane. Above it a component stays a lane of its own, joined only by a real path
554 * collision. Set it to 0 to disable cohesion while keeping the table.
555 *
556 * A separate export from LIMITS for the same reason `EFFORT` is: the LIMITS
557 * invariant asserts every entry is a positive integer, and `byTier` is a table.
558 * The cap-authority check covers this group all the same — every entry here must
559 * have a reader in `lib/`, `bin/` or `workflows/`.
560 *
561 * Read by `lib/waves.mjs` (lane construction, cohesion packing) and
562 * `lib/plan-fingerprint.mjs`; printed by `interlock limits` and emitted as
563 * `laneCaps` by `interlock limits --json`.
564 */
565export const LANE_CAPS = {
566 byTier: { 1: 8, 2: 8, 3: 6, 4: 4, 5: 8 },
567 cohesionMaxTier: 3,
568 /** Hardest-task tier at or above which a multi-task lane dispatches on opus. */
569 opusMinTier: 4
570}
571
572/**
573 * The envelope inside which a change may be planned as ONE lane — every task,
574 * in order, on one opus agent (`--solo`, or the classifier's recommendation).
575 *
576 * One bound, task count, on purpose. The classifier supplies the shape
577 * judgement ("this change is one coherent edit"); this supplies the ceiling.
578 * Neither restates the other, which is why the `plan-waves` prompt is forbidden
579 * from naming this number: a model that can read the bound can argue with it.
580 *
581 * A recommendation above the envelope is refused and named. An explicit `--solo`
582 * flag may exceed it — a human flag is the one input allowed to, the same way
583 * `--max-parallel` may ask for anything under the runtime ceiling — and the plan
584 * warns that it did.
585 *
586 * Read by `lib/waves.mjs` (mode decision) and `lib/plan-fingerprint.mjs`;
587 * printed by `interlock limits` and emitted as `solo` by `--json`.
588 */
589export const SOLO = {
590 maxTasks: 20
591}
592
593/**
594 * The thresholds the merge verdict applies (`interlock merge-confidence`,
595 * `lib/merge-confidence.mjs`), published here so no skill, prompt or document
596 * restates one as the rule — the reason this module exists.
597 *
598 * A separate export from LIMITS, like LANE_CAPS and EVAL_CAPS, for two reasons.
599 * `ceiling` is a table, not a positive-integer loop count, and the LIMITS
600 * invariant holds every entry to that shape. And these are not loop caps: the
601 * verdict is the worst band over every signal, and these numbers only decide
602 * which band one signal reads, or where inside its band's range a score lands.
603 *
604 * `ceiling` is the score each band may reach; a band's floor is one above the
605 * next-worse band's ceiling, and red's floor is 0. `unobserved` has no row: it
606 * takes amber's range, as it takes amber's rank for the verdict, so a fourth
607 * number would be one nobody reads. The domain-spec text cap the epic lists is
608 * deliberately absent: its reader lands with the `domain` review dimension, and a
609 * printed cap with no reader fails the cap-authority sweep.
610 *
611 * Read by `lib/merge-confidence.mjs`, which cites each key by name in the reason
612 * it applies it in; printed by `interlock limits` and emitted as `mergeBands` by
613 * `--json`. The cap-authority sweep covers the group, `ceiling` counting as one
614 * cap on the terms `LANE_CAPS.byTier` does.
615 */
616export const MERGE_BANDS = Object.freeze({
617 ceiling: Object.freeze({ green: 100, amber: 79, red: 39 }),
618
619 /** Surviving review warnings at or under this read green; one more is amber. */
620 maxWarningsForMerge: 2,
621
622 /** Skeptic verdicts a surviving blocker or warning needs before it counts as adjudicated. */
623 minVerdictsPerFinding: 2,
624
625 /** Points the project coverage total may fall below the base total and still read green. */
626 maxCoverageDeclinePts: 1,
627
628 /** Changed-line coverage, in percent, a change with no baseline must reach to read green. */
629 patchCoverageFloorPct: 80,
630
631 /** Changed lines below which coverage is not judged at all; a change of exactly this many is. */
632 minChangedLinesForCoverage: 20,
633
634 /** Changed lines, added plus deleted, above which the diff shape is amber. */
635 maxChangedLinesForMerge: 400,
636
637 /** Changed files above which the diff shape is amber. */
638 maxChangedFilesForMerge: 20
639})
640
641/**
642 * Caps for the corpus reader (`interlock report`).
643 *
644 * Not a policy ceiling like the ones above — nothing halts on it. It bounds how
645 * much of an unbounded, ever-growing corpus one invocation opens, so a
646 * repository with fifty thousand trajectories still gets a report. Reaching it
647 * is stated in the output rather than sampled silently: a truncated scan that
648 * looked complete would be worse than no report at all.
649 */
650export const REPORT_CAPS = {
651 /** Trajectory files opened in one `interlock report` invocation. */
652 maxRunsScanned: 2000
653}
654
655/**
656 * Clamp a requested parallelism to something both Interlock and the runtime
657 * will honour. A caller asking for 40 gets the runtime ceiling, not an error:
658 * over-asking is a preference, not a mistake worth failing a run over.
659 * @param {number} [requested]
660 * @returns {{value: number, clamped: boolean, reason: string|null}}
661 */
662export function clampParallel(requested) {
663 if (!Number.isInteger(requested) || requested <= 0) {
664 return { value: LIMITS.maxParallel, clamped: false, reason: null }
665 }
666 if (requested > RUNTIME.maxConcurrentAgents) {
667 return {
668 value: RUNTIME.maxConcurrentAgents,
669 clamped: true,
670 reason: `workflow runtime allows at most ${RUNTIME.maxConcurrentAgents} concurrent agents`
671 }
672 }
673 return { value: requested, clamped: false, reason: null }
674}
675
676/**
677 * Human-readable dump, so a skill can show the caps without hardcoding them.
678 *
679 * `runtimeObserved` is the concurrency this machine's runtime will honour as far
680 * as the caller could observe it (`runtimeSlotsOf` in `lib/host/claude-env.mjs`):
681 * an override from the environment, or the vendor default beside the CPU count
682 * that may reduce it. Printed beside the vendor fact, never in place of it, and
683 * read by the caller — this module still reads no environment.
684 *
685 * @param {{runtimeObserved?: {observed: number|null, source: string, cpuCount: number|null, invalid?: string}}} [opts]
686 */
687export function formatLimits({ runtimeObserved } = {}) {
688 const rows = [
689 ['max parallel agents per batch', LIMITS.maxParallel],
690 ['inter-wave fix attempts (per wave)', LIMITS.interWaveFixAttempts],
691 ['replans (per run)', LIMITS.replansPerRun],
692 ['remediation rounds', LIMITS.remediationRounds],
693 ['root-cause iterations (per run)', LIMITS.rootCauseIterations],
694 ['task failures tolerated', LIMITS.taskFailureHalt],
695 ['run steps (per run)', LIMITS.maxRunSteps],
696 ['inter-wave verify budget (floor)', `${LIMITS.interWaveVerifyBudgetMs / 1000}s`],
697 ['inter-wave verifications (per run)', LIMITS.interWaveVerifications],
698 ['verify spill threshold (bytes)', LIMITS.verifySpillBytes],
699 ['verify preview budget (chars)', LIMITS.verifyPreviewChars],
700 ['wave handoff budget (chars, per task)', LIMITS.maxHandoffChars],
701 ['review policy scan cap (bytes)', LIMITS.maxReviewPolicyBytes],
702 ['domain spec text budget (chars)', LIMITS.maxDomainSpecChars],
703 ['note match rows (max)', LIMITS.maxNoteMatchRows],
704 ['push timeout (ms)', LIMITS.notifyTimeoutMs],
705 ['resume card list rows (per list)', LIMITS.resumeCardListRows],
706 ['launch ledger max age (ms)', LIMITS.launchLedgerMaxAgeMs],
707 ['meter quiet after (ms)', LIMITS.meterQuietAfterMs],
708 ['meter tick (ms)', LIMITS.meterTickMs],
709 ['handoff pane chars', LIMITS.handoffPaneChars],
710 ['wave board min width (columns)', LIMITS.waveBoardMinColumns],
711 ['wave board default width (columns)', LIMITS.waveBoardDefaultColumns]
712 ]
713 const evalRows = [
714 ['eval smoke cost ceiling (per PR)', `$${EVAL_CAPS.smokeCostUsd}`],
715 ['eval full-run cost ceiling (scheduled)', `$${EVAL_CAPS.fullRunCostUsd}`],
716 ['eval outcome-run cost ceiling (scheduled)', `$${EVAL_CAPS.shipEvalCostUsd}`],
717 ['eval cost-per-task sweep ceiling (by hand)', `$${EVAL_CAPS.matrixCostUsd}`],
718 ['eval runs per case', EVAL_CAPS.runsPerCase],
719 ['eval promotion: consecutive qualifying runs', EVAL_CAPS.promotionRuns],
720 ['eval promotion: trials per qualifying run', EVAL_CAPS.promotionTrialsPerRun],
721 ['eval promotion: judge agreement floor', `${Math.round(EVAL_CAPS.judgeAgreementFloor * 100)}%`]
722 ]
723 // The price table prints beside the ceiling it serves: an operator reading a
724 // dollar cap needs to see which prices turned tokens into those dollars, and
725 // the id is what a recorded row is keyed against.
726 const priceRows = [
727 ['price table id', MODEL_PRICES.id],
728 ...Object.keys(MODEL_PRICES.perMillionTokens)
729 .sort()
730 .map(model => [
731 `price: ${model} ($/Mtok)`,
732 `in ${MODEL_PRICES.perMillionTokens[model].input}, out ${MODEL_PRICES.perMillionTokens[model].output}`
733 ]),
734 // The cache multipliers print beside the base rates for the same reason the
735 // base rates print beside the ceiling: they are part of what turns a token
736 // count into a dollar figure, and a multiplier nobody can see is a price
737 // written in prose. One read row per model, because the read multiplier is
738 // not one figure; one write row per lifetime tier, because they are never
739 // summed. A priced model with no read multiplier prints as `unpriced`, which
740 // is what the pricer makes of it.
741 ...Object.keys(MODEL_PRICES.perMillionTokens)
742 .sort()
743 .map(model => [
744 `cache read multiplier: ${model} (x input)`,
745 typeof MODEL_PRICES.cacheMultipliers.read[model] === 'number'
746 ? MODEL_PRICES.cacheMultipliers.read[model]
747 : 'unpriced'
748 ]),
749 ...Object.keys(MODEL_PRICES.cacheMultipliers.write)
750 .sort()
751 .map(tier => [`cache write multiplier: ${tier} (x input)`, MODEL_PRICES.cacheMultipliers.write[tier]])
752 ]
753 const reportRows = [['report trajectory scan cap', REPORT_CAPS.maxRunsScanned]]
754 // One row per ceiling, then one per threshold. `unobserved` prints beside
755 // amber because it takes amber's range; it has no number of its own.
756 const mergeRows = [
757 ['merge band ceiling: green', MERGE_BANDS.ceiling.green],
758 ['merge band ceiling: amber (also unobserved)', MERGE_BANDS.ceiling.amber],
759 ['merge band ceiling: red', MERGE_BANDS.ceiling.red],
760 ['merge: max surviving warnings', MERGE_BANDS.maxWarningsForMerge],
761 ['merge: min skeptic verdicts per finding', MERGE_BANDS.minVerdictsPerFinding],
762 ['merge: max coverage decline (points)', MERGE_BANDS.maxCoverageDeclinePts],
763 ['merge: patch coverage floor (%, no baseline)', MERGE_BANDS.patchCoverageFloorPct],
764 ['merge: min changed lines to judge coverage', MERGE_BANDS.minChangedLinesForCoverage],
765 ['merge: max changed lines', MERGE_BANDS.maxChangedLinesForMerge],
766 ['merge: max changed files', MERGE_BANDS.maxChangedFilesForMerge]
767 ]
768 // One row per tier, rather than a rendered object: an operator reading this
769 // wants to know what bounds the lane in front of them, and a tier is how they
770 // find it. The cohesion ceiling and the solo envelope print beside them because
771 // all three answer one question — how many tasks may one agent be handed.
772 const laneRows = [
773 ['lane cap: tier 1 lane (also untiered)', LANE_CAPS.byTier[1]],
774 ['lane cap: tier 2 lane', LANE_CAPS.byTier[2]],
775 ['lane cap: tier 3 lane', LANE_CAPS.byTier[3]],
776 ['lane cap: tier 4 lane', LANE_CAPS.byTier[4]],
777 ['lane cap: tier 5 lane', LANE_CAPS.byTier[5]],
778 ['cohesion tier ceiling (packs at or below)', LANE_CAPS.cohesionMaxTier],
779 ['multi-task opus floor (hardest tier at or above)', LANE_CAPS.opusMinTier],
780 ['solo envelope (max tasks in one lane)', SOLO.maxTasks]
781 ]
782 // `null` in the tier table means inherit the session default; print it as
783 // "inherit" so an operator reads the policy, not an empty cell.
784 const inherit = v => (v === null || v === undefined ? 'inherit (session default)' : v)
785 const effortRows = [
786 ['effort: tier 1 lane', inherit(EFFORT.byTier[1])],
787 ['effort: tier 2 lane', inherit(EFFORT.byTier[2])],
788 ['effort: tier 3 lane', inherit(EFFORT.byTier[3])],
789 ['effort: tier 4 lane', inherit(EFFORT.byTier[4])],
790 ['effort: tier 5 lane', inherit(EFFORT.byTier[5])],
791 ['effort: verify step (inter-wave and final)', EFFORT.verify],
792 ['effort: review skeptic step', EFFORT.skeptic]
793 ]
794 const routeCell = r => `model ${inherit(r.model)} · effort ${inherit(r.effort)}`
795 const routingRows = [
796 ...Object.entries(SPAWN_ROUTING).map(([role, row]) => [`routing: ${role}`, routeCell(row)]),
797 ...Object.entries(SPAWN_ROUTING)
798 .filter(([, row]) => row.strict)
799 .map(([role, row]) => [`routing: ${role} (strict)`, routeCell(row.strict)]),
800 ['review depth: default', REVIEW_DEPTH.default],
801 ...['lean', 'strict'].flatMap(d => [
802 [`review depth: ${d} dimensions`, REVIEW_DEPTH[d].dimensions.join(', ')],
803 [`review depth: ${d} skeptics`, REVIEW_DEPTH[d].skeptics]
804 ])
805 ]
806 const width = Math.max(
807 ...[...rows, ...laneRows, ...mergeRows, ...evalRows, ...priceRows, ...reportRows, ...effortRows, ...routingRows].map(
808 ([label]) => label.length
809 )
810 )
811 const fmt = ([label, value]) => ` ${String(label).padEnd(width)} ${value}`
812 return (
813 rows.map(fmt).join('\n') +
814 '\n\n' +
815 laneRows.map(fmt).join('\n') +
816 '\n\n' +
817 mergeRows.map(fmt).join('\n') +
818 '\n\n' +
819 evalRows.map(fmt).join('\n') +
820 '\n\n' +
821 priceRows.map(fmt).join('\n') +
822 '\n\n' +
823 reportRows.map(fmt).join('\n') +
824 '\n\n' +
825 effortRows.map(fmt).join('\n') +
826 '\n\n' +
827 routingRows.map(fmt).join('\n') +
828 `\n\nruntime ceilings: ${RUNTIME.maxConcurrentAgents} concurrent, ` +
829 `${RUNTIME.maxAgentsPerRun} agents per run${observedSlots(runtimeObserved)}\n`
830 )
831}
832
833/** The observed clause of the runtime-ceilings line, or '' when nothing was observed. */
834function observedSlots(observed) {
835 if (!observed || typeof observed !== 'object') return ''
836 if (observed.source === 'env' && Number.isInteger(observed.observed)) {
837 return ` — observed on this machine: CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS=${observed.observed}`
838 }
839 const machine = Number.isInteger(observed.cpuCount) ? `this ${observed.cpuCount}-CPU machine` : 'this machine'
840 const ignored =
841 typeof observed.invalid === 'string'
842 ? `CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS=${observed.invalid} is not a valid count and is ignored; `
843 : ''
844 return ` — observed on this machine: ${ignored}vendor default, possibly reduced on ${machine}`
845}
846lib/meter-palette.mjs 52 lines1// The ship meter's colours, as the theme keys the pane draws with.
2//
3// Each value is a key of the person's own theme, never a fixed hue: `Text` and
4// `Box` colour props resolve a theme key, so the pane follows the light, dark
5// or colour-blind theme the person chose (probed on Claude Code 2.1.295: the
6// keys below resolve, nested spans inside one `Text` keep their own, a
7// bordered `Box` takes one for its border, and an unknown key draws uncoloured
8// with no error). A colour names what a word means: a state the renderer
9// printed, a name, a heading, a word the host or the CLI sent. It is never a
10// threshold or a verdict of the meter's own, so a figure the engine reports
11// (the context, the cost, a plan window) carries none.
12//
13// Pure and Node-free: the hooks module runs in the engine with no Node, and
14// imports this file.
15
16export const PALETTE = Object.freeze({
17 // A state word the board printed: the recorded ok, the recorded failure, the cursor.
18 ok: 'success',
19 failed: 'error',
20 current: 'warning',
21 // A lane label and an agent's name.
22 identity: 'suggestion',
23 // The run header and the section headings.
24 accent: 'claude',
25 // A word the CLI or the host raised to be read: a banner, the quiet word, a running turn.
26 warn: 'warning',
27 // A refusal, and a turn the host ended without an answer.
28 alarm: 'error'
29})
30
31const DIM_WORDS = new Set(['pending', 'not reached', 'not recorded', 'per task'])
32
33/** The props a state word the board printed is drawn with: a hue for ok, failed and current, dim for the rest, else none. */
34export function stateProps(word) {
35 if (word === 'ok') return { color: PALETTE.ok }
36 if (word === 'failed') return { color: PALETTE.failed }
37 if (word === 'current') return { color: PALETTE.current }
38 if (DIM_WORDS.has(word)) return { dimColor: true }
39 return null
40}
41
42/**
43 * The props an agent's turn word is drawn with. No reason is a turn still
44 * running; `answer` is the host's ordinary end; any other word the host sends
45 * is a turn it ended without one. The caller shows the word itself verbatim.
46 */
47export function turnProps(reason) {
48 if (reason === null || reason === undefined) return { color: PALETTE.warn }
49 if (reason === 'answer') return { color: PALETTE.ok }
50 return { color: PALETTE.alarm }
51}
52lib/meter-quiet.mjs 46 lines1// The ship meter's quiet figure (show-quiet-time-and-reset-the-meter-on-clear
2// design D3): how long a live run has gone without activity, and the word the
3// meter shows once that reaches the published threshold.
4//
5// Pure and Node-free: `hooks/mod.mjs` imports it inside the engine, where there
6// is no Node, and `test/spine/mod-pins.test.mjs` walks the import. The two
7// numbers are `interlock limits`'s; neither this file nor the hooks module
8// restates them. The word names no cause: a run waiting on a plan window and a
9// run that hung read the same here, and the person tells them apart from the
10// windows the pane lists beside it.
11
12import { LIMITS } from './limits.mjs'
13
14const MINUTE_MS = 60 * 1000
15
16/** The period of the meter's interval, in milliseconds. */
17export const TICK_MS = LIMITS.meterTickMs
18
19/**
20 * Milliseconds from the last activity to now, never negative (a clock that went
21 * backwards reads as no wait). `null` unless both are finite numbers: a time
22 * the module could not read is no figure, never a guessed one.
23 *
24 * @param {unknown} lastActivityAt milliseconds since the epoch, or null
25 * @param {unknown} now milliseconds since the epoch, or null
26 * @returns {number|null}
27 */
28export function quietMs(lastActivityAt, now) {
29 if (!Number.isFinite(lastActivityAt) || !Number.isFinite(now)) return null
30 return Math.max(0, now - lastActivityAt)
31}
32
33/**
34 * `quiet <n> min` once `ms` reaches the threshold, `<n>` the whole minutes and
35 * `<1` under one; `null` below it, or for no figure.
36 *
37 * @param {number|null} ms what `quietMs` returned
38 * @param {number} [afterMs] the threshold; the published one unless a test names another
39 * @returns {string|null}
40 */
41export function quietWord(ms, afterMs = LIMITS.meterQuietAfterMs) {
42 if (!Number.isFinite(ms) || ms < afterMs) return null
43 const minutes = Math.floor(ms / MINUTE_MS)
44 return `quiet ${minutes < 1 ? '<1' : minutes} min`
45}
46lib/meter-time.mjs 44 lines1// The ship meter's time words: the clock reading a line was stamped with, and
2// how long a turn took, as a person reads them.
3//
4// Each reading is the engine's own (`$.clock.now()` in the hooks module), so a
5// time is either a real reading or absent: absent draws as nothing, never as a
6// guessed time. The wall-clock words are the local time of the machine the
7// engine runs on, from `Date`'s own local fields. The duration bands are unit
8// conversions (seconds, minutes, hours), not thresholds: no band is a verdict
9// on the figure it formats.
10//
11// Pure and Node-free: the hooks module runs in the engine with no Node, and
12// imports this file.
13
14const isTime = ms => typeof ms === 'number' && Number.isFinite(ms)
15const pad = n => String(n).padStart(2, '0')
16
17/** The local wall-clock time of a reading, `HH:MM:SS`; `''` for no reading. */
18export function clockText(ms) {
19 if (!isTime(ms)) return ''
20 const d = new Date(ms)
21 return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
22}
23
24/** The local date and time of a reading, `YYYY-MM-DD HH:MM:SS`; `''` for no reading. */
25export function stampText(ms) {
26 if (!isTime(ms)) return ''
27 const d = new Date(ms)
28 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${clockText(ms)}`
29}
30
31/**
32 * A duration in milliseconds as a person reads it: under a minute, seconds to
33 * one decimal, cut down (`41.2s`, `0.8s`, never `60.0s`); under an hour, whole
34 * minutes and seconds (`2m 14s`); else hours and minutes (`1h 03m`). `''` for
35 * no figure, a negative one or one that is not a finite number.
36 */
37export function durationText(ms) {
38 if (!isTime(ms) || ms < 0) return ''
39 if (ms < 60_000) return `${(Math.floor(ms / 100) / 10).toFixed(1)}s`
40 const seconds = Math.floor(ms / 1000)
41 if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${pad(seconds % 60)}s`
42 return `${Math.floor(seconds / 3600)}h ${pad(Math.floor((seconds % 3600) / 60))}m`
43}
44lib/meter-timeline.mjs 162 lines1// The ship meter's step timeline: what each step the CLI printed says, and the
2// order the pane lays the steps, the agents they spawned and the agents no
3// step names in.
4//
5// A step's words are its own fields, verbatim: the action, its position, how
6// many lanes a batch dispatched, a skipped verification's reason, a halt's
7// reason and the plan size a step relayed. No word here is a verdict, a cause
8// or a state the step did not carry.
9//
10// The order is pure data over plain inputs, so it is pinned under Node
11// (`test/spine/meter-timeline.test.mjs`) and the hooks module only draws it:
12//
13// - The top level is the launch, every step and every relay agent no step
14// names, laid by time. An entry with a time sorts by it, ties keeping their
15// input order (the launch, then the steps as they crossed, then the relays as
16// first seen); an entry with no time follows every timed one, in input order.
17// - Beneath a step, at depth 1, the agents it spawned: a spawn is joined to an
18// agent by its briefing hash, one agent per spawn in step order (an agent
19// beyond the spawns that carry its hash stays with the last of them). The
20// joined spawns are laid by their agent's first request time, by the same
21// rule; the spawns no agent has joined yet follow, `waiting`, in the step's
22// spawn order. A step's relay is drawn on the step's own line and nowhere
23// else.
24// - Last, the agents nothing names, under one head, in first-seen order.
25//
26// Pure and Node-free: the hooks module runs in the engine with no Node, and
27// imports this file.
28
29/** The actions that dispatch a batch of lanes. */
30export const BATCH_ACTIONS = new Set(['run-batch', 'test-wave'])
31
32const isInt = v => Number.isInteger(v)
33const isTime = v => typeof v === 'number' && Number.isFinite(v)
34const str = v => (typeof v === 'string' && v ? v : null)
35const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
36
37/** `batch <j>/<k>`, one-based, as the status line says it; `null` when the step carries no position. */
38export function batchText(batchIndex, batchCount) {
39 return isInt(batchIndex) && isInt(batchCount) ? `batch ${batchIndex + 1}/${batchCount}` : null
40}
41
42/** How many lanes run side by side: `N in parallel`, `1 lane`, or `null` for none. */
43export function laneCountText(n) {
44 if (!isInt(n) || n < 1) return null
45 return n === 1 ? '1 lane' : `${n} in parallel`
46}
47
48/** The waves a plan summary holds, its test wave counted; `null` for anything that is not a summary. */
49export function planWaveCount(plan) {
50 if (plan === null || typeof plan !== 'object' || !Array.isArray(plan.waves)) return null
51 return plan.waves.length + (plan.testWave ? 1 : 0)
52}
53
54/** A step's words, from its own fields only. */
55export function stepText(step) {
56 const s = step && typeof step === 'object' ? step : {}
57 const parts = [String(s.action)]
58 if (s.wave !== undefined && s.wave !== null) parts.push(`wave ${s.wave}`)
59 const batch = batchText(s.batchIndex, s.batchCount)
60 if (batch) parts.push(batch)
61 if (BATCH_ACTIONS.has(s.action)) {
62 const lanes = laneCountText(Array.isArray(s.spawns) ? s.spawns.length : 0)
63 if (lanes) parts.push(lanes)
64 }
65 if (s.action === 'verify' && s.skipped === true) parts.push(str(s.reason) ? `skipped: ${s.reason}` : 'skipped')
66 if (s.action === 'halt' && str(s.reason)) parts.push(s.reason)
67 if (isInt(s.planWaves)) parts.push(`plan: ${plural(s.planWaves, 'wave')}`)
68 return parts.join(' · ')
69}
70
71/** The entries with a time laid by it, ties in input order; then the entries with none, in input order. */
72function byTime(entries) {
73 const timed = entries.map((entry, i) => ({ entry, i })).filter(({ entry }) => isTime(entry.at))
74 timed.sort((a, b) => a.entry.at - b.entry.at || a.i - b.i)
75 return [...timed.map(({ entry }) => entry), ...entries.filter(entry => !isTime(entry.at))]
76}
77
78/**
79 * The timeline as ordered display entries, each `{ key, kind, at, depth, ... }`:
80 * `launch` (`name`), `step` (`step`), `spawn` (`step`, `spawn`, `agent` or
81 * `null` while it waits), `relay` (`agent`, a relay agent no step names),
82 * `unmatched-head`, and `unmatched` (`agent`). An agent's entry is keyed
83 * `agent-<id>`, a waiting spawn's `spawn-<n>-<label>`, a step's `step-<n>`.
84 *
85 * @param {{
86 * steps?: {n: number, at: number|null, action: string, wave?: unknown, waveIndex?: unknown, batchIndex?: unknown,
87 * batchCount?: unknown, skipped?: unknown, reason?: unknown, planWaves?: number|null, relayId?: string|null,
88 * spawns: {label: string, title: string, sha: string|null}[]}[],
89 * agents?: {id: string, sha?: string|null, relay?: string|null, firstAt?: number|null}[],
90 * launch?: {at: number|null, name?: string|null}|null
91 * }} input
92 * @returns {object[]}
93 */
94export function timeline({ steps = [], agents = [], launch = null } = {}) {
95 const relays = new Set(steps.map(step => str(step.relayId)).filter(Boolean))
96
97 // Each spawn carrying a hash, in step order, and the agents carrying it, first seen first.
98 const slots = new Map()
99 const spawnsOf = step => (Array.isArray(step.spawns) ? step.spawns : [])
100 steps.forEach((step, i) =>
101 spawnsOf(step).forEach((spawn, j) => {
102 const sha = str(spawn.sha)
103 if (!sha) return
104 if (!slots.has(sha)) slots.set(sha, [])
105 slots.get(sha).push({ pos: `${i}:${j}`, agents: [] })
106 })
107 )
108 const placed = new Set()
109 const counts = new Map()
110 for (const agent of agents) {
111 const sha = str(agent.sha)
112 if (!sha || relays.has(agent.id) || !slots.has(sha)) continue
113 const held = slots.get(sha)
114 const at = counts.get(sha) || 0
115 held[Math.min(at, held.length - 1)].agents.push(agent)
116 counts.set(sha, at + 1)
117 placed.add(agent.id)
118 }
119 const joinedBy = new Map()
120 for (const held of slots.values()) for (const slot of held) joinedBy.set(slot.pos, slot.agents)
121
122 const top = []
123 if (launch && typeof launch === 'object') {
124 top.push({ key: 'launch', kind: 'launch', at: isTime(launch.at) ? launch.at : null, depth: 0, name: str(launch.name) })
125 }
126 for (const step of steps) top.push({ key: `step-${step.n}`, kind: 'step', at: isTime(step.at) ? step.at : null, depth: 0, step })
127 const orphans = agents.filter(agent => str(agent.relay) && !relays.has(agent.id) && !placed.has(agent.id))
128 for (const agent of orphans) {
129 top.push({ key: `agent-${agent.id}`, kind: 'relay', at: isTime(agent.firstAt) ? agent.firstAt : null, depth: 0, agent })
130 placed.add(agent.id)
131 }
132
133 const out = []
134 for (const entry of byTime(top)) {
135 out.push(entry)
136 if (entry.kind !== 'step') continue
137 const i = steps.indexOf(entry.step)
138 const joined = []
139 const waiting = []
140 for (const [j, spawn] of spawnsOf(entry.step).entries()) {
141 const held = joinedBy.get(`${i}:${j}`) || []
142 if (!held.length) {
143 waiting.push({ key: `spawn-${entry.step.n}-${spawn.label}`, kind: 'spawn', at: null, depth: 1, step: entry.step, spawn, agent: null })
144 }
145 for (const agent of held) {
146 const at = isTime(agent.firstAt) ? agent.firstAt : null
147 joined.push({ key: `agent-${agent.id}`, kind: 'spawn', at, depth: 1, step: entry.step, spawn, agent })
148 }
149 }
150 out.push(...byTime(joined), ...waiting)
151 }
152
153 const unmatched = agents.filter(agent => !relays.has(agent.id) && !placed.has(agent.id))
154 if (unmatched.length) {
155 out.push({ key: 'agents-unmatched-head', kind: 'unmatched-head', at: null, depth: 0 })
156 for (const agent of unmatched) {
157 out.push({ key: `agent-${agent.id}`, kind: 'unmatched', at: isTime(agent.firstAt) ? agent.firstAt : null, depth: 1, agent })
158 }
159 }
160 return out
161}
162lib/meter-refusals.mjs 74 lines1// The ship meter's refusal words (speak-permission-prompts-and-guard-denials
2// design D4-D6): the four guard names a settings guard's denial is read by,
3// the slice of an errored result's text the meter repeats, and the pane lines.
4//
5// Pure and Node-free: `hooks/mod.mjs` imports it inside the engine, where there
6// is no Node, and `test/spine/mod-pins.test.mjs` walks the import and pins the
7// names against the four guards' own `GUARD` constants. Nothing here judges a
8// denial: the words are the guard's, and the ruling is `lib/launch-rule.mjs`'s.
9
10/** The settings guards whose denials the meter repeats, as each prints its name. */
11export const GUARD_NAMES = Object.freeze(['guard-tests', 'guard-tasks', 'guard-commit', 'guard-relaunch'])
12
13// Anywhere in the text, not only at its start: the engine puts
14// `PreToolUse:<tool> hook error: ` in front of a settings hook's reason (probe 2).
15const NAMED = new RegExp(`\\b(${GUARD_NAMES.join('|')}): `)
16
17/**
18 * The text from the first guard name on, or `null` for a text that names no
19 * guard (another plugin's deny, a command that failed) or is not a string.
20 *
21 * @param {unknown} text an errored tool result's `text`
22 * @returns {string|null}
23 */
24export function guardReason(text) {
25 if (typeof text !== 'string') return null
26 const m = NAMED.exec(text)
27 return m ? text.slice(m.index) : null
28}
29
30/**
31 * The guard that spoke `reason`, as `guardReason` sliced it; `null` for none.
32 *
33 * @param {unknown} reason
34 * @returns {string|null}
35 */
36export function guardOf(reason) {
37 if (typeof reason !== 'string') return null
38 const m = NAMED.exec(reason)
39 return m && m.index === 0 ? m[1] : null
40}
41
42/**
43 * `guard denials: <n> (<guard> <n>, …)` in the order each guard was first
44 * seen, or `null` when none was: the pane draws no line for nothing.
45 *
46 * @param {Map<string, number>|undefined} counts
47 * @returns {string|null}
48 */
49export function guardDenialLine(counts) {
50 if (!(counts instanceof Map) || counts.size === 0) return null
51 let total = 0
52 const parts = []
53 for (const [guard, n] of counts) {
54 total += n
55 parts.push(`${guard} ${n}`)
56 }
57 return `guard denials: ${total} (${parts.join(', ')})`
58}
59
60/**
61 * The launch guard's current ruling over the session's record, in the rule's
62 * own words. `now` is `null` only when the guard's facts could not be read,
63 * which allows the next launch (design D5).
64 *
65 * @param {{ decision: string, reason: string|null }} ruling what `decideLaunch` returned
66 * @param {number|null} now
67 * @returns {string}
68 */
69export function launchGuardLine(ruling, now) {
70 if (now === null) return 'launch guard: facts unreadable; the next launch is allowed'
71 if (ruling && ruling.decision === 'deny' && ruling.reason) return `launch guard: next launch refused: ${ruling.reason}`
72 return 'launch guard: next launch allowed'
73}
74lib/preflight-file.mjs 273 lines1// The session start's report file: what `hooks/preflight.mjs` leaves in
2// `.claude/ship/preflight.json`, and every line the hooks module draws from it
3// (show-preflight-and-interrupted-runs-at-session-start design D1, D5-D8).
4//
5// Two readers of one shape. The hook builds the report from what it already
6// holds: the doctor's verdict and checks, the interrupted-run notes it spoke
7// and marked, the halt resume cards it listed. The hooks module reads it at a
8// prompt the person submits and draws the `AbovePrompt` band and two panes.
9// Neither side derives a fact the other did not say: every word drawn is the
10// doctor's, the hook's or the card's, and the time is a date, never a
11// staleness verdict.
12//
13// Node-free, and importing only `./limits.mjs`, because the hooks module runs
14// in the engine with no Node (test/spine/mod-pins.test.mjs walks it). The
15// handoff pane's cap is read here and restated nowhere in the module.
16
17import { LIMITS } from './limits.mjs'
18
19/** Bump when the report's shape changes, so a reader can tell an older one. */
20export const PREFLIGHT_SCHEMA = 'interlock.preflight/1'
21
22/** Where the report lands, relative to the working root. Already gitignored with `.claude/ship/`. */
23export const PREFLIGHT_FILE = '.claude/ship/preflight.json'
24
25/** The most characters of a card the handoff pane renders: the `Markdown` element's own bound (design D7). */
26export const HANDOFF_PANE_CHARS = LIMITS.handoffPaneChars
27
28/** The SessionStart sources the host names; anything else is recorded as null. */
29const SOURCES = new Set(['startup', 'resume', 'clear', 'compact'])
30
31const str = v => (typeof v === 'string' && v ? v : null)
32const text = v => (typeof v === 'string' ? v : v === null || v === undefined ? '' : String(v))
33const list = v => (Array.isArray(v) ? v.filter(x => x && typeof x === 'object') : [])
34const count = v => (Number.isInteger(v) && v >= 0 ? v : 0)
35
36/** The report file's path under `cwd`, or the relative path the engine resolves under the session's directory. */
37export function preflightFilePath(cwd) {
38 if (typeof cwd !== 'string' || !cwd) return PREFLIGHT_FILE
39 return `${cwd.endsWith('/') ? cwd.slice(0, -1) : cwd}/${PREFLIGHT_FILE}`
40}
41
42function doctorOf(d) {
43 const doctor = d && typeof d === 'object' ? d : {}
44 const counts =
45 doctor.counts && typeof doctor.counts === 'object'
46 ? Object.fromEntries(['ok', 'warn', 'fail', 'skip'].map(k => [k, count(doctor.counts[k])]))
47 : null
48 return {
49 ran: doctor.ran === true,
50 parsed: doctor.parsed === true,
51 ok: typeof doctor.ok === 'boolean' ? doctor.ok : null,
52 counts,
53 // `evidence` is copied line for line, strings only: the cli-version row records the
54 // resolved binary path and both versions there, and the file is what says which
55 // interlock a session was served (spec: hooks/session-preflight, design D5).
56 checks: list(doctor.checks).map(c => ({
57 id: text(c.id),
58 status: text(c.status),
59 detail: text(c.detail),
60 fix: str(c.fix),
61 evidence: Array.isArray(c.evidence) ? c.evidence.filter(e => typeof e === 'string') : []
62 }))
63 }
64}
65
66function notesOf(n) {
67 const notes = n && typeof n === 'object' ? n : {}
68 return {
69 spoken: list(notes.spoken).map(s => ({
70 runId: text(s.runId),
71 change: str(s.change),
72 stage: str(s.stage),
73 banner: text(s.banner),
74 marked: s.marked === true,
75 marks: list(s.marks).map(m => ({ root: text(m.root), marked: m.marked === true, reason: str(m.reason) }))
76 })),
77 unreadable: list(notes.unreadable).map(u => ({ file: text(u.file), reason: text(u.reason) }))
78 }
79}
80
81function cardsOf(c) {
82 const cards = c && typeof c === 'object' ? c : {}
83 return {
84 listed: list(cards.listed).map(k => ({ path: text(k.path), change: text(k.change), runId: text(k.runId), writtenAt: str(k.writtenAt) })),
85 archived: count(cards.archived),
86 unreadable: list(cards.unreadable).map(u => ({ path: text(u.path), reason: text(u.reason) })),
87 lookedIn: Array.isArray(cards.lookedIn) ? cards.lookedIn.filter(d => typeof d === 'string' && d) : []
88 }
89}
90
91/**
92 * The report, every field present: an absent fact is `null` or `[]`, never
93 * omitted (design D1). Pure: the caller passes the time it wrote at.
94 */
95export function buildPreflightReport(input) {
96 const i = input && typeof input === 'object' ? input : {}
97 return {
98 schema: PREFLIGHT_SCHEMA,
99 writtenAt: str(i.writtenAt),
100 source: SOURCES.has(i.source) ? i.source : null,
101 root: str(i.root),
102 stateHome: str(i.stateHome),
103 surface: str(i.surface),
104 message: typeof i.message === 'string' ? i.message : null,
105 doctor: doctorOf(i.doctor),
106 notes: notesOf(i.notes),
107 cards: cardsOf(i.cards)
108 }
109}
110
111/** `{ report }` from the file's text, or `{ problem }` naming why there is none. */
112export function readPreflightReport(raw) {
113 if (typeof raw !== 'string') return { problem: `not text: the read returned ${raw === null ? 'null' : typeof raw}` }
114 let value
115 try {
116 value = JSON.parse(raw)
117 } catch (err) {
118 return { problem: `not JSON: ${(err && err.message) || err}` }
119 }
120 if (!value || typeof value !== 'object' || Array.isArray(value)) return { problem: 'not an object' }
121 if (value.schema !== PREFLIGHT_SCHEMA) return { problem: `stamped ${JSON.stringify(value.schema)}, not ${PREFLIGHT_SCHEMA}` }
122 return { report: buildPreflightReport(value) }
123}
124
125const flagged = report => report.doctor.checks.filter(c => c.status === 'fail' || c.status === 'warn')
126
127/**
128 * Whether the band has anything to say: a fail or warn check, a doctor that
129 * did not run or parse, a spoken note. A card is not a reason: it stays on disk
130 * until its change is archived and would hold the band at every session start;
131 * the two panes show it on request.
132 */
133export function shouldDraw(report) {
134 return flagged(report).length > 0 || !report.doctor.ran || !report.doctor.parsed || report.notes.spoken.length > 0
135}
136
137/** One listed card's line: where it is, which change and run, when it was written. */
138export function cardLine(card) {
139 return `${card.path} · ${card.change} · run ${card.runId} · written ${card.writtenAt || 'at an unknown time'}`
140}
141
142/** The listed cards, newest written first; equal or unknown times keep the listing's order. */
143export function orderCards(report) {
144 const at = c => {
145 const t = Date.parse(c.writtenAt)
146 return Number.isNaN(t) ? -Infinity : t
147 }
148 return report.cards.listed
149 .map((card, i) => ({ card, i }))
150 .sort((a, b) => at(b.card) - at(a.card) || a.i - b.i)
151 .map(x => x.card)
152}
153
154const writtenLine = report => `preflight written ${report.writtenAt || 'at an unknown time'}`
155
156/**
157 * The band's lines, in order (design D6): the message's first line, each
158 * `fail` or `warn` check in the doctor's words, each spoken note's banner, and
159 * when the report was written. No card: `/interlock-preflight` and
160 * `/interlock-handoff` list them. Empty when there is nothing to say.
161 */
162export function bandLines(report) {
163 if (!shouldDraw(report)) return []
164 const lines = []
165 const first = (report.message || '').split('\n')[0]
166 if (first) lines.push(first)
167 for (const c of flagged(report)) lines.push(`${c.status} ${c.id}: ${c.detail}`)
168 for (const n of report.notes.spoken) lines.push(n.banner)
169 lines.push(`${writtenLine(report)} · /interlock-preflight`)
170 return lines
171}
172
173/**
174 * The `/interlock-preflight` pane's lines: the message verbatim, every check
175 * with its fix lines indented as the hook prints them, the notes spoken at
176 * this session start with each root's mark, the cards and what was not
177 * listed, and every note and card the hook could not read. No empty line.
178 */
179export function preflightPaneLines(report) {
180 const lines = []
181 for (const line of (report.message || '').split('\n')) if (line) lines.push(line)
182 lines.push(writtenLine(report))
183
184 lines.push(report.doctor.ran ? (report.doctor.parsed ? 'checks' : 'checks: the doctor ran and its output could not be parsed') : 'checks: the doctor did not run')
185 for (const c of report.doctor.checks) {
186 lines.push(`${c.status} ${c.id}: ${c.detail}`)
187 if (c.fix) {
188 const [first, ...rest] = c.fix.split('\n')
189 lines.push(` fix: ${first}`)
190 for (const more of rest) if (more.trim()) lines.push(` ${more.trim()}`)
191 }
192 }
193
194 lines.push(report.notes.spoken.length ? 'interrupted runs spoken at this session start' : 'no interrupted run was spoken at this session start')
195 for (const n of report.notes.spoken) {
196 lines.push(n.banner)
197 for (const m of n.marks) lines.push(m.marked ? ` marked · ${m.root}` : ` not marked: ${m.reason || 'no reason given'}`)
198 }
199 for (const u of report.notes.unreadable) lines.push(`note unreadable: ${u.file}: ${u.reason}`)
200
201 const ordered = orderCards(report)
202 lines.push(ordered.length ? 'halt resume cards — /interlock-handoff' : 'no halt resume card is on disk for an open change')
203 for (const card of ordered) lines.push(cardLine(card))
204 if (report.cards.archived) lines.push(`${report.cards.archived} card(s) of archived changes not listed`)
205 for (const u of report.cards.unreadable) lines.push(`card unreadable: ${u.path}: ${u.reason}`)
206 for (const dir of report.cards.lookedIn) lines.push(`looked in: ${dir}`)
207 return lines
208}
209
210/** What a pane says with no report held: the file's path and why, or that it has not been read yet. */
211export function noReportText(path, problem) {
212 return `no preflight report is held for this session start: ${path}: ${problem || 'not read yet'}`
213}
214
215/** What the handoff pane says with a report and no card: that, and every directory looked in. */
216export function noCardText(report) {
217 return ['no halt resume card is on disk for an open change', ...report.cards.lookedIn.map(dir => `looked in: ${dir}`)]
218}
219
220// Every control character but tab and newline: the `Markdown` element refuses them.
221const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g
222
223/**
224 * A card's text as the handoff pane renders it: control characters made
225 * spaces, and when longer than `cap`, cut so that the text and a note naming
226 * the characters left out and the card's path fit within `cap` (design D7).
227 */
228export function clampCard(raw, path, cap = LIMITS.handoffPaneChars) {
229 const clean = text(raw).replace(CONTROL, ' ')
230 if (clean.length <= cap) return { text: clean, cut: 0 }
231 const note = n => `\n\n_… ${n} characters left out; the whole card is ${path}_`
232 // The note for the whole text is the longest the note can be, so the kept head plus any shorter note still fits.
233 let keep = Math.max(0, cap - note(clean.length).length)
234 const code = clean.charCodeAt(keep - 1)
235 if (keep > 0 && code >= 0xd800 && code <= 0xdbff) keep -= 1
236 const cut = clean.length - keep
237 return { text: (clean.slice(0, keep) + note(cut)).slice(0, cap), cut }
238}
239
240/** What the module holds between reads (design D8): the report or the problem, the hide flag, whether the problem was named. */
241export function freshStart() {
242 return { report: null, path: null, problem: null, hidden: false, named: false }
243}
244
245/**
246 * The module's next `start` after a read (design D5, D8), whether the band
247 * must be redrawn, and the one debug line to name, if any. A re-read of the
248 * report already held changes nothing, hide flag and all. A new report is
249 * held, and stays hidden only when it continues a report already held across
250 * a compaction. A problem drops the held report, since the file is no longer
251 * this session's, and is named once until a report is held again.
252 *
253 * @param {object} start what `freshStart` returns, as last adopted
254 * @param {{report?: object, problem?: string}} outcome `readPreflightReport`'s result, or a read's rejection as a problem
255 * @param {string} path the file's path, named on the debug line and the panes
256 * @returns {{start: object, changed: boolean, log: string|null}}
257 */
258export function adoptPreflight(start, outcome, path) {
259 const held = start && typeof start === 'object' ? start : freshStart()
260 const report = outcome && outcome.report
261 if (report) {
262 if (held.report && held.report.writtenAt === report.writtenAt && held.report.root === report.root) {
263 return { start: held, changed: false, log: null }
264 }
265 const hidden = held.report !== null && held.hidden && report.source === 'compact'
266 return { start: { report, path, problem: null, hidden, named: false }, changed: true, log: null }
267 }
268 const problem = (outcome && outcome.problem) || 'no report was read'
269 const log = held.named ? null : `interlock meter: no preflight report at ${path}: ${problem}`
270 const changed = held.report !== null || held.problem !== problem || held.path !== path
271 return { start: { report: null, path, problem, hidden: held.hidden, named: true }, changed, log }
272}
273lib/spec-meter.mjs 660 lines1// The spec meter's text rules (observe-the-spec-run-live design D1-D9).
2//
3// `/interlock:spec` has no CLI spine to draw from: it is a prose skill that
4// drives `openspec` and `interlock` through the Bash tool and writes its
5// artifacts with the Write tool. The hooks module draws it anyway, from what
6// already crossed the engine, and this module holds every rule it draws by:
7// which load starts a run (D1), which command lines are the flow's keyed lines
8// and how a compound line is cut (D3), where a line names its change (D2), the
9// fields each line's JSON must carry (D3), which writes are counted (D4),
10// which server tool uses are advisor entries, and every word the status line
11// and the pane say (D6). The module keeps the
12// record and makes the engine calls; nothing here does either.
13//
14// Every word drawn is the CLI's: a field it printed, composed from the field
15// and never from its text, a count of events the engine raised, or a time the
16// engine's clock gave. A line that cannot be read is said to be unread, with
17// its first line. Nothing here compares a count against a number, names a
18// threshold, or reads OpenSpec's own roll-up of the artifact ladder: the table
19// is the ladder as printed, and the record is the artifacts on disk, the
20// findings file and the gate's exit, which the pane says.
21//
22// It runs inside the engine through `hooks/mod.mjs`, so it is pure and imports
23// nothing (`test/spine/mod-pins.test.mjs` walks it). It does not import the
24// CLI's own modules for their shapes: they reach `node:fs`, and re-deriving a
25// verdict from them is what the meter must not do (D9).
26
27export const SPEC_PANE = 'interlock-spec'
28export const SPEC_TITLE = 'Interlock spec'
29export const NO_SPEC_LINE = 'no spec run is live in this session'
30export const SPEC_RECORD_LINE = "the artifacts on disk, the findings file and the gate's exit are the record"
31export const SPEC_UNPLACED_TOAST = '/interlock-spec opens the spec meter'
32export const UNKNOWN_CHANGE = 'change: unknown until named'
33export const SPEC_REPLACED_LINE = 'interlock spec: a new spec run replaced the previous one'
34
35/**
36 * The flow's keyed lines, by their command words, in the flow's order: the
37 * spec skill's drift, change, ladder, notes, ledger, validate, autonomy and
38 * checkpoint lines, with review-artifacts' gate and continuity's readiness where they
39 * fall (D3). The skill-lines pin reads the three skills against this list.
40 */
41export const KEYED_LINES = Object.freeze([
42 Object.freeze({ kind: 'drift', words: Object.freeze(['interlock', 'drift']) }),
43 Object.freeze({ kind: 'new-change', words: Object.freeze(['openspec', 'new', 'change']) }),
44 Object.freeze({ kind: 'status', words: Object.freeze(['openspec', 'status']) }),
45 Object.freeze({ kind: 'notes', words: Object.freeze(['interlock', 'note', 'match']) }),
46 Object.freeze({ kind: 'ledger', words: Object.freeze(['interlock', 'ledger']) }),
47 Object.freeze({ kind: 'validate', words: Object.freeze(['interlock', 'validate']) }),
48 Object.freeze({ kind: 'gate', words: Object.freeze(['interlock', 'gate']) }),
49 Object.freeze({ kind: 'autonomy', words: Object.freeze(['interlock', 'autonomy', 'record']) }),
50 Object.freeze({ kind: 'autonomy', words: Object.freeze(['interlock', 'autonomy', 'clean']) }),
51 Object.freeze({ kind: 'ready', words: Object.freeze(['interlock', 'ready']) }),
52 Object.freeze({ kind: 'checkpoint', words: Object.freeze(['interlock', 'notify', 'checkpoint']) })
53])
54
55/** Lines whose argv may name the change and whose result is never read (D2). */
56export const NAMING_ONLY = Object.freeze([Object.freeze(['openspec', 'instructions'])])
57
58/** The kinds whose result text is read; the rest are read by their argv alone (D3). */
59export const TEXT_KINDS = Object.freeze(['status', 'drift', 'notes', 'ledger', 'validate', 'gate', 'ready'])
60
61/** The skills a load can be, by the name the engine carries (D1, as probe 1 left it). */
62const SKILL_ROLES = new Map([
63 ['interlock:spec', 'spec'],
64 ['interlock:explore', 'explore'],
65 ['interlock:review-artifacts', 'review-artifacts']
66])
67
68/** The line the engine puts before a failed command's output (probe 3). */
69const ENGINE_PREFIX = /^Exit code \d+$/
70
71const UNPARSED_CUT = 200
72
73const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v)
74const isString = v => typeof v === 'string' && v !== ''
75const countOf = v => (Array.isArray(v) ? v.length : null)
76const shown = v => (v === null || v === undefined ? '?' : String(v))
77
78/**
79 * What a skill name loads: `spec`, `explore`, `review-artifacts`, or `null`.
80 * Only the plugin's namespaced names count, a leading `/` dropped: neither
81 * event that carries a load carries the skill's text, so a bare `spec` could
82 * be anyone's (D1).
83 */
84export function skillRole(name) {
85 if (typeof name !== 'string') return null
86 return SKILL_ROLES.get(name.trim().replace(/^\//, '')) || null
87}
88
89/** The skill a submitted prompt names by its first word (`/interlock:spec …`), or `null`. Nothing else is read. */
90export function promptSkill(text) {
91 if (typeof text !== 'string') return null
92 const m = text.match(/^\s*\/([A-Za-z0-9_.-]+(?::[A-Za-z0-9_.-]+)?)(?=\s|$)/)
93 return m ? m[1] : null
94}
95
96/**
97 * A shell command's words, unquoted, up to the first unquoted `|`, `;`, `&`,
98 * `>` or `<`. Each word is `{ value, plain }`, `plain` when no part of it was
99 * quoted. Never throws.
100 */
101export function argvOf(command) {
102 if (typeof command !== 'string') return []
103 const words = []
104 let value = ''
105 let plain = true
106 let open = false
107 let quote = null
108 const end = () => {
109 if (open) words.push({ value, plain })
110 value = ''
111 plain = true
112 open = false
113 }
114 for (let i = 0; i < command.length; i++) {
115 const c = command[i]
116 if (quote === "'") {
117 if (c === "'") quote = null
118 else value += c
119 continue
120 }
121 if (quote === '"') {
122 if (c === '"') quote = null
123 else if (c === '\\' && i + 1 < command.length && '"\\$`'.includes(command[i + 1])) value += command[++i]
124 else value += c
125 continue
126 }
127 if (c === "'" || c === '"') {
128 quote = c
129 plain = false
130 open = true
131 } else if (c === '\\' && i + 1 < command.length) {
132 value += command[++i]
133 open = true
134 } else if ('|;&><'.includes(c)) {
135 break
136 } else if (/\s/.test(c)) {
137 end()
138 } else {
139 value += c
140 open = true
141 }
142 }
143 end()
144 return words
145}
146
147/** Whether `words` begins with the plain words `prefix`. */
148const startsWith = (words, prefix) => prefix.every((w, i) => words[i] && words[i].plain && words[i].value === w)
149
150/**
151 * The kind of one command line by its first words, after leading whitespace:
152 * a keyed kind, `naming-only`, or `null`. It keys on the command words and not
153 * on `--json`, so a line on the previous skill text is classified and shown
154 * unparsed rather than ignored (D3).
155 */
156export function lineKind(command) {
157 const words = argvOf(command)
158 for (const { kind, words: prefix } of KEYED_LINES) if (startsWith(words, prefix)) return kind
159 for (const prefix of NAMING_ONLY) if (startsWith(words, prefix)) return 'naming-only'
160 return null
161}
162
163/**
164 * A command cut at every unquoted `&&`, `||`, `;` and line break, each segment
165 * trimmed; past an unquoted `<<` the rest is one segment, so a heredoc's body
166 * is never read as commands. Never throws.
167 */
168export function segmentsOf(command) {
169 if (typeof command !== 'string') return []
170 const out = []
171 let start = 0
172 let quote = null
173 for (let i = 0; i < command.length; i++) {
174 const c = command[i]
175 if (quote) {
176 if (c === quote) quote = null
177 else if (c === '\\' && quote === '"') i++
178 continue
179 }
180 if (c === "'" || c === '"') quote = c
181 else if (c === '\\') i++
182 else if (c === '<' && command[i + 1] === '<') break
183 else if (c === ';' || c === '\n') {
184 out.push(command.slice(start, i))
185 start = i + 1
186 } else if ((c === '&' && command[i + 1] === '&') || (c === '|' && command[i + 1] === '|')) {
187 out.push(command.slice(start, i))
188 start = i + 2
189 i++
190 }
191 }
192 out.push(command.slice(start))
193 return out.map(s => s.trim()).filter(Boolean)
194}
195
196/**
197 * The keyed segments of a command, in order: `{ kind, segment }` for each
198 * segment `lineKind` classifies, `naming-only` included (D3, the compound
199 * split probe 1 asked for).
200 */
201export function specLines(command) {
202 return segmentsOf(command)
203 .map(segment => ({ kind: lineKind(segment), segment }))
204 .filter(line => line.kind !== null)
205}
206
207/** A name the CLI could have meant: a non-empty string with no unexpanded `$`, backtick or `<`. */
208const nameOf = v => (isString(v) && !/[$`<]/.test(v) ? v : null)
209
210/** The value of `--<flag> v` or `--<flag>=v` in `words`, or `null`. */
211function flagValue(words, flag) {
212 for (let i = 0; i < words.length; i++) {
213 const w = words[i].value
214 if (w === `--${flag}`) return words[i + 1] ? words[i + 1].value : null
215 if (w.startsWith(`--${flag}=`)) return w.slice(flag.length + 3)
216 }
217 return null
218}
219
220/** The positional at `index` when it is not a flag. */
221const positional = (words, index) => (words[index] && !words[index].value.startsWith('-') ? words[index].value : null)
222
223/**
224 * The change a line names (D2): from its argv first, the positional after
225 * `openspec new change`, `--change` on any `openspec` line, the name after
226 * `interlock ledger|validate|ready`, `interlock notify checkpoint` and
227 * `interlock note match`,
228 * `--metrics` on `interlock gate`; then a non-empty `changeName` or `change`
229 * in the parsed result. Never a path, a prompt or another tool's input.
230 */
231export function changeOf(kind, command, value) {
232 const words = argvOf(command)
233 let named = null
234 if (kind === 'new-change') named = positional(words, 3)
235 else if (words[0] && words[0].value === 'openspec') named = flagValue(words, 'change')
236 else if (kind === 'ledger' || kind === 'validate' || kind === 'ready') named = positional(words, 2)
237 else if (kind === 'checkpoint' || kind === 'notes') named = positional(words, 3)
238 else if (kind === 'gate') named = flagValue(words, 'metrics')
239 if (nameOf(named)) return named
240 if (isObject(value)) return nameOf(value.changeName) || nameOf(value.change)
241 return null
242}
243
244/**
245 * The one JSON object a command printed, as `emit` prints it: from the first
246 * line that is exactly `{` to the last that is exactly `}`, so an engine
247 * prefix line and a stderr tail do not defeat it. `{ value }` or `{ problem }`.
248 */
249export function findJson(text) {
250 if (typeof text !== 'string') return { problem: 'no result text' }
251 const lines = text.split('\n').map(l => l.replace(/\r$/, ''))
252 const first = lines.indexOf('{')
253 const last = lines.lastIndexOf('}')
254 if (first === -1 || last < first) return { problem: 'output not JSON' }
255 try {
256 const value = JSON.parse(lines.slice(first, last + 1).join('\n'))
257 return isObject(value) ? { value } : { problem: 'output not JSON' }
258 } catch {
259 return { problem: 'output not JSON' }
260 }
261}
262
263/** The text a result carries: the command's own stdout when the engine kept it, else what the model reads. */
264function resultText(r) {
265 if (!isObject(r)) return null
266 if (isObject(r.result) && typeof r.result.stdout === 'string') return r.result.stdout
267 return typeof r.text === 'string' ? r.text : null
268}
269
270/** The first non-empty line of a result, past the engine's failed-command prefix, cut. */
271function firstLine(text) {
272 const lines = (typeof text === 'string' ? text : '').split('\n').map(l => l.trim())
273 const line = lines.find(l => l && !ENGINE_PREFIX.test(l)) || ''
274 return line.length > UNPARSED_CUT ? line.slice(0, UNPARSED_CUT) : line
275}
276
277/** An entry for a line that ran and was not read: its first line and why (D3). */
278export const unparsedEntry = (kind, text, reason) => ({ kind, unparsed: firstLine(text), reason })
279
280const isBool = v => typeof v === 'boolean'
281const isCount = v => Number.isInteger(v)
282
283/** Each text kind's needed fields, and what it keeps of them (D3). */
284const READERS = {
285 status(v) {
286 const ok = Array.isArray(v.artifacts) && v.artifacts.every(a => isObject(a) && isString(a.id) && isString(a.status))
287 if (!ok) return { missing: ['artifacts'] }
288 return {
289 entry: {
290 artifacts: v.artifacts.map(a => ({
291 id: a.id,
292 status: a.status,
293 outputPath: isString(a.outputPath) ? a.outputPath : null,
294 requires: Array.isArray(a.requires) ? a.requires.filter(isString) : []
295 })),
296 applyRequires: Array.isArray(v.applyRequires) ? v.applyRequires.filter(isString) : null,
297 changeName: isString(v.changeName) ? v.changeName : null,
298 schemaName: isString(v.schemaName) ? v.schemaName : null
299 }
300 }
301 },
302 drift(v) {
303 const stale = isObject(v.stale) ? v.stale : {}
304 const missing = [
305 ...(Array.isArray(v.unarchived) ? [] : ['unarchived']),
306 ...(Array.isArray(stale.broken) ? [] : ['stale.broken']),
307 ...(Array.isArray(stale.aging) ? [] : ['stale.aging'])
308 ]
309 if (missing.length) return { missing }
310 return { entry: { unarchived: v.unarchived.length, broken: stale.broken.length, aging: stale.aging.length } }
311 },
312 notes(v) {
313 const missing = [
314 ...(Array.isArray(v.rows) ? [] : ['rows']),
315 ...(isCount(v.omitted) ? [] : ['omitted']),
316 ...(isCount(v.unreadable) ? [] : ['unreadable'])
317 ]
318 if (missing.length) return { missing }
319 return { entry: { rows: v.rows.length, omitted: v.omitted, unreadable: v.unreadable } }
320 },
321 ledger(v) {
322 if (!isBool(v.blocking)) return { missing: ['blocking'] }
323 const entry = { blocking: v.blocking }
324 for (const f of ['needsHuman', 'invalidCount']) if (isCount(v[f])) entry[f] = v[f]
325 for (const f of ['missing', 'unparseable']) if (isBool(v[f])) entry[f] = v[f]
326 return { entry }
327 },
328 validate(v) {
329 const missing = [...(isBool(v.ready) ? [] : ['ready']), ...(Array.isArray(v.problems) ? [] : ['problems'])]
330 if (missing.length) return { missing }
331 return { entry: { ready: v.ready, problems: v.problems.map(p => (typeof p === 'string' ? p : JSON.stringify(p))) } }
332 },
333 gate(v) {
334 const counts = isObject(v.counts) ? v.counts : {}
335 const missing = [
336 ...(isBool(v.passed) ? [] : ['passed']),
337 ...['blocker', 'warning', 'suggestion'].filter(s => !isCount(counts[s])).map(s => `counts.${s}`),
338 ...(Array.isArray(v.malformed) ? [] : ['malformed'])
339 ]
340 if (missing.length) return { missing }
341 const entry = {
342 passed: v.passed,
343 counts: { blocker: counts.blocker, warning: counts.warning, suggestion: counts.suggestion },
344 malformed: v.malformed.length,
345 metrics: null
346 }
347 if (isObject(v.metrics)) {
348 entry.metrics = {
349 written: isBool(v.metrics.written) ? v.metrics.written : null,
350 path: isString(v.metrics.path) ? v.metrics.path : null,
351 reason: isString(v.metrics.reason) ? v.metrics.reason : null
352 }
353 }
354 return { entry }
355 },
356 ready(v) {
357 const missing = [...(isBool(v.ready) ? [] : ['ready']), ...(Array.isArray(v.blockers) ? [] : ['blockers'])]
358 if (missing.length) return { missing }
359 return { entry: { ready: v.ready, blockers: v.blockers.length } }
360 }
361}
362
363/** The kinds a name that does not resolve answers `{ error, candidates }` for (`requireChange`). */
364const RESOLVING = new Set(['notes', 'ledger', 'validate', 'ready'])
365const VERDICT = { notes: 'rows', ledger: 'blocking', validate: 'ready', ready: 'ready' }
366
367/**
368 * What one keyed line's result says, as an entry the record keeps, with the
369 * change it names as `name` (D2, D3). Only the fields a kind needs are kept:
370 * a result lacking them, or not JSON, or too large to have been kept inline,
371 * is an unparsed entry with its first line and the reason. `new-change`,
372 * `autonomy` and `checkpoint` read no text; `autonomy` keeps only `record` or
373 * `clean`. OpenSpec's own roll-up of the ladder is never read.
374 */
375export function readResult(kind, command, r) {
376 if (kind === 'new-change' || kind === 'checkpoint') return { kind, name: changeOf(kind, command, null) }
377 if (kind === 'autonomy') {
378 const words = argvOf(command)
379 return { kind, command: words[2] ? words[2].value : null, name: null }
380 }
381 if (!READERS[kind]) return null
382 if (isObject(r) && isObject(r.result) && isString(r.result.persistedOutputPath)) {
383 return { ...unparsedEntry(kind, resultText(r), 'output too large to read inline'), name: changeOf(kind, command, null) }
384 }
385 const text = resultText(r)
386 if (text === null) return { ...unparsedEntry(kind, '', 'no result text'), name: changeOf(kind, command, null) }
387 const { value, problem } = findJson(text)
388 if (!value) return { ...unparsedEntry(kind, text, problem), name: changeOf(kind, command, null) }
389 const name = changeOf(kind, command, value)
390 if (RESOLVING.has(kind) && isString(value.error) && Array.isArray(value.candidates) && !(VERDICT[kind] in value)) {
391 return { kind, error: value.error, candidates: value.candidates.filter(isString), name }
392 }
393 const { entry, missing, unread } = READERS[kind](value)
394 if (unread) return { ...unparsedEntry(kind, text, unread), name }
395 if (!entry) return { ...unparsedEntry(kind, text, `fields missing: ${missing.join(', ')}`), name }
396 return { kind, ...entry, name }
397}
398
399/**
400 * Which write a path is (D4): an artifact under `openspec/changes/<dir>/`
401 * (`archive` excluded), the explore brief, or a review-artifacts findings
402 * file; otherwise `null`. A path files a write under its directory and never
403 * names the change.
404 */
405export function writeOf(path) {
406 if (typeof path !== 'string' || !path) return null
407 const p = path.replace(/\\/g, '/')
408 const artifact = p.match(/(?:^|\/)openspec\/changes\/([^/]+)\/(.+)$/)
409 if (artifact) return artifact[1] === 'archive' ? null : { kind: 'artifact', change: artifact[1], file: artifact[2] }
410 if (/(?:^|\/)\.claude\/handoff\/explore-[^/]*\.md$/.test(p)) return { kind: 'brief', path }
411 const findings = p.match(/(?:^|\/)\.claude\/metrics\/review-artifacts-(.+)-\d{8}-\d{6}\.json$/)
412 if (findings) return { kind: 'findings', change: findings[1], path }
413 return null
414}
415
416/**
417 * The advisor entries one `turn.step` result carries in `serverToolUses`
418 * (replace-subagent-advisors-with-advisor-tool, "Counting consults"): the id
419 * of each entry whose `name` is the string `advisor`, or `null` for one with no
420 * string id. Anything that is not an array, and any entry that is not an
421 * object, reads as no entry. Never throws.
422 */
423export function advisorEntryIds(serverToolUses) {
424 if (!Array.isArray(serverToolUses)) return []
425 return serverToolUses.filter(u => isObject(u) && u.name === 'advisor').map(u => (isString(u.id) ? u.id : null))
426}
427
428/** A fresh advisor tally: what the spec run has seen, keyed by entry id. */
429export const freshAdvisorTally = () => ({ session: 0, subagents: 0, ids: new Set() })
430
431/**
432 * Adds one `turn.step`'s advisor entries to `tally`, toward the session or
433 * toward subagents, each id once across the run; an entry with no id counts
434 * once where it is. Returns how many were added. Never throws.
435 */
436export function addAdvisorEntries(tally, serverToolUses, fromSubagent) {
437 if (!isObject(tally) || !(tally.ids instanceof Set)) return 0
438 let added = 0
439 for (const id of advisorEntryIds(serverToolUses)) {
440 if (id !== null) {
441 if (tally.ids.has(id)) continue
442 tally.ids.add(id)
443 }
444 if (fromSubagent) tally.subagents++
445 else tally.session++
446 added++
447 }
448 return added
449}
450
451/**
452 * The pane's advisor-consults line, or `null` until the run has seen its first
453 * advisor entry: the meter does not read settings, so it cannot tell a tool
454 * that is off from an engine that never reports server tool uses, and a line
455 * before the first entry would read as a measured zero. The count is drawn and
456 * never compared.
457 */
458export function advisorConsultsText(tally) {
459 if (!isObject(tally) || !isCount(tally.session) || !isCount(tally.subagents)) return null
460 if (tally.session + tally.subagents === 0) return null
461 return `advisor consults seen: session ${tally.session} · subagents ${tally.subagents}`
462}
463
464/** The status line's stage for an entry, in the CLI's words (D6's table). */
465export function stageText(entry, spawned = 0) {
466 if (!isObject(entry)) return null
467 const { kind } = entry
468 if (typeof entry.unparsed === 'string') return `${kind} (unparsed)`
469 if (isString(entry.error)) return `${kind}: change not resolved (candidates ${countOf(entry.candidates) ?? 0})`
470 switch (kind) {
471 case 'explore':
472 return spawned ? `explore (${spawned} investigators)` : 'explore'
473 case 'review-artifacts':
474 return 'review-artifacts'
475 case 'new-change':
476 return 'new change'
477 case 'status': {
478 const done = entry.artifacts.filter(a => a.status === 'done').length
479 const next = entry.artifacts.find(a => a.status === 'ready')
480 return `status ${done}/${entry.artifacts.length} done${next ? ` · next: ${next.id}` : ''}`
481 }
482 case 'drift':
483 return `drift (unarchived ${entry.unarchived} · broken ${entry.broken} · aging ${entry.aging})`
484 case 'notes':
485 return `notes ${entry.rows} matched (omitted ${entry.omitted})`
486 case 'ledger':
487 if (entry.missing === true) return 'ledger missing'
488 if (entry.unparseable === true) return 'ledger unparseable'
489 return `ledger ${entry.blocking ? 'blocking' : 'clear'} (needs_human ${shown(entry.needsHuman)} · invalid ${shown(entry.invalidCount)})`
490 case 'validate':
491 return entry.ready ? 'validate READY' : `validate NOT READY (problems ${entry.problems.length})`
492 case 'gate': {
493 const notes = [
494 ...(entry.malformed ? [`malformed ${entry.malformed}`] : []),
495 ...(entry.metrics && entry.metrics.written === false ? ['metrics not written'] : [])
496 ]
497 if (entry.passed) return `gate PASS${notes.length ? ` (${notes.join(' · ')})` : ''}`
498 const { blocker, warning } = entry.counts
499 return `gate BLOCKED (${[`blocker ${blocker}`, `warning ${warning}`, ...notes].join(' · ')})`
500 }
501 case 'autonomy':
502 return `autonomy ${entry.command || '?'}`
503 case 'ready':
504 return entry.ready ? 'ready true' : `ready false (blockers ${entry.blockers})`
505 case 'checkpoint':
506 return 'checkpoint'
507 default:
508 return null
509 }
510}
511
512/** `interlock spec: <change> · <stage>`, the stage omitted until there is one (D6). */
513export function specStatusText(spec) {
514 const stage = stageText(spec.stage, spec.explore.spawned)
515 return `interlock spec: ${spec.current || UNKNOWN_CHANGE}${stage ? ` · ${stage}` : ''}`
516}
517
518const iso = at => (Number.isFinite(at) ? new Date(at).toISOString() : null)
519
520/** A result line on the pane, by its JSON names, or why it is absent (D6). */
521function resultLine(kind, entry) {
522 if (!entry) return `${kind}: not run yet`
523 if (typeof entry.unparsed === 'string') return `${kind}: not read (${entry.reason}) · ${entry.unparsed}`
524 if (isString(entry.error)) return `${kind}: change not resolved · candidates ${entry.candidates.join(', ') || 'none'}`
525 switch (kind) {
526 case 'drift':
527 return `drift: unarchived ${entry.unarchived} · broken ${entry.broken} · aging ${entry.aging}`
528 case 'notes':
529 return `notes: ${entry.rows} matched · omitted ${entry.omitted} · unreadable ${entry.unreadable}`
530 case 'ledger':
531 return `ledger: ${['blocking', 'needsHuman', 'invalidCount', 'missing', 'unparseable']
532 .filter(f => f in entry)
533 .map(f => `${f} ${entry[f]}`)
534 .join(' · ')}`
535 case 'validate':
536 return `validate: ready ${entry.ready} · problems ${entry.problems.length}`
537 case 'gate': {
538 const { blocker, warning, suggestion } = entry.counts
539 const m = entry.metrics
540 const metrics = !m
541 ? ''
542 : m.written === false
543 ? ` · metrics not written (${m.reason || 'no reason given'})`
544 : m.path
545 ? ` · metrics ${m.path}`
546 : ''
547 return `gate: passed ${entry.passed} · blocker ${blocker} · warning ${warning} · suggestion ${suggestion} · malformed ${entry.malformed}${metrics}`
548 }
549 case 'ready':
550 return `ready: ready ${entry.ready} · blockers ${entry.blockers}`
551 default:
552 return `${kind}: not run yet`
553 }
554}
555
556/**
557 * The `/interlock-spec` pane as keyed lines, `{ key, text, bold?, dim? }`
558 * (D6): the module maps them onto the engine's `Box` and `Text` and nothing
559 * else. No row carries a tick, a colour or a threshold.
560 */
561export function specPaneLines(spec) {
562 if (!spec || spec.phase === 'idle') return [{ key: 'spec-none', text: NO_SPEC_LINE, dim: true }]
563 const change = spec.current ? spec.changes.get(spec.current) || {} : {}
564 const status = change.status
565 const out = []
566 const schema = status && !status.unparsed && !status.error && status.schemaName
567 out.push({ key: 'spec-header', text: `${spec.current || UNKNOWN_CHANGE}${schema ? ` · schema ${schema}` : ''}`, bold: true })
568 if (!status || typeof status.unparsed === 'string' || isString(status.error)) {
569 out.push({ key: 'spec-status', text: resultLine('status', status) })
570 } else {
571 for (const a of status.artifacts) out.push({ key: `spec-artifact-${a.id}`, text: `${a.id} · ${a.status} · ${a.outputPath || '?'}` })
572 if (status.applyRequires) out.push({ key: 'spec-apply-requires', text: `applyRequires: ${status.applyRequires.join(', ') || 'none'}` })
573 }
574 const spawned = spec.explore.spawned
575 out.push({
576 key: 'spec-explore',
577 text: `explore: ${spawned ? `${spawned} investigators spawned` : 'none reported by this host'} · ${
578 spec.explore.brief ? `brief ${spec.explore.brief}` : 'no brief written yet'
579 }`
580 })
581 out.push({ key: 'spec-drift', text: resultLine('drift', spec.drift) })
582 for (const kind of ['notes', 'ledger', 'validate', 'gate', 'ready']) {
583 out.push({ key: `spec-${kind}`, text: resultLine(kind, change[kind]) })
584 if (kind === 'validate' && change.validate && Array.isArray(change.validate.problems)) {
585 change.validate.problems.forEach((p, i) => out.push({ key: `spec-validate-problem-${i}`, text: p }))
586 }
587 }
588 out.push({ key: 'spec-autonomy', text: `autonomy: ${spec.autonomy || 'not run yet'}` })
589 const consults = advisorConsultsText(spec.advisor)
590 if (consults) out.push({ key: 'spec-advisor-consults', text: consults })
591 out.push({ key: 'spec-writes', text: 'writes', bold: true })
592 const writes = spec.current ? spec.writes.get(spec.current) : null
593 if (!writes || !writes.size) out.push({ key: 'spec-writes-none', text: 'no artifact writes yet', dim: true })
594 for (const [file, w] of writes || []) {
595 out.push({ key: `spec-write-${file}`, text: `${file} · written ${w.count}× · ${iso(w.at) ? `last ${iso(w.at)}` : 'last time unknown'}` })
596 }
597 const findings = spec.current ? spec.findings.get(spec.current) : null
598 if (findings) out.push({ key: 'spec-findings', text: `findings file: ${findings}` })
599 out.push({ key: 'spec-last-activity', text: iso(spec.lastActivityAt) ? `last activity ${iso(spec.lastActivityAt)}` : 'last activity unknown' })
600 if (spec.checkpointCrossed) {
601 out.push({
602 key: 'spec-checkpoint',
603 text: iso(spec.checkpointAt) ? `checkpoint reached ${iso(spec.checkpointAt)}` : 'checkpoint reached, time unknown'
604 })
605 }
606 if (spec.handedOver) {
607 out.push({
608 key: 'spec-handover',
609 text: iso(spec.handedOverAt) ? `handed over to ship at ${iso(spec.handedOverAt)}` : 'handed over to ship, time unknown'
610 })
611 }
612 const others = spec.order.filter(name => name !== spec.current)
613 if (others.length) out.push({ key: 'spec-other-changes', text: `other changes named this run: ${others.join(', ')}` })
614 out.push({ key: 'spec-record', text: SPEC_RECORD_LINE, dim: true })
615 return out
616}
617
618/** The debug line for a keyed line that crossed when no spec run could draw it (D3). */
619export function lateLineText(kind, phase) {
620 return phase === 'checkpoint'
621 ? `interlock spec: a ${kind} line crossed after the checkpoint; not drawn`
622 : `interlock spec: a ${kind} line crossed with no live spec run; not drawn`
623}
624
625/** The debug line for a keyed line's result that was not read (D3). */
626export function unreadLineText(entry, command) {
627 return `interlock spec: ${entry.kind} result not read (${entry.reason}): ${String(command).slice(0, 80)}`
628}
629
630/**
631 * A spec run record (D7): `phase` is `idle`, `live`, `checkpoint` or
632 * `handed-over`. `changes` holds each named change's results; the unnamed
633 * slot is `null`'s, never drawn. Writes and findings are filed by directory.
634 */
635export function freshSpec(flags = {}) {
636 return {
637 phase: 'idle',
638 current: null,
639 changes: new Map(),
640 order: [],
641 explore: { spawned: 0, brief: null },
642 drift: null,
643 autonomy: null,
644 stage: null,
645 writes: new Map(),
646 findings: new Map(),
647 advisor: freshAdvisorTally(),
648 startedAt: null,
649 lastActivityAt: null,
650 checkpointCrossed: false,
651 checkpointAt: null,
652 handedOver: false,
653 handedOverAt: null,
654 clockFailed: false,
655 afterBoundary: flags.afterBoundary === true,
656 // Whether a keyed line with no run to draw it has been named on the debug log.
657 lateNamed: false
658 }
659}
660lib/lane.mjs 177 lines1// The lane rule (draw-wave-plan-and-handoff-graph-from-the-cli design D3): the
2// tier, label, title, model and effort a lane dispatches under, the cut that
3// fits a drawn row to a width, and the one reader of a task's `dependsOn`.
4//
5// Moved out of `lib/waves.mjs` unchanged, because that module imports
6// `node:crypto` and the ship meter's hooks module, which runs in the engine with
7// no Node, needs the same names the planner gives a lane. `lib/waves.mjs`
8// re-exports the lane functions it always exported, so its importers are
9// unchanged.
10//
11// Pure and Node-free: `test/spine/draw-plan.test.mjs` walks this closure.
12
13import { EFFORT, LANE_CAPS } from './limits.mjs'
14
15/** The tier a lane dispatches on: the highest among its tasks. */
16export function laneTier(lane) {
17 return lane.reduce((m, t) => (Number.isInteger(t.tier) && t.tier > m ? t.tier : m), 0)
18}
19
20/**
21 * The label a lane runs under — the name its agent, its trajectory line and its
22 * briefing file all carry.
23 *
24 * Stable across replays, so a resumed run cache-hits the lane it already ran.
25 * This derivation was written three times (the workflow script, the ACP driver,
26 * and `bin/interlock`'s own trajectory logger); it is stated here once because a
27 * trajectory line and the agent it describes must carry one name, not two.
28 */
29export function laneLabel(lane) {
30 return lane.length === 1 ? lane[0].id : `${lane[0].id}+${lane.length - 1}`
31}
32
33/** Separates a spawn's label from the words its title adds. */
34export const TITLE_SEPARATOR = ' · '
35
36/** The longest title a lane displays under, ellipsis included. */
37const TITLE_MAX = 48
38
39/**
40 * The words a lane's title is built from: the first six words of a task
41 * description, stripped of markdown emphasis and trailing punctuation; '' when
42 * there are none. A fixed point — the gist of a gist is itself — so a plan
43 * summary that stores it in place of the description titles every lane exactly
44 * as the plan does (draw-the-wave-board-in-the-meter-pane design D3).
45 *
46 * @param {unknown} description
47 * @returns {string}
48 */
49export function titleGist(description) {
50 const text = typeof description === 'string' ? description : ''
51 const words = text.replace(/[`*_]/g, '').replace(/\s+/g, ' ').trim().split(' ').slice(0, 6).join(' ')
52 return words.replace(/[\s.,;:—-]+$/, '')
53}
54
55/**
56 * What a lane is called in words: `task 1.1` for a one-task lane, `tasks 1.1+2`
57 * for a lane of several. The role word names what the agent is doing for a
58 * reader of /workflows and the meter, where a bare `1.5` reads as an outline
59 * sub-number. Display only: the join key stays `laneLabel`.
60 */
61export function laneName(lane) {
62 return `${lane.length === 1 ? 'task' : 'tasks'} ${laneLabel(lane)}`
63}
64
65/**
66 * The words a lane's title adds after its name: the first words of its first
67 * task's description, cut so that label + separator + gist fits TITLE_MAX
68 * (ellipsis included); '' when the description says nothing. The role word does
69 * not count against the cap, so a gist is cut exactly where it always was.
70 */
71export function laneGist(lane) {
72 const gist = titleGist(lane[0] && lane[0].description)
73 if (!gist) return ''
74 const head = `${laneLabel(lane)}${TITLE_SEPARATOR}`
75 const full = `${head}${gist}`
76 const cut = full.length <= TITLE_MAX ? full : `${full.slice(0, TITLE_MAX - 1).trimEnd()}…`
77 return cut.slice(head.length)
78}
79
80/**
81 * The name a lane is SHOWN under — its role word and label, then the first words
82 * of its first task's description: `tasks 1.1+5 · Add the relaunch guard to…`.
83 * The role word names what the agent is doing for a reader of /workflows and the
84 * meter; the cap is on the label and gist, so a gist is cut where it always was.
85 *
86 * Display only. Everything that joins on a lane — its briefing file, worktree,
87 * trajectory line, record-batch fold — keys on `laneLabel`, because a key built
88 * from prose would change whenever a task was reworded. It is still a pure
89 * function of the lane, so a replay displays, and cache-hits, the same agent.
90 */
91export function laneTitle(lane) {
92 const gist = laneGist(lane)
93 return gist ? `${laneName(lane)}${TITLE_SEPARATOR}${gist}` : laneName(lane)
94}
95
96/**
97 * One task's declared dependency edges, deduplicated, in the order written.
98 *
99 * THE ONLY READER of `task.dependsOn`, for the same reason `predictedPaths` is
100 * the only reader of `task.paths`: validation, layering and the replan path all
101 * ask the same question, and three readers each doing their own trimming is how
102 * one of them ends up matching an id the others do not. Here rather than in
103 * `lib/waves.mjs`, which imports it, so the Node-free plan summary can ask it
104 * too (draw-the-wave-board-in-the-meter-pane design D3).
105 *
106 * Entries are trimmed. A whitespace-only entry is dropped here and rejected by
107 * `validate`, which runs first on every path into the planner.
108 */
109export function dependsOnIds(task) {
110 const raw = task && Array.isArray(task.dependsOn) ? task.dependsOn : []
111 const out = []
112 for (const entry of raw) {
113 if (typeof entry !== 'string' || !entry.trim()) continue
114 const id = entry.trim()
115 if (!out.includes(id)) out.push(id)
116 }
117 return out
118}
119
120/**
121 * The model a lane dispatches on, derived from the lane's shape and hardest tier.
122 *
123 * A lane of one task dispatches on that task's clamped model — haiku or sonnet,
124 * or opus for a tier-5 task or a solo promotion. A lane of two or more tasks is
125 * the work agent the planner chose not to split: it dispatches on opus when its
126 * hardest tier is at or above `LANE_CAPS.opusMinTier`, or when every task already
127 * carries opus (solo promotion of the whole change). Otherwise it runs on
128 * sonnet — routine multi-task work no longer pays the flagship model by default.
129 * Nothing here rewrites `task.model`: a narrowed lane of one returns to the
130 * task's model.
131 */
132export function laneModel(lane) {
133 if (!Array.isArray(lane) || lane.length === 0) return 'sonnet'
134 if (lane.length === 1) {
135 const only = lane[0]
136 return (only && only.model) || 'sonnet'
137 }
138 // Solo promotions rewrite every task to opus after the clamp; an all-opus
139 // multi-task lane is that decision (or a pure tier-5 pack), not the floor.
140 if (lane.every(t => t && t.model === 'opus')) return 'opus'
141 return laneTier(lane) >= LANE_CAPS.opusMinTier ? 'opus' : 'sonnet'
142}
143
144/**
145 * The reasoning effort a lane dispatches at — a sibling of `laneModel`, derived
146 * from the same hardest-task tier, looked up in the table published by
147 * `lib/limits.mjs`. A lane is one agent, and that agent must be capable of the
148 * hardest thing in the lane, so the effort is the hardest task's, never the
149 * first task's — the one direction of this trade that is not survivable.
150 *
151 * Returns `null` (inherit the session default — do not force) for tiers 3–4 by
152 * policy and for an untiered lane (`laneTier` → 0) by fallback; the plan's
153 * effort report distinguishes the two. Effort is derived from tier alone. The
154 * model a lane dispatches on follows shape and the opus floor, so a multi-task
155 * lane of tier-1 or tier-2 tasks runs on sonnet at `low`.
156 */
157export function laneEffort(lane) {
158 const tier = laneTier(lane)
159 return EFFORT.byTier[tier] ?? null
160}
161
162/**
163 * A drawn row fitted to `columns` code points: unchanged when it fits; else its
164 * first `columns - 1` code points and `…`, so the result is exactly `columns`
165 * wide. Both renderers cut every row with it, so a plan board and a run board
166 * cut alike, and at the place the ship meter's pane cuts a line.
167 *
168 * @param {string} text
169 * @param {number} columns
170 * @returns {string}
171 */
172export function fitRow(text, columns) {
173 const points = [...text]
174 if (points.length <= columns) return text
175 return `${points.slice(0, Math.max(0, columns - 1)).join('')}…`
176}
177