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(spec): record person row decisions before apply [B26,S18,S19]
Corey Olson542337588e3e
diff --git a/docs/api.md b/docs/api.mdindex f064965e..0438641f 100644--- a/docs/api.md+++ b/docs/api.md@@ -75,6 +75,9 @@ A successful command returns the fields listed below. `version` is always the nu| `spec unmet` | `version:number`, `rows:array` || `spec signoff` | `version:number`, `count:number`, `by:string`, `ids:array`, `evidence:array` || `spec signers` | `version:number`, `added:boolean`, `by:string`, `path:string`, `initial:boolean` |+| `spec approve` | `version:number`, `decisions:array` |+| `spec decline` | `version:number`, `decisions:array` |+| `spec apply` | `version:number`, `applied:array`, `files:array` || `hook pre-commit` | `version:number`, `messages:array` || `hook commit-msg` | `version:number`, `messages:array` || `hook pre-push` | `version:number`, `messages:array` |@@ -146,6 +149,10 @@ A move body is `{verb, item, args, agent}`. `item` is the positive integer id whDecision moves keep the CLI's routing: `shout` with `args.decision: true` may omit `args.to`; agents ask their coordinator, and the coordinator asks the person. `pass` takes the decision's id as `item` and `args.note`. Answering a decision addressed to the person requires `answer` with `args.as: "person"` from the coordinator's main checkout. Other callers receive the CLI's refusal.+`spec approve <ids>` and `spec decline <ids> --reason "why"` record the person's exact row decision without writing repo files. Bare ids name SPEC.md rows; `doctrine:<id>` names a repo doctrine row. These commands refuse agent shells and agent worktrees. The authenticated local view uses moves `spec-approve` with `args: {ids: "G1 G2", by: "<optional SSH principal>"}` or `spec-decline` with `args: {ids: "G1", reason: "why"}`, acting through the main checkout. Pending rows keep their source `status` and add `decision` and `stage` (`approved, pending apply` or `declined, pending apply`) in `spec show` and the shared view/API state.++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.+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.mdindex 6c941f30..5ab67f80 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -251,12 +251,16 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `shout` | sender | `shout`, `to`, `decision`, `request`, `answers` || `pass` | coordinator | `shout`, `to`, `decision`, `request`, `answers` || `answer` | answerer | `shout`, `to`, `decision`, `request`, `answers`, `outcome`, `channel` |+| `row_decision` | person | `record`, `channel` |+| `row_apply` | coordinator | `events` |<!-- events:end -->New CLI claims include a `policy` object (`version: 1`, `commit`) in the frozen criterion. It pins the coordinator checkout’s committed configuration on its attached main branch. A temporary detached review checkout refuses new policy-dependent claims or project gates with `NO_POLICY`; the coordinator returns to its main branch. Existing frozen submissions remain verifiable. Legacy claims use their recorded claim-base commit. A CLI `submit` records the pre-merge coordinator HEAD as optional `policyCommit`; historical doctor and acceptance checks use this snapshot when allowing unchanged foreign files brought in from MAIN. Verified dependencies may also contribute unchanged files in their own lanes before a MAIN merge; foreign deletion or replacement is not authorized by an unrelated dependency’s tree. The complete candidate diff against both claim base and frozen MAIN is checked with rename detection disabled, preserving deleted paths and whitespace in names. Frozen item checks run against the exact submitted commit in an isolated checkout when accepting and auditing; repairing a reviewer’s checkout cannot make a red submission green.Person answer events additionally record their `channel`, either `terminal` or `view`, including the forwarded answer to the original asker. Agent answers omit that field.+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.+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/docs/formats.test.js b/docs/formats.test.jsindex cd94bbea..a411d45f 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -25,6 +25,8 @@ import {passDecision,PERSON,recordAttempt,+ recordRowDecisions,+ applyRowDecisions,refreeze,register,release,@@ -152,6 +154,8 @@ function recordEventContract() {answerDecision(board, personQuestion, { agentId: coordinator, text: 'approved', lanes: ['docs', 'tests'], asPerson: true });const request = shout(board, { from: PERSON, to: coordinator, text: 'sample request', lanes: ['docs', 'tests'], request: true });answerDecision(board, request, { agentId: coordinator, text: 'done', lanes: ['docs', 'tests'] });+ const decisions = recordRowDecisions(board, { agentId: PERSON, channel: 'terminal', decisions: [{ kind: 'spec', file: 'SPEC.md', id: 'A1', source: '- A1 [draft] Exact row.', replacement: '- A1 [approved] Exact row.', text: 'Exact row.', decision: 'approve', reason: '' }] });+ applyRowDecisions(board, { agentId: coordinator, events: decisions.map((record) => record.event) });const freeze = (digest) => () => ({ text: `criterion-${digest}`, digest });const first = addItem(board, { by: coordinator, lane: 'docs', title: 'Accepted example', criterion: 'Initial', specIds: ['A1'], route: 'strong' });editItem(board, first, { agentId: coordinator, brief: 'Files: docs/formats.md\nTest: docs/formats.test.js', route: 'mid', criterion: 'Changed', check: 'node test' });@@ -182,7 +186,7 @@ function recordEventContract() {releaseLane(board, 'view', { agentId: coordinator });const rows = events(board).map((row) => ({ ...row, detail: JSON.parse(row.event_detail) }));closeBoard(board);- return { rows, actors: { [coordinator]: 'coordinator', [builder]: 'builder', [reviewer]: 'reviewer', board: 'board' } };+ return { rows, actors: { [coordinator]: 'coordinator', [builder]: 'builder', [reviewer]: 'reviewer', [PERSON]: 'person', board: 'board' } };}/** Reopen a file after removing old-format objects and report the repaired guard event. */diff --git a/src/api.js b/src/api.jsindex de32b846..c6068e28 100644--- a/src/api.js+++ b/src/api.js@@ -10,6 +10,7 @@ import { relayLinked, relayOperation } from './relay.js';import { laneNames } from './lanes.js';import { listApiProjects } from './projects.js';import { milestoneRoadmap } from './roadmap.js';+import { projectRowDecisions } from './row-decisions.js';import { Refused } from './refused.js';import { codeAt, projectState } from './serve.js';import { createApiHandler } from './api-http.js';@@ -81,6 +82,8 @@ 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-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'] },claim: { item: true },@@ -107,7 +110,7 @@ export function moveArgs({ verb, item, args = {} }) {if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Refused('BAD_REQUEST', 'args needs a JSON object containing this move\'s arguments');const allowed = [...(form.positions ?? []), ...(form.flags ?? []), ...(form.booleans ?? [])];for (const key of Object.keys(args)) if (!allowed.includes(key)) throw new Refused('BAD_REQUEST', `${verb} does not take args.${key}; use only this CLI move's arguments`);- const argv = [verb];+ const argv = form.prefix ? [...form.prefix] : [verb];if (form.item) {if (!Number.isSafeInteger(item) || item < 1) throw new Refused('BAD_REQUEST', `${verb} needs a positive integer item; use the item id from the board state`);argv.push(String(item));@@ -195,14 +198,16 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =boards: () => apiBoardListing(projects),board: (id) => findBoard(id, projects),state: (board, who, seen) => {- const state = projectState(board.root, { seen });+ let state = projectState(board.root, { seen });state.board = board.id;const projectData = withBoard(board.root, (db) => ({requests: store.openRequests(db),milestones: milestoneRoadmap(board.root, db),+ rowDecisions: store.rowDecisions(db),}));state.requests = projectData.requests;state.milestones = projectData.milestones;+ state = projectRowDecisions(projectData.rowDecisions, state);return state;},code: (board, ref) => codeAt(board.root, ref),diff --git a/src/board.js b/src/board.jsindex afccd4f9..e70d8a75 100644--- a/src/board.js+++ b/src/board.js@@ -14,6 +14,7 @@ import { briefFiles, briefSections } from './brief.js';import { COORDINATOR } from './config.js';import { GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, effectiveGuards, storeTriggers } from './machine.js';import { Refused } from './refused.js';+import { parseSpec } from './spec.js';export const ACCEPT_REASON = 'CRITERION_MET';export const PERSON = 'person';@@ -1841,6 +1842,68 @@ export function removeMilestone(board, name, { agentId }) {});}+/** Current person decisions, including applied receipts, stored without checkout-dependent state. */+export function rowDecisions(board) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('row_decisions');+ return row ? JSON.parse(row.meta_value) : [];+}++/** Persist the current decision index inside its caller's board transaction. */+function writeRowDecisions(board, records) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')+ .run('row_decisions', JSON.stringify(records));+}++/** Record one exact-row decision per event; sender-side channel checks precede deterministic replay. */+export function recordRowDecisions(board, { agentId, channel, decisions }) {+ if (agentId !== PERSON) throw new Refused('B26_PERSON_APPROVAL', 'only the person approves or declines rows; use pullboard view for the person to decide');+ if (!['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_CHANNEL', 'row decisions use the terminal or the view; use pullboard view');+ if (!Array.isArray(decisions) || !decisions.length) throw new Refused('ROW_DECISION', 'name at least one row to approve or decline; use pullboard spec approve <ids>');+ const keys = new Set();+ for (const record of decisions) {+ if (!record || !['approve', 'decline'].includes(record.decision) || !['spec', 'doctrine'].includes(record.kind)+ || !['id', 'file', 'source', 'replacement', 'text'].every((key) => typeof record[key] === 'string' && record[key].trim())+ || (record.decision === 'decline' && !String(record.reason ?? '').trim())) throw new Refused('ROW_DECISION', 'a row decision needs its id, file and exact text; use pullboard spec approve or decline');+ const original = parseSpec(`## Decision\n${record.source}\n`).rows;+ const replacement = parseSpec(`## Decision\n${record.replacement}\n`).rows;+ const target = replacement[0];+ if (original.length !== 1 || original[0].id !== record.id || replacement.length !== 1 || target.id !== record.id+ || target.status !== (record.decision === 'approve' ? 'approved' : 'wont') || target.text !== record.text+ || (record.decision === 'decline' && target.text !== record.reason)) throw new Refused('ROW_DECISION', 'the exact row must match its recorded approval or decline; use pullboard spec approve or decline');+ const key = `${record.kind}:${record.id}`;+ if (keys.has(key)) throw new Refused('ROW_DECISION', `${key} is named twice; use each row once`);+ keys.add(key);+ }+ return atomic(board, () => {+ let current = rowDecisions(board);+ const recorded = decisions.map((record) => {+ logEvent(board, PERSON, 'row_decision', null, { record, channel });+ const entry = { ...record, event: board.lastEvent.event_id, at: board.lastEvent.event_at, applied: false };+ current = [...current.filter((old) => old.kind !== record.kind || old.id !== record.id), entry];+ return entry;+ });+ writeRowDecisions(board, current);+ return recorded;+ });+}++/** A coordinator records which exact decisions its local file changes applied, with no replay writes. */+export function applyRowDecisions(board, { agentId, events }) {+ if (agentId !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator applies row decisions; ask your coordinator to run pullboard spec apply');+ if (!Array.isArray(events) || events.some((event) => !Number.isSafeInteger(event) || event < 1)) throw new Refused('ROW_DECISION', 'apply needs current decision event ids; use pullboard spec apply');+ return atomic(board, () => {+ const records = rowDecisions(board);+ const found = events.map((event) => records.find((record) => record.event === event));+ if (found.some((record) => !record)) throw new Refused('STALE_ROW_DECISION', 'a row decision was replaced; use pullboard spec apply with the current decisions');+ const applied = found.filter((record) => !record.applied);+ if (!applied.length) return [];+ const at = now(board);+ writeRowDecisions(board, records.map((record) => events.includes(record.event) ? { ...record, applied: true, appliedAt: at } : record));+ logEvent(board, agentId, 'row_apply', null, { events: applied.map((record) => record.event) });+ return applied.map((record) => ({ ...record, applied: true, appliedAt: at }));+ });+}+/*** The newest unread shouts, without marking them read: `resume` shows them, `inbox` reads them.*diff --git a/src/cli.js b/src/cli.jsindex eab7aeb5..87e78241 100644--- a/src/cli.js+++ b/src/cli.js@@ -12,6 +12,7 @@ import * as store from './board.js';import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';import { loadDoctrine } from './doctrine.js';import { requirePersonChannel } from './person.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 {@@ -153,6 +154,8 @@ Specsignoff: --note "what was checked" stays with the receiptpullboard spec signers add [--key <path>] [--by <principal>] opt into SSH-signed sign-offsprincipal defaults to Git user.email; --by overrides it+ pullboard spec approve <ids> | decline <ids> --reason "why" the person's exact-row decision+ pullboard spec apply coordinator applies recorded row decisions to the filesRole guidespullboard prompt decompose|plan|signoff|review|verify how to do each role; Claude Code gets them as skills@@ -1709,13 +1712,13 @@ function specProof(ctx) {}/**- * The spec commands: JSON rows, check, view, show, unmet, signoff.+ * The spec commands: reads, sign-offs and person decisions applied by the coordinator.** @param {any} io* @param {any} args- * @returns {number}+ * @returns {Promise<number>}*/-function specCommand(io, { first, second, rest, values }) {+async function specCommand(io, { first, second, rest, values }) {const ctx = context(io);const commandFlags = {'--json': ['json'],@@ -1725,8 +1728,11 @@ function specCommand(io, { first, second, rest, values }) {unmet: ['must'],signoff: ['by', 'note', 'note-file'],signers: ['key', 'by'],+ approve: ['by'],+ decline: ['reason'],+ apply: [],}[first ?? '--json'];- if (!commandFlags) throw new Refused('USAGE', 'use pullboard spec --json | check | view | show <id> | unmet [--must] | signoff <ids> --by <name> [--note "..."]');+ if (!commandFlags) throw new Refused('USAGE', 'use pullboard spec --json | check | view | show <id> | unmet [--must] | signoff <ids> | approve <ids> | decline <ids> --reason "why" | apply');const allowedFlags = [...new Set([...commandFlags, 'json'])];for (const flag of Object.keys(values)) {if (!allowedFlags.includes(flag)) {@@ -1738,6 +1744,36 @@ function specCommand(io, { first, second, rest, values }) {if (!spec.exists) throw new Refused('NO_SPEC', `no ${ctx.config.spec}; run: pullboard init`);const practice = ctx.doctrine;const signoffs = readSignoffs(ctx.info.root);+ if (first === 'approve' || first === 'decline') {+ requirePersonChannel(io.personChannel);+ return withBoard(ctx, async (board) => {+ 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 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`));+ return 0;+ });+ }+ if (first === 'apply') {+ if (second || rest.length) throw new Refused('USAGE', 'pullboard spec apply takes no ids; it applies current person decisions');+ return withBoard(ctx, async (board) => {+ const me = whoAmI(ctx, board);+ if (!ctx.info.isMain || me.id !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator applies row decisions; ask your coordinator to run pullboard spec apply');+ const plan = planRowApply(ctx.info.root, ctx.config, store.rowDecisions(board));+ writeRowApply(ctx.info.root, plan);+ let applied;+ try { applied = await ordered(ctx, board, 'applyRowDecisions', [{ agentId: me.id, events: plan.records.map((record) => record.event) }]); }+ catch (error) { restoreRowApply(ctx.info.root, plan); throw error; }+ io.result?.({ applied, files: plan.files.map((file) => file.file) });+ applied.forEach((record) => io.say(`${record.file}: ${record.id} ${record.decision === 'approve' ? 'approved' : 'wont'}${record.reason ? `: ${record.reason}` : ''}`));+ if (!applied.length) io.say('no pending row decisions');+ else io.say('stage and commit the changed row files and any .pullboard/signoffs.jsonl receipts');+ return 0;+ });+ }if (first === 'check' || first === undefined) {const files = [[ctx.config.spec, spec], ...(practice.exists ? [[ctx.config.practice, practice]] : [])];for (const [, parsed] of files) assertRequiredSigners(ctx.info.root, parsed.rows);@@ -1795,11 +1831,16 @@ function specCommand(io, { first, second, rest, values }) {return 0;}if (first === 'show') {- const row = spec.rows.find((entry) => entry.id === second);+ const doctrineId = second?.startsWith('doctrine:');+ const parsed = doctrineId ? practice : spec;+ const id = doctrineId ? second.slice('doctrine:'.length) : second;+ const source = parsed.rows.find((entry) => entry.id === id);+ const row = source && withBoard(ctx, (board) => decisionProjection(store.rowDecisions(board), source, doctrineId ? 'doctrine' : 'spec'));if (!row) throw new Refused('NO_ROW', `no row ${second ?? ''} in ${ctx.config.spec}`);- const standing = standings(spec.rows, signoffs).get(row.id) ?? { met: [], stale: [] };+ const standing = standings(parsed.rows, signoffs).get(row.id) ?? { met: [], stale: [] };io.result?.({ row, standing });io.say(`${row.id} [${row.status}${row.tier ? `, ${row.tier}` : ''}] ${row.text}`);+ if (row.stage) io.say(row.stage);if (row.gate) io.say(`gate: ${row.gate}`);if (row.serves.length) io.say(`serves: ${row.serves.join(', ')}`);io.say(`signed: ${standing.met.map((entry) => `${entry.by} ${entry.on}`).join(', ') || 'no'}${standing.stale.length ? `; stale: ${standing.stale.length}` : ''}`);@@ -1839,7 +1880,7 @@ function specCommand(io, { first, second, rest, values }) {io.say(`signed ${count} rows as ${by}; commit .pullboard/signoffs.jsonl`);return 0;}- throw new Refused('USAGE', 'pullboard spec --json | check | view | show <id> | unmet [--must] | signoff <ids> [--by <principal>] | signers add');+ throw new Refused('USAGE', 'pullboard spec --json | check | view | show <id> | unmet [--must] | signoff <ids> | signers add | approve <ids> | decline <ids> --reason "why" | apply');}/** Read one consent line without waiting for EOF in an interactive terminal [V2]. */@@ -1957,7 +1998,7 @@ async function runCommand(argv, io) {io.say(`forgot ${root}`);return 0;}- if (command === 'spec') return specCommand(io, args);+ if (command === 'spec') return await specCommand(io, args);if (command === 'prompt') {let root = io.cwd;try {diff --git a/src/engine.js b/src/engine.jsindex 1307b828..7829cc77 100644--- a/src/engine.js+++ b/src/engine.js@@ -11,6 +11,7 @@ export const ENGINE_OPERATIONS = Object.freeze(['claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'merged','withdraw', 'refreeze', 'shout', 'passDecision', 'answerDecision', 'holdLane', 'releaseLane','addMilestone', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone',+ 'recordRowDecisions', 'applyRowDecisions',]);/** Read a replica's committed prefix without trusting an independently saved transport cursor. */diff --git a/src/json.js b/src/json.jsindex db039c59..3e9a5b99 100644--- a/src/json.js+++ b/src/json.js@@ -71,6 +71,9 @@ export const JSON_SHAPES = {'spec unmet': shape({ rows: 'array' }),'spec signoff': shape({ count: 'number', by: 'string', ids: 'array', evidence: 'array' }),'spec signers': shape({ added: 'boolean', by: 'string', path: 'string', initial: 'boolean' }),+ 'spec approve': shape({ decisions: 'array' }),+ 'spec decline': shape({ decisions: 'array' }),+ 'spec apply': shape({ applied: 'array', files: 'array' }),'hook pre-commit': shape({ messages: 'array' }),'hook commit-msg': shape({ messages: 'array' }),'hook pre-push': shape({ messages: 'array' }),diff --git a/src/row-decisions.js b/src/row-decisions.jsnew file mode 100644index 00000000..bee85e06--- /dev/null+++ b/src/row-decisions.js@@ -0,0 +1,119 @@+/** Exact person row decisions and coordinator file application [B26,S18,S19]. */+import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { loadDoctrine } from './doctrine.js';+import { loadSpec, SIGNOFFS_FILE } from './spec.js';+import { defaultPrincipal, hasSignerFile, signRowDecision, verifyRowDecision } from './signature.js';+import { Refused } from './refused.js';++/** Resolve qualified doctrine ids while bare ids continue to name the spec. */+function decisionRows(root, config, ids) {+ const spec = loadSpec(root, config);+ const doctrine = loadDoctrine(root, config);+ return ids.map((reference) => {+ const kind = reference.startsWith('doctrine:') ? 'doctrine' : 'spec';+ const id = kind === 'doctrine' ? reference.slice('doctrine:'.length) : reference;+ const parsed = kind === 'doctrine' ? doctrine.repo : spec;+ const matches = parsed.rows.filter((row) => row.id === id);+ if (matches.length !== 1) throw new Refused('NO_ROW', `${reference} names ${matches.length} repo rows; use one id from ${parsed.name}`);+ const file = kind === 'doctrine' ? doctrine.name : config.spec;+ const source = readFileSync(join(root, file), 'utf8').split(/\r?\n/u)[matches[0].line - 1];+ return { kind, file, row: matches[0], source };+ });+}++/** Capture all source text and signatures before recording any decision on the board. */+export function prepareRowDecisions(root, config, { ids, decision, reason = '', 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"');+ 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 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: '' };+ return signed ? signRowDecision(root, record) : record;+ });+}++/** Compare a decision with the current row, excluding inherited standard rows from file edits. */+export function pendingRowDecision(records, row, kind) {+ return records.find((record) => record.kind === kind && record.id === row.id && !record.applied+ && (row.text === record.text || row.text === record.source.match(/\]\s+([^|]*)(?:\||$)/u)?.[1]?.trim()));+}++/** Add pending status to existing rows without replacing their current file-backed status. */+export function decisionProjection(records, row, kind) {+ const decision = pendingRowDecision(records, row, kind);+ return decision ? { ...row, decision, stage: `${decision.decision === 'approve' ? 'approved' : 'declined'}, pending apply` } : row;+}++/** Decorate the shared API state so the cockpit receives the same pending decisions as spec show. */+export function projectRowDecisions(records, state) {+ return { ...state,+ spec: state.spec.map((row) => decisionProjection(records, row, 'spec')),+ practice: state.practice.map((row) => row.origin === 'standard' ? row : decisionProjection(records, row, 'doctrine')),+ };+}++/** Remove local index metadata while retaining the one canonical person receipt verbatim. */+function decisionReceipt({ event, at, applied, appliedAt, ...record }) { return record; }++/** Preflight every file and signature before an apply writes even its first byte. */+export function planRowApply(root, config, records) {+ const pending = records.filter((record) => !record.applied);+ const files = new Map();+ for (const record of pending) {+ verifyRowDecision(root, record);+ const file = record.kind === 'spec' ? config.spec : loadDoctrine(root, config).name;+ const aliases = new Set(['DOCTRINE.md', 'PRACTICE.md']);+ if (file !== record.file && !(record.kind === 'doctrine' && aliases.has(file) && aliases.has(record.file))) throw new Refused('STALE_ROW_DECISION', `${record.id}'s file changed; ask the person to approve its current row again`);+ if (!files.has(file)) files.set(file, { file, before: readFileSync(join(root, file), 'utf8') });+ const change = files.get(file);+ const lines = (change.after ?? change.before).split('\n');+ const parsed = loadSpec(root, { ...config, spec: file });+ const matches = parsed.rows.filter((row) => row.id === record.id);+ const index = matches.length === 1 ? matches[0].line - 1 : -1;+ const source = index < 0 ? '' : lines[index].replace(/\r$/u, '');+ if (source !== record.source && source !== record.replacement) throw new Refused('STALE_ROW_DECISION', `${record.id}'s exact row changed after the person's decision; ask the person to approve its current text again`);+ lines[index] = `${record.replacement}${lines[index].endsWith('\r') ? '\r' : ''}`;+ change.after = lines.join('\n');+ }+ const signoffPath = join(root, SIGNOFFS_FILE);+ const before = existsSync(signoffPath) ? readFileSync(signoffPath, 'utf8') : null;+ const previous = before?.split('\n').filter(Boolean).map(JSON.parse) ?? [];+ const receipts = pending.filter((record) => record.signature).map(decisionReceipt)+ .filter((record) => !previous.some((old) => old.signature === record.signature));+ return { records: pending, files: [...files.values()].filter((file) => file.after !== file.before), signoffs: { before, receipts } };+}++/** Apply preflighted file changes, restoring earlier writes if a later filesystem write fails. */+export function writeRowApply(root, plan) {+ const written = [];+ try {+ for (const file of plan.files) {+ writeFileSync(join(root, file.file), file.after);+ written.push(file);+ }+ if (plan.signoffs.receipts.length) {+ const file = join(root, SIGNOFFS_FILE);+ mkdirSync(dirname(file), { recursive: true });+ appendFileSync(file, `${plan.signoffs.before && !plan.signoffs.before.endsWith('\n') ? '\n' : ''}${plan.signoffs.receipts.map((record) => JSON.stringify(record)).join('\n')}\n`);+ }+ } catch (error) {+ restoreRowApply(root, { ...plan, files: written });+ throw error;+ }+}++/** Undo this apply's file writes when its board move or a later filesystem operation refuses. */+export function restoreRowApply(root, plan) {+ for (const file of [...plan.files].reverse()) writeFileSync(join(root, file.file), file.before);+ if (!plan.signoffs.receipts.length) return;+ const file = join(root, SIGNOFFS_FILE);+ if (plan.signoffs.before === null) rmSync(file, { force: true });+ else writeFileSync(file, plan.signoffs.before);+}diff --git a/src/signature.js b/src/signature.jsindex 48fe6718..5ad0fd1b 100644--- a/src/signature.js+++ b/src/signature.js@@ -130,6 +130,9 @@ function readInitialSignerHash(root) {/** Serialize canonical signed content with stable field order. */export function canonical(record) {+ if (record.type === 'row-decision') {+ return JSON.stringify({ version: 1, type: record.type, firstCommit: record.firstCommit, initialHash: record.initialHash, id: record.id, file: record.file, kind: record.kind, source: record.source, replacement: record.replacement, text: record.text, decision: record.decision, reason: record.reason, commit: record.commit, by: record.by, on: record.on, note: record.note ?? '' });+ }if (record.type === 'signers') {return JSON.stringify({ version: 1, type: record.type, firstCommit: record.firstCommit, initialHash: record.initialHash, previousHash: record.previousHash, previousSigners: record.previousSigners, hash: record.hash, by: record.by, on: record.on });}@@ -284,6 +287,24 @@ export function signRows(root, records, requestedKey) {return signed;}+/** Sign an exact person decision without writing a receipt into the checkout before apply. */+export function signRowDecision(root, fields, requestedKey) {+ const allowed = readSignerText(root);+ verifySignedRecords(root, readRawRecords(root));+ if (!listsPrincipal(allowed, fields.by)) throw new Refused('UNLISTED_SIGNER', `${fields.by} is not listed in ${SIGNERS_FILE}`);+ if (!fields.commit) throw new Refused('NO_SIGNING_COMMIT', 'signed approvals include the commit read; commit or check out the repo first');+ const record = { version: 1, type: 'row-decision', firstCommit: readFirstCommit(root), initialHash: readInitialSignerHash(root), ...fields };+ record.signature = makeSignature(root, record, requestedKey);+ verifySignature(record, allowed);+ return record;+}++/** Validate a board-held approval against this checkout's established SSH trust history. */+export function verifyRowDecision(root, record) {+ if (record.decision === 'approve' && hasSignerFile(root) && !record.signature) throw new Refused('MISSING_SIGNATURE', `${record.id} approval needs the person's signed sign-off; use pullboard spec approve again`);+ verifySignedRecords(root, [...readRawRecords(root), ...(record.signature ? [record] : [])]);+}+/** Use Git's exact email as the allowed-signers principal; `--by` explicitly overrides it. */export function defaultPrincipal(root) {const email = gitSetting(root, 'user.email');diff --git a/test/api.test.js b/test/api.test.jsindex 84454066..41c5b0ee 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -571,6 +571,9 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>json(source, source.repo, 'milestone', ['edit', 'Catalog', '--name', 'Release', '--note', 'Catalog coverage'], 'edit');json(source, source.repo, 'milestone', ['remove', 'Later'], 'remove');json(source, source.repo, 'milestone', ['remove', 'Release'], 'remove');+ json(source, source.repo, 'spec', ['approve', 'G1'], 'approve');+ json(source, source.repo, 'spec', ['decline', 'G1', '--reason', 'Catalog decline'], 'decline');+ json(source, source.repo, 'spec', ['apply'], 'apply');const missing = Object.keys(JSON_SHAPES.commands).filter((key) => !covered.has(key));assert.deepEqual(missing, [], `add real-repo invocations for undocumented coverage gaps: ${missing.join(', ')}`);assert.deepEqual([...coveredRoots].sort(), resultCommands(), 'every actual root/factory command has an invocation');diff --git a/test/row-decisions-replay.test.js b/test/row-decisions-replay.test.jsnew file mode 100644index 00000000..c735516b--- /dev/null+++ b/test/row-decisions-replay.test.js@@ -0,0 +1,117 @@+/** Real-SQLite replay tests for person row decisions and coordinator apply receipts [B26,H3,H16,S18,S19]. */+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, 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 { exportBoard, importBoard } from '../src/exchange.js';+import { appliedSequence, applyEngineMove, engineReceipt, prepareEngineMove } from '../src/engine.js';+import { AGENT_SHELL_MARKERS } from '../src/person.js';++const RECORDED_AT = '2026-10-08T18:00:00.000Z';+const APPLIED_AT = '2026-10-08T18:01:00.000Z';++const DECISIONS = [+ {+ kind: 'spec', file: 'SPEC.md', id: 'G1',+ source: '- G1 [draft, must] Approve this row. | gate: test/row-decisions.test.js',+ replacement: '- G1 [approved, must] Approve this row. | gate: test/row-decisions.test.js',+ text: 'Approve this row.', decision: 'approve', reason: '',+ },+ {+ kind: 'doctrine', file: 'DOCTRINE.md', id: 'L1',+ source: '- L1 [draft] Decline this rule. | gate: review',+ replacement: '- L1 [wont] The person declined. | gate: review',+ text: 'The person declined.', decision: 'decline', reason: 'The person declined.',+ },+];++/** Open a source board and two native SQLite replicas with divergent ambient clocks. */+function decisionCopies(t) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-row-decision-replay-'));+ const source = store.openBoard(join(directory, 'source.sqlite'), { now: () => new Date('2026-10-08T12:00:00.000Z') });+ store.register(source, { lane: 'coordinator', path: '/fixture' });+ store.register(source, { lane: 'web', path: '/fixture/web-1' });+ store.addItem(source, { by: 'coordinator', lane: 'web', title: 'Unchanged fixture item' });+ const initial = exportBoard(source);+ const copies = ['person-shell', 'plain-shell'].map((name, index) => {+ const clock = { now: () => new Date(`2026-10-08T${index + 14}:00:00.000Z`) };+ const board = store.openBoard(join(directory, `${name}.sqlite`), clock);+ importBoard(board, initial);+ return board;+ });+ t.after(() => {+ for (const board of copies) store.closeBoard(board);+ store.closeBoard(source);+ rmSync(directory, { recursive: true, force: true });+ });+ return { directory, source, copies };+}++/** Apply one captured operation to each replica while their process environments differ. */+function replayWithDifferentShells(one, two, move, sequence, at) {+ const original = AGENT_SHELL_MARKERS.map((name) => [name, process.env[name]]);+ try {+ for (const name of AGENT_SHELL_MARKERS) process.env[name] = 'fixture-agent';+ const first = applyEngineMove(one, move, { sequence, at });+ for (const name of AGENT_SHELL_MARKERS) delete process.env[name];+ const second = applyEngineMove(two, move, { sequence, at });+ assert.deepEqual(first, second, 'replicas ignore sender shell markers and use the sealed operation');+ return first;+ } finally {+ for (const [name, value] of original) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ }+}++test('captured person decisions and coordinator apply replay identically without touching checkout files [B26,H3,H16,S18,S19]', (t) => {+ const { directory, source, copies: [one, two] } = decisionCopies(t);+ const sentinel = join(directory, 'SPEC.md');+ writeFileSync(sentinel, 'leave this checkout file alone\n');+ const sentinelBefore = readFileSync(sentinel, 'utf8');++ const baseline = exportBoard(source);+ assert.throws(() => store.recordRowDecisions(source, {+ agentId: 'web-1', channel: 'view', decisions: DECISIONS,+ }), { code: 'B26_PERSON_APPROVAL' });+ assert.throws(() => store.applyRowDecisions(source, { agentId: 'web-1', events: [] }), { code: 'COORDINATOR_ONLY' });+ assert.throws(() => store.recordRowDecisions(source, {+ agentId: 'person', channel: 'view', decisions: [{ ...DECISIONS[0], source: DECISIONS[0].source.replace('G1', 'G9') }],+ }), { code: 'ROW_DECISION' });+ assert.throws(() => store.recordRowDecisions(source, {+ agentId: 'person', channel: 'view', decisions: [{ ...DECISIONS[0], replacement: DECISIONS[0].source }],+ }), { code: 'ROW_DECISION' });+ assert.deepEqual(exportBoard(source), baseline, 'actor and source/replacement refusals leave tables and metadata unchanged');++ const recordMove = prepareEngineMove(one, 'recordRowDecisions', [{+ agentId: 'person', channel: 'view', decisions: DECISIONS,+ }], { id: 'person-row-decisions' });+ const recorded = replayWithDifferentShells(one, two, recordMove, 1, RECORDED_AT);+ assert.equal(recorded.events.length, 2);+ assert.ok(recorded.events.every((event) => event.event_kind === 'row_decision' && event.event_by === 'person'));+ assert.ok(recorded.events.every((event) => event.event_at === RECORDED_AT));+ assert.deepEqual(store.rowDecisions(one).map(({ id, decision, applied }) => ({ id, decision, applied })), [+ { id: 'G1', decision: 'approve', applied: false },+ { id: 'L1', decision: 'decline', applied: false },+ ]);++ const eventIds = store.rowDecisions(one).map((record) => record.event);+ const applyMove = prepareEngineMove(one, 'applyRowDecisions', [{ agentId: 'coordinator', events: eventIds }], { id: 'apply-row-decisions' });+ const applied = replayWithDifferentShells(one, two, applyMove, 2, APPLIED_AT);+ assert.equal(applied.events.length, 1);+ assert.equal(applied.events[0].event_kind, 'row_apply');+ assert.equal(applied.events[0].event_at, APPLIED_AT);+ assert.ok(store.rowDecisions(one).every((record) => record.applied && record.appliedAt === APPLIED_AT));+ assert.deepEqual(engineReceipt(one, 'person-row-decisions'), engineReceipt(two, 'person-row-decisions'));+ assert.deepEqual(engineReceipt(one, 'apply-row-decisions'), engineReceipt(two, 'apply-row-decisions'));+ assert.equal(appliedSequence(one), 2);+ assert.equal(appliedSequence(two), 2);+ assert.deepEqual(exportBoard(one), exportBoard(two), 'complete native exports include tables, metadata and receipts');+ const complete = exportBoard(one);+ assert.deepEqual(applyEngineMove(one, applyMove, { sequence: 2, at: APPLIED_AT }), applied);+ assert.deepEqual(exportBoard(one), complete, 'an acknowledged apply retry appends no duplicate events');+ assert.equal(readFileSync(sentinel, 'utf8'), sentinelBefore, 'board-only engine operations never rewrite SPEC.md');+});diff --git a/test/row-decisions.test.js b/test/row-decisions.test.jsnew file mode 100644index 00000000..ffc89ad8--- /dev/null+++ b/test/row-decisions.test.js@@ -0,0 +1,358 @@+/** Person-authored row decisions stay on the board until a coordinator applies them [B26,S18,S19]. */+import assert from 'node:assert/strict';+import { execFileSync, spawn, spawnSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { once } from 'node:events';+import { after, test } from 'node:test';+import { parseSpec } from '../src/spec.js';+import { AGENT_SHELL_MARKERS } from '../src/person.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const SPEC_FILE = 'SPEC.md';+const DOCTRINE_FILE = 'DOCTRINE.md';+const TEMP_DIRS = [];+const BASE_SPEC = `# Row decision fixture++## G · Goals+- G1 [draft, must] Approve this row. | gate: true | serves: G3+- G2 [draft, aim] Decline this row. | gate: true+- G3 [approved, must] Keep this unaffected row. | gate: true+`;+const BASE_DOCTRINE = `# Repo doctrine++## L · Local+- L1 [draft] Approve this doctrine row. | gate: true+`;++/** Remove each private fixture after child processes have been stopped. */+function cleanup() {+ for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });+}++after(cleanup);++/** Remove inherited Git selectors and every recognized agent-shell marker from a copy. */+function personEnvironment(source) {+ const env = { ...source };+ for (const key of Object.keys(env)) {+ if (key.startsWith('GIT_') || AGENT_SHELL_MARKERS.includes(key)) delete env[key];+ }+ return env;+}++/** Quote one shell word for the private Pullboard hook shim. */+function shellWord(value) {+ return `'${String(value).replaceAll("'", "'\\''")}'`;+}++/** Build a private real-Git fixture with isolated user and machine homes. */+function sandbox() {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-row-decisions-'));+ TEMP_DIRS.push(dir);+ const bin = join(dir, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const env = personEnvironment({+ ...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',+ GIT_AUTHOR_NAME: 'Row decision fixture',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Row decision fixture',+ GIT_COMMITTER_EMAIL: '[email protected]',+ });+ /** Run Git with the fixture's private identity and configuration. */+ function git(cwd, ...args) {+ return execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();+ }+ /** Run the real CLI with a clean person environment and optional explicit markers. */+ function run(cwd, args, extraEnv = {}) {+ return spawnSync(process.execPath, [BIN, ...args], {+ cwd, env: { ...personEnvironment(env), ...extraEnv }, encoding: 'utf8', timeout: 15_000,+ });+ }+ return { dir, env, git, run };+}++/** Initialize and commit a real repo with SPEC, DOCTRINE, an SQLite board and private lanes. */+function project({ spec = BASE_SPEC, doctrine = BASE_DOCTRINE } = {}) {+ const box = sandbox();+ mkdirSync(join(box.dir, 'repo'));+ const root = realpathSync(join(box.dir, 'repo'));+ box.git(root, 'init', '-q', '-b', 'main');+ const initialized = box.run(root, ['init']);+ assert.equal(initialized.status, 0, `${initialized.stdout}${initialized.stderr}`);+ const configFile = join(root, 'pullboard.json');+ const config = JSON.parse(readFileSync(configFile, 'utf8'));+ writeFileSync(configFile, `${JSON.stringify({+ ...config,+ gate: 'true',+ spec: SPEC_FILE,+ practice: DOCTRINE_FILE,+ lanes: { web: { owns: ['web/'], specs: ['G'] }, review: { owns: [], specs: ['G'] } },+ shared: [],+ }, null, 2)}\n`);+ mkdirSync(join(root, 'web'));+ writeFileSync(join(root, SPEC_FILE), spec);+ writeFileSync(join(root, DOCTRINE_FILE), doctrine);+ box.git(root, 'add', '-A');+ box.git(root, 'commit', '-q', '-m', 'chore: set up row decision fixture');+ const fixture = { ...box, root };+ fixture.web = addWorktree(fixture, 'web', 'web/one');+ return fixture;+}++/** Create a real joined agent checkout so its identity cannot be inferred from a spoofable flag. */+function addWorktree(box, lane, branch) {+ const path = join(box.dir, lane);+ box.git(box.root, 'worktree', 'add', '-q', path, '-b', branch);+ const joined = box.run(path, ['join', lane]);+ assert.equal(joined.status, 0, `${joined.stdout}${joined.stderr}`);+ return path;+}++/** Run an ordinary terminal or agent CLI command with optional environment markers. */+function command(box, cwd, ...args) {+ const { extraEnv = {} } = args.at(-1) ?? {};+ const actualArgs = args.at(-1)?.extraEnv ? args.slice(0, -1) : args;+ return box.run(cwd, actualArgs, extraEnv);+}++/** Read the event count from the private SQLite file without opening or migrating the board. */+function eventCount(box) {+ const db = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });+ try { return db.prepare('SELECT COUNT(*) AS count FROM event').get().count; }+ finally { db.close(); }+}++/** Read and parse a row from the real project source file. */+function sourceRow(box, file, id) {+ const parsed = parseSpec(readFileSync(join(box.root, file), 'utf8'));+ const row = parsed.rows.find((entry) => entry.id === id);+ assert.ok(row, `${id} remains in ${file}`);+ return row;+}++/** Start the private real view with clean person credentials and expose authenticated requests. */+async function startView(t, box) {+ const child = spawn(process.execPath, [BIN, 'view', '--no-open', '--port', '0', '--json'], {+ cwd: box.root, env: { ...personEnvironment(box.env), CODEX_SHELL: 'private-agent-view-host' }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stdout = '';+ let stderr = '';+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8').on('data', (part) => { stderr += part; });+ const closed = once(child, 'close');+ t.after(async () => {+ if (child.exitCode !== null) return;+ child.kill('SIGTERM');+ let timer;+ await Promise.race([closed, new Promise((done) => {+ timer = setTimeout(() => { child.kill('SIGKILL'); done(); }, 5000);+ })]);+ clearTimeout(timer);+ });+ const document = await new Promise((resolveDocument, rejectDocument) => {+ const timer = setTimeout(() => rejectDocument(new Error(`view did not start: ${stderr}`)), 10_000);+ child.stdout.on('data', (chunk) => {+ stdout += chunk;+ try { resolveDocument(JSON.parse(stdout)); clearTimeout(timer); }+ catch { /* Wait until the one JSON document is complete. */ }+ });+ child.once('error', rejectDocument);+ child.once('close', () => rejectDocument(new Error(`view exited early: ${stderr}`)));+ });+ const address = new URL(document.url);+ const key = address.searchParams.get('k');+ assert.ok(key, 'the private view URL includes its one-use request credential');+ /** Send a bounded authenticated request to the live view adapter. */+ function request(path, options = {}) {+ return fetch(new URL(path, address.origin), {+ ...options,+ headers: { 'x-pullboard-key': key, ...options.headers },+ signal: AbortSignal.timeout(10_000),+ });+ }+ return request;+}++/** Find this fixture's board in the actual view API and return its stable route prefix. */+async function viewBoardPath(request, root) {+ const response = await request('/api/v1/boards');+ assert.equal(response.status, 200);+ const document = await response.json();+ const board = document.boards.find((entry) => entry.root === root);+ assert.ok(board, 'the initialized fixture appears in the actual view API');+ return `/api/v1/boards/${board.id}`;+}++/** Send one spec decision through the authenticated view move adapter. */+async function viewDecision(request, boardPath, verb, args) {+ const response = await request(`${boardPath}/moves`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ verb, agent: 'coordinator', args }),+ });+ assert.equal(response.status, 200, await response.clone().text());+ return response.json();+}++test('[B26,S18,S19] person decisions wait on the board until one apply preserves every other field', async function pendingThenApply(t) {+ const box = project();+ const specPath = join(box.root, SPEC_FILE);+ const doctrinePath = join(box.root, DOCTRINE_FILE);+ const beforeSpec = readFileSync(specPath, 'utf8');+ const beforeDoctrine = readFileSync(doctrinePath, 'utf8');+ const beforeEvents = eventCount(box);++ const request = await startView(t, box);+ const boardPath = await viewBoardPath(request, box.root);+ const identity = command(box, box.web, 'whoami', '--json');+ assert.equal(identity.status, 0, identity.stderr);+ const agentDecision = await request(`${boardPath}/moves`, {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ verb: 'spec-approve', agent: JSON.parse(identity.stdout).id, args: { ids: 'G1' } }),+ });+ assert.equal(agentDecision.status, 409, 'a named API agent cannot become the person');+ assert.equal((await agentDecision.json()).error.code, 'B26_PERSON_APPROVAL');+ await viewDecision(request, boardPath, 'spec-approve', { ids: 'G1' });+ const declined = command(box, box.root, 'spec', 'decline', 'G2', '--reason', 'not needed', '--json');+ assert.equal(declined.status, 0, `${declined.stdout}${declined.stderr}`);+ const doctrineApproval = command(box, box.root, 'spec', 'approve', 'doctrine:L1', '--json');+ assert.equal(doctrineApproval.status, 0, `${doctrineApproval.stdout}${doctrineApproval.stderr}`);+ assert.equal(readFileSync(specPath, 'utf8'), beforeSpec, 'approve and decline only append board decisions');+ assert.equal(readFileSync(doctrinePath, 'utf8'), beforeDoctrine, 'the doctrine source also waits for coordinator apply');+ assert.equal(eventCount(box), beforeEvents + 3, 'each decision is recorded as a board event');++ for (const [key, stage] of [['G1', 'approved, pending apply'], ['G2', 'declined, pending apply'], ['doctrine:L1', 'approved, pending apply']]) {+ const shown = command(box, box.root, 'spec', 'show', key, '--json');+ assert.equal(shown.status, 0, `${shown.stdout}${shown.stderr}`);+ const row = JSON.parse(shown.stdout).row;+ assert.ok(row.decision, `${key} includes the recorded decision`);+ assert.equal(row.stage, stage);+ }+ const stateResponse = await request(`${boardPath}/state`);+ assert.equal(stateResponse.status, 200);+ const state = await stateResponse.json();+ assert.equal(state.state.spec.find((row) => row.id === 'G1').stage, 'approved, pending apply');+ assert.equal(state.state.spec.find((row) => row.id === 'G2').stage, 'declined, pending apply');+ assert.equal(state.state.practice.find((row) => row.id === 'L1').stage, 'approved, pending apply');++ const applied = command(box, box.root, 'spec', 'apply', '--json');+ assert.equal(applied.status, 0, `${applied.stdout}${applied.stderr}`);+ const g1 = sourceRow(box, SPEC_FILE, 'G1');+ const g2 = sourceRow(box, SPEC_FILE, 'G2');+ const g3 = sourceRow(box, SPEC_FILE, 'G3');+ const l1 = sourceRow(box, DOCTRINE_FILE, 'L1');+ assert.equal(g1.status, 'approved');+ assert.equal(g1.tier, 'must');+ assert.equal(g1.gate, 'true');+ assert.deepEqual(g1.serves, ['G3']);+ assert.equal(g2.status, 'wont');+ assert.equal(g2.tier, 'aim');+ assert.equal(g2.gate, 'true');+ assert.match(g2.text, /not needed/u, 'the decline reason is recorded in the row text');+ assert.deepEqual(g3, { ...parseSpec(beforeSpec).rows.find((row) => row.id === 'G3') }, 'an unaffected row keeps every parsed field');+ assert.equal(l1.status, 'approved', 'coordinator apply also handles the repo doctrine file');+ const afterEvents = eventCount(box);+ const again = command(box, box.root, 'spec', 'apply', '--json');+ assert.equal(again.status, 0, again.stderr);+ assert.deepEqual(JSON.parse(again.stdout).applied, []);+ assert.equal(eventCount(box), afterEvents, 'a second apply does not duplicate the receipt');+});++test('[B26] agent markers and agent worktrees cannot decide rows; only the coordinator applies them', function guardPersonAndCoordinatorActions() {+ const box = project();+ const original = readFileSync(join(box.root, SPEC_FILE), 'utf8');+ const before = eventCount(box);+ for (const marker of AGENT_SHELL_MARKERS) {+ const refused = box.run(box.root, ['spec', 'approve', 'G1', '--json'], { [marker]: 'agent-fixture' });+ assert.equal(refused.status, 1, `${marker}: ${refused.stdout}${refused.stderr}`);+ assert.equal(JSON.parse(refused.stdout).error.code, 'B26_PERSON_CHANNEL', marker);+ assert.equal(readFileSync(join(box.root, SPEC_FILE), 'utf8'), original, `${marker} cannot edit SPEC.md`);+ assert.equal(eventCount(box), before, `${marker} cannot append a board decision`);+ }+ const fromWorktree = box.run(box.web, ['spec', 'approve', 'G1', '--json']);+ assert.equal(fromWorktree.status, 1, `${fromWorktree.stdout}${fromWorktree.stderr}`);+ assert.equal(JSON.parse(fromWorktree.stdout).error.code, 'B26_PERSON_APPROVAL');+ assert.equal(eventCount(box), before, 'an agent worktree cannot act as the person without a shell marker');++ const approved = command(box, box.root, 'spec', 'approve', 'G1', '--json');+ assert.equal(approved.status, 0, `${approved.stdout}${approved.stderr}`);+ const pending = readFileSync(join(box.root, SPEC_FILE), 'utf8');+ const agentApply = box.run(box.web, ['spec', 'apply', '--json']);+ assert.equal(agentApply.status, 1, `${agentApply.stdout}${agentApply.stderr}`);+ assert.equal(readFileSync(join(box.root, SPEC_FILE), 'utf8'), pending, 'an agent cannot apply a pending decision');+ const applied = command(box, box.root, 'spec', 'apply', '--json');+ assert.equal(applied.status, 0, `${applied.stdout}${applied.stderr}`);+ assert.equal(sourceRow(box, SPEC_FILE, 'G1').status, 'approved');+});++test('[B26,S18,S19] stale row text refuses apply without changing any approved row', function staleApplyIsAtomic() {+ const box = project();+ for (const id of ['G1', 'G2']) {+ const approved = command(box, box.root, 'spec', 'approve', id, '--json');+ assert.equal(approved.status, 0, `${approved.stdout}${approved.stderr}`);+ }+ const source = join(box.root, SPEC_FILE);+ const edited = readFileSync(source, 'utf8').replace('Decline this row.', 'Someone edited this row after approval.');+ writeFileSync(source, edited);+ const beforeApply = readFileSync(source, 'utf8');+ const refused = command(box, box.root, 'spec', 'apply', '--json');+ assert.notEqual(refused.status, 0, `${refused.stdout}${refused.stderr}`);+ const document = JSON.parse(refused.stdout);+ assert.ok(document.error, 'stale decision refusal stays a structured CLI refusal');+ assert.equal(readFileSync(source, 'utf8'), beforeApply, 'the stale check prevents partial writes to SPEC.md');+ assert.equal(sourceRow(box, SPEC_FILE, 'G1').status, 'draft', 'even the earlier valid decision is not applied first');+ assert.equal(sourceRow(box, SPEC_FILE, 'G2').status, 'draft');+ assert.equal(sourceRow(box, SPEC_FILE, 'G2').text, 'Someone edited this row after approval.');+});++/** Create a real SSH Ed25519 key pair for the required-signer decision case. */+function makeKey(path) {+ execFileSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', '[email protected]', '-f', path], { stdio: 'pipe' });+ return { privateKey: path, publicKey: `${path}.pub` };+}++test('[B26,S18,S19] signer-required approval signs the exact applied row and tampering is refused', function signedRowDecision() {+ const signedSpec = `# Signed row decision fixture\n\n## G · Goals\n- G1 [draft, must] This exact row requires the person's signature. | gate: true | signers: CO\n`;+ const box = project({ spec: signedSpec });+ const key = makeKey(join(box.dir, 'co-signing-key'));+ box.git(box.root, 'config', 'user.signingkey', key.privateKey);+ const listed = command(box, box.root, 'spec', 'signers', 'add', '--key', key.publicKey, '--by', 'CO', '--json');+ assert.equal(listed.status, 0, `${listed.stdout}${listed.stderr}`);++ const approve = command(box, box.root, 'spec', 'approve', 'G1', '--by', 'CO', '--json');+ assert.equal(approve.status, 0, `${approve.stdout}${approve.stderr}`);+ assert.ok(JSON.parse(approve.stdout).decisions[0].signature, 'approval carries its signature before any source apply');+ assert.equal(sourceRow(box, SPEC_FILE, 'G1').status, 'draft');+ assert.equal(existsSync(join(box.root, '.pullboard', 'signoffs.jsonl')), false, 'signing the pending decision writes no checkout receipt');+ const applied = command(box, box.root, 'spec', 'apply', '--json');+ assert.equal(applied.status, 0, `${applied.stdout}${applied.stderr}`);+ const check = command(box, box.root, 'spec', 'check');+ assert.equal(check.status, 0, `${check.stdout}${check.stderr}`);++ const ledger = join(box.root, '.pullboard', 'signoffs.jsonl');+ const original = readFileSync(ledger, 'utf8');+ const receipt = original.split('\n').filter(Boolean).map(JSON.parse).find((entry) => entry.type === 'row-decision' && entry.id === 'G1');+ assert.ok(receipt?.signature, 'apply emits the signed receipt for the approved row');+ assert.equal(sourceRow(box, SPEC_FILE, 'G1').status, 'approved');+ for (const field of ['text', 'source', 'replacement', 'decision', 'reason', 'file']) {+ const tampered = original.split('\n').filter(Boolean).map(JSON.parse).map((entry) => (+ entry.type === 'row-decision' && entry.id === 'G1' ? { ...entry, [field]: `${entry[field]} altered` } : entry+ ));+ writeFileSync(ledger, `${tampered.map((entry) => JSON.stringify(entry)).join('\n')}\n`);+ const refused = command(box, box.root, 'spec', 'check');+ assert.notEqual(refused.status, 0, `${field} is signed`);+ assert.match(`${refused.stdout}${refused.stderr}`, /BAD_SIGNATURE/u, `${field} tampering invalidates the approval receipt`);+ }+ writeFileSync(ledger, original);+});