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(api): integrate accepted board features [A2,A6,A7,B27]
Corey Olson9ff3ecfd904e
diff --cc docs/api.mdindex decb6386,9d324588..cb3d5987--- a/docs/api.md+++ b/docs/api.md@@@ -84,36 -89,3 +90,38 @@@ A refusal keeps the command's existing<!-- api-refusal-shapes:end -->The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.++## Local HTTP API v1++Run `pullboard serve --port 0` to print a private API address on `127.0.0.1`. Authenticate each call with the address's `k` query parameter, an `X-Pullboard-Key` header, or `Authorization: Bearer <key>`. The secret belongs to that server session. Board ids are random 128-bit values stored in each board; reopening or moving a repo preserves its id.++| Method and path | Result |+| --- | --- |+| `GET /api/v1/boards` | Registered boards with their project details and ids |+| `GET /api/v1/boards/:board/state` | The view's board state, including open coordinator requests |+| `GET /api/v1/boards/:board/events?after=N` | Events after sequence N, in order |+| `POST /api/v1/boards/:board/moves` | One CLI move and its emitted event |+| `POST /api/v1/boards/:board/requests` | A person's request for the coordinator |++<!-- api-http-shapes:start -->+| Response | Required top-level fields |+| --- | --- |+| `boards` | `version:number`, `boards:array` |+| `state` | `version:number`, `state:object` |+| `events` | `version:number`, `events:array` |+| `move` | `version:number`, `event:object`, `result:object` |+| `request` | `version:number`, `event:object`, `result:object` |+| `stream` | `version:number`, `event:object` |+<!-- api-http-shapes:end -->++A move body is `{verb, item, args, agent}`. `item` is the positive integer id when the move needs one. `args` names its CLI positional arguments and flags; text values stay literal, including leading dashes. Omit `agent` to act as the coordinator, or name a registered agent to run in its worktree. Coordinator verification takes `args.as: "coordinator"`, matching the CLI's explicit identity check. The local session secret may act as any agent on that board. `result` is the CLI's JSON result. `next` claims work atomically; when a claim is already held it renews it and returns the renewal event. With no work available it returns the CLI's `NOTHING_FREE` refusal. Waiting remains a CLI option.+++Decision 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.+++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.++For live events, send `Accept: text/event-stream` to the events path. Each message's `id` is its event sequence and its `data` has the `stream` shape above. Reconnect with `Last-Event-ID` to resume after that sequence; it takes precedence over `after`.++HTTP refusals use the same versioned error envelope above: 400 for malformed calls, 401 for a missing or wrong session secret, 403 for an agent belonging to another board, 404 for an unknown board or path, and 409 for the CLI engine's refusal. Shouts and answers append their events in the same transaction as their records. A move returns its own event, including when it also sends a coordinator shout.diff --cc src/api.jsindex 236f1fb3,00000000..a521dc57mode 100644,000000..100644--- a/src/api.js+++ b/src/api.js@@@ -1,241 -1,0 +1,243 @@@+/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */+import { randomBytes, timingSafeEqual } from 'node:crypto';+import { createServer } from 'node:http';+import { join } from 'node:path';+import * as store from './board.js';+import { COORDINATOR, loadConfig } from './config.js';+import { repoInfo } from './git.js';+import { refusalDocument } from './json.js';+import { laneNames } from './lanes.js';+import { listProjects } from './projects.js';+import { Refused } from './refused.js';+import { projectState } from './serve.js';++const ADDRESS = '127.0.0.1';+const VERSION = 1;+const BODY_BYTES = 100_000;++/** Read a registered board and release its SQLite connection on every path. */+function withBoard(root, read) {+ const info = repoInfo(root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));+ try { return read(board, info); } finally { store.closeBoard(board); }+}++/** Registered boards carry one persistent identity across local and relay addresses. */+export function apiBoards() {+ return listProjects().map((project) => withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) })));+}++/** Resolve only registered boards, so a request cannot open an arbitrary path on the machine. */+function findBoard(id) {+ const board = apiBoards().find((entry) => entry.id === id);+ if (!board) throw new Refused('NO_BOARD', `no registered board ${id}; run pullboard serve in its repo and use GET /api/v1/boards`);+ return board;+}++/** A decimal event cursor never skips records through coercion or unsafe integer rounding. */+function eventCursor(value) {+ if (value === null || value === undefined || value === '') return 0;+ if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw new Refused('BAD_CURSOR', 'after and Last-Event-ID need a nonnegative integer; use the last event id received');+ return Number(value);+}++/** Read events in sequence, including changes made by other processes on the same board. */+function afterEvents(root, after) {+ return withBoard(root, (board) => board.db.prepare('SELECT * FROM event WHERE event_id > ? ORDER BY event_id').all(after));+}++/** Only JSON objects within the byte limit may become move arguments. */+async function readBody(req) {+ if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) throw new Refused('BAD_REQUEST', 'send an application/json object as the request body');+ const chunks = [];+ let size = 0;+ for await (const chunk of req) {+ size += chunk.length;+ if (size > BODY_BYTES) throw new Refused('BAD_REQUEST', `the body exceeds ${BODY_BYTES} bytes; send one move or request at a time`);+ chunks.push(chunk);+ }+ let body;+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new Refused('BAD_REQUEST', 'the body is not JSON; send an application/json object'); }+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Refused('BAD_REQUEST', 'the body needs a JSON object; send one move or request at a time');+ return body;+}++/** Resolve an authenticated local caller's agent to its own checkout, never another board. */+function agentPath(root, name = COORDINATOR) {+ if (typeof name !== 'string' || !name) throw new Refused('BAD_REQUEST', 'agent needs a registered name; omit it to act as the coordinator');+ return withBoard(root, (board, info) => {+ if (name === COORDINATOR) store.ensureCoordinator(board, root);+ const agent = store.listAgents(board).find((entry) => entry.agent_id === name);+ if (!agent) throw new Refused('NO_AGENT', `no registered agent ${name}; use the agents in this board's state or join a worktree first`);+ if (repoInfo(agent.agent_path).commonDir !== info.commonDir) throw new Refused('WRONG_BOARD', `agent ${name}'s worktree belongs to another board; join the agent in this board's worktree`);+ return agent.agent_path;+ });+}++/** Declarative CLI forms keep API calls on the same argument parser and engine as terminal moves. */+const MOVES = {+ add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'] },+ edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'] },+ claim: { item: true },+ release: { item: true },+ submit: { item: true },+ done: { item: true },+ verify: { item: true, positions: ['decision'], flags: ['reason', 'note', 'as'] },+ merged: { item: true, positions: ['commit'] },+ withdraw: { item: true, positions: ['reason'] },+ refreeze: { item: true },+ escalate: { item: true, flags: ['note'] },+ hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },- shout: { positions: ['to', 'text'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },- answer: { item: true, positions: ['text'] },++ shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },++ answer: { item: true, positions: ['text'], flags: ['as'] },++ pass: { item: true, positions: ['note'] },+ next: { flags: ['as'], booleans: ['verify'] },+};++/** Reject unsupported fields, then pass values as distinct argv entries, never a shell command. */+export function moveArgs({ verb, item, args = {} }) {+ if (verb === 'accept' || verb === 'reject') return moveArgs({ verb: 'verify', item, args: { ...args, decision: verb } });+ const form = Object.hasOwn(MOVES, verb) ? MOVES[verb] : null;+ if (!form) throw new Refused('BAD_REQUEST', `no API move ${String(verb)}; use a board move such as add, claim, submit, verify, shout or answer`);+ 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];+ 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));+ } else if (item !== undefined && item !== null) throw new Refused('BAD_REQUEST', `${verb} does not take item; put its arguments in args`);+ const positional = [];+ for (const key of form.positions ?? []) {++ if (args[key] === undefined && form.optional?.includes(key)) continue;+ if (typeof args[key] !== 'string' || !args[key].trim()) throw new Refused('BAD_REQUEST', `${verb} needs args.${key} as nonempty text; supply the CLI move's argument`);+ positional.push(args[key]);+ }+ for (const key of form.flags ?? []) if (args[key] !== undefined) {+ if (typeof args[key] !== 'string') throw new Refused('BAD_REQUEST', `args.${key} needs text; supply the CLI flag's value`);+ argv.push(`--${key}=${args[key]}`);+ }+ for (const key of form.booleans ?? []) if (args[key] !== undefined) {+ if (typeof args[key] !== 'boolean') throw new Refused('BAD_REQUEST', `args.${key} needs true or false`);+ if (args[key]) argv.push(`--${key}`);+ }+ // Positionals follow -- so titles and notes beginning with a dash never become CLI flags.+ argv.push('--json', '--', ...positional);+ return argv;+}++/** Execute one actual CLI command and retain its emitted event without a latest-row race. */+async function executeMove(root, body, runCommand) {+ if (Object.keys(body).some((key) => !['verb', 'item', 'args', 'agent'].includes(key))) throw new Refused('BAD_REQUEST', 'a move takes only verb, item, args and agent; remove the unknown fields');+ const argv = moveArgs(body);+ let cwd;+ try { cwd = agentPath(root, body.agent); } catch (error) {+ if (!(error instanceof Refused) || error.code === 'BAD_REQUEST') throw error;+ return { status: error.code === 'WRONG_BOARD' ? 403 : 409, body: refusalDocument(error) };+ }+ let output = '';+ let diagnostics = '';+ const events = [];+ const status = await runCommand(argv, {+ cwd,+ stdout: { isTTY: false, write: (text) => { output += text; } },+ stderr: { write: (text) => { diagnostics += text; } },+ onEvent: (row) => { events.push(row); },+ });+ const result = JSON.parse(output);+ if (status) return { status: 409, body: result };+ const kind = body.verb === 'verify' ? body.args?.decision+ : body.verb === 'done' ? 'submit'+ : body.verb === 'hold' && body.args?.off ? 'unhold' : body.verb;+ const event = events.find((row) => row.event_kind === kind) ?? events.at(-1);+ if (!event) throw new Error(`move ${body.verb} produced no event${diagnostics ? `: ${diagnostics}` : ''}`);+ return { status: 200, body: { version: VERSION, event, result } };+}++/** Create a person's coordinator request through the same shout transaction as the CLI. */+function createRequest(root, body) {+ if (typeof body.text !== 'string' || !body.text.trim() || Object.keys(body).some((key) => key !== 'text')) throw new Refused('BAD_REQUEST', 'a request needs {text: "what the coordinator should do"}');+ return withBoard(root, (board) => {+ const id = store.shout(board, { from: 'person', to: COORDINATOR, text: body.text, request: true, lanes: laneNames(loadConfig(root)) });+ return { version: VERSION, event: board.lastEvent, result: { id, request: true } };+ });+}++/** Keep an event stream open and resume from either supported cursor, releasing it on disconnect. */+function streamEvents(root, after, res, streams) {+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff' });+ res.write(': API v1\n\n');+ let cursor = after;+ const send = () => {+ try {+ for (const event of afterEvents(root, cursor)) {+ res.write(`id: ${event.event_id}\ndata: ${JSON.stringify({ version: VERSION, event })}\n\n`);+ cursor = event.event_id;+ }+ } catch (error) {+ res.write(`event: error\ndata: ${JSON.stringify(refusalDocument(error))}\n\n`);+ res.end();+ }+ };+ const timer = setInterval(send, 200);+ timer.unref();+ streams.add(res);+ res.once('close', () => { clearInterval(timer); streams.delete(res); });+ send();+}++/** Serve the RFC 0002 API only on loopback, behind the same session-secret boundary as the view. */+export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand } = {}) {+ if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');+ const key = Buffer.from(secret);+ const streams = new Set();+ let bound;+ const json = (res, status, body) => {+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });+ res.end(JSON.stringify(body));+ };+ const server = createServer(async (req, res) => {+ try {+ const url = new URL(req.url ?? '/', `http://${ADDRESS}`);+ const authorization = String(req.headers.authorization ?? '');+ const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? (authorization.startsWith('Bearer ') ? authorization.slice(7) : url.searchParams.get('k') ?? '')));+ const ownHost = req.headers.host === `${ADDRESS}:${bound}` || req.headers.host === `localhost:${bound}`;+ if (!ownHost || given.length !== key.length || !timingSafeEqual(given, key)) return json(res, 401, refusalDocument(new Refused('AUTH_REQUIRED', 'this API needs its session secret and own host; use the address pullboard serve printed')));+ if (req.method === 'GET' && url.pathname === '/api/v1/boards') return json(res, 200, { version: VERSION, boards: apiBoards() });+ const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests)$/.exec(url.pathname);+ if (!route) return json(res, 404, refusalDocument(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, events, moves or requests path')));+ const board = findBoard(route[1]);+ if (req.method === 'GET' && route[2] === 'state') {+ const state = projectState(board.root);+ state.requests = withBoard(board.root, (db) => store.openRequests(db));+ return json(res, 200, { version: VERSION, state });+ }+ if (req.method === 'GET' && route[2] === 'events') {+ const after = eventCursor(req.headers['last-event-id'] ?? url.searchParams.get('after'));+ if (String(req.headers.accept ?? '').includes('text/event-stream')) return streamEvents(board.root, after, res, streams);+ return json(res, 200, { version: VERSION, events: afterEvents(board.root, after) });+ }+ if (req.method === 'POST' && route[2] === 'moves') {+ const moved = await executeMove(board.root, await readBody(req), runCommand);+ return json(res, moved.status, moved.body);+ }+ if (req.method === 'POST' && route[2] === 'requests') return json(res, 200, createRequest(board.root, await readBody(req)));+ return json(res, 400, refusalDocument(new Refused('BAD_REQUEST', `use the documented method for ${route[2]}; reads use GET and moves and requests use POST`)));+ } catch (error) {+ const status = error.code === 'NO_BOARD' ? 404 : error instanceof Refused ? 400 : 500;+ if (!res.headersSent) json(res, status, refusalDocument(error));+ else res.end();+ }+ });+ return new Promise((ready, fail) => {+ server.once('error', (error) => fail(new Refused(error.code === 'EADDRINUSE' ? 'PORT_BUSY' : 'API_LISTEN', `cannot listen on ${ADDRESS}:${port}: ${error.message}; run pullboard serve --port 0 to choose a free port`)));+ server.listen(port, ADDRESS, () => {+ bound = server.address().port;+ ready({+ url: `http://${ADDRESS}:${bound}/api/v1/boards?k=${secret}`,+ port: bound,+ close: () => new Promise((closed) => { for (const stream of streams) stream.end(); server.close(() => closed()); server.closeIdleConnections(); }),+ });+ });+ });+}diff --cc src/board.jsindex a7593c7f,a5eb56f8..b8e1e0fa--- a/src/board.js+++ b/src/board.js@@@ -1137,49 -1115,91 +1138,114 @@@ export function verdictsFor(board, id)}/**- * Shout to a lane, an agent, or `all` (B7). The caller passes the lanes the config declares.+ * Insert a shout within the caller's transaction.** @param {any} board- * @param {{ from: string, to: string, text: string, lanes: string[] }} message- * @param {{ from: string, to: string, text: string, lanes: string[], decision?: boolean, answers?: number | null, evidence?: any }} message++ * @param {{ from: string, to: string, text: string, lanes: string[], decision?: boolean, answers?: number | null, evidence?: any, request?: boolean }} message+ * @returns {number}*/- export function shout(board, { from, to, text, lanes, decision = false, answers = null, evidence = null, request = false }) {- return atomic(board, () => {- if (!text.trim()) throw new Refused('EMPTY_SHOUT', 'a shout needs text');- if (request && (from !== 'person' || to !== COORDINATOR || decision || answers !== null)) {- throw new Refused('BAD_REQUEST', 'a request goes from the person to the coordinator; use the board requests endpoint with its text');-function insertShout(board, { from, to, text, lanes, decision = false, answers = null, evidence = null }) {++function insertShout(board, { from, to, text, lanes, decision = false, answers = null, evidence = null, request = false }) {+ if (!text.trim()) throw new Refused('EMPTY_SHOUT', 'a shout needs text');++ if (request && (from !== 'person' || to !== COORDINATOR || decision || answers !== null)) {++ throw new Refused('BAD_REQUEST', 'a request goes from the person to the coordinator; use the board requests endpoint with its text');++ }++ const ask = answers === null ? null : getShout(board, answers);+ const isAgent = board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(to);- if (to !== 'all' && to !== PERSON && !lanes.includes(to) && !isAgent) {++ const requestReply = ask?.shout_request && to === ask.shout_from;++ if (to !== 'all' && to !== PERSON && !lanes.includes(to) && !isAgent && !requestReply) {+ throw new Refused('NO_READER', `nobody reads "${to}": name a lane, an agent or all`);+ }+ if (to === PERSON && decision && from !== COORDINATOR) {+ throw new Refused('B26_PERSON_DECISION', `only the coordinator can ask the person for a decision; ask your coordinator: pullboard shout coordinator "${text.trim()}" --decision`);+ }- if (answers !== null && !getShout(board, answers).shout_decision) {++ let outcome = '';++ if (ask?.shout_request) {++ if (from !== COORDINATOR || !requestReply) throw new Refused('COORDINATOR_ONLY', `only the coordinator answers request #${answers}; ask the coordinator to run pullboard answer ${answers} done or declined <reason>`);++ if (board.db.prepare('SELECT 1 FROM shout WHERE shout_answers = ? AND shout_request_outcome != ?').get(answers, '')) {++ throw new Refused('REQUEST_CLOSED', `request #${answers} was already answered; read pullboard inbox before answering another request`);+ }- const ask = answers === null ? null : getShout(board, answers);- const isAgent = board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(to);- const requestReply = ask?.shout_request && to === ask.shout_from;- if (to !== 'all' && !lanes.includes(to) && !isAgent && !requestReply) {- throw new Refused('NO_READER', `nobody reads "${to}": name a lane, an agent or all`);++ const reply = /^(done|declined)(?:\s+([\s\S]+))?$/.exec(text.trim());++ if (!reply || (reply[1] === 'declined' && !reply[2]?.trim())) {++ throw new Refused('REQUEST_OUTCOME', `answer request #${answers} with done or declined followed by a reason: pullboard answer ${answers} done or declined <reason>`);+ }- let outcome = '';- if (ask?.shout_request) {- if (from !== COORDINATOR || !requestReply) throw new Refused('COORDINATOR_ONLY', `only the coordinator answers request #${answers}; ask the coordinator to run pullboard answer ${answers} done or declined <reason>`);- if (board.db.prepare('SELECT 1 FROM shout WHERE shout_answers = ? AND shout_request_outcome != ?').get(answers, '')) {- throw new Refused('REQUEST_CLOSED', `request #${answers} was already answered; read pullboard inbox before answering another request`);- }- const reply = /^(done|declined)(?:\s+([\s\S]+))?$/.exec(text.trim());- if (!reply || (reply[1] === 'declined' && !reply[2]?.trim())) {- throw new Refused('REQUEST_OUTCOME', `answer request #${answers} with done or declined followed by a reason: pullboard answer ${answers} done or declined <reason>`);- }- outcome = reply[1];- } else if (ask && !ask.shout_decision) {- throw new Refused('NOT_A_DECISION', `shout #${answers} asked for no decision; reply with pullboard shout`);++ outcome = reply[1];++ } else if (ask && !ask.shout_decision) {+ throw new Refused('NOT_A_DECISION', `shout #${answers} asked for no decision; reply with pullboard shout`);+ }+ if (evidence) checkEvidence(board, evidence);+ const result = board.db+ .prepare(+ `INSERT INTO shout (shout_from, shout_to, shout_text, shout_at, shout_decision, shout_answers,- shout_evidence_kind, shout_evidence_outcome, shout_evidence_item, shout_evidence_commit)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,++ shout_evidence_kind, shout_evidence_outcome, shout_evidence_item, shout_evidence_commit,++ shout_request, shout_request_outcome)++ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ )- .run(from, to, text.trim(), now(board), decision ? 1 : 0, answers, evidence?.kind ?? null, evidence ? evidence.outcome.trim() : null, evidence?.item ?? null, evidence?.commit ?? null);- return Number(result.lastInsertRowid);++ .run(from, to, text.trim(), now(board), decision ? 1 : 0, answers, evidence?.kind ?? null, evidence ? evidence.outcome.trim() : null, evidence?.item ?? null, evidence?.commit ?? null, request ? 1 : 0, outcome);++ const id = Number(result.lastInsertRowid);++ logEvent(board, from, answers === null ? 'shout' : decision ? 'pass' : 'answer', null, { shout: id, to, decision: Boolean(decision), request: Boolean(request), answers, ...(outcome ? { outcome } : {}) });++ return id;+ }++ /**+ * Shout to a lane, an agent, `all`, or the person (B7, B25, B26). The caller passes declared lanes.+ *+ * @param {any} board- * @param {{ from: string, to: string, text: string, lanes: string[], decision?: boolean, answers?: number | null, evidence?: any }} message++ * @param {{ from: string, to: string, text: string, lanes: string[], decision?: boolean, answers?: number | null, evidence?: any, request?: boolean }} message+ * @returns {number}+ */+ export function shout(board, message) {+ return atomic(board, () => insertShout(board, message));+ }++ /**+ * Pass an open coordinator decision to the person with the original question and note (B27).+ *+ * @param {any} board+ * @param {number} id+ * @param {{ agentId: string, note: string, lanes: string[] }} options+ * @returns {number}+ */+ export function passDecision(board, id, { agentId, note, lanes }) {+ return atomic(board, () => {+ if (agentId !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator can pass a decision up');+ const ask = getShout(board, id);+ if (!ask.shout_decision || ask.shout_to !== COORDINATOR) throw new Refused('NOT_COORDINATOR_DECISION', `shout #${id} is not a decision waiting for the coordinator`);+ if (board.db.prepare('SELECT 1 FROM shout WHERE shout_answers = ?').get(id)) throw new Refused('ALREADY_ANSWERED', `shout #${id} already has an answer`);+ const text = `Passed up from ${ask.shout_from}: ${ask.shout_text}\nCoordinator note: ${String(note ?? '').trim()}`;+ if (!String(note ?? '').trim()) throw new Refused('EMPTY_NOTE', 'include a note with the reason for passing this decision');+ return insertShout(board, { from: COORDINATOR, to: PERSON, text, lanes, decision: true, answers: id });+ });+ }++ /**+ * Answer an open decision addressed to the caller, delivering passed-up answers to the asker (B27).+ *+ * @param {any} board+ * @param {number} id+ * @param {{ agentId: string, text: string, lanes: string[], asPerson?: boolean }} options+ * @returns {number}+ */+ export function answerDecision(board, id, { agentId, text, lanes, asPerson = false }) {+ return atomic(board, () => {+ const ask = getShout(board, id);++ if (ask.shout_request) {++ if (asPerson) throw new Refused('B26_PERSON_ANSWER', `requests are answered by the coordinator; run pullboard answer ${id} done or declined <reason>`);++ return insertShout(board, { from: agentId, to: ask.shout_from, text, lanes, answers: id });+ }- if (evidence) checkEvidence(board, evidence);- const result = board.db- .prepare(- `INSERT INTO shout (shout_from, shout_to, shout_text, shout_at, shout_decision, shout_answers,- shout_evidence_kind, shout_evidence_outcome, shout_evidence_item, shout_evidence_commit,- shout_request, shout_request_outcome)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- )- .run(from, to, text.trim(), now(board), decision ? 1 : 0, answers, evidence?.kind ?? null, evidence ? evidence.outcome.trim() : null, evidence?.item ?? null, evidence?.commit ?? null, request ? 1 : 0, outcome);- const id = Number(result.lastInsertRowid);- logEvent(board, from, answers === null ? 'shout' : 'answer', null, { shout: id, to, decision: Boolean(decision), request: Boolean(request), answers, ...(outcome ? { outcome } : {}) });- return id;+ if (!ask.shout_decision) throw new Refused('NOT_A_DECISION', `shout #${id} asked for no decision`);+ if (board.db.prepare('SELECT 1 FROM shout WHERE shout_answers = ?').get(id)) throw new Refused('ALREADY_ANSWERED', `shout #${id} already has an answer`);+ if (asPerson && agentId !== COORDINATOR) throw new Refused('B26_PERSON_ANSWER', `only the main checkout can answer as the person; ask your coordinator: pullboard answer ${id} "<answer>"`);+ if (asPerson && ask.shout_to !== PERSON) throw new Refused('B26_PERSON_ANSWER', `person mode answers only decisions addressed to the person; the coordinator answers this one: pullboard answer ${id} "<answer>"`);+ if (!asPerson && ask.shout_to === PERSON && agentId === COORDINATOR) throw new Refused('B26_PERSON_ANSWER', `this decision is addressed to the person; answer from the main checkout: pullboard answer ${id} "<answer>" --as person`);+ const personAnswer = asPerson;+ if (ask.shout_to !== agentId && !personAnswer) throw new Refused('NOT_YOUR_DECISION', `shout #${id} is addressed to ${ask.shout_to}, not ${agentId}`);+ const from = personAnswer ? PERSON : agentId;+ const answerId = insertShout(board, { from, to: ask.shout_from, text, lanes, answers: id });+ if (personAnswer && ask.shout_answers !== null) {+ const original = getShout(board, ask.shout_answers);+ insertShout(board, { from: PERSON, to: original.shout_from, text: `Person answered #${id}: ${String(text).trim()}`, lanes, answers: original.shout_id });+ }+ return answerId;});}@@@ -1216,25 -1236,24 +1282,31 @@@ export function getShout(board, id)}/**- * Shouts that asked for a decision nobody has answered yet, oldest first (B21). They stay here, and- * in the person's Needs-you, until an answer names them; nothing ever edits the ask.+ * Shouts that asked for a decision nobody has answered yet, oldest first (B21). An optional+ * recipient limits the queue; without one this returns every open decision for internal readers.** @param {any} board+ * @param {string} [recipient]* @returns {any[]}*/- export function openDecisions(board) {+ export function openDecisions(board, recipient = null) {+ if (recipient === null) {+ return board.db+ .prepare('SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id')+ .all();+ }return board.db- .prepare('SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id')- .all();+ .prepare('SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND ask.shout_to = ? AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id')+ .all(recipient);}+/** Requests remain visible to the coordinator until a done or declined answer closes them (A2). */+export function openRequests(board) {+ return board.db.prepare(`SELECT * FROM shout ask WHERE ask.shout_request = 1+ AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id AND reply.shout_request_outcome IN ('done', 'declined'))+ ORDER BY ask.shout_id`).all();+}+/*** The SQL that picks an agent's unread shouts: to it, to its lane, or to all, from anyone else.*/diff --cc src/cli.jsindex 3917d086,1b7fc430..199f38a4--- a/src/cli.js+++ b/src/cli.js@@@ -46,7 -46,8 +46,9 @@@ import { commandOutput } from './json.jimport { forgetProject, registerProject } from './projects.js';import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';import { serveView } from './serve.js';+import { serveApi } from './api.js';+ import { doctorProblems } from './doctor.js';+ import { exportBoard, importBoard } from './exchange.js';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));export const VERSION = PACKAGE.version;diff --cc src/doctor.jsindex 00000000,8965e071..c3442e9fmode 000000,100644..100644--- a/src/doctor.js+++ b/src/doctor.js@@@ -1,0 -1,163 +1,163 @@@+ /** Read-only integrity checks for a pullboard board file (A6). */+ import { existsSync } from 'node:fs';+ import { DatabaseSync } from 'node:sqlite';+ import { BLANKS, STATES, storeTriggers } from './machine.js';+-const SCHEMA_VERSION = 1;++import { SCHEMA_VERSION } from './board.js';+ const blankCharacters = new Set(BLANKS.map((point) => String.fromCodePoint(point)));++ /**+ * Check a board and its git pins without opening it through the migrator, which repairs boards on+ * open. `doctor` must report the evidence it sees and leave that evidence untouched.+ *+ * @param {string} file+ * @param {string} root+ * @param {(root: string, args: string[]) => { status: number, stdout: string }} tryGit+ * @returns {{ code: string, message: string, next: string }[]}+ */+ export function doctorProblems(file, root, tryGit) {+ 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 {+ const schemaProblems = versionProblems(db);+ if (schemaProblems.length) return schemaProblems;+ const layout = layoutProblems(db);+ return [+ ...triggerProblems(db),+ ...layout.problems,+ ...(layout.itemFields ? itemProblems(db) : []),+ ...(layout.itemPins ? pinProblems(db, root, tryGit) : []),+ ...(layout.verdicts ? verdictProblems(db, root, tryGit) : []),+ ];+ } finally {+ db.close();+ }+ }++ /**+ * Make one stable finding for both text and JSON output.+ *+ * @param {string} code+ * @param {string} message+ * @param {string} next+ * @returns {{ code: string, message: string, next: string }}+ */+ const finding = (code, message, next) => ({ code, message, next });++ /** Inspect the layout before each row check, retaining trigger findings on an incomplete board. */+ function layoutProblems(db) {+ const required = {+ item: [...new Set(['item_id', 'item_status', 'item_commit', ...STATES.flatMap((state) => state.requires)])],+ verdict: ['verdict_id', 'item_id', 'verdict_commit'],+ };+ const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((table) => table.name));+ const columns = new Map();+ const problems = [];+ for (const [table, fields] of Object.entries(required)) {+ if (!tables.has(table)) {+ problems.push(finding('TABLE_MISSING', `board table ${table} is missing`, 'restore a consistent board backup, or run pullboard status to recreate the missing table'));+ columns.set(table, new Set());+ continue;+ }+ const present = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((column) => column.name));+ columns.set(table, present);+ const missing = fields.filter((field) => !present.has(field));+ if (missing.length) problems.push(finding('COLUMN_MISSING', `board table ${table} is missing columns ${missing.join(', ')}`, 'restore a consistent board backup, then run pullboard status'));+ }+ const has = (table, fields) => fields.every((field) => columns.get(table).has(field));+ return {+ problems,+ itemFields: has('item', ['item_id', 'item_status']),+ itemPins: has('item', ['item_id', 'item_status', 'item_commit']),+ verdicts: has('verdict', required.verdict),+ };+ }++ /**+ * Report a schema version this executable cannot safely use.+ *+ * @param {DatabaseSync} db+ * @returns {{ code: string, message: string, next: string }[]}+ */+ function versionProblems(db) {+ const version = db.prepare('PRAGMA user_version').get().user_version;+ if (version === SCHEMA_VERSION) return [];+ const repair = version < SCHEMA_VERSION+ ? 'run pullboard status to upgrade this board'+ : 'use a pullboard version that supports this board schema';+ return [finding('SCHEMA_VERSION', `schema version is ${version}; this pullboard expects ${SCHEMA_VERSION}`, repair)];+ }++ /**+ * Report missing, changed or undeclared lifecycle triggers and how the normal opener repairs them.+ *+ * @param {DatabaseSync} db+ * @returns {{ code: string, message: string, next: string }[]}+ */+ function triggerProblems(db) {+ const expected = storeTriggers();+ const actual = new Map(db.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'machine%'").all().map((row) => [row.name, row.sql]));+ const problems = [];+ for (const trigger of expected) {+ const sql = actual.get(trigger.name);+ if (sql === undefined) problems.push(finding('TRIGGER_MISSING', `board trigger ${trigger.name} is missing`, 'run pullboard status'));+ else if (sql !== trigger.sql) problems.push(finding('TRIGGER_CHANGED', `board trigger ${trigger.name} has changed`, 'run pullboard status'));+ }+ for (const name of actual.keys()) {+ if (!expected.some((trigger) => trigger.name === name)) problems.push(finding('TRIGGER_UNEXPECTED', `board trigger ${name} is unexpected`, 'run pullboard status'));+ }+ return problems;+ }++ /**+ * Report item rows missing fields required by their current state.+ *+ * @param {DatabaseSync} db+ * @returns {{ code: string, message: string, next: string }[]}+ */+ function itemProblems(db) {+ const required = new Map(STATES.map((state) => [state.id, state.requires]));+ const problems = [];+ for (const item of db.prepare('SELECT * FROM item ORDER BY item_id').all()) {+ const fields = required.get(item.item_status) ?? [];+ const missing = fields.filter((field) => [...String(item[field] ?? '')].every((character) => blankCharacters.has(character)));+ if (missing.length) problems.push(finding('ITEM_FIELDS', `item #${item.item_id} (${item.item_status}) is missing ${missing.join(', ')}`, 'restore a consistent board backup, then run pullboard doctor'));+ }+ return problems;+ }++ /**+ * Report submitted or verified items whose saved commit pin no longer resolves.+ *+ * @param {DatabaseSync} db+ * @param {string} root+ * @param {(root: string, args: string[]) => { status: number, stdout: string }} tryGit+ * @returns {{ code: string, message: string, next: string }[]}+ */+ function pinProblems(db, root, tryGit) {+ const items = db.prepare("SELECT item_id, item_commit FROM item WHERE item_status IN ('submitted', 'verified') ORDER BY item_id").all();+ return items.flatMap((item) => {+ const commit = item.item_commit ?? '';+ const pin = `refs/pullboard/items/${item.item_id}/${commit.slice(0, 12)}`;+ const found = commit && tryGit(root, ['rev-parse', '--verify', '--quiet', `${pin}^{commit}`]);+ if (found?.status === 0 && found.stdout === commit) return [];+ return [finding('ITEM_PIN_MISSING', `item #${item.item_id} has no pin for ${commit || 'its missing commit'} at ${pin}`, `fetch the commit if needed, then run git update-ref ${pin} ${commit || '<commit>'}`)];+ });+ }++ /**+ * Report verdict receipts whose commit object is no longer in the repository.+ *+ * @param {DatabaseSync} db+ * @param {string} root+ * @param {(root: string, args: string[]) => { status: number, stdout: string }} tryGit+ * @returns {{ code: string, message: string, next: string }[]}+ */+ function verdictProblems(db, root, tryGit) {+ return db.prepare('SELECT verdict_id, item_id, verdict_commit FROM verdict ORDER BY verdict_id').all().flatMap((verdict) => {+ const found = tryGit(root, ['rev-parse', '--verify', '--quiet', `${verdict.verdict_commit}^{commit}`]);+ if (found.status === 0 && found.stdout === verdict.verdict_commit) return [];+ const pin = `refs/pullboard/items/${verdict.item_id}/${verdict.verdict_commit.slice(0, 12)}`;+ return [finding('VERDICT_COMMIT_MISSING', `verdict #${verdict.verdict_id} for item #${verdict.item_id} names missing commit ${verdict.verdict_commit}`, `fetch the commit if needed, then run git update-ref ${pin} ${verdict.verdict_commit}`)];+ });+ }diff --cc src/exchange.jsindex 00000000,00a806e6..eb460c5bmode 000000,100644..100644--- a/src/exchange.js+++ b/src/exchange.js@@@ -1,0 -1,160 +1,168 @@@+ /**+ * Export and import whole board files (A7), including their AUTOINCREMENT counters, so a copy can+ * continue producing the same ids after its rows are restored.+ */+ import { Refused } from './refused.js';+ import { storeTriggers } from './machine.js';++ const VERSION = 1;++ /**+ * Quote a SQLite identifier read from the database or a validated document.+ * @param {string} name+ * @returns {string}+ */+ const identifier = (name) => `"${name.replaceAll('"', '""')}"`;++ /**+ * Names of the board's data tables, with sqlite_sequence last so imported counters remain exact.+ * @param {any} db+ * @returns {string[]}+ */+ function tableNames(db) {+ const names = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(({ name }) => name);+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_sequence'").get()) names.push('sqlite_sequence');+ return names;+ }++ /**+ * The columns in a board table, in their declared order.+ * @param {any} db+ * @param {string} table+ * @returns {string[]}+ */+ function columnsOf(db, table) {+ return db.prepare(`PRAGMA table_info(${identifier(table)})`).all().map(({ name }) => name);+ }++ /**+ * Capture every board table and row in the stable v1 document format.+ * @param {{ db: any }} board+ * @returns {{ version: number, tables: Record<string, any[]> }}+ */+ export function exportBoard(board) {+ const db = board.db;+ db.exec('BEGIN DEFERRED');+ try {+ const tables = Object.fromEntries(tableNames(db).map((table) => [+ table,+ db.prepare(`SELECT * FROM ${identifier(table)} ORDER BY ${table === 'sqlite_sequence' ? 'name' : 'rowid'}`).all(),+ ]));+ db.exec('COMMIT');+ return { version: VERSION, tables };+ } catch (error) {+ db.exec('ROLLBACK');+ throw error;+ }+ }++ /**+ * Validate the document shape against the open board's schema before changing any rows.+ * @param {any} db+ * @param {any} document+ * @param {string[]} names+ */+ function validateDocument(db, document, names) {+ if (!document || typeof document !== 'object' || Array.isArray(document) || document.version !== VERSION) {+ throw new Refused('IMPORT_VERSION', `expected board export version ${VERSION}; export it again with this pullboard version`);+ }+ if (!document.tables || typeof document.tables !== 'object' || Array.isArray(document.tables)) {+ throw new Refused('IMPORT_FORMAT', 'the export needs a tables object; use pullboard export to make one');+ }+ const supplied = Object.keys(document.tables).sort();+ const expected = [...names].sort();+ if (JSON.stringify(supplied) !== JSON.stringify(expected)) {+ throw new Refused('IMPORT_SCHEMA', `the export tables do not match this board; export and import with the same pullboard version`);+ }+ for (const table of names) {+ const columns = columnsOf(db, table);+ const rows = document.tables[table];+ if (!Array.isArray(rows)) throw new Refused('IMPORT_FORMAT', `table ${table} must contain an array of rows; export it again`);+ for (const row of rows) {+ if (!row || typeof row !== 'object' || Array.isArray(row) || JSON.stringify(Object.keys(row).sort()) !== JSON.stringify([...columns].sort())) {+ throw new Refused('IMPORT_SCHEMA', `a ${table} row does not have exactly its board columns; export it again`);+ }+ }+ }+ }+++/** Only the generated identity is disposable when restoring a fresh board (A2, A7). */++function hasOnlyIdentity(db) {++ const rows = db.prepare('SELECT * FROM board_meta').all();++ return rows.length === 1 && rows[0].meta_key === 'board_id' && /^[0-9a-f]{32}$/.test(rows[0].meta_value);++}+++ /** True only for the coordinator registration and join event that `pullboard init` creates. */+ function hasOnlyInitCoordinator(db, names) {- if (!names.includes('sqlite_sequence')) return false;++ if (!names.includes('sqlite_sequence') || !hasOnlyIdentity(db)) return false;+ const agents = db.prepare('SELECT * FROM agent').all();+ const events = db.prepare('SELECT * FROM event').all();+ const sequence = db.prepare('SELECT name, seq FROM sqlite_sequence ORDER BY name').all();+ if (agents.length !== 1 || events.length !== 1 || sequence.length !== 1) return false;+ const [agent] = agents;+ const [event] = events;+ if (+ agent.agent_id !== 'coordinator'+ || agent.agent_lane !== 'coordinator'+ || agent.agent_route !== 'strong'+ || agent.agent_last_shout_id !== 0+ || !agent.agent_path+ || event.event_by !== 'coordinator'+ || event.event_kind !== 'join'+ || event.item_id !== null+ || sequence[0].name !== 'event'+ || sequence[0].seq !== 1+ ) return false;+ try {+ if (JSON.stringify(JSON.parse(event.event_detail)) !== JSON.stringify({ lane: 'coordinator' })) return false;+ } catch {+ return false;+ }+ return names- .filter((table) => table !== 'agent' && table !== 'event' && table !== 'sqlite_sequence')++ .filter((table) => table !== 'agent' && table !== 'event' && table !== 'sqlite_sequence' && table !== 'board_meta')+ .every((table) => !db.prepare(`SELECT 1 FROM ${identifier(table)} LIMIT 1`).get());+ }++ /**+ * Restore a v1 export only into an empty board, atomically, while briefly allowing historical item+ * states to be inserted before restoring the board's declared lifecycle triggers.+ * @param {{ db: any }} board+ * @param {any} document+ * @returns {{ tables: string[] }}+ */+ export function importBoard(board, document) {+ const db = board.db;+ const names = tableNames(db);+ validateDocument(db, document, names);+ db.exec('PRAGMA defer_foreign_keys = ON; BEGIN IMMEDIATE');+ try {- const occupied = names.filter((table) => db.prepare(`SELECT 1 FROM ${identifier(table)} LIMIT 1`).get());++ const onlyIdentity = hasOnlyIdentity(db);++ const occupied = names.filter((table) => !(table === 'board_meta' && onlyIdentity) && db.prepare(`SELECT 1 FROM ${identifier(table)} LIMIT 1`).get());+ const initCoordinator = occupied.length > 0 && hasOnlyInitCoordinator(db, names);+ if (occupied.length && !initCoordinator) {+ throw new Refused('IMPORT_NOT_EMPTY', `board tables already have rows (${occupied.join(', ')}); import into a repo with an empty board`);+ }+ const triggers = db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'machine_%'").all();+ for (const { name } of triggers) db.exec(`DROP TRIGGER ${identifier(name)}`);+ if (initCoordinator) {+ db.exec('DELETE FROM event; DELETE FROM agent; DELETE FROM sqlite_sequence');+ }++ if (onlyIdentity) db.exec('DELETE FROM board_meta');+ for (const table of names.filter((name) => name !== 'sqlite_sequence')) {+ const columns = columnsOf(db, table);+ const sql = `INSERT INTO ${identifier(table)} (${columns.map(identifier).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;+ const insert = db.prepare(sql);+ for (const row of document.tables[table]) insert.run(...columns.map((column) => row[column]));+ }+ const setSequence = db.prepare('UPDATE sqlite_sequence SET seq = ? WHERE name = ?');+ for (const row of document.tables.sqlite_sequence ?? []) {+ if (!setSequence.run(row.seq, row.name).changes) db.prepare('INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)').run(row.name, row.seq);+ }+ for (const { name, sql } of storeTriggers()) db.exec(sql);+ db.exec('COMMIT');+ return { tables: names };+ } catch (error) {+ db.exec('ROLLBACK');+ throw error;+ }+ }diff --cc test/api.test.jsindex 28ceb8c7,e165f974..2e1085e7--- a/test/api.test.js+++ b/test/api.test.js@@@ -322,56 -324,10 +324,67 @@@ test('[A1] refusals are one JSON documermSync(box.dir, { recursive: true, force: true });});-test('[A1] view flushes one JSON document before shutdown', async (t) => {- const box = project();- t.after(() => rmSync(box.dir, { recursive: true, force: true }));- const child = spawn(process.execPath, [BIN, 'view', '--no-open', '--port', '0', '--json'], { cwd: box.repo, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });+test('[A1] long-running servers flush one JSON document before shutdown', async (t) => {+ for (const command of ['view', 'serve']) {+ const box = project();+ t.after(() => rmSync(box.dir, { recursive: true, force: true }));+ const child = spawn(process.execPath, [BIN, command, ...(command === 'view' ? ['--no-open'] : []), '--port', '0', '--json'], { cwd: box.repo, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ let stderr = '';+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8');+ child.stdout.on('data', (chunk) => { stdout += chunk; });+ child.stderr.on('data', (chunk) => { stderr += chunk; });+ const closed = once(child, 'close');+ t.after(() => {+ if (child.exitCode === null) child.kill('SIGTERM');+ });+ const ready = new Promise((resolveReady, rejectReady) => {+ const timeout = setTimeout(() => rejectReady(new Error('view did not flush its JSON result')), 10_000);+ child.stdout.on('data', () => {+ try {+ const document = JSON.parse(stdout);+ clearTimeout(timeout);+ resolveReady(document);+ } catch {+ // The public document is pretty-printed; wait until it is complete.+ }+ });+ child.once('error', (error) => {+ clearTimeout(timeout);+ rejectReady(error);+ });+ });+ const document = await ready;+ assert.equal(document.version, 1);+ coveredRoots.add(command);+ assertRequiredShape(document, shapeFor(command).required, command);+ child.kill('SIGTERM');+ await closed;+ assert.equal(stderr, '');+ assert.deepEqual(parseOneDocument(stdout), document, `${command} does not flush a second document on shutdown`);+ }+});+test('[A1] every catalog command and subcommand has a real CLI exercise', () => {++ const source = project();++ const target = project();++ const document = json(source, source.repo, 'export');++ const file = join(source.dir, 'board.json');++ writeFileSync(file, JSON.stringify(document));++ json(source, target.repo, 'import', [file]);++ const humanTarget = project();++ const humanImport = source.run(humanTarget.repo, 'import', file);++ assert.equal(humanImport.status, 0, humanImport.stderr || humanImport.stdout);++ assert.match(humanImport.stdout, /imported version 1 board tables/);+++ 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');+});++/** Start the real local API server and stop it when its test finishes. */+async function startApi(t, box) {+ const child = spawn(process.execPath, [BIN, 'serve', '--port', '0', '--json'], { cwd: box.repo, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });let stdout = '';let stderr = '';child.stdout.setEncoding('utf8');@@@ -379,234 -335,48 +392,281 @@@child.stdout.on('data', (chunk) => { stdout += chunk; });child.stderr.on('data', (chunk) => { stderr += chunk; });const closed = once(child, 'close');- t.after(() => {+ t.after(async () => {if (child.exitCode === null) child.kill('SIGTERM');+ if (child.exitCode === null) {+ let timeout;+ await Promise.race([closed, new Promise((resolveDone) => { timeout = setTimeout(resolveDone, 10_000); })]);+ clearTimeout(timeout);+ }});- const ready = new Promise((resolveReady, rejectReady) => {- const timeout = setTimeout(() => rejectReady(new Error('view did not flush its JSON result')), 10_000);- child.stdout.on('data', () => {+ const document = await new Promise((resolveReady, rejectReady) => {+ const timeout = setTimeout(() => rejectReady(new Error(`serve did not flush its JSON result: ${stderr}`)), 10_000);+ const check = () => {try {- const document = JSON.parse(stdout);+ const parsed = JSON.parse(stdout);clearTimeout(timeout);- resolveReady(document);+ resolveReady(parsed);} catch {- // The public document is pretty-printed; wait until it is complete.+ // The startup envelope is pretty-printed across several chunks.}- });- child.once('error', (error) => {- clearTimeout(timeout);- rejectReady(error);+ };+ child.stdout.on('data', check);+ child.once('error', (error) => { clearTimeout(timeout); rejectReady(error); });+ child.once('close', (code) => {+ if (code !== 0) { clearTimeout(timeout); rejectReady(new Error(`serve exited ${code}: ${stderr}`)); }});});- const document = await ready;assert.equal(document.version, 1);- coveredRoots.add('view');- assertRequiredShape(document, shapeFor('view').required, 'view');- child.kill('SIGTERM');- await closed;- assert.equal(stderr, '');- assert.deepEqual(parseOneDocument(stdout), document, 'view does not flush a second document on shutdown');+ const parsed = new URL(document.url);+ const secret = parsed.searchParams.get('k');+ assert.ok(secret, 'serve startup exposes its per-session secret in its private URL');+ return { child, document, origin: parsed.origin, secret, stderr: () => stderr };+}++/** Send one bounded HTTP request to the fixture API, authenticating by header unless overridden. */+function apiFetch(api, path, options = {}) {+ const { noSecret = false, ...requestOptions } = options;+ const headers = { ...(noSecret ? {} : { 'x-pullboard-key': api.secret }), ...requestOptions.headers };+ return fetch(new URL(path, api.origin), { ...requestOptions, headers, signal: requestOptions.signal ?? AbortSignal.timeout(10_000) });+}++/** Parse and validate a versioned API refusal. */+async function apiError(response, status) {+ assert.equal(response.status, status);+ const document = await response.json();+ assertRequiredShape(document, JSON_SHAPES.error.required, 'HTTP error envelope');+ assertRequiredShape(document.error, JSON_SHAPES.errorFields, 'HTTP error');+ return document.error;+}++/** Read exactly the next non-comment server-sent event, preserving partial frames across chunks. */+async function nextSseEvent(reader, pending = { text: '' }) {+ const decoder = new TextDecoder();+ while (true) {+ const boundary = pending.text.indexOf('\n\n');+ if (boundary >= 0) {+ const frame = pending.text.slice(0, boundary);+ pending.text = pending.text.slice(boundary + 2);+ const id = /^id: (.+)$/m.exec(frame)?.[1];+ const data = [...frame.matchAll(/^data: (.+)$/gm)].map((match) => match[1]).join('\n');+ if (id !== undefined && data) return { id, document: JSON.parse(data) };+ continue;+ }+ const { done, value } = await reader.read();+ assert.equal(done, false, 'the live event stream remains open');+ pending.text += decoder.decode(value, { stream: true });+ }+}++test('[A2] local HTTP v1 versions state and moves, authenticates, and preserves CLI refusals', async (t) => {+ const box = project();+ const api = await startApi(t, box);++ const boardsResponse = await apiFetch(api, '/api/v1/boards');+ assert.equal(boardsResponse.status, 200);+ const boardsDocument = await boardsResponse.json();+ assertRequiredShape(boardsDocument, JSON_SHAPES.http.boards.required, 'boards response');+ const board = boardsDocument.boards.find((candidate) => candidate.root === box.repo);+ assert.ok(board?.id);+ const boardPath = `/api/v1/boards/${board.id}`;++ await apiError(await apiFetch(api, '/api/v1/boards', { noSecret: true }), 401);+ await apiError(await apiFetch(api, '/api/v1/boards', { headers: { 'x-pullboard-key': 'wrong-session-secret' } }), 401);+ const unknown = await apiError(await apiFetch(api, `/api/v1/boards/${'0'.repeat(32)}/state`), 404);+ assert.equal(unknown.code, 'NO_BOARD');++ const stateResponse = await apiFetch(api, `${boardPath}/state`);+ assert.equal(stateResponse.status, 200);+ const stateDocument = await stateResponse.json();+ assertRequiredShape(stateDocument, JSON_SHAPES.http.state.required, 'state response');+ assert.equal(stateDocument.version, 1);+ const eventsResponse = await apiFetch(api, `${boardPath}/events?after=0`);+ assert.equal(eventsResponse.status, 200);+ const eventsDocument = await eventsResponse.json();+ assertRequiredShape(eventsDocument, JSON_SHAPES.http.events.required, 'events response');+ assert.equal(eventsDocument.version, 1);++ const malformed = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{bad json' });+ assert.equal((await apiError(malformed, 400)).code, 'BAD_REQUEST');+ const oversized = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: 'x'.repeat(100_001) } }) });+ assert.equal((await apiError(oversized, 400)).code, 'BAD_REQUEST');+ const unknownVerb = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'pretend', args: {} }) });+ assert.equal((await apiError(unknownVerb, 400)).code, 'BAD_REQUEST');+ const unknownArgument = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: 'Ignored', extra: true } }) });+ assert.equal((await apiError(unknownArgument, 400)).code, 'BAD_REQUEST');++ const cliRefusal = JSON.parse(box.run(box.repo, 'claim', '999', '--json').stdout).error;+ const refusalResponse = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'claim', item: 999, args: {} }) });+ assert.deepEqual(await apiError(refusalResponse, 409), cliRefusal, 'HTTP move refusals preserve the CLI code, message and next step');++ const noWork = JSON.parse(box.run(box.repo, 'next', '--json').stdout).error;+ const nextResponse = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'next', args: {} }) });+ assert.equal(noWork.code, 'NOTHING_FREE');+ assert.deepEqual(await apiError(nextResponse, 409), noWork, 'next keeps the CLI no-work refusal and its polling guidance');++ const verifierRefusal = JSON.parse(box.run(box.repo, 'verify', '999', 'accept', '--as', 'coordinator', '--note', 'checked the API', '--json').stdout).error;+ const verifyResponse = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'verify', item: 999, args: { decision: 'accept', as: 'coordinator', note: 'checked the API' } }) });+ assert.deepEqual(await apiError(verifyResponse, 409), verifierRefusal, 'coordinator verification can explicitly assert the same identity as the CLI');++ const movedResponse = await apiFetch(api, `${boardPath}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: '--help' } }) });+ assert.equal(movedResponse.status, 200);+ const moved = await movedResponse.json();+ assertRequiredShape(moved, JSON_SHAPES.http.move.required, 'move response');+ assert.equal(moved.result.item.item_title, '--help', 'positional titles beginning with a dash stay literal');+ assert.equal(moved.event.event_kind, 'add');+ assert.equal(moved.event.event_id, eventsDocument.events.at(-1)?.event_id + 1);+ assert.equal(api.stderr(), '');});-test('[A1] every catalog command and subcommand has a real CLI exercise', () => {- const source = project();- const target = project();- const document = json(source, source.repo, 'export');- const file = join(source.dir, 'board.json');- writeFileSync(file, JSON.stringify(document));- json(source, target.repo, 'import', [file]);- const humanTarget = project();- const humanImport = source.run(humanTarget.repo, 'import', file);- assert.equal(humanImport.status, 0, humanImport.stderr || humanImport.stdout);- assert.match(humanImport.stdout, /imported version 1 board tables/);+test('[A2] moves run as the named worktree agent and requests stay visible until answered', async (t) => {+ const box = project();+ const app = join(box.dir, 'app-1');+ box.git(box.repo, 'worktree', 'add', '-q', '-b', 'app/one', app);+ assert.equal(box.run(app, 'join', 'app').status, 0);+ const api = await startApi(t, box);+ const boards = await (await apiFetch(api, '/api/v1/boards')).json();+ const board = boards.boards.find((candidate) => candidate.root === box.repo);+ const path = `/api/v1/boards/${board.id}`;++ const added = await (await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: 'Agent work' } }) })).json();+ const claimedResponse = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'next', args: {}, agent: 'app-1' }) });+ assert.equal(claimedResponse.status, 200);+ const claimed = await claimedResponse.json();+ assert.equal(claimed.event.event_by, 'app-1');+ assert.equal(claimed.event.event_kind, 'claim');+ assert.equal(claimed.result.item.item_id, added.result.item.item_id);++ const renewedResponse = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'next', args: {}, agent: 'app-1' }) });+ assert.equal(renewedResponse.status, 200);+ const renewed = await renewedResponse.json();+ assert.equal(renewed.result.held, true);+ assert.equal(renewed.event.event_kind, 'renew');+ assert.ok(renewed.event.event_id > claimed.event.event_id);+ assert.equal(renewed.result.item.item_id, claimed.result.item.item_id);++ const escalatedResponse = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'escalate', item: added.result.item.item_id, args: { note: 'Two attempts failed' }, agent: 'app-1' }) });+ assert.equal(escalatedResponse.status, 200);+ const escalated = await escalatedResponse.json();+ assert.equal(escalated.event.event_kind, 'escalate', 'a move returns its own event even when it also sends a coordinator shout');+ const afterEscalation = (await (await apiFetch(api, `${path}/events?after=${renewed.event.event_id}`)).json()).events;+ assert.deepEqual(afterEscalation.map((event) => event.event_kind), ['escalate', 'shout']);+ assert.equal(afterEscalation[0].event_id, escalated.event.event_id);++ const requestResponse = await apiFetch(api, `${path}/requests`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'Approve the API row' }) });+ assert.equal(requestResponse.status, 200);+ const requested = await requestResponse.json();+ assertRequiredShape(requested, JSON_SHAPES.http.request.required, 'request response');+ const requestId = requested.result.id;+ assert.equal(requested.event.event_by, 'person');+ const state = (await (await apiFetch(api, `${path}/state`)).json()).state;+ assert.deepEqual(state.requests.map((entry) => entry.shout_id), [requestId]);+ assert.ok(!state.decisions.some((entry) => entry.shout_id === requestId), 'person requests are not open decisions');+ const inbox = json(box, box.repo, 'inbox');+ assert.equal(inbox.shouts[0].shout_id, requestId, 'coordinator inbox places the request first');+ const resumed = json(box, box.repo, 'resume');+ assert.equal(resumed.requests[0].shout_id, requestId, 'coordinator resume places the request first');++ const answerResponse = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'answer', item: requestId, args: { text: 'done' } }) });+ assert.equal(answerResponse.status, 200);+ const answered = await answerResponse.json();+ assert.equal(answered.event.event_kind, 'answer');+ assert.equal(answered.event.event_by, 'coordinator');+ assert.deepEqual((await (await apiFetch(api, `${path}/state`)).json()).state.requests, []);+});- 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');++test('[A2,B25,B26,B27] HTTP decisions preserve routing, passing and explicit person answers', async (t) => {++ const box = project();++ const app = join(box.dir, 'app-1');++ box.git(box.repo, 'worktree', 'add', '-q', '-b', 'app/one', app);++ assert.equal(box.run(app, 'join', 'app').status, 0);++ const api = await startApi(t, box);++ const boards = await (await apiFetch(api, '/api/v1/boards')).json();++ const board = boards.boards.find((candidate) => candidate.root === box.repo);++ const path = `/api/v1/boards/${board.id}`;++ /** Send a real HTTP move while retaining the caller and CLI argument boundaries. */++ const move = (verb, args, item, agent = 'coordinator') => apiFetch(api, `${path}/moves`, {++ method: 'POST', headers: { 'content-type': 'application/json' },++ body: JSON.stringify({ verb, args, ...(item === undefined ? {} : { item }), agent }),++ });++++ const askResponse = await move('shout', { text: 'May this ship?', decision: true }, undefined, 'app-1');++ assert.equal(askResponse.status, 200);++ const ask = await askResponse.json();++ assert.equal(ask.version, 1);++ assert.equal(ask.event.event_kind, 'shout');++ assert.equal(ask.event.event_by, 'app-1');++ assert.equal(JSON.parse(ask.event.event_detail).to, 'coordinator');++++ const notCoordinator = JSON.parse(box.run(app, 'pass', String(ask.result.id), 'Needs the person', '--json').stdout).error;++ assert.deepEqual(await apiError(await move('pass', { note: 'Needs the person' }, ask.result.id, 'app-1'), 409), notCoordinator);++++ const passResponse = await move('pass', { note: 'Needs the person' }, ask.result.id);++ assert.equal(passResponse.status, 200);++ const passed = await passResponse.json();++ assert.equal(passed.version, 1);++ assert.equal(passed.event.event_kind, 'pass');++ assert.equal(JSON.parse(passed.event.event_detail).to, 'person');++++ const personRequired = JSON.parse(box.run(box.repo, 'answer', String(passed.result.id), 'Approved', '--json').stdout).error;++ assert.equal(personRequired.code, 'B26_PERSON_ANSWER');++ assert.deepEqual(await apiError(await move('answer', { text: 'Approved' }, passed.result.id), 409), personRequired);++ const answerResponse = await move('answer', { text: 'Approved', as: 'person' }, passed.result.id);++ assert.equal(answerResponse.status, 200);++ const answered = await answerResponse.json();++ assert.equal(answered.version, 1);++ assert.equal(answered.event.event_by, 'person');++ assert.equal(answered.event.event_kind, 'answer');++ const replies = json(box, app, 'inbox').shouts;++ assert.ok(replies.some((entry) => entry.shout_answers === ask.result.id && entry.shout_from === 'person' && entry.shout_text.includes('Approved')));++ assert.deepEqual((await (await apiFetch(api, `${path}/state`)).json()).state.decisions, []);++});+++test('[A2] SSE delivers a live move and resumes after Last-Event-ID without replay', async (t) => {+ const box = project();+ const api = await startApi(t, box);+ const boards = await (await apiFetch(api, '/api/v1/boards')).json();+ const board = boards.boards.find((candidate) => candidate.root === box.repo);+ const path = `/api/v1/boards/${board.id}`;+ const backlog = await (await apiFetch(api, `${path}/events?after=0`)).json();+ const cursor = backlog.events.at(-1)?.event_id ?? 0;+ const eventUrl = `${path}/events?after=${cursor}`;++ const firstResponse = await apiFetch(api, eventUrl, { headers: { accept: 'text/event-stream' }, signal: AbortSignal.timeout(10_000) });+ assert.equal(firstResponse.status, 200);+ assert.match(firstResponse.headers.get('content-type'), /text\/event-stream/);+ const firstReader = firstResponse.body.getReader();+ const firstPending = { text: '' };+ let firstEvent;+ try {+ const firstMove = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: 'Live one' } }) });+ assert.equal(firstMove.status, 200);+ const expectedFirst = await firstMove.json();+ firstEvent = await nextSseEvent(firstReader, firstPending);+ assertRequiredShape(firstEvent.document, JSON_SHAPES.http.stream.required, 'SSE event');+ assert.equal(firstEvent.document.version, 1);+ assert.equal(firstEvent.id, String(expectedFirst.event.event_id));+ assert.deepEqual(firstEvent.document.event, expectedFirst.event);+ } finally {+ await firstReader.cancel();+ }++ const reconnect = await apiFetch(api, `${path}/events`, {+ headers: { accept: 'text/event-stream', 'last-event-id': firstEvent.id },+ signal: AbortSignal.timeout(10_000),+ });+ assert.equal(reconnect.status, 200);+ const reader = reconnect.body.getReader();+ try {+ const secondMove = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: 'Live two' } }) });+ assert.equal(secondMove.status, 200);+ const expectedSecond = await secondMove.json();+ const second = await nextSseEvent(reader);+ assert.equal(second.id, String(expectedSecond.event.event_id));+ assert.ok(Number(second.id) > Number(firstEvent.id), 'the reconnect resumed after the delivered event without replay');+ assert.equal(second.document.event.event_kind, 'add');+ assert.notEqual(second.id, firstEvent.id);+ } finally {+ await reader.cancel();+ }});diff --cc test/doctor.test.jsindex 00000000,3b731721..b27758b1mode 000000,100644..100644--- a/test/doctor.test.js+++ b/test/doctor.test.js@@@ -1,0 -1,196 +1,197 @@@+ /** Integrity checks use throwaway git repositories and real board databases (A6). */+ import assert from 'node:assert/strict';+ import { execFileSync, spawnSync } from 'node:child_process';+ import { 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 { SCHEMA_VERSION } from '../src/board.js';++ const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+ const sandboxes = [];++ after(() => {+ for (const dir of sandboxes) rmSync(dir, { recursive: true, force: true });+ });++ /**+ * Create a committed repo with a board and isolated git identity for one integrity scenario.+ */+ function boardBox({ initialize = true } = {}) {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-doctor-'));+ sandboxes.push(dir);+ const root = join(dir, 'repo');+ mkdirSync(root);+ const env = {+ ...process.env,+ PULLBOARD_HOME: join(dir, 'home'),+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Doctor Test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Doctor Test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const git = (...args) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8' }).trim();+ const run = (...args) => spawnSync(process.execPath, [BIN, ...args], { cwd: root, env, encoding: 'utf8' });+ git('init', '-q', '-b', 'main');+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', lanes: {} }, null, 2));+ git('add', '-A');+ git('commit', '-q', '-m', 'chore: setup');+ const dbFile = join(root, '.git', 'pullboard', 'board.sqlite');+ if (initialize) assert.equal(run('status').status, 0);+ else mkdirSync(join(root, '.git', 'pullboard'), { recursive: true });+ return { dir, root, env, git, run, dbFile };+ }++ /**+ * Open the test board directly so a fixture can model corruption that normal triggers prevent.+ */+ function mutate(box, action) {+ const db = new DatabaseSync(box.dbFile);+ try {+ action(db);+ } finally {+ db.close();+ }+ }++ /**+ * Add a valid open row, then return its integer id for a corruption test.+ */+ function addItem(box) {+ let id;+ mutate(box, (db) => {+ db.prepare('INSERT INTO item (item_lane, item_title, item_created_by, item_created_at, item_updated_at) VALUES (?, ?, ?, ?, ?)')+ .run('web', 'Doctor fixture', 'coordinator', '2026-10-07T00:00:00.000Z', '2026-10-07T00:00:00.000Z');+ id = Number(db.prepare('SELECT last_insert_rowid() AS id').get().id);+ });+ return id;+ }++ test('doctor reports a clean board in one line and leaves it unchanged [A6]', () => {+ const box = boardBox();+ const before = readFileSync(box.dbFile);+ const result = box.run('doctor');+ assert.equal(result.status, 0);+ assert.equal(result.stdout, 'board is clean\n');+ assert.equal(result.stderr, '');+ assert.deepEqual(readFileSync(box.dbFile), before);+ });++ test('doctor finds a missing lifecycle trigger without reinstalling it [A6]', () => {+ const box = boardBox();+ mutate(box, (db) => db.exec('DROP TRIGGER machine_item_start'));+ const result = box.run('doctor');+ assert.equal(result.status, 1);+ assert.match(result.stdout, /machine_item_start is missing; repair: run pullboard status/);+ const db = new DatabaseSync(box.dbFile, { readOnly: true });+ try {+ assert.equal(db.prepare("SELECT count(*) AS n FROM sqlite_master WHERE type='trigger' AND name='machine_item_start'").get().n, 0);+ } finally {+ db.close();+ }+ });++ test('doctor reports every required field missing from an item state [A6]', () => {+ const box = boardBox();+ const id = addItem(box);+ mutate(box, (db) => {+ db.exec('DROP TRIGGER machine_item_move; DROP TRIGGER machine_fields_claimed');+ db.prepare("UPDATE item SET item_status='claimed', item_owner='', item_lease_until='', item_frozen_digest='' WHERE item_id=?").run(id);+ });+ const result = box.run('doctor');+ assert.equal(result.status, 1);+ assert.match(result.stdout, new RegExp(`item #${id} \\(claimed\\) is missing item_owner, item_lease_until, item_frozen_digest`));+ assert.match(result.stdout, /restore a consistent board backup, then run pullboard doctor/);+ });++ test('doctor reports a submitted item whose git pin is gone [A6]', () => {+ const box = boardBox();+ const id = addItem(box);+ const verifiedId = addItem(box);+ writeFileSync(join(box.root, 'proof.txt'), 'commit for the submitted item\n');+ box.git('add', '-A');+ box.git('commit', '-q', '-m', 'docs: make a fixture commit');+ const commit = box.git('rev-parse', 'HEAD');+ mutate(box, (db) => {+ db.exec('DROP TRIGGER machine_item_move; DROP TRIGGER machine_fields_submitted; DROP TRIGGER machine_fields_verified; DROP TRIGGER machine_proof_verified');+ db.prepare("UPDATE item SET item_status='submitted', item_built_by='web-1', item_commit=?, item_frozen_digest='fixture-digest' WHERE item_id=?").run(commit, id);+ db.prepare("UPDATE item SET item_status='verified', item_verified_by='review-1', item_commit=? WHERE item_id=?").run(commit, verifiedId);+ });+ const result = box.run('doctor');+ assert.equal(result.status, 1);+ assert.match(result.stdout, new RegExp(`item #${id} has no pin for ${commit}`));+ assert.match(result.stdout, new RegExp(`git update-ref refs/pullboard/items/${id}/${commit.slice(0, 12)} ${commit}`));+ assert.match(result.stdout, new RegExp(`item #${verifiedId} has no pin for ${commit}`));+ });++ test('doctor reports verdicts whose commit object is gone [A6]', () => {+ const box = boardBox();+ const id = addItem(box);+ const missing = 'f'.repeat(40);+ mutate(box, (db) => {+ db.prepare(`INSERT INTO verdict (item_id, verdict_by, verdict_decision, verdict_reason, verdict_note,+ verdict_commit, verdict_digest, verdict_head, verdict_at) VALUES (?, 'review-1', 'REJECT', 'OTHER', 'fixture', ?, 'digest', 'head', '2026-10-07T00:00:00.000Z')`)+ .run(id, missing);+ });+ const result = box.run('doctor');+ assert.equal(result.status, 1);+ assert.match(result.stdout, new RegExp(`verdict #1 for item #${id} names missing commit ${missing}`));+ assert.match(result.stdout, new RegExp(`git update-ref refs/pullboard/items/${id}/${missing.slice(0, 12)} ${missing}`));+ });++ test('doctor reports older and newer schema versions without migrating either [A6]', () => {+ const box = boardBox();+ mutate(box, (db) => db.exec('PRAGMA user_version = 0'));+ const older = box.run('doctor');+ assert.equal(older.status, 1);- assert.match(older.stdout, /schema version is 0; this pullboard expects 1; repair: run pullboard status to upgrade this board/);- mutate(box, (db) => db.exec('PRAGMA user_version = 2'));++ assert.match(older.stdout, new RegExp(`schema version is 0; this pullboard expects ${SCHEMA_VERSION}; repair: run pullboard status to upgrade this board`));++ mutate(box, (db) => db.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`));+ const newer = box.run('doctor');+ assert.equal(newer.status, 1);- assert.match(newer.stdout, /schema version is 2; this pullboard expects 1; repair: use a pullboard version that supports this board schema/);++ assert.match(newer.stdout, new RegExp(`schema version is ${SCHEMA_VERSION + 1}; this pullboard expects ${SCHEMA_VERSION}; repair: use a pullboard version that supports this board schema`));+ const db = new DatabaseSync(box.dbFile, { readOnly: true });+ try {- assert.equal(db.prepare('PRAGMA user_version').get().user_version, 2);++ assert.equal(db.prepare('PRAGMA user_version').get().user_version, SCHEMA_VERSION + 1);+ } finally {+ db.close();+ }+ });++ test('doctor reports an older empty SQLite layout without querying current tables [A6]', () => {+ const box = boardBox({ initialize: false });+ const db = new DatabaseSync(box.dbFile);+ db.exec('PRAGMA user_version = 0');+ db.close();+ const before = readFileSync(box.dbFile);+ const result = box.run('doctor');+ assert.equal(result.status, 1);- assert.match(result.stdout, /schema version is 0; this pullboard expects 1; repair: run pullboard status to upgrade this board/);++ assert.match(result.stdout, new RegExp(`schema version is 0; this pullboard expects ${SCHEMA_VERSION}; repair: run pullboard status to upgrade this board`));+ assert.doesNotMatch(result.stderr, /no such table|SQLITE_ERROR|Error:/);+ assert.deepEqual(readFileSync(box.dbFile), before);+ });++ test('doctor reports missing triggers on a current empty layout without changing it [A6]', () => {+ const box = boardBox({ initialize: false });+ const db = new DatabaseSync(box.dbFile);- db.exec('PRAGMA user_version = 1');++ db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);+ db.close();+ const before = readFileSync(box.dbFile);+ for (const flags of [[], ['--json']]) {+ const result = box.run('doctor', ...flags);+ assert.equal(result.status, 1);+ assert.equal(result.stderr, '');+ if (flags.length) {+ const document = JSON.parse(result.stdout);+ assert.equal(document.version, 1);+ assert.ok(document.problems.some((problem) => problem.code === 'TRIGGER_MISSING' && problem.message.includes('machine_item_start') && problem.next === 'run pullboard status'));+ assert.ok(document.problems.some((problem) => problem.code === 'TABLE_MISSING' && problem.message.includes('item') && problem.next.includes('pullboard status')));+ } else {+ assert.match(result.stdout, /machine_item_start is missing; repair: run pullboard status/);+ assert.doesNotMatch(result.stdout, /no such table|Error:/);+ }+ assert.deepEqual(readFileSync(box.dbFile), before);+ }+ });diff --cc test/exchange.test.jsindex 00000000,9544b388..aa47adcfmode 000000,100644..100644--- a/test/exchange.test.js+++ b/test/exchange.test.js@@@ -1,0 -1,234 +1,256 @@@+ /**+ * The v1 board exchange keeps each SQLite row, including lifecycle history and sequence counters.+ */+ import assert from 'node:assert/strict';+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+ import { spawnSync } from 'node:child_process';+ import { tmpdir } from 'node:os';+ import { join, resolve } from 'node:path';+ import { test } from 'node:test';+ import * as store from '../src/board.js';+ import { exportBoard, importBoard } from '../src/exchange.js';++ const SHA = 'a'.repeat(40);+ const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+ /** The deterministic frozen criterion used by the fixture. */+ const FREEZE = (item) => ({ text: item.item_title, digest: `digest:${item.item_title}` });++ /**+ * Make a real board file with every item state, both verdict outcomes, decision and evidence shouts,+ * registered agents, an event history and a held lane.+ * @param {string} file+ * @returns {any}+ */+ function populatedBoard(file) {+ const board = store.openBoard(file);+ store.register(board, { lane: 'coordinator', path: '/source' });+ for (let index = 1; index <= 5; index += 1) store.register(board, { lane: 'web', path: `/source/web-${index}` });+ /** Add one open item before driving it into a lifecycle state. */+ const add = (title) => store.addItem(board, { by: 'coordinator', lane: 'web', title });+ const open = add('open');+ const claimed = add('claimed');+ store.claim(board, claimed, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });+ const submitted = add('submitted');+ store.claim(board, submitted, { agentId: 'web-2', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });+ store.submit(board, submitted, { agentId: 'web-2', commit: SHA, tree: 'tree:submitted' });+ const verified = add('verified');+ store.claim(board, verified, { agentId: 'web-3', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });+ store.submit(board, verified, { agentId: 'web-3', commit: SHA, tree: 'tree:verified' });+ store.verify(board, verified, { agentId: 'web-4', decision: 'ACCEPT', note: 'removed the proof; its test failed', head: SHA, digest: `digest:verified`, policy: 'any' });+ const rejected = add('rejected then reopened');+ store.claim(board, rejected, { agentId: 'web-5', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });+ store.submit(board, rejected, { agentId: 'web-5', commit: SHA, tree: 'tree:rejected' });+ store.verify(board, rejected, { agentId: 'web-2', decision: 'REJECT', reason: 'TEST_FAILURE', note: 'the check fails', head: SHA, digest: `digest:rejected then reopened`, policy: 'any' });+ const withdrawn = add('withdrawn');+ store.withdraw(board, withdrawn, { agentId: 'coordinator', reason: 'no longer needed' });+ store.shout(board, { from: 'coordinator', to: 'web', text: 'Should this ship?', lanes: ['web'], decision: true });+ store.shout(board, { from: 'web-1', to: 'coordinator', text: 'Tried the edge case', lanes: [], evidence: { kind: 'attempt', outcome: 'passed after fix', item: open, commit: SHA } });+ store.holdLane(board, 'web', { agentId: 'coordinator', reason: 'freeze the board for export' });+ return board;+ }++ /**+ * Create a disposable directory removed after a test finishes.+ * @returns {string}+ */+ const tempDirectory = () => mkdtempSync(join(tmpdir(), 'pullboard-exchange-'));++ /**+ * Create an isolated real git repo with the smallest valid Pullboard config.+ * @param {string} root+ */+ function gitRepo(root) {+ mkdirSync(root);+ const result = spawnSync('git', ['init', '-q'], { cwd: root, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ lanes: {} }));+ }++ test('round trips every board row, state, history and AUTOINCREMENT counter [A7]', () => {+ const directory = tempDirectory();+ const source = populatedBoard(join(directory, 'source.sqlite'));+ const target = store.openBoard(join(directory, 'target.sqlite'));+ try {+ const document = exportBoard(source);+ const result = importBoard(target, document);+ assert.deepEqual(result.tables, Object.keys(document.tables));+ assert.deepEqual(exportBoard(target), document);+ assert.deepEqual(document.tables.item.map((row) => row.item_status).sort(), ['claimed', 'open', 'open', 'submitted', 'verified', 'withdrawn']);+ assert.ok(document.tables.verdict.some((row) => row.verdict_decision === 'ACCEPT'));+ assert.ok(document.tables.verdict.some((row) => row.verdict_decision === 'REJECT'));+ assert.ok(document.tables.shout.some((row) => row.shout_decision === 1));+ assert.ok(document.tables.shout.some((row) => row.shout_evidence_kind === 'attempt'));+ const previousSequence = document.tables.sqlite_sequence.find((row) => row.name === 'item').seq;+ const next = store.addItem(target, { by: 'coordinator', lane: 'web', title: 'next id' });+ assert.equal(next, previousSequence + 1);+ } finally {+ store.closeBoard(source);+ store.closeBoard(target);+ rmSync(directory, { recursive: true, force: true });+ }+ });++ test('export keeps a single SQLite snapshot while another connection writes [A7]', () => {+ const directory = tempDirectory();+ const file = join(directory, 'shared.sqlite');+ const source = store.openBoard(file);+ const writer = store.openBoard(file);+ try {+ store.register(source, { lane: 'coordinator', path: '/shared' });+ store.register(source, { lane: 'web', path: '/shared/web-1' });+ store.register(source, { lane: 'web', path: '/shared/web-2' });+ store.addItem(source, { by: 'coordinator', lane: 'web', title: 'present before export' });+ const before = JSON.stringify(exportBoard(source));+ let wrote = false;+ const db = new Proxy(source.db, {+ get(target, property) {+ if (property === 'prepare') return (sql) => {+ const statement = target.prepare(sql);+ if (sql !== 'SELECT * FROM "item" ORDER BY rowid') return statement;+ return { all: (...args) => {+ const rows = statement.all(...args);+ if (!wrote) {+ wrote = true;+ writeAcceptedItem(writer);+ }+ return rows;+ } };+ };+ const value = Reflect.get(target, property, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const duringWrite = JSON.stringify(exportBoard({ db }));+ assert.equal(wrote, true, 'the second connection wrote after the item table was read');+ assert.equal(duringWrite, before, 'every exported table came from the same pre-write snapshot');+ assert.equal(exportBoard(writer).tables.item.length, 2, 'the legitimate write committed to the board');+ } finally {+ store.closeBoard(writer);+ store.closeBoard(source);+ rmSync(directory, { recursive: true, force: true });+ }+ });++ /**+ * Create an item and finish its lifecycle on the second database connection.+ * @param {any} board+ */+ function writeAcceptedItem(board) {+ const item = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'written during export' });+ const freeze = (row) => ({ text: row.item_title, digest: `digest:${row.item_title}` });+ store.claim(board, item, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, freeze });+ store.submit(board, item, { agentId: 'web-1', commit: 'b'.repeat(40), tree: 'tree:concurrent' });+ store.verify(board, item, { agentId: 'web-2', decision: 'ACCEPT', note: 'the check passed', head: 'b'.repeat(40), digest: 'digest:written during export', policy: 'any' });+ }++ test('import refuses a board with rows and leaves it unchanged [A7]', () => {+ const directory = tempDirectory();+ const source = populatedBoard(join(directory, 'source.sqlite'));+ const target = store.openBoard(join(directory, 'target.sqlite'));+ try {+ store.register(target, { lane: 'coordinator', path: '/target' });+ store.addItem(target, { by: 'coordinator', lane: 'web', title: 'real work makes this board nonempty' });+ const before = exportBoard(target);+ assert.throws(() => importBoard(target, exportBoard(source)), /IMPORT_NOT_EMPTY.*empty board/);+ assert.deepEqual(exportBoard(target), before);+ } finally {+ store.closeBoard(source);+ store.closeBoard(target);+ rmSync(directory, { recursive: true, force: true });+ }+ });++ test('import refuses an export from another version before writing [A7]', () => {+ const directory = tempDirectory();+ const source = populatedBoard(join(directory, 'source.sqlite'));+ const target = store.openBoard(join(directory, 'target.sqlite'));+ try {+ const document = exportBoard(source);++ const before = exportBoard(target);+ document.version = 2;+ assert.throws(() => importBoard(target, document), /IMPORT_VERSION.*version 1/);- const empty = store.openBoard(':memory:');- try {- assert.deepEqual(exportBoard(target), exportBoard(empty));- } finally {- store.closeBoard(empty);- }++ assert.deepEqual(exportBoard(target), before);+ } finally {+ store.closeBoard(source);+ store.closeBoard(target);+ rmSync(directory, { recursive: true, force: true });+ }+ });++ test('export and import CLI commands exchange a versioned document between real repos [A7]', async () => {+ const directory = tempDirectory();+ const sourceRoot = join(directory, 'source');+ const targetRoot = join(directory, 'target');+ gitRepo(sourceRoot);+ gitRepo(targetRoot);+ const source = store.openBoard(join(sourceRoot, '.git', 'pullboard', 'board.sqlite'));+ store.register(source, { lane: 'coordinator', path: sourceRoot });+ store.closeBoard(source);+ const env = {+ ...process.env,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Exchange Test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Exchange Test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ PULLBOARD_HOME: join(directory, 'home'),+ };+ const cli = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });+ try {+ const initialized = cli(targetRoot, 'init');+ assert.equal(initialized.status, 0, initialized.stderr || initialized.stdout);+ assert.match(initialized.stdout, /coordinator/i);++ const exported = cli(sourceRoot, 'export', '--json');+ assert.equal(exported.status, 0, exported.stderr || exported.stdout);+ const document = JSON.parse(exported.stdout);+ writeFileSync(join(directory, 'board.json'), JSON.stringify(document));+ const imported = cli(targetRoot, 'import', join(directory, 'board.json'));+ assert.equal(imported.status, 0, imported.stderr || imported.stdout);+ assert.match(imported.stdout, /imported version 1 board tables/);++ const reexported = cli(targetRoot, 'export', '--json');+ assert.equal(reexported.status, 0, reexported.stderr || reexported.stdout);+ assert.deepEqual(JSON.parse(reexported.stdout), document, 'a board initialized by pullboard can receive the full export');++ const importedBoard = store.openBoard(join(targetRoot, '.git', 'pullboard', 'board.sqlite'));+ try {+ assert.deepEqual(JSON.parse(JSON.stringify(exportBoard(importedBoard))), document);+ } finally {+ store.closeBoard(importedBoard);+ }+ const status = cli(targetRoot, 'status');+ assert.equal(status.status, 0, status.stderr || status.stdout);+ const listed = cli(targetRoot, 'list', '--all');+ assert.equal(listed.status, 0, listed.stderr || listed.stdout);+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+ });++++++test('import preserves other metadata and refuses malformed fresh identities [A2,A7]', () => {++ const directory = tempDirectory();++ const source = populatedBoard(join(directory, 'source.sqlite'));++ try {++ for (const [index, change] of [++ "INSERT INTO board_meta VALUES ('retained', 'repo setting')",++ "UPDATE board_meta SET meta_value = 'invalid' WHERE meta_key = 'board_id'",++ ].entries()) {++ const target = store.openBoard(join(directory, `target-${index}.sqlite`));++ try {++ store.register(target, { lane: 'coordinator', path: '/target' });++ target.db.exec(change);++ const before = exportBoard(target);++ assert.throws(() => importBoard(target, exportBoard(source)), /IMPORT_NOT_EMPTY.*empty board/);++ assert.deepEqual(exportBoard(target), before, 'a refusal preserves every target row');++ } finally {++ store.closeBoard(target);++ }++ }++ } finally {++ store.closeBoard(source);++ rmSync(directory, { recursive: true, force: true });++ }++});