Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(core): refresh declared model names on main [O8,O3]
Corey Olson056d767e9fcb
diff --cc docs/api.mdindex 158b6a3e,daa7eff2..fa365da2--- a/docs/api.md+++ b/docs/api.md@@@ -19,10 -27,11 +27,11 @@@ The board-state API's item projection i| `version` | `version:number`, `release:string` || `init` | `version:number`, `root:string`, `notes:array` || `hooks` | `version:number`, `notes:array` |-| `join` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string` |+| `join` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `model:string`, `displayName:string` |+ | `takeover` | `version:number`, `agent:string`, `path:string` |-| `worktree` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `branch:string`, `prompt:string` |+| `worktree` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `branch:string`, `prompt:string`, `model:string`, `displayName:string` || `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `stale:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `dirty:number`, `next:string` |-| `whoami` | `version:number`, `id:string`, `lane:string`, `path:string` |+| `whoami` | `version:number`, `id:string`, `lane:string`, `path:string`, `model:string`, `displayName:string` || `lanes` | `version:number`, `lanes:object`, `shared:array`, `coordinator:string` || `resources` | `version:number`, `resources:array` || `settings` | `version:number`, `settings:object` |@@@ -85,9 -97,15 +97,15 @@@| `hook pre-push` | `version:number`, `messages:array` |<!-- api-command-shapes:end -->- `join` and `worktree` require a free-text `--model` label or `PULLBOARD_MODEL` environment value; labels are not inferred from a provider or family. Rejoining the same worktree preserves its agent id; a supplied model or optional `--family` updates that declaration, while omission preserves it. `pullboard.json` may set `agents.names` to `suffix` (the default, `web-1 (Claude)`) or `prefix` (`claude-web-1`). CLI `agent` fields remain stable ids; `displayName` shows the chosen style. `resume.me` and API state `agents[]` carry `model` and `displayName`; older agents with no model display `unknown`. Each event records the actor model in `event_detail.model` for a registered agent, with `unknown` for legacy agents without a declaration. `show` includes `item_builder_family` and each verdict's `verdict_verifier_family`. These family fields are `null` when the agent did not declare a family, and later declarations do not rewrite prior submissions or verdicts.+ `hook pre-merge-commit` runs the same staged checks as `hook pre-commit` before Git creates an automatic merge commit. `init` and `hooks` install it; `doctor` names it when absent at Git's effective hook path. Lane ownership comes from `HEAD:pullboard.json`, so an unstaged configuration edit cannot grant a lane new folders. Lane-sensitive checks refuse a repository with `info/grafts` in its Git common directory because grafts alter ancestry even when replacement objects are disabled.- `status.reviewQueue` contains `pending`, `reviewing` (distinct agents with live review leases), `reserved`, `oldestSubmittedAt` and `ageMs`. Age starts at each outstanding item's latest submit event; reserving or renewing its review does not reset it. An empty queue has `oldestSubmittedAt: null` and `ageMs: 0`.-`join` and `worktree` accept an optional free-text `--family` declaration. Rejoining the same worktree preserves its agent id; a supplied family updates the declaration, while omitting `--family` preserves it. `resume` includes it as `me.family`; `show` includes `item_builder_family` and each verdict's `verdict_verifier_family`. These recorded fields are `null` when the agent did not declare a family, and later declarations do not rewrite prior submissions or verdicts.++`join` and `worktree` require a free-text `--model` label or `PULLBOARD_MODEL` environment value; labels are not inferred from a provider or family. Rejoining the same worktree preserves its agent id; the model label is required on every join, and omitting the optional `--family` preserves its prior declaration. `pullboard.json` may set `agents.names` to `suffix` (the default, `web-1 (Claude)`) or `prefix` (`claude-web-1`). CLI `agent` fields remain stable ids; `displayName` shows the chosen style. `resume.me` and API state `agents[]` carry `model` and `displayName`; older agents with no model display `unknown`. Each event records the actor model in `event_detail.model` for a registered agent, with `unknown` for legacy agents without a declaration. `show` includes `item_builder_family` and each verdict's `verdict_verifier_family`. These family fields are `null` when the agent did not declare a family, and later declarations do not rewrite prior submissions or verdicts.++ Each checkout is bound to the first agent session that writes there. The local Git directory holds only its session digest, agent id and timestamp; bindings are absent from board exports and relay snapshots. Another agent session gets `NOT_YOUR_CHECKOUT` and the command to make its own worktree. The same agent starting a new session runs `pullboard takeover`; the existing ordered shout records the takeover, addressed to the person for the main checkout or the coordinator for a lane checkout. Markerless terminals, reads, the view and person requests keep their existing behavior. A shout or decision addressed to its sender is refused with `SELF_SHOUT`.++ `status.reviewQueue` contains `pending`, `reviewing` (distinct agents with live review leases), `reserved`, `oldestSubmittedAt` and `ageMs`. Age starts at each outstanding item's latest submit event; reserving or renewing its review does not reset it. An empty queue has `oldestSubmittedAt: null` and `ageMs: 0`. Among unreserved submissions, `awaitingFirstReview` counts items with no release since their latest submission; `releasedWithoutVerdict` counts those released without a verdict. `releasedItems` lists `{item, releases, reason}` with the cumulative release count and latest reason for that submission. Historical releases without a reason show `reason not recorded`.++ Releasing a reserved review requires a nonempty one-line `--note` (or `--note-file`); the authenticated release action accepts the same `note` field. A refusal keeps the reservation and records no release. The same reviewer is not offered that submission again until it is resubmitted or an hour passes, while other reviewers remain eligible. Releasing a build claim keeps its existing behavior and does not require a reason.When outstanding reviews reach `verify.reviewRatio` times the active reviewers (default 3, with zero reviewers counting as one), `next` first offers a review the agent may take. This creates no claim or reservation. Its additive v1 `offer` has the review's `item` id, exact `command` to reserve it, `queue` and `ratio`; `build` previews the otherwise available build or is `null`. `next --verify <id>` reserves explicitly. `next --build` claims explicitly; a fresh claim's event detail records `reviewSkipped` with the offered id (or `null`), ratio and queue snapshot. Renewing an existing claim creates no new skip.diff --cc docs/formats.mdindex 64521021,c3a29297..f94119b0--- a/docs/formats.md+++ b/docs/formats.md@@@ -70,12 -76,20 +76,20 @@@ The board file is in the repository's G| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. || `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. || `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |- | `move engine` | `3` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |-| `move engine` | `7` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |++| `move engine` | `8` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |<!-- format-versions:end -->- Pullboard 0.6.1 released engine 1. The first change to released move semantics raises the engine once for the next release; later changes developed before that release keep the same version. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Older clients refuse engine-2 moves before changing rows or replay cursors; engine 2 still accepts engine-1 moves.-Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Pullboard 0.8.3 released engine 6, adding board-scoped machine credentials and permitting machine execution only for one exact, earlier authenticated phone request, including its payload digest. Engine 7 adds ordered item holds through `holdItem` and `releaseItemHold`; engine-6 clients stop with `ENGINE_VERSION` before interpreting either operation or advancing their replay cursor. Older request receipts retain their recorded engine semantics. Upgrade every linked device before using the new moves.++Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Pullboard 0.8.3 released engine 6, adding board-scoped machine credentials and permitting machine execution only for one exact, earlier authenticated phone request, including its payload digest. Engine 7 adds ordered item holds through `holdItem` and `releaseItemHold`; engine-6 clients stop with `ENGINE_VERSION` before interpreting either operation or advancing their replay cursor. Older request receipts retain their recorded engine semantics. Pullboard 0.8.4 released engine 7. Engine 8 is the shared 0.8.5 move version: registration retains declared model labels and every registered agent move records its model snapshot. Engines 1 through 7 retain their original registration and event details without these model fields. Upgrade every linked device before using the new moves.- Engine 3 checks each move or request against the relay's authenticated sender before replay. An agent token acts only as its named agent and cannot act as the person. Refused attribution attempts advance the sequence with a `relay_refusal_<sequence>` receipt and a `relay_refused` event naming the sender, attempted actor and refusal code. They change no item, shout or verdict and do not reserve the forged operation id. Snapshot restoration requires a person sender. The event log remains version 1.+ The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.+ A linked board requires at least engine 3 after issuing any agent token, including+ revoked or expired tokens. Issuing any machine credential raises that board’s minimum to engine 6, including after revocation or expiry. The minimum survives reopening the auth database;+ unlink removes the board and ends its lifetime. A missing declaration is legacy+ engine 1. Board-content requests below their minimum, and malformed declarations,+ receive `ENGINE_VERSION` with upgrade guidance before records are returned or+ changed. The service checks again under its board lock and on live-stream polls.++ Engine 3 checks each move or request against the relay's authenticated sender before replay. An agent token acts only as its named agent and cannot act as the person. Refused attribution attempts advance the sequence with a `relay_refusal_<sequence>` receipt and a `relay_refused` event naming the sender, attempted actor and refusal code. They change no item, shout or verdict and do not reserve the forged operation id. Snapshot restoration requires an authenticated person or board machine sender. A machine can register ordinary agents and ensure the coordinator; other person effects require an earlier authenticated phone intent with exact operation, arguments, target and digest. Every replica consumes its execution once, including row decisions waiting for repository application. Receipt shouts have fixed text; refusal details remain in the structured request result. The event log remains version 1.A board without `event_log_version` is a legacy version-0 event log. Opening an older board writes the current marker without replacing its events. Opening a newer event log refuses with `EVENT_LOG_VERSION`, naming the stored and supported versions and asking you to upgrade Pullboard. `doctor` reports that version conflict read-only.@@@ -225,13 -252,13 +252,14 @@@ Each connection also has a temporary `m## Event log- The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its append-only record format has the independent `EVENT_LOG_VERSION`. Each event has an increasing integer id, an ISO timestamp, the actor, the event kind, an optional item id, and a JSON object in `event_detail`. Board moves append their event inside the same immediate transaction as the move. Events are append-only; board triggers reject updates and deletes. The actor column is the acting agent id, except guard-repair events, which use `board`. Each event by a registered agent also carries a `model` string snapshot in `event_detail`; legacy agents without a declaration use `unknown`. This common snapshot is separate from the per-kind payload fields listed below. The following rows name the emitted kinds and the union of their operation-specific detail keys:-The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its append-only record format has the independent `EVENT_LOG_VERSION`. Each event has an increasing integer id, an ISO timestamp, the actor, the event kind, an optional item id, and a JSON object in `event_detail`. Board moves append their event inside the same immediate transaction as the move. Events are append-only; board triggers reject updates and deletes. The actor column is the acting agent id, except guard-repair events, which use `board`. The following rows name the emitted kinds and their established detail keys; CLI accept events additionally carry the frozen-check result described below:++The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its append-only record format has the independent `EVENT_LOG_VERSION`. Each event has an increasing integer id, an ISO timestamp, the actor, the event kind, an optional item id, and a JSON object in `event_detail`. Board moves append their event inside the same immediate transaction as the move. Events are append-only; board triggers reject updates and deletes. The actor column is the acting agent id, except guard-repair events, which use `board`. Under engine 8, each event by a registered agent also carries a `model` string snapshot in `event_detail`; legacy agents without a declaration use `unknown`. Declared models live under `agent_model:<agent id>` in `board_meta`, without changing the agent table or stable ids. Rejoining with another model appends a `model` event whose common snapshot holds the new declaration. This common snapshot is separate from the per-kind payload fields listed below. The following rows name the emitted kinds and the union of their operation-specific detail keys; CLI accept events additionally carry the frozen-check result described below:<!-- events:start -->| Kind | Actor | Detail fields || --- | --- | --- || `join` | joining agent | `lane`, `route` || `family` | agent | `family` |++| `model` | agent | — || `moved` | coordinator | `path` || `add` | item creator | `lane`, `specIds`, `after`, `route` || `edit` | editor | `brief`, `route`, `criterion`, `check`, `unfrozen` |diff --cc docs/formats.test.jsindex b0e28022,0752aba5..2a931df2--- a/docs/formats.test.js+++ b/docs/formats.test.js@@@ -144,6 -230,6 +230,7 @@@ function recordEventContract()const coordinator = ensureCoordinator(board, '/coordinator');const builder = register(board, { lane: 'docs', path: '/builder' });register(board, { lane: 'docs', path: '/builder', family: 'codex' });++ register(board, { lane: 'docs', path: '/builder', model: 'Fixture Model' });const reviewer = register(board, { lane: 'tests', path: '/reviewer' });register(board, { lane: 'small', path: '/small', route: 'light' });ensureCoordinator(board, '/coordinator-moved');@@@ -346,6 -538,6 +539,7 @@@ test('[A5] schema, versions, event kindconst actorByKind = {join: 'joining agent',family: 'agent',++ model: 'agent',moved: 'coordinator',add: 'item creator',edit: 'editor',diff --cc src/board.jsindex 612d1556,d75de199..879add9f--- a/src/board.js+++ b/src/board.js@@@ -356,9 -363,6 +363,10 @@@ export function atomic(board, work)* @param {object} [detail]*/function logEvent(board, by, kind, itemId, detail = {}) {+ const model = agentModel(board, by);+ const isAgent = Boolean(board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(by));- const recorded = isAgent ? { ...detail, model: model ?? 'unknown' } : detail;++ const recorded = (board.executionEngineVersion ?? ENGINE_VERSION) >= 8 && isAgent++ ? { ...detail, model: model ?? 'unknown' } : detail;const inserted = board.db.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)',@@@ -461,13 -444,13 +469,14 @@@ function saveAgentModel(board, id, mode* worktree as the next agent in its lane (`web-1`, `web-2`, ...), on a route: the tier of model* behind it, which decides the items it may take (B13). The optional family is free text supplied* by the agent; the board neither names nor infers it. Registering again preserves the agent id;- * an explicitly supplied family updates the declaration, while omission preserves it.+ * explicitly supplied family and model values update their declarations, while omission preserves them.** @param {any} board- * @param {{ lane: string, path: string, route?: string, family?: string | null }} who+ * @param {{ lane: string, path: string, route?: string, family?: string | null, model?: string | null }} who* @returns {string} The agent's id.*/-export function register(board, { lane, path, route = 'strong', family }) {+export function register(board, { lane, path, route = 'strong', family, model }) {++ if ((board.executionEngineVersion ?? ENGINE_VERSION) < 8) model = undefined;checkRoute(route);if (lane === COORDINATOR && route !== 'strong') {throw new Refused('BAD_ROUTE', 'the coordinator plans, merges and verifies; it is always strong');@@@ -503,7 -482,6 +512,7 @@@'INSERT INTO agent (agent_id, agent_lane, agent_path, agent_route, agent_family, agent_created_at) VALUES (?, ?, ?, ?, ?, ?)',).run(id, lane, path, route, family ?? null, now(board));- saveAgentModel(board, id, model);++ if ((board.executionEngineVersion ?? ENGINE_VERSION) >= 8) saveAgentModel(board, id, model);logEvent(board, id, 'join', null, route === 'strong' ? { lane } : { lane, route });return id;});diff --cc src/cli.jsindex 5228da88,4d9de0fb..a87d5e12--- a/src/cli.js+++ b/src/cli.js@@@ -9,13 -9,13 +9,14 @@@ import { basename, dirname, isAbsoluteimport { pathToFileURL } from 'node:url';import { parseArgs } from 'node:util';import * as store from './board.js';- import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';+ import { CONFIG_FILE, COORDINATOR, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';+import { displayAgentName } from './agent-names.js';- import { loadDoctrine } from './doctrine.js';- import { requirePersonChannel } from './person.js';+ import { doctrineHistory, loadDoctrine } from './doctrine.js';+ import { agentSessionDigest, requirePersonChannel } from './person.js';+ import { bindLocalSession } from './agent-session.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';- import { digestOf, gateReport, runGate, runShell } from './gate.js';- import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';+ import { digestOf, gateReport, runGate, runShell, runSubmitGate, submitGateReport, withGateSlot } from './gate.js';+ import { bareWorktreeFinding, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';import {FIX_NOTE,applyFixers,@@@ -72,11 -122,11 +123,12 @@@ Nothing ships until a second agent veriSet uppullboard tour see it work: a reject and its rework, scripted, in thirty secondspullboard init config, SPEC.md, agent instructions, git hooks, board- pullboard worktree <lane> [--route light] [--family <name>] make and join a worktree for a new agent- pullboard join <lane> [--route light] [--family <name>] register this worktree as an agent- --route sets which work the model can take; --family records its name+ pullboard worktree <lane> --model <name> [--route light] [--family <name>] make and join a worktree for a new agent+ pullboard join <lane> --model <name> [--route light] [--family <name>] register this worktree as an agent+ --model is required (or set PULLBOARD_MODEL); --family records its family+ pullboard.json agents.names: suffix (default) or prefixpullboard whoami | lanes | status who you are, the lanes, the board at a glance+ pullboard takeover rebind this checkout when the same agent starts a new sessionpullboard resources local resource holders and their FIFO queuespullboard settings [gateSlots <n>] view or set this machine's gate slots (default 2)pullboard view [--port N] [--no-open] every project on this machine in your browser: items, shouts, doctrine,@@@ -193,12 -256,13 +258,13 @@@ const HELP_GROUPS =];const HELP_EXAMPLES = {- tour: 'pullboard tour', init: 'pullboard init', worktree: 'pullboard worktree web', resume: 'pullboard resume',+ tour: 'pullboard tour', init: 'pullboard init', worktree: 'pullboard worktree web --model "Example Model"', join: 'pullboard join web --model "Example Model"', resume: 'pullboard resume',add: 'pullboard add web "Upload page" --specs G1', list: 'pullboard list web', show: 'pullboard show 12',claim: 'pullboard claim 12', submit: 'pullboard submit 12', 'next --verify': 'pullboard next --verify',+ fact: 'pullboard fact 12 measurement "The check passes in 8 seconds"',verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',- status: 'pullboard status', view: 'pullboard view', log: 'pullboard log 12', ledger: 'pullboard ledger',+ status: 'pullboard status', view: 'pullboard view', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',roadmap: 'pullboard roadmap', milestone: 'pullboard milestone add "0.7.0" --items 12,13',edit: 'pullboard edit 12 --brief "Add the upload page"', release: 'pullboard release 12',escalate: 'pullboard escalate 12 --note "needs a manual step"', next: 'pullboard next',@@@ -236,7 -301,7 +303,8 @@@ const HELP_FLAG_EXPLANATIONS ='--brief': 'what a cold agent needs','--check': 'the command that proves it','--family': 'records the family name',+ '--model': 'required model label, or set PULLBOARD_MODEL',+ '--landing': 'prioritizes a trunk landing in the machine gate queue','--json': 'prints one versioned document','--note': 'what was checked stays with the receipt','--note-file': 'keeps quotes, $ and backticks intact',@@@ -639,20 -729,63 +733,72 @@@ function withBoard(ctx, work)/** Dispatch a board mutation locally, or seal it before any linked replica applies it. */async function ordered(ctx, board, operation, args) {- return relayLinked(ctx.info.root)- ? relayOperation(ctx.info.root, operation, args, ctx.io)- : store[operation](board, ...args);+ const command = ['add', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;+ /** Dispatch while this session holds the checkout, including long-running next/run loops. */+ const execute = () => relayLinked(ctx.info.root)+ ? relayOperation(ctx.info.root, operation, args, ctx.io, command, () => store[operation](board, ...args)) : store[operation](board, ...args);+ const digest = agentSessionDigest();+ if (CHECKOUT_LEASES.has(ctx.io) || !digest || ctx.io.personChannel === 'view' || ctx.io.personRequest) return execute();+ const agent = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id ?? 'unjoined agent';+ const lease = await bindLocalSession(ctx.info, { agent, digest, keepLease: true });+ try { return await execute(); }+ finally { lease.release(); }+ }++ /** Check ownership before sync or command side effects; reads and authenticated person channels keep their identity. */+ async function bindCheckoutSession(io, positionals, values) {+ if (values.help || values.version || io.personChannel === 'view' || io.personRequest) return;+ const [command, first] = positionals;+ if (command === 'takeover' && (positionals.length !== 1 || Object.keys(values).some((key) => key !== 'json'))) {+ throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');+ }+ const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',+ 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'merged', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];+ if (!writes.includes(command) && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;+ if (command === 'answer' && values.as === 'person') return;+ const digest = agentSessionDigest();+ if (!digest) {+ if (command === 'takeover') throw new Refused('AGENT_SESSION', 'takeover belongs to an agent session; run pullboard takeover from the agent’s shell');+ return;+ }+ const info = repoInfo(io.cwd);+ let agent = info.isMain ? COORDINATOR : null;+ if (!info.isMain) {+ const ctx = context(io);+ agent = withBoard(ctx, (board) => store.agentAt(board, info.root)?.agent_id);+ if (!agent && command !== 'join') throw new Refused('NOT_JOINED', 'this worktree has not joined a lane; run pullboard join <lane>');+ }+ const lease = await bindLocalSession(info, { agent: agent ?? 'unjoined agent', digest, takeover: command === 'takeover', keepLease: !['run', 'next'].includes(command),+ /** Use an existing ordered shout so takeover has a receipt without changing the board format. */+ recordTakeover: async () => {+ const ctx = context(io);+ await withBoard(ctx, async (board) => {+ const me = whoAmI(ctx, board);+ const message = { from: me.id, to: info.isMain ? 'person' : COORDINATOR,- text: `${me.id} took over this checkout in a new agent session.`, lanes: laneNames(ctx.config) };++ text: `${me.displayName} took over this checkout in a new agent session.`, lanes: laneNames(ctx.config) };+ if (relayLinked(info.root)) await relayOperation(info.root, 'shout', [message], io, undefined, () => store.shout(board, message));+ else store.shout(board, message);+ });+ },+ });+ if (agent) return { lease };+ /** Replace the temporary identity after a successful first join, retaining the winning session. */+ return { lease, finish: async () => {+ const ctx = context(io);+ const me = withBoard(ctx, (board) => whoAmI(ctx, board));+ lease.updateAgent(me.id);+ } };}+/** Choose an explicitly supplied model or the standard environment fallback, refusing an unknown identity. */+function requiredModel(value, env = process.env) {+ const model = (value ?? env.PULLBOARD_MODEL ?? '').trim();+ if (!model || /[\u0000-\u001f\u007f-\u009f]/u.test(model)) {+ throw new Refused('MODEL_REQUIRED', 'give --model "<model name>" or set PULLBOARD_MODEL in this shell before joining');+ }+ return model;+}+/*** Who is asking: the coordinator in the main checkout, or the agent this worktree joined as.*@@@ -662,7 -795,7 +808,7 @@@*/function whoAmI(ctx, board) {if (ctx.info.isMain) {-- const registered = board.db.prepare('SELECT * FROM agent WHERE agent_id=?').get(COORDINATOR);++ const registered = store.listAgents(board).find((agent) => agent.agent_id === COORDINATOR);const linked = relayLinked(ctx.info.root);if (linked && !registered) throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before acting');const id = linked ? COORDINATOR : store.ensureCoordinator(board, ctx.info.root);@@@ -747,50 -894,10 +907,62 @@@ function itemLine(item, name = (id) =>const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : '';const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;- return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}`;- const hold = item.item_hold_reason ? ` held by ${item.item_hold_by}: ${item.item_hold_reason}` : '';++ const hold = item.item_hold_reason ? ` held by ${name(item.item_hold_by)}: ${item.item_hold_reason}` : '';+ return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}`;}+/** Format a stable agent id for human-facing CLI output. */+function agentDisplayName(agents, config, id) {+ if (!id) return '';+ const agent = agents.find((entry) => entry.agent_id === id);+ if (agent) return displayAgentName(agent, config.agents.names);+ if (id === 'person' || id === 'all' || Object.hasOwn(config.lanes, id)) return id;+ return displayAgentName({ agent_id: id }, config.agents.names);+}++/** Render only declared actor positions in a refusal, preserving user text and stable JSON ids. */+function agentRefusalText(message, code, name) {+ const patterns = {+ ALREADY_JOINED: /^(\[ALREADY_JOINED\] this worktree is )(\S+)( in )/,+ HELD: /^(\[HELD\] item #\d+ is held by )(\S+)( until )/,++ ITEM_HELD: /^(\[ITEM_HELD\] item #\d+ is held by )(\S+)(: )/,+ LANE_HELD: /^(\[LANE_HELD\] )(\S+)( holds the )/,+ REVIEW_HELD: /^(\[REVIEW_HELD\] )(\S+)( holds the )/,+ NOT_YOURS: /^(\[NOT_YOURS\] only the coordinator or )(\S+)(, who )/,- NO_AGENT: /^(\[NO_AGENT\] no agent )(\S+)()$/,++ NO_AGENT: /^(\[NO_AGENT\] no (?:registered )?agent )(\S+)(;|$)/,++ NOT_YOUR_CHECKOUT: /^(\[NOT_YOUR_CHECKOUT\] this checkout belongs to )(\S+)( in )/,++ FACT_JUDGEMENT: /^(\[FACT_JUDGEMENT\] only the item's live holder \()(\S+)(\))/,++ RELAY_PERSON_ONLY: /^(\[RELAY_PERSON_ONLY\] agent )(\S+)( cannot )/,++ SELF_SHOUT: /^(\[SELF_SHOUT\] a shout cannot be addressed to its sender )(\S+)(;)/,++ NO_READER: /^(\[NO_READER\] nobody reads ")(.*?)(":)/,+ };++ if (code === 'RELAY_SENDER_MISMATCH') {++ return message.replace(/^(\[RELAY_SENDER_MISMATCH\] agent )(\S+)( cannot act as )(.*?)(; send this operation)/,++ (_, before, sender, middle, actor, after) => `${before}${name(sender)}${middle}${actor === '(no declared agent)' ? actor : name(actor)}${after}`);++ }+ if (code === 'NOT_YOUR_DECISION') {+ return message.replace(/^(\[NOT_YOUR_DECISION\] shout #\d+ is addressed to )(\S+)(, not your \S+ lane \(agent )(\S+)(\))$/,+ (_, before, to, middle, caller, after) => `${before}${name(to)}${middle}${name(caller)}${after}`);+ }+ return patterns[code] ? message.replace(patterns[code], (_, before, id, after) => `${before}${name(id)}${after}`) : message;+}++/** Read current display settings for text refusals; the structured error retains its stable identifiers. */+function displayedRefusal(io, error) {- if (!['ALREADY_JOINED', 'HELD', 'LANE_HELD', 'REVIEW_HELD', 'NOT_YOURS', 'NOT_YOUR_DECISION', 'NO_AGENT'].includes(error.code)) return error.message;++ if (!['ALREADY_JOINED', 'HELD', 'ITEM_HELD', 'LANE_HELD', 'REVIEW_HELD', 'NOT_YOURS', 'NOT_YOUR_DECISION', 'NO_AGENT', 'NOT_YOUR_CHECKOUT', 'FACT_JUDGEMENT', 'RELAY_PERSON_ONLY', 'RELAY_SENDER_MISMATCH', 'SELF_SHOUT', 'NO_READER'].includes(error.code)) return error.message;+ try {+ const ctx = context(io);+ const agents = withBoard(ctx, (board) => store.listAgents(board));+ return agentRefusalText(error.message, error.code, (id) => agentDisplayName(agents, ctx.config, id));+ } catch { return error.message; }+}++/** Label the holder at the start of a generated wait reason without rewriting its quoted reason. */+function displayedWait(reason, agents, config) {- return reason.replace(/^(\S+)( holds the )/, (_, id, rest) => `${agentDisplayName(agents, config, id)}${rest}`);++ return reason.replace(/^(\S+)( holds the )/, (_, id, rest) => `${agentDisplayName(agents, config, id)}${rest}`)++ .replace(/^(#\d+ is held by )(\S+)(: )/, (_, before, id, after) => `${before}${agentDisplayName(agents, config, id)}${after}`);+}+/*** The files an agent has been working in (N20): what its latest three items touched, and what is* uncommitted in its worktree now.@@@ -932,15 -1144,21 +1209,23 @@@ function resumeHere(io)holds: store.laneHolds(board),unread: store.unreadCount(board, me.id),newest: store.peekShouts(board, me.id, 1),+ agents: store.listAgents(board),};});+ card.relayProblems = unlinkedRelayProjects();const { me } = card;+ const name = (id) => agentDisplayName(card.agents, ctx.config, id);- card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows).map((item) => ({ ...item, ...staleItemFinding(item) }));+ card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows, ctx.doctrine.rows).map((item) => ({ ...item, ...staleItemFinding(item) }));+ if (isMain) {+ card.staleFollowUps = { count: card.stale.length + card.staleIntegrations.length,+ list: 'pullboard resume --json', items: card.stale, integrations: card.staleIntegrations };+ delete card.staleIntegrations;+ card.reviewQueue = { items: card.toVerify, awaiting: card.awaiting };+ }const say = (line) => io.say(line);+ for (const problem of card.relayProblems) say(problem.message);const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;- say(`resume: ${me.id}${me.family ? ` (${me.family})` : ''}, ${me.lane} lane${isMain ? ', the main checkout' : ''}, at ${root}`);+ say(`resume: ${me.displayName}${me.family ? ` [family ${me.family}]` : ''}, ${me.lane} lane${isMain ? ', the main checkout' : ''}, at ${root}`);const dirty = dirtyFiles(root).length;if (!isMain) {const branch = tryGit(root, ['rev-parse', '--abbrev-ref', 'HEAD']).stdout || 'HEAD';@@@ -959,13 -1177,32 +1244,32 @@@if (files.length) say(` files: ${files.join(', ')}`);}for (const { item, verdict } of card.sentBack) {- say(`sent back: #${item.item_id} ${verdict ? `${verdict.verdict_reason} by ${verdict.verdict_by}: ${firstLine(verdict.verdict_note)}` : 'rejected'}`);+ say(`sent back: #${item.item_id} ${verdict ? `${verdict.verdict_reason} by ${name(verdict.verdict_by)}: ${firstLine(verdict.verdict_note)}` : 'rejected'}`);}- for (const item of card.stale) say(`stale: ${item.message}; next: ${item.next}`);+ if (isMain && card.staleFollowUps.count) say(`${plural(card.staleFollowUps.count, 'stale follow-up')}; list them with ${card.staleFollowUps.list}`);+ else if (!isMain) for (const item of card.stale) say(`stale: ${item.message}; next: ${item.next}`);if (card.awaiting.length) say(`awaiting a verdict: ${card.awaiting.map((item) => `#${item.item_id} (${span(ctx, item.item_updated_at)})`).join(', ')}`);if (isMain) {- if (card.toVerify.length) say(`to verify: ${card.toVerify.map((item) => `#${item.item_id} ${item.item_lane} (${span(ctx, item.item_updated_at)})`).join(', ')}`);- if (card.toMerge.length) say(`verified, not merged: ${card.toMerge.map((item) => `#${item.item_id} at ${item.item_commit.slice(0, 12)}`).join(', ')}; pullboard merged <id> <commit> records each`);+ /** Limit each text section; JSON keeps every record for a complete handoff. */+ const section = (entries, line) => {+ for (const entry of entries.slice(0, 3)) say(line(entry));+ if (entries.length > 3) say(` ${entries.length - 3} more; list them with pullboard resume --json`);+ };- section(card.openDecisions, (ask) => `open decision #${ask.id} from ${ask.asker} (${ask.age}): ${firstLine(ask.question)}`);- section(card.recentAnswers, (answer) => `recent decision #${answer.id}: ${answer.answeredBy} answered ${answer.asker} (${answer.age} ago): ${firstLine(answer.answer)}`);++ section(card.openDecisions, (ask) => `open decision #${ask.id} from ${name(ask.asker)} (${ask.age}): ${firstLine(ask.question)}`);++ section(card.recentAnswers, (answer) => `recent decision #${answer.id}: ${name(answer.answeredBy)} answered ${name(answer.asker)} (${answer.age} ago): ${firstLine(answer.answer)}`);+ if (card.toMerge.length) {+ const groups = card.verifiedNotMerged;+ /** Keep merge groups on one line while retaining all entries in JSON. */+ const listed = (entries, line) => entries.slice(0, 3).map(line).join(', ')+ + (entries.length > 3 ? `, +${entries.length - 3} more (pullboard resume --json)` : '') || 'none';+ say(`verified, not merged — merges cleanly: ${listed(groups.clean, (item) => `#${item.item_id} ${firstLine(item.item_title)}`)}`);+ say(`verified, not merged — conflicts: ${listed(groups.conflicts, ({ item, files }) => `#${item.item_id} ${firstLine(item.item_title)} (${files.join(', ') || 'files unavailable'})`)}`);- say(`verified, not merged — claimed for integration: ${listed(groups.integrating, ({ item, by, at, commit }) => `#${item.item_id} by ${by} at ${at} (${commit.slice(0, 12)})`)}`);++ say(`verified, not merged — claimed for integration: ${listed(groups.integrating, ({ item, by, at, commit }) => `#${item.item_id} by ${name(by)} at ${at} (${commit.slice(0, 12)})`)}`);+ }- section(card.personQuestions, (ask) => `waiting on the person: #${ask.id} from ${ask.asker} (${ask.age}): ${firstLine(ask.question)}`);++ section(card.personQuestions, (ask) => `waiting on the person: #${ask.id} from ${name(ask.asker)} (${ask.age}): ${firstLine(ask.question)}`);+ if (card.toVerify.length) say('review queue:');+ section(card.toVerify, (item) => ` to verify: #${item.item_id} ${item.item_lane} (${span(ctx, item.item_updated_at)})`);+ if (card.toMerge.length) say('merge verified work, run the gate, then record each with pullboard merged <id> <commit>');for (const hold of card.holds) say(`held: the ${hold.hold_lane} lane, ${hold.hold_reason}`);const byLane = Object.entries(Map.groupBy(card.open, (item) => item.item_lane)).map(([lane, items]) => `${lane} ${items.length}`);say(`open: ${card.open.length}${byLane.length ? ` (${byLane.join(', ')})` : ''}`);@@@ -1098,14 -1335,19 +1402,21 @@@ function setupCommands(io, { first, valthrow new Refused('NO_LANE', `no lane "${first ?? ''}"; lanes: ${laneNames(ctx.config).slice(1).join(', ') || 'none yet, declare them in pullboard.json'}`);}const route = values.route ?? 'strong';- const id = await withBoard(ctx, async (board) => await ordered(ctx, board, 'register', [{ lane: first, path: ctx.info.root, route, family: values.family }]));- io.result?.({ agent: id, lane: first, route, path: ctx.info.root });- io.say(`joined as ${id} in the ${first} lane${route === 'light' ? ', on the light route' : ''}`);+ const model = requiredModel(values.model);+ const id = await withBoard(ctx, async (board) => await ordered(ctx, board, 'register', [{ lane: first, path: ctx.info.root, route, family: values.family, model }]));+ const displayName = displayAgentName({ agent_id: id, agent_model: model }, ctx.config.agents.names);+ io.result?.({ agent: id, lane: first, route, path: ctx.info.root, model, displayName });+ io.say(`joined as ${displayName} in the ${first} lane${route === 'light' ? ', on the light route' : ''}`);return 0;},- worktree: () => worktreeFor(io, first, values.route ?? 'strong', values.family ?? null),+ worktree: () => worktreeFor(io, first, values.route ?? 'strong', values.family ?? null, values.model),+ takeover: () => {+ const ctx = context(io);+ const me = withBoard(ctx, (board) => whoAmI(ctx, board));+ io.result?.({ agent: me.id, path: ctx.info.root });- io.say(`${me.id} took over this checkout for the current agent session`);++ io.say(`${me.displayName} took over this checkout for the current agent session`);+ return 0;+ },};}@@@ -1138,8 -1378,13 +1449,13 @@@ async function worktreeFor(io, lane, rogit(mainRoot, ['worktree', 'add', '-q', '-b', `${lane}/${n}`, pathFor(n), git(mainRoot, ['rev-parse', 'HEAD'])]);const root = git(pathFor(n), ['rev-parse', '--show-toplevel']);let id;- try { id = await withBoard(ctx, async (board) => await ordered(ctx, board, 'register', [{ lane, path: root, route, family }])); }+ try { id = await withBoard(ctx, async (board) => await ordered(ctx, board, 'register', [{ lane, path: root, route, family, model }])); }catch (error) {+ const registered = withBoard(ctx, (board) => store.agentAt(board, root));+ if (registered) {+ io.err('pullboard: registration is already ordered; the worktree is preserved. Retry enrollment to obtain its credential: ' + cdTo(root) + ' pullboard join ' + lane + (route === 'strong' ? '' : ' --route ' + route) + (family ? ' --family ' + shellWord(family) : ''));+ throw error;+ }// Only remove the clean worktree just created here; preserve it if another process changed it.const removed = tryGit(mainRoot, ['worktree', 'remove', root]);if (removed.status === 0) tryGit(mainRoot, ['branch', '-d', `${lane}/${n}`]);@@@ -1242,8 -1482,8 +1558,8 @@@ function readCommands(io, { first, secoif (!resources.length) io.say('no resources have been used');for (const resource of resources) {io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);- for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''} since ${holder.since}`);- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}`));- for (const holder of resource.holders) io.say(` held by ${holder.agent}${holder.repo ? ` in ${holder.repo}` : ''}${holder.landing ? ' (landing)' : holder.itemCheck ? ' (item check)' : ''} since ${holder.since}`);- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${waiter.agent}${waiter.repo ? ` in ${waiter.repo}` : ''}${waiter.landing ? ' (landing)' : waiter.itemCheck ? ' (item check)' : ''}`));++ for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''}${holder.landing ? ' (landing)' : holder.itemCheck ? ' (item check)' : ''} since ${holder.since}`);++ resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${waiter.landing ? ' (landing)' : waiter.itemCheck ? ' (item check)' : ''}`));}return 0;},@@@ -1298,20 -1535,19 +1614,21 @@@show: () => {const ctx = context(io);const id = idArg(first);- const { item, verdicts, moves, related, reviewer, agents } = withBoard(ctx, (board) => ({- const { item, verdicts, moves, thread, related, reviewer } = withBoard(ctx, (board) => ({++ const { item, verdicts, moves, thread, related, reviewer, agents } = withBoard(ctx, (board) => ({item: store.getItem(board, id),verdicts: store.verdictsFor(board, id),moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),+ thread: store.itemThread(board, id),related: store.relatedItems(board, store.getItem(board, id)),reviewer: store.reviewHolder(board, store.getItem(board, id)),+ agents: store.listAgents(board),}));+ const agentName = (id) => displayAgentName(agents.find((agent) => agent.agent_id === id) ?? { agent_id: id }, ctx.config.agents.names);if (values.json) {- io.result({ ...item, verdicts });+ io.result({ ...item, verdicts, thread });return 0;}- io.say(itemLine(item));+ io.say(itemLine(item, agentName));if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);if (item.item_check) io.say(`check: ${item.item_check}`);sayCheckBaseline(io, item);@@@ -1330,16 -1566,30 +1647,30 @@@io.say(`frozen at claim (${item.item_frozen_digest.slice(0, 12)}):`);frozen.rows.forEach((row) => io.say(` ${row.id}: ${row.text}${row.gate ? ` | gate: ${row.gate}` : ''}`));}- if (item.item_commit) io.say(`submitted by ${item.item_built_by}${item.item_builder_family ? ` (${item.item_builder_family})` : ''} at ${item.item_commit}`);- if (reviewer) io.say(`under review by ${reviewer} until ${item.item_review_until}`);+ if (item.item_commit) io.say(`submitted by ${agentName(item.item_built_by)}${item.item_builder_family ? ` [family ${item.item_builder_family}]` : ''} at ${item.item_commit}`);+ if (reviewer) io.say(`under review by ${agentName(reviewer)} until ${item.item_review_until}`);// Earlier verdicts as one line each, so an item sent back several times stays short to read// (N30); --history prints every note in full.- const verdictLine = (verdict) => `${verdict.verdict_decision} ${verdict.verdict_reason} by ${verdict.verdict_by}${verdict.verdict_verifier_family ? ` (${verdict.verdict_verifier_family})` : ''} at ${verdict.verdict_commit.slice(0, 12)}`;+ const verdictLine = (verdict) => `${verdict.verdict_decision} ${verdict.verdict_reason} by ${agentName(verdict.verdict_by)}${verdict.verdict_verifier_family ? ` [family ${verdict.verdict_verifier_family}]` : ''} at ${verdict.verdict_commit.slice(0, 12)}`;const notes = verdicts.map((verdict, index) => (values.history || index === verdicts.length - 1 ? verdict.verdict_note : firstLineOf(verdict.verdict_note)));- verdicts.forEach((verdict, index) => io.say(`${verdictLine(verdict)}${notes[index] ? `: ${notes[index]}` : ''}`));+ verdicts.forEach((verdict, index) => {+ io.say(`${verdictLine(verdict)}${notes[index] ? `: ${notes[index]}` : ''}`);+ io.say(` check: ${verdict.check ?? 'unknown'}`);+ });if (notes.some((note, index) => note !== verdicts[index].verdict_note)) io.say(`(earlier verdicts shortened; every note in full: pullboard show ${id} --history)`);if (item.item_merged_commit) io.say(`merged as ${item.item_merged_commit}`);if (item.item_withdrawn_reason) io.say(`withdrawn: ${item.item_withdrawn_reason}`);+ io.say('thread:');+ for (const entry of thread) {- const stamp = ` ${entry.at} ${entry.by} `;++ const stamp = ` ${entry.at} ${agentDisplayName(agents, ctx.config, entry.by)} `;+ if (entry.type === 'fact') {+ io.say(`${stamp}fact ${entry.kind} ${entry.id}${entry.supersedes ? ' (supersedes ' + entry.supersedes + ')' : ''}: ${entry.text}`);+ if (entry.ref) io.say(` ref: ${entry.ref.path}:${entry.ref.start}${entry.ref.end === entry.ref.start ? '' : '-' + entry.ref.end}@${entry.ref.commit}`);+ } else {+ const detail = entry.detail;+ io.say(`${stamp}${entry.kind}${detail.commit ? ' at ' + detail.commit : ''}${detail.reason ? ': ' + detail.reason : ''}`);+ }+ }return 0;},status: () => {@@@ -1354,8 -1604,9 +1685,9 @@@return 0;}if (summary.relay.linked) io.say(`relay: sequence ${summary.relay.sequence}; ${summary.relay.behind} pending uploads`);+ if (summary.relay.oversizedSnapshot && !summary.relay.refusedCheckpoint) io.say(formatSnapshotLimit(summary.relay.oversizedSnapshot));const { items, accepted, rejected } = summary.stats;- io.say(`${summary.me.id}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);+ io.say(`${summary.me.displayName}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);io.say(`verdicts: ${accepted} accepted, ${rejected} rejected`);io.say(reviewQueueLine(ctx, summary.reviewQueue));@@@ -1410,25 -1662,38 +1748,39 @@@});io.result?.({ decisions: asks });if (!asks.length) io.say('no open decisions');- for (const ask of asks) io.say(`#${ask.shout_id} ${ask.shout_from} -> ${ask.shout_to}, ${span(ctx, ask.shout_at)} ago: ${firstLine(ask.shout_text)}`);+ for (const ask of asks) io.say(`#${ask.shout_id} ${agentDisplayName(agents, ctx.config, ask.shout_from)} -> ${agentDisplayName(agents, ctx.config, ask.shout_to)}, ${span(ctx, ask.shout_at)} ago: ${firstLine(ask.shout_text)}`);return 0;},+ stats: () => {+ const ctx = context(io);- const stats = withBoard(ctx, (board) => proofStats(board, { since: values.since }));++ const { stats, agents } = withBoard(ctx, (board) => ({ stats: proofStats(board, { since: values.since }), agents: store.listAgents(board) }));+ io.result?.({ stats });+ io.say(`${stats.submissions} submissions · ${stats.rejections} rejections · ${(stats.rejectionShare * 100).toFixed(1)}% sent back`);+ io.say(`${stats.merged} items merged · ${stats.mergedWithoutAccept} merged without an accept`);+ io.say(`${stats.agentCount} agents · ${stats.familyCount} family buckets: ${stats.families.map((family) => `${family.name} (${family.agents} agents, ${family.moves} moves)`).join('; ') || 'none'}`);- io.say(`agents: ${stats.agents.map((agent) => `${agent.id} (${agent.families.join('/')}; ${agent.moves} moves)`).join(', ') || 'none'}`);++ io.say(`agents: ${stats.agents.map((agent) => `${agentDisplayName(agents, ctx.config, agent.id)} (${agent.families.join('/')}; ${agent.moves} moves)`).join(', ') || 'none'}`);+ io.say(`events: ${stats.firstEventAt ?? 'none'} to ${stats.lastEventAt ?? 'none'}${stats.since ? ` (since ${stats.since})` : ''}`);+ return 0;+ },ledger: () => {const ctx = context(io);- const { items, stats } = withBoard(ctx, (board) => ({+ const { items, stats, agents } = withBoard(ctx, (board) => ({- items: store.listItems(board, { all: true }),+ items: store.listItems(board, { all: true }).map((item) => ({+ ...item,+ check: store.verdictsFor(board, item.item_id).at(-1)?.check ?? 'unknown',+ })),stats: store.stats(board),+ agents: store.listAgents(board),}));const built = items.filter((item) => item.item_built_by && item.item_status !== 'withdrawn').reverse();io.result?.({ items: built, stats });const cell = (text) => String(text ?? '').replace(/\|/g, '/').replace(/\s+/g, ' ');io.say(`${stats.items.verified} verified by a second agent · ${stats.items.submitted} awaiting verification · ${stats.rejected} rejection${stats.rejected === 1 ? '' : 's'} along the way`);io.say('');- io.say('| # | Lane | Item | Spec | Built by | Verified by | Commit | Merged |');- io.say('| --- | --- | --- | --- | --- | --- | --- | --- |');+ io.say('| # | Lane | Item | Spec | Built by | Verified by | Check | Commit | Merged |');+ io.say('| --- | --- | --- | --- | --- | --- | --- | --- | --- |');for (const item of built) {- io.say(`| ${item.item_id} | ${item.item_lane} | ${cell(item.item_title)} | ${cell(item.item_spec_ids)} | ${agentDisplayName(agents, ctx.config, item.item_built_by)} | ${agentDisplayName(agents, ctx.config, item.item_verified_by)} | ${(item.item_commit ?? '').slice(0, 12)} | ${(item.item_merged_commit ?? '').slice(0, 12)} |`);- io.say(`| ${item.item_id} | ${item.item_lane} | ${cell(item.item_title)} | ${cell(item.item_spec_ids)} | ${item.item_built_by} | ${item.item_verified_by ?? ''} | ${item.check === 'none' ? 'unchecked' : item.check} | ${(item.item_commit ?? '').slice(0, 12)} | ${(item.item_merged_commit ?? '').slice(0, 12)} |`);++ io.say(`| ${item.item_id} | ${item.item_lane} | ${cell(item.item_title)} | ${cell(item.item_spec_ids)} | ${agentDisplayName(agents, ctx.config, item.item_built_by)} | ${agentDisplayName(agents, ctx.config, item.item_verified_by)} | ${item.check === 'none' ? 'unchecked' : item.check} | ${(item.item_commit ?? '').slice(0, 12)} | ${(item.item_merged_commit ?? '').slice(0, 12)} |`);}return 0;},@@@ -1654,8 -1977,8 +2065,9 @@@ async function nextHere(io, values)if (found.item) {if (found.offer) { sayReviewOffer(ctx, found); return 0; }const item = found.item;+ const agents = withBoard(ctx, (board) => store.listAgents(board));- io.result?.({ item, review: Boolean(values.verify), held: Boolean(found.held), shared: found.shared ?? [] });+ io.result?.({ item, review: Boolean(values.verify), held: Boolean(found.held), shared: found.shared ?? [], reasons: found.reasons ?? [] });- for (const reason of found.reasons ?? []) io.say(reason);++ for (const reason of found.reasons ?? []) io.say(displayedWait(reason, agents, ctx.config));const here = cdTo(ctx.info.root);const as = ctx.info.isMain ? ' --as coordinator' : '';if (values.verify) {@@@ -1678,8 -2001,7 +2090,10 @@@}if (!found.retry && Date.now() >= deadline) {const waited = minutes ? ` after ${minutes} minutes` : '';- io.err(`pullboard: [NOTHING_FREE] ${found.reasons.join('; ')}${waited}. To keep looking: pullboard next --wait 9${values.verify ? ' --verify' : ''} (minutes; give the command a ten-minute timeout)`);+ const agents = withBoard(ctx, (board) => store.listAgents(board));- io.err(`pullboard: [NOTHING_FREE] ${found.reasons.map((reason) => displayedWait(reason, agents, ctx.config)).join('; ')}${waited}. To keep looking: pullboard next --wait 9${values.verify ? ' --verify' : ''} (minutes; give the command a ten-minute timeout)`);++ const repair = `${waited}. To keep looking: pullboard next --wait 9${values.verify ? ' --verify' : ''} (minutes; give the command a ten-minute timeout)`;++ io.refusal?.(new Refused('NOTHING_FREE', found.reasons.join('; ') + repair));++ io.err(`pullboard: [NOTHING_FREE] ${found.reasons.map((reason) => displayedWait(reason, agents, ctx.config)).join('; ')}${repair}`);return 1;}if (!found.retry) await new Promise((done) => setTimeout(done, 5000));@@@ -1888,10 -2241,10 +2334,10 @@@ function workCommands(io, args)else io.err('Run this check? [y/N]');const answer = await firstInputLine(io.stdin);if (!/^y(?:es)?$/iu.test(answer.trim())) {- throw new Refused('CHECK_CONFIRM', `the check set by ${by} was not run: ${check}; run pullboard check ${item.item_id} --yes after reading the command, or answer yes at the prompt`);+ throw new Refused('CHECK_CONFIRM', `the check set by ${authorName} was not run: ${check}; run pullboard check ${item.item_id} --yes after reading the command, or answer yes at the prompt`);}}- const run = runShell(ctx.info.root, check);+ const run = await withGateSlot(ctx.info.root, () => runShell(ctx.info.root, check), { itemCheck: true, onWait: gateWaitReporter(io) });io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, by, report: run.isGreen ? '' : digestOf(run.output) });io.say(`check ${run.isGreen ? 'green' : 'red'} in ${run.seconds}s: ${check}`);if (!run.isGreen) io.say(digestOf(run.output).replace(/^/gm, ' '));@@@ -1950,11 -2329,9 +2422,11 @@@const hasRecipient = first && recipients.includes(first);const to = hasRecipient ? first : values.decision ? (me.id === COORDINATOR ? 'person' : COORDINATOR) : first ?? '';const text = [hasRecipient ? second : first, ...(hasRecipient ? rest : [second, ...rest])].filter(Boolean).join(' ');- const id = await ordered(ctx, board, 'shout', [{ from: me.id, to, text, lanes: laneNames(ctx.config), decision: Boolean(values.decision), evidence }]);+ const id = await ordered(ctx, board, 'shout', [{ from: io.personRequest?.phase === 'execute' ? store.PERSON : me.id, to, text, lanes: laneNames(ctx.config), decision: Boolean(values.decision), evidence }]);io.result?.({ id, decision: Boolean(values.decision) });- io.say(values.decision ? `asked ${to} for a decision as #${id}; it stays open until someone runs: pullboard answer ${id} "<the decision>"` : `shouted to ${to}`);+ const agents = store.listAgents(board);+ const recipient = agents.some((agent) => agent.agent_id === to) ? agentDisplayName(agents, ctx.config, to) : to;+ io.say(values.decision ? `asked ${recipient} for a decision as #${id}; it stays open until someone runs: pullboard answer ${id} "<the decision>"` : `shouted to ${recipient}`);return 0;}),answer: () => act(async (ctx, board, me) => {@@@ -2347,9 -2772,50 +2867,52 @@@ async function runCommand(argv, io)if (command === 'hook') return await hookCommand(io, args);if (command === 'settings') return settingsCommand(io, args);if (command === 'relay') {+ if (first === 'devices') {+ if (second || rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay devices');+ const devices = readRelayMachine().devices.map(({ deviceId, label, fingerprint, createdAt }) => ({ deviceId, label, fingerprint, createdAt }));+ io.result?.({ devices });+ for (const device of devices) io.say(`${device.deviceId} ${device.label} ${device.fingerprint}`);+ if (!devices.length) io.say('no paired devices; run pullboard relay on --all');+ return 0;+ }+ if (first === 'revoke' && /^device-[0-9a-f]{32}$/u.test(second ?? '')) {+ if (rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay revoke <device>');+ const result = await revokeRelayDevice(second, io);+ io.result?.(result); io.say(result.notice); return 0;+ }+ if (values.all) {+ if (first !== 'on' || second || rest.length) throw new Refused('USAGE', 'pullboard relay on --all [--url <address>]');+ const result = await relayOnAll(values.url, io);+ io.result?.(result); return result.failed.length ? 1 : 0;+ }+ if (['tokens', 'revoke'].includes(first)) {+ if (rest.length || values.url || (first === 'tokens' && second) || (first === 'revoke' && !second)) {+ throw new Refused('USAGE', 'pullboard relay tokens, or pullboard relay revoke <token-id>');+ }+ const ctx = context(io);+ const result = first === 'tokens' ? await relayTokens(ctx.info.root, io) : await relayRevoke(ctx.info.root, second, io);+ io.result?.(result);+ if (first === 'tokens') {+ if (!result.tokens.length) io.say('no agent tokens on this board');- for (const row of result.tokens) io.say(row.id + ' ' + row.agent + ' ' + (row.revoked ? 'revoked' : 'expires ' + new Date(row.expires).toISOString()));++ const ctx = context(io);++ const agents = withBoard(ctx, (board) => store.listAgents(board));++ for (const row of result.tokens) io.say(row.id + ' ' + agentDisplayName(agents, ctx.config, row.agent) + ' ' + (row.revoked ? 'revoked' : 'expires ' + new Date(row.expires).toISOString()));+ } else io.say('revoked token ' + result.id + '; other agent tokens are unchanged');+ return 0;+ }+ if (first === 'pair') {+ if (second || rest.length || values.url) throw new Refused('USAGE', 'pullboard relay pair');+ const ctx = context(io);+ return await relayPair(ctx.info.root, io);+ }+ if (first === 'join') {+ if (!second || rest.length) throw new Refused('USAGE', 'pullboard relay join <code> [--url <address>]');+ const ctx = context(io);+ return await relayJoin(ctx.info.root, second, values.url, io);+ }if (second || rest.length || (first && !['on', 'off'].includes(first)) || (values.url && first !== 'on')) throw new Refused('USAGE', 'pullboard relay [on|off] [--url <address>]');const ctx = context(io);- if (!first) await syncRelay(ctx.info.root, io);+ if (!first) { await syncRelay(ctx.info.root, io); await executePersonRequests(ctx.info.root, io, main); }const result = first === 'on' ? await relayOn(ctx.info.root, values.url, io): first === 'off' ? await relayOff(ctx.info.root, io) : relayStatus(ctx.info.root);io.result?.(result);@@@ -2377,28 -2843,88 +2940,88 @@@}}+ /** Retain the primary branch on every command without creating a board for global help. */+ function rememberTrunk(io) {+ let info;+ try { info = repoInfo(io.cwd); }+ catch (error) {+ if (error instanceof Refused && ['NOT_A_REPO', 'NO_REPO', 'CORE_BARE'].includes(error.code)) return;+ throw error;+ }+ if (!info.isMain) return;+ const primary = mainCheckout(info.root);+ if (primary?.branch) trunkRef(info.root, primary.branch);+ }+/** Run one command and emit its single versioned JSON result when requested (A1). */export async function main(argv, streams) {+ return withGitFacts(() => runMain(argv, streams));+ }++ /** Parse and execute one CLI command, binding its checkout session and Git-fact scope. */+ async function runMain(argv, streams) {const io = commandOutput(argv, streams);let sync = true;+ let needsRepo = true;+ let parsed;+ let checkoutSession;try {- const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });+ parsed = parseCommandArgs(argv);const command = parsed.positionals[0];+ io.relayJson = Boolean(parsed.values.json);+ io.relayCommand = { cliOperation: command === 'done' ? 'submit' : command, cwd: resolve(io.cwd),+ positionals: parsed.positionals.slice(1),+ values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };sync = Boolean(command) && !parsed.values.help && !parsed.values.version && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command);- } catch { sync = false; }- /** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */- const retry = async () => {- try { await syncRelay(io.cwd, io); }- catch (error) {+ needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');+ } catch { sync = false; needsRepo = false; }+ if (parsed) {+ try {+ const [command, verb] = parsed.positionals;+ if (!parsed.values.help && !parsed.values.version &&+ (parsed.values.as === 'person' && command !== 'decisions' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb))) requirePersonChannel(io.personChannel);+ checkoutSession = await bindCheckoutSession(io, parsed.positionals, parsed.values);+ if (checkoutSession?.lease) CHECKOUT_LEASES.set(io, checkoutSession.lease);+ } catch (error) {if (!(error instanceof Refused)) throw error;- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);+ io.refusal(error);- io.err(`pullboard: ${error.message}`);++ io.err(`pullboard: ${displayedRefusal(io, error)}`);+ io.flush(1);+ return 1;}- };- if (sync) await retry();- const code = await runCommand(argv, io);- if (sync && code === 0) await retry();- io.flush(code);- return code;+ }+ try {+ /** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */+ const retry = async () => {+ try {+ await syncRelay(io.cwd, io);+ await retryCheckBaselines(io.cwd, io);+ }+ catch (error) {+ if (!(error instanceof Refused)) throw error;- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);++ if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}`);+ }+ };+ if (needsRepo) rememberTrunk(io);+ if (sync) {+ try { await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }+ await retry();+ try { await executePersonRequests(io.cwd, io, main); }+ catch (error) {+ if (!(error instanceof Refused)) throw error;- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);++ if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}`);+ }+ }+ const code = await runCommand(argv, io);+ if (code === 0) await checkoutSession?.finish?.();+ if (sync && code === 0) await retry();+ const status = io.exitCode(code);+ io.flush(status);+ return status;+ } finally {+ CHECKOUT_LEASES.delete(io);+ checkoutSession?.lease?.release();+ }}/** Result-producing command names, including aliases, for API contract coverage (A1). */diff --cc src/config.jsindex 14f81601,c74d7f02..8f1927b6--- a/src/config.js+++ b/src/config.js@@@ -39,7 -44,7 +44,8 @@@ export function defaults()lease: '2h',reviewLease: '30m',verify: { policy: 'any', family: 'off', reviewRatio: 3 },+ agents: { names: 'suffix' },+ check: { install: '', timeout: '5m' },lanes: {},products: {},shared: [],@@@ -90,7 -95,10 +96,14 @@@ function merge(base, raw)verify: typeof raw.verify === 'string'? { ...base.verify, policy: raw.verify }: { ...base.verify, ...(raw.verify ?? {}) },- agents: { ...base.agents, ...(raw.agents ?? {}) },++ agents: raw.agents === undefined ? base.agents++ : raw.agents && typeof raw.agents === 'object' && !Array.isArray(raw.agents)++ ? { ...base.agents, ...raw.agents }++ : raw.agents,+ check: raw.check === undefined ? base.check+ : raw.check && typeof raw.check === 'object' && !Array.isArray(raw.check)+ ? { ...base.check, ...raw.check }+ : raw.check,};}diff --cc src/json.jsindex 40a16736,3ded1a14..0f3f7c5c--- a/src/json.js+++ b/src/json.js@@@ -13,10 -13,11 +13,11 @@@ export const JSON_SHAPES =version: shape({ release: 'string' }),init: shape({ root: 'string', notes: 'array' }),hooks: shape({ notes: 'array' }),- join: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string' }),+ join: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', model: 'string', displayName: 'string' }),+ takeover: shape({ agent: 'string', path: 'string' }),- worktree: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', branch: 'string', prompt: 'string' }),+ worktree: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', branch: 'string', prompt: 'string', model: 'string', displayName: 'string' }),resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', stale: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: 'string' }),- whoami: shape({ id: 'string', lane: 'string', path: 'string' }),+ whoami: shape({ id: 'string', lane: 'string', path: 'string', model: 'string', displayName: 'string' }),lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),resources: shape({ resources: 'array' }),settings: shape({ settings: 'object' }),diff --cc src/machine.jsindex dabd921c,e770f89b..4b3490cc--- a/src/machine.js+++ b/src/machine.js@@@ -9,8 -9,8 +9,8 @@@* broken copy, and checks the declaration against the refusals board.js and cli.js raise today.*/- /** Executable move semantics; bump once per release after a released move's meaning changes [H16]. */- export const ENGINE_VERSION = 3;+ /** Executable move semantics, carried by every sealed move and retained during replay [H16]. */-export const ENGINE_VERSION = 7;++export const ENGINE_VERSION = 8;/** @typedef {'agent' | 'coordinator' | 'clock'} Role */diff --cc src/templates.jsindex 5ec2d5c7,19c8d1d7..e0d6f352--- a/src/templates.js+++ b/src/templates.js@@@ -19,9 -20,8 +20,9 @@@ export function configTemplate(gate, figate,...(fix.length ? { fix } : {}),spec: 'SPEC.md',- practice: 'PRACTICE.md',+ practice: DOCTRINE_FILE,verify: { policy: 'any', family: 'off' },+ agents: { names: 'suffix' },lease: '2h',lanes: { review: { owns: [], starts: 'any time: verifiers check submitted work and own no folders' } },shared: [],diff --cc src/tour.jsindex 42ec5c07,d2aecdda..61984255--- a/src/tour.js+++ b/src/tour.js@@@ -9,6 -9,8 +9,9 @@@ import { chmodSync, mkdirSync, mkdtempSimport { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';++import { displayAgentName } from './agent-names.js';+ import { loadConfig } from './config.js';+ import { registerProjectAndLink } from './projects.js';const BIN = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));@@@ -99,7 -103,7 +104,7 @@@ export async function tour(io)*/const run = (who, file, args, { label = `${file} ${typed(args)}`, show = /./, fails = false, tone } = {}) => {pause(400 * pace);-- if (label) io.say(` ${paint(who, PROMPT_COLOR[who], color)} $ ${label}`);++ if (label) io.say(` ${paint(displayAgentName({ agent_id: who, agent_model: who === 'coordinator' ? null : 'Scripted' }), PROMPT_COLOR[who], color)} $ ${label}`);const result = spawnSync(file, args, {cwd: where[who],encoding: 'utf8',diff --cc test/agent-model-engine.test.jsindex 00000000,00000000..f21a0fc3new file mode 100644--- /dev/null+++ b/test/agent-model-engine.test.js@@@ -1,0 -1,0 +1,68 @@@++/** Declared models replay with their recorded engine and survive board exchange [O8,O3,H16]. */++import assert from 'node:assert/strict';++import { test } from 'node:test';++import * as store from '../src/board.js';++import { applyEngineMove, prepareEngineMove } from '../src/engine.js';++import { exportBoard, importBoard } from '../src/exchange.js';++import { ENGINE_VERSION } from '../src/machine.js';++import { configProblems, defaults, loadConfig } from '../src/config.js';++import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';++import { tmpdir } from 'node:os';++import { join } from 'node:path';++++test('model declarations and event snapshots retain engines 1 through 7 semantics [O8,O3,H16]', (t) => {++ assert.equal(ENGINE_VERSION, 8, 'model moves share the approved 0.8.5 engine');++ for (const version of [1, 2, 3, 4, 5, 6, 7, 8]) {++ const board = store.openBoard(':memory:');++ t.after(() => store.closeBoard(board));++ const registration = prepareEngineMove(board, 'register', [{ lane: 'web', path: '/web', model: 'First Model' }]);++ const first = applyEngineMove(board, { ...registration, engine: version }, { sequence: 1, at: '2026-10-10T07:00:00Z' });++ assert.equal(first.error, undefined);++ assert.equal(first.result, 'web-1');++ assert.equal(store.agentAt(board, '/web').agent_model, version < 8 ? null : 'First Model');++ assert.deepEqual(JSON.parse(first.events[0].event_detail), version < 8++ ? { lane: 'web' } : { lane: 'web', model: 'First Model' });++++ const update = prepareEngineMove(board, 'register', [{ lane: 'web', path: '/web', model: 'Second Model' }]);++ const changed = applyEngineMove(board, { ...update, engine: version }, { sequence: 2, at: '2026-10-10T07:01:00Z' });++ assert.equal(changed.error, undefined);++ assert.equal(changed.result, 'web-1');++ assert.equal(changed.events.length, version < 8 ? 0 : 1);++ assert.equal(store.agentAt(board, '/web').agent_model, version < 8 ? null : 'Second Model');++ if (version === 8) {++ assert.equal(changed.events[0].event_kind, 'model');++ assert.deepEqual(JSON.parse(changed.events[0].event_detail), { model: 'Second Model' });++ assert.deepEqual(JSON.parse(store.events(board)[0].event_detail), { lane: 'web', model: 'First Model' },++ 'later model changes never rewrite an earlier move snapshot');++ }++ }++});++++test('exchanged replicas keep models and record identical later agent moves [O8,O3,H16]', (t) => {++ const source = store.openBoard(':memory:');++ const replica = store.openBoard(':memory:');++ t.after(() => { store.closeBoard(source); store.closeBoard(replica); });++ const id = store.register(source, { lane: 'web', path: '/web', model: 'Declared Model' });++ importBoard(replica, exportBoard(source));++ assert.equal(store.agentAt(replica, '/web').agent_model, 'Declared Model');++ const move = prepareEngineMove(source, 'shout', [{ from: id, to: 'person', text: 'Keep web-1 literal', lanes: ['web'] }]);++ const receipt = { sequence: 1, at: '2026-10-10T07:02:00Z' };++ const one = applyEngineMove(source, move, receipt);++ const two = applyEngineMove(replica, move, receipt);++ assert.equal(one.error, undefined);++ assert.deepEqual(two, one);++ assert.equal(one.events[0].event_by, 'web-1');++ assert.equal(JSON.parse(one.events[0].event_detail).model, 'Declared Model');++ assert.deepEqual(exportBoard(replica), exportBoard(source));++});++++test('agent name options preserve valid defaults and refuse invalid objects [O8]', (t) => {++ assert.equal(defaults().agents.names, 'suffix');++ const root = mkdtempSync(join(tmpdir(), 'pullboard-agent-names-'));++ t.after(() => rmSync(root, { recursive: true, force: true }));++ for (const agents of [null, 'prefix', [], { names: 'other' }]) {++ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ agents }));++ assert.throws(() => loadConfig(root), (error) => error.code === 'BAD_CONFIG');++ }++ assert.deepEqual(configProblems({ ...defaults(), agents: { names: 'prefix' } }), []);++});diff --cc test/agent-session.test.jsindex 00000000,5161a81f..62d63f5amode 000000,100644..100644--- a/test/agent-session.test.js+++ b/test/agent-session.test.js@@@ -1,0 -1,309 +1,309 @@@+ /** Checkout-session ownership and takeover behavior [B3,B7]. */+ import assert from 'node:assert/strict';+ import { startFixtureChild as spawn, fixtureChildMessage, reportFixtureChildFailure, runFixtureChild, runFixtureGit } from './fixture-child.js';+ import { createHash } from 'node:crypto';+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, readdirSync } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { pathToFileURL } from 'node:url';+ import { join, resolve } from 'node:path';+ import { after, test } from 'node:test';+ import { DatabaseSync } from 'node:sqlite';+ import { listResources } from '../src/resources.js';++ const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+ const DIRS = [];+ const MARKERS = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT', 'CODEX_THREAD_ID', 'CODEX_SESSION_ID', 'CODEX_CI', 'CODEX_SHELL'];+ const SPEC = '# Session fixture\n\n## G · Goals\n- G1 [approved, must] The fixture works. | gate: true\n';+ const CONFIG = { gate: 'true', spec: 'SPEC.md', verify: 'any', lease: '2h', lanes: { web: { owns: ['web/'], specs: ['G1'] } }, shared: ['docs/'] };++ after(() => { for (const dir of DIRS) rmSync(dir, { recursive: true, force: true }); });++ /** Build a private CLI environment without ambient agent/session or Git selectors. */+ function sandbox() {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-agent-session-'));+ DIRS.push(dir);+ const bin = join(dir, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec '${process.execPath.replaceAll("'", "'\\''")}' '${BIN.replaceAll("'", "'\\''")}' "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const base = { ...process.env };+ for (const key of Object.keys(base)) if (key.startsWith('GIT_') || MARKERS.includes(key) || key === 'CLAUDE_CODE_SESSION_ID') delete base[key];+ Object.assign(base, {+ PULLBOARD_HOME: join(dir, 'pullboard-home'),+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'), PATH: `${bin}:${process.env.PATH}`,+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Session fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Session fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ });+ /** Run real Git with the private environment. */+ function git(cwd, ...args) {+ return runFixtureGit(args, { cwd, env: base });+ }+ /** Run the actual CLI with an explicit agent session or markerless terminal. */+ function run(cwd, args, { session, sessionKey = 'CLAUDE_CODE_SESSION_ID', agent = true } = {}) {+ const env = { ...base };+ if (agent) {+ env.CLAUDECODE = '1';+ if (session !== undefined) env[sessionKey] = session;+ }+ return runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });+ }+ return { dir, base, git, run };+ }++ /** Create the main checkout and one joined lane worktree with a private board. */+ function project() {+ const box = sandbox();+ const repo = join(box.dir, 'repo');+ mkdirSync(repo);+ box.git(repo, 'init', '-q', '-b', 'main');+ assert.equal(box.run(repo, ['init'], { agent: false }).status, 0);+ writeFileSync(join(repo, 'pullboard.json'), `${JSON.stringify(CONFIG, null, 2)}\n`);+ writeFileSync(join(repo, 'SPEC.md'), SPEC);+ mkdirSync(join(repo, 'web'));+ writeFileSync(join(repo, 'web', 'page.txt'), 'ready\n');+ box.git(repo, 'add', '-A');+ box.git(repo, 'commit', '-q', '-m', 'chore: initialize session fixture');+ const added = box.run(repo, ['add', 'web', 'fixture item', '--specs', 'G1', '--json'], { agent: false });+ assert.equal(added.status, 0, `${added.stdout}${added.stderr}`);+ const web = join(box.dir, 'web-agent');+ box.git(repo, 'worktree', 'add', '-q', web, '-b', 'web/session');+ const joined = box.run(web, ['join', 'web'], { agent: false });+ assert.equal(joined.status, 0, `${joined.stdout}${joined.stderr}`);+ return { ...box, repo, web, boardFile: resolve(repo, box.git(repo, 'rev-parse', '--git-common-dir'), 'pullboard', 'board.sqlite') };+ }++ /** Capture stable board counts so a refused write proves no event, row, or shout was added. */+ function boardSnapshot(file) {+ const db = new DatabaseSync(file, { readOnly: true });+ try {+ return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(({name}) => [name, db.prepare(`SELECT * FROM ${name} ORDER BY rowid`).all()]));+ } finally { db.close(); }+ }++ /** Keep raw ids out of SQLite and local files; only the current digest lives in this checkout’s Git directory. */+ function assertNoRawSession(box, cwd, secrets, sessionKey = 'CLAUDE_CODE_SESSION_ID') {+ const file = box.boardFile;+ const dir = file.slice(0, file.lastIndexOf('/'));+ const files = readdirSync(dir).filter((name) => /board\.sqlite(?:-(?:wal|shm))?$/u.test(name));+ assert.ok(files.length, 'private SQLite board files were created');+ for (const name of files) {+ const bytes = readFileSync(join(dir, name));+ for (const secret of secrets) assert.equal(bytes.includes(Buffer.from(secret)), false, `raw session id is not persisted in ${name}`);+ }+ const db = new DatabaseSync(file, { readOnly: true });+ try {+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all().map((row) => row.name);+ const stored = tables.flatMap((table) => db.prepare(`SELECT * FROM \"${table.replaceAll('\"', '\"\"')}\"`).all())+ .map((row) => JSON.stringify(row)).join('\\n');+ for (const secret of secrets) {+ const digest = createHash('sha256').update(JSON.stringify([sessionKey, secret])).digest('hex');+ assert.equal(stored.includes(digest), false, 'session bindings never enter shared board data');+ }+ } finally { db.close(); }+ const local = resolve(cwd, box.git(cwd, 'rev-parse', '--git-dir'), 'pullboard-checkout-session.json');+ const bindingText = readFileSync(local, 'utf8');+ for (const secret of secrets) assert.equal(bindingText.includes(secret), false);+ const binding = JSON.parse(bindingText);+ assert.equal(binding.agent, cwd === box.repo ? 'coordinator' : 'web-1');+ assert.equal(binding.digest, createHash('sha256').update(JSON.stringify([sessionKey, secrets.at(-1)])).digest('hex'));+ assert.ok(Number.isFinite(Date.parse(binding.at)));+ }++ test('a second session cannot write in the main checkout until takeover [B3,B7]', () => {+ const box = project();+ const first = 'claude-session-secret-first-273';+ const second = 'claude-session-secret-second-273';+ const initial = box.run(box.repo, ['shout', 'web', 'first session owns main', '--json'], { session: first });+ assert.equal(initial.status, 0, `${initial.stdout}${initial.stderr}`);+ const before = boardSnapshot(box.boardFile);+ const refused = box.run(box.repo, ['shout', 'web', 'must not land', '--json'], { session: second });+ assert.notEqual(refused.status, 0);+ const error = JSON.parse(refused.stdout).error;+ assert.equal(error.code, 'NOT_YOUR_CHECKOUT');+ assert.match(error.message, /coordinator/u);+ assert.match(error.next, /pullboard worktree/u);+ assert.match(error.message, /pullboard takeover/u);+ assert.deepEqual(boardSnapshot(box.boardFile), before, 'refusal leaves all board counts unchanged');+ const worktrees = box.git(box.repo, 'worktree', 'list', '--porcelain');+ for (const args of [['init'], ['worktree', 'web'], ['hooks'], ['spec', 'apply'], ['hook', 'pre-commit'], ['submit', '1']]) {+ const blocked = box.run(box.repo, [...args, '--json'], { session: second });+ assert.equal(blocked.status, 1, `${args.join(' ')} must refuse another session before side effects`);+ assert.equal(JSON.parse(blocked.stdout).error.code, 'NOT_YOUR_CHECKOUT');+ assert.deepEqual(boardSnapshot(box.boardFile), before, `${args.join(' ')} leaves every board row intact`);+ assert.equal(box.git(box.repo, 'worktree', 'list', '--porcelain'), worktrees, 'the wrong session cannot create a worktree first');+ }++ const takeover = box.run(box.repo, ['takeover', '--json'], { session: second });+ assert.equal(takeover.status, 0, `${takeover.stdout}${takeover.stderr}`);+ const rows = boardSnapshot(box.boardFile);+ assert.ok(rows.event.slice(before.event.length).some(row => row.event_kind === 'shout' && row.event_by === 'coordinator'), 'takeover is recorded through an existing ordered shout event');- assert.match(rows.shout.at(-1).shout_text, /coordinator took over/);++ assert.match(rows.shout.at(-1).shout_text, /coordinator \(unknown\) took over/);+ assert.equal(rows.shout.at(-1).shout_to, 'person');+ assert.equal(rows.shout.length, before.shout.length + 1, 'main-checkout takeover records the person notice');+ const after = box.run(box.repo, ['shout', 'web', 'second session owns main', '--json'], { session: second });+ assert.equal(after.status, 0, `${after.stdout}${after.stderr}`);+ assertNoRawSession(box, box.repo, [first, second]);+ const beforeSelf = boardSnapshot(box.boardFile);+ const self = box.run(box.repo, ['shout', 'coordinator', 'cannot address myself', '--json'], { agent: false });+ assert.notEqual(self.status, 0);+ assert.deepEqual(boardSnapshot(box.boardFile), beforeSelf, 'self-addressed shout is refused without changing the board');+ });++ test('lane ownership is session-scoped and takeover preserves the joined agent [B3,B7]', () => {+ const box = project();+ const first = 'codex-thread-secret-first-273';+ const second = 'codex-thread-secret-second-273';+ const claim = box.run(box.web, ['claim', '1', '--json'], { session: first, sessionKey: 'CODEX_THREAD_ID' });+ assert.equal(claim.status, 0, `${claim.stdout}${claim.stderr}`);+ const sameSession = box.run(box.web, ['claim', '1', '--json'], { session: first, sessionKey: 'CODEX_THREAD_ID' });+ assert.equal(sameSession.status, 0, `${sameSession.stdout}${sameSession.stderr}`);+ const before = boardSnapshot(box.boardFile);+ const refused = box.run(box.web, ['claim', '1', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });+ assert.notEqual(refused.status, 0);+ assert.equal(JSON.parse(refused.stdout).error.code, 'NOT_YOUR_CHECKOUT');+ assert.match(JSON.parse(refused.stdout).error.message, /web-1/u);+ assert.match(JSON.parse(refused.stdout).error.next, /pullboard worktree/u);+ assert.deepEqual(boardSnapshot(box.boardFile), before, 'refused lane write leaves event and item counts unchanged');++ const takeover = box.run(box.web, ['takeover', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });+ assert.equal(takeover.status, 0, `${takeover.stdout}${takeover.stderr}`);+ assert.equal(boardSnapshot(box.boardFile).event.length, before.event.length + 1, 'lane takeover records one event');+ assert.equal(boardSnapshot(box.boardFile).shout.at(-1).shout_to, 'coordinator');+ const after = box.run(box.web, ['claim', '1', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });+ assert.equal(after.status, 0, `${after.stdout}${after.stderr}`);+ assertNoRawSession(box, box.web, [first, second], 'CODEX_THREAD_ID');+ });++ test('no-session shells are one session and markerless terminals retain their writes [B3,B7]', () => {+ const box = project();+ const sentinel = box.run(box.web, ['claim', '1', '--json'], { session: undefined });+ assert.equal(sentinel.status, 0, `${sentinel.stdout}${sentinel.stderr}`);+ const noSessionAgain = box.run(box.web, ['claim', '1', '--json'], { session: undefined });+ assert.equal(noSessionAgain.status, 0, `${noSessionAgain.stdout}${noSessionAgain.stderr}`);+ const terminalRead = box.run(box.web, ['show', '1', '--json'], { agent: false });+ assert.equal(terminalRead.status, 0, `${terminalRead.stdout}${terminalRead.stderr}`);+ assert.equal(JSON.parse(terminalRead.stdout).item_status, 'claimed');+ const beforeIdentified = boardSnapshot(box.boardFile);+ const identified = box.run(box.web, ['release', '1', '--json'], { session: 'identified-after-sentinel-273', sessionKey: 'CODEX_SESSION_ID' });+ assert.equal(identified.status, 1);+ assert.equal(JSON.parse(identified.stdout).error.code, 'NOT_YOUR_CHECKOUT');+ assert.deepEqual(boardSnapshot(box.boardFile), beforeIdentified);+ const terminalWrite = box.run(box.web, ['shout', 'coordinator', 'the markerless terminal still works', '--json'], { agent: false });+ assert.equal(terminalWrite.status, 0, terminalWrite.stdout + terminalWrite.stderr);+ const secondSessionRead = box.run(box.web, ['show', '1', '--json'], { session: 'read-from-another-session-273' });+ assert.equal(secondSessionRead.status, 0, secondSessionRead.stdout + secondSessionRead.stderr);++ // Existing relay-person-request coverage should be retained: this private CLI fixture does not+ // establish a linked relay or inject io.personRequest, so an ordinary shout is not a substitute.+ // A decision addressed to its own sender must be refused rather than self-answered.+ const beforeSelf = boardSnapshot(box.boardFile);+ const self = box.run(box.repo, ['shout', 'coordinator', 'self decision', '--decision', '--json'], { agent: false });+ assert.notEqual(self.status, 0);+ assert.deepEqual(boardSnapshot(box.boardFile), beforeSelf, 'self-addressed decision is refused without a write');+ });++ test('the actual view adapter writes without taking over an agent session [B3,B7]', () => {+ const box = project();+ const owner = box.run(box.repo, ['shout', 'web', 'agent owns this checkout', '--json'], { session: 'view-owner-session-273' });+ assert.equal(owner.status, 0, owner.stdout + owner.stderr);+ const file = resolve(box.repo, box.git(box.repo, 'rev-parse', '--git-dir'), 'pullboard-checkout-session.json');+ const before = readFileSync(file);+ const apiModule = pathToFileURL(resolve(import.meta.dirname, '../src/api.js')).href;+ const cliModule = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;+ const source = `+ const { executeMove } = await import(${JSON.stringify(apiModule)});+ const { main } = await import(${JSON.stringify(cliModule)});+ const response = await executeMove(process.cwd(), { verb: 'shout', args: { to: 'web', text: 'actual view action' } }, main);+ process.stdout.write(JSON.stringify(response));+ `;+ const response = runFixtureChild(process.execPath, ['--input-type=module', '-e', source], {+ cwd: box.repo, env: { ...box.base, CODEX_THREAD_ID: 'other-process-view-session-273' }, encoding: 'utf8',+ });+ assert.equal(response.status, 0, fixtureChildMessage(response));+ const document = JSON.parse(response.stdout);+ assert.equal(document.status, 200, response.stdout);+ assert.equal(document.body.event.event_kind, 'shout');+ assert.equal(document.body.event.event_by, 'coordinator');+ assert.equal(boardSnapshot(box.boardFile).shout.at(-1).shout_text, 'actual view action');+ assert.deepEqual(readFileSync(file), before, 'the authenticated view does not alter the local agent-session binding');+ });++ test('takeover waits for an active write and then refuses the old session [B3,B7]', { timeout: 45_000 }, async () => {+ const box = project();+ const started = join(box.dir, 'gate-started');+ const release = join(box.dir, 'gate-release');+ const gateFile = join(box.dir, 'holding-gate.cjs');+ writeFileSync(gateFile, `const fs = require('node:fs');+ fs.writeFileSync(${JSON.stringify(started)}, 'started');+ const timer = setInterval(() => { if (fs.existsSync(${JSON.stringify(release)})) { clearInterval(timer); process.exit(0); } }, 10);+ setTimeout(() => process.exit(19), 20000).unref();+ `);+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: `node '${gateFile.replaceAll("'", "'\\''")}'` }));+ box.git(box.repo, 'add', 'pullboard.json');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: configure holding gate');+ box.git(box.web, 'merge', '--quiet', 'main');+ const claim = box.run(box.web, ['claim', '1', '--json'], { session: 'active-write-273', sessionKey: 'CODEX_SESSION_ID' });+ assert.equal(claim.status, 0, claim.stdout + claim.stderr);+ writeFileSync(join(box.web, 'web/page.txt'), 'changed for the claimed item\n');+ box.git(box.web, 'add', 'web/page.txt');+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): change the page [G1]');+ /** Start a real CLI write with a durable closed-process observation. */+ function launch(session, ...args) {+ const command = process.execPath;+ const childArgs = [BIN, ...args, '--json'];+ const childEnv = { ...box.base, CODEX_SESSION_ID: session };+ const startedAt = performance.now();+ const child = spawn(command, childArgs, { cwd: box.web, env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });+ let output = '';+ let stderr = '';+ child.stdout.setEncoding('utf8').on('data', (part) => { output += part; });+ child.stderr.setEncoding('utf8').on('data', (part) => { stderr += part; });+ let spawnError = null;+ child.once('error', (error) => { spawnError = error; });+ child.closed = new Promise((resolveClose) => child.once('close', (code, signal) => {+ const failure = code === 0 && !signal && !spawnError ? null : reportFixtureChildFailure({ command, args: childArgs,+ status: code, signal, elapsedMs: performance.now() - startedAt, stderr, env: childEnv,+ detail: spawnError?.message ?? '' });+ resolveClose({ code, signal, output, stderr, failure });+ }));+ return child;+ }+ /** Wait on an actual private fixture observation, with an assertion if it never becomes true. */+ async function observed(predicate, label) {+ const deadline = Date.now() + 10_000;+ while (!predicate() && Date.now() < deadline) await new Promise((done) => setTimeout(done, 10));+ assert.ok(predicate(), label);+ }+ /** Observe the takeover waiting on this checkout's resource rather than depending on a sleep. */+ function queued() {+ return listResources({ scope: 'repo', root: box.repo }).some((resource) => resource.name.startsWith('checkout-session:') && resource.line.length > 0);+ }+ const submission = launch('active-write-273', 'submit', '1');+ let takeover;+ try {+ await observed(() => existsSync(started) || submission.exitCode !== null, 'the actual submission reaches its configured gate');+ assert.equal(submission.exitCode, null, 'the submission is still writing while the gate waits');+ takeover = launch('next-write-273', 'takeover');+ await observed(() => queued() || takeover.exitCode !== null, 'the takeover reaches the same checkout guard');+ assert.equal(takeover.exitCode, null, 'takeover waits until the old session finishes its active write');+ assert.equal(boardSnapshot(box.boardFile).shout.length, 0, 'takeover has not recorded a receipt before acquiring the checkout');+ writeFileSync(release, 'release');+ const submitted = await submission.closed;+ assert.equal(submitted.code, 0, submitted.failure ?? submitted.output);+ const taken = await takeover.closed;+ assert.equal(taken.code, 0, taken.failure ?? taken.output);+ assert.equal(boardSnapshot(box.boardFile).item[0].item_status, 'submitted');+ const beforeRefusal = boardSnapshot(box.boardFile);+ const old = box.run(box.web, ['shout', 'coordinator', 'old session cannot write', '--json'], { session: 'active-write-273', sessionKey: 'CODEX_SESSION_ID' });+ assert.equal(old.status, 1);+ assert.equal(JSON.parse(old.stdout).error.code, 'NOT_YOUR_CHECKOUT');+ assert.deepEqual(boardSnapshot(box.boardFile), beforeRefusal);+ } finally {+ writeFileSync(release, 'release');+ if (submission.exitCode === null) submission.kill('SIGTERM');+ if (takeover?.exitCode === null) takeover.kill('SIGTERM');+ await submission.closed;+ if (takeover) await takeover.closed;+ }+ });diff --cc test/api.test.jsindex 2fdb49ad,46df3d18..143fcd4c--- a/test/api.test.js+++ b/test/api.test.js@@@ -214,7 -185,7 +219,7 @@@ function json(box, cwd, command, argsassert.equal(result.status, 0, `${command} ${args.join(' ')}: ${result.stderr}${result.stdout}`);const document = JSON.parse(result.stdout);if (command === 'check') {-- assert.equal(result.stderr, `check #${document.id} set by ${document.by}: ${document.check}\n`, 'check attribution is visible before execution while stdout remains one JSON document');++ assert.equal(result.stderr, `check #${document.id} set by ${document.by} (unknown): ${document.check}\n`, 'check attribution is visible before execution while stdout remains one JSON document');} else assert.equal(result.stderr, '', `${command} --json must keep stderr empty`);assert.equal(document.version, 1, `${command} --json has a version 1 envelope`);assertRequiredShape(document, shapeFor(command, subcommand).required, command);diff --cc test/coordinator-resume.test.jsindex 00000000,3787e31d..57fb9285mode 000000,100644..100644--- a/test/coordinator-resume.test.js+++ b/test/coordinator-resume.test.js@@@ -1,0 -1,301 +1,301 @@@+ /** Keep the coordinator's handoff brief short, ordered, and derived from real Git and board state [N19,B3]. */+ import assert from 'node:assert/strict';+ import { runFixtureExecFile as execFileSync, runFixtureChild as spawnSync, runFixtureChild, runFixtureGit } from './fixture-child.js';+ import { DatabaseSync } from 'node:sqlite';+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { join, resolve } from 'node:path';+ import { after, test } from 'node:test';++ const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+ const sandboxes = [];+ const SPEC = `# Resume fixture\n\n## G · Goals\n- G1 [approved, must] The first feature works. | gate: test\n- G2 [approved, must] The second feature works. | gate: test\n`;+ const HOUR = 60 * 60 * 1000;+ const DAY = 24 * HOUR;++ after(() => {+ for (const dir of sandboxes) rmSync(dir, { recursive: true, force: true });+ });++ /** Make an isolated real-Git repo, initialized board, coordinator and strong builder. */+ function fixture() {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-coordinator-resume-')));+ sandboxes.push(dir);+ const shims = join(dir, 'bin');+ mkdirSync(shims);+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "${BIN}" "$@"\n`, { mode: 0o755 });+ chmodSync(join(shims, 'pullboard'), 0o755);+ const env = {+ ...process.env,+ PATH: `${shims}:${process.env.PATH}`,+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Test Agent', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Test Agent', GIT_COMMITTER_EMAIL: '[email protected]',+ PULLBOARD_HOME: join(dir, 'home'), PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),+ };+ delete env.PULLBOARD_RELAY_TOKEN;+ const repo = join(dir, 'repo');+ mkdirSync(repo);+ /** Run Git in this private fixture with its isolated identity. */+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env });+ /** Run the actual CLI in a fixture checkout and retain both output streams. */+ const run = (cwd, ...args) => {+ const result = runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });+ return { code: result.status, out: result.stdout ?? '', err: result.failure ?? result.stderr ?? '', failure: result.failure };+ };+ git(repo, 'init', '-q', '-b', 'main');+ assert.equal(run(repo, 'init').code, 0);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({+ gate: 'true', spec: 'SPEC.md', verify: 'any', lease: '2h',+ lanes: { web: { owns: ['web/'], specs: ['G1', 'G2'] } },+ }, null, 2));+ writeFileSync(join(repo, 'SPEC.md'), SPEC);+ write(repo, 'web/shared.txt', 'base\n');+ commit(git, repo, 'chore: create resume fixture');+ const made = run(repo, 'worktree', 'web', '--route', 'strong', '--json');+ assert.equal(made.code, 0, made.err || made.out);+ const web = JSON.parse(made.out).path;+ return { dir, env, repo, web, git, run };+ }++ /** Write a fixture file and create its parent directory. */+ function write(root, path, text) {+ mkdirSync(join(root, path, '..'), { recursive: true });+ writeFileSync(join(root, path), text);+ }++ /** Stage and commit the fixture's current tree through its installed hooks. */+ function commit(git, cwd, message) {+ git(cwd, 'add', '-A');+ git(cwd, 'commit', '-q', '-m', message);+ return git(cwd, 'rev-parse', 'HEAD');+ }++ /** Ask real Git whether one fixture commit contains another. */+ function isAncestor(box, cwd, ancestor, commitId) {+ return runFixtureChild('git', ['merge-base', '--is-ancestor', ancestor, commitId], { cwd, env: box.env }).status === 0;+ }++ /** Add a separately joined strong builder so each item's accepted commit has an isolated branch. */+ function addBuilder(box, name) {+ const cwd = join(box.dir, name);+ box.git(box.repo, 'worktree', 'add', '-q', '-b', `web/${name}`, cwd, 'main');+ const joined = box.run(cwd, 'join', 'web', '--route', 'strong');+ assert.equal(joined.code, 0, joined.err || joined.out);+ return cwd;+ }++ /** Add and claim a strong item with the complete brief shape expected by production. */+ function addAndClaim(box, cwd, title, row) {+ const brief = `Files:\n- web/fixture.txt\nTest:\n- inspect the committed fixture history`;+ const added = box.run(box.repo, 'add', 'web', title, '--route', 'strong', '--specs', row,+ '--criterion', 'the cited row holds', '--check', 'true', '--brief', brief);+ assert.equal(added.code, 0, added.err || added.out);+ const id = Number(/#(\d+)/u.exec(added.out)?.[1]);+ assert.ok(id > 0, added.out);+ const claimed = box.run(cwd, 'claim', String(id));+ assert.equal(claimed.code, 0, claimed.err || claimed.out);+ return id;+ }++ /** Submit one builder commit with a valid row-citing header. */+ function submitFile(box, cwd, id, row, path, text, subject) {+ write(cwd, path, text);+ const head = commit(box.git, cwd, `feat(web): ${subject} [${row}]`);+ const submitted = box.run(cwd, 'submit', String(id));+ assert.equal(submitted.code, 0, submitted.err || submitted.out);+ return head;+ }++ /** Verify an exact submitted commit from the main checkout, then return it to main. */+ function acceptAt(box, id, commitId) {+ box.git(box.repo, 'switch', '-q', '--detach', commitId);+ const accepted = box.run(box.repo, 'verify', String(id), 'accept', '--note', 'the frozen row holds', '--as', 'coordinator');+ assert.equal(accepted.code, 0, accepted.err || accepted.out);+ box.git(box.repo, 'switch', '-q', 'main');+ }++ /** Record structured integration evidence independently of the human-readable shout text. */+ function integrationEvidence(box, cwd, id, kind, outcome, commitId, text) {+ const result = box.run(cwd, 'shout', 'coordinator', text, '--evidence', kind, '--outcome', outcome,+ '--item', String(id), '--commit', commitId, '--json');+ assert.equal(result.code, 0, result.err || result.out);+ return JSON.parse(result.out).id;+ }++ test("the coordinator's handoff brief orders current work and leaves agent resumes unchanged [N19,B3]", () => {+ const box = fixture();+ const cleanBuilder = box.web;+ const cleanId = addAndClaim(box, cleanBuilder, 'Clean item', 'G1');+ const cleanHead = submitFile(box, cleanBuilder, cleanId, 'G1', 'web/clean.txt', 'clean\n', 'add clean file');+ acceptAt(box, cleanId, cleanHead);++ const conflictBuilder = addBuilder(box, 'conflict-builder');+ const conflictId = addAndClaim(box, conflictBuilder, 'Conflict item', 'G1');+ const conflictHead = submitFile(box, conflictBuilder, conflictId, 'G1', 'web/shared.txt', 'builder side\n', 'change shared file');+ acceptAt(box, conflictId, conflictHead);++ const activeBuilder = addBuilder(box, 'active-builder');+ const activeId = addAndClaim(box, activeBuilder, 'Typed integration', 'G1');+ const activeHead = submitFile(box, activeBuilder, activeId, 'G1', 'web/active.txt', 'accepted base\n', 'prepare integration');+ acceptAt(box, activeId, activeHead);+ write(activeBuilder, 'web/descendant.txt', 'later integration work\n');+ const descendant = commit(box.git, activeBuilder, 'chore(web): prepare integration descendant [G1]');+ assert.equal(isAncestor(box, activeBuilder, activeHead, descendant), true, 'the evidence SHA is a descendant of the accepted head');+ integrationEvidence(box, activeBuilder, activeId, 'attempt', 'integrating', descendant, 'The worktree is ready for coordinator integration.');++ const supersededBuilder = addBuilder(box, 'superseded-builder');+ const supersededId = addAndClaim(box, supersededBuilder, 'Superseded integration', 'G2');+ const supersededHead = submitFile(box, supersededBuilder, supersededId, 'G2', 'web/superseded.txt', 'accepted\n', 'prepare superseded integration');+ acceptAt(box, supersededId, supersededHead);+ write(supersededBuilder, 'web/superseded-descendant.txt', 'descendant\n');+ const supersededDescendant = commit(box.git, supersededBuilder, 'chore(web): prepare superseded descendant [G2]');+ integrationEvidence(box, supersededBuilder, supersededId, 'attempt', 'integrating', supersededDescendant, 'Begin integration.');+ integrationEvidence(box, supersededBuilder, supersededId, 'receipt', 'superseded', supersededDescendant, 'The same actor has a later receipt.');++ const plainBuilder = addBuilder(box, 'plain-builder');+ const plainId = addAndClaim(box, plainBuilder, 'Plain text only', 'G2');+ const plainHead = submitFile(box, plainBuilder, plainId, 'G2', 'web/plain.txt', 'plain\n', 'prepare plain evidence');+ acceptAt(box, plainId, plainHead);+ const plain = box.run(plainBuilder, 'shout', 'coordinator', `#${plainId} integrated at ${plainHead}`);+ assert.equal(plain.code, 0, plain.err || plain.out);++ const factBuilder = addBuilder(box, 'fact-builder');+ const factId = addAndClaim(box, factBuilder, 'Fact text only', 'G2');+ const factHead = submitFile(box, factBuilder, factId, 'G2', 'web/fact.txt', 'fact\n', 'prepare fact evidence');+ acceptAt(box, factId, factHead);+ const fact = box.run(box.repo, 'fact', String(factId), 'note', `#${factId} integrated at ${factHead}`, '--ref', `web/fact.txt:1@${factHead}`);+ assert.equal(fact.code, 0, fact.err || fact.out);++ const unrelatedBuilder = addBuilder(box, 'unrelated-builder');+ const unrelatedId = addAndClaim(box, unrelatedBuilder, 'Non-ancestor evidence', 'G2');+ const unrelatedHead = submitFile(box, unrelatedBuilder, unrelatedId, 'G2', 'web/unrelated.txt', 'accepted\n', 'prepare non-ancestor evidence');+ acceptAt(box, unrelatedId, unrelatedHead);+ const unrelatedTree = box.git(box.repo, 'rev-parse', 'main^{tree}');+ const unrelatedCommit = box.git(box.repo, 'commit-tree', unrelatedTree, '-m', 'unrelated integration evidence');+ assert.equal(isAncestor(box, box.repo, unrelatedHead, unrelatedCommit), false, 'the evidence SHA does not contain the accepted head');+ integrationEvidence(box, unrelatedBuilder, unrelatedId, 'attempt', 'integrating', unrelatedCommit, 'This SHA is not descended from the accepted head.');+ integrationEvidence(box, activeBuilder, activeId, 'attempt', 'integrating', unrelatedCommit, 'An invalid newer attempt cannot close the earlier valid claim.');+ integrationEvidence(box, plainBuilder, activeId, 'receipt', 'done', descendant, 'Another actor cannot close the builder integration attempt.');++ const expiredBuilder = addBuilder(box, 'expired-builder');+ const expiredId = addAndClaim(box, expiredBuilder, 'Expired integration evidence', 'G2');+ const expiredHead = submitFile(box, expiredBuilder, expiredId, 'G2', 'web/expired.txt', 'accepted\n', 'prepare expired evidence');+ acceptAt(box, expiredId, expiredHead);+ const expiredShoutId = integrationEvidence(box, expiredBuilder, expiredId, 'attempt', 'integrating', expiredHead, 'This attempt is older than one day.');+ const boardFile = join(box.repo, '.git', 'pullboard', 'board.sqlite');+ const db = new DatabaseSync(boardFile);+ try {+ const old = new Date(Date.now() - DAY - HOUR).toISOString();+ db.prepare('UPDATE shout SET shout_at = ? WHERE shout_id = ?').run(old, expiredShoutId);+ } finally {+ db.close();+ }++ write(box.repo, 'web/shared.txt', 'trunk side\n');+ commit(box.git, box.repo, 'feat(web): trunk shared edit [G1]');++ const reviewBuilder = addBuilder(box, 'review-builder');+ const reviewId = addAndClaim(box, reviewBuilder, 'Review item', 'G2');+ submitFile(box, reviewBuilder, reviewId, 'G2', 'web/review.txt', 'review\n', 'submit review item');++ const open = box.run(cleanBuilder, 'shout', 'coordinator', 'Need a decision on the next build.', '--decision');+ assert.equal(open.code, 0, open.err || open.out);+ const openId = Number(/#(\d+)/u.exec(open.out)?.[1]);+ const personQuestion = box.run(box.repo, 'shout', 'person', 'Should the release wait?', '--decision');+ assert.equal(personQuestion.code, 0, personQuestion.err || personQuestion.out);+ const personQuestionId = Number(/#(\d+)/u.exec(personQuestion.out)?.[1]);+ const answeredQuestion = box.run(box.repo, 'shout', 'person', 'Can the report ship today?', '--decision');+ assert.equal(answeredQuestion.code, 0, answeredQuestion.err || answeredQuestion.out);+ const answeredId = Number(/#(\d+)/u.exec(answeredQuestion.out)?.[1]);+ const answered = box.run(box.repo, 'answer', String(answeredId), 'Yes, after the review.', '--as', 'person');+ assert.equal(answered.code, 0, answered.err || answered.out);++ const oldAsk = box.run(box.repo, 'shout', 'person', 'Old answered decision.', '--decision', '--json');+ assert.equal(oldAsk.code, 0, oldAsk.err || oldAsk.out);+ const oldAskId = JSON.parse(oldAsk.out).id;+ const oldAnswer = box.run(box.repo, 'answer', String(oldAskId), 'Old answer stays in history.', '--as', 'person', '--json');+ assert.equal(oldAnswer.code, 0, oldAnswer.err || oldAnswer.out);+ const oldAnswerId = JSON.parse(oldAnswer.out).id;+ for (let index = 0; index < 4; index += 1) {+ const ask = box.run(cleanBuilder, 'shout', 'coordinator', `Additional decision ${index}: ${'detail '.repeat(50)}`, '--decision');+ assert.equal(ask.code, 0, ask.err || ask.out);+ }++ const timestampDb = new DatabaseSync(boardFile);+ try {+ const now = Date.now();+ timestampDb.prepare('UPDATE shout SET shout_at = ? WHERE shout_id = ?').run(new Date(now - 2 * HOUR).toISOString(), openId);+ const answerId = timestampDb.prepare('SELECT shout_id FROM shout WHERE shout_answers = ? ORDER BY shout_id LIMIT 1').get(answeredId).shout_id;+ timestampDb.prepare('UPDATE shout SET shout_at = ? WHERE shout_id = ?').run(new Date(now - HOUR).toISOString(), answerId);+ timestampDb.prepare('UPDATE shout SET shout_at = ? WHERE shout_id = ?').run(new Date(now - DAY - HOUR).toISOString(), oldAnswerId);+ } finally {+ timestampDb.close();+ }++ // More than the normal recent-shout window must not hide typed evidence from resume.+ for (let index = 0; index < 45; index += 1) {+ const noise = box.run(box.repo, 'shout', 'person', `noise ${index}: #${activeId} integrated at ${descendant}`);+ assert.equal(noise.code, 0, noise.err || noise.out);+ }+ const currentSpec = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');+ writeFileSync(join(box.repo, 'SPEC.md'), currentSpec.replace('The first feature works.', 'The first feature works differently.'));++ const resumed = box.run(box.repo, 'resume');+ assert.equal(resumed.code, 0, resumed.err);+ assert.ok(resumed.out.length < 4_000, `handoff brief should stay short (${resumed.out.length} characters)`);+ assert.equal((resumed.out.match(/^open decision /gmu) ?? []).length, 3, 'text caps each section while JSON keeps all records');+ assert.doesNotMatch(resumed.out, /Old answer stays in history/u);- assert.match(resumed.out, new RegExp(`open decision #${openId} from web-1 \\(2h\\): Need a decision`));- assert.match(resumed.out, /recent decision .*person answered coordinator \(1h ago\): Yes, after the review\./u);++ assert.match(resumed.out, new RegExp(`open decision #${openId} from web-1 \\(Test Model\\) \\(2h\\): Need a decision`));++ assert.match(resumed.out, /recent decision .*person answered coordinator \(unknown\) \(1h ago\): Yes, after the review\./u);+ assert.match(resumed.out, new RegExp(`merges cleanly: #${cleanId} Clean item`));+ assert.match(resumed.out, new RegExp(`conflicts: #${conflictId} Conflict item \\(web/shared\\.txt\\)`));- assert.match(resumed.out, new RegExp(`claimed for integration: #${activeId} by web-3 at .*\\(${descendant.slice(0, 12)}\\)`));++ assert.match(resumed.out, new RegExp(`claimed for integration: #${activeId} by web-3 \\(Test Model\\) at .*\\(${descendant.slice(0, 12)}\\)`));+ assert.doesNotMatch(resumed.out, new RegExp(`claimed for integration: #(?:${supersededId}|${plainId}|${factId}|${unrelatedId}|${expiredId})\\b`),+ 'a later same-actor receipt, plain shout/fact text, non-ancestor SHA, or expired attempt is not an active integration claim');+ assert.match(resumed.out, new RegExp(`waiting on the person: #${personQuestionId} from coordinator`));+ assert.match(resumed.out, /review queue:/u);+ assert.match(resumed.out, new RegExp(`review queue:[\\s\\S]*?to verify: #${reviewId} web \\(`));+ assert.match(resumed.out, /4 stale follow-ups; list them with pullboard resume --json/u,+ 'the three stale row follow-ups and expired evidence collapse into one counted line');+ assert.equal((resumed.out.match(/^stale:/gmu) ?? []).length, 0, 'stale details collapse to one line');+ const positions = [+ resumed.out.indexOf(`open decision #${openId}`), resumed.out.indexOf('recent decision '),+ resumed.out.indexOf('verified, not merged — merges cleanly:'),+ resumed.out.indexOf('verified, not merged — conflicts:'),+ resumed.out.indexOf('verified, not merged — claimed for integration:'),+ resumed.out.indexOf('waiting on the person:'), resumed.out.indexOf('review queue:'),+ ];+ assert.ok(positions.every((position) => position >= 0) && positions.every((position, index) => index === 0 || positions[index - 1] < position),+ 'the handoff sections stay in the requested order');++ const json = box.run(box.repo, 'resume', '--json');+ assert.equal(json.code, 0, json.err || json.out);+ const document = JSON.parse(json.out);+ assert.equal(document.version, 1);+ assert.equal(document.openDecisions.length, 5);+ assert.equal(document.recentAnswers.length, 1);+ assert.equal(document.openDecisions[0].id, openId);+ assert.equal(document.openDecisions[0].asker, 'web-1');+ assert.equal(document.recentAnswers[0].answeredBy, 'person');+ assert.deepEqual(document.verifiedNotMerged.clean.map((item) => item.item_id).sort((a, b) => a - b),+ [cleanId, supersededId, plainId, factId, unrelatedId, expiredId].sort((a, b) => a - b));+ assert.deepEqual(document.verifiedNotMerged.conflicts[0].files, ['web/shared.txt']);+ assert.deepEqual(document.verifiedNotMerged.integrating.map((entry) => entry.item.item_id), [activeId],+ 'the >40 later plain shouts do not hide the structured descendant attempt');+ assert.equal(document.verifiedNotMerged.integrating[0].commit, descendant, 'the typed evidence keeps its full descendant SHA');+ assert.equal(document.personQuestions[0].id, personQuestionId);+ assert.equal(document.reviewQueue.items[0].item_id, reviewId);+ assert.equal(document.staleFollowUps.count, 4);+ assert.deepEqual(document.staleFollowUps.items.map((item) => item.id).sort((a, b) => a - b), [cleanId, conflictId, activeId]);+ assert.deepEqual(document.staleFollowUps.integrations.map((entry) => entry.item.item_id), [expiredId]);+ assert.equal(document.staleFollowUps.list, 'pullboard resume --json');++ const agentText = box.run(cleanBuilder, 'resume').out;+ assert.match(agentText, /^resume: web-1/u);+ assert.doesNotMatch(agentText, /open decision |recent decision |verified, not merged|waiting on the person|review queue:/u);+ const agentJson = JSON.parse(box.run(cleanBuilder, 'resume', '--json').out);+ for (const section of ['openDecisions', 'recentAnswers', 'verifiedNotMerged', 'personQuestions', 'reviewQueue', 'staleFollowUps']) {+ assert.equal(Object.hasOwn(agentJson, section), false, `agent resume keeps coordinator-only ${section} fields absent`);+ }+ });diff --cc test/e2e-cli.test.jsindex 00000000,1abf8e3c..4034489dmode 000000,100644..100644--- a/test/e2e-cli.test.js+++ b/test/e2e-cli.test.js@@@ -1,0 -1,399 +1,399 @@@+ /**+ * End to end on real repos: the CLI runs as its own process, git runs the installed hooks, and+ * worktrees are real worktrees (B1–B3, B6, V3, V4, V7, L3, L4, C3, I1, I2, P2).+ */+ import assert from 'node:assert/strict';+ import { runFixtureExecFile as execFileSync, startFixtureChild as spawn, runFixtureChild as spawnSync } from './fixture-child.js';+ import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+ } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { request } from 'node:http';+ import { connect } from 'node:net';+ import { join, resolve } from 'node:path';+ import { after, test } from 'node:test';+ import { parseSpec } from '../src/spec.js';+ import { checkAtCommit } from '../src/trusted-policy.js';+ import * as store from '../src/board.js';++ import { createE2eHelpers } from './e2e-helpers.js';+ import { fetchFresh } from './http-fixture.js';+ const e2e = createE2eHelpers();+ after(e2e.cleanup);+ const {+ BIN, cockpitSource, sandboxes, sandbox, CONFIG, SPEC, project, holdingGate,+ launch, waitFor, gateEvents, commitFile, attackCommit, privateCheckSubmission,+ startView, LIGHT_BRIEF,+ } = e2e;++ test('init adds a Claude Code session hook that runs resume, and keeps every other setting [I6]', () => {+ const box = sandbox();+ const repo = join(box.dir, 'repo');+ mkdirSync(join(repo, '.claude'), { recursive: true });+ box.git(repo, 'init', '-q', '-b', 'main');+ const mine = { permissions: { allow: ['Bash(npm test)'] }, hooks: { Stop: [{ hooks: [{ type: 'command', command: 'echo done' }] }] } };+ writeFileSync(join(repo, '.claude', 'settings.json'), JSON.stringify(mine));+ assert.match(box.run(repo, 'init').out, /added a Claude Code session hook/);+ assert.match(box.run(repo, 'init').out, /kept the Claude Code session hook/);+ const settings = JSON.parse(readFileSync(join(repo, '.claude', 'settings.json'), 'utf8'));+ assert.deepEqual(settings.permissions, mine.permissions);+ assert.deepEqual(settings.hooks.Stop, mine.hooks.Stop);+ assert.equal(settings.hooks.SessionStart.length, 1);+ const { command } = settings.hooks.SessionStart[0].hooks[0];+ const card = spawnSync('sh', ['-c', command], { cwd: repo, env: box.env, encoding: 'utf8' });+ assert.equal(card.status, 0, card.stderr);+ assert.match(card.stdout, /^resume: coordinator/);+ const bare = spawnSync('sh', ['-c', command], { cwd: repo, env: { ...box.env, PATH: '/usr/bin:/bin' }, encoding: 'utf8' });+ assert.equal(bare.status, 0, 'without pullboard installed, the session still starts');+ assert.equal(bare.stdout, '');+ });++ test('the tour runs a reject and its rework on a throwaway repo, in under thirty seconds [N10]', () => {+ const box = sandbox();+ const plainEnv = { ...box.env, TMPDIR: box.dir };+ delete plainEnv.NO_COLOR;+ delete plainEnv.FORCE_COLOR;+ const started = Date.now();+ const shown = spawnSync(process.execPath, [BIN, 'tour'], { cwd: box.dir, env: plainEnv, encoding: 'utf8' });+ assert.equal(shown.status, 0, `${shown.stdout}${shown.stderr}`);+ assert.ok(Date.now() - started < 30_000, 'thirty seconds');+ assert.doesNotMatch(shown.stdout, /\u001b\[/, 'piped output stays plain');- assert.match(shown.stdout, /review-1 \$ pullboard verify 1 reject --reason BEHAVIOR_MISMATCH/);- assert.match(shown.stdout, /sent back: #1 BEHAVIOR_MISMATCH by review-1: greet\(''\) returns "Hello, !"/);++ assert.match(shown.stdout, /review-1 \(Scripted\) \$ pullboard verify 1 reject --reason BEHAVIOR_MISMATCH/);++ assert.match(shown.stdout, /sent back: #1 BEHAVIOR_MISMATCH by review-1 \(Scripted\): greet\(''\) returns "Hello, !"/);+ assert.match(shown.stdout, /with the fix removed\n {7}# pass 1\n {7}# fail 1/);+ assert.match(shown.stdout, /verified #1: CRITERION_MET/);- assert.match(shown.stdout, /\| 1 \| app \| Greeting \| G1 \| app-1 \| review-1 \|/);++ assert.match(shown.stdout, /\| 1 \| app \| Greeting \| G1 \| app-1 \(Scripted\) \| review-1 \(Scripted\) \|/);++ const forced = spawnSync(process.execPath, [BIN, 'tour'], { cwd: box.dir, env: { ...plainEnv, FORCE_COLOR: '1' }, encoding: 'utf8' });+ assert.equal(forced.status, 0, `${forced.stdout}${forced.stderr}`);+ assert.match(forced.stdout, /\u001b\[1m1 The person approved one spec row\. The coordinator files it as work\.\u001b\[0m/);- assert.match(forced.stdout, /\u001b\[36mcoordinator\u001b\[0m \$/);- assert.match(forced.stdout, /\u001b\[33mapp-1\u001b\[0m \$/);- assert.match(forced.stdout, /\u001b\[35mreview-1\u001b\[0m \$/);++ assert.match(forced.stdout, /\u001b\[36mcoordinator \(unknown\)\u001b\[0m \$/);++ assert.match(forced.stdout, /\u001b\[33mapp-1 \(Scripted\)\u001b\[0m \$/);++ assert.match(forced.stdout, /\u001b\[35mreview-1 \(Scripted\)\u001b\[0m \$/);+ assert.match(forced.stdout, /\u001b\[31m[^\n]*rejected #1/);+ assert.match(forced.stdout, /\u001b\[31m[^\n]*# fail 1/);+ assert.match(forced.stdout, /\u001b\[32m[^\n]*verified #1: CRITERION_MET/);+ assert.match(forced.stdout, /\u001b\[32m[^\n]*# pass 2/);++ const noColor = spawnSync(process.execPath, [BIN, 'tour'], { cwd: box.dir, env: { ...plainEnv, FORCE_COLOR: '1', NO_COLOR: '1' }, encoding: 'utf8' });+ assert.equal(noColor.status, 0, `${noColor.stdout}${noColor.stderr}`);+ assert.doesNotMatch(noColor.stdout, /\u001b\[/, 'NO_COLOR wins even if the environment could otherwise force color');+ const normalizeTourRoot = (text) => text+ .replace(/Look around: cd .* && pullboard log/, 'Look around: cd <tour> && pullboard log')+ .replace(/\b[0-9a-f]{12}\b/g, '<sha>')+ .replace(/claimed #1 until \S+ criterion frozen/g, 'claimed #1 until <time> criterion frozen')+ // A gate's rounded wall time is not output NO_COLOR could change, so a slower gate must still compare equal.+ .replace(/gate (green|red) in \d+s/g, 'gate $1 in <n>s');+ assert.equal(normalizeTourRoot(noColor.stdout), normalizeTourRoot(shown.stdout), 'NO_COLOR preserves the plain tour output');++ const repo = /Look around: cd (\S+) && pullboard log/.exec(shown.stdout)[1];+ assert.match(box.git(repo, 'log', '--format=%an %s', '-1'), /^app-1 fix\(app\): a blank name greets the world \[G1\]$/);+ const hooks = join(box.dir, 'ambient-hooks');+ mkdirSync(hooks);+ writeFileSync(join(hooks, 'pre-commit'), '#!/bin/sh\necho ambient hook ran >&2\nexit 1\n');+ chmodSync(join(hooks, 'pre-commit'), 0o755);+ const ambient = { ...plainEnv, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'core.hooksPath', GIT_CONFIG_VALUE_0: hooks, GIT_DIR: join(box.dir, 'elsewhere.git') };+ const isolated = spawnSync(process.execPath, [BIN, 'tour'], { cwd: box.dir, env: ambient, encoding: 'utf8' });+ assert.equal(isolated.status, 0, `git settings from the environment stay out: ${isolated.stdout}`);+ const empty = join(box.dir, 'empty');+ mkdirSync(empty);+ const stopped = spawnSync(process.execPath, [BIN, 'tour'], { cwd: box.dir, env: { ...plainEnv, PATH: empty }, encoding: 'utf8' });+ assert.equal(stopped.status, 1);+ assert.match(stopped.stdout, /The tour stopped: git init -q -b main exited null/);+ });++ test('the tour registers a labelled demo that view lists and forget removes [N10, N26]', async () => {+ const box = project();+ const tourEnv = { ...box.env, TMPDIR: box.dir, HOME: box.dir };+ delete tourEnv.PULLBOARD_MODEL;+ const result = spawnSync(process.execPath, [BIN, 'tour'], {+ cwd: box.dir,+ env: tourEnv,+ encoding: 'utf8',+ });+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);+ assert.equal(result.stdout.trimEnd().split('\n').at(-1), 'see it: pullboard view');+ const demoRoot = /Look around: cd (\S+) && pullboard log/.exec(result.stdout)?.[1];+ assert.ok(demoRoot, 'the retained demo path is printed');+ const registered = JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, 'projects.json'), 'utf8')).projects;+ assert.deepEqual(registered.map(({ root, name }) => [root, name]), [[box.repo, 'repo'], [demoRoot, 'demo']]);++ const view = await startView(box, box.repo);+ try {+ const listing = await fetchFresh(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': view.key } });+ assert.equal(listing.status, 200);+ assert.deepEqual((await listing.json()).boards.map(({ root, name }) => [root, name]), [[box.repo, 'repo'], [demoRoot, 'demo']]);+ const forgotten = box.run(box.dir, 'forget', demoRoot);+ assert.equal(forgotten.code, 0, forgotten.err);+ assert.match(forgotten.out, /forgot/);+ const after = await fetchFresh(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': view.key } });+ assert.deepEqual((await after.json()).boards.map(({ root, name }) => [root, name]), [[box.repo, 'repo']]);+ } finally {+ await view.stop();+ }+ });++ test('the run pack names verified items that touched the same files, so a cold agent follows them [N21]', () => {+ const box = project();+ const script = (name, lines) => {+ writeFileSync(join(box.dir, name), ['#!/bin/sh', 'mkdir -p web', ...lines, ''].join('\n'));+ return `sh ${join(box.dir, name)}`;+ };+ const greet = script('greet.sh', ["echo \"export const title = 'Hi';\" > web/page.js"]);+ const follow = script('follow.sh', ['grep -q "^- #1 Greet: web/page.js$" "$PULLBOARD_PACK" && echo "export const bye = \'Bye\';" >> web/page.js']);+ box.run(box.repo, 'add', 'web', 'Greet', '--route', 'light', '--criterion', 'says Hi', '--check', 'grep -q Hi web/page.js', '--brief', LIGHT_BRIEF);+ const runner = box.run(box.repo, 'worktree', 'web', '--route', 'light').out.match(/^made (\S+) /)[1];+ assert.match(box.run(runner, 'run', '--agent-light', greet, '--attempts', '1').out, /submitted #1/);+ box.git(box.web, 'merge', '-q', '--ff-only', JSON.parse(box.run(box.repo, 'show', '1', '--json').out).item_commit);+ assert.match(box.run(box.web, 'verify', '1', 'accept', '--note', 'emptied the page; the check failed').out, /verified #1/);+ box.run(box.repo, 'add', 'web', 'Say', 'bye', '--route', 'light', '--criterion', 'says Bye', '--check', 'grep -q Bye web/page.js', '--brief', LIGHT_BRIEF);+ const ran = box.run(runner, 'run', '--agent-light', follow, '--attempts', '1');+ assert.match(ran.out, /submitted #2/, ran.out);+ const packs = join(box.dir, 'repo', '.git', 'worktrees', runner.split('/').at(-1), 'pullboard', 'packs');+ assert.match(readFileSync(join(packs, '2-light-1.md'), 'utf8'), /## Finished items that touched the same files\n- #1 Greet: web\/page.js\nFollow the patterns/);+ });++ test('a fresh worktree with no install of its own runs pullboard from the main checkout, for git hooks and the session hook [I6]', () => {+ const box = project();+ const bare = { ...box.env, PATH: '/usr/bin:/bin' };+ const commit = () => spawnSync('git', ['commit', '-q', '-m', 'feat(web): page [G1]'], { cwd: box.web, env: bare, encoding: 'utf8' });+ const { command } = JSON.parse(readFileSync(join(box.web, '.claude', 'settings.json'), 'utf8')).hooks.SessionStart[0].hooks[0];+ const resume = () => spawnSync('sh', ['-c', command], { cwd: box.web, env: bare, encoding: 'utf8' });+ mkdirSync(join(box.web, 'web'));+ writeFileSync(join(box.web, 'web', 'page.html'), '<h1>Hi</h1>');+ box.git(box.web, 'add', '-A');+ const refused = commit();+ assert.notEqual(refused.status, 0);+ assert.match(refused.stderr, /pullboard is not installed/);+ assert.deepEqual([resume().status, resume().stdout], [0, ''], 'no install anywhere: the session still starts, silently');+ const bin = join(box.repo, 'node_modules', '.bin');+ mkdirSync(bin, { recursive: true });+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "${BIN}" "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const committed = commit();+ assert.equal(committed.status, 0, committed.stderr);- assert.match(resume().stdout, /^resume: web-1, web lane/);++ assert.match(resume().stdout, /^resume: web-1 \(Test Model\), web lane/);+ });++ test('the gate reaches the agent as a digest: one line when green, the failure when red; the whole output stays in the git dir [V10]', () => {+ const box = project();+ writeFileSync(join(box.repo, 'gate.cjs'), [+ "const red = require('node:fs').existsSync('RED');",+ "const { writeSync } = require('node:fs');",+ "for (let i = 0; i < 400; i++) writeSync(1, `ok ${i} ${'x'.repeat(red ? 10 : 3000)}\\n`);",+ "if (red) { writeSync(2, 'not ok 401 - the page renders a heading\\n'); for (let i = 0; i < 100; i++) writeSync(1, `# note ${i}\\n`); process.exitCode = 1; }",+ '',+ ].join('\n'));+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: 'node gate.cjs # prints a lot' }));+ box.git(box.repo, 'add', '-A');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: a noisy gate');+ const log = join(box.repo, box.git(box.repo, 'rev-parse', '--git-path', 'pullboard-gate.log'));+ const green = box.run(box.repo, 'gate');+ assert.equal(green.code, 0, green.err);+ assert.match(green.out, /^gate green in \d+s\n$/);+ assert.ok(readFileSync(log, 'utf8').length > 1_200_000, 'more than the default 1 MB pipe buffer, read whole');+ writeFileSync(join(box.repo, 'RED'), 'red');+ box.git(box.repo, 'add', 'RED');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: turn the gate red');+ const red = box.run(box.repo, 'gate');+ assert.equal(red.code, 1);+ assert.match(red.out, /^gate red in \d+s:\n {2}not ok 401 - the page renders a heading\n/);+ assert.match(red.out, / {2}# note 99\nthe whole output is in /);+ assert.ok(red.out.length < 4000, `${red.out.length} characters`);+ const lines = readFileSync(log, 'utf8').split('\n');+ assert.equal(lines.length, 502);+ assert.equal(lines[400], 'not ok 401 - the page renders a heading', 'stdout and stderr in one stream, in order');+ box.run(box.repo, 'add', 'coordinator', 'Coordinator work');+ box.run(box.repo, 'claim', '1');+ assert.match(box.run(box.repo, 'submit', '1').err, /GATE_RED[\s\S]*not ok 401 - the page renders a heading/);+ });++ test('submit refuses a bar that moved since the claim, before any verifier runs; a refreeze and a fresh claim recover [V11]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1', '--criterion', 'renders');+ box.run(box.web, 'claim', '1');+ writeFileSync(join(box.repo, 'SPEC.md'), SPEC.replace('The page renders.', 'The page renders a heading.'));+ assert.equal(box.run(box.repo, 'spec', 'approve', 'G1').code, 0);+ box.git(box.repo, 'commit', '-qam', 'docs: tighten G1');+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ commitFile(box, box.web, 'web/a.html', '<h1>Hi</h1>', 'feat(web): page [G1]');+ const refused = box.run(box.web, 'submit', '1');+ assert.equal(refused.code, 1);+ assert.match(refused.err, /CRITERIA_CHANGED\] the spec rows #1 cites changed after it was claimed, so no verifier could judge it; the coordinator runs pullboard refreeze 1, then you claim it and submit again/);+ assert.equal(JSON.parse(box.run(box.repo, 'show', '1', '--json').out).item_status, 'claimed');+ assert.match(box.run(box.repo, 'refreeze', '1').out, /refrozen/);+ box.run(box.web, 'claim', '1');+ assert.match(box.run(box.web, 'submit', '1').out, /submitted #1/);+ });++ test('spec check at an older commit skips ids that items cite from a later commit; a never-committed id still fails [S10]', () => {+ const box = project();+ writeFileSync(join(box.repo, 'SPEC.md'), `${SPEC}- G3 [draft, must] The page has a footer.\n`);+ box.git(box.repo, 'commit', '-qam', 'docs(spec): a footer row');+ box.run(box.repo, 'add', 'web', 'Footer', '--specs', 'G3');+ const older = box.run(box.web, 'spec', 'check');+ assert.equal(older.code, 0, older.out);+ writeFileSync(join(box.repo, 'SPEC.md'), `${SPEC}- G3 [draft, must] The page has a footer.\n- G4 [draft, must] Not committed.\n`);+ box.run(box.repo, 'add', 'web', 'Ghost', '--specs', 'G4');+ const ghost = box.run(box.web, 'spec', 'check');+ assert.equal(ghost.code, 1);+ assert.match(ghost.out, /SPEC.md: G4 error: item #2 cites it, but it was never committed/);+ assert.doesNotMatch(ghost.out, /G3 error/);+ });++ test('check runs the item\'s own check command, yours by default, and prints a digest [N23]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1', '--check', 'test -f web/a.html || { echo "not ok 1 - web/a.html is missing"; exit 1; }');+ box.run(box.repo, 'add', 'web', 'Loose', '--specs', 'G1');+ assert.match(box.run(box.web, 'check').err, /NOT_HOLDING.*pullboard gate/);+ box.run(box.web, 'claim', '1');+ const red = box.run(box.web, 'check', '--yes');+ assert.equal(red.code, 1);+ assert.match(red.out, /^check red in \d+s: test -f web\/a.html/m);+ assert.match(red.out, /\n {2}not ok 1 - web\/a.html is missing\n/);+ mkdirSync(join(box.web, 'web'));+ writeFileSync(join(box.web, 'web', 'a.html'), '<h1>Hi</h1>');+ const green = box.run(box.web, 'check', '--yes');+ assert.equal(green.code, 0, green.out);+ assert.match(green.out, /^check green in \d+s: test -f web\/a.html/m);+ assert.equal(green.out.split('\n').filter(Boolean).length, 2);- assert.match(green.out, /^check #1 set by coordinator:/);++ assert.match(green.out, /^check #1 set by coordinator \(unknown\):/);+ assert.equal(box.run(box.repo, 'check', '1').code, 1, 'named, from another checkout: there the file is missing');+ assert.match(box.run(box.web, 'check', '2').err, /NO_CHECK.*#2 has no check command/);+ assert.match(box.run(box.repo, 'help', '--all').out, /pullboard check \[id\]/);+ });++ test('submit leaves a dependency fast-forwarded in out of the files it records [N21]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Dependency', '--specs', 'G1');+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1', '--after', '1');+ const second = box.run(box.repo, 'worktree', 'web').out.match(/^made (\S+) /)[1];+ box.run(box.web, 'claim', '1');+ commitFile(box, box.web, 'web/dep.html', 'dep', 'feat(web): the dependency [G1]');+ assert.equal(box.run(box.web, 'submit', '1').code, 0);+ box.git(box.repo, 'switch', '-q', '--detach', 'web/one');+ assert.match(box.run(box.repo, 'verify', '1', 'accept', '--as', 'coordinator', '--note', 'removed dep.html; the page broke').out, /verified #1/);+ box.git(box.repo, 'switch', '-q', 'main');+ box.run(second, 'claim', '2');+ box.git(second, 'merge', '-q', '--ff-only', 'web/one');+ commitFile(box, second, 'web/page.html', 'page', 'feat(web): the page [G1]');+ assert.equal(box.run(second, 'submit', '2').code, 0);+ assert.equal(JSON.parse(box.run(box.repo, 'show', '2', '--json').out).item_files, 'web/page.html');+ });++ test('verify and escalate take a note from a file, exactly as written [V12]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1');+ box.run(box.web, 'claim', '1');+ commitFile(box, box.web, 'web/a.html', 'a', 'feat(web): page [G1]');+ box.run(box.web, 'submit', '1');+ const note = 'ran `npm test` with $HOME unset: "it failed"\nthen restored it';+ writeFileSync(join(box.dir, 'note.txt'), `${note}\n`);+ box.git(box.repo, 'switch', '-q', '--detach', 'web/one');+ assert.match(box.run(box.repo, 'verify', '1', 'reject', '--reason', 'TEST_FAILURE', '--note', 'x', '--note-file', join(box.dir, 'note.txt'), '--as', 'coordinator').err, /USAGE\] give the note once/);+ assert.match(box.run(box.repo, 'verify', '1', 'reject', '--reason', 'TEST_FAILURE', '--note-file', join(box.dir, 'nope.txt'), '--as', 'coordinator').err, /NO_FILE/);+ assert.match(box.run(box.repo, 'verify', '1', 'reject', '--reason', 'TEST_FAILURE', '--note-file', join(box.dir, 'note.txt'), '--as', 'coordinator').out, /rejected #1/);+ assert.equal(JSON.parse(box.run(box.repo, 'show', '1', '--json').out).verdicts[0].verdict_note, note);+ box.git(box.repo, 'switch', '-q', 'main');+ box.run(box.repo, 'add', 'web', 'Light', '--route', 'light', '--criterion', 'says hi', '--check', 'true', '--brief', LIGHT_BRIEF);+ const light = box.run(box.repo, 'worktree', 'web', '--route', 'light').out.match(/^made (\S+) /)[1];+ box.run(light, 'claim', '2');+ assert.match(box.run(light, 'escalate', '2', '--note-file', join(box.dir, 'note.txt')).out, /#2 escalated light -> mid/);+ assert.match(box.run(box.repo, 'show', '2').out, /ran `npm test` with \$HOME unset: "it failed"/);+ assert.match(box.run(box.repo, 'help', '--all').out, /--note-file <file>/);+ });++ test('the help keeps every command description apart from its usage [N37]', () => {+ const box = sandbox();+ const help = box.run(box.dir, 'help', '--all').out;+ const commandLines = help.split('\n').filter((line) => line.startsWith(' pullboard '));+ for (const line of commandLines) {+ const hasDescriptionGap = / {2,}\S/.test(line.slice(' pullboard '.length));+ const usageOnly = /(?:<[^<>]+>|\[[^\[\]]+\]|"[^"]*")$/.test(line);+ assert.ok(hasDescriptionGap || usageOnly, `command usage runs into its description: ${line}`);+ }+ const lines = help.split('\n');+ const answerLine = lines.findIndex((line) => line.startsWith(' pullboard answer '));+ const answerDescription = lines[answerLine + 1];+ assert.ok(+ answerLine >= 0 && answerDescription?.startsWith(`${' '.repeat(40)}answer your decision;`),+ 'the answer description follows its usage at the description column',+ );+ });++ test('output into a reader that stops early ends quietly [N24]', async () => {+ const box = project();+ for (let n = 0; n < 40; n++) box.run(box.repo, 'add', 'web', `Item ${n}`, '--specs', 'G1');+ const child = spawn(process.execPath, [BIN, 'list', '--all'], { cwd: box.repo, env: box.env });+ child.stdout.destroy();+ let stderr = '';+ child.stderr.on('data', (chunk) => { stderr += chunk; });+ const code = await new Promise((done) => child.on('close', done));+ assert.equal(stderr, '');+ assert.equal(code, 0);+ });++ test('every wait pullboard suggests names its unit and fits one ten-minute tool call [N25]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1');+ box.run(box.repo, 'add', 'web', 'Second', '--specs', 'G1', '--after', '1');+ box.run(box.web, 'claim', '1');+ commitFile(box, box.web, 'web/a.html', 'a', 'feat(web): page [G1]');+ box.run(box.web, 'submit', '1');+ assert.match(box.run(box.web, 'next').err, /To keep looking: pullboard next --wait 9 \(minutes; give the command a ten-minute timeout\)/);+ assert.match(box.run(box.web, 'resume').out, /next: pullboard next --wait 9 \(minutes\); 1 in your lane waits on other work/);+ box.run(box.repo, 'hold', 'web', '--reason', 'G1 is changing');+ assert.match(box.run(box.web, 'resume').out, /next: wait for the hold to lift: pullboard next --wait 9 \(minutes\)/);+ const agents = readFileSync(join(box.repo, 'AGENTS.md'), 'utf8');+ assert.match(agents, /`pullboard next --wait 9` keeps looking for up to 9 minutes, which fits one tool call with a ten-minute timeout/);+ assert.doesNotMatch(agents, /--wait 30/);+ });++ test('submit names the item and the way out when a cited row was retired after the claim [V11]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1');+ box.run(box.web, 'claim', '1');+ writeFileSync(join(box.repo, 'SPEC.md'), SPEC.replace('- G1 [approved, must] The page renders. | gate: web test', '- G1 [retired] The page renders.'));+ box.git(box.repo, 'commit', '-qam', 'docs(spec): retire G1');+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ commitFile(box, box.web, 'web/a.html', 'a', 'feat(web): page');+ const refused = box.run(box.web, 'submit', '1');+ assert.equal(refused.code, 1);+ assert.match(refused.err, /CRITERIA_CHANGED\] the spec rows #1 cites changed after it was claimed \(G1 is retired\), so no verifier could judge it; the coordinator either restores the row and runs pullboard refreeze 1, or withdraws #1/);+ assert.equal(JSON.parse(box.run(box.repo, 'show', '1', '--json').out).item_status, 'claimed');+ });++ test('worktree prints the opening lines of a subagent\'s prompt, with its folder and identity [I7]', () => {+ const box = sandbox();+ const repo = join(box.dir, "my app's $PULLBOARD_PATH_PROBE");+ mkdirSync(repo);+ box.git(repo, 'init', '-q', '-b', 'main');+ box.run(repo, 'init');+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify(CONFIG, null, 2));+ writeFileSync(join(repo, 'SPEC.md'), SPEC);+ box.git(repo, 'add', '-A');+ box.git(repo, 'commit', '-q', '-m', 'chore: set up pullboard');+ const made = box.run(repo, 'worktree', 'web').out;+ const folder = join(box.dir, "my app's $PULLBOARD_PATH_PROBE-web-1");+ const quoted = `'${folder.replaceAll("'", "'\\''")}'`;+ assert.match(made, /For a subagent working here, begin its prompt with:\n/);- assert.ok(made.includes(` You are web-1, in the web lane. Work only in ${quoted}, and start every command with cd ${quoted} &&\n`), made);++ assert.ok(made.includes(` You are web-1 (Test Model), in the web lane. Work only in ${quoted}, and start every command with cd ${quoted} &&\n`), made);+ assert.ok(made.includes(` Read '${folder.replaceAll("'", "'\\''")}/AGENTS.md' first. Its rules govern this work, over any other repo's instructions you were given.\n`), made);+ // Pasted into a shell as printed, the line enters the real folder: nothing in the path expands.+ const cdLine = /start every command with (cd .+ &&)\n/.exec(made)[1];+ const entered = spawnSync('sh', ['-c', `${cdLine} pwd`], { env: { ...box.env, PULLBOARD_PATH_PROBE: 'elsewhere' }, encoding: 'utf8' });+ assert.equal(entered.stdout.trim(), folder);+ });++ /**+ * Start `pullboard view` in a folder and read the link it prints; stop() ends it.+ */diff --cc test/e2e-model-names.test.jsindex 00000000,00000000..5c5c042dnew file mode 100644--- /dev/null+++ b/test/e2e-model-names.test.js@@@ -1,0 -1,0 +1,191 @@@++/** CLI model labels, stable agent identities, and model-free scripted tours [O8,O3,N10]. */++import assert from 'node:assert/strict';++import { spawnSync } from 'node:child_process';++import { existsSync, readFileSync, writeFileSync } from 'node:fs';++import { join } from 'node:path';++import { after, test } from 'node:test';++import * as store from '../src/board.js';++import { createE2eHelpers } from './e2e-helpers.js';++import { runFixtureChild } from './fixture-child.js';++++const e2e = createE2eHelpers();++after(e2e.cleanup);++const { BIN, sandbox, project } = e2e;++++test('model names label CLI actors without changing IDs, messages, or the context prompt [O8,O3]', () => {++ for (const style of ['suffix', 'prefix']) {++ const box = sandbox();++ box.env.PULLBOARD_MODEL = 'Test Model';++ const repo = project('true', box);++ const legacyJoin = box.run(repo.web, 'whoami', '--json');++ assert.equal(legacyJoin.code, 0, legacyJoin.err || legacyJoin.out);++ assert.equal(JSON.parse(legacyJoin.out).model, 'Test Model', 'the model environment identifies the initial join');++++ delete box.env.PULLBOARD_MODEL;++ const missingWorktree = box.run(repo.repo, 'worktree', 'api', '--json');++ assert.equal(missingWorktree.code, 1);++ assert.equal(JSON.parse(missingWorktree.out).error.code, 'MODEL_REQUIRED');++ assert.equal(existsSync(join(box.dir, 'repo-api-1')), false, 'a refused worktree leaves no folder');++++ const unjoined = join(box.dir, 'unjoined-web');++ box.git(repo.repo, 'worktree', 'add', '-q', '-b', 'web/unjoined', unjoined);++ const missingJoin = box.run(unjoined, 'join', 'web', '--json');++ assert.equal(missingJoin.code, 1);++ assert.equal(JSON.parse(missingJoin.out).error.code, 'MODEL_REQUIRED');++++ const configFile = join(repo.repo, 'pullboard.json');++ const config = JSON.parse(readFileSync(configFile, 'utf8'));++ config.agents = { names: style };++ writeFileSync(configFile, `${JSON.stringify(config, null, 2)}\n`);++ box.git(repo.repo, 'add', 'pullboard.json');++ box.git(repo.repo, 'commit', '-q', '-m', 'chore(repo): choose agent names [G1]');++ box.git(repo.web, 'merge', '-q', '--ff-only', 'main');++++ const joined = box.run(repo.web, 'join', 'web', '--model', 'Claude', '--json');++ assert.equal(joined.code, 0, joined.err || joined.out);++ assert.equal(JSON.parse(joined.out).agent, 'web-1');++ const made = box.run(repo.repo, 'worktree', 'web', '--model', 'GPT 6', '--json');++ assert.equal(made.code, 0, made.err || made.out);++ const second = JSON.parse(made.out);++ assert.equal(second.agent, 'web-2');++++ const builderName = style === 'suffix' ? 'web-1 (Claude)' : 'claude-web-1';++ const otherName = style === 'suffix' ? 'web-2 (GPT 6)' : 'gpt-6-web-2';++ const coordinatorName = style === 'suffix' ? 'coordinator (unknown)' : 'unknown-coordinator';++ assert.ok(second.prompt.includes(`You are ${otherName}, in the web lane.`), second.prompt);++ assert.ok(second.prompt.includes("Model: 'GPT 6'. This worktree joined with --model 'GPT 6'."), second.prompt);++ assert.ok(second.prompt.includes("pass --model 'GPT 6' or set PULLBOARD_MODEL='GPT 6'"), second.prompt);++++ const wrongLane = box.run(repo.web, 'join', 'api', '--model', 'Claude');++ assert.equal(wrongLane.code, 1);++ assert.ok(wrongLane.err.includes(`this worktree is ${builderName} in the web lane`), wrongLane.err);++++ const selfShout = box.run(repo.web, 'shout', 'web-1', 'Keep web-1 literal');++ assert.equal(selfShout.code, 1);++ assert.ok(selfShout.err.includes(`sender ${builderName};`), selfShout.err);++ const missingReader = box.run(repo.web, 'shout', 'web-99', 'Keep web-1 literal');++ assert.equal(missingReader.code, 1);++ assert.ok(missingReader.err.includes(style === 'suffix' ? '"web-99 (unknown)"' : '"unknown-web-99"'), missingReader.err);++++ const added = box.run(repo.repo, 'add', 'web', 'Model receipt', '--specs', 'G1', '--check', 'true', '--json');++ assert.equal(added.code, 0, added.err || added.out);++ const id = JSON.parse(added.out).item.item_id;++ const claimed = box.run(repo.web, 'claim', String(id));++ assert.equal(claimed.code, 0, claimed.err || claimed.out);++ const held = box.run(second.path, 'claim', String(id));++ assert.equal(held.code, 1);++ assert.ok(held.err.includes(`held by ${builderName} until`), held.err);++ const structuredHeld = box.run(second.path, 'claim', String(id), '--json');++ assert.equal(JSON.parse(structuredHeld.out).error.code, 'HELD');++ assert.match(JSON.parse(structuredHeld.out).error.message, /held by web-1 until/);++++ const check = box.run(repo.repo, 'check', String(id), '--yes', '--json');++ assert.equal(check.code, 0, check.err || check.out);++ assert.equal(JSON.parse(check.out).by, 'coordinator', 'the structured receipt keeps the stable actor ID');++ assert.ok(check.err.includes(`set by ${coordinatorName}: true`), check.err);++ const declinedCheck = spawnSync(process.execPath, [BIN, 'check', String(id)], {++ cwd: second.path, env: box.env, encoding: 'utf8', input: 'n\n',++ });++ assert.equal(declinedCheck.status, 1);++ assert.ok(declinedCheck.stderr.includes(`the check set by ${coordinatorName} was not run`), declinedCheck.stderr);++++ const asked = box.run(repo.repo, 'shout', 'web-1', 'Keep web-1 literal', '--decision', '--json');++ assert.equal(asked.code, 0, asked.err || asked.out);++ const ask = JSON.parse(asked.out).id;++ const wrongAnswer = box.run(second.path, 'answer', String(ask), 'wrong agent');++ assert.equal(wrongAnswer.code, 1);++ assert.ok(wrongAnswer.err.includes(`addressed to ${builderName}, not your web lane (agent ${otherName})`), wrongAnswer.err);++++ assert.equal(box.run(repo.repo, 'hold', 'web', '--reason', 'Keep web-1 literal in the reason').code, 0);++ const waiting = box.run(second.path, 'next', '--build');++ assert.equal(waiting.code, 1);++ assert.ok(waiting.err.includes(`${coordinatorName} holds the web lane: Keep web-1 literal in the reason`), waiting.err);++ assert.equal(box.run(repo.repo, 'hold', 'web', '--off').code, 0);++++ const identity = box.run(repo.web, 'whoami', '--json');++ assert.equal(identity.code, 0, identity.err || identity.out);++ assert.equal(JSON.parse(identity.out).id, 'web-1');++ assert.equal(JSON.parse(identity.out).displayName, builderName);++ const log = box.run(repo.repo, 'log', '--json');++ assert.equal(log.code, 0, log.err || log.out);++ const claim = JSON.parse(log.out).events.find((event) => event.event_kind === 'claim' && event.item_id === id);++ assert.equal(claim.event_by, 'web-1', 'event attribution stays the stable agent ID');++ assert.equal(JSON.parse(claim.event_detail).model, 'Claude');++++ const statsText = box.run(repo.web, 'stats');++ assert.equal(statsText.code, 0, statsText.err || statsText.out);++ assert.ok(statsText.out.includes(`${builderName} (`), statsText.out);++ const statsJson = box.run(repo.web, 'stats', '--json');++ assert.ok(JSON.parse(statsJson.out).stats.agents.some((agent) => agent.id === 'web-1'));++ const takeover = runFixtureChild(process.execPath, [BIN, 'takeover'], {++ cwd: second.path, env: { ...box.env, CODEX_THREAD_ID: 'model-label-takeover-fixture' }, encoding: 'utf8',++ });++ assert.equal(takeover.status, 0, `${takeover.stdout}${takeover.stderr}`);++ assert.ok(takeover.stdout.includes(`${otherName} took over`), takeover.stdout);++ const displaced = runFixtureChild(process.execPath, [BIN, 'shout', 'coordinator', 'Refused session'], {++ cwd: second.path, env: { ...box.env, CODEX_THREAD_ID: 'different-model-session-fixture' }, encoding: 'utf8',++ });++ assert.equal(displaced.status, 1);++ assert.ok(displaced.stderr.includes(`belongs to ${otherName} in another agent session`), displaced.stderr);++ const judgement = box.run(second.path, 'fact', String(id), 'decision', 'Wrong actor judgement');++ assert.equal(judgement.code, 1);++ assert.ok(judgement.err.includes(`live holder (${builderName})`), judgement.err);++ const thread = box.run(repo.web, 'show', String(id));++ assert.equal(thread.code, 0, thread.err || thread.out);++ assert.ok(thread.out.includes(` ${builderName} claim`), thread.out);++ const decision = box.run(repo.web, 'shout', 'coordinator', 'Keep web-1 literal in question', '--decision');++ assert.equal(decision.code, 0, decision.err || decision.out);++ const resume = box.run(repo.repo, 'resume');++ assert.equal(resume.code, 0, resume.err || resume.out);++ assert.ok(resume.out.includes(`from ${builderName} (`), resume.out);++ assert.ok(resume.out.includes('Keep web-1 literal in question'), resume.out);++++ assert.equal(box.run(repo.web, 'release', String(id)).code, 0);++ assert.equal(box.run(repo.repo, 'hold', String(id), 'Keep web-1 literal in item reason').code, 0);++ for (const command of [['list', 'web'], ['show', String(id)]]) {++ const heldText = box.run(repo.web, ...command);++ assert.equal(heldText.code, 0, heldText.err || heldText.out);++ assert.ok(heldText.out.includes(`held by ${coordinatorName}: Keep web-1 literal in item reason`), heldText.out);++ }++ const itemClaim = box.run(second.path, 'claim', String(id));++ assert.equal(itemClaim.code, 1);++ assert.ok(itemClaim.err.includes(`held by ${coordinatorName}: Keep web-1 literal in item reason`), itemClaim.err);++ const noFree = box.run(second.path, 'next', '--build');++ assert.equal(noFree.code, 1);++ assert.ok(noFree.err.includes(`#${id} is held by ${coordinatorName}: Keep web-1 literal in item reason`), noFree.err);++ const noFreeJson = box.run(second.path, 'next', '--build', '--json');++ assert.ok(JSON.parse(noFreeJson.out).error.message.includes(`#${id} is held by coordinator: Keep web-1 literal in item reason`));++ const available = box.run(repo.repo, 'add', 'web', 'Other model receipt', '--specs', 'G1', '--json');++ assert.equal(available.code, 0, available.err || available.out);++ const selected = box.run(second.path, 'next', '--build');++ assert.equal(selected.code, 0, selected.err || selected.out);++ assert.ok(selected.out.includes(`#${id} is held by ${coordinatorName}: Keep web-1 literal in item reason`), selected.out);++ const freeId = JSON.parse(available.out).item.item_id;++ assert.equal(box.run(second.path, 'release', String(freeId)).code, 0);++ const selectedJson = box.run(second.path, 'next', '--build', '--json');++ assert.ok(JSON.parse(selectedJson.out).reasons.includes(`#${id} is held by coordinator: Keep web-1 literal in item reason`));++++ const board = store.openBoard(join(repo.repo, '.git', 'pullboard', 'board.sqlite'));++ try { board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run('agent_model:web-2'); }++ finally { store.closeBoard(board); }++ const legacy = box.run(second.path, 'whoami', '--json');++ assert.equal(legacy.code, 0, legacy.err || legacy.out);++ assert.equal(JSON.parse(legacy.out).id, 'web-2');++ assert.equal(JSON.parse(legacy.out).displayName, style === 'suffix' ? 'web-2 (unknown)' : 'unknown-web-2');++ }++});++++test('the scripted tour names its model without PULLBOARD_MODEL [N10,O8]', () => {++ const box = sandbox();++ const env = { ...box.env, TMPDIR: box.dir };++ delete env.PULLBOARD_MODEL;++ delete env.NO_COLOR;++ delete env.FORCE_COLOR;++ const startedAt = Date.now();++ const result = runFixtureChild(process.execPath, [BIN, 'tour'], { cwd: box.dir, env, encoding: 'utf8' });++ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);++ assert.ok(Date.now() - startedAt < 30_000, 'the tour remains a short scripted example');++ assert.match(result.stdout, /app-1 \(Scripted\) \$ pullboard next/);++ assert.match(result.stdout, /sent back: #1 BEHAVIOR_MISMATCH by review-1 \(Scripted\):/);++ assert.match(result.stdout, /\| 1 \| app \| Greeting \| G1 \| app-1 \(Scripted\) \| review-1 \(Scripted\) \|/);++});diff --cc test/e2e-runner.test.jsindex 00000000,3d8a67ee..6f5409d3mode 000000,100644..100644--- a/test/e2e-runner.test.js+++ b/test/e2e-runner.test.js@@@ -1,0 -1,301 +1,301 @@@+ /**+ * End to end on real repos: the CLI runs as its own process, git runs the installed hooks, and+ * worktrees are real worktrees (B1–B3, B6, V3, V4, V7, L3, L4, C3, I1, I2, P2).+ */+ import assert from 'node:assert/strict';+ import { runFixtureExecFile as execFileSync, startFixtureChild as spawn, runFixtureChild as spawnSync } from './fixture-child.js';+ import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+ } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { request } from 'node:http';+ import { connect } from 'node:net';+ import { join, resolve } from 'node:path';+ import { after, test } from 'node:test';+ import { parseSpec } from '../src/spec.js';+ import { checkAtCommit } from '../src/trusted-policy.js';+ import * as store from '../src/board.js';++ import { createE2eHelpers } from './e2e-helpers.js';+ const e2e = createE2eHelpers();+ after(e2e.cleanup);+ const {+ BIN, cockpitSource, sandboxes, sandbox, CONFIG, SPEC, project, holdingGate,+ launch, waitFor, gateEvents, commitFile, attackCommit, privateCheckSubmission,+ startView, LIGHT_BRIEF,+ } = e2e;++ test('an item carries a brief to whoever claims it; a light agent sees only its tier [B10, B13, B14]', () => {+ const box = project();+ writeFileSync(join(box.dir, 'brief.md'), LIGHT_BRIEF);+ assert.equal(box.run(box.repo, 'add', 'web', 'Design', 'the', 'page', '--specs', 'G1').code, 0);+ assert.match(box.run(box.repo, 'add', 'web', 'Copy', '--route', 'light', '--brief-file', join(box.dir, 'brief.md')).err, /NO_BRIEF.*--criterion.*--check/);+ assert.match(box.run(box.repo, 'add', 'web', 'Copy', '--brief', 'x', '--brief-file', 'y').err, /USAGE.*give the brief once/);+ const foreign = box.run(box.repo, 'add', 'web', 'Copy', '--route', 'light', '--criterion', 'c', '--check', 'true', '--brief', LIGHT_BRIEF.replace('web/page.js', 'api/server.js'));+ assert.match(foreign.err, /BRIEF_LANE.*api\/server.js \(api's\)/);+ const added = box.run(box.repo, 'add', 'web', 'Copy', 'the', 'header', '--route', 'light', '--criterion', 'the page shows the header', '--check', 'test -f web/page.js', '--brief-file', join(box.dir, 'brief.md'), '--wait');+ assert.equal(added.code, 0, added.err);+ assert.equal(added.out.trim(), `#2\ncheck baseline red at main ${box.git(box.repo, 'rev-parse', 'main')}: test -f web/page.js`);+ assert.match(box.run(box.repo, 'list').out, /#2 {2}open {2}web {2}Copy the header {2}light/);+ assert.doesNotMatch(box.run(box.repo, 'list', '--route', 'light').out, /Design the page/);+ const made = box.run(box.repo, 'worktree', 'web', '--route', 'light');- assert.match(made.out, /joined as web-2 in the web lane, on the light route/);++ assert.match(made.out, /joined as web-2 \(Test Model\) in the web lane, on the light route/);+ const light = made.out.match(/^made (\S+) /)[1];- assert.match(box.run(light, 'whoami').out, /^web-2 \(web lane, light route\)/);++ assert.match(box.run(light, 'whoami').out, /^web-2 \(Test Model\) \(web lane, light route\)/);+ const next = box.run(light, 'next');+ assert.match(next.out, /claimed #2: Copy the header\ncriterion: the page shows the header\ncheck: test -f web\/page.js {3}\(run it before you submit\)\nbrief:\n {2}Files:\n {2}- web\/page.js/);+ assert.match(box.run(light, 'claim', '1').err, /ROUTE/);+ assert.match(box.run(box.web, 'next').out, /claimed #1: Design the page/);+ assert.equal(box.run(box.repo, 'edit', '1', '--brief', 'Start from the sketch in docs/page.md.').code, 0);+ assert.match(box.run(box.web, 'show', '1').out, /brief:\n {2}Start from the sketch in docs\/page.md./);+ assert.match(box.run(box.web, 'edit', '2', '--brief', 'mine').err, /NOT_YOURS/);+ });++ test('run builds routed items unattended: the failure feeds the next attempt; red work escalates, pinned [N14, B15]', () => {+ const box = project();+ const agent = join(box.dir, 'agent.sh');+ writeFileSync(agent, [+ '#!/bin/sh',+ 'mkdir -p web api',+ 'if [ "$PULLBOARD_ITEM" = "1" ]; then',+ ' if [ "$PULLBOARD_ATTEMPT" = "1" ]; then echo "export const title = \'Hello\';" > web/page.js; echo stray > api/stray.js;',+ ' elif grep -q "The check" "$PULLBOARD_PACK"; then echo "export const title = \'Hi\';" > web/page.js; fi',+ 'else',+ ' echo "export const footer = \'nope\'; // $PULLBOARD_CHECK $PULLBOARD_TIER" | tr B b > web/footer.js',+ 'fi',+ '',+ ].join('\n'));+ const brief = (file) => LIGHT_BRIEF.replace('web/page.js', file);+ const has = (file, text) => `grep -q ${text} ${file}`;+ assert.equal(box.run(box.repo, 'add', 'web', 'Greet', 'on', 'the', 'page', '--specs', 'G1', '--route', 'light', '--criterion', 'the page says Hi', '--check', has('web/page.js', 'Hi'), '--brief', brief('web/page.js')).code, 0);+ assert.equal(box.run(box.repo, 'add', 'web', 'Say', 'bye', '--route', 'light', '--criterion', 'the footer says Bye', '--check', has('web/footer.js', 'Bye'), '--brief', brief('web/footer.js')).code, 0);+ const made = box.run(box.repo, 'worktree', 'web', '--route', 'light');+ const light = made.out.match(/^made (\S+) /)[1];+ assert.match(box.run(box.repo, 'run', '--agent', `sh ${agent}`).err, /MAIN_IS_COORDINATOR/);+ assert.match(box.run(light, 'run', '--agent-mid', `sh ${agent}`).err, /ROUTE.*joined on the light route, so it cannot take mid items/);+ const ran = box.run(light, 'run', '--agent-light', `sh ${agent}`, '--attempts', '2', '--minutes', '2');+ assert.equal(ran.code, 0, ran.err);+ assert.match(ran.out, /#1 attempt 1: red[\s\S]*#1 attempt 2: green \(agent \d+s, check \d+s\)\nsubmitted #1/);+ assert.match(ran.out, /nothing left to run: no open light runnable items in the web lane/);+ assert.match(ran.out, /#2 attempt 2: red[\s\S]*#2 escalated light -> mid; the attempt is pinned at refs\/pullboard\/attempts\/2\//);+ assert.match(ran.out, /runner done: 1 submitted, 1 escalated/);+ const packs = join(box.dir, 'repo', '.git', 'worktrees', light.split('/').at(-1), 'pullboard', 'packs');+ const second = readFileSync(join(packs, '1-light-2.md'), 'utf8');+ assert.equal(existsSync(join(packs, '1-light-1.log')), true);+ assert.match(second, /reverted your changes outside the brief's files: api\/stray.js/);+ assert.match(second, /### web\/page.js\n```\nexport const title = 'Hello';/);+ assert.equal(existsSync(join(light, 'api', 'stray.js')), false);+ assert.equal(box.git(light, 'log', '-1', '--format=%s', 'refs/pullboard/items/1/' + box.git(light, 'rev-parse', '--short=12', 'HEAD')), 'feat(web): greet on the page [G1]');+ assert.equal(box.git(light, 'status', '--porcelain'), '');+ const pinned = box.git(light, 'for-each-ref', '--format=%(refname)', 'refs/pullboard/attempts/2/');+ assert.match(box.git(light, 'show', `${pinned}:web/footer.js`), /nope'; \/\/ grep -q bye web\/footer.js light/);+ const shown = box.run(box.repo, 'show', '2').out;+ assert.match(shown, /#2 {2}open {2}web {2}Say bye {2}mid/);+ assert.match(shown, /unattended attempts: red, red/);- assert.match(shown, /escalated light -> mid by web-2, pinned at refs\/pullboard\/attempts\/2\/[0-9a-f]{12}: 2 attempts stayed red/);- assert.match(box.run(box.repo, 'inbox').out, /web-2 -> coordinator: #2 escalated light -> mid after 2 red attempts/);++ assert.match(shown, /escalated light -> mid by web-2 \(Test Model\), pinned at refs\/pullboard\/attempts\/2\/[0-9a-f]{12}: 2 attempts stayed red/);++ assert.match(box.run(box.repo, 'inbox').out, /web-2 \(Test Model\) -> coordinator \(unknown\): #2 escalated light -> mid after 2 red attempts/);+ });++ test('one runner climbs the tiers: an escalated item goes to the next command, with the earlier tries; it merges the verified work an item waits on [N16]', () => {+ const box = project();+ const script = (name, lines) => {+ writeFileSync(join(box.dir, name), ['#!/bin/sh', 'mkdir -p web api', ...lines, ''].join('\n'));+ return `sh ${join(box.dir, name)}`;+ };+ const good = script('web.sh', ["echo \"export const title = 'Hi';\" > web/page.js"]);+ const weak = script('weak.sh', ['echo nope > api/server.js']);+ const strong = script('strong.sh', ['grep -q "Earlier tries by a lighter model" "$PULLBOARD_PACK" && echo "export const served = true;" > api/server.js']);+ const brief = (file) => LIGHT_BRIEF.replace('web/page.js', file);+ box.run(box.repo, 'add', 'web', 'Greet', '--route', 'light', '--criterion', 'says Hi', '--check', 'grep -q Hi web/page.js', '--brief', brief('web/page.js'));+ box.run(box.repo, 'add', 'api', 'Serve', 'the', 'page', '--after', '1', '--route', 'light', '--criterion', 'serves it', '--check', 'test -f web/page.js && grep -q served api/server.js', '--brief', brief('api/server.js'));+ const webRunner = box.run(box.repo, 'worktree', 'web', '--route', 'light').out.match(/^made (\S+) /)[1];+ assert.match(box.run(webRunner, 'run', '--agent-light', good, '--attempts', '1').out, /submitted #1/);+ const commit = JSON.parse(box.run(box.repo, 'show', '1', '--json').out).item_commit;+ box.git(box.web, 'merge', '-q', '--ff-only', commit);+ assert.match(box.run(box.web, 'verify', '1', 'accept', '--note', 'ran the check, then emptied the file and saw it fail').out, /verified #1/);+ const apiRunner = box.run(box.repo, 'worktree', 'api', '--route', 'mid').out.match(/^made (\S+) /)[1];+ const ran = box.run(apiRunner, 'run', '--agent-light', weak, '--agent-mid', strong, '--attempts', '2', '--minutes', '2');+ assert.equal(ran.code, 0, ran.err);+ assert.match(ran.out, /#2 attempt 1\/2: running the light agent[\s\S]*#2 escalated light -> mid[\s\S]*#2 attempt 1\/2: running the mid agent\n#2 attempt 1: green[\s\S]*submitted #2/);+ assert.match(ran.out, /runner done: 1 submitted, 1 escalated/);+ assert.equal(box.tryGit(apiRunner, 'merge-base', '--is-ancestor', commit, 'HEAD').status, 0);+ const packs = join(box.dir, 'repo', '.git', 'worktrees', apiRunner.split('/').at(-1), 'pullboard', 'packs');+ assert.match(readFileSync(join(packs, '2-mid-1.md'), 'utf8'), /## Earlier tries by a lighter model\n- 2 attempts stayed red/);+ assert.equal(existsSync(join(packs, '2-light-1.md')), true);+ });++ test('the runner returns a claimed dependent item when its verified dependency conflicts [B8,V1,R1]', () => {+ const box = project();+ const localRunner = box.run(box.repo, 'worktree', 'api', '--route', 'light').out.match(/^made (\S+) /)[1];+ const dependencyRunner = box.run(box.repo, 'worktree', 'api', '--route', 'light').out.match(/^made (\S+) /)[1];+ mkdirSync(join(localRunner, 'api'));+ writeFileSync(join(localRunner, 'api', 'server.js'), "export const source = 'local';\n");+ box.git(localRunner, 'add', 'api/server.js');+ box.git(localRunner, 'commit', '-q', '-m', 'feat(api): local server variant [G2]');++ const brief = LIGHT_BRIEF.replace('web/page.js', 'api/server.js');+ box.run(box.repo, 'add', 'api', 'Upstream API', '--route', 'light', '--specs', 'G2', '--criterion', 'serves the upstream API',+ '--check', 'grep -q upstream api/server.js', '--brief', brief);+ const upstreamAgent = `sh ${join(box.dir, 'upstream.sh')}`;+ writeFileSync(join(box.dir, 'upstream.sh'), '#!/bin/sh\nmkdir -p api\nprintf "export const source = upstream;\\n" > api/server.js\n');+ assert.match(box.run(dependencyRunner, 'run', '--agent-light', upstreamAgent, '--attempts', '1').out, /submitted #1/);+ const dependencyCommit = JSON.parse(box.run(box.repo, 'show', '1', '--json').out).item_commit;+ box.git(box.web, 'merge', '-q', '--ff-only', dependencyCommit);+ assert.match(box.run(box.web, 'verify', '1', 'accept', '--note', 'The exact upstream API check passed.').out, /verified #1/);++ box.run(box.repo, 'add', 'api', 'Dependent API', '--after', '1', '--route', 'light', '--specs', 'G2', '--criterion', 'integrates upstream API',+ '--check', 'grep -q upstream api/server.js', '--brief', brief);+ const blocked = box.run(localRunner, 'run', '--agent-light', 'true', '--attempts', '1');+ assert.notEqual(blocked.code, 0, blocked.out);+ assert.match(blocked.err, /MERGE_CONFLICT/);+ assert.equal(JSON.parse(box.run(box.repo, 'show', '2', '--json').out).item_status, 'open', 'the automatic claimed-item release remains unchanged');+ });++ test('sweep files one light item per flagged file, in its lane; a second sweep skips what is open [N15]', () => {+ const box = project();+ writeFileSync(join(box.dir, 'novar.mjs'), [+ "import fs from 'node:fs';",+ "import path from 'node:path';",+ 'const walk = (p) => fs.statSync(p).isDirectory() ? fs.readdirSync(p).filter((n) => !n.startsWith(".") && n !== "node_modules").flatMap((n) => walk(path.join(p, n))) : [p];',+ 'let found = 0;',+ 'for (const file of process.argv.slice(2).flatMap(walk).filter((f) => f.endsWith(".js"))) {',+ ' fs.readFileSync(file, "utf8").split("\\n").forEach((line, i) => { const col = line.indexOf("var "); if (col >= 0) { found += 1; console.log(`${file}:${i + 1}:${col + 1}: no-var Unexpected var, use let or const.`); } });',+ '}',+ 'process.exit(found ? 1 : 0);',+ '',+ ].join('\n'));+ commitFile(box, box.repo, 'web/a.js', 'var a = 1;\nvar b = 2;\n', 'chore: two vars');+ commitFile(box, box.repo, 'api/b.js', 'var c = 3;\n', 'chore: one var');+ const sweep = ['sweep', '--run', `node ${join(box.dir, 'novar.mjs')} .`, '--check', `node ${join(box.dir, 'novar.mjs')} {file}`];+ assert.match(box.run(box.web, ...sweep).err, /COORDINATOR_ONLY/);+ assert.match(box.run(box.repo, ...sweep, '--dry-run').out, /would file: fix 2 problems in web\/a.js \(web lane, light\)/);+ const filed = box.run(box.repo, ...sweep);+ assert.equal(filed.code, 0, filed.err);+ assert.match(filed.out, /#1 fix 2 problems in web\/a.js \(web lane, light\)\n#2 fix 1 problem in api\/b.js \(api lane, light\)/);+ assert.match(filed.out, /3 problems in 2 files; filed 2/);+ const shown = box.run(box.repo, 'show', '1').out;+ assert.match(shown, new RegExp(`check: node ${join(box.dir, 'novar.mjs')} web/a.js`));+ assert.match(shown, /- line 2:1 no-var: Unexpected var, use let or const\./);+ assert.match(box.run(box.repo, ...sweep).out, /already open: web\/a.js, api\/b.js\n3 problems in 2 files; filed 0/);+ commitFile(box, box.repo, 'docs/c.js', 'var d = 4;\n', 'chore: one more var');+ const blind = box.run(box.repo, 'sweep', '--run', `node ${join(box.dir, 'novar.mjs')} .`, '--check', `node ${join(box.dir, 'novar.mjs')} {file} | tail -5`);+ assert.equal(blind.code, 1);+ assert.match(blind.err, /CHECK_CANNOT_FAIL\] the check passes on docs\/c.js although the checker flags problems there/);+ assert.match(blind.out, /filed 0/);+ });++ test('pre-commit runs the fixers on fully staged files and restages them; partly staged files are left alone [C5]', () => {+ const box = project();+ const fixer = join(box.dir, 'trim.mjs');+ writeFileSync(fixer, "import fs from 'node:fs';\nfor (const f of process.argv.slice(2)) fs.writeFileSync(f, fs.readFileSync(f, 'utf8').replace(/[ \\t]+$/gm, ''));\n");+ const config = JSON.parse(readFileSync(join(box.repo, 'pullboard.json'), 'utf8'));+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...config, fix: [{ run: `node ${fixer}`, files: ['*.js'] }] }, null, 2));+ box.git(box.repo, 'commit', '-qam', 'chore: trim trailing spaces at commit');+ mkdirSync(join(box.repo, 'docs'), { recursive: true });+ writeFileSync(join(box.repo, 'docs', 'a.js'), 'const a = 1; \n');+ writeFileSync(join(box.repo, 'docs', 'b.md'), 'text \n');+ writeFileSync(join(box.repo, 'docs', 'c.js'), 'const c = 1; \n');+ box.git(box.repo, 'add', 'docs');+ writeFileSync(join(box.repo, 'docs', 'c.js'), 'const c = 1; \nconst d = 2;\n');+ const committed = box.tryGit(box.repo, 'commit', '-q', '-m', 'docs: three files');+ assert.equal(committed.status, 0, committed.stderr);+ const committedText = (path) => box.tryGit(box.repo, 'show', `HEAD:${path}`).stdout;+ assert.equal(committedText('docs/a.js'), 'const a = 1;\n');+ assert.equal(readFileSync(join(box.repo, 'docs', 'a.js'), 'utf8'), 'const a = 1;\n');+ assert.equal(committedText('docs/b.md'), 'text \n');+ assert.equal(committedText('docs/c.js'), 'const c = 1; \n');+ assert.match(committed.stderr, /not fixed, because they are partly staged: docs\/c.js/);+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...config, fix: [{ run: 'false', files: ['*.js'] }] }, null, 2));+ box.git(box.repo, 'commit', '-qam', 'chore: a fixer that fails');+ writeFileSync(join(box.repo, 'docs', 'e.js'), 'const e = 1; \n');+ box.git(box.repo, 'add', 'docs/e.js');+ const failed = box.tryGit(box.repo, 'commit', '-q', '-m', 'docs: one more');+ assert.equal(failed.status, 0, failed.stderr);+ assert.match(failed.stderr, /fixer "false" failed \(1\); staged nothing from it/);+ assert.equal(committedText('docs/e.js'), 'const e = 1; \n');+ });++ test('resume puts an agent back to work from the board: its claim, its branch, what came back, the next step [N19]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1', '--brief', 'Files: web/page.html');+ const fresh = box.run(box.web, 'resume');+ assert.equal(fresh.code, 0, fresh.err);- assert.match(fresh.out, /^resume: web-1, web lane, at /);++ assert.match(fresh.out, /^resume: web-1 \(Test Model\), web lane, at /);+ assert.match(fresh.out, /branch web\/one: 0 ahead of main, 0 behind/);+ assert.match(fresh.out, /next: pullboard next \(1 ready in your lane\)/);+ box.run(box.web, 'next');+ mkdirSync(join(box.web, 'web'));+ writeFileSync(join(box.web, 'web', 'page.html'), '<h1>Hi</h1>');+ box.run(box.repo, 'shout', 'web-1', 'the heading text is in G1');+ const building = box.run(box.web, 'resume').out;+ assert.match(building, /1 file uncommitted/);+ assert.match(building, /holding #1 Page, lease \d+[mh] left/);+ assert.match(building, /files: web\/page\.html/);- assert.match(building, /1 unread shout; newest from coordinator: the heading text is in G1/);++ assert.match(building, /1 unread shout; newest from coordinator \(unknown\): the heading text is in G1/);+ assert.match(building, /next: build #1, commit, then pullboard submit 1/);+ box.git(box.web, 'add', '-A');+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): page [G1]');+ assert.equal(box.run(box.web, 'submit', '1').code, 0);+ const coordinator = box.run(box.repo, 'resume').out;- assert.match(coordinator, /^resume: coordinator, coordinator lane, the main checkout/);++ assert.match(coordinator, /^resume: coordinator \(unknown\), coordinator lane, the main checkout/);+ assert.match(coordinator, /to verify: #1 web \(\d+[mhd]\)/);+ assert.match(coordinator, /next: pullboard next --verify --as coordinator/);+ box.git(box.repo, 'switch', '-q', '--detach', 'web/one');+ box.run(box.repo, 'verify', '1', 'reject', '--reason', 'TEST_FAILURE', '--note', 'no test proves the heading\nthe rest is fine', '--as', 'coordinator');+ const back = box.run(box.web, 'resume').out;+ assert.match(back, /branch web\/one: main is detached for a verification/);+ box.git(box.repo, 'switch', '-q', 'main');+ assert.match(box.run(box.web, 'resume').out, /branch web\/one: 1 ahead of main, 0 behind/);- assert.match(back, /sent back: #1 TEST_FAILURE by coordinator: no test proves the heading$/m);++ assert.match(back, /sent back: #1 TEST_FAILURE by coordinator \(unknown\): no test proves the heading$/m);+ assert.match(back, /next: pullboard claim 1, fix what the verifier found, and submit again/);+ });++ test('next takes work near your recent files; submit records them; show names related verified work [N20, N21]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Footer', '--specs', 'G1', '--brief', 'Files: web/footer.html');+ box.run(box.repo, 'add', 'web', 'Header', '--specs', 'G1', '--brief', 'Files: web/header.html');+ mkdirSync(join(box.web, 'web'));+ writeFileSync(join(box.web, 'web', 'header.html'), '<header>');+ const next = box.run(box.web, 'next');+ assert.match(next.out, /claimed #2: Header/);+ assert.match(next.out, /it touches a file you worked in recently: web\/header\.html/);+ box.git(box.web, 'add', '-A');+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): header [G1]');+ commitFile(box, box.web, 'web/nav.html', '<nav>', 'feat(web): nav in the header [G1]');+ commitFile(box, box.repo, 'docs/notes.md', 'main moves on', 'docs: notes on main');+ box.git(box.web, 'merge', '-q', '--no-edit', 'main');+ assert.equal(box.run(box.web, 'submit', '2').code, 0);+ assert.equal(JSON.parse(box.run(box.web, 'show', '2', '--json').out).item_files, 'web/header.html\nweb/nav.html', 'only the item\'s own commits, not the merge');+ box.git(box.repo, 'switch', '-q', '--detach', 'web/one');+ box.run(box.repo, 'verify', '2', 'accept', '--note', 'emptied the header; the page lost it', '--as', 'coordinator');+ box.git(box.repo, 'switch', '-q', 'main');+ box.run(box.repo, 'add', 'web', 'Menu', '--specs', 'G1', '--brief', 'Files: web/nav.html, web/menu.html');+ assert.match(box.run(box.repo, 'show', '3').out, /related: #2 Header: web\/nav\.html \(git log -p -1 [0-9a-f]{12} -- web\/nav\.html\)/);+ const warm = box.run(box.web, 'next');+ assert.match(warm.out, /claimed #3: Menu/, 'a clean tree: the files of the items it built last are what is warm');+ assert.match(warm.out, /it touches a file you worked in recently: web\/nav\.html/);+ });++ test('hold pauses a lane: next names who held it and why; --off lets it go [N22]', () => {+ const box = project();+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1');+ assert.match(box.run(box.web, 'hold', 'web', '--reason', 'mine').err, /COORDINATOR_ONLY/);+ assert.match(box.run(box.repo, 'hold', 'nowhere', '--reason', 'x').err, /NO_LANE/);+ assert.match(box.run(box.repo, 'hold', 'web', '--reason', 'G1 is being rewritten').out, /holding the web lane: G1 is being rewritten/);+ const held = box.run(box.web, 'next');+ assert.equal(held.code, 1);- assert.match(held.err, /coordinator holds the web lane: G1 is being rewritten/);++ assert.match(held.err, /coordinator \(unknown\) holds the web lane: G1 is being rewritten/);+ assert.match(box.run(box.web, 'claim', '1').err, /LANE_HELD/);- assert.match(box.run(box.web, 'resume').out, /the web lane is held by coordinator: G1 is being rewritten/);++ assert.match(box.run(box.web, 'resume').out, /the web lane is held by coordinator \(unknown\): G1 is being rewritten/);+ assert.match(box.run(box.repo, 'hold', 'web', '--off').out, /released the web lane/);+ assert.match(box.run(box.web, 'next').out, /claimed #1: Page/);+ });diff --cc test/e2e.test.jsindex afb07c13,28d591bd..8d24f350--- a/test/e2e.test.js+++ b/test/e2e.test.js@@@ -272,12 -200,12 +200,12 @@@ test('the board lives in the git commoassert.ok(existsSync(join(box.repo, '.git', 'pullboard', 'board.sqlite')));assert.equal(box.git(box.repo, 'status', '--porcelain'), '');assert.match(box.run(box.repo, 'whoami').out, /^coordinator/);- assert.match(box.run(box.web, 'whoami').out, /^web-1 \(web lane\)/);+ assert.match(box.run(box.web, 'whoami').out, /^web-1 \(Test Model\) \(web lane\)/);const second = join(box.dir, 'web-2');box.git(box.repo, 'worktree', 'add', '-q', second, '-b', 'web/two');- assert.match(box.run(second, 'join', 'web').out, /joined as web-2 \(Test Model\)/);+ assert.match(box.run(second, 'join', 'web').out, /joined as web-2/);- assert.match(box.run(second, 'whoami').out, /^web-2 \(web lane\)/, 'a second worktree in the same lane is its own agent');- assert.match(box.run(box.web, 'whoami').out, /^web-1 \(web lane\)/, 'and the first stays itself');+ assert.match(box.run(second, 'whoami').out, /^web-2 \(Test Model\) \(web lane\)/, 'a second worktree in the same lane is its own agent');+ assert.match(box.run(box.web, 'whoami').out, /^web-1 \(Test Model\) \(web lane\)/, 'and the first stays itself');assert.match(box.run(box.web, 'init').err, /NOT_MAIN/);assert.match(box.run(box.repo, 'join', 'web').err, /MAIN_IS_COORDINATOR/);});diff --cc test/item-hold.test.jsindex 00000000,8f4c0f6a..42ba7fe8mode 000000,100644..100644--- a/test/item-hold.test.js+++ b/test/item-hold.test.js@@@ -1,0 -1,161 +1,161 @@@+ /** Coordinator item holds preserve routing, claims and ordered replay [N2,N22,H16,M1]. */+ import assert from 'node:assert/strict';+ import { test } from 'node:test';+ import { createE2eHelpers } from './e2e-helpers.js';+ import * as store from '../src/board.js';+ import { applyRelayMove, prepareEngineMove } from '../src/engine.js';+ import { exportBoard, importBoard } from '../src/exchange.js';++ const e2e = createE2eHelpers();++ /** Add a runnable mid item to a real private board. */+ function addMidItem(board, lane, title) {+ return store.addItem(board, { by: 'coordinator', lane, title, route: 'mid',+ criterion: 'The private fixture proves the hold.', brief: e2e.LIGHT_BRIEF, check: 'true' });+ }++ /** Read a successful private CLI JSON result without hiding its diagnostic on failure. */+ function jsonSuccess(box, cwd, ...args) {+ const result = box.run(cwd, ...args, '--json');+ assert.equal(result.code, 0, result.err || result.out);+ return JSON.parse(result.out);+ }++ /** Read the item fields that a hold must leave unchanged. */+ function withoutHold(item) {+ const { item_hold_reason, item_hold_by, item_hold_at, item_updated_at, ...unchanged } = item;+ return unchanged;+ }++ test('a held item is never offered or claimed [N2,N22,M1]', t => {+ const box = e2e.project('true');+ t.after(e2e.cleanup);+ const board = store.openBoard(`${box.repo}/.git/pullboard/board.sqlite`);+ t.after(() => store.closeBoard(board));+ const held = new Map();+ const actors = [];+ for (const lane of ['web', 'api']) {+ const id = addMidItem(board, lane, `Held ${lane} item`);+ const before = store.getItem(board, id);+ const reason = `waiting for the person in ${lane}`;+ const result = jsonSuccess(box, box.repo, 'hold', String(id), reason);+ assert.equal(result.id, id);+ assert.equal(result.lane, lane);+ assert.equal(result.held, true);+ assert.equal(result.reason, reason);+ assert.deepEqual(withoutHold(store.getItem(board, id)), withoutHold(before));- assert.match(box.run(box.repo, 'show', String(id)).out, new RegExp(`held by coordinator: ${reason}`));- assert.match(box.run(box.repo, 'list', lane).out, new RegExp(`held by coordinator: ${reason}`));++ assert.match(box.run(box.repo, 'show', String(id)).out, new RegExp(`held by coordinator \\(unknown\\): ${reason}`));++ assert.match(box.run(box.repo, 'list', lane).out, new RegExp(`held by coordinator \\(unknown\\): ${reason}`));+ held.set(lane, { id, reason });+ for (const route of ['light', 'mid', 'strong']) {+ const actor = jsonSuccess(box, box.repo, 'worktree', lane, '--route', route);+ actors.push({ ...actor, lane, route });+ const next = store.nextFor(board, { agentId: actor.agent, lane });+ assert.equal(next.item, null, `${lane}/${route} cannot offer a held item`);+ assert.ok(next.reasons.includes(`#${id} is held by coordinator: ${reason}`));+ const attempted = box.run(actor.path, 'next', '--build', '--json');+ assert.equal(attempted.code, 1);+ const refusal = JSON.parse(attempted.out);+ assert.equal(refusal.error.code, 'NOTHING_FREE');+ assert.ok(refusal.error.message.includes(`#${id} is held by coordinator: ${reason}`));+ }+ }+ jsonSuccess(box, box.repo, 'hold', 'web', '--reason', 'lane release review');+ const webActor = actors.find(value => value.lane === 'web' && value.route === 'strong');+ const paused = box.run(webActor.path, 'next', '--build', '--json');+ assert.equal(paused.code, 1);+ const pausedReason = JSON.parse(paused.out).error.message;+ assert.ok(pausedReason.includes('lane release review'));+ assert.ok(pausedReason.includes(`#${held.get('web').id} is held by coordinator: ${held.get('web').reason}`),+ 'a lane hold does not mask the item hold reason');+ jsonSuccess(box, box.repo, 'hold', 'web', '--off');+ for (const actor of actors) {+ for (const { id, reason } of held.values()) {+ const attempted = box.run(actor.path, 'claim', String(id), '--json');+ assert.equal(attempted.code, 1);+ const refusal = JSON.parse(attempted.out);+ assert.equal(refusal.error.code, 'ITEM_HELD', `${actor.lane}/${actor.route} cannot claim a held item in either lane`);+ assert.ok(refusal.error.message.includes(reason));+ assert.equal(store.getItem(board, id).item_status, 'open');+ assert.equal(store.getItem(board, id).item_owner, null);+ }+ }+ const actor = actors.find(value => value.lane === 'web' && value.route === 'mid');+ const free = addMidItem(board, 'web', 'Available work after a held item');+ const selected = jsonSuccess(box, actor.path, 'next', '--build');+ assert.equal(selected.item.item_id, free, 'next passes the held item to claim available work');+ assert.ok(selected.reasons.includes(`#${held.get('web').id} is held by coordinator: ${held.get('web').reason}`));+ const unauthorized = box.run(actor.path, 'hold', String(free), 'an agent cannot hold work', '--json');+ assert.equal(unauthorized.code, 1);+ assert.match(unauthorized.out + unauthorized.err, /COORDINATOR_ONLY/u);+ });++ test('lifting a hold makes the item offerable again [N2,N22,H16,M1]', t => {+ const box = e2e.project('true');+ t.after(e2e.cleanup);+ const board = store.openBoard(`${box.repo}/.git/pullboard/board.sqlite`);+ t.after(() => store.closeBoard(board));+ const id = addMidItem(board, 'web', 'Held item');+ const peer = store.openBoard(':memory:');+ t.after(() => store.closeBoard(peer));+ store.register(peer, { lane: 'coordinator', path: '/peer' });+ store.register(peer, { lane: 'web', path: '/peer-web' });+ assert.equal(addMidItem(peer, 'web', 'Held item'), id);+ const initial = store.getItem(board, id);+ const hold = prepareEngineMove(board, 'holdItem', [id, { agentId: 'coordinator', reason: 'review the release' }]);+ const at = '2026-10-09T12:00:00.000Z';+ const transport = { kind: 'move', sender: { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' } };+ const applied = applyRelayMove(board, hold, { ...transport, sequence: 1, at });+ assert.deepEqual(applyRelayMove(peer, hold, { ...transport, sequence: 1, at }), applied);+ assert.equal(store.getItem(peer, id).item_hold_reason, 'review the release');+ const holdEvent = store.events(peer, { itemId: id }).at(-1);+ assert.equal(holdEvent.event_kind, 'hold_item');+ assert.equal(JSON.parse(holdEvent.event_detail).reason, 'review the release');+ const restored = store.openBoard(':memory:');+ t.after(() => store.closeBoard(restored));+ importBoard(restored, exportBoard(board));+ assert.deepEqual(store.getItem(restored, id), store.getItem(board, id), 'snapshot sync preserves the complete held item');+ assert.deepEqual(store.events(restored), store.events(board), 'snapshot sync preserves the hold event');+ assert.equal(store.nextFor(restored, { agentId: 'web-1', lane: 'web' }).item, null);+ const legacyExport = exportBoard(board);+ for (const item of legacyExport.tables.item) {+ delete item.item_hold_reason;+ delete item.item_hold_by;+ delete item.item_hold_at;+ }+ const incompatible = store.openBoard(':memory:');+ t.after(() => store.closeBoard(incompatible));+ assert.throws(() => importBoard(incompatible, legacyExport), error => error.code === 'IMPORT_SCHEMA'+ && error.message === '[IMPORT_SCHEMA] a item row does not have exactly its board columns; export it again',+ 'a pre-hold export retains the existing strict-schema refusal');+ const release = prepareEngineMove(board, 'releaseItemHold', [id, { agentId: 'coordinator' }]);+ const releaseAt = '2026-10-09T12:01:00.000Z';+ const released = applyRelayMove(board, release, { ...transport, sequence: 2, at: releaseAt });+ assert.deepEqual(applyRelayMove(peer, release, { ...transport, sequence: 2, at: releaseAt }), released);+ assert.equal(store.events(peer, { itemId: id }).at(-1).event_kind, 'unhold_item');+ for (const replica of [board, peer]) {+ const item = store.getItem(replica, id);+ assert.equal(item.item_hold_reason, null);+ assert.equal(item.item_hold_by, null);+ assert.equal(item.item_hold_at, null);+ assert.equal(store.nextFor(replica, { agentId: 'web-1', lane: 'web' }).item.item_id, id);+ }+ assert.deepEqual(withoutHold(store.getItem(board, id)), withoutHold(initial));+ jsonSuccess(box, box.repo, 'hold', String(id), 'CLI hold and lift');+ const lifted = jsonSuccess(box, box.repo, 'hold', String(id), '--off');+ assert.equal(lifted.held, false);+ assert.equal(lifted.reason, null);+ assert.equal(store.nextFor(board, { agentId: 'web-1', lane: 'web' }).item.item_id, id);+ assert.equal(jsonSuccess(box, box.web, 'next', '--build').item.item_id, id);+ jsonSuccess(box, box.repo, 'hold', String(id), 'finish your current work');+ assert.equal(store.getItem(board, id).item_owner, 'web-1');+ const heldClaimCopy = store.openBoard(':memory:');+ t.after(() => store.closeBoard(heldClaimCopy));+ importBoard(heldClaimCopy, exportBoard(board));+ assert.deepEqual(store.getItem(heldClaimCopy, id), store.getItem(board, id), 'snapshot sync preserves the held claim and reason');+ assert.equal(store.getItem(heldClaimCopy, id).item_owner, 'web-1');+ assert.equal(jsonSuccess(box, box.web, 'claim', String(id)).renewed, true);+ box.git(box.web, 'commit', '--allow-empty', '-qm', 'feat(web): finish held work [G1]');+ assert.equal(jsonSuccess(box, box.web, 'submit', String(id)).id, id);+ assert.equal(store.getItem(board, id).item_status, 'submitted', 'the existing live holder can still submit');+ });diff --cc test/stats-cli.test.jsindex 00000000,9fc45160..a569bacamode 000000,100644..100644--- a/test/stats-cli.test.js+++ b/test/stats-cli.test.js@@@ -1,0 -1,102 +1,102 @@@+ /** Event-derived proof numbers have the same data in text and versioned JSON [R1,R2,A1]. */+ import assert from 'node:assert/strict';+ import { runFixtureGit } from './fixture-child.js';+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { join } from 'node:path';+ import { test } from 'node:test';+ import * as store from '../src/board.js';+ import { main } from '../src/cli.js';+ import { proofStats } from '../src/stats.js';+ import { serveApi } from '../src/api.js';+ import { fetchFresh } from './http-fixture.js';++ /** Capture the real CLI without spawning a second model or changing the machine's registry. */+ async function run(root, args) {+ let stdout = '';+ let stderr = '';+ const code = await main(args, { cwd: root,+ stdout: { isTTY: false, write: (text) => { stdout += text; } },+ stderr: { write: (text) => { stderr += text; } } });+ return { code, stdout, stderr, data: args.includes('--json') ? JSON.parse(stdout) : null };+ }++ /** Create an isolated Git board with one rejected submission and accepted rework. */+ function fixture(t) {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-stats-cli-')));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, stdio: 'pipe' });+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ lanes: { web: { owns: ['web/'] } } }));+ writeFileSync(join(root, 'PRACTICE.md'), '');+ const clock = { now: () => new Date('2026-10-08T12:00:00.000Z') };+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'), clock);+ t.after(() => store.closeBoard(board));+ store.register(board, { lane: 'coordinator', path: root });+ const builder = store.register(board, { lane: 'web', path: join(root, 'web') });+ const reviewer = store.register(board, { lane: 'review', path: join(root, 'review') });+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Proof fixture' });+ const freeze = () => ({ text: 'Proof fixture', digest: 'frozen' });+ const submit = (commit) => {+ store.claim(board, id, { agentId: builder, lane: 'web', leaseMs: 3_600_000, freeze });+ store.submit(board, id, { agentId: builder, commit, tree: 'b'.repeat(40) });+ };+ submit('a'.repeat(40));+ store.verify(board, id, { agentId: reviewer, decision: 'REJECT', reason: 'TEST_FAILURE', note: 'Fixture rejects the first attempt.', head: 'a'.repeat(40), digest: 'frozen', policy: 'any' });+ submit('c'.repeat(40));+ store.verify(board, id, { agentId: reviewer, decision: 'ACCEPT', note: 'Fixture rework meets its bar.', head: 'c'.repeat(40), digest: 'frozen', policy: 'any' });+ store.merged(board, id, { agentId: 'coordinator', commit: 'd'.repeat(40) });+ return { root, board };+ }++ test('[R1,R2,A1] stats JSON is versioned, text states the same proof numbers and neither records a move', async (t) => {+ const { root, board } = fixture(t);+ const before = store.events(board);+ const expected = proofStats(board);+ const json = await run(root, ['stats', '--json']);+ assert.equal(json.code, 0, json.stderr);+ assert.equal(json.stderr, '');+ assert.deepEqual(json.data, { version: 1, stats: expected });+ assert.deepEqual([expected.submissions, expected.rejections, expected.rejectionShare, expected.merged, expected.mergedWithoutAccept], [2, 1, 0.5, 1, 0]);+ const text = await run(root, ['stats']);+ assert.equal(text.code, 0, text.stderr);+ assert.match(text.stdout, /2 submissions · 1 rejections · 50\.0% sent back/u);+ assert.match(text.stdout, /1 items merged · 0 merged without an accept/u);+ assert.match(text.stdout, /3 agents · 1 family buckets: unknown \(3 agents,/u);- assert.match(text.stdout, /agents: coordinator \(unknown; \d+ moves\), review-1 \(unknown; \d+ moves\), web-1 \(unknown; \d+ moves\)/u);++ assert.match(text.stdout, /agents: coordinator \(unknown\) \(unknown; \d+ moves\), review-1 \(unknown\) \(unknown; \d+ moves\), web-1 \(unknown\) \(unknown; \d+ moves\)/u);+ assert.ok(text.stdout.includes(expected.firstEventAt));+ assert.ok(text.stdout.includes(expected.lastEventAt));+ assert.deepEqual(store.events(board), before, 'reading statistics appends no move');+ });++ test('[R2,A1] stats forwards the inclusive date window and returns an actionable invalid-date refusal', async (t) => {+ const { root, board } = fixture(t);+ const json = await run(root, ['stats', '--since', '2026-10-09', '--json']);+ assert.equal(json.code, 0, json.stderr);+ assert.deepEqual(json.data.stats, proofStats(board, { since: '2026-10-09' }));+ assert.equal(json.data.stats.submissions, 0);+ assert.equal(json.data.stats.firstEventAt, null);+ const bad = await run(root, ['stats', '--since', '2026-02-30', '--json']);+ assert.equal(bad.code, 1);+ assert.equal(bad.data.version, 1);+ assert.equal(bad.data.error.code, 'BAD_SINCE');+ assert.match(bad.data.error.next, /--since 2026-10-08/u);+ const help = await run(root, ['stats', '--help']);+ assert.equal(help.code, 0);+ assert.match(help.stdout, /--since <date>/u);+ });++ /** Exercise authenticated state from the same private board used by the command checks. */+ test('[R1,R2,A2] local HTTP state exposes exactly the command statistics', async (t) => {+ const { root, board } = fixture(t);+ const api = await serveApi({ runCommand: main, projects: () => [{ root, name: 'Statistics fixture' }] });+ t.after(() => api.close());+ const url = new URL(api.url);+ const headers = { 'x-pullboard-key': url.searchParams.get('k') };+ const response = await fetchFresh(`${url.origin}/api/v1/boards/${store.boardId(board)}/state`, { headers });+ assert.equal(response.status, 200);+ const document = await response.json();+ const command = await run(root, ['stats', '--json']);+ assert.equal(command.code, 0, command.stderr);+ assert.equal(document.version, 1);+ assert.deepEqual(document.state.proofStats, command.data.stats);+ });