Skip to content

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.

feat(spec): guard approved row rewrites [S19,V3]

Corey Olson89b0ef31ad39
diff --git a/docs/api.md b/docs/api.md
index 0438641f..f7361e5e 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -19,7 +19,7 @@ A successful command returns the fields listed below. `version` is always the nu
| `hooks` | `version:number`, `notes:array` |
| `join` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string` |
| `worktree` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `branch:string`, `prompt:string` |
-| `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `dirty:number`, `next: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` |
| `lanes` | `version:number`, `lanes:object`, `shared:array`, `coordinator:string` |
| `resources` | `version:number`, `resources:array` |
@@ -153,6 +153,10 @@ Decision moves keep the CLI's routing: `shout` with `args.decision: true` may om
Only the coordinator runs `spec apply`. It preflights every pending row against the exact source text, refusing stale decisions before writing any file. Approval changes the status to `approved`; decline changes it to `wont` with the person's reason as the row text, preserving trailing fields. SSH-enabled approvals carry one signed `row-decision` receipt binding the file, source, replacement, decision, reason and row text. Apply copies that same receipt into `.pullboard/signoffs.jsonl`; it remains a current exact-text sign-off. Commit the changed files and receipts together.
+To approve new wording, the person uses `spec approve <one-id> --text "exact proposed text"`, or `spec-approve` with `args: {ids: "G1", text: "exact proposed text"}`. This records the same exact-row receipt; files wait for coordinator apply. Text must be one nonempty line without a field separator. Pre-commit checks the staged row against that person decision or a verified staged SSH sign-off; unstaged receipts cannot authorize a commit.
+
+Doctor and resume report every stale frozen item after cited text changes. Open, claimed and submitted items suggest coordinator refreeze. Verified and merged items keep their receipts, report that they shipped against the old text, and suggest adding a follow-up citing the changed row. Resume JSON includes these findings in `stale`.
+
The SQLite schema marker is now `PRAGMA user_version = 2`. Opening an older board upgrades it in place: `board_meta` stores the id as `meta_key = "board_id"` and a 32-character hexadecimal `meta_value`; `shout_request` and `shout_request_outcome` mark requests and their answers. Existing items, agents and events remain intact. The HTTP envelope stays at version 1 independently of the SQLite schema marker.
A request body is `{text}`. It creates a request from the person to the coordinator. Open requests stay first in coordinator `resume` and `inbox` until answered `done`, or `declined` with a reason, and do not count as open decisions.
diff --git a/docs/formats.md b/docs/formats.md
index 5ab67f80..64273d86 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -261,6 +261,8 @@ Person answer events additionally record their `channel`, either `terminal` or `
Person row decisions use one `row_decision` event per row. Its `record` holds `kind` (`spec` or `doctrine`), file, id, exact source and replacement lines, target text, decision, reason and identity. SSH approvals additionally hold the canonical signature and trust anchors. The current index is additive `board_meta` key `row_decisions`; each entry includes its event id, timestamp and applied state. Coordinator `row_apply` events name the exact decision event ids applied locally. Replica replay changes board metadata only and never writes checkout files.
+An approval of proposed new wording uses that same record: `source` is the existing exact line and `replacement` carries the approved target text. Pre-commit compares the staged target against the person decision or a verified staged signed receipt. No second approval format or event kind is needed.
+
Migration preserves event rows and adds only schema objects that are missing.
The schema, trigger and parser tables in this guide are checked against live `openBoard(':memory:')` and `parseSpec` results by `docs/formats.test.js`.
diff --git a/src/api.js b/src/api.js
index c6068e28..171cae77 100644
--- a/src/api.js
+++ b/src/api.js
@@ -82,7 +82,7 @@ function agentPath(root, name = COORDINATOR) {
/** Declarative CLI forms keep API calls on the same argument parser and engine as terminal moves. */
const MOVES = {
- 'spec-approve': { prefix: ['spec', 'approve'], positions: ['ids'], flags: ['by'] },
+ 'spec-approve': { prefix: ['spec', 'approve'], positions: ['ids'], flags: ['by', 'text'] },
'spec-decline': { prefix: ['spec', 'decline'], positions: ['ids'], flags: ['reason'] },
add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'] },
edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'] },
diff --git a/src/approved-rows.js b/src/approved-rows.js
new file mode 100644
index 00000000..b8be8b1a
--- /dev/null
+++ b/src/approved-rows.js
@@ -0,0 +1,104 @@
+/** Person approval guards staged approved-row rewrites and exposes stale frozen items [S19,V3]. */
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { spawnSync } from 'node:child_process';
+import { parseSpec, SIGNOFFS_FILE } from './spec.js';
+import { rowDecisions } from './board.js';
+import { hasSignerFile, verifySignedRecords } from './signature.js';
+import { Refused } from './refused.js';
+
+const TRUST_FILES = ['.pullboard/signers', '.pullboard/first-commit', '.pullboard/signers.initial', SIGNOFFS_FILE];
+
+/** Read exact Git object bytes rather than an unrelated unstaged working copy. */
+function gitText(root, revision, file) {
+ const result = spawnSync('git', ['--no-replace-objects', 'show', `${revision}:${file}`], { cwd: root, encoding: 'utf8' });
+ return result.status === 0 ? result.stdout : null;
+}
+
+/** Read the shared decision index without opening the board's migrator or changing its evidence. */
+function boardApprovals(file) {
+ if (!file || !existsSync(file)) return [];
+ const db = new DatabaseSync(file, { readOnly: true });
+ try { return rowDecisions({ db }); }
+ finally { db.close(); }
+}
+
+/** Verify staged receipts using staged trust files anchored to the already committed opt-in. */
+function stagedApprovals(root, decisions) {
+ const snapshot = mkdtempSync(join(tmpdir(), 'pullboard-staged-approval-'));
+ try {
+ mkdirSync(join(snapshot, '.pullboard'));
+ for (const file of TRUST_FILES) {
+ const staged = gitText(root, '', file);
+ const before = gitText(root, 'HEAD', file);
+ if (before !== null && (file.endsWith('/first-commit') || file.endsWith('/signers.initial')) && staged !== before) {
+ throw new Refused('APPROVED_ROW_CHANGE', `${file} cannot change the established SSH trust anchor; restore its committed bytes`);
+ }
+ if (file.endsWith('/signers') && before !== null && staged === null) throw new Refused('APPROVED_ROW_CHANGE', 'SSH signers cannot be removed to bypass person approval; restore .pullboard/signers');
+ if (staged !== null) writeFileSync(join(snapshot, file), staged);
+ }
+ const ledger = gitText(root, '', SIGNOFFS_FILE);
+ const records = ledger?.split('\n').filter((line) => line.trim()).map(JSON.parse) ?? [];
+ const signed = decisions.filter((record) => record.signature);
+ verifySignedRecords(snapshot, [...records, ...signed]);
+ const enabled = hasSignerFile(snapshot);
+ return { records: enabled ? records.filter((record) => record.signature) : [], signed: enabled };
+ } finally { rmSync(snapshot, { recursive: true, force: true }); }
+}
+
+/** Refuse each rewritten approved row unless its exact staged target has person authorization. */
+export function approvedRowProblems(root, config, boardFile) {
+ const changes = [];
+ for (const [kind, file] of [['spec', config.spec], ['doctrine', config.practice]]) {
+ const before = gitText(root, 'HEAD', file);
+ const staged = gitText(root, '', file);
+ if (before === null || staged === null || before === staged) continue;
+ const rows = parseSpec(staged);
+ for (const old of parseSpec(before).rows.filter((row) => row.status === 'approved')) {
+ const matches = rows.rows.filter((row) => row.id === old.id);
+ if (matches.length !== 1 || matches[0].text === old.text) continue;
+ changes.push({ kind, file, row: matches[0], target: staged.split(/\r?\n/u)[matches[0].line - 1] });
+ }
+ }
+ if (!changes.length) return [];
+ try {
+ const decisions = boardApprovals(boardFile);
+ const trust = stagedApprovals(root, decisions);
+ return changes.filter(({ kind, file, row, target }) => {
+ const approved = decisions.some((record) => record.kind === kind && record.id === row.id && record.file === file
+ && record.replacement === target && record.text === row.text && (!trust.signed || record.decision === 'decline' || record.signature));
+ const signed = trust.records.some((record) => record.id === row.id && record.text === row.text
+ && (record.type === 'row-decision' ? record.kind === kind && record.file === file : kind === 'spec'));
+ return !approved && !signed;
+ }).map(({ kind, file, row }) => `${file}: ${row.id} changes approved text without the person's exact approval; ask the person to approve ${kind === 'doctrine' ? 'doctrine:' : ''}${row.id} in pullboard view or sign its new text, then stage the signed receipt`);
+ } catch (error) {
+ return [`approved-row authorization cannot be checked: ${error.message}; restore valid staged SSH trust files and signed receipts before committing`];
+ }
+}
+
+/** List every frozen item whose cited row text has changed, retaining historical accepted receipts. */
+export function staleFrozenItems(items, rows) {
+ const current = new Map(rows.map((row) => [row.id, row.text]));
+ return items.flatMap((item) => {
+ if (!item.item_frozen) return [];
+ const frozen = JSON.parse(item.item_frozen);
+ const changed = (frozen.rows ?? []).filter((row) => current.get(row.id) !== row.text).map((row) => row.id);
+ return changed.length ? [{ id: item.item_id, lane: item.item_lane, status: item.item_status, merged: !!item.item_merged_commit, rows: changed }] : [];
+ });
+}
+
+/** Explain repair without changing a historical verdict or pretending closed items can refreeze. */
+export function staleItemFinding(item) {
+ const rows = item.rows.join(', ');
+ const active = ['open', 'claimed', 'submitted'].includes(item.status);
+ const message = item.status === 'verified' || item.merged
+ ? `item #${item.id} shipped against the old text of ${rows}`
+ : `item #${item.id} (${item.status}) is stale: frozen against the old text of ${rows}`;
+ const title = `Bring #${item.id} in line with ${rows}'s new text`;
+ const quoted = `'${title.replaceAll("'", "'\\''")}'`;
+ const next = active ? `ask the coordinator to run pullboard refreeze ${item.id}`
+ : `ask the coordinator for a follow-up: pullboard add ${item.lane} ${quoted} --specs ${item.rows.join(',')}`;
+ return { code: 'STALE_ITEM', message, next };
+}
diff --git a/src/cli.js b/src/cli.js
index 17fc1407..31bd706e 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -54,6 +54,7 @@ import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { exportView, serveView } from './serve.js';
import { serveApi } from './api.js';
import { doctorProblems } from './doctor.js';
+import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots } from './trusted-policy.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
@@ -155,6 +156,7 @@ Spec
pullboard spec signers add [--key <path>] [--by <principal>] opt into SSH-signed sign-offs
principal defaults to Git user.email; --by overrides it
pullboard spec approve <ids> | decline <ids> --reason "why" the person's exact-row decision
+ approve <id> --text "new wording" approves an exact rewrite
pullboard spec apply coordinator applies recorded row decisions to the files
Role guides
@@ -186,6 +188,7 @@ const OPTIONS = {
after: { type: 'string' },
brief: { type: 'string' },
'brief-file': { type: 'string' },
+ text: { type: 'string' },
route: { type: 'string' },
family: { type: 'string' },
as: { type: 'string' },
@@ -670,6 +673,7 @@ function resumeHere(io) {
};
});
const { me } = card;
+ card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows).map((item) => ({ ...item, ...staleItemFinding(item) }));
const say = (line) => io.say(line);
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}`);
@@ -693,6 +697,7 @@ function resumeHere(io) {
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'}`);
}
+ 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(', ')}`);
@@ -1089,7 +1094,7 @@ function readCommands(io, { first, second, rest, values }) {
return 1;
}
const ctx = context(io);
- const problems = doctorProblems(ctx.file, ctx.info.root, tryGit);
+ const problems = doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config);
io.result?.({ problems });
if (!problems.length) {
io.say('board is clean');
@@ -1730,7 +1735,7 @@ async function specCommand(io, { first, second, rest, values }) {
unmet: ['must'],
signoff: ['by', 'note', 'note-file'],
signers: ['key', 'by'],
- approve: ['by'],
+ approve: ['by', 'text'],
decline: ['reason'],
apply: [],
}[first ?? '--json'];
@@ -1752,7 +1757,7 @@ async function specCommand(io, { first, second, rest, values }) {
const me = whoAmI(ctx, board);
if (!ctx.info.isMain || me.id !== COORDINATOR) throw new Refused('B26_PERSON_APPROVAL', 'only the person from the main checkout approves or declines rows; use pullboard view for the person to decide');
const ids = [second, ...rest].filter(Boolean).flatMap((text) => text.split(/[\s,]+/u)).filter(Boolean);
- const records = prepareRowDecisions(ctx.info.root, ctx.config, { ids, decision: first, reason: values.reason, by: values.by, on: new Date().toISOString(), commit: headCommit(ctx.info.root) ?? '' });
+ const records = prepareRowDecisions(ctx.info.root, ctx.config, { ids, decision: first, reason: values.reason, text: values.text, by: values.by, on: new Date().toISOString(), commit: headCommit(ctx.info.root) ?? '' });
const decisions = await ordered(ctx, board, 'recordRowDecisions', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal', decisions: records }]);
io.result?.({ decisions });
decisions.forEach((record) => io.say(`${record.kind === 'doctrine' ? 'doctrine:' : ''}${record.id}: ${first === 'approve' ? 'approved' : 'declined'}, pending apply`));
@@ -1931,7 +1936,7 @@ async function hookCommand(io, { first, second }) {
if (first === 'pre-commit') {
applyFixers(info.root, ctx.config.fix).forEach((note) => io.err(`pullboard pre-commit: ${note}`));
const agent = info.isMain ? null : withBoard(ctx, (board) => store.agentAt(board, info.root));
- problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent });
+ problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent, boardFile: ctx.file });
} else if (first === 'commit-msg') {
const message = readFileSync(second ?? '', 'utf8');
problems = commitMsgProblems(message, { rules: ctx.config.commits, spec: loadSpec(info.root, ctx.config) });
diff --git a/src/doctor.js b/src/doctor.js
index a96efca7..de5c3959 100644
--- a/src/doctor.js
+++ b/src/doctor.js
@@ -5,6 +5,8 @@ import { checkAtCommit, submissionPaths, dependencySnapshots } from './trusted-p
import { BLANKS, STATES, storeTriggers } from './machine.js';
import { readEventLogVersion, SCHEMA_VERSION } from './board.js';
+import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
+import { loadSpec } from './spec.js';
const blankCharacters = new Set(BLANKS.map((point) => String.fromCodePoint(point)));
/**
@@ -14,9 +16,10 @@ const blankCharacters = new Set(BLANKS.map((point) => String.fromCodePoint(point
* @param {string} file
* @param {string} root
* @param {(root: string, args: string[]) => { status: number, stdout: string }} tryGit
+ * @param {any} [config] - Compare frozen rows with this checkout's current source when supplied.
* @returns {{ code: string, message: string, next: string }[]}
*/
-export function doctorProblems(file, root, tryGit) {
+export function doctorProblems(file, root, tryGit, config) {
if (!existsSync(file)) return [finding('BOARD_MISSING', 'board file is missing', 'run pullboard status to create a new board')];
const db = new DatabaseSync(file, { readOnly: true });
try {
@@ -35,6 +38,7 @@ export function doctorProblems(file, root, tryGit) {
...(layout.itemPins ? pinProblems(db, root, tryGit) : []),
...(layout.verdicts ? verdictProblems(db, root, tryGit) : []),
...(layout.itemAudit ? submissionProblems(db, root) : []),
+ ...(layout.itemAudit && config ? staleFrozenItems(db.prepare('SELECT * FROM item ORDER BY item_id').all(), loadSpec(root, config).rows).map(staleItemFinding) : []),
];
} finally {
db.close();
diff --git a/src/hooks.js b/src/hooks.js
index 593e3f35..2b21f24a 100644
--- a/src/hooks.js
+++ b/src/hooks.js
@@ -9,6 +9,7 @@ import { join } from 'node:path';
import { git, gitChildEnv, tryGit } from './git.js';
import { outOfLane } from './lanes.js';
import { citedIds, deletedIds, idProblems } from './spec.js';
+import { approvedRowProblems } from './approved-rows.js';
export const HOOKS = ['pre-commit', 'commit-msg', 'pre-push'];
export const HOOKS_DIR = '.githooks';
@@ -195,10 +196,10 @@ export function blockedPaths(paths, protect) {
* changes outside its folders. The main checkout is the coordinator's and may change anything; any
* other worktree must have joined a lane.
*
- * @param {{ root: string, isMain: boolean, config: any, agent: any }} context
+ * @param {{ root: string, isMain: boolean, config: any, agent: any, boardFile?: string }} context
* @returns {string[]}
*/
-export function preCommitProblems({ root, isMain, config, agent }) {
+export function preCommitProblems({ root, isMain, config, agent, boardFile }) {
const { touched, written } = stagedPaths(root);
const problems = blockedPaths(written, config.protect).map(
(path) => `${path} is a blocked file (env or secrets); keep it out of git`,
@@ -208,6 +209,7 @@ export function preCommitProblems({ root, isMain, config, agent }) {
problems.push(...secretsIn(addedLines(diff)).map((where) => `possible secret: ${where}`));
}
problems.push(...deletedRowProblems(root, [config.spec, config.practice]));
+ problems.push(...approvedRowProblems(root, config, boardFile));
if (isMain) return problems;
if (!agent) {
problems.push('this worktree has not joined a lane: pullboard join <lane>');
diff --git a/src/json.js b/src/json.js
index 3e9a5b99..dc33b0d0 100644
--- a/src/json.js
+++ b/src/json.js
@@ -15,7 +15,7 @@ export const JSON_SHAPES = {
hooks: shape({ notes: 'array' }),
join: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string' }),
worktree: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', branch: 'string', prompt: 'string' }),
- resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: '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' }),
lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),
resources: shape({ resources: 'array' }),
diff --git a/src/row-decisions.js b/src/row-decisions.js
index bee85e06..f45638c0 100644
--- a/src/row-decisions.js
+++ b/src/row-decisions.js
@@ -23,15 +23,16 @@ function decisionRows(root, config, ids) {
}
/** Capture all source text and signatures before recording any decision on the board. */
-export function prepareRowDecisions(root, config, { ids, decision, reason = '', by, on, commit = '' }) {
+export function prepareRowDecisions(root, config, { ids, decision, reason = '', text: proposedText, by, on, commit = '' }) {
if (!ids.length) throw new Refused('USAGE', 'name rows: pullboard spec approve <ids> or spec decline <ids> --reason "why"');
if (!['approve', 'decline'].includes(decision)) throw new Refused('ROW_DECISION', 'use pullboard spec approve or decline');
if (decision === 'decline' && (!reason.trim() || /[\r\n|]/u.test(reason))) throw new Refused('ROW_DECISION', 'a decline needs a one-line reason without a field separator; use --reason "why"');
+ if (proposedText !== undefined && (decision !== 'approve' || ids.length !== 1 || !proposedText.trim() || /[\r\n|]/u.test(proposedText))) throw new Refused('ROW_DECISION', 'approve one row with --text "exact one-line text", without a field separator');
const signed = decision === 'approve' && hasSignerFile(root);
const principal = by ?? (signed ? defaultPrincipal(root) : 'person');
return decisionRows(root, config, ids).map(({ kind, file, row, source }) => {
const status = decision === 'approve' ? 'approved' : 'wont';
- const text = decision === 'approve' ? row.text : reason.trim();
+ const text = decision === 'approve' ? proposedText?.trim() ?? row.text : reason.trim();
const replacement = source.replace(/\[([a-z]+)(,\s*[a-z]+)?\]/u, (_, old, tier = '') => `[${status}${tier}]`)
.replace(/(\]\s+)([^|]*)(?=\s*\||$)/u, (_, prefix, old) => `${prefix}${text}${old.match(/\s+$/u)?.[0] ?? ''}`);
const record = { version: 1, type: 'row-decision', kind, file, id: row.id, source, replacement, text, decision, reason: decision === 'decline' ? reason.trim() : '', by: principal, on, commit, note: '' };
diff --git a/test/approved-row-changes.test.js b/test/approved-row-changes.test.js
new file mode 100644
index 00000000..abfad66d
--- /dev/null
+++ b/test/approved-row-changes.test.js
@@ -0,0 +1,242 @@
+/** Approved-row edits need an exact person decision or staged SSH receipt [S19,V3]. */
+import assert from 'node:assert/strict';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+import { AGENT_SHELL_MARKERS } from '../src/person.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const TEMP_DIRS = [];
+const SPEC = `# Approved row edit fixture
+
+## G · Goals
+- G1 [approved, must] The existing approved promise. | gate: true | signers: CO
+- G2 [draft, aim] A draft promise that can be refined.
+- G3 [approved, must] An unaffected approved promise. | gate: true
+`;
+
+/** Delete every private repo, key and home created by this file. */
+function cleanup() {
+ for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });
+}
+
+after(cleanup);
+
+/** Remove ambient Git selectors and agent-shell identity markers from fixture children. */
+function isolatedEnvironment(source) {
+ const env = { ...source };
+ for (const name of Object.keys(env)) {
+ if (name.startsWith('GIT_') || AGENT_SHELL_MARKERS.includes(name)) delete env[name];
+ }
+ return env;
+}
+
+/** Quote one shell argument for the private Git hook executable. */
+function shellWord(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
+
+/** Create a private repo, initialized board, installed hooks and real committed SPEC rows. */
+function fixture(t, { signer = false, doctrine = false } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-approved-row-'));
+ TEMP_DIRS.push(dir);
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const root = join(dir, 'repo');
+ const bin = join(dir, 'bin');
+ mkdirSync(root);
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);
+ chmodSync(join(bin, 'pullboard'), 0o755);
+ const env = {
+ ...isolatedEnvironment(process.env),
+ PATH: `${bin}:${process.env.PATH}`,
+ HOME: join(dir, 'home'),
+ PULLBOARD_HOME: join(dir, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ /** Run Git while preserving this fixture's local identity and the hook's active index. */
+ function git(...args) {
+ return execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: 'pipe' }).trim();
+ }
+ /** Run Pullboard in the fixture repo and retain both output streams for assertions. */
+ function pullboard(...args) {
+ return spawnSync(process.execPath, [BIN, ...args], { cwd: root, env, encoding: 'utf8', timeout: 20_000 });
+ }
+ git('init', '-q', '-b', 'main');
+ git('config', 'user.name', 'Approved-row fixture');
+ git('config', 'user.email', '[email protected]');
+ const initialized = pullboard('init');
+ assert.equal(initialized.status, 0, `${initialized.stdout}${initialized.stderr}`);
+ const configPath = join(root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, `${JSON.stringify({ ...config, gate: 'true', spec: 'SPEC.md' }, null, 2)}\n`);
+ writeFileSync(join(root, 'SPEC.md'), SPEC);
+ if (doctrine) writeFileSync(join(root, 'PRACTICE.md'), '# Local rules\n\n## L · Local\n- L1 [approved] Keep the local rule exact. | gate: true\n');
+ mkdirSync(join(root, 'test'));
+ writeFileSync(join(root, 'test', 'promise.test.js'), "import assert from 'node:assert/strict';\nimport { readFileSync } from 'node:fs';\nimport { test } from 'node:test';\ntest('approved promise remains documented [G1]', () => { assert.match(readFileSync('SPEC.md', 'utf8'), /G1 \\[approved/); });\n");
+ git('add', '-A');
+ const initial = spawnSync('git', ['commit', '-q', '-m', 'chore: initialize approved-row fixture'], { cwd: root, env, encoding: 'utf8', timeout: 20_000 });
+ assert.equal(initial.status, 0, `${initial.stdout}${initial.stderr}`);
+ if (signer) {
+ const key = join(dir, 'co-signing-key');
+ execFileSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', '[email protected]', '-f', key], { stdio: 'pipe' });
+ git('config', 'user.signingkey', key);
+ const added = pullboard('spec', 'signers', 'add', '--key', `${key}.pub`, '--by', 'CO');
+ assert.equal(added.status, 0, `${added.stdout}${added.stderr}`);
+ git('add', '.pullboard/signers', '.pullboard/first-commit', '.pullboard/signers.initial');
+ const trustCommit = commit({ root, env });
+ assert.equal(trustCommit.status, 0, `${trustCommit.stdout}${trustCommit.stderr}`);
+ }
+ return { dir, root, env, git, pullboard };
+}
+
+/** Replace one row's prose while preserving status, tier and every trailing field. */
+function setRowText(box, id, text) {
+ const file = join(box.root, 'SPEC.md');
+ const source = readFileSync(file, 'utf8');
+ const row = new RegExp(`^(- ${id} \\[[^\\]]+\\] )([^|\\n]*)(.*)$`, 'mu');
+ assert.match(source, row, `${id} exists in the fixture`);
+ writeFileSync(file, source.replace(row, (_, prefix, _oldText, fields) => `${prefix}${text}${fields ? ' ' : ''}${fields}`));
+}
+
+/** Attempt a real commit through the installed Pullboard pre-commit and commit-msg hooks. */
+function commit(box, subject = 'docs: update approved row') {
+ return spawnSync('git', ['commit', '-m', subject], { cwd: box.root, env: box.env, encoding: 'utf8', timeout: 30_000 });
+}
+
+/** Stage SPEC.md and any explicitly named supporting receipt files. */
+function stage(box, ...paths) {
+ box.git('add', '--', 'SPEC.md', ...paths);
+}
+
+test('[S19,V3] raw staged changes to an approved row are refused by the real commit hook', (t) => {
+ const box = fixture(t);
+ const before = box.git('rev-parse', 'HEAD');
+ setRowText(box, 'G1', 'A rewrite with no person approval.');
+ stage(box);
+ const refused = commit(box);
+ assert.notEqual(refused.status, 0, `${refused.stdout}${refused.stderr}`);
+ assert.match(`${refused.stdout}${refused.stderr}`, /G1 changes approved text.*person/iu);
+ assert.equal(box.git('rev-parse', 'HEAD'), before, 'the refused staged rewrite never becomes a commit');
+});
+
+test('[B26,S19,V3] exact board approval and decline apply authorize only their approved-row text changes', (t) => {
+ const box = fixture(t);
+ setRowText(box, 'G1', 'The person approved this exact replacement.');
+ const approved = box.pullboard('spec', 'approve', 'G1', '--json');
+ assert.equal(approved.status, 0, `${approved.stdout}${approved.stderr}`);
+ stage(box);
+ const accepted = commit(box, 'docs: apply person-approved wording');
+ assert.equal(accepted.status, 0, `${accepted.stdout}${accepted.stderr}`);
+
+ const declined = box.pullboard('spec', 'decline', 'G1', '--reason', 'The promise is no longer required.', '--json');
+ assert.equal(declined.status, 0, `${declined.stdout}${declined.stderr}`);
+ const applied = box.pullboard('spec', 'apply', '--json');
+ assert.equal(applied.status, 0, `${applied.stdout}${applied.stderr}`);
+ stage(box);
+ const declinedCommit = commit(box, 'docs: apply person-declined wording');
+ assert.equal(declinedCommit.status, 0, `${declinedCommit.stdout}${declinedCommit.stderr}`);
+ assert.match(readFileSync(join(box.root, 'SPEC.md'), 'utf8'), /G1 \[wont, must\] The promise is no longer required\./u);
+});
+
+test('[S19] unchanged approved rows and draft-row wording remain committable', (t) => {
+ const box = fixture(t);
+ writeFileSync(join(box.root, 'notes.txt'), 'The approved row was not changed.\n');
+ box.git('add', 'notes.txt');
+ const unchanged = commit(box, 'docs: add unrelated notes');
+ assert.equal(unchanged.status, 0, `${unchanged.stdout}${unchanged.stderr}`);
+
+ setRowText(box, 'G2', 'The person refined a draft before approval.');
+ stage(box);
+ const draft = commit(box, 'docs: refine draft row');
+ assert.equal(draft.status, 0, `${draft.stdout}${draft.stderr}`);
+});
+
+test('[S19,V3] an exact approval cannot authorize different staged bytes in a partial commit', (t) => {
+ const box = fixture(t);
+ setRowText(box, 'G1', 'The person approved these exact bytes.');
+ const approved = box.pullboard('spec', 'approve', 'G1', '--json');
+ assert.equal(approved.status, 0, `${approved.stdout}${approved.stderr}`);
+
+ setRowText(box, 'G1', 'Different text is staged instead.');
+ stage(box);
+ setRowText(box, 'G1', 'The person approved these exact bytes.');
+ const refused = commit(box);
+ assert.notEqual(refused.status, 0, `${refused.stdout}${refused.stderr}`);
+ assert.match(`${refused.stdout}${refused.stderr}`, /G1 changes approved text.*person/iu);
+ assert.match(box.git('show', ':SPEC.md'), /Different text is staged instead\./u, 'the unauthorized text is in the index');
+ assert.match(readFileSync(join(box.root, 'SPEC.md'), 'utf8'), /The person approved these exact bytes\./u, 'the different worktree text must not mask staged bytes');
+});
+
+test('[S18,S19,S20] pre-commit validates the staged SSH receipt and staged signer trust, not worktree substitutes', (t) => {
+ const box = fixture(t, { signer: true });
+ setRowText(box, 'G1', 'The signed person-approved wording.');
+ const signed = box.pullboard('spec', 'signoff', 'G1', '--by', 'CO', '--json');
+ assert.equal(signed.status, 0, `${signed.stdout}${signed.stderr}`);
+ const ledger = join(box.root, '.pullboard', 'signoffs.jsonl');
+ const validReceipt = readFileSync(ledger, 'utf8');
+
+ box.git('add', 'SPEC.md');
+ const unstaged = commit(box, 'docs: use unstaged signoff');
+ assert.notEqual(unstaged.status, 0, `${unstaged.stdout}${unstaged.stderr}`);
+
+ const tampered = validReceipt.split('\n').filter(Boolean).map(JSON.parse).map((record) => ({ ...record, on: `${record.on} forged` }));
+ writeFileSync(ledger, `${tampered.map((record) => JSON.stringify(record)).join('\n')}\n`);
+ box.git('add', '.pullboard/signoffs.jsonl');
+ writeFileSync(ledger, validReceipt);
+ const stagedTamper = commit(box, 'docs: use forged staged signoff');
+ assert.notEqual(stagedTamper.status, 0, `${stagedTamper.stdout}${stagedTamper.stderr}`);
+ assert.match(`${stagedTamper.stdout}${stagedTamper.stderr}`, /BAD_SIGNATURE|signature|sign-?off/iu);
+
+ box.git('add', '.pullboard/signoffs.jsonl');
+ writeFileSync(join(box.root, '.pullboard', 'signers'), 'untrusted unstaged signer\n');
+ const verifiedStaged = commit(box, 'docs: use valid staged signoff');
+ assert.equal(verifiedStaged.status, 0, `${verifiedStaged.stdout}${verifiedStaged.stderr}`);
+ assert.equal(box.git('show', 'HEAD:.pullboard/signers'), box.git('show', 'HEAD^:.pullboard/signers'), 'the valid committed trust list came from the index');
+});
+
+test('[B26,S18,S19] proposed SSH-approved wording and person-declined wording commit through one decision record', (t) => {
+ const box = fixture(t, { signer: true });
+ const before = readFileSync(join(box.root, 'SPEC.md'), 'utf8');
+ const text = 'The exact signed replacement the person approved.';
+ const approved = box.pullboard('spec', 'approve', 'G1', '--text', text, '--by', 'CO', '--json');
+ assert.equal(approved.status, 0, `${approved.stdout}${approved.stderr}`);
+ const record = JSON.parse(approved.stdout).decisions[0];
+ assert.ok(record.signature);
+ assert.equal(record.type, 'row-decision');
+ assert.equal(record.text, text);
+ assert.equal(readFileSync(join(box.root, 'SPEC.md'), 'utf8'), before);
+ assert.equal(box.pullboard('spec', 'apply').status, 0);
+ stage(box, '.pullboard/signoffs.jsonl');
+ const accepted = commit(box, 'docs: apply exact signed row decision');
+ assert.equal(accepted.status, 0, `${accepted.stdout}${accepted.stderr}`);
+ const declined = box.pullboard('spec', 'decline', 'G1', '--reason', 'The person declined this promise.');
+ assert.equal(declined.status, 0, `${declined.stdout}${declined.stderr}`);
+ assert.equal(box.pullboard('spec', 'apply').status, 0);
+ stage(box);
+ const declinedCommit = commit(box, 'docs: apply signed-repo person decline');
+ assert.equal(declinedCommit.status, 0, `${declinedCommit.stdout}${declinedCommit.stderr}`);
+});
+
+test('[S19] repo doctrine approved text has the same exact person-approval commit guard', (t) => {
+ const box = fixture(t, { doctrine: true });
+ const file = join(box.root, 'PRACTICE.md');
+ const before = readFileSync(file, 'utf8');
+ writeFileSync(file, before.replace('Keep the local rule exact.', 'An unauthorized local rule.'));
+ box.git('add', 'PRACTICE.md');
+ const refused = commit(box);
+ assert.notEqual(refused.status, 0);
+ assert.match(`${refused.stdout}${refused.stderr}`, /L1 changes approved text.*person/u);
+ writeFileSync(file, before);
+ box.git('add', 'PRACTICE.md');
+ const approved = box.pullboard('spec', 'approve', 'doctrine:L1', '--text', 'The exact approved local rule.');
+ assert.equal(approved.status, 0, `${approved.stdout}${approved.stderr}`);
+ assert.equal(box.pullboard('spec', 'apply').status, 0);
+ box.git('add', 'PRACTICE.md');
+ const accepted = commit(box, 'docs: apply person-approved local rule');
+ assert.equal(accepted.status, 0, `${accepted.stdout}${accepted.stderr}`);
+});
diff --git a/test/e2e.test.js b/test/e2e.test.js
index 8d040607..55fc3a82 100644
--- a/test/e2e.test.js
+++ b/test/e2e.test.js
@@ -640,6 +640,7 @@ test('verify runs at the submitted commit, against the criterion frozen at claim
assert.match(box.run(box.repo, 'verify', '1', 'accept', '--as', 'coordinator').err, /NOT_AT_COMMIT/);
box.git(box.repo, 'merge', '-q', '--ff-only', 'web/one');
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');
assert.match(box.run(box.repo, 'verify', '1', 'accept', '--as', 'coordinator').err, /CRITERIA_CHANGED/);
assert.match(box.run(box.repo, 'refreeze', '1').out, /refrozen/);
@@ -1325,6 +1326,7 @@ test('submit refuses a bar that moved since the claim, before any verifier runs;
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]');
diff --git a/test/row-decisions.test.js b/test/row-decisions.test.js
index ffc89ad8..fae12dec 100644
--- a/test/row-decisions.test.js
+++ b/test/row-decisions.test.js
@@ -356,3 +356,36 @@ test('[B26,S18,S19] signer-required approval signs the exact applied row and tam
}
writeFileSync(ledger, original);
});
+
+test('[B26,S19,V3] a view approval binds proposed wording without changing the source before apply', async function approvedRewrite(t) {
+ const box = project();
+ const file = join(box.root, SPEC_FILE);
+ const before = readFileSync(file, 'utf8');
+ const text = 'The person approved this exact revised promise.';
+ const request = await startView(t, box);
+ const boardPath = await viewBoardPath(request, box.root);
+ const events = eventCount(box);
+ for (const args of [{ ids: 'G1 G3', text }, { ids: 'G3', text: '' }, { ids: 'G3', text: 'two\nlines' }, { ids: 'G3', text: 'text | gate: changed' }]) {
+ const response = await request(`${boardPath}/moves`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ verb: 'spec-approve', agent: 'coordinator', args }),
+ });
+ assert.equal(response.status, 409, 'proposed wording needs one valid exact text and one row');
+ assert.equal((await response.json()).error.code, 'ROW_DECISION');
+ assert.equal(eventCount(box), events, 'invalid text writes no person-decision event');
+ assert.equal(readFileSync(file, 'utf8'), before, 'invalid proposed text never changes source');
+ }
+ await viewDecision(request, boardPath, 'spec-approve', { ids: 'G3', text });
+ assert.equal(readFileSync(file, 'utf8'), before, 'the API decision writes no source bytes');
+ const state = await (await request(`${boardPath}/state`)).json();
+ const row = state.state.spec.find((entry) => entry.id === 'G3');
+ assert.equal(row.text, 'Keep this unaffected row.');
+ assert.equal(row.decision.text, text, 'the one existing decision record binds the proposed target');
+ assert.equal(row.stage, 'approved, pending apply');
+ const apply = command(box, box.root, 'spec', 'apply');
+ assert.equal(apply.status, 0, `${apply.stdout}${apply.stderr}`);
+ assert.equal(sourceRow(box, SPEC_FILE, 'G3').text, text);
+ box.git(box.root, 'add', SPEC_FILE);
+ box.git(box.root, 'commit', '-q', '-m', 'docs: apply the person-approved rewrite');
+ assert.ok(box.git(box.root, 'show', 'HEAD:SPEC.md').includes(text), 'the exact view-approved rewrite passes the real commit hook');
+});
diff --git a/test/stale-frozen-items.test.js b/test/stale-frozen-items.test.js
new file mode 100644
index 00000000..56f607d9
--- /dev/null
+++ b/test/stale-frozen-items.test.js
@@ -0,0 +1,230 @@
+/** Approved row edits identify every affected frozen item without rewriting receipts [S19,V3]. */
+import assert from 'node:assert/strict';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+import { DatabaseSync } from 'node:sqlite';
+import { AGENT_SHELL_MARKERS } from '../src/person.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const TEMP_DIRS = [];
+const OLD_SPEC = `# Stale frozen fixture
+
+## G · Goals
+- G1 [approved, must] The current promise. | gate: true
+- G3 [approved, must] An unaffected promise. | gate: true
+`;
+const NEW_TEXT = 'The person approved this exact updated promise.';
+
+/** Remove each private repo, board and home created by this file. */
+function cleanup() {
+ for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });
+}
+
+after(cleanup);
+
+/** Quote one shell argument for the fixture's private hook executable. */
+function shellWord(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
+
+/** Build a private real-Git project with an initialized board, active hooks and a web worktree. */
+function project(t) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-stale-frozen-'));
+ TEMP_DIRS.push(dir);
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const root = join(dir, 'repo');
+ const web = join(dir, 'web');
+ const bin = join(dir, 'bin');
+ mkdirSync(root);
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);
+ chmodSync(join(bin, 'pullboard'), 0o755);
+ const env = { ...process.env };
+ for (const name of Object.keys(env)) if (name.startsWith('GIT_') || AGENT_SHELL_MARKERS.includes(name)) delete env[name];
+ Object.assign(env, {
+ PATH: `${bin}:${process.env.PATH}`,
+ HOME: join(dir, 'home'),
+ PULLBOARD_HOME: join(dir, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ });
+ /** Run a bounded real Pullboard CLI process in one fixture checkout. */
+ function pullboard(cwd, ...args) {
+ return spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 30_000 });
+ }
+ /** Run real Git with isolated identity while preserving hook-provided index variables. */
+ function git(cwd, ...args) {
+ return execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
+ }
+ git(root, 'init', '-q', '-b', 'main');
+ git(root, 'config', 'user.name', 'Stale-frozen fixture');
+ git(root, 'config', 'user.email', '[email protected]');
+ const initialized = pullboard(root, 'init');
+ assert.equal(initialized.status, 0, `${initialized.stdout}${initialized.stderr}`);
+ writeFileSync(join(root, 'pullboard.json'), `${JSON.stringify({
+ gate: 'true', spec: 'SPEC.md', verify: 'coordinator', lease: '2h',
+ lanes: { web: { owns: ['web/'], specs: ['G1', 'G3'] } }, shared: [],
+ }, null, 2)}\n`);
+ writeFileSync(join(root, 'SPEC.md'), OLD_SPEC);
+ mkdirSync(join(root, 'web'));
+ git(root, 'add', '-A');
+ const initial = spawnSync('git', ['commit', '-q', '-m', 'chore: initialize stale-frozen fixture'], { cwd: root, env, encoding: 'utf8', timeout: 30_000 });
+ assert.equal(initial.status, 0, `${initial.stdout}${initial.stderr}`);
+ git(root, 'worktree', 'add', '-q', web, '-b', 'web/stale-frozen');
+ const joined = pullboard(web, 'join', 'web');
+ assert.equal(joined.status, 0, `${joined.stdout}${joined.stderr}`);
+ return { dir, root, web, env, git, pullboard };
+}
+
+/** Create a real item that cites one frozen row and return its persisted id. */
+function addItem(box, title, specId = 'G1') {
+ const result = box.pullboard(box.root, 'add', 'web', title, '--criterion', `Check ${title}.`, '--specs', specId, '--json');
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ return JSON.parse(result.stdout).item.item_id;
+}
+
+/** Run a CLI command and require its successful result. */
+function succeeds(box, cwd, ...args) {
+ const result = box.pullboard(cwd, ...args);
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ return result;
+}
+
+/** Freeze an item's cited text by claiming it in the real agent worktree. */
+function claim(box, id) {
+ succeeds(box, box.web, 'claim', String(id));
+}
+
+/** Make, submit and return a real lane commit for an item. */
+function submit(box, id, name) {
+ claim(box, id);
+ const relative = `web/${name}.txt`;
+ mkdirSync(join(box.web, 'web'), { recursive: true });
+ writeFileSync(join(box.web, relative), `${name}\n`);
+ box.git(box.web, 'add', relative);
+ const committed = spawnSync('git', ['commit', '-m', `feat(web): build ${name} [G1]`], { cwd: box.web, env: box.env, encoding: 'utf8', timeout: 30_000 });
+ assert.equal(committed.status, 0, `${committed.stdout}${committed.stderr}`);
+ const head = box.git(box.web, 'rev-parse', 'HEAD');
+ succeeds(box, box.web, 'submit', String(id));
+ return head;
+}
+
+/** Verify a submitted private fixture commit as the coordinator without touching any real board. */
+function accept(box, id, commit) {
+ box.git(box.root, 'switch', '--detach', commit);
+ succeeds(box, box.root, 'verify', String(id), 'accept', '--as', 'coordinator', '--note', 'checked the private fixture commit');
+ box.git(box.root, 'switch', 'main');
+}
+
+/** Read item and verdict receipts without opening or migrating the board. */
+function receiptSnapshot(box) {
+ const common = box.git(box.root, 'rev-parse', '--path-format=absolute', '--git-common-dir');
+ const file = join(common, 'pullboard', 'board.sqlite');
+ const db = new DatabaseSync(file, { readOnly: true });
+ try {
+ return {
+ items: db.prepare('SELECT item_id, item_status, item_frozen, item_frozen_digest, item_verdict, item_commit, item_merged_commit FROM item ORDER BY item_id').all(),
+ verdicts: db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all(),
+ };
+ } finally { db.close(); }
+}
+
+/** Read the underlying SQLite bytes to prove doctor did not repair or rewrite board evidence. */
+function boardBytes(box) {
+ const common = box.git(box.root, 'rev-parse', '--path-format=absolute', '--git-common-dir');
+ return readFileSync(join(common, 'pullboard', 'board.sqlite'));
+}
+
+test('[S19,V3] doctor and resume list stale frozen items in every lifecycle state without rewriting evidence', { timeout: 120_000 }, (t) => {
+ const box = project(t);
+ const ids = {};
+
+ ids.open = addItem(box, 'Open stale item');
+ claim(box, ids.open);
+ succeeds(box, box.web, 'release', String(ids.open));
+
+ ids.submitted = addItem(box, 'Submitted stale item');
+ submit(box, ids.submitted, 'submitted');
+
+ ids.verified = addItem(box, 'Verified stale item');
+ const verifiedCommit = submit(box, ids.verified, 'verified');
+ accept(box, ids.verified, verifiedCommit);
+
+ ids.merged = addItem(box, 'Merged stale item');
+ const mergedCommit = submit(box, ids.merged, 'merged');
+ accept(box, ids.merged, mergedCommit);
+ box.git(box.root, 'merge', '--no-edit', mergedCommit);
+ succeeds(box, box.root, 'merged', String(ids.merged), box.git(box.root, 'rev-parse', 'HEAD'));
+
+ ids.withdrawn = addItem(box, 'Withdrawn stale item');
+ claim(box, ids.withdrawn);
+ succeeds(box, box.web, 'release', String(ids.withdrawn));
+ succeeds(box, box.root, 'withdraw', String(ids.withdrawn), 'no longer needed');
+
+ ids.unaffected = addItem(box, 'Unaffected G3 item', 'G3');
+ claim(box, ids.unaffected);
+ succeeds(box, box.web, 'release', String(ids.unaffected));
+
+ ids.claimed = addItem(box, 'Claimed stale item');
+ claim(box, ids.claimed);
+
+ const decision = box.pullboard(box.root, 'spec', 'approve', 'G1', '--text', NEW_TEXT, '--json');
+ assert.equal(decision.status, 0, `${decision.stdout}${decision.stderr}`);
+ succeeds(box, box.root, 'spec', 'apply', '--json');
+ box.git(box.root, 'add', 'SPEC.md');
+ const appliedCommit = spawnSync('git', ['commit', '-m', 'docs: update approved G1 wording [G1]'], { cwd: box.root, env: box.env, encoding: 'utf8', timeout: 30_000 });
+ assert.equal(appliedCommit.status, 0, `${appliedCommit.stdout}${appliedCommit.stderr}`);
+ assert.ok(readFileSync(join(box.root, 'SPEC.md'), 'utf8').includes(NEW_TEXT));
+
+ const expected = [ids.open, ids.claimed, ids.submitted, ids.verified, ids.merged, ids.withdrawn].sort((a, b) => a - b);
+ const statuses = new Map([
+ [ids.open, 'open'], [ids.claimed, 'claimed'], [ids.submitted, 'submitted'],
+ [ids.verified, 'verified'], [ids.merged, 'verified'], [ids.withdrawn, 'withdrawn'],
+ ]);
+ const before = receiptSnapshot(box);
+ const bytesBeforeDoctor = boardBytes(box);
+
+ const doctorJson = box.pullboard(box.root, 'doctor', '--json');
+ assert.notEqual(doctorJson.status, 0, doctorJson.stderr || doctorJson.stdout);
+ const doctorDocument = JSON.parse(doctorJson.stdout);
+ const findings = doctorDocument.problems.filter((problem) => problem.code === 'STALE_ITEM');
+ assert.deepEqual(findings.map((finding) => Number(/item #(\d+)/u.exec(finding.message)?.[1])).sort((a, b) => a - b), expected);
+ for (const finding of findings) {
+ const id = Number(/item #(\d+)/u.exec(finding.message)?.[1]);
+ if (['open', 'claimed', 'submitted'].includes(statuses.get(id))) assert.match(finding.next, new RegExp(`pullboard refreeze ${id}\\b`));
+ else if (['verified', 'merged'].includes(statuses.get(id))) {
+ assert.match(finding.message, new RegExp(`item #${id} shipped against the old text of G1`));
+ assert.match(finding.next, /pullboard add web .*--specs G1/u);
+ }
+ }
+ assert.deepEqual(boardBytes(box), bytesBeforeDoctor, 'doctor did not write or migrate any board bytes');
+
+ const doctorText = box.pullboard(box.root, 'doctor');
+ assert.equal(doctorText.status, 1, doctorText.stderr || doctorText.stdout);
+ for (const id of expected) assert.match(doctorText.stdout, new RegExp(`item #${id}\\b`));
+ const afterResumeBaseline = receiptSnapshot(box);
+ const resumeJson = succeeds(box, box.root, 'resume', '--json');
+ const resumeDocument = JSON.parse(resumeJson.stdout);
+ assert.deepEqual(resumeDocument.stale.map((item) => item.id).sort((a, b) => a - b), expected);
+ for (const item of resumeDocument.stale) {
+ if (['open', 'claimed', 'submitted'].includes(item.status)) assert.match(item.next, new RegExp(`pullboard refreeze ${item.id}\\b`));
+ else if (['verified', 'merged'].includes(item.status)) {
+ assert.match(item.message, new RegExp(`item #${item.id} shipped against the old text of G1`));
+ assert.match(item.next, /pullboard add web .*--specs G1/u);
+ }
+ }
+ const resumeText = succeeds(box, box.root, 'resume');
+ for (const id of expected) assert.match(resumeText.stdout, new RegExp(`item #${id}\\b`));
+ assert.deepEqual(receiptSnapshot(box), afterResumeBaseline, 'resume leaves frozen fields, merge receipts and accepted verdicts unchanged');
+ assert.deepEqual(receiptSnapshot(box), before, 'diagnostics do not alter accepted receipts or frozen bars');
+ assert.ok(!findings.some((finding) => finding.message.includes(`item #${ids.unaffected} `)), 'the item frozen on G3 remains unaffected');
+ succeeds(box, box.root, 'refreeze', String(ids.open));
+ const afterRefreeze = JSON.parse(succeeds(box, box.root, 'resume', '--json').stdout);
+ assert.deepEqual(afterRefreeze.stale.map((item) => item.id).sort((a, b) => a - b), expected.filter((id) => id !== ids.open), 'explicit refreeze clears only the active item repaired against new text');
+ const historical = (snapshot) => snapshot.items.filter((item) => item.item_status === 'verified');
+ assert.deepEqual(historical(receiptSnapshot(box)), historical(before), 'refreezing active work preserves every accepted historical receipt');
+});