Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

test: unit and end-to-end suites, two-process claim race

Corey Olsonf1912fd509a8
diff --git a/test/board.test.js b/test/board.test.js
new file mode 100644
index 00000000..54a4e889
--- /dev/null
+++ b/test/board.test.js
@@ -0,0 +1,195 @@
+/**
+ * The board's rules on an in-memory board with a hand-turned clock (B4–B7, V1, V2, V5, V6, V8, R1,
+ * R2). The git-facing rules (V3, V4, V7) run against real repos in e2e.test.js.
+ */
+import assert from 'node:assert/strict';
+import { beforeEach, test } from 'node:test';
+import * as store from '../src/board.js';
+
+const HOUR = 3_600_000;
+const SHA_A = 'a'.repeat(40);
+const SHA_B = 'b'.repeat(40);
+let board;
+let clock;
+
+/**
+ * A freeze that digests the item's title, like the real one digests its criterion.
+ */
+const freeze = (item) => ({ text: item.item_title, digest: `digest:${item.item_title}` });
+
+/**
+ * Claim as an agent in its lane, with a 2-hour lease.
+ */
+const claimAs = (id, agentId, lane) => store.claim(board, id, { agentId, lane, leaseMs: 2 * HOUR, freeze });
+
+beforeEach(() => {
+ let at = Date.parse('2026-10-04T12:00:00Z');
+ clock = { now: () => new Date(at), advance: (ms) => { at += ms; } };
+ board = store.openBoard(':memory:', clock);
+ 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' });
+ store.register(board, { lane: 'api', path: '/repo-api-1' });
+});
+
+test('agents are numbered per lane; one coordinator; a worktree joins once', () => {
+ assert.deepEqual(store.listAgents(board).map((agent) => agent.agent_id), ['coordinator', 'web-1', 'web-2', 'api-1']);
+ assert.equal(store.register(board, { lane: 'web', path: '/repo-web-1' }), 'web-1');
+ assert.throws(() => store.register(board, { lane: 'api', path: '/repo-web-1' }), /ALREADY_JOINED/);
+ assert.throws(() => store.register(board, { lane: 'coordinator', path: '/elsewhere' }), /ONE_COORDINATOR/);
+});
+
+test('the coordinator follows the main checkout when the repo moves', () => {
+ assert.equal(store.ensureCoordinator(board, '/moved/repo'), 'coordinator');
+ assert.equal(store.agentAt(board, '/moved/repo').agent_id, 'coordinator');
+});
+
+test('a claim is a lease: renewable by its holder, free again once it lapses [B4]', () => {
+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });
+ claimAs(id, 'web-1', 'web');
+ assert.throws(() => claimAs(id, 'web-2', 'web'), /HELD/);
+ assert.equal(claimAs(id, 'web-1', 'web').renewed, true);
+ clock.advance(2 * HOUR + 1);
+ assert.equal(store.getItem(board, id).item_status, 'open');
+ assert.equal(claimAs(id, 'web-2', 'web').renewed, false);
+ assert.equal(store.getItem(board, id).item_owner, 'web-2');
+});
+
+test('one live top-level claim per agent; child items are free; lanes hold [B5]', () => {
+ const first = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'One' });
+ const second = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Two' });
+ const child = store.addItem(board, { by: 'web-1', lane: 'web', title: 'One, part', parentId: first });
+ const api = store.addItem(board, { by: 'coordinator', lane: 'api', title: 'Endpoint' });
+ claimAs(first, 'web-1', 'web');
+ assert.throws(() => claimAs(second, 'web-1', 'web'), /ONE_CLAIM/);
+ claimAs(child, 'web-1', 'web');
+ assert.throws(() => claimAs(api, 'web-1', 'web'), /WRONG_LANE/);
+ claimAs(api, 'coordinator', 'coordinator');
+ assert.throws(
+ () => store.addItem(board, { by: 'web-1', lane: 'api', title: 'Cross', parentId: first }),
+ /PARENT_LANE/,
+ );
+});
+
+test('the first claim freezes the criterion; later claims keep it [V2]', () => {
+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });
+ assert.equal(claimAs(id, 'web-1', 'web').digest, 'digest:Page');
+ store.release(board, id, 'web-1');
+ const other = (item) => ({ text: 'changed', digest: `other:${item.item_id}` });
+ store.claim(board, id, { agentId: 'web-2', lane: 'web', leaseMs: HOUR, freeze: other });
+ assert.equal(store.getItem(board, id).item_frozen_digest, 'digest:Page');
+});
+
+test('submit needs your claim and finished children', () => {
+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });
+ const child = store.addItem(board, { by: 'web-1', lane: 'web', title: 'Part', parentId: id });
+ assert.throws(() => store.submit(board, id, { agentId: 'web-1', commit: SHA_A, tree: 't' }), /NOT_YOURS/);
+ claimAs(id, 'web-1', 'web');
+ assert.throws(() => store.submit(board, id, { agentId: 'web-1', commit: SHA_A, tree: 't' }), /CHILDREN_OPEN/);
+ store.withdraw(board, child, { agentId: 'coordinator', reason: 'folded into the parent' });
+ store.submit(board, id, { agentId: 'web-1', commit: SHA_A, tree: 't' });
+ assert.equal(store.getItem(board, id).item_status, 'submitted');
+});
+
+/**
+ * An item built by web-1 and submitted at SHA_A.
+ */
+function submitted() {
+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });
+ claimAs(id, 'web-1', 'web');
+ store.submit(board, id, { agentId: 'web-1', commit: SHA_A, tree: 'tree-a' });
+ return id;
+}
+
+/**
+ * A verdict with the defaults a correct verifier would pass.
+ */
+const verdict = (id, fields) =>
+ store.verify(board, id, { head: SHA_A, digest: 'digest:Page', policy: 'any', ...fields });
+
+test('the builder never verifies its own work [V1]', () => {
+ const id = submitted();
+ assert.throws(() => verdict(id, { agentId: 'web-1', decision: 'ACCEPT' }), /SELF_VERIFY/);
+ assert.equal(verdict(id, { agentId: 'web-2', decision: 'ACCEPT' }).reason, 'CRITERION_MET');
+});
+
+test('under verify: coordinator, lane work is the coordinator\'s to verify', () => {
+ const id = submitted();
+ assert.throws(
+ () => verdict(id, { agentId: 'web-2', decision: 'ACCEPT', policy: 'coordinator' }),
+ /COORDINATOR_VERIFIES/,
+ );
+ verdict(id, { agentId: 'coordinator', decision: 'ACCEPT', policy: 'coordinator' });
+});
+
+test('a verdict against a moved criterion is refused [V2]', () => {
+ const id = submitted();
+ assert.throws(() => verdict(id, { agentId: 'web-2', decision: 'ACCEPT', digest: 'digest:moved' }), /CRITERIA_CHANGED/);
+ const result = store.refreeze(board, id, { agentId: 'coordinator', freeze: () => ({ text: 'x', digest: 'digest:moved' }) });
+ assert.deepEqual(result, { before: 'digest:Page', after: 'digest:moved' });
+ assert.equal(store.getItem(board, id).item_status, 'open');
+ assert.throws(() => store.refreeze(board, id, { agentId: 'web-2', freeze }), /COORDINATOR_ONLY/);
+});
+
+test('ACCEPT needs CRITERION_MET; REJECT needs a reason code and a note [V5]', () => {
+ const id = submitted();
+ assert.throws(() => verdict(id, { agentId: 'web-2', decision: 'ACCEPT', reason: 'OTHER' }), /BAD_REASON/);
+ assert.throws(() => verdict(id, { agentId: 'web-2', decision: 'REJECT' }), /BAD_REASON/);
+ assert.throws(() => verdict(id, { agentId: 'web-2', decision: 'REJECT', reason: 'TEST_FAILURE' }), /NOTE_REQUIRED/);
+ assert.throws(() => verdict(id, { agentId: 'web-2', decision: 'MAYBE' }), /BAD_DECISION/);
+});
+
+test('REJECT reopens the item; resubmitting a rejected head is refused [V6]', () => {
+ const id = submitted();
+ verdict(id, { agentId: 'web-2', decision: 'REJECT', reason: 'BEHAVIOR_MISMATCH', note: 'title missing' });
+ const item = store.getItem(board, id);
+ assert.equal(item.item_status, 'open');
+ assert.equal(item.item_verdict, 'REJECT');
+ claimAs(id, 'web-1', 'web');
+ assert.throws(() => store.submit(board, id, { agentId: 'web-1', commit: SHA_A, tree: 'tree-a' }), /HEAD_NOT_NEW/);
+ store.submit(board, id, { agentId: 'web-1', commit: SHA_B, tree: 'tree-b' });
+ verdict(id, { agentId: 'web-2', decision: 'ACCEPT' });
+ assert.equal(store.getItem(board, id).item_status, 'verified');
+});
+
+test('every verdict binds the submitted commit and the frozen digest [V8]', () => {
+ const id = submitted();
+ verdict(id, { agentId: 'web-2', decision: 'ACCEPT', head: SHA_B });
+ const [recorded] = store.verdictsFor(board, id);
+ assert.equal(recorded.verdict_commit, SHA_A);
+ assert.equal(recorded.verdict_digest, 'digest:Page');
+ assert.equal(recorded.verdict_head, SHA_B);
+ assert.throws(() => verdict(id, { agentId: 'api-1', decision: 'ACCEPT' }), /NOT_SUBMITTED/);
+});
+
+test('merged and withdraw are the coordinator\'s, and only for the right states', () => {
+ const id = submitted();
+ assert.throws(() => store.merged(board, id, { agentId: 'coordinator', commit: SHA_B }), /NOT_VERIFIED/);
+ verdict(id, { agentId: 'web-2', decision: 'ACCEPT' });
+ assert.throws(() => store.merged(board, id, { agentId: 'web-2', commit: SHA_B }), /COORDINATOR_ONLY/);
+ store.merged(board, id, { agentId: 'coordinator', commit: SHA_B });
+ assert.equal(store.getItem(board, id).item_merged_commit, SHA_B);
+ assert.throws(() => store.withdraw(board, id, { agentId: 'coordinator', reason: 'late' }), /CLOSED/);
+});
+
+test('shouts reach a lane, an agent or all; inbox marks them read [B7]', () => {
+ const lanes = ['coordinator', 'web', 'api'];
+ store.shout(board, { from: 'coordinator', to: 'web', text: 'web: rebase', lanes });
+ store.shout(board, { from: 'api-1', to: 'web-2', text: 'web-2: schema changed', lanes });
+ store.shout(board, { from: 'web-1', to: 'all', text: 'all: gate is slow', lanes });
+ assert.throws(() => store.shout(board, { from: 'web-1', to: 'nobody', text: 'x', lanes }), /NO_READER/);
+ assert.equal(store.unreadCount(board, 'web-2'), 3);
+ assert.deepEqual(store.inbox(board, 'web-2').map((shout) => shout.shout_text), ['web: rebase', 'web-2: schema changed', 'all: gate is slow']);
+ assert.equal(store.unreadCount(board, 'web-2'), 0);
+ assert.deepEqual(store.inbox(board, 'web-1').map((shout) => shout.shout_text), ['web: rebase']);
+});
+
+test('every move lands in the event log; stats count items and verdicts [R1, R2]', () => {
+ const id = submitted();
+ verdict(id, { agentId: 'web-2', decision: 'REJECT', reason: 'TEST_FAILURE', note: 'red' });
+ const kinds = store.events(board, { itemId: id }).map((event) => `${event.event_by}:${event.event_kind}`);
+ assert.deepEqual(kinds, ['coordinator:add', 'web-1:claim', 'web-1:submit', 'web-2:reject']);
+ const stats = store.stats(board);
+ assert.equal(stats.items.open, 1);
+ assert.equal(stats.rejected, 1);
+});
diff --git a/test/e2e.test.js b/test/e2e.test.js
new file mode 100644
index 00000000..0a9cafdf
--- /dev/null
+++ b/test/e2e.test.js
@@ -0,0 +1,265 @@
+/**
+ * End to end on real repos: the CLI runs as its own process, git runs the installed hooks, and
+ * worktrees are real worktrees (B1–B3, B6, V3, V4, V7, L3, L4, C3, I1, I2, P2).
+ */
+import assert from 'node:assert/strict';
+import { execFileSync, spawn, spawnSync } from 'node:child_process';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const sandboxes = [];
+
+after(() => {
+ for (const dir of sandboxes) rmSync(dir, { recursive: true, force: true });
+});
+
+/**
+ * A scratch directory with a `pullboard` shim on the PATH, so the hooks git runs find the CLI, and
+ * git isolated from the machine's own config.
+ */
+function sandbox() {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-e2e-')));
+ sandboxes.push(dir);
+ const shims = join(dir, 'bin');
+ mkdirSync(shims);
+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "${BIN}" "$@"\n`);
+ chmodSync(join(shims, 'pullboard'), 0o755);
+ const env = {
+ ...process.env,
+ PATH: `${shims}:${process.env.PATH}`,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Test Agent',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test Agent',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
+ const tryGit = (cwd, ...args) => spawnSync('git', args, { cwd, env, encoding: 'utf8' });
+ const run = (cwd, ...args) => {
+ const result = spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
+ return { code: result.status, out: result.stdout, err: result.stderr };
+ };
+ return { dir, env, git, tryGit, run };
+}
+
+const CONFIG = {
+ gate: 'test ! -f RED',
+ spec: 'SPEC.md',
+ verify: 'any',
+ lease: '2h',
+ lanes: { web: { owns: ['web/'], specs: ['G1'] }, api: { owns: ['api/'], specs: ['G2'] } },
+ shared: ['docs/'],
+};
+
+const SPEC = `# Demo spec
+
+## G · Goals
+- G1 [approved, must] The page renders. | gate: web test
+- G2 [approved, must] The API answers. | gate: api test
+`;
+
+/**
+ * A repo set up with pullboard, two lanes and a spec, committed through its own hooks, plus a
+ * worktree joined to the web lane.
+ */
+function project() {
+ const box = sandbox();
+ const repo = join(box.dir, 'repo');
+ mkdirSync(repo);
+ box.git(repo, 'init', '-q', '-b', 'main');
+ assert.equal(box.run(repo, 'init').code, 0);
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify(CONFIG, null, 2));
+ writeFileSync(join(repo, 'SPEC.md'), SPEC);
+ box.git(repo, 'add', '-A');
+ box.git(repo, 'commit', '-q', '-m', 'chore: set up pullboard');
+ const web = join(box.dir, 'web-1');
+ box.git(repo, 'worktree', 'add', '-q', web, '-b', 'web/one');
+ assert.match(box.run(web, 'join', 'web').out, /joined as web-1/);
+ return { ...box, repo, web };
+}
+
+/**
+ * Write a file in a worktree and commit it, returning git's result so a refusal can be read.
+ */
+function commitFile(box, cwd, path, text, message) {
+ mkdirSync(join(cwd, path, '..'), { recursive: true });
+ writeFileSync(join(cwd, path), text);
+ box.git(cwd, 'add', '-A');
+ return box.tryGit(cwd, 'commit', '-q', '-m', message);
+}
+
+test('init writes config, spec, agent docs and hooks once, and never clobbers [I1, I2]', () => {
+ const box = sandbox();
+ const repo = join(box.dir, 'repo');
+ mkdirSync(repo);
+ box.git(repo, 'init', '-q', '-b', 'main');
+ writeFileSync(join(repo, 'AGENTS.md'), '# Mine\n\nkeep me\n');
+ writeFileSync(join(repo, 'package.json'), JSON.stringify({ scripts: { test: 'node --test' } }));
+ const first = box.run(repo, 'init');
+ assert.equal(first.code, 0);
+ assert.match(first.out, /added the pullboard section to AGENTS.md/);
+ assert.equal(JSON.parse(readFileSync(join(repo, 'pullboard.json'), 'utf8')).gate, 'npm test');
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: 'mine' }));
+ const second = box.run(repo, 'init');
+ assert.match(second.out, /kept pullboard.json/);
+ assert.equal(JSON.parse(readFileSync(join(repo, 'pullboard.json'), 'utf8')).gate, 'mine');
+ const agents = readFileSync(join(repo, 'AGENTS.md'), 'utf8');
+ assert.ok(agents.startsWith('# Mine\n\nkeep me\n'));
+ assert.equal(agents.split('<!-- pullboard:start -->').length, 2);
+ assert.equal(readFileSync(join(repo, 'CLAUDE.md'), 'utf8'), '@AGENTS.md\n');
+ assert.equal(box.git(repo, 'config', '--get', 'core.hooksPath'), '.githooks');
+ for (const hook of ['pre-commit', 'commit-msg', 'pre-push']) assert.ok(existsSync(join(repo, '.githooks', hook)));
+});
+
+test('the board lives in the git common dir; every worktree sees it; nothing is committed [B1, B3]', () => {
+ const box = project();
+ assert.equal(box.run(box.repo, 'add', 'web', 'Build', 'the', 'page', '--specs', 'G1').out.trim(), '#1');
+ assert.match(box.run(box.web, 'list').out, /#1 {2}open {2}web {2}Build the page {2}\[G1\]/);
+ assert.ok(existsSync(join(box.repo, '.git', 'pullboard', 'board.sqlite')));
+ assert.equal(box.git(box.repo, 'status', '--porcelain'), '');
+ assert.match(box.run(box.repo, 'whoami').out, /^coordinator/);
+ assert.match(box.run(box.web, 'whoami').out, /^web-1 \(web lane\)/);
+ assert.match(box.run(box.web, 'init').err, /NOT_MAIN/);
+ assert.match(box.run(box.repo, 'join', 'web').err, /MAIN_IS_COORDINATOR/);
+});
+
+test('items cite spec ids that exist [B6]', () => {
+ const box = project();
+ const refused = box.run(box.repo, 'add', 'web', 'Ghost', '--specs', 'G9');
+ assert.equal(refused.code, 1);
+ assert.match(refused.err, /UNKNOWN_SPEC\] G9 is not in SPEC.md/);
+});
+
+test('a lane commits only inside its folders; an unjoined worktree cannot commit [L3, L4]', () => {
+ const box = project();
+ const loose = join(box.dir, 'loose');
+ box.git(box.repo, 'worktree', 'add', '-q', loose, '-b', 'loose');
+ const unjoined = commitFile(box, loose, 'web/a.html', 'a', 'feat(web): page [G1]');
+ assert.notEqual(unjoined.status, 0);
+ assert.match(unjoined.stderr, /has not joined a lane/);
+ const foreign = commitFile(box, box.web, 'api/a.js', 'a', 'feat(web): page [G1]');
+ assert.match(foreign.stderr, /outside the web lane: api\/a.js \(api's\)/);
+ box.git(box.web, 'reset', '-q', '--hard');
+ box.git(box.web, 'clean', '-fdq');
+ assert.equal(commitFile(box, box.web, 'docs/web.md', 'shared', 'docs: web notes').status, 0);
+ assert.equal(commitFile(box, box.web, 'web/a.html', 'a', 'feat(web): page [G1]').status, 0);
+ mkdirSync(join(box.web, 'api'));
+ box.git(box.web, 'mv', 'web/a.html', 'api/a.html');
+ const moved = box.tryGit(box.web, 'commit', '-q', '-m', 'refactor(web): move the page');
+ assert.match(moved.stderr, /outside the web lane: api\/a.html/);
+});
+
+test('submit needs a clean tree, nothing untracked, and the gate green at HEAD [V4]', () => {
+ const box = project();
+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1');
+ assert.match(box.run(box.web, 'claim', '1').out, /claimed #1/);
+ commitFile(box, box.web, 'web/a.html', 'a', 'feat(web): page [G1]');
+ writeFileSync(join(box.web, 'web', 'a.html'), 'edited');
+ assert.match(box.run(box.web, 'submit', '1').err, /DIRTY/);
+ box.git(box.web, 'checkout', '--', 'web/a.html');
+ writeFileSync(join(box.web, 'web', 'stray.txt'), 'x');
+ assert.match(box.run(box.web, 'submit', '1').err, /UNTRACKED/);
+ rmSync(join(box.web, 'web', 'stray.txt'));
+ const submitted = box.run(box.web, 'submit', '1');
+ assert.equal(submitted.code, 0, submitted.err);
+ assert.match(submitted.out, /submitted #1 at [0-9a-f]{12}; gate green/);
+});
+
+test('a red gate refuses submit', () => {
+ const box = project();
+ writeFileSync(join(box.repo, 'RED'), 'red');
+ box.git(box.repo, 'add', 'RED');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: turn the gate red');
+ box.run(box.repo, 'add', 'coordinator', 'Coordinator work');
+ box.run(box.repo, 'claim', '1');
+ const refused = box.run(box.repo, 'submit', '1');
+ assert.equal(refused.code, 1);
+ assert.match(refused.err, /GATE_RED/);
+});
+
+test('verify runs at the submitted commit, against the criterion frozen at claim [V3, V7]', () => {
+ const box = project();
+ box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1', '--criterion', 'renders a heading');
+ box.run(box.web, 'claim', '1');
+ commitFile(box, box.web, 'web/a.html', '<h1>Hi</h1>', 'feat(web): page [G1]');
+ assert.equal(box.run(box.web, 'submit', '1').code, 0);
+ assert.match(box.run(box.web, 'verify', '1', 'accept').err, /SELF_VERIFY/);
+ assert.match(box.run(box.repo, 'verify', '1', 'accept').err, /NOT_AT_COMMIT/);
+ box.git(box.repo, 'merge', '-q', '--ff-only', 'web/one');
+ writeFileSync(join(box.repo, 'SPEC.md'), SPEC.replace('The page renders.', 'The page renders a heading.'));
+ box.git(box.repo, 'commit', '-qam', 'docs: tighten G1');
+ assert.match(box.run(box.repo, 'verify', '1', 'accept').err, /CRITERIA_CHANGED/);
+ assert.match(box.run(box.repo, 'refreeze', '1').out, /refrozen/);
+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');
+ box.run(box.web, 'claim', '1');
+ assert.equal(box.run(box.web, 'submit', '1').code, 0);
+ assert.match(box.run(box.repo, 'verify', '1', 'accept').out, /verified #1: CRITERION_MET/);
+ const show = box.run(box.repo, 'show', '1').out;
+ assert.match(show, /G1: The page renders a heading\./);
+ assert.match(show, /ACCEPT CRITERION_MET by coordinator/);
+ const ledger = box.run(box.repo, 'ledger').out;
+ assert.match(ledger, /1 verified by a second agent/);
+ assert.match(ledger, /\| 1 \| web \| Page \| G1 \| web-1 \| coordinator \|/);
+});
+
+test('pre-push runs the gate once per tree and pushes only the checked-out commit [C3]', () => {
+ const box = project();
+ const remote = join(box.dir, 'remote.git');
+ box.git(box.dir, 'init', '-q', '--bare', remote);
+ box.git(box.repo, 'remote', 'add', 'origin', remote);
+ const first = box.tryGit(box.repo, 'push', '-q', 'origin', 'main');
+ assert.equal(first.status, 0, first.stderr);
+ assert.ok(existsSync(join(box.repo, '.git', 'pullboard-gate-green')));
+ assert.match(box.run(box.repo, 'gate').out, /this tree already passed/);
+ const elsewhere = box.tryGit(box.repo, 'push', '-q', 'origin', 'web/one:web/one');
+ assert.equal(elsewhere.status, 0, 'web/one is at the same commit as main, so it is what is checked out');
+ commitFile(box, box.web, 'web/b.html', 'b', 'feat(web): second page [G1]');
+ const notHere = box.tryGit(box.repo, 'push', '-q', 'origin', 'web/one');
+ assert.notEqual(notHere.status, 0);
+ assert.match(notHere.stderr, /is not checked out/);
+});
+
+/**
+ * Run `pullboard claim` from two worktrees at once, so both race for the same lock.
+ */
+function race(box, first, second, id) {
+ const one = (cwd) =>
+ new Promise((done) => {
+ const child = spawn(process.execPath, [BIN, 'claim', String(id)], { cwd, env: box.env });
+ let err = '';
+ child.stderr.on('data', (chunk) => {
+ err += chunk;
+ });
+ child.on('close', (code) => done({ cwd, code, err }));
+ });
+ return Promise.all([one(first), one(second)]);
+}
+
+test('two agents racing for one item: exactly one wins, every time [B2]', async () => {
+ const box = project();
+ const second = join(box.dir, 'web-2');
+ box.git(box.repo, 'worktree', 'add', '-q', second, '-b', 'web/two');
+ assert.match(box.run(second, 'join', 'web').out, /joined as web-2/);
+ for (let round = 1; round <= 6; round += 1) {
+ box.run(box.repo, 'add', 'web', `Item ${round}`);
+ const results = await race(box, box.web, second, round);
+ const winners = results.filter((result) => result.code === 0);
+ const losers = results.filter((result) => result.code !== 0);
+ assert.equal(winners.length, 1, `round ${round}: ${JSON.stringify(results)}`);
+ assert.match(losers[0].err, /HELD/);
+ assert.equal(box.run(winners[0].cwd, 'release', String(round)).code, 0);
+ }
+});
diff --git a/test/hooks.test.js b/test/hooks.test.js
new file mode 100644
index 00000000..ef226b12
--- /dev/null
+++ b/test/hooks.test.js
@@ -0,0 +1,73 @@
+/**
+ * The commit-message rules (C1, C2) and the pre-commit pattern checks, without git.
+ */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { defaults } from '../src/config.js';
+import { addedLines, blockedPaths, commitMsgProblems, matchesPattern, secretsIn } from '../src/hooks.js';
+import { parseSpec } from '../src/spec.js';
+
+const SPEC = { ...parseSpec('## G\n- G1 [approved, must] One. | gate: t\n- G2 [retired] Gone.\n'), name: 'SPEC.md' };
+const RULES = defaults().commits;
+
+/**
+ * Problems with a message under the default rules, or the given ones.
+ */
+const check = (message, rules = RULES) => commitMsgProblems(message, { rules, spec: SPEC });
+
+test('a clean header citing a live id passes [C1, C2]', () => {
+ assert.deepEqual(check('feat(web): add the page [G1]'), []);
+ assert.deepEqual(check('docs: explain lanes'), []);
+ assert.deepEqual(check('feat(web)!: drop the old page [G1]\n\nThe old page is gone.'), []);
+});
+
+test('feat and fix cite ids; cited ids exist and are not retired [C2]', () => {
+ assert.match(check('feat(web): add the page')[0], /cite the spec ids/);
+ assert.match(check('fix: patch [G9]')[0], /G9 is not in SPEC.md/);
+ assert.match(check('fix: patch [G2]')[0], /G2 is retired/);
+});
+
+test('header format, length, case and period [C1]', () => {
+ assert.match(check('Added the page')[0], /type\(scope\): subject/);
+ assert.match(check(`docs: ${'x'.repeat(80)}`)[0], /characters; at most 72/);
+ assert.deepEqual(check('docs: Explain lanes.'), ['the subject starts lowercase', 'the subject has no trailing period']);
+ assert.deepEqual(check('docs: explain lanes\nsecond line'), ['leave a blank line after the header']);
+});
+
+test('comments are dropped; merges, reverts and fixups are exempt', () => {
+ assert.deepEqual(check('docs: explain lanes\n# Please enter the commit message'), []);
+ assert.deepEqual(check("Merge branch 'web/page'"), []);
+ assert.deepEqual(check('fixup! feat(web): add the page [G1]'), []);
+});
+
+test('opt-in rules: filler words, emoji, co-author trailers', () => {
+ const strict = { ...RULES, banned: ['basically', 'seamless'], noEmoji: true, noCoAuthor: true };
+ const problems = check('docs: basically seamless lanes \u{1F680}\n\nCo-Authored-By: Bot <b@x>', strict);
+ assert.deepEqual(problems, ['filler word: "basically"', 'filler word: "seamless"', 'no emojis', 'no Co-Authored-By trailer']);
+ assert.deepEqual(check('docs: basically fine'), []);
+});
+
+test('blocked paths: env files by name, examples allowed, patterns with a slash match paths', () => {
+ const protect = { ...defaults().protect, blocked: [...defaults().protect.blocked, 'data/*.csv'] };
+ assert.deepEqual(
+ blockedPaths(['.env', 'app/.env.local', 'prod.env', '.env.example', 'data/claims.csv', 'docs/data/x.csv', 'src/a.js'], protect),
+ ['.env', 'app/.env.local', 'prod.env', 'data/claims.csv'],
+ );
+ assert.ok(matchesPattern('*.env', 'deep/dir/staging.env'));
+ assert.ok(!matchesPattern('.env.*', 'environment.js'));
+});
+
+test('secrets are named by kind and place, never echoed', () => {
+ // Built at run time, so this file never holds a string its own pre-commit scan would refuse.
+ const fakeKey = ['sk', 'ant', 'abcdefghijklmnopqrstuvwxyz0123'].join('-');
+ const diff = [
+ '+++ b/config/settings.js',
+ '@@ -0,0 +1,3 @@',
+ '+const ok = 1;',
+ `+const key = "${fakeKey}";`,
+ '+export CLOUDFLARE_API_TOKEN=abcdefghijklmnopqrstuvwxyz012345',
+ ].join('\n');
+ const found = secretsIn(addedLines(diff));
+ assert.deepEqual(found, ['Anthropic key at config/settings.js:2', 'env-style secret at config/settings.js:3']);
+ assert.ok(found.every((entry) => !entry.includes('abcdefghij')));
+});
diff --git a/test/lanes.test.js b/test/lanes.test.js
new file mode 100644
index 00000000..f8cabb08
--- /dev/null
+++ b/test/lanes.test.js
@@ -0,0 +1,66 @@
+/**
+ * Lanes (L1, L2) and the config they live in.
+ */
+import assert from 'node:assert/strict';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { configProblems, defaults, durationMs, loadConfig } from '../src/config.js';
+import { isLane, laneNames, laneOf, outOfLane } from '../src/lanes.js';
+
+const CONFIG = {
+ ...defaults(),
+ lanes: {
+ web: { owns: ['apps/web/'] },
+ ui: { owns: ['apps/web/src/views/', 'packages/design/'] },
+ api: { owns: ['apps/api/'] },
+ },
+ shared: ['redteam/'],
+};
+
+test('the longest owned prefix decides a path\'s lane; unowned paths are the coordinator\'s [L2]', () => {
+ assert.equal(laneOf(CONFIG, 'apps/web/src/server.js'), 'web');
+ assert.equal(laneOf(CONFIG, 'apps/web/src/views/home.js'), 'ui');
+ assert.equal(laneOf(CONFIG, 'README.md'), 'coordinator');
+});
+
+test('a lane may change its own paths and shared ones; the coordinator may change anything', () => {
+ const paths = ['apps/web/a.js', 'apps/web/src/views/b.js', 'apps/api/c.js', 'redteam/d.test.js'];
+ assert.deepEqual(outOfLane(CONFIG, 'web', paths), [
+ "apps/web/src/views/b.js (ui's)",
+ "apps/api/c.js (api's)",
+ ]);
+ assert.deepEqual(outOfLane(CONFIG, 'coordinator', paths), []);
+});
+
+test('lane names list the coordinator first [L1]', () => {
+ assert.deepEqual(laneNames(CONFIG), ['coordinator', 'web', 'ui', 'api']);
+ assert.ok(isLane(CONFIG, 'coordinator'));
+ assert.ok(!isLane(CONFIG, 'all'));
+});
+
+test('a config with a bad lane refuses and names the field', () => {
+ const problems = configProblems({ ...CONFIG, lanes: { Web: { owns: 'apps/' }, all: { owns: [] } } });
+ assert.ok(problems.some((problem) => problem.includes('lane "Web"')));
+ assert.ok(problems.some((problem) => problem.includes('lane "all"')));
+ assert.ok(configProblems({ ...CONFIG, verify: 'anyone' }).some((problem) => problem.includes('"verify"')));
+});
+
+test('config merges nested groups over the defaults, and leases read as durations', () => {
+ const root = mkdtempSync(join(tmpdir(), 'pullboard-config-'));
+ try {
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'npm test', commits: { maxHeader: 60 }, lease: '90m' }));
+ const config = loadConfig(root);
+ assert.equal(config.commits.maxHeader, 60);
+ assert.deepEqual(config.commits.requireIds, ['feat', 'fix']);
+ assert.equal(config.leaseMs, 90 * 60_000);
+ writeFileSync(join(root, 'pullboard.json'), '{ not json');
+ assert.throws(() => loadConfig(root), /BAD_CONFIG/);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ assert.equal(durationMs('2h'), 7_200_000);
+ assert.equal(durationMs('1d'), 86_400_000);
+ assert.throws(() => durationMs('soon'), /BAD_CONFIG/);
+});
diff --git a/test/package.test.js b/test/package.test.js
new file mode 100644
index 00000000..58a4e560
--- /dev/null
+++ b/test/package.test.js
@@ -0,0 +1,30 @@
+/**
+ * The package stays dependency-free (P3): nothing to install but Node, nothing in node_modules to
+ * trust, and every import is a Node built-in or a file of its own.
+ */
+import assert from 'node:assert/strict';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { test } from 'node:test';
+
+const ROOT = resolve(import.meta.dirname, '..');
+const PACKAGE = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
+
+test('no dependencies of any kind, and Node 22.13 or newer [P3]', () => {
+ assert.equal(PACKAGE.dependencies, undefined);
+ assert.equal(PACKAGE.devDependencies, undefined);
+ assert.equal(PACKAGE.engines.node, '>=22.13');
+});
+
+test('every import is a node: built-in or a relative file [P3]', () => {
+ const files = [
+ ...readdirSync(join(ROOT, 'src')).map((name) => join(ROOT, 'src', name)),
+ join(ROOT, 'bin', 'pullboard.js'),
+ ];
+ for (const file of files) {
+ const imports = [...readFileSync(file, 'utf8').matchAll(/(?:from|import\()\s*'([^']+)'/g)].map((match) => match[1]);
+ for (const target of imports) {
+ assert.ok(target.startsWith('node:') || target.startsWith('.'), `${file} imports ${target}`);
+ }
+ }
+});
diff --git a/test/spec.test.js b/test/spec.test.js
new file mode 100644
index 00000000..49e3c11f
--- /dev/null
+++ b/test/spec.test.js
@@ -0,0 +1,131 @@
+/**
+ * The spec (S1–S5): parsing SPEC.md rows, the lint, the frozen criterion and sign-offs.
+ */
+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 {
+ citedIds,
+ frozenCriterion,
+ idProblems,
+ lintSpec,
+ parseSpec,
+ readSignoffs,
+ signOff,
+ standings,
+ unmetRows,
+} from '../src/spec.js';
+
+const SPEC = `# Demo
+
+Intro line.
+
+## G · Goals
+- G1 [approved, must] Same file twice is a no-op. | gate: idempotency test
+- G1.2 [draft, aim] Shows a diff. | serves: G1
+- G2 [retired] Old idea.
+
+## K · Constraints
+- K1 [approved, must] Runs offline. | gate: e2e test | serves: G1, G1.2
+`;
+
+test('rows parse with id, status, tier, text, gate, serves, section and line [S1]', () => {
+ const spec = parseSpec(SPEC);
+ assert.equal(spec.title, 'Demo');
+ assert.deepEqual(spec.intro, ['Intro line.']);
+ assert.equal(spec.sections.length, 2);
+ assert.equal(spec.rows.length, 4);
+ const row = spec.rows.find((entry) => entry.id === 'K1');
+ assert.deepEqual(
+ { status: row.status, tier: row.tier, text: row.text, gate: row.gate, serves: row.serves },
+ { status: 'approved', tier: 'must', text: 'Runs offline.', gate: 'e2e test', serves: ['G1', 'G1.2'] },
+ );
+ assert.equal(row.section, 'K · Constraints');
+ assert.equal(row.line, 11);
+ assert.deepEqual(lintSpec(spec), []);
+});
+
+test('a row-like line that does not parse is an error, never dropped [S1]', () => {
+ const spec = parseSpec('## G\n- G1 [approved, must]\n- just a bullet note\n');
+ const findings = lintSpec(spec);
+ assert.equal(findings.length, 1);
+ assert.match(findings[0].message, /does not parse/);
+ assert.equal(findings[0].line, 2);
+});
+
+test('rows inside code fences are examples, not rows', () => {
+ const spec = parseSpec('## G\n```\n- G1 [approved, must] Example. | gate: x\n```\n');
+ assert.equal(spec.rows.length, 0);
+});
+
+test('ids are unique, retired ones included [S2]', () => {
+ const findings = lintSpec(parseSpec('## G\n- G1 [retired] Old.\n- G1 [draft] New.\n'));
+ assert.match(findings[0].message, /duplicate id; first on line 2/);
+});
+
+test('serves links must name real ids and never cycle [S3]', () => {
+ const unknown = lintSpec(parseSpec('## G\n- G1 [draft] One. | serves: G9\n'));
+ assert.match(unknown[0].message, /serves G9, which is not in the spec/);
+ const cycle = lintSpec(parseSpec('## G\n- G1 [draft] One. | serves: G2\n- G2 [draft] Two. | serves: G1\n'));
+ assert.ok(cycle.some((finding) => /cycle: G1 -> G2 -> G1/.test(finding.message)));
+});
+
+test('approved must-rows name their gate [S4]', () => {
+ const findings = lintSpec(parseSpec('## G\n- G1 [approved, must] No gate here.\n'));
+ assert.match(findings[0].message, /names its gate/);
+ assert.deepEqual(lintSpec(parseSpec('## G\n- G1 [approved, aim] Aims need none.\n')), []);
+});
+
+test('bad status, bad tier and unknown fields are errors; long rows warn', () => {
+ const findings = lintSpec(
+ parseSpec(`## G\n- G1 [maybe, should] Text. | owner: me\n- G2 [draft] ${'word '.repeat(25)}\n`),
+ );
+ const messages = findings.map((finding) => `${finding.level}: ${finding.message}`);
+ assert.ok(messages.some((message) => message.startsWith('error: status "maybe"')));
+ assert.ok(messages.some((message) => message.startsWith('error: tier "should"')));
+ assert.ok(messages.some((message) => message.startsWith('error: unknown field "owner: me"')));
+ assert.ok(messages.some((message) => message.startsWith('warning: 25 words')));
+});
+
+test('cited ids must exist and must not be retired', () => {
+ const spec = { ...parseSpec(SPEC), name: 'SPEC.md' };
+ assert.deepEqual(idProblems(spec, ['G1', 'K1']), []);
+ assert.deepEqual(idProblems(spec, ['G9', 'G2']), ['G9 is not in SPEC.md', 'G2 is retired']);
+});
+
+test('the frozen criterion covers title, criterion and cited row text [V2]', () => {
+ const item = { item_title: 'Load twice', item_criterion: 'second load adds nothing', item_spec_ids: 'G1' };
+ const first = frozenCriterion(parseSpec(SPEC), item);
+ assert.equal(first.digest.length, 64);
+ assert.equal(frozenCriterion(parseSpec(SPEC), item).digest, first.digest);
+ const reworded = SPEC.replace('Same file twice is a no-op.', 'Same file twice changes nothing.');
+ assert.notEqual(frozenCriterion(parseSpec(reworded), item).digest, first.digest);
+ assert.notEqual(frozenCriterion(parseSpec(SPEC), { ...item, item_criterion: 'other' }).digest, first.digest);
+ assert.throws(() => frozenCriterion(parseSpec(SPEC), { ...item, item_spec_ids: 'G9' }), /UNKNOWN_SPEC/);
+});
+
+test('a sign-off holds the text it approved; changing the row makes it stale [S5]', () => {
+ const root = mkdtempSync(join(tmpdir(), 'pullboard-signoff-'));
+ try {
+ const spec = parseSpec(SPEC);
+ assert.equal(signOff(root, spec, { ids: ['G1', 'K1'], by: 'CO', on: '2026-10-04' }), 2);
+ assert.throws(() => signOff(root, spec, { ids: ['G1.2'], by: 'CO', on: '2026-10-04' }), /only approved rows/);
+ assert.throws(() => signOff(root, spec, { ids: ['G1'], by: 'claude bot', on: '2026-10-04' }), /BAD_SIGNER/);
+ const signoffs = readSignoffs(root);
+ assert.equal(signoffs.length, 2);
+ assert.deepEqual(unmetRows(spec.rows, signoffs), []);
+ const changed = parseSpec(SPEC.replace('Runs offline.', 'Runs offline, always.'));
+ assert.deepEqual(unmetRows(changed.rows, signoffs).map((row) => row.id), ['K1']);
+ assert.equal(standings(changed.rows, signoffs).get('K1').stale.length, 1);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('commit headers cite ids in a trailing bracket [C2]', () => {
+ assert.deepEqual(citedIds('feat(web): add the page [G1, K1.2]'), ['G1', 'K1.2']);
+ assert.deepEqual(citedIds('feat(web): add the page'), []);
+ assert.deepEqual(citedIds('fix: handle [x] in the middle of text'), []);
+});