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): serve local board moves and live events [A2,R2]
Corey Olsonc99c654d22dd
diff --git a/src/api.js b/src/api.jsnew file mode 100644index 00000000..236f1fb3--- /dev/null+++ b/src/api.js@@ -0,0 +1,241 @@+/** 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'] },+ 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 (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 --git a/src/board.js b/src/board.jsindex 3a1d84f9..bb5bbc1d 100644--- a/src/board.js+++ b/src/board.js@@ -6,6 +6,7 @@* every move lands in an append-only event log (R2). The caller supplies what only git and the* spec know: the commit, the verifier's checkout, the frozen criterion.*/+import { randomBytes } from 'node:crypto';import { mkdirSync } from 'node:fs';import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';@@ -47,6 +48,10 @@ export const REJECT_REASONS = [export const systemClock = { now: () => new Date() };const SCHEMA = `+ CREATE TABLE IF NOT EXISTS board_meta (+ meta_key TEXT PRIMARY KEY,+ meta_value TEXT NOT NULL+ );CREATE TABLE IF NOT EXISTS agent (agent_id TEXT PRIMARY KEY,agent_lane TEXT NOT NULL,@@ -135,6 +140,7 @@ export function openBoard(file, clock = systemClock) {if (file !== ':memory:') db.exec('PRAGMA journal_mode = WAL');db.exec(SCHEMA);migrate(db);+ db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('board_id', randomBytes(16).toString('hex'));const board = { db, clock };guardStore(board);guardMoves(board);@@ -162,6 +168,7 @@ function guardMoves(board) {}/** The board's PRAGMA user_version once its triggers are in: losing one after that is news. */+export const SCHEMA_VERSION = 2;const GUARDED = 1;/**@@ -185,14 +192,17 @@ function guardStore(board) {};};const isWhole = ({ missing, changed, stale }) => !missing.length && !changed.length && !stale.length;- if (isWhole(drift())) return;+ if (isWhole(drift())) {+ if (board.db.prepare('PRAGMA user_version').get().user_version < SCHEMA_VERSION) board.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);+ return;+ }atomic(board, () => {const found = drift();if (isWhole(found)) return;for (const name of [...found.changed, ...found.stale]) board.db.exec(`DROP TRIGGER IF EXISTS "${name}"`);for (const { name, sql } of wanted) if (found.missing.includes(name) || found.changed.includes(name)) board.db.exec(sql);if (board.db.prepare('PRAGMA user_version').get().user_version >= GUARDED) logEvent(board, 'board', 'guards', null, found);- else board.db.exec(`PRAGMA user_version = ${GUARDED}`);+ if (board.db.prepare('PRAGMA user_version').get().user_version < SCHEMA_VERSION) board.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);});}@@ -219,6 +229,8 @@ function migrate(db) {['shout', 'shout_evidence_outcome', 'TEXT'],['shout', 'shout_evidence_item', 'INTEGER'],['shout', 'shout_evidence_commit', 'TEXT'],+ ['shout', 'shout_request', 'INTEGER NOT NULL DEFAULT 0'],+ ['shout', 'shout_request_outcome', "TEXT NOT NULL DEFAULT ''"],];for (const [table, column, type] of added) {const columns = db.prepare(`PRAGMA table_info(${table})`).all().map((entry) => entry.name);@@ -226,6 +238,11 @@ function migrate(db) {}}+/** The persistent local and relay identity of this board (A2). */+export function boardId(board) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('board_id').meta_value;+}+/*** Close the board's file.*@@ -280,6 +297,7 @@ function logEvent(board, by, kind, itemId, detail = {}) {).run(now(board), by, kind, itemId, JSON.stringify(detail));board.lastEvent = board.db.prepare('SELECT * FROM event WHERE event_id = ?').get(inserted.lastInsertRowid);+ (board.emittedEvents ??= []).push(board.lastEvent);}/**@@ -1120,24 +1138,45 @@ export function verdictsFor(board, id) {* @param {any} board* @param {{ from: string, to: string, text: string, lanes: string[] }} message*/-export function shout(board, { from, to, text, lanes, decision = false, answers = null, evidence = null }) {- if (!text.trim()) throw new Refused('EMPTY_SHOUT', 'a shout needs text');- const isAgent = board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(to);- if (to !== 'all' && !lanes.includes(to) && !isAgent) {- throw new Refused('NO_READER', `nobody reads "${to}": name a lane, an agent or all`);- }- if (answers !== null && !getShout(board, answers).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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- )- .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);+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');+ }+ 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`);+ }+ 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`);+ }+ 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;+ });}/** The kinds of evidence a shout can carry (B22): what was tried, or what was measured. */@@ -1185,6 +1224,13 @@ export function openDecisions(board) {.all();}+/** 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.*/@@ -1206,7 +1252,10 @@ export function inbox(board, agentId) {.all(agent.agent_last_shout_id, agentId, agent.agent_lane, agentId);const last = shouts.at(-1)?.shout_id ?? agent.agent_last_shout_id;board.db.prepare('UPDATE agent SET agent_last_shout_id = ? WHERE agent_id = ?').run(last, agentId);- return shouts;+ if (agentId !== COORDINATOR) return shouts;+ const requests = openRequests(board);+ const ids = new Set(requests.map((shout) => shout.shout_id));+ return [...requests, ...shouts.filter((shout) => !ids.has(shout.shout_id))];});}diff --git a/src/cli.js b/src/cli.jsindex 35b848fd..eb09d083 100644--- a/src/cli.js+++ b/src/cli.js@@ -46,6 +46,7 @@ import { commandOutput } from './json.js';import { forgetProject, registerProject } from './projects.js';import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';import { serveView } from './serve.js';+import { serveApi } from './api.js';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));export const VERSION = PACKAGE.version;@@ -62,6 +63,8 @@ Set uppullboard whoami | lanes | status who you are, the lanes, the board at a glancepullboard view [--port N] [--no-open] every project on this machine in your browser: items, shouts, doctrine,agents and activity, live; add items, shout and hold lanes from it+ pullboard serve [--port N] local API v1: boards, state, moves, requests and live events,+ behind the session secret in its printed addresspullboard resume where you are: your claim, branch, uncommitted work, what came back,unread shouts, what to do next; run it to start any sessionpullboard hooks reinstall the git hooks (e.g. after a fresh clone)@@ -344,9 +347,10 @@ function configHere(info) {*/function withBoard(ctx, work) {const board = store.openBoard(ctx.file, ctx.clock);+ const firstEvent = board.emittedEvents?.length ?? 0;try {const result = work(board);- if (board.lastEvent) ctx.io.onEvent?.(board.lastEvent);+ for (const event of board.emittedEvents?.slice(firstEvent) ?? []) ctx.io.onEvent?.(event);return result;} finally {store.closeBoard(board);@@ -523,6 +527,7 @@ const reworkNext = (card) => `pullboard claim ${card.sentBack[0].item.item_id},* @returns {string}*/function coordinatorNext(card, rows) {+ if (card.requests.length) return `answer request #${card.requests[0].shout_id}: pullboard answer ${card.requests[0].shout_id} done, or declined <reason>`;const live = rows.filter((row) => !['wont', 'retired'].includes(row.status));if (!live.length) return "turn what the person wants into spec rows with them: the pullboard-decompose skill (pullboard prompt decompose)";const approved = live.filter((row) => row.status === 'approved');@@ -562,6 +567,7 @@ function resumeHere(io) {return {me,all,+ requests: me.id === COORDINATOR ? store.openRequests(board) : [],holding: all.filter((item) => item.item_status === 'claimed' && item.item_owner === me.id),sentBack: all.filter((item) => item.item_status === 'open' && item.item_verdict === 'REJECT' && item.item_built_by === me.id)@@ -591,6 +597,7 @@ function resumeHere(io) {} else if (dirty) {say(`${plural(dirty, 'file')} uncommitted in the main checkout`);}+ for (const request of card.requests) say(`request #${request.shout_id}: ${request.shout_text}; answer with pullboard answer ${request.shout_id} done, or declined <reason>`);for (const item of card.holding) {say(`holding #${item.item_id} ${item.item_title}, lease ${span(ctx, item.item_lease_until)} left${item.item_check ? `; check: ${item.item_check}` : ''}`);const files = briefFiles(item.item_brief);@@ -661,6 +668,27 @@ async function viewHere(io, values) {return 0;}+/** Serve API v1 until a shutdown signal, printing its address before waiting (A2). */+async function serveHere(io, values) {+ const ctx = context(io);+ const mainRoot = git(ctx.info.root, ['worktree', 'list', '--porcelain']).split('\n')[0].slice('worktree '.length);+ registerProject(mainRoot, new Date(), loadConfig(mainRoot));+ const port = values.port === undefined ? 0 : Number(values.port);+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Refused('USAGE', '--port is a number from 0 to 65535; use 0 to choose a free one');+ const api = await serveApi({ port, runCommand: main });+ io.result?.({ url: api.url, port: api.port });+ io.say(`Pullboard API v1: ${api.url}`);+ io.say('Only this machine can reach it, with its session secret. Ctrl-C stops it.');+ io.flush?.(0);+ await new Promise((stop) => {+ const stopped = () => { process.off('SIGINT', stopped); process.off('SIGTERM', stopped); stop(); };+ process.once('SIGINT', stopped);+ process.once('SIGTERM', stopped);+ });+ await api.close();+ return 0;+}+/*** The commands that set a repo or a worktree up.*@@ -1550,6 +1578,7 @@ async function runCommand(argv, io) {return 0;}if (command === 'view') return await viewHere(io, values);+ if (command === 'serve') return await serveHere(io, values);if (command === 'forget') {if (!first || second) throw new Refused('USAGE', 'pullboard forget <path>');const root = resolve(io.cwd, first);@@ -1611,6 +1640,6 @@ export function resultCommands() {...Object.keys(setupCommands({}, args)),...Object.keys(readCommands({}, args)),...Object.keys(workCommands({}, args)),- 'help', 'version', 'tour', 'lifecycle', 'view', 'forget', 'spec', 'prompt', 'hook', 'gate',+ 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'forget', 'spec', 'prompt', 'hook', 'gate',])].sort();}diff --git a/src/json.js b/src/json.jsindex 84169483..8d297dcc 100644--- a/src/json.js+++ b/src/json.js@@ -15,7 +15,7 @@ export const JSON_SHAPES = {hooks: shape({ notes: 'array' }),join: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string' }),worktree: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', branch: 'string', prompt: 'string' }),- resume: shape({ me: 'object', all: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: 'string' }),+ resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: 'string' }),whoami: shape({ id: 'string', lane: 'string', path: 'string' }),lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),list: shape({ items: 'array' }),@@ -46,6 +46,7 @@ export const JSON_SHAPES = {tour: shape({ messages: 'array' }),lifecycle: shape({ markdown: 'string' }),view: shape({ url: 'string', port: 'number' }),+ serve: shape({ url: 'string', port: 'number' }),forget: shape({ root: 'string' }),prompt: shape({ role: 'string', text: 'string' }),gate: shape({ green: 'boolean', report: 'string' }),@@ -59,6 +60,13 @@ export const JSON_SHAPES = {'hook commit-msg': shape({ messages: 'array' }),'hook pre-push': shape({ messages: 'array' }),},+ http: {+ boards: shape({ boards: 'array' }),+ state: shape({ state: 'object' }),+ events: shape({ events: 'array' }),+ move: shape({ event: 'object', result: 'object' }),+ stream: shape({ event: 'object' }),+ },error: shape({ error: 'object' }),errorFields: { code: 'string', message: 'string', next: 'string' },};@@ -69,6 +77,12 @@ function nextStep(message) {return match?.[1] ?? 'Run pullboard help, correct the reported problem, and retry the command.';}+/** A refusal shared by the CLI and API, retaining its rule and repair guidance (A1, A2). */+export function refusalDocument(error) {+ const message = String(error.message).replace(/^\[[A-Z_]+\] /, '');+ return { version: JSON_SHAPES.version, error: { code: error.code ?? 'INTERNAL', message, next: nextStep(message) } };+}+/*** Collect one command's output; text mode writes immediately and JSON mode writes one document.* Long-running view explicitly flushes its address before waiting for a shutdown signal.@@ -92,7 +106,7 @@ export function commandOutput(argv, streams) {const text = refusal?.message ?? [...diagnostics, ...messages].join('\n');const match = /\[([A-Z_]+)\]\s*([\s\S]*)/.exec(text);const message = refusal ? text.replace(/^\[[A-Z_]+\] /, '') : match?.[2] ?? text;- document = { version: JSON_SHAPES.version, error: { code: refusal?.code ?? match?.[1] ?? (code === 2 ? 'USAGE' : 'COMMAND_FAILED'), message, next: nextStep(message) } };+ document = refusalDocument({ code: refusal?.code ?? match?.[1] ?? (code === 2 ? 'USAGE' : 'COMMAND_FAILED'), message });} else if (result !== undefined) {document = { version: JSON_SHAPES.version, ...result };} else {diff --git a/test/api-identity.test.js b/test/api-identity.test.jsnew file mode 100644index 00000000..082e49f2--- /dev/null+++ b/test/api-identity.test.js@@ -0,0 +1,105 @@+/** Board identity is random, durable across moves and added to older boards in place (A2). */+import assert from 'node:assert/strict';+import { mkdtempSync, renameSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { test } from 'node:test';+import * as store from '../src/board.js';++/** Make a unique directory for a real SQLite board file. */+function boardFile() {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-identity-'));+ return { directory, file: join(directory, 'board.sqlite') };+}++test('[A2] fresh boards receive distinct 128-bit identities', () => {+ const first = boardFile();+ const second = boardFile();+ try {+ const boardA = store.openBoard(first.file);+ const boardB = store.openBoard(second.file);+ try {+ const idA = store.boardId(boardA);+ const idB = store.boardId(boardB);+ assert.match(idA, /^[0-9a-f]{32}$/);+ assert.match(idB, /^[0-9a-f]{32}$/);+ assert.notEqual(idA, idB);+ } finally {+ store.closeBoard(boardA);+ store.closeBoard(boardB);+ }+ } finally {+ rmSync(first.directory, { recursive: true, force: true });+ rmSync(second.directory, { recursive: true, force: true });+ }+});++test('[A2] board identity survives connection reopen and moving its directory', () => {+ const box = boardFile();+ const movedDirectory = `${box.directory}-moved`;+ try {+ const board = store.openBoard(box.file);+ const originalId = store.boardId(board);+ store.closeBoard(board);++ const reopened = store.openBoard(box.file);+ assert.equal(store.boardId(reopened), originalId);+ store.closeBoard(reopened);++ renameSync(box.directory, movedDirectory);+ const moved = store.openBoard(join(movedDirectory, 'board.sqlite'));+ try {+ assert.equal(store.boardId(moved), originalId);+ } finally {+ store.closeBoard(moved);+ }+ } finally {+ rmSync(box.directory, { recursive: true, force: true });+ rmSync(movedDirectory, { recursive: true, force: true });+ }+});++test('[A2] an older board gains one identity during in-place upgrade without losing rows', () => {+ const box = boardFile();+ try {+ const board = store.openBoard(box.file);+ store.register(board, { lane: 'coordinator', path: '/repo' });+ const itemId = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Preserved item' });+ const before = {+ agents: board.db.prepare('SELECT * FROM agent ORDER BY agent_id').all(),+ items: board.db.prepare('SELECT * FROM item ORDER BY item_id').all(),+ events: board.db.prepare('SELECT * FROM event ORDER BY event_id').all(),+ };+ store.closeBoard(board);++ const old = new DatabaseSync(box.file);+ old.exec('DROP TABLE board_meta; PRAGMA user_version = 1');+ old.close();++ const upgraded = store.openBoard(box.file);+ let id;+ try {+ id = store.boardId(upgraded);+ assert.match(id, /^[0-9a-f]{32}$/);+ assert.equal(upgraded.db.prepare('PRAGMA user_version').get().user_version, 2);+ assert.deepEqual(upgraded.db.prepare('SELECT * FROM agent ORDER BY agent_id').all(), before.agents);+ assert.deepEqual(upgraded.db.prepare('SELECT * FROM item ORDER BY item_id').all(), before.items);+ assert.deepEqual(upgraded.db.prepare('SELECT * FROM event ORDER BY event_id').all(), before.events);+ assert.equal(upgraded.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key = 'board_id'").get().meta_value, id);+ assert.equal(store.getItem(upgraded, itemId).item_title, 'Preserved item');+ } finally {+ store.closeBoard(upgraded);+ }++ const reopened = store.openBoard(box.file);+ try {+ assert.equal(store.boardId(reopened), id);+ assert.equal(reopened.db.prepare("SELECT COUNT(*) AS count FROM board_meta WHERE meta_key = 'board_id'").get().count, 1);+ } finally {+ store.closeBoard(reopened);+ }+ } finally {+ rmSync(box.directory, { recursive: true, force: true });+ }+});diff --git a/test/api-requests.test.js b/test/api-requests.test.jsnew file mode 100644index 00000000..e3a98859--- /dev/null+++ b/test/api-requests.test.js@@ -0,0 +1,104 @@+/** Person requests stay open until answered and their messages enter the event log (A2). */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } 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';++/** Make a real throwaway SQLite board with a coordinator and one lane agent. */+function boardFor(t) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-api-requests-'));+ t.after(() => rmSync(directory, { recursive: true, force: true }));+ const board = store.openBoard(join(directory, 'board.sqlite'));+ t.after(() => store.closeBoard(board));+ store.register(board, { lane: 'coordinator', path: join(directory, 'repo') });+ store.register(board, { lane: 'app', path: join(directory, 'app-1') });+ return board;+}++/** Add one message's declared lanes for the fixture board. */+const lanes = ['coordinator', 'app'];++test('[A2] a request stays open after inbox read, while ordinary decisions keep their lifecycle', (t) => {+ const board = boardFor(t);+ const request = store.shout(board, {+ from: 'person', to: 'coordinator', text: 'Approve the API row', lanes, request: true,+ });+ const decision = store.shout(board, {+ from: 'app-1', to: 'coordinator', text: 'May I change the contract?', lanes, decision: true,+ });++ const firstInbox = store.inbox(board, 'coordinator');+ assert.deepEqual(firstInbox.map((message) => message.shout_id), [request, decision]);+ assert.deepEqual(store.openRequests(board).map((message) => message.shout_id), [request]);+ assert.deepEqual(store.openDecisions(board).map((message) => message.shout_id), [decision]);+ assert.deepEqual(store.inbox(board, 'coordinator').map((message) => message.shout_id), [request], 'open requests are prepended again after the unread cursor advances');+ assert.deepEqual(store.openRequests(board).map((message) => message.shout_id), [request], 'reading does not close the request');++ store.shout(board, {+ from: 'coordinator', to: 'person', text: 'done', lanes, answers: request,+ });+ assert.deepEqual(store.openRequests(board), [], 'the request closes only when the coordinator answers');+ assert.deepEqual(store.openDecisions(board).map((message) => message.shout_id), [decision], 'answering a request does not answer an ordinary decision');+ store.shout(board, {+ from: 'coordinator', to: 'app-1', text: 'Yes, keep the change within the approved row.', lanes, answers: decision,+ });+ assert.deepEqual(store.openDecisions(board), []);+});++test('[A2] only the coordinator may decline a request, and a decline needs a reason', (t) => {+ const board = boardFor(t);+ const request = store.shout(board, {+ from: 'person', to: 'coordinator', text: 'Approve the API row', lanes, request: true,+ });+ const countBefore = board.db.prepare('SELECT COUNT(*) AS count FROM shout').get().count;+ const eventsBefore = store.events(board).length;++ assert.throws(() => store.shout(board, {+ from: 'coordinator', to: 'person', text: 'declined', lanes, answers: request,+ }), (error) => error.code === 'REQUEST_OUTCOME');+ assert.throws(() => store.shout(board, {+ from: 'app-1', to: 'person', text: 'declined because it is out of scope', lanes, answers: request,+ }), (error) => error.code === 'COORDINATOR_ONLY');+ assert.equal(board.db.prepare('SELECT COUNT(*) AS count FROM shout').get().count, countBefore);+ assert.equal(store.events(board).length, eventsBefore);+ assert.deepEqual(store.openRequests(board).map((message) => message.shout_id), [request]);++ const reply = store.shout(board, {+ from: 'coordinator', to: 'person', text: 'declined because it is out of scope', lanes, answers: request,+ });+ assert.equal(store.getShout(board, reply).shout_request_outcome, 'declined');+ assert.equal(store.getShout(board, reply).shout_text, 'declined because it is out of scope');+ assert.deepEqual(store.openRequests(board), []);+});++test('[A2] successful shouts and answers each append their corresponding event', (t) => {+ const board = boardFor(t);+ const baseline = store.events(board).length;+ const request = store.shout(board, {+ from: 'person', to: 'coordinator', text: 'Approve the API row', lanes, request: true,+ });+ const afterRequest = store.events(board);+ const requestEvent = afterRequest.at(-1);+ assert.equal(afterRequest.length, baseline + 1);+ assert.equal(requestEvent.event_by, 'person');+ assert.equal(requestEvent.event_kind, 'shout');+ assert.deepEqual(JSON.parse(requestEvent.event_detail), {+ shout: request, to: 'coordinator', decision: false, request: true, answers: null,+ });++ const answer = store.shout(board, {+ from: 'coordinator', to: 'person', text: 'done', lanes, answers: request,+ });+ const afterAnswer = store.events(board);+ const answerEvent = afterAnswer.at(-1);+ assert.equal(afterAnswer.length, baseline + 2);+ assert.equal(answerEvent.event_by, 'coordinator');+ assert.equal(answerEvent.event_kind, 'answer');+ assert.deepEqual(JSON.parse(answerEvent.event_detail), {+ shout: answer, to: 'person', decision: false, request: false, answers: request, outcome: 'done',+ });+ assert.deepEqual(afterAnswer.slice(-2).map((event) => event.event_id), [requestEvent.event_id, answerEvent.event_id]);+ assert.equal(store.getShout(board, answer).shout_answers, request);+});diff --git a/test/api.test.js b/test/api.test.jsindex abc35bda..d15da8a3 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -322,10 +322,56 @@ test('[A1] refusals are one JSON document with exact public error fields', () =>rmSync(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 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');@@ -333,37 +379,216 @@ test('[A1] view flushes one JSON document before shutdown', async (t) => {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 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 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 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] 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: 'claim', item: added.result.item.item_id, args: {}, agent: 'app-1' }) });+ assert.equal(claimedResponse.status, 200);+ const claimed = await claimedResponse.json();+ assert.equal(claimed.event.event_by, 'app-1');++ 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=${claimed.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();+ 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, []);+});++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 --git a/test/boundary.test.js b/test/boundary.test.jsindex f0e34a10..6359755c 100644--- a/test/boundary.test.js+++ b/test/boundary.test.js@@ -34,9 +34,9 @@ test('the core names no model, engine or vendor; secret patterns may name the keassert.deepEqual(found, []);});-test('the core opens no outbound connection; only the view listens, on loopback, and its page calls only it [P5, N26]', () => {+test('the core opens no outbound connection; the view and API listen on loopback, and the page calls only them [P5, N26, A2]', () => {const allowed = (file, line) =>- (file === 'src/serve.js' && line.trim() === "import { createServer } from 'node:http';") ||+ (['src/serve.js', 'src/api.js'].includes(file) && line.trim() === "import { createServer } from 'node:http';") ||(file === 'src/cockpit.js' && /^\s*const res = await fetch\(path, /.test(line));const found = sources().flatMap(({ file, lines }) =>lines.flatMap((line, index) => (NETWORK.test(line) && !allowed(file, line) ? [`${file}:${index + 1}: ${line.trim()}`] : [])),@@ -45,5 +45,8 @@ test('the core opens no outbound connection; only the view listens, on loopback,const serve = readFileSync(join(ROOT, 'src', 'serve.js'), 'utf8');assert.match(serve, /export const LOOPBACK = '127\.0\.0\.1';/);assert.match(serve, /server\.listen\(port, LOOPBACK, /);+ const api = readFileSync(join(ROOT, 'src', 'api.js'), 'utf8');+ assert.match(api, /const ADDRESS = '127\.0\.0\.1';/);+ assert.match(api, /server\.listen\(port, ADDRESS, /);assert.match(serve, /connect-src 'self'/, "the page may call nothing but its own server");});