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(board): the board file refuses moves nobody declared [M3]
Corey Olsoned1bfc4b1269
diff --git a/src/board.js b/src/board.jsindex bb320d88..ccffb249 100644--- a/src/board.js+++ b/src/board.js@@ -11,6 +11,7 @@ import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { briefFiles, briefSections } from './brief.js';import { COORDINATOR } from './config.js';+import { storeTriggers } from './machine.js';import { Refused } from './refused.js';export const ACCEPT_REASON = 'CRITERION_MET';@@ -134,7 +135,44 @@ export function openBoard(file, clock = systemClock) {if (file !== ':memory:') db.exec('PRAGMA journal_mode = WAL');db.exec(SCHEMA);migrate(db);- return { db, clock };+ const board = { db, clock };+ guardStore(board);+ return board;+}++/** The board's PRAGMA user_version once its triggers are in: losing one after that is news. */+const GUARDED = 1;++/**+ * Install the triggers that make the board file refuse what the lifecycle does not allow (M3), and+ * put back any that are missing or differ from the declaration. A board that never had them is just+ * older and gets them quietly; a board that had them and lost one was edited by hand, so the event+ * log says which came back.+ *+ * @param {any} board+ */+function guardStore(board) {+ const wanted = storeTriggers();+ const drift = () => {+ const have = new Map(+ board.db.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'machine%'").all().map((row) => [row.name, row.sql]),+ );+ return {+ missing: wanted.filter(({ name }) => !have.has(name)).map(({ name }) => name),+ changed: wanted.filter(({ name, sql }) => have.has(name) && have.get(name) !== sql).map(({ name }) => name),+ stale: [...have.keys()].filter((name) => !wanted.some((trigger) => trigger.name === name)),+ };+ };+ const isWhole = ({ missing, changed, stale }) => !missing.length && !changed.length && !stale.length;+ if (isWhole(drift())) 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}`);+ });}/**diff --git a/src/machine.js b/src/machine.jsindex 6a539faa..b3657319 100644--- a/src/machine.js+++ b/src/machine.js@@ -26,6 +26,8 @@* @property {string} means* @property {boolean} [final] - Nothing leaves it.* @property {string[]} requires - Item fields that are set whenever an item is in this state.+ * @property {{ says: string, sql: string }} [proof] - What must exist before an item enters it, as an+ * SQL condition on NEW, the item row being written; the board file itself checks it (M3).*//**@@ -44,6 +46,9 @@/*** @typedef {object} Machine* @property {Role[]} roles+ * @property {string} initial - The state every item starts in.+ * @property {Record<string, 'append' | 'keep'>} records - Tables the board keeps for good: rows only+ * ever added (append), or rows never deleted (keep).* @property {State[]} states* @property {Guard[]} guards* @property {Move[]} moves@@ -57,12 +62,29 @@ export const IN_STATE = 'inState';/** @type {Role[]} */export const ROLES = ['agent', 'coordinator', 'clock'];+/** Where every item starts. */+export const INITIAL = 'open';++/**+ * What the board file keeps for good: the event log and verdicts are only ever added to (R2, V8),+ * and an item is withdrawn, never deleted.+ *+ * @type {Record<string, 'append' | 'keep'>}+ */+export const RECORDS = { event: 'append', verdict: 'append', item: 'keep' };+/** @type {State[]} */export const STATES = [{ id: 'open', means: 'waiting for a builder; claimable once what it waits on is verified', requires: [] },{ id: 'claimed', means: 'an agent holds it under a lease, its criterion frozen', requires: ['item_owner', 'item_lease_until', 'item_frozen_digest'] },{ id: 'submitted', means: 'built and gated green at a pinned commit, waiting for another agent', requires: ['item_built_by', 'item_commit', 'item_frozen_digest'] },- { id: 'verified', final: true, means: 'another agent accepted it at the submitted commit', requires: ['item_verified_by', 'item_commit'] },+ {+ id: 'verified', final: true, means: 'another agent accepted it at the submitted commit', requires: ['item_verified_by', 'item_commit'],+ proof: {+ says: 'an ACCEPT at the submitted commit, on the frozen criterion, by an agent that did not build it',+ sql: "EXISTS (SELECT 1 FROM verdict v WHERE v.item_id = NEW.item_id AND v.verdict_decision = 'ACCEPT' AND v.verdict_commit = NEW.item_commit AND v.verdict_digest = NEW.item_frozen_digest AND v.verdict_by <> NEW.item_built_by)",+ },+ },{ id: 'withdrawn', final: true, means: 'nobody should build it; the reason stays on it', requires: ['item_withdrawn_reason'] },];@@ -158,7 +180,7 @@ export const EXIT_GUARDS = {export const UNKNOWN_MOVE = { refuse: 'BAD_DECISION', rule: 'a verdict is accept or reject', next: 'pullboard verify <id> accept, or reject --reason CODE --note "..."' };/** @type {Machine} */-export const MACHINE = { roles: ROLES, states: STATES, guards: GUARDS, moves: MOVES, exitGuards: EXIT_GUARDS, unknownMove: UNKNOWN_MOVE };+export const MACHINE = { roles: ROLES, initial: INITIAL, records: RECORDS, states: STATES, guards: GUARDS, moves: MOVES, exitGuards: EXIT_GUARDS, unknownMove: UNKNOWN_MOVE };/*** The guards a move passes, in order: its own, then any exit guard of its target it left out.@@ -216,8 +238,8 @@ function unresolved(machine) {}/**- * Property 2: every state is reachable from open, every non-final state can still reach a final- * one (no traps), and nothing leaves a final state.+ * Property 2: every state is reachable from where items start, every non-final state can still+ * reach a final one (no traps), and nothing leaves a final state.** @param {Machine} machine* @returns {string[]}@@ -231,12 +253,12 @@ function unreachable(machine) {back.set(move.to, [...(back.get(move.to) ?? []), from]);}}- const fromOpen = reach('open', forward);+ const fromStart = reach(machine.initial, forward);const canEnd = new Set();for (const state of machine.states.filter((entry) => entry.final)) for (const id of reach(state.id, back)) canEnd.add(id);const problems = [];for (const state of machine.states) {- if (!fromOpen.has(state.id)) problems.push(`state ${state.id} cannot be reached from open`);+ if (!fromStart.has(state.id)) problems.push(`state ${state.id} cannot be reached from ${machine.initial}`);if (!canEnd.has(state.id)) problems.push(`state ${state.id} is a trap: no way from it to a final state`);if (state.final && forward.has(state.id)) problems.push(`final state ${state.id} has a move out`);}@@ -347,3 +369,61 @@ export function machineProblems(machine = MACHINE) {...missingFields(machine),];}++/**+ * Text as an SQL string literal.+ *+ * @param {string} text+ * @returns {string}+ */+const sqlText = (text) => `'${text.replaceAll("'", "''")}'`;++/**+ * The SQLite triggers that make the board file itself refuse what the declaration does not allow+ * (M3): an item that starts anywhere but the start, a state or a move nobody declared, a state+ * entered without its fields, a final state entered without its proof, and an edit to a record the+ * board keeps for good. All of it comes from the declaration, so the board reinstalls any trigger+ * that differs when the declaration changes.+ *+ * The triggers stop a status written by hand. They cannot stop an agent that forges a verdict row+ * under some name and then moves the item; that forgery stays in the ledger under the name it used.+ *+ * @param {Machine} [machine]+ * @returns {{ name: string, sql: string }[]}+ */+export function storeTriggers(machine = MACHINE) {+ const refuse = (code, text) => `BEGIN SELECT RAISE(ABORT, ${sqlText(`${code}: ${text}; the board changes only through pullboard commands`)}); END`;+ const onStatus = 'BEFORE UPDATE OF item_status ON item';+ const states = machine.states.map((state) => state.id);+ const moves = [...new Set(machine.moves.flatMap((move) => move.from.filter((from) => from !== move.to).map((from) => `${from}>${move.to}`)))];+ const declared = `OLD.item_status || '>' || NEW.item_status IN (${moves.map(sqlText).join(', ')})`;+ const entering = (state) => `NEW.item_status = ${sqlText(state)} AND OLD.item_status <> NEW.item_status AND ${declared}`;+ const trigger = (name, on, body) => ({ name, sql: `CREATE TRIGGER ${name} ${on}\n${body}` });+ // Each write meets at most one trigger: an unknown state, else an undeclared move, else missing+ // fields, else a missing proof. SQLite fires triggers in no promised order, so their conditions+ // exclude each other and the refusal never depends on which one ran first.+ const triggers = [+ trigger('machine_item_start', 'BEFORE INSERT ON item', `WHEN NEW.item_status <> ${sqlText(machine.initial)}\n${refuse('UNDECLARED_MOVE', `an item starts ${machine.initial}`)}`),+ trigger('machine_item_state', onStatus, `WHEN NEW.item_status NOT IN (${states.map(sqlText).join(', ')})\n${refuse('UNDECLARED_STATE', `an item is ${states.join(', ')}`)}`),+ trigger(+ 'machine_item_move',+ onStatus,+ `WHEN NEW.item_status IN (${states.map(sqlText).join(', ')}) AND OLD.item_status <> NEW.item_status AND NOT ${declared}\n${refuse('UNDECLARED_MOVE', `the moves are ${moves.join(', ')}`)}`,+ ),+ ];+ const missingOf = (state) => state.requires.map((field) => `coalesce(NEW.${field}, '') = ''`).join(' OR ');+ for (const state of machine.states.filter((entry) => entry.requires.length)) {+ triggers.push(trigger(`machine_fields_${state.id}`, onStatus, `WHEN ${entering(state.id)} AND (${missingOf(state)})\n${refuse('MISSING_FIELD', `${state.id} needs ${state.requires.join(', ')}`)}`));+ }+ for (const state of machine.states.filter((entry) => entry.proof)) {+ const complete = state.requires.length ? ` AND NOT (${missingOf(state)})` : '';+ triggers.push(trigger(`machine_proof_${state.id}`, onStatus, `WHEN ${entering(state.id)}${complete} AND NOT ${state.proof.sql}\n${refuse('NOT_PROVEN', `${state.id} needs ${state.proof.says}`)}`));+ }+ for (const [table, kept] of Object.entries(machine.records)) {+ for (const change of kept === 'append' ? ['update', 'delete'] : ['delete']) {+ const text = kept === 'append' ? `${table} rows are only ever added` : `an ${table} is withdrawn, never deleted`;+ triggers.push(trigger(`machine_${table}_${change}`, `BEFORE ${change.toUpperCase()} ON ${table}`, refuse(kept === 'append' ? 'APPEND_ONLY' : 'KEPT', text)));+ }+ }+ return triggers;+}diff --git a/test/machine.test.js b/test/machine.test.jsindex cc6bf856..d9bbea07 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -3,9 +3,13 @@* failing on a broken copy, and in step with the refusals board.js and cli.js raise today.*/import assert from 'node:assert/strict';-import { readFileSync } from 'node:fs';+import { mkdtempSync, readFileSync, 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 { IN_STATE, MACHINE, effectiveGuards, machineProblems } from '../src/machine.js';+import * as store from '../src/board.js';+import { IN_STATE, MACHINE, effectiveGuards, machineProblems, storeTriggers } from '../src/machine.js';/*** Refusals that are not about an item's lifecycle, so no move declares them: how a command was@@ -430,3 +434,208 @@ test('a broken copy of the code fails the check: a refusal added wherever a moveconst doubleQuoted = editedSource('cli.js', /^const cdTo = .*$/m, "const cdTo = (root) => { if (!root) throw new Refused(\"NO_ROOT\", 'no root'); return 'cd ' + root + ' &&'; };");assert.deepEqual(codeProblems(MACHINE, doubleQuoted), ['NO_ROOT is raised by accept and reject but not declared there']);});++const SHA_A = 'a'.repeat(40);+const SHA_B = 'b'.repeat(40);++/**+ * A freeze that digests the title, as the real one digests the criterion.+ *+ * @param {any} item+ * @returns {{ text: string, digest: string }}+ */+const freeze = (item) => ({ text: item.item_title, digest: `digest:${item.item_title}` });++/**+ * A board file on disk with a coordinator and two web agents, opened the way the CLI opens it,+ * and a way to open the same file raw, as any agent with a shell could.+ *+ * @returns {{ file: string, board: any, raw: () => DatabaseSync, done: () => void }}+ */+function boardOnDisk() {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-machine-'));+ const file = join(dir, 'board.sqlite');+ const board = store.openBoard(file);+ store.register(board, { lane: 'coordinator', path: '/repo' });+ store.register(board, { lane: 'web', path: '/repo-web-1' });+ store.register(board, { lane: 'web', path: '/repo-web-2' });+ const handles = [board.db];+ return {+ file,+ board,+ raw: () => {+ const db = new DatabaseSync(file);+ handles.push(db);+ return db;+ },+ done: () => {+ for (const db of handles) {+ try {+ db.close();+ } catch {+ // already closed by the test+ }+ }+ rmSync(dir, { recursive: true, force: true });+ },+ };+}++/**+ * An item web-1 claimed and submitted.+ *+ * @param {any} board+ * @returns {number}+ */+function submittedItem(board) {+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });+ store.claim(board, id, { agentId: 'web-1', lane: 'web', leaseMs: 7_200_000, freeze });+ store.submit(board, id, { agentId: 'web-1', commit: SHA_A, tree: 'tree' });+ return id;+}++/**+ * A verdict with what a careful verifier passes.+ *+ * @param {any} board+ * @param {number} id+ * @param {string} agentId+ * @param {'ACCEPT' | 'REJECT'} decision+ */+function verdictOn(board, id, agentId, decision) {+ const reason = decision === 'REJECT' ? { reason: 'TEST_FAILURE' } : {};+ store.verify(board, id, { agentId, decision, head: SHA_A, digest: 'digest:Page', policy: 'any', note: 'reverted the fix; its test went red; restored it', ...reason });+}++/**+ * Insert an ACCEPT by hand, as a forger would.+ *+ * @param {DatabaseSync} db+ * @param {number} id+ * @param {string} by+ * @param {string} commit+ * @param {string} [digest]+ */+function forgeAccept(db, id, by, commit, digest = 'digest:Page') {+ db.prepare(+ `INSERT INTO verdict (item_id, verdict_by, verdict_decision, verdict_reason, verdict_note, verdict_commit, verdict_digest, verdict_head, verdict_at)+ VALUES (?, ?, 'ACCEPT', 'CRITERION_MET', 'forged', ?, ?, ?, '2026-10-06T00:00:00Z')`,+ ).run(id, by, commit, digest, commit);+}++/**+ * The names of a board file's triggers.+ *+ * @param {any} board+ * @returns {string[]}+ */+const triggerNames = (board) => board.db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name").all().map((row) => row.name);++test('the board file refuses, written by hand: an unknown state, an undeclared move, an unproven verified, a reasonless withdrawal, an edited record [M3]', () => {+ const lab = boardOnDisk();+ try {+ const open = store.addItem(lab.board, { by: 'coordinator', lane: 'web', title: 'Page' });+ const built = submittedItem(lab.board);+ const raw = lab.raw();+ const refused = (sql, args, code) => assert.throws(() => raw.prepare(sql).run(...args), new RegExp(code), sql);+ refused('UPDATE item SET item_status = ? WHERE item_id = ?', ['shipped', open], 'UNDECLARED_STATE');+ refused('UPDATE item SET item_status = ? WHERE item_id = ?', ['verified', open], 'UNDECLARED_MOVE');+ refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-2' WHERE item_id = ?", [built], 'NOT_PROVEN');+ forgeAccept(raw, built, 'web-1', SHA_A);+ refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-1' WHERE item_id = ?", [built], 'NOT_PROVEN');+ forgeAccept(raw, built, 'web-2', SHA_B);+ refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-2' WHERE item_id = ?", [built], 'NOT_PROVEN');+ forgeAccept(raw, built, 'web-2', SHA_A, 'digest:Another criterion');+ refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-2' WHERE item_id = ?", [built], 'NOT_PROVEN');+ refused("UPDATE item SET item_status = 'withdrawn' WHERE item_id = ?", [open], 'MISSING_FIELD');+ refused("UPDATE event SET event_kind = 'nothing' WHERE event_id = 1", [], 'APPEND_ONLY');+ refused('DELETE FROM event', [], 'APPEND_ONLY');+ refused("UPDATE verdict SET verdict_by = 'web-2'", [], 'APPEND_ONLY');+ refused('DELETE FROM verdict', [], 'APPEND_ONLY');+ refused('DELETE FROM item WHERE item_id = ?', [open], 'KEPT');+ refused(+ "INSERT INTO item (item_lane, item_title, item_status, item_created_by, item_created_at, item_updated_at) VALUES ('web', 'Forged', 'verified', 'web-1', 'now', 'now')",+ [],+ 'UNDECLARED_MOVE',+ );+ assert.equal(store.getItem(lab.board, open).item_status, 'open');+ assert.equal(store.getItem(lab.board, built).item_status, 'submitted');+ } finally {+ lab.done();+ }+});++test('every move the board makes passes the triggers: claim, submit, accept, reject, rework, release, escalate, refreeze, withdraw [M3]', () => {+ const lab = boardOnDisk();+ try {+ const { board } = lab;+ const accepted = submittedItem(board);+ verdictOn(board, accepted, 'web-2', 'ACCEPT');+ store.merged(board, accepted, { agentId: 'coordinator', commit: SHA_A });+ const rejected = submittedItem(board);+ verdictOn(board, rejected, 'web-2', 'REJECT');+ store.claim(board, rejected, { agentId: 'web-1', lane: 'web', leaseMs: 7_200_000, freeze });+ store.release(board, rejected, 'web-1');+ store.escalate(board, rejected, { agentId: 'coordinator', note: 'two tries stayed red' });+ store.refreeze(board, rejected, { agentId: 'coordinator', freeze });+ const dropped = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Old idea' });+ store.claim(board, dropped, { agentId: 'web-2', lane: 'web', leaseMs: 7_200_000, freeze });+ store.withdraw(board, dropped, { agentId: 'coordinator', reason: 'superseded' });+ assert.deepEqual([accepted, rejected, dropped].map((id) => store.getItem(board, id).item_status), ['verified', 'open', 'withdrawn']);+ } finally {+ lab.done();+ }+});++test('an older board gets the triggers quietly on its next open; one dropped by hand comes back, and the log says so [M3]', () => {+ const lab = boardOnDisk();+ try {+ const id = store.addItem(lab.board, { by: 'coordinator', lane: 'web', title: 'Page' });+ const every = storeTriggers().map(({ name }) => name).sort();+ assert.deepEqual(triggerNames(lab.board), every);+ store.closeBoard(lab.board);++ const older = lab.raw();+ for (const name of every) older.exec(`DROP TRIGGER ${name}`);+ older.exec('PRAGMA user_version = 0');+ older.prepare("UPDATE item SET item_status = 'verified' WHERE item_id = ?").run(id);+ older.prepare("UPDATE item SET item_status = 'open' WHERE item_id = ?").run(id);+ older.close();++ const upgraded = store.openBoard(lab.file);+ assert.deepEqual(triggerNames(upgraded), every);+ assert.equal(upgraded.db.prepare("SELECT COUNT(*) AS n FROM event WHERE event_kind = 'guards'").get().n, 0, 'an older board gets them quietly');+ store.closeBoard(upgraded);++ const tampered = lab.raw();+ tampered.exec('DROP TRIGGER machine_proof_verified');+ tampered.exec('DROP TRIGGER machine_item_move');+ tampered.exec('CREATE TRIGGER machine_item_move BEFORE UPDATE OF item_status ON item WHEN 0 BEGIN SELECT 1; END');+ tampered.close();++ const restored = store.openBoard(lab.file);+ try {+ assert.deepEqual(triggerNames(restored), every);+ const logged = restored.db.prepare("SELECT event_by, event_detail FROM event WHERE event_kind = 'guards'").all();+ assert.deepEqual(logged.map((row) => [row.event_by, JSON.parse(row.event_detail)]), [['board', { missing: ['machine_proof_verified'], changed: ['machine_item_move'], stale: [] }]]);+ assert.throws(() => lab.raw().prepare("UPDATE item SET item_status = 'verified' WHERE item_id = ?").run(id), /UNDECLARED_MOVE/);+ } finally {+ store.closeBoard(restored);+ }+ } finally {+ lab.done();+ }+});++test('the triggers come from the declaration, so a changed declaration changes them [M1, M3]', () => {+ const moveSql = (machine) => storeTriggers(machine).find(({ name }) => name === 'machine_item_move').sql;+ const pairs = MACHINE.moves.flatMap((move) => move.from.filter((from) => from !== move.to).map((from) => `'${from}>${move.to}'`));+ for (const pair of pairs) assert.ok(moveSql(MACHINE).includes(pair), `the move trigger allows ${pair}`);+ assert.ok(!moveSql(MACHINE).includes("'open>submitted'"));+ const machine = copy();+ machine.moves.push({ verb: 'land', from: ['open'], to: 'submitted', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', IN_STATE], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'] });+ assert.ok(moveSql(machine).includes("'open>submitted'"));+ const names = storeTriggers().map(({ name }) => name);+ for (const state of MACHINE.states.filter((entry) => entry.requires.length)) assert.ok(names.includes(`machine_fields_${state.id}`), `${state.id} has a fields trigger`);+ assert.ok(names.includes('machine_proof_verified'));+});