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(core): defer check baselines [V2,H16]

Corey Olson3730ea23ceb3
diff --git a/bin/check-baseline.js b/bin/check-baseline.js
new file mode 100644
index 00000000..2063ec08
--- /dev/null
+++ b/bin/check-baseline.js
@@ -0,0 +1,13 @@
+#!/usr/bin/env node
+/** Private detached baseline worker; no command or caller-supplied result comes from its arguments [V2,H16]. */
+const emitWarning = process.emitWarning;
+/** Hide only Node's experimental SQLite notice, as the main CLI does. */
+process.emitWarning = (warning, ...rest) => {
+ if (!String(warning).includes('SQLite is an experimental feature')) emitWarning.call(process, warning, ...rest);
+};
+const [root, rawId, request] = process.argv.slice(2);
+if (root && /^[1-9]\d*$/.test(rawId ?? '') && /^[a-f0-9-]{36}$/.test(request ?? '')) {
+ const { runCheckBaselineWorker } = await import('../src/check-baseline-worker.js');
+ try { await runCheckBaselineWorker(root, Number(rawId), request); }
+ catch { process.exitCode = 1; }
+} else process.exitCode = 2;
diff --git a/docs/api.md b/docs/api.md
index 4afdebd5..62a9aba1 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -10,7 +10,9 @@ 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.
+When `add` or `edit` supplies a new nonempty check, it records the item before measuring that check in a background temporary checkout of the captured `main` commit. Use `--wait` to wait for the measurement before returning, or `args.wait: true` for an HTTP add/edit move. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, request?, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `pending`, `green`, `red`, or `unavailable`. A background request carries an opaque `request` identity; an older completion cannot overwrite a newly edited or cleared check.
+
+A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. 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. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.
<!-- api-command-shapes:start -->
| Command | Required top-level fields |
diff --git a/docs/formats.md b/docs/formats.md
index 5ab67f80..24599486 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -70,10 +70,10 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo
| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. |
| `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. |
| `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |
-| `move engine` | `1` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |
+| `move engine` | `2` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |
<!-- format-versions:end -->
-The move-engine bump rule starts with the first release that includes engine 1. Changes developed together before that release form the initial engine 1.
+Pullboard 0.6.1 released engine 1. The first change to released move semantics raises the engine once for the next release; later changes developed before that release keep the same version. Older clients refuse newer-engine moves before changing rows or replay cursors; engine 2 still accepts engine-1 moves.
A board without `event_log_version` is a legacy version-0 event log. Opening an older board writes the current marker without replacing its events. Opening a newer event log refuses with `EVENT_LOG_VERSION`, naming the stored and supported versions and asking you to upgrade Pullboard. `doctor` reports that version conflict read-only.
diff --git a/src/api.js b/src/api.js
index c6068e28..34cbb7dd 100644
--- a/src/api.js
+++ b/src/api.js
@@ -84,8 +84,8 @@ function agentPath(root, name = COORDINATOR) {
const MOVES = {
'spec-approve': { prefix: ['spec', 'approve'], positions: ['ids'], flags: ['by'] },
'spec-decline': { prefix: ['spec', 'decline'], positions: ['ids'], flags: ['reason'] },
- add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'] },
- edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'] },
+ add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'], booleans: ['wait'] },
+ edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'], booleans: ['wait'] },
claim: { item: true },
release: { item: true },
submit: { item: true },
diff --git a/src/board.js b/src/board.js
index dcc13f18..35a8ad4a 100644
--- a/src/board.js
+++ b/src/board.js
@@ -675,21 +675,42 @@ 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.command !== command || !['green', 'red', 'unavailable', 'pending'].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.result === 'pending' && !baseline.request)
+ || (baseline.request !== undefined && (typeof baseline.request !== 'string' || !/^[a-f0-9-]{36}$/.test(baseline.request)))
|| (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.request === undefined ? {} : { request: baseline.request }),
...(baseline.reason === undefined ? {} : { reason: baseline.reason }),
...(baseline.seconds === undefined ? {} : { seconds: baseline.seconds }),
...(baseline.result === 'green' ? { warning: 'CRITERION_PROVES_NOTHING' } : {}),
};
}
+/** Record a captured result only for the still-current authorized background request [V2,H16]. */
+export function completeCheckBaseline(board, id, { agentId, expected, baseline }) {
+ return atomic(board, () => {
+ const result = normalizeCheckBaseline(agentId, baseline?.command, baseline);
+ if (!expected || !result || result.result === 'pending' || result.command !== expected.command || result.main !== expected.main
+ || typeof expected.request !== 'string' || !/^[a-f0-9-]{36}$/.test(expected.request)) {
+ throw new Refused('BAD_CHECK_BASELINE', 'a completed baseline must match its authorized request; set --check again from the coordinator');
+ }
+ const item = itemById(board, id);
+ const current = itemCheckBaseline(board, item);
+ if (current?.result !== 'pending' || current.request !== expected.request || current.command !== expected.command || current.main !== expected.main) return false;
+ const recorded = { ...result, request: expected.request };
+ saveCheckBaseline(board, id, recorded);
+ logEvent(board, agentId, 'check-baseline', id, { checkBaseline: recorded });
+ return true;
+ });
+}
+
/** 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}`;
diff --git a/src/check-baseline-worker.js b/src/check-baseline-worker.js
new file mode 100644
index 00000000..55984ad8
--- /dev/null
+++ b/src/check-baseline-worker.js
@@ -0,0 +1,96 @@
+/** Detached baseline measurements and durable completion receipts use the ordered board engine [V2,H16]. */
+import { spawn } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import * as store from './board.js';
+import { checkBaseline } from './check-baseline.js';
+import { gitChildEnv, repoInfo } from './git.js';
+import { relayLinked, relayOperation } from './relay.js';
+import { Refused } from './refused.js';
+
+const WORKER = resolve(import.meta.dirname, '../bin/check-baseline.js');
+
+/** Resolve private completion storage beside this repository's shared board. */
+function locations(root) {
+ const info = repoInfo(root);
+ return { board: join(info.commonDir, 'pullboard', 'board.sqlite'), receipts: join(info.commonDir, 'pullboard', 'baseline-results') };
+}
+
+/** Close a real board around one short operation; measurements never hold a database connection. */
+function withBoard(root, work) {
+ const board = store.openBoard(locations(root).board);
+ try { return work(board); } finally { store.closeBoard(board); }
+}
+
+/** Apply captured data through the same local or linked engine as the original add/edit. */
+async function complete(root, receipt, io) {
+ const args = [receipt.id, { agentId: 'coordinator', expected: receipt.expected, baseline: receipt.baseline }];
+ return relayLinked(root) ? relayOperation(root, 'completeCheckBaseline', args, io)
+ : withBoard(root, (board) => store.completeCheckBaseline(board, ...args));
+}
+
+/** Persist a completed observation before attempting relay delivery; retries never rerun its shell. */
+function saveReceipt(root, receipt) {
+ const directory = locations(root).receipts;
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const file = join(directory, `${receipt.expected.request}.json`);
+ const temporary = `${file}.${process.pid}.tmp`;
+ writeFileSync(temporary, JSON.stringify(receipt), { mode: 0o600 });
+ renameSync(temporary, file);
+ return file;
+}
+
+/** Retry only finished observations, retaining a receipt if the relay cannot acknowledge it yet. */
+export async function retryCheckBaselines(root, io) {
+ const directory = locations(root).receipts;
+ if (!existsSync(directory)) return;
+ for (const name of readdirSync(directory).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name))) {
+ const file = join(directory, name);
+ try {
+ const receipt = JSON.parse(readFileSync(file, 'utf8'));
+ await complete(root, receipt, io);
+ rmSync(file, { force: true });
+ } catch (error) {
+ if (error.code === 'ENOENT') continue; // Another delivery may have removed this same receipt.
+ io.err(`pullboard: baseline completion pending; retry with pullboard show (${error instanceof Refused ? error.code : 'BASELINE_RECEIPT'})`);
+ }
+ }
+}
+
+/** Start a detached child with independent streams so the caller exits while its check is running. */
+export async function startCheckBaseline(root, id, baseline) {
+ if (baseline?.result !== 'pending') return;
+ const child = spawn(process.execPath, [WORKER, root, String(id), baseline.request], {
+ cwd: root, env: gitChildEnv(root), detached: true, stdio: 'ignore',
+ });
+ await new Promise((resolve, reject) => {
+ child.once('spawn', resolve);
+ child.once('error', reject);
+ });
+ child.unref();
+}
+
+/** Measure the captured main once, then seal its terminal result without overwriting a newer check. */
+export async function runCheckBaselineWorker(root, id, request) {
+ const expected = withBoard(root, (board) => store.getItem(board, id).item_check_baseline);
+ if (expected?.result !== 'pending' || expected.request !== request) return;
+ let baseline;
+ try { baseline = checkBaseline(root, expected.command, { main: expected.main }); }
+ catch { baseline = { command: expected.command, main: expected.main, result: 'unavailable', reason: 'background check could not run; set --check again from the coordinator' }; }
+ const receipt = { id, expected, baseline };
+ const file = saveReceipt(root, receipt);
+ const io = {
+ /** Discard normal relay prose in the detached worker. */
+ say() {},
+ /** Retain delivery failures in the receipt rather than an abandoned terminal stream. */
+ err() {},
+ stderr: {
+ /** The worker cannot ask for an interactive sign-in; its receipt remains retryable. */
+ write() {},
+ },
+ };
+ try {
+ await complete(root, receipt, io);
+ rmSync(file, { force: true });
+ } catch { /* The next CLI command retries the durable captured result. */ }
+}
diff --git a/src/check-baseline.js b/src/check-baseline.js
index 49634d0f..ed115f2d 100644
--- a/src/check-baseline.js
+++ b/src/check-baseline.js
@@ -1,5 +1,6 @@
/** Observe a proposed check on an isolated copy of main before recording its move [V2,H16]. */
import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -13,12 +14,13 @@ import { CONFIG_FILE } from './config.js';
*
* @param {string} root
* @param {string} command
+ * @param {{main?: string}} [options]
* @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 };
+export function checkBaseline(root, command, { main = undefined } = {}) {
+ const captured = main === undefined ? prepareCheckBaseline(root, command) : { command, main, result: 'pending' };
+ if (captured.result !== 'pending') return captured;
+ const base = { command, main: captured.main };
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');
@@ -34,6 +36,15 @@ export function checkBaseline(root, command) {
}
}
+/** Capture the authorized check's immutable base without running its shell command [V2,H16]. */
+export function prepareCheckBaseline(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' };
+ return { ...base, result: 'pending', request: randomUUID() };
+}
+
/** 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}`]);
@@ -48,6 +59,10 @@ function gateOnMain(root, main) {
export function sayCheckBaseline(io, item) {
const base = item.item_check_baseline;
if (!base) return;
+ if (base.result === 'pending') {
+ io.say(`check baseline running in the background at main ${base.main}: ${base.command}`);
+ return;
+ }
if (base.result === 'unavailable') {
io.say(`check baseline unavailable: ${base.reason}`);
return;
diff --git a/src/cli.js b/src/cli.js
index 453c3957..d7614537 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -42,7 +42,8 @@ import {
unmetRows,
} from './spec.js';
import { briefFiles } from './brief.js';
-import { checkBaseline, sayCheckBaseline } from './check-baseline.js';
+import { checkBaseline, prepareCheckBaseline, sayCheckBaseline } from './check-baseline.js';
+import { retryCheckBaselines, startCheckBaseline } from './check-baseline-worker.js';
import { runItems } from './run.js';
import { parseProblems, sweepItems } from './sweep.js';
import { renderSpecView } from './view.js';
@@ -92,8 +93,10 @@ Work
[--brief "..." | --brief-file <file>] [--route light|mid]
--after: claiming waits until those items are verified
--brief: what a cold agent needs; --route light: any model can build it
- [--check "<command>"] the command that proves it; with --criterion and a brief, needed below strong
+ [--check "<command>"] [--wait] the command that proves it; --wait waits for its main baseline
+ with --criterion and a brief, --check is needed below strong
pullboard edit <id> [--brief "..." | --brief-file <file>] [--route light|mid|strong] [--criterion "..."] [--check "..."]
+ [--wait] wait for a new check's baseline; otherwise it runs in the background
pullboard escalate <id> --note "what was tried and how it failed" hand it one tier up
pullboard run --agent "<command>" [--attempts 3] [--minutes 15] [--items N] [--wait M]
build routed items unattended in this worktree: the agent command reads
@@ -427,6 +430,28 @@ const OPTIONS = {
version: { type: 'boolean', short: 'v' },
};
+/** Parse --wait as a switch for add/edit and as minutes for next/run, preserving all other options. */
+function parseCommandArgs(argv) {
+ let command;
+ for (const wait of [{ type: 'boolean' }, OPTIONS.wait]) {
+ try {
+ command = parseArgs({ args: argv, options: { ...OPTIONS, wait }, allowPositionals: true }).positionals[0];
+ if (['add', 'edit'].includes(command)) break;
+ } catch { /* The final parser supplies the existing actionable usage error. */ }
+ }
+ const options = ['add', 'edit'].includes(command) ? { ...OPTIONS, wait: { type: 'boolean' } } : OPTIONS;
+ return parseArgs({ args: argv, options, allowPositionals: true });
+}
+
+/** Start an already-recorded request, recording an unavailable result if its child cannot start. */
+async function launchBaseline(ctx, board, id, baseline) {
+ try { await startCheckBaseline(ctx.info.root, id, baseline); }
+ catch {
+ await ordered(ctx, board, 'completeCheckBaseline', [id, { agentId: COORDINATOR, expected: baseline,
+ baseline: { command: baseline.command, main: baseline.main, result: 'unavailable', reason: 'background worker could not start; set --check again from the coordinator' } }]);
+ }
+}
+
/**
* A positive whole number from an argument, or a refusal naming what was expected.
*
@@ -1714,8 +1739,9 @@ function workCommands(io, args) {
check: values.check,
};
const { command } = store.validateItemAddition(board, item);
- if (command) item.checkBaseline = checkBaseline(ctx.info.root, command);
+ if (command) item.checkBaseline = values.wait ? checkBaseline(ctx.info.root, command) : prepareCheckBaseline(ctx.info.root, command);
const id = await ordered(ctx, board, 'addItem', [item]);
+ if (item.checkBaseline?.result === 'pending') await launchBaseline(ctx, board, id, item.checkBaseline);
io.result?.({ item: store.getItem(board, id) });
io.say(`#${id}`);
sayCheckBaseline(io, store.getItem(board, id));
@@ -1732,8 +1758,9 @@ function workCommands(io, args) {
check: values.check,
};
const { item, command } = store.validateItemEdit(board, id, change);
- if (command && command !== item.item_check) change.checkBaseline = checkBaseline(ctx.info.root, command);
+ if (command && command !== item.item_check) change.checkBaseline = values.wait ? checkBaseline(ctx.info.root, command) : prepareCheckBaseline(ctx.info.root, command);
await ordered(ctx, board, 'editItem', [id, change]);
+ if (change.checkBaseline?.result === 'pending') await launchBaseline(ctx, board, id, change.checkBaseline);
io.result?.({ item: store.getItem(board, id) });
io.say(`edited #${id}`);
sayCheckBaseline(io, store.getItem(board, id));
@@ -2176,7 +2203,7 @@ async function hookCommand(io, { first, second }) {
async function runCommand(argv, io) {
let parsed;
try {
- parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
+ parsed = parseCommandArgs(argv);
} catch (error) {
io.refusal?.(new Refused('USAGE', `${error.message}; run pullboard help`));
io.err(`pullboard: ${error.message}\nRun pullboard help --all for the full list.`);
@@ -2267,13 +2294,16 @@ export async function main(argv, streams) {
const io = commandOutput(argv, streams);
let sync = true;
try {
- const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
+ const parsed = parseCommandArgs(argv);
const command = parsed.positionals[0];
sync = Boolean(command) && !parsed.values.help && !parsed.values.version && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command);
} catch { sync = false; }
/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
const retry = async () => {
- try { await syncRelay(io.cwd, io); }
+ try {
+ await syncRelay(io.cwd, io);
+ await retryCheckBaselines(io.cwd, io);
+ }
catch (error) {
if (!(error instanceof Refused)) throw error;
if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);
diff --git a/src/engine.js b/src/engine.js
index 7829cc77..d9b920a5 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -7,7 +7,7 @@ import { Refused } from './refused.js';
/** Only these public board operations may be requested by an encrypted move. */
export const ENGINE_OPERATIONS = Object.freeze([
- 'register', 'ensureCoordinator', 'addItem', 'editItem', 'escalate', 'recordAttempt',
+ 'register', 'ensureCoordinator', 'addItem', 'editItem', 'completeCheckBaseline', 'escalate', 'recordAttempt',
'claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'merged',
'withdraw', 'refreeze', 'shout', 'passDecision', 'answerDecision', 'holdLane', 'releaseLane',
'addMilestone', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone',
diff --git a/src/machine.js b/src/machine.js
index 1bcbd9bf..d93cce97 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -9,8 +9,8 @@
* broken copy, and checks the declaration against the refusals board.js and cli.js raise today.
*/
-/** Executable move semantics; bump whenever a move's meaning changes [H16]. */
-export const ENGINE_VERSION = 1;
+/** Executable move semantics; bump once per release after a released move's meaning changes [H16]. */
+export const ENGINE_VERSION = 2;
/** @typedef {'agent' | 'coordinator' | 'clock'} Role */
diff --git a/test/check-baseline-worker.test.js b/test/check-baseline-worker.test.js
new file mode 100644
index 00000000..5933b017
--- /dev/null
+++ b/test/check-baseline-worker.test.js
@@ -0,0 +1,158 @@
+/** Background check baseline completions are authorized and replay as deterministic board moves [V2,H16]. */
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';
+import { ENGINE_VERSION } from '../src/machine.js';
+
+const MAIN = 'a'.repeat(40);
+const ADD_AT = '2026-10-08T20:00:00.000Z';
+const RESULT_AT = '2026-10-08T20:00:01.000Z';
+
+/** Build a valid pending request whose identity is stable across replicas. */
+function pendingBaseline(command, request = randomUUID(), main = MAIN) {
+ return { command, main, result: 'pending', request };
+}
+
+/** Open an in-memory board and register it for node:test cleanup. */
+function memoryBoard(t) {
+ const board = store.openBoard(':memory:');
+ t.after(() => store.closeBoard(board));
+ return board;
+}
+
+/** Create three real SQLite boards with the same exported starting rows. */
+function boardReplicas(t) {
+ const source = memoryBoard(t);
+ const replicas = [memoryBoard(t), memoryBoard(t)];
+ const initial = exportBoard(source);
+ for (const board of replicas) importBoard(board, initial);
+ return { source, replicas };
+}
+
+/** Make a harmless shell command that would leave a marker if any replica executed it. */
+function markerCommand(marker) {
+ /** Quote the synthetic marker command's literals for a POSIX shell. */
+ const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
+ const script = `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran')`;
+ return `${quote(process.execPath)} -e ${quote(script)}`;
+}
+
+/** Apply one immutable captured operation to each board at the same relay sequence and time. */
+function applyToEach(boards, move, sequence, at) {
+ return boards.map((board) => applyEngineMove(board, move, { sequence, at }));
+}
+
+test('[V2,H16] a captured pending baseline completes once and replays without executing its command', (t) => {
+ assert.ok(ENGINE_VERSION >= 2, 'completeCheckBaseline is a released engine operation');
+ const { source, replicas } = boardReplicas(t);
+ const marker = join(tmpdir(), `pullboard-baseline-must-not-run-${randomUUID()}`);
+ t.after(() => rmSync(marker, { force: true }));
+ const command = markerCommand(marker);
+ const pending = pendingBaseline(command, '11111111-1111-4111-8111-111111111111');
+ const boards = [source, ...replicas];
+
+ const add = prepareEngineMove(source, 'addItem', [{
+ by: 'coordinator', lane: 'web', title: 'Background baseline',
+ check: command, checkBaseline: pending,
+ }], { id: 'baseline-worker-add' });
+ const added = applyToEach(boards, add, 1, ADD_AT);
+ assert.ok(added.every((outcome) => outcome.result === 1));
+ const itemId = added[0].result;
+ assert.ok(boards.every((board) => store.getItem(board, itemId).item_check_baseline.result === 'pending'));
+ assert.equal(existsSync(marker), false, 'recording the requested command does not run it');
+
+ const baseline = { command, main: pending.main, result: 'green' };
+ const completion = prepareEngineMove(source, 'completeCheckBaseline', [itemId, {
+ agentId: 'coordinator', expected: pending, baseline,
+ }], { id: 'baseline-worker-result' });
+ const completed = applyToEach(boards, completion, 2, RESULT_AT);
+ assert.ok(completed.every((outcome) => outcome.result === true));
+ assert.ok(boards.every((board) => {
+ const current = store.getItem(board, itemId).item_check_baseline;
+ return current.command === command && current.main === MAIN && current.result === 'green'
+ && current.request === pending.request && current.warning === 'CRITERION_PROVES_NOTHING';
+ }));
+ assert.ok(boards.every((board) => store.events(board, { itemId }).filter((event) => event.event_kind === 'check-baseline').length === 1));
+ assert.deepEqual(exportBoard(source), exportBoard(replicas[0]));
+ assert.deepEqual(exportBoard(source), exportBoard(replicas[1]));
+ assert.equal(existsSync(marker), false, 'the completion move stores the result without executing the check');
+});
+
+test('[V2,H16] stale requests, cleared checks and duplicate terminal results cannot overwrite a baseline', (t) => {
+ const board = memoryBoard(t);
+ const commandA = 'check-a';
+ const commandB = 'check-b';
+ const first = pendingBaseline(commandA, '22222222-2222-4222-8222-222222222222');
+ const itemId = store.addItem(board, {
+ by: 'coordinator', lane: 'web', title: 'Superseded baseline',
+ check: commandA, checkBaseline: first,
+ });
+ const second = pendingBaseline(commandB, '33333333-3333-4333-8333-333333333333');
+ store.editItem(board, itemId, { agentId: 'coordinator', check: commandB, checkBaseline: second });
+ const third = pendingBaseline(commandA, '44444444-4444-4444-8444-444444444444');
+ store.editItem(board, itemId, { agentId: 'coordinator', check: commandA, checkBaseline: third });
+ const beforeOldResult = exportBoard(board);
+ const stale = store.completeCheckBaseline(board, itemId, {
+ agentId: 'coordinator', expected: first,
+ baseline: { command: commandA, main: MAIN, result: 'green' },
+ });
+ assert.equal(stale, false, 'A→B→A still rejects A’s old request id');
+ assert.deepEqual(exportBoard(board), beforeOldResult, 'stale completion creates neither metadata nor an event');
+
+ store.editItem(board, itemId, { agentId: 'coordinator', check: '' });
+ const afterClear = exportBoard(board);
+ assert.equal(store.completeCheckBaseline(board, itemId, {
+ agentId: 'coordinator', expected: third,
+ baseline: { command: commandA, main: MAIN, result: 'red' },
+ }), false, 'a cleared check no longer has a pending request');
+ assert.deepEqual(exportBoard(board), afterClear, 'a late result cannot restore cleared baseline metadata');
+ assert.equal(Object.hasOwn(store.getItem(board, itemId), 'item_check_baseline'), false);
+
+ const fourth = pendingBaseline('check-final', '55555555-5555-4555-8555-555555555555');
+ store.editItem(board, itemId, { agentId: 'coordinator', check: fourth.command, checkBaseline: fourth });
+ const result = { command: fourth.command, main: MAIN, result: 'red' };
+ assert.equal(store.completeCheckBaseline(board, itemId, { agentId: 'coordinator', expected: fourth, baseline: result }), true);
+ const afterTerminal = exportBoard(board);
+ const eventCount = store.events(board, { itemId }).length;
+ assert.equal(store.completeCheckBaseline(board, itemId, { agentId: 'coordinator', expected: fourth, baseline: result }), false,
+ 'a duplicate completion cannot replace a terminal result');
+ assert.deepEqual(exportBoard(board), afterTerminal);
+ assert.equal(store.events(board, { itemId }).length, eventCount);
+});
+
+test('[V2,H16] only the coordinator can set or complete a check baseline and invalid results leave no writes', (t) => {
+ const board = memoryBoard(t);
+ const pending = pendingBaseline('true', '66666666-6666-4666-8666-666666666666');
+ const before = exportBoard(board);
+ assert.throws(() => store.addItem(board, {
+ by: 'web-1', lane: 'web', title: 'Agent supplied baseline', check: pending.command, checkBaseline: pending,
+ }), { code: 'COORDINATOR_CHECK' });
+ assert.deepEqual(exportBoard(board), before, 'an unauthorized pending baseline adds no item or event');
+
+ const ordinaryId = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Ordinary item', check: pending.command });
+ const beforeUnauthorizedEdit = exportBoard(board);
+ assert.throws(() => store.editItem(board, ordinaryId, {
+ agentId: 'web-1', check: pending.command, checkBaseline: pending,
+ }), { code: 'COORDINATOR_CHECK' });
+ assert.deepEqual(exportBoard(board), beforeUnauthorizedEdit, 'an unauthorized edit stores no pending baseline');
+
+ const itemId = store.addItem(board, {
+ by: 'coordinator', lane: 'web', title: 'Authorized pending baseline',
+ check: pending.command, checkBaseline: pending,
+ });
+ const beforeBadCompletion = exportBoard(board);
+ assert.throws(() => store.completeCheckBaseline(board, itemId, {
+ agentId: 'web-1', expected: pending, baseline: { command: pending.command, main: MAIN, result: 'green' },
+ }), { code: 'COORDINATOR_CHECK' });
+ assert.deepEqual(exportBoard(board), beforeBadCompletion, 'an unauthorized completion changes no rows');
+ assert.throws(() => store.completeCheckBaseline(board, itemId, {
+ agentId: 'coordinator', expected: pending, baseline: { command: pending.command, main: MAIN, result: 'orange' },
+ }), { code: 'BAD_CHECK_BASELINE' });
+ assert.deepEqual(exportBoard(board), beforeBadCompletion, 'an invalid result changes no rows');
+});
diff --git a/test/check-baseline.test.js b/test/check-baseline.test.js
index d09a2fef..9a628870 100644
--- a/test/check-baseline.test.js
+++ b/test/check-baseline.test.js
@@ -5,7 +5,8 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, wr
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 { openBoard, closeBoard, getItem } from '../src/board.js';
+import { checkBaseline, prepareCheckBaseline } from '../src/check-baseline.js';
import { exportBoard, importBoard } from '../src/exchange.js';
import { applyEngineMove, prepareEngineMove } from '../src/engine.js';
@@ -53,10 +54,10 @@ function sandbox() {
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) {
+ function run(cwd, args, input, options = {}) {
return spawnSync(process.execPath, [BIN, ...args], {
cwd, env, encoding: 'utf8', timeout: 20_000,
- ...(input === undefined ? {} : { input }),
+ ...(input === undefined ? {} : { input }), ...options,
});
}
return { dir, env, git, run };
@@ -119,7 +120,7 @@ function fileCheck(expected, marker = 'check-marker.txt', observations = null) {
/** 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']);
+ const result = box.run(box.repo, ['add', 'web', title, '--specs', 'G1', '--criterion', 'the check is measured on main', '--check', check, '--wait', '--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 };
@@ -132,6 +133,84 @@ function showItem(box, id, cwd = box.repo) {
return { result, item: JSON.parse(result.stdout) };
}
+/** Await an actual fixture state, with a deadline used only to prevent a stranded child. */
+async function waitForState(read, description) {
+ const deadline = Date.now() + 30_000;
+ while (!read() && Date.now() < deadline) await new Promise((done) => setTimeout(done, 25));
+ assert.ok(read(), description);
+}
+
+/** Build a check held on a release file; its finite fallback lets a blocking mutant finish red. */
+function heldCheck(box, name) {
+ const started = join(box.dir, `${name}-started.json`);
+ const finished = join(box.dir, `${name}-finished`);
+ const release = join(box.dir, `${name}-release`);
+ const script = [
+ "const fs=require('node:fs');",
+ `fs.writeFileSync(${JSON.stringify(started)},JSON.stringify({cwd:process.cwd(),content:fs.readFileSync('web/result.txt','utf8').trim()}));`,
+ `const until=Date.now()+20000;while(!fs.existsSync(${JSON.stringify(release)})&&Date.now()<until)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25);`,
+ `fs.writeFileSync(${JSON.stringify(finished)},'finished');`,
+ ].join('');
+ return { started, finished, release, command: `${shellWord(process.execPath)} -e ${shellWord(script)}` };
+}
+
+test('[V2,H16] add and edit return while isolated background checks are held, then publish their results', async (t) => {
+ const box = project({ content: 'committed' });
+ const originalMain = box.git(box.repo, 'rev-parse', 'main');
+ writeFileSync(join(box.repo, 'web/result.txt'), 'dirty live checkout\n');
+ const addition = heldCheck(box, 'add-background');
+ const edit = heldCheck(box, 'edit-background');
+ t.after(() => {
+ writeFileSync(addition.release, 'release');
+ writeFileSync(edit.release, 'release');
+ });
+ const added = box.run(box.repo, ['add', 'web', 'Background check', '--check', addition.command, '--json'], undefined, { timeout: 45_000 });
+ assert.equal(added.status, 0, `${added.stdout}${added.stderr}`);
+ assert.equal(existsSync(addition.finished), false, 'add returns before its baseline finishes');
+ const item = JSON.parse(added.stdout).item;
+ assert.equal(item.item_check_baseline.result, 'pending');
+ assert.equal(item.item_check_baseline.main, originalMain);
+ await waitForState(() => existsSync(addition.started), 'the detached add worker runs after the caller exits');
+ const observed = JSON.parse(readFileSync(addition.started, 'utf8'));
+ assert.notEqual(observed.cwd, box.repo);
+ assert.equal(observed.content, 'committed', 'the baseline sees committed main, never dirty live content');
+ writeFileSync(addition.release, 'release');
+ await waitForState(() => withBoard(join(box.repo, BOARD_FILE), (board) => getItem(board, item.item_id).item_check_baseline?.result === 'green'), 'the background add result is recorded');
+ assert.equal(existsSync(observed.cwd), false, 'the isolated checkout is removed after its check');
+ assert.match(box.run(box.repo, ['show', String(item.item_id)]).stdout, /CRITERION_PROVES_NOTHING/u);
+ const edited = box.run(box.repo, ['edit', String(item.item_id), '--check', edit.command, '--json'], undefined, { timeout: 45_000 });
+ assert.equal(edited.status, 0, `${edited.stdout}${edited.stderr}`);
+ assert.equal(existsSync(edit.finished), false, 'edit returns before its changed check finishes');
+ assert.equal(JSON.parse(edited.stdout).item.item_check_baseline.result, 'pending');
+ await waitForState(() => existsSync(edit.started), 'the detached edit worker starts');
+ writeFileSync(edit.release, 'release');
+ await waitForState(() => withBoard(join(box.repo, BOARD_FILE), (board) => getItem(board, item.item_id).item_check_baseline?.result === 'green'), 'the background edit result is recorded');
+ const final = showItem(box, item.item_id).item;
+ assert.equal(final.item_check_baseline.command, edit.command);
+ assert.equal(final.item_check_baseline.warning, 'CRITERION_PROVES_NOTHING');
+ assert.equal(readFileSync(join(box.repo, 'web/result.txt'), 'utf8'), 'dirty live checkout\n');
+});
+
+test('[V2,H16] --wait keeps the check blocking and the captured base survives a later main commit', (t) => {
+ const box = project({ content: 'original' });
+ const held = heldCheck(box, 'wait-background');
+ t.after(() => writeFileSync(held.release, 'release'));
+ const waited = box.run(box.repo, ['add', 'web', 'Wait for check', '--check', held.command, '--wait', '--json'], undefined, { timeout: 45_000 });
+ assert.equal(waited.status, 0, `${waited.stdout}${waited.stderr}`);
+ assert.equal(existsSync(held.finished), true, '--wait returns only after the held check finishes');
+ assert.equal(JSON.parse(waited.stdout).item.item_check_baseline.result, 'green');
+ const command = fileCheck('original', 'captured-base-marker.txt');
+ const captured = prepareCheckBaseline(box.repo, command);
+ writeFileSync(join(box.repo, 'web/result.txt'), 'new main\n');
+ box.git(box.repo, 'add', 'web/result.txt');
+ box.git(box.repo, 'commit', '-q', '-m', 'test: change captured main fixture');
+ const completed = checkBaseline(box.repo, command, { main: captured.main });
+ assert.notEqual(captured.main, box.git(box.repo, 'rev-parse', 'main'));
+ assert.equal(completed.main, captured.main);
+ assert.equal(completed.result, 'green', 'a later main cannot change the queued observation');
+ assert.equal(existsSync(join(box.repo, 'captured-base-marker.txt')), false);
+});
+
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');
@@ -173,7 +252,7 @@ test('[V2,H3,H16] green baseline warns through add edit show and private next ve
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']);
+ const edited = box.run(box.repo, ['edit', String(item.item_id), '--check', changedCheck, '--wait', '--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);
@@ -183,10 +262,10 @@ test('[V2,H3,H16] green baseline warns through add edit show and private next ve
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]);
+ const textAdded = box.run(box.repo, ['add', 'web', 'Text baseline warning', '--check', check, '--wait']);
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`]);
+ const textEdited = box.run(box.repo, ['edit', String(item.item_id), '--check', `${changedCheck}\n# a distinct command`, '--wait']);
assert.equal(textEdited.status, 0, textEdited.stderr);
assert.match(textEdited.stdout, /warning: \[CRITERION_PROVES_NOTHING\]/u);
@@ -229,7 +308,7 @@ test('[V2,H3,H16] repo gates skip command execution and baselines preserve clear
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']);
+ const changed = box.run(box.repo, ['edit', String(gated.item_id), '--check', changedCheck, '--wait', '--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);
diff --git a/test/e2e.test.js b/test/e2e.test.js
index 967d9787..bf6e7be1 100644
--- a/test/e2e.test.js
+++ b/test/e2e.test.js
@@ -941,7 +941,7 @@ test('an item carries a brief to whoever claims it; a light agent sees only its
assert.match(box.run(box.repo, 'add', 'web', 'Copy', '--brief', 'x', '--brief-file', 'y').err, /USAGE.*give the brief once/);
const foreign = box.run(box.repo, 'add', 'web', 'Copy', '--route', 'light', '--criterion', 'c', '--check', 'true', '--brief', LIGHT_BRIEF.replace('web/page.js', 'api/server.js'));
assert.match(foreign.err, /BRIEF_LANE.*api\/server.js \(api's\)/);
- const added = box.run(box.repo, 'add', 'web', 'Copy', 'the', 'header', '--route', 'light', '--criterion', 'the page shows the header', '--check', 'test -f web/page.js', '--brief-file', join(box.dir, 'brief.md'));
+ const added = box.run(box.repo, 'add', 'web', 'Copy', 'the', 'header', '--route', 'light', '--criterion', 'the page shows the header', '--check', 'test -f web/page.js', '--brief-file', join(box.dir, 'brief.md'), '--wait');
assert.equal(added.code, 0, added.err);
assert.equal(added.out.trim(), `#2\ncheck baseline red at main ${box.git(box.repo, 'rev-parse', 'main')}: test -f web/page.js`);
assert.match(box.run(box.repo, 'list').out, /#2 {2}open {2}web {2}Copy the header {2}light/);