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.

feat(check): record checks against committed main [V2,H3,H16]

Corey Olson590538df3b5a
diff --git a/docs/api.md b/docs/api.md
index 8db67928..d7b78482 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -10,6 +10,8 @@ A successful command returns the fields listed below. `version` is always the nu
`pullboard settings` reads machine-wide settings from `~/.pullboard/settings.json`; `pullboard settings gateSlots <n>` changes the gate queue capacity, which defaults to `2`. Capacity changes are refused while a gate is running or waiting, so existing holders and FIFO order remain intact.
+When `add` or `edit` supplies a new nonempty check, Pullboard measures it once in a temporary checkout of the current `main` commit. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `green`, `red`, or `unavailable`. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when filing, showing, or reserving the item for review. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. The captured observation travels with the board move, so replicas store the result without executing the command.
+
<!-- api-command-shapes:start -->
| Command | Required top-level fields |
| --- | --- |
diff --git a/src/board.js b/src/board.js
index 69444f9a..dbbf5a38 100644
--- a/src/board.js
+++ b/src/board.js
@@ -559,27 +559,10 @@ function routeOf(board, agentId) {
* @param {{ by: string, lane: string, title: string, criterion?: string, specIds?: string[], parentId?: number | null, after?: number[], brief?: string, route?: string, check?: string }} item
* @returns {number} The new item's id.
*/
-export function addItem(board, { by, lane, title, criterion = '', specIds = [], parentId = null, after = [], brief = '', route = 'strong', check }) {
- const command = coordinatorCheck(by, check) ?? '';
- const cleanTitle = title.trim();
- if (!cleanTitle) throw new Refused('NO_TITLE', 'an item needs a title');
- checkRoute(route);
- checkRouted({ brief: brief.trim(), route, criterion, check: command });
+export function addItem(board, { by, lane, title, criterion = '', specIds = [], parentId = null, after = [], brief = '', route = 'strong', check, checkBaseline }) {
return atomic(board, () => {
- if (parentId !== null) {
- const parent = itemById(board, parentId);
- if (parent.item_lane !== lane) {
- throw new Refused('PARENT_LANE', `a child item sits in its parent's lane (${parent.item_lane})`);
- }
- if (['verified', 'withdrawn'].includes(parent.item_status)) {
- throw new Refused('PARENT_CLOSED', `item #${parentId} is ${parent.item_status}`);
- }
- }
- for (const dependency of after) {
- if (itemById(board, dependency).item_status === 'withdrawn') {
- throw new Refused('WITHDRAWN', `item #${dependency} is withdrawn; nothing can wait on it`);
- }
- }
+ const { command, cleanTitle } = validateItemAddition(board, { by, lane, title, criterion, parentId, after, brief, route, check });
+ const baseline = normalizeCheckBaseline(by, command, checkBaseline);
const at = now(board);
const result = board.db
.prepare(
@@ -589,11 +572,36 @@ export function addItem(board, { by, lane, title, criterion = '', specIds = [],
)
.run(parentId, lane, cleanTitle, criterion.trim(), specIds.join(','), after.join(','), brief.trim(), route, command, by, at, at);
const id = Number(result.lastInsertRowid);
- logEvent(board, by, 'add', id, { lane, specIds, after, route });
+ saveCheckBaseline(board, id, baseline);
+ logEvent(board, by, 'add', id, { lane, specIds, after, route, ...(baseline ? { checkBaseline: baseline } : {}) });
return id;
});
}
+/** Validate an addition before its sender runs a new check, and again when the ordered move applies. */
+export function validateItemAddition(board, { by, lane, title, criterion = '', parentId = null, after = [], brief = '', route = 'strong', check }) {
+ const command = coordinatorCheck(by, check) ?? '';
+ const cleanTitle = title.trim();
+ if (!cleanTitle) throw new Refused('NO_TITLE', 'an item needs a title');
+ checkRoute(route);
+ checkRouted({ brief: brief.trim(), route, criterion, check: command });
+ if (parentId !== null) {
+ const parent = itemById(board, parentId);
+ if (parent.item_lane !== lane) {
+ throw new Refused('PARENT_LANE', `a child item sits in its parent's lane (${parent.item_lane})`);
+ }
+ if (['verified', 'withdrawn'].includes(parent.item_status)) {
+ throw new Refused('PARENT_CLOSED', `item #${parentId} is ${parent.item_status}`);
+ }
+ }
+ for (const dependency of after) {
+ if (itemById(board, dependency).item_status === 'withdrawn') {
+ throw new Refused('WITHDRAWN', `item #${dependency} is withdrawn; nothing can wait on it`);
+ }
+ }
+ return { command, cleanTitle };
+}
+
/**
* Change an item's brief, route, criterion or check (B10, B13, B14). The brief says how to build it
* and may change until the item is verified or withdrawn. The route, the criterion and the check
@@ -605,45 +613,54 @@ export function addItem(board, { by, lane, title, criterion = '', specIds = [],
* @param {number} id
* @param {{ agentId: string, brief?: string, route?: string, criterion?: string, check?: string }} change
*/
-export function editItem(board, id, { agentId, brief, route, criterion, check }) {
- const command = coordinatorCheck(agentId, check);
- if ([brief, route, criterion, check].every((value) => value === undefined)) {
- throw new Refused('USAGE', 'say what changes: --brief "...", --brief-file <file>, --route light|mid|strong, --criterion "..." or --check "<command>"');
- }
+export function editItem(board, id, { agentId, brief, route, criterion, check, checkBaseline }) {
atomic(board, () => {
- const item = current(board, itemById(board, id));
- if (agentId !== COORDINATOR && agentId !== item.item_created_by) {
- throw new Refused('NOT_YOURS', `only the coordinator or ${item.item_created_by}, who added #${id}, edits it; shout them instead`);
- }
- if (['verified', 'withdrawn'].includes(item.item_status)) {
- throw new Refused('CLOSED', `item #${id} is ${item.item_status}`);
- }
- const next = {
- item_brief: brief === undefined ? item.item_brief : brief.trim(),
- item_route: route ?? item.item_route,
- item_criterion: criterion === undefined ? item.item_criterion : criterion.trim(),
- item_check: command === undefined ? item.item_check : command,
- };
- checkRoute(next.item_route);
- const moved = ['item_route', 'item_criterion', 'item_check'].filter((key) => next[key] !== item[key]);
- if (moved.length && item.item_status !== 'open') {
- throw new Refused('HELD', `item #${id} is ${item.item_status}; change its route, criterion or check only while it is open`);
- }
- checkRouted({ brief: next.item_brief, route: next.item_route, criterion: next.item_criterion, check: next.item_check });
- const unfreeze = next.item_criterion !== item.item_criterion || next.item_check !== item.item_check;
+ const { item, next, command, unfreeze } = validateItemEdit(board, id, { agentId, brief, route, criterion, check });
+ const baseline = normalizeCheckBaseline(agentId, command, checkBaseline);
setItem(board, id, { ...next, ...(unfreeze ? { item_frozen: null, item_frozen_digest: null } : {}) });
+ if (baseline || next.item_check !== item.item_check) saveCheckBaseline(board, id, baseline);
logEvent(board, agentId, 'edit', id, {
...(next.item_brief !== item.item_brief ? { brief: `${next.item_brief.length} characters` } : {}),
...(next.item_route !== item.item_route ? { route: next.item_route } : {}),
...(next.item_criterion !== item.item_criterion ? { criterion: next.item_criterion } : {}),
...(command !== undefined ? { check: next.item_check } : {}),
+ ...(baseline ? { checkBaseline: baseline } : {}),
...(unfreeze && item.item_frozen_digest ? { unfrozen: item.item_frozen_digest } : {}),
});
});
}
+/** Validate an edit without side effects, so a refused change never starts a shell baseline. */
+export function validateItemEdit(board, id, { agentId, brief, route, criterion, check }) {
+ const command = coordinatorCheck(agentId, check);
+ if ([brief, route, criterion, check].every((value) => value === undefined)) {
+ throw new Refused('USAGE', 'say what changes: --brief "...", --brief-file <file>, --route light|mid|strong, --criterion "..." or --check "<command>"');
+ }
+ const item = current(board, itemById(board, id));
+ if (agentId !== COORDINATOR && agentId !== item.item_created_by) {
+ throw new Refused('NOT_YOURS', `only the coordinator or ${item.item_created_by}, who added #${id}, edits it; shout them instead`);
+ }
+ if (['verified', 'withdrawn'].includes(item.item_status)) {
+ throw new Refused('CLOSED', `item #${id} is ${item.item_status}`);
+ }
+ const next = {
+ item_brief: brief === undefined ? item.item_brief : brief.trim(),
+ item_route: route ?? item.item_route,
+ item_criterion: criterion === undefined ? item.item_criterion : criterion.trim(),
+ item_check: command === undefined ? item.item_check : command,
+ };
+ checkRoute(next.item_route);
+ const moved = ['item_route', 'item_criterion', 'item_check'].filter((key) => next[key] !== item[key]);
+ if (moved.length && item.item_status !== 'open') {
+ throw new Refused('HELD', `item #${id} is ${item.item_status}; change its route, criterion or check only while it is open`);
+ }
+ checkRouted({ brief: next.item_brief, route: next.item_route, criterion: next.item_criterion, check: next.item_check });
+ const unfreeze = next.item_criterion !== item.item_criterion || next.item_check !== item.item_check;
+ return { item, next, command, unfreeze };
+}
+
/** Normalize an explicitly supplied check only when its author is the coordinator [V2]. */
-function coordinatorCheck(agentId, command) {
+export function coordinatorCheck(agentId, command) {
if (command === undefined) return undefined;
if (agentId !== COORDINATOR) {
throw new Refused('COORDINATOR_CHECK', 'only the coordinator sets or edits an item check; ask your coordinator to supply --check');
@@ -652,6 +669,42 @@ function coordinatorCheck(agentId, command) {
return command.trim();
}
+/** Validate captured baseline data without asking a replica to run Git or a shell [V2,H16]. */
+function normalizeCheckBaseline(agentId, command, baseline) {
+ if (baseline === undefined) return undefined;
+ coordinatorCheck(agentId, command ?? '');
+ if (!command || !baseline || typeof baseline !== 'object' || Array.isArray(baseline)
+ || baseline.command !== command || !['green', 'red', 'unavailable'].includes(baseline.result)
+ || !(baseline.main === null || typeof baseline.main === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(baseline.main))
+ || (baseline.result !== 'unavailable' && baseline.main === null)
+ || (baseline.reason !== undefined && typeof baseline.reason !== 'string')
+ || (baseline.seconds !== undefined && (!Number.isSafeInteger(baseline.seconds) || baseline.seconds < 0))) {
+ throw new Refused('BAD_CHECK_BASELINE', 'the check baseline must describe this command at a main commit; set --check again from the coordinator');
+ }
+ return {
+ command, main: baseline.main, result: baseline.result,
+ ...(baseline.reason === undefined ? {} : { reason: baseline.reason }),
+ ...(baseline.seconds === undefined ? {} : { seconds: baseline.seconds }),
+ ...(baseline.result === 'green' ? { warning: 'CRITERION_PROVES_NOTHING' } : {}),
+ };
+}
+
+/** Store or clear an item's observation atomically with its check and immutable audit event. */
+function saveCheckBaseline(board, id, baseline) {
+ const key = `item_check_baseline_${id}`;
+ if (!baseline) board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(key);
+ else board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')
+ .run(key, JSON.stringify(baseline));
+}
+
+/** Read an observation only when it still describes the item's current check command. */
+function itemCheckBaseline(board, item) {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_check_baseline_${item.item_id}`);
+ if (!row) return null;
+ const baseline = JSON.parse(row.meta_value);
+ return baseline.command === item.item_check ? baseline : null;
+}
+
/** Read the current check's setter from immutable edits, or its original item author [V2]. */
export function itemCheckAuthor(board, id) {
const item = itemById(board, id);
@@ -1233,7 +1286,9 @@ export function listItems(board, { lane, all = false } = {}) {
* @returns {any}
*/
export function getItem(board, id) {
- return current(board, itemById(board, id));
+ const item = current(board, itemById(board, id));
+ const baseline = itemCheckBaseline(board, item);
+ return baseline ? { ...item, item_check_baseline: baseline } : item;
}
/**
diff --git a/src/check-baseline.js b/src/check-baseline.js
new file mode 100644
index 00000000..49634d0f
--- /dev/null
+++ b/src/check-baseline.js
@@ -0,0 +1,59 @@
+/** Observe a proposed check on an isolated copy of main before recording its move [V2,H16]. */
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { gitChildEnv, tryGit } from './git.js';
+import { runShell } from './gate.js';
+import { CONFIG_FILE } from './config.js';
+
+/**
+ * Capture the command and main commit once on the sender; replay only receives this observation.
+ * A missing main cannot turn a warning into a new gate, and the repo gate is already green there.
+ *
+ * @param {string} root
+ * @param {string} command
+ * @returns {{command: string, main: string|null, result: string, reason?: string, seconds?: number}}
+ */
+export function checkBaseline(root, command) {
+ const main = tryGit(root, ['rev-parse', '--verify', 'refs/heads/main^{commit}']);
+ if (main.status !== 0) return { command, main: null, result: 'unavailable', reason: 'no main' };
+ const base = { command, main: main.stdout };
+ if (command === gateOnMain(root, base.main)) return { ...base, result: 'green', reason: 'repo gate' };
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-check-base-'));
+ const checkout = join(directory, 'checkout');
+ const env = gitChildEnv(root);
+ try {
+ const clone = spawnSync('git', ['clone', '--quiet', '--shared', '--no-checkout', '--', root, checkout], { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ const selected = clone.status === 0 && spawnSync('git', ['-c', 'core.hooksPath=/dev/null', 'checkout', '--quiet', '--detach', base.main], { cwd: checkout, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ if (!selected || selected.status !== 0) return { ...base, result: 'unavailable', reason: 'temporary checkout could not be prepared' };
+ const ran = runShell(checkout, command);
+ return { ...base, result: ran.isGreen ? 'green' : 'red', seconds: ran.seconds };
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+/** Use main's committed gate for the shortcut; a dirty local config cannot manufacture a green base. */
+function gateOnMain(root, main) {
+ const config = tryGit(root, ['show', `${main}:${CONFIG_FILE}`]);
+ if (config.status !== 0) return '';
+ try {
+ const gate = JSON.parse(config.stdout)?.gate;
+ return typeof gate === 'string' ? gate.trim() : '';
+ } catch { return ''; }
+}
+
+/** Print a recorded observation, including the warning every reviewer must see before work. */
+export function sayCheckBaseline(io, item) {
+ const base = item.item_check_baseline;
+ if (!base) return;
+ if (base.result === 'unavailable') {
+ io.say(`check baseline unavailable: ${base.reason}`);
+ return;
+ }
+ io.say(`check baseline ${base.result} at main ${base.main}${base.reason ? ` (${base.reason})` : ''}: ${base.command}`);
+ if (base.result === 'green') {
+ io.say('warning: [CRITERION_PROVES_NOTHING] this check already passes on main; use a check that fails before the work and passes after it');
+ }
+}
diff --git a/src/cli.js b/src/cli.js
index bc3199a4..11886a09 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -39,6 +39,7 @@ import {
unmetRows,
} from './spec.js';
import { briefFiles } from './brief.js';
+import { checkBaseline, sayCheckBaseline } from './check-baseline.js';
import { runItems } from './run.js';
import { parseProblems, sweepItems } from './sweep.js';
import { renderSpecView } from './view.js';
@@ -987,6 +988,7 @@ function readCommands(io, { first, second, rest, values }) {
io.say(itemLine(item));
if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);
if (item.item_check) io.say(`check: ${item.item_check}`);
+ sayCheckBaseline(io, item);
sayBrief(io, item.item_brief);
for (const { item: other, shared } of related) {
io.say(`related: #${other.item_id} ${other.item_title}: ${shared.slice(0, 4).join(', ')}${shared.length > 4 ? ', ...' : ''} (git log -p -1 ${other.item_commit.slice(0, 12)} -- ${shared[0]})`);
@@ -1279,6 +1281,7 @@ async function nextHere(io, values) {
const here = cdTo(ctx.info.root);
const as = ctx.info.isMain ? ' --as coordinator' : '';
if (values.verify) {
+ sayCheckBaseline(io, item);
io.say(`next to verify: #${item.item_id} ${item.item_title}, built by ${item.item_built_by} at ${item.item_commit.slice(0, 12)}`);
io.say(`reserved for you until ${item.item_review_until}: another agent's verdict on it is refused until then; pullboard next --verify again renews it`);
io.say(`check out exactly that commit, here: ${here} git switch --detach ${item.item_commit}`);
@@ -1382,7 +1385,7 @@ function workCommands(io, args) {
const parentId = values.parent ? idArg(values.parent, 'a parent item id') : null;
const after = idList(values.after).map((text) => idArg(text, 'an item id after --after'));
const title = [second, ...rest].filter(Boolean).join(' ');
- const id = await ordered(ctx, board, 'addItem', [{
+ const item = {
by: me.id,
lane: first,
title,
@@ -1393,23 +1396,31 @@ function workCommands(io, args) {
brief: briefInLane(ctx, first, briefArg(io, values) ?? ''),
route: values.route ?? 'strong',
check: values.check,
- }]);
+ };
+ const { command } = store.validateItemAddition(board, item);
+ if (command) item.checkBaseline = checkBaseline(ctx.info.root, command);
+ const id = await ordered(ctx, board, 'addItem', [item]);
io.result?.({ item: store.getItem(board, id) });
io.say(`#${id}`);
+ sayCheckBaseline(io, store.getItem(board, id));
return 0;
}),
edit: () => act(async (ctx, board, me) => {
const id = idArg(first);
const brief = briefArg(io, values);
- await ordered(ctx, board, 'editItem', [id, {
+ const change = {
agentId: me.id,
brief: brief === undefined ? undefined : briefInLane(ctx, store.getItem(board, id).item_lane, brief),
route: values.route,
criterion: values.criterion,
check: values.check,
- }]);
+ };
+ const { item, command } = store.validateItemEdit(board, id, change);
+ if (command && command !== item.item_check) change.checkBaseline = checkBaseline(ctx.info.root, command);
+ await ordered(ctx, board, 'editItem', [id, change]);
io.result?.({ item: store.getItem(board, id) });
io.say(`edited #${id}`);
+ sayCheckBaseline(io, store.getItem(board, id));
return 0;
}),
escalate: () => act(async (ctx, board, me) => {
diff --git a/test/check-baseline.test.js b/test/check-baseline.test.js
new file mode 100644
index 00000000..d09a2fef
--- /dev/null
+++ b/test/check-baseline.test.js
@@ -0,0 +1,353 @@
+/** Check baselines run against main and travel with deterministic board moves [V2,H3,H16,N23]. */
+import assert from 'node:assert/strict';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+import { openBoard, closeBoard } from '../src/board.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const BOARD_FILE = '.git/pullboard/board.sqlite';
+const TEMP_DIRS = [];
+const SPEC = `# Check baseline fixture\n\n## G · Goals\n- G1 [approved, must] The fixture keeps its board. | gate: true\n`;
+
+/** Remove each private fixture after node:test has stopped its child processes. */
+function cleanupFixtures() {
+ for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });
+}
+
+after(cleanupFixtures);
+
+/** Quote one shell word without allowing fixture paths or source to become syntax. */
+function shellWord(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
+
+/** Create private Git, CLI and machine-home settings without inheriting repository selectors. */
+function sandbox() {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-check-baseline-'));
+ TEMP_DIRS.push(dir);
+ const bin = join(dir, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);
+ chmodSync(join(bin, 'pullboard'), 0o755);
+ const env = { ...process.env };
+ for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];
+ Object.assign(env, {
+ PATH: `${bin}:${process.env.PATH}`,
+ HOME: join(dir, 'home'),
+ PULLBOARD_HOME: join(dir, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Check baseline fixture',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Check baseline fixture',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ });
+ /** Run Git with only this fixture's config and identity. */
+ function git(cwd, ...args) {
+ return execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
+ }
+ /** Run a real pullboard CLI process with optional stdin. */
+ function run(cwd, args, input) {
+ return spawnSync(process.execPath, [BIN, ...args], {
+ cwd, env, encoding: 'utf8', timeout: 20_000,
+ ...(input === undefined ? {} : { input }),
+ });
+ }
+ return { dir, env, git, run };
+}
+
+/** Initialize an isolated repo and optional real web/review worktrees. */
+function project({ gate = 'true', content = 'green', commit = true, worktrees = false } = {}) {
+ const box = sandbox();
+ const repo = join(box.dir, 'repo');
+ mkdirSync(repo);
+ box.git(repo, 'init', '-q', '-b', 'main');
+ mkdirSync(join(repo, 'web'));
+ writeFileSync(join(repo, 'web', 'result.txt'), `${content}\n`);
+ const initialized = box.run(repo, ['init']);
+ assert.equal(initialized.status, 0, initialized.stderr);
+ const configFile = join(repo, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
+ writeFileSync(configFile, `${JSON.stringify({
+ ...config,
+ gate,
+ spec: 'SPEC.md',
+ lanes: {
+ web: { owns: ['web/'], specs: ['G1'] },
+ review: { owns: [], specs: ['G1'] },
+ },
+ shared: [],
+ }, null, 2)}\n`);
+ writeFileSync(join(repo, 'SPEC.md'), SPEC);
+ if (commit) {
+ box.git(repo, 'add', '-A');
+ box.git(repo, 'commit', '-q', '-m', 'chore: set up check baseline fixture');
+ }
+ const fixture = { ...box, repo, web: null, review: null };
+ if (worktrees) {
+ fixture.web = addWorktree(fixture, 'web', 'web/agent');
+ fixture.review = addWorktree(fixture, 'review', 'review/agent');
+ }
+ return fixture;
+}
+
+/** Create and join one real worktree for the requested fixture lane. */
+function addWorktree(box, lane, branch) {
+ const path = join(box.dir, lane);
+ box.git(box.repo, 'worktree', 'add', '-q', path, '-b', branch);
+ const joined = box.run(path, ['join', lane]);
+ assert.equal(joined.status, 0, joined.stderr);
+ return path;
+}
+
+/** Build a command that records its execution location and checks one tracked value. */
+function fileCheck(expected, marker = 'check-marker.txt', observations = null) {
+ const script = [
+ "const fs = require('node:fs');",
+ `fs.writeFileSync(${JSON.stringify(marker)}, 'ran');`,
+ ...(observations ? [`fs.appendFileSync(${JSON.stringify(observations)}, process.cwd() + '\\n');`] : []),
+ `process.exit(fs.readFileSync('web/result.txt', 'utf8').trim() === ${JSON.stringify(expected)} ? 0 : 1);`,
+ ].join('');
+ return `${shellWord(process.execPath)} -e ${shellWord(script)}`;
+}
+
+/** Add a check-bearing item as coordinator and return its JSON result and item id. */
+function addChecked(box, title, check) {
+ const result = box.run(box.repo, ['add', 'web', title, '--specs', 'G1', '--criterion', 'the check is measured on main', '--check', check, '--json']);
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ assert.equal(result.stderr, '', 'add writes no baseline diagnostics to stderr');
+ return { result, item: JSON.parse(result.stdout).item };
+}
+
+/** Read the item's JSON view so tests inspect its public baseline shape. */
+function showItem(box, id, cwd = box.repo) {
+ const result = box.run(cwd, ['show', String(id), '--json']);
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ return { result, item: JSON.parse(result.stdout) };
+}
+
+test('[V2,H3,H16] baseline comes from committed main while manual check uses the branch', async function baselineUsesMain() {
+ const box = project({ content: 'red', worktrees: true });
+ const main = box.git(box.repo, 'rev-parse', 'refs/heads/main');
+ writeFileSync(join(box.repo, 'web', 'result.txt'), 'green\n');
+ writeFileSync(join(box.web, 'web', 'result.txt'), 'green\n');
+ const before = box.git(box.repo, 'status', '--porcelain');
+ const marker = 'baseline-command-ran.txt';
+ const observations = join(box.dir, 'baseline-executions.txt');
+ const check = fileCheck('green', marker, observations);
+ const { item } = addChecked(box, 'Main baseline is red', check);
+ assert.equal(item.item_check_baseline.command, check);
+ assert.equal(item.item_check_baseline.main, main);
+ assert.equal(item.item_check_baseline.result, 'red', 'the stored result describes committed main, not the dirty green worktree');
+ assert.ok(Number.isFinite(item.item_check_baseline.seconds), 'the baseline includes its measured run time');
+ assert.equal(item.item_check_baseline.warning, undefined, 'a red baseline does not say the criterion already passes');
+ assert.equal(existsSync(join(box.repo, marker)), false, 'baseline execution never writes into the live main checkout');
+ assert.equal(existsSync(join(box.web, marker)), false, 'baseline execution never writes into the live agent checkout');
+ assert.equal(box.git(box.repo, 'status', '--porcelain'), before, 'baseline capture preserves the dirty live main checkout');
+ const locations = readFileSync(observations, 'utf8').trim().split('\n');
+ assert.equal(locations.length, 1, 'the newly supplied check runs exactly once');
+ assert.ok(locations[0] !== box.repo && locations[0] !== box.web, 'it runs in neither live checkout');
+ assert.equal(existsSync(locations[0]), false, 'the temporary checkout is removed after recording the result');
+
+ const manual = box.run(box.web, ['check', String(item.item_id), '--yes', '--json']);
+ assert.equal(manual.status, 0, `${manual.stdout}${manual.stderr}`);
+ assert.equal(JSON.parse(manual.stdout).green, true, 'manual check runs against the green branch');
+ assert.equal(readFileSync(join(box.web, marker), 'utf8'), 'ran');
+ const after = showItem(box, item.item_id, box.web).item;
+ assert.deepEqual(after.item_check_baseline, item.item_check_baseline, 'manual branch success does not rewrite the main baseline');
+});
+
+test('[V2,H3,H16] green baseline warns through add edit show and private next verify', async function greenBaselineWarnings() {
+ const box = project({ content: 'green', worktrees: true });
+ const check = fileCheck('green', 'first-check-marker.txt');
+ const { result: added, item } = addChecked(box, 'Green baseline warning', check);
+ assert.match(added.stdout, /CRITERION_PROVES_NOTHING/u);
+ assert.equal(item.item_check_baseline.result, 'green');
+ assert.equal(item.item_check_baseline.main, box.git(box.repo, 'rev-parse', 'refs/heads/main'));
+ assert.equal(existsSync(join(box.repo, 'first-check-marker.txt')), false, 'the passing baseline ran in its temporary clone');
+
+ const changedCheck = fileCheck('green', 'edited-check-marker.txt');
+ const edited = box.run(box.repo, ['edit', String(item.item_id), '--check', changedCheck, '--json']);
+ assert.equal(edited.status, 0, `${edited.stdout}${edited.stderr}`);
+ assert.equal(edited.stderr, '', 'edit writes no baseline diagnostics to stderr');
+ assert.match(edited.stdout, /CRITERION_PROVES_NOTHING/u);
+ assert.equal(JSON.parse(edited.stdout).item.item_check_baseline.command, changedCheck);
+ assert.equal(existsSync(join(box.repo, 'edited-check-marker.txt')), false, 'the edited baseline also ran in a temporary clone');
+
+ const shown = box.run(box.repo, ['show', String(item.item_id)]);
+ assert.equal(shown.status, 0, shown.stderr);
+ assert.match(shown.stdout, /CRITERION_PROVES_NOTHING/u);
+ const textAdded = box.run(box.repo, ['add', 'web', 'Text baseline warning', '--check', check]);
+ assert.equal(textAdded.status, 0, textAdded.stderr);
+ assert.match(textAdded.stdout, /warning: \[CRITERION_PROVES_NOTHING\]/u);
+ const textEdited = box.run(box.repo, ['edit', String(item.item_id), '--check', `${changedCheck}\n# a distinct command`]);
+ assert.equal(textEdited.status, 0, textEdited.stderr);
+ assert.match(textEdited.stdout, /warning: \[CRITERION_PROVES_NOTHING\]/u);
+
+ const claimed = box.run(box.web, ['next']);
+ assert.equal(claimed.status, 0, `${claimed.stdout}${claimed.stderr}`);
+ writeFileSync(join(box.web, 'web', 'proof.txt'), 'submitted\n');
+ box.git(box.web, 'add', 'web/proof.txt');
+ box.git(box.web, 'commit', '-q', '-m', 'test: submit green check baseline fixture');
+ const submitted = box.run(box.web, ['submit', String(item.item_id)]);
+ assert.equal(submitted.status, 0, `${submitted.stdout}${submitted.stderr}`);
+
+ const review = box.run(box.review, ['next', '--verify']);
+ assert.equal(review.status, 0, `${review.stdout}${review.stderr}`);
+ assert.match(review.stdout, /CRITERION_PROVES_NOTHING/u);
+});
+
+test('[V2,H3,H16] repo gates skip command execution and baselines preserve clear and missing-main states', async function baselineTransitions() {
+ const box = project({ content: 'green' });
+ const gateMarker = join(box.dir, 'repo-gate-marker.txt');
+ const gate = fileCheck('green', gateMarker);
+ const configFile = join(box.repo, 'pullboard.json');
+ writeFileSync(configFile, JSON.stringify({ ...JSON.parse(readFileSync(configFile, 'utf8')), gate }));
+ box.git(box.repo, 'add', 'pullboard.json');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: set the fixture gate');
+ const { item: gated } = addChecked(box, 'Gate check', gate);
+ assert.deepEqual(gated.item_check_baseline, {
+ command: gate,
+ main: box.git(box.repo, 'rev-parse', 'refs/heads/main'),
+ result: 'green',
+ reason: 'repo gate',
+ warning: 'CRITERION_PROVES_NOTHING',
+ });
+ assert.equal(existsSync(gateMarker), false, 'an exact gate match never runs its command, even in the temporary clone');
+
+ const metadataEdit = box.run(box.repo, ['edit', String(gated.item_id), '--brief', 'updated brief', '--json']);
+ assert.equal(metadataEdit.status, 0, `${metadataEdit.stdout}${metadataEdit.stderr}`);
+ assert.deepEqual(JSON.parse(metadataEdit.stdout).item.item_check_baseline, gated.item_check_baseline,
+ 'an edit that leaves the check unchanged retains the measured baseline');
+
+ const changedExecutions = join(box.dir, 'changed-check-executions.txt');
+ const changedCheck = fileCheck('green', 'changed-check-marker.txt', changedExecutions);
+ writeFileSync(configFile, JSON.stringify({ ...JSON.parse(readFileSync(configFile, 'utf8')), gate: changedCheck }));
+ const changed = box.run(box.repo, ['edit', String(gated.item_id), '--check', changedCheck, '--json']);
+ assert.equal(changed.status, 0, `${changed.stdout}${changed.stderr}`);
+ const changedBaseline = JSON.parse(changed.stdout).item.item_check_baseline;
+ assert.equal(changedBaseline.command, changedCheck);
+ assert.equal(changedBaseline.main, gated.item_check_baseline.main);
+ assert.equal(changedBaseline.result, 'green');
+ assert.equal(changedBaseline.reason, undefined, 'a dirty config cannot turn a new check into the committed main gate');
+ assert.equal(readFileSync(changedExecutions, 'utf8').trim().split('\n').length, 1, 'the dirty-config check really runs once at main');
+ assert.equal(existsSync(join(box.repo, 'changed-check-marker.txt')), false, 'changed checks run only in the temporary main clone');
+
+ const cleared = box.run(box.repo, ['edit', String(gated.item_id), '--check', '', '--json']);
+ assert.equal(cleared.status, 0, `${cleared.stdout}${cleared.stderr}`);
+ assert.equal(JSON.parse(cleared.stdout).item.item_check, '');
+ assert.equal(Object.hasOwn(JSON.parse(cleared.stdout).item, 'item_check_baseline'), false, 'clearing a check clears its baseline');
+ assert.ok(!snapshotFile(join(box.repo, BOARD_FILE)).tables.board_meta.some((row) => row.meta_key === `item_check_baseline_${gated.item_id}`), 'clearing also removes the persisted baseline metadata');
+
+ const unborn = project({ commit: false });
+ const noMainCheck = fileCheck('green', 'unborn-check-marker.txt');
+ const { item: unavailable } = addChecked(unborn, 'Unborn main baseline', noMainCheck);
+ assert.deepEqual(unavailable.item_check_baseline, {
+ command: noMainCheck, main: null, result: 'unavailable', reason: 'no main',
+ }, 'an unborn main reports unavailable without refusing item creation');
+ assert.equal(existsSync(join(unborn.repo, 'unborn-check-marker.txt')), false, 'no-main handling never falls back to the live checkout');
+});
+
+/** Open a board file and always close it after returning a synchronous result. */
+function withBoard(file, callback) {
+ const board = openBoard(file);
+ try { return callback(board); } finally { closeBoard(board); }
+}
+
+/** Import one native snapshot into a separate real SQLite replica. */
+function importReplica(file, snapshot) {
+ withBoard(file, (board) => importBoard(board, snapshot));
+}
+
+/** Read a native snapshot from a replica, including its event and metadata tables. */
+function snapshotFile(file) {
+ return withBoard(file, exportBoard);
+}
+
+/** Apply a captured move in a separate Node process so each replica has its own cwd and env. */
+function applyInReplica(file, replicaDir, moveFile, env, at = '2026-10-07T12:00:00.000Z') {
+ const boardUrl = new URL('../src/board.js', import.meta.url).href;
+ const engineUrl = new URL('../src/engine.js', import.meta.url).href;
+ const source = [
+ `import { openBoard, closeBoard } from ${JSON.stringify(boardUrl)};`,
+ `import { applyEngineMove } from ${JSON.stringify(engineUrl)};`,
+ "import { readFileSync } from 'node:fs';",
+ 'const board = openBoard(process.argv[1]);',
+ 'try { applyEngineMove(board, JSON.parse(readFileSync(process.argv[2], "utf8")), { sequence: Number(process.argv[3]), at: process.argv[4] }); }',
+ 'finally { closeBoard(board); }',
+ ].join('\n');
+ return spawnSync(process.execPath, ['--input-type=module', '-e', source, file, moveFile, String(env.sequence), at], {
+ cwd: replicaDir, env, encoding: 'utf8', timeout: 10_000,
+ });
+}
+
+test('[H3,H16] captured add and edit baselines replay identically without running shell checks', async function baselineMoveReplay() {
+ const box = project();
+ const baseFile = join(box.repo, BOARD_FILE);
+ const seed = snapshotFile(baseFile);
+ const senderFile = join(box.dir, 'sender.sqlite');
+ importReplica(senderFile, seed);
+ const senderDir = join(box.dir, 'sender');
+ const replicaA = join(box.dir, 'replica-a');
+ const replicaB = join(box.dir, 'replica-b');
+ for (const dir of [senderDir, replicaA, replicaB]) mkdirSync(dir);
+ const fileA = join(replicaA, 'board.sqlite');
+ const fileB = join(replicaB, 'board.sqlite');
+ importReplica(fileA, seed);
+ importReplica(fileB, seed);
+ const markerA = join(replicaA, 'must-not-run');
+ const markerB = join(replicaB, 'must-not-run');
+ const shellCheck = `${shellWord(process.execPath)} -e ${shellWord(`require('node:fs').writeFileSync(process.cwd() + '/must-not-run', 'ran')`)}`;
+ const baseline = {
+ command: shellCheck,
+ main: 'a'.repeat(40),
+ result: 'red',
+ };
+ let move;
+ withBoard(senderFile, (sender) => {
+ move = prepareEngineMove(sender, 'addItem', [{
+ by: 'coordinator', lane: 'web', title: 'Replayed baseline', criterion: 'the baseline stays captured',
+ check: shellCheck, checkBaseline: baseline,
+ }], { id: 'check-baseline-add' });
+ });
+ assert.deepEqual(move.args[0].checkBaseline, baseline, 'the measured object is embedded in the sender-authored move');
+ withBoard(senderFile, (sender) => applyEngineMove(sender, move, { sequence: 1, at: '2026-10-07T12:00:00.000Z' }));
+ const moveFile = join(box.dir, 'add-move.json');
+ writeFileSync(moveFile, JSON.stringify(move));
+ const envA = { ...box.env, CHECK_REPLICA: 'a', sequence: '1' };
+ const envB = { ...box.env, CHECK_REPLICA: 'b', sequence: '1' };
+ const appliedA = applyInReplica(fileA, replicaA, moveFile, envA);
+ const appliedB = applyInReplica(fileB, replicaB, moveFile, envB);
+ assert.equal(appliedA.status, 0, `${appliedA.stdout}${appliedA.stderr}`);
+ assert.equal(appliedB.status, 0, `${appliedB.stdout}${appliedB.stderr}`);
+ assert.equal(existsSync(markerA), false, 'replica A stores the captured result without running the command');
+ assert.equal(existsSync(markerB), false, 'replica B stores the captured result without running the command');
+ assert.deepEqual(snapshotFile(fileA), snapshotFile(fileB), 'both SQLite replicas commit the same item, baseline, event and receipt');
+
+ const editBaseline = { ...baseline, command: `${shellCheck} --edited`, result: 'green' };
+ let edit;
+ withBoard(senderFile, (sender) => {
+ const item = sender.db.prepare("SELECT item_id FROM item WHERE item_title='Replayed baseline'").get();
+ edit = prepareEngineMove(sender, 'editItem', [item.item_id, {
+ agentId: 'coordinator', check: editBaseline.command, checkBaseline: editBaseline,
+ }], { id: 'check-baseline-edit' });
+ });
+ assert.deepEqual(edit.args[1].checkBaseline, editBaseline, 'the edited measurement is captured before replay too');
+ withBoard(senderFile, (sender) => applyEngineMove(sender, edit, { sequence: 2, at: '2026-10-07T12:00:01.000Z' }));
+ const editFile = join(box.dir, 'edit-move.json');
+ writeFileSync(editFile, JSON.stringify(edit));
+ const editedA = applyInReplica(fileA, replicaA, editFile, { ...envA, sequence: '2' }, '2026-10-07T12:00:01.000Z');
+ const editedB = applyInReplica(fileB, replicaB, editFile, { ...envB, sequence: '2' }, '2026-10-07T12:00:01.000Z');
+ assert.equal(editedA.status, 0, `${editedA.stdout}${editedA.stderr}`);
+ assert.equal(editedB.status, 0, `${editedB.stdout}${editedB.stderr}`);
+ assert.equal(existsSync(markerA), false);
+ assert.equal(existsSync(markerB), false);
+ assert.deepEqual(snapshotFile(fileA), snapshotFile(fileB), 'replayed edits preserve equal baseline and event metadata');
+ assert.deepEqual(snapshotFile(senderFile), snapshotFile(fileA), 'sender and both receiving databases share the same add/edit history');
+});