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.

fix(board): protect shared schema from unmerged worktrees [A5,A6]

Corey Olsond4dd873fb492
diff --git a/src/api.js b/src/api.js
index 8daa5343..4a07a5fb 100644
--- a/src/api.js
+++ b/src/api.js
@@ -15,18 +15,23 @@ import { createApiHandler } from './api-http.js';
const ADDRESS = '127.0.0.1';
const VERSION = 1;
-/** Read a registered board and release its SQLite connection on every path. */
-function withBoard(root, read) {
+/** Read a registered board and release its SQLite connection on every path.
+ *
+ * @param {string} root
+ * @param {(board: any, info: any) => any} read
+ * @param {boolean} [isMain] Whether the running CLI code comes from the main checkout.
+ */
+function withBoard(root, read, isMain) {
const info = repoInfo(root);
loadConfig(info.root);
- const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: isMain ?? info.isMain });
try { return read(board, info); } finally { store.closeBoard(board); }
}
/** Registered boards carry one persistent identity across local and relay addresses. */
-export function apiBoards(projects = listApiProjects) {
+export function apiBoards(projects = listApiProjects, isMain) {
return projects().flatMap((project) => {
- try { return [withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) }))]; }
+ try { return [withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) }), isMain)]; }
catch { return []; }
});
}
@@ -37,12 +42,12 @@ export function apiBoards(projects = listApiProjects) {
* @param {() => { root: string, name: string, project: string, added: string }[]} projects
* @returns {{ boards: object[], warnings: object[] }}
*/
-function apiBoardListing(projects = listApiProjects) {
+function apiBoardListing(projects = listApiProjects, isMain) {
const boards = [];
const warnings = [];
for (const project of projects()) {
try {
- boards.push(withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) })));
+ boards.push(withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) }), isMain));
} catch {
const error = new Refused('BOARD_UNAVAILABLE', `registered project ${project.root} cannot be read; restore the repo or run pullboard forget ${project.root}`);
warnings.push({ ...project, error: refusalDocument(error) });
@@ -52,19 +57,19 @@ function apiBoardListing(projects = listApiProjects) {
}
/** Resolve only registered boards, so a request cannot open an arbitrary path on the machine. */
-function findBoard(id, projects) {
- const board = apiBoards(projects).find((entry) => entry.id === id);
+function findBoard(id, projects, isMain) {
+ const board = apiBoards(projects, isMain).find((entry) => entry.id === id);
if (!board) throw new Refused('NO_BOARD', `no registered board ${id}; run pullboard serve in its repo and use GET /api/v1/boards`);
return board;
}
/** Read events in sequence, including changes made by other processes on the same board. */
-function afterEvents(root, after) {
- return withBoard(root, (board) => board.db.prepare('SELECT * FROM event WHERE event_id > ? ORDER BY event_id').all(after));
+function afterEvents(root, after, isMain) {
+ return withBoard(root, (board) => board.db.prepare('SELECT * FROM event WHERE event_id > ? ORDER BY event_id').all(after), isMain);
}
/** Resolve an authenticated local caller's agent to its own checkout, never another board. */
-function agentPath(root, name = COORDINATOR) {
+function agentPath(root, name = COORDINATOR, isMain) {
if (typeof name !== 'string' || !name) throw new Refused('BAD_REQUEST', 'agent needs a registered name; omit it to act as the coordinator');
return withBoard(root, (board, info) => {
if (name === COORDINATOR) store.ensureCoordinator(board, root);
@@ -72,7 +77,7 @@ function agentPath(root, name = COORDINATOR) {
if (!agent) throw new Refused('NO_AGENT', `no registered agent ${name}; use the agents in this board's state or join a worktree first`);
if (repoInfo(agent.agent_path).commonDir !== info.commonDir) throw new Refused('WRONG_BOARD', `agent ${name}'s worktree belongs to another board; join the agent in this board's worktree`);
return agent.agent_path;
- });
+ }, isMain);
}
/** Declarative CLI forms keep API calls on the same argument parser and engine as terminal moves. */
@@ -128,11 +133,11 @@ export function moveArgs({ verb, item, args = {} }) {
}
/** Execute one actual CLI command and retain its emitted event without a latest-row race. */
-async function executeMove(root, body, runCommand) {
+async function executeMove(root, body, runCommand, isMain) {
if (Object.keys(body).some((key) => !['verb', 'item', 'args', 'agent'].includes(key))) throw new Refused('BAD_REQUEST', 'a move takes only verb, item, args and agent; remove the unknown fields');
const argv = moveArgs(body);
let cwd;
- try { cwd = agentPath(root, body.agent); } catch (error) {
+ try { cwd = agentPath(root, body.agent, isMain); } catch (error) {
if (!(error instanceof Refused) || error.code === 'BAD_REQUEST') throw error;
return { status: error.code === 'WRONG_BOARD' ? 403 : 409, body: refusalDocument(error) };
}
@@ -141,6 +146,7 @@ async function executeMove(root, body, runCommand) {
const events = [];
const status = await runCommand(argv, {
cwd,
+ codeIsMain: isMain,
stdout: { isTTY: false, write: (text) => { output += text; } },
stderr: { write: (text) => { diagnostics += text; } },
onEvent: (row) => { events.push(row); },
@@ -156,16 +162,16 @@ async function executeMove(root, body, runCommand) {
}
/** Create a person's coordinator request through the same shout transaction as the CLI. */
-function createRequest(root, body) {
+function createRequest(root, body, isMain) {
if (typeof body.text !== 'string' || !body.text.trim() || Object.keys(body).some((key) => key !== 'text')) throw new Refused('BAD_REQUEST', 'a request needs {text: "what the coordinator should do"}');
return withBoard(root, (board) => {
const id = store.shout(board, { from: 'person', to: COORDINATOR, text: body.text, request: true, lanes: laneNames(loadConfig(root)) });
return { version: VERSION, event: board.lastEvent, result: { id, request: true } };
- });
+ }, isMain);
}
/** Create the authenticated local adapter used by the HTTP server and other local transports. */
-export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects } = {}) {
+export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, isMain } = {}) {
if (typeof getPort !== 'function') throw new TypeError('createLocalApiHandler needs a bound-port getter');
if (typeof runCommand !== 'function') throw new TypeError('createLocalApiHandler needs the actual CLI entry point as runCommand');
const key = Buffer.from(secret);
@@ -180,26 +186,26 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
if (req.headers.origin && req.headers.origin !== 'http://' + req.headers.host) throw new Refused('API_ORIGIN', 'use the API from its own origin');
return { local: true };
},
- boards: () => apiBoardListing(projects),
- board: (id) => findBoard(id, projects),
+ boards: () => apiBoardListing(projects, isMain),
+ board: (id) => findBoard(id, projects, isMain),
state: (board, who, seen) => {
- const state = projectState(board.root, { seen });
+ const state = projectState(board.root, { seen, isMain });
state.board = board.id;
- state.requests = withBoard(board.root, (db) => store.openRequests(db));
+ state.requests = withBoard(board.root, (db) => store.openRequests(db), isMain);
return state;
},
code: (board, ref) => codeAt(board.root, ref),
- events: (board, after) => afterEvents(board.root, after),
- move: (board, body) => executeMove(board.root, body, runCommand),
- request: (board, body) => createRequest(board.root, body),
+ events: (board, after) => afterEvents(board.root, after, isMain),
+ move: (board, body) => executeMove(board.root, body, runCommand, isMain),
+ request: (board, body) => createRequest(board.root, body, isMain),
});
}
/** Serve the RFC 0002 API only on loopback, behind the same session-secret boundary as the view. */
-export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects } = {}) {
+export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects, isMain } = {}) {
if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');
let bound;
- const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects });
+ const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects, isMain });
const server = createServer(handler);
server.requestTimeout = 15_000;
return new Promise((ready, fail) => {
diff --git a/src/board.js b/src/board.js
index b5c6f1eb..7d9cd207 100644
--- a/src/board.js
+++ b/src/board.js
@@ -7,7 +7,7 @@
* spec know: the commit, the verifier's checkout, the frozen criterion.
*/
import { randomBytes } from 'node:crypto';
-import { mkdirSync } from 'node:fs';
+import { existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { briefFiles, briefSections } from './brief.js';
@@ -138,9 +138,28 @@ const SCHEMA = `
*
* @param {string} file
* @param {{ now: () => Date }} [clock]
+ * @param {{ isMain?: boolean }} [options] Only the main checkout may upgrade a shared board.
* @returns {{ db: DatabaseSync, clock: { now: () => Date } }}
*/
-export function openBoard(file, clock = systemClock) {
+export function openBoard(file, clock = systemClock, { isMain } = {}) {
+ if (file !== ':memory:' && isMain === false) {
+ let boardVersion = 0;
+ if (existsSync(file)) {
+ const current = new DatabaseSync(file, { readOnly: true });
+ try {
+ current.exec('PRAGMA busy_timeout = 10000');
+ boardVersion = current.prepare('PRAGMA user_version').get().user_version;
+ } finally {
+ current.close();
+ }
+ }
+ if (SCHEMA_VERSION > boardVersion) {
+ throw new Refused(
+ 'UNMERGED_SCHEMA',
+ `this worktree expects board schema ${SCHEMA_VERSION}, newer than the shared board's version ${boardVersion}; merge this code into the main checkout first, or test it against a throwaway board`,
+ );
+ }
+ }
if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });
const db = new DatabaseSync(file);
db.exec('PRAGMA busy_timeout = 10000');
diff --git a/src/cli.js b/src/cli.js
index a27ace02..aeef32e3 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -348,9 +348,12 @@ function sayBrief(io, brief) {
*/
function context(io) {
const info = repoInfo(io.cwd);
+ const allowSchemaUpgrade = io.codeIsMain ?? (process.env.PULLBOARD_CODE_IS_MAIN === undefined
+ ? info.isMain
+ : process.env.PULLBOARD_CODE_IS_MAIN === '1');
const config = configHere(info);
const file = join(info.commonDir, 'pullboard', 'board.sqlite');
- return { info, config, file, doctrine: loadDoctrine(info.root, config), io, clock: io.clock ?? store.systemClock };
+ return { info, config, file, allowSchemaUpgrade, doctrine: loadDoctrine(info.root, config), io, clock: io.clock ?? store.systemClock };
}
/**
@@ -387,7 +390,7 @@ function configHere(info) {
* @returns {T}
*/
function withBoard(ctx, work) {
- const board = store.openBoard(ctx.file, ctx.clock);
+ const board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade });
const firstEvent = board.emittedEvents?.length ?? 0;
try {
const result = work(board);
@@ -695,15 +698,17 @@ async function viewHere(io, values) {
io.say(`wrote snapshot ${exported.path}`);
return 0;
}
+ let isMain = false;
try {
const info = repoInfo(io.cwd);
+ isMain = info.isMain;
if (info.isMain && existsSync(join(info.root, CONFIG_FILE))) registerProject(info.root, new Date(), loadConfig(info.root));
} catch (error) {
if (!(error instanceof Refused)) throw error;
}
const port = values.port === undefined ? 0 : Number(values.port);
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Refused('USAGE', '--port is a number from 0 to 65535; 0 picks a free one');
- const view = await serveView({ port });
+ const view = await serveView({ port, isMain });
io.result?.({ url: view.url, port: view.port });
io.say(`Pullboard view: ${view.url}`);
io.say('Only this machine can reach it, and only with that link. Ctrl-C stops it.');
@@ -727,7 +732,7 @@ async function serveHere(io, values) {
registerProject(mainRoot, new Date(), loadConfig(mainRoot));
const port = values.port === undefined ? 0 : Number(values.port);
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Refused('USAGE', '--port is a number from 0 to 65535; use 0 to choose a free one');
- const api = await serveApi({ port, runCommand: main });
+ const api = await serveApi({ port, runCommand: main, isMain: ctx.info.isMain });
io.result?.({ url: api.url, port: api.port });
io.say(`Pullboard API v1: ${api.url}`);
io.say('Only this machine can reach it, with its session secret. Ctrl-C stops it.');
@@ -754,7 +759,7 @@ function setupCommands(io, { first, values }) {
const info = repoInfo(io.cwd);
const notes = initRepo({
info,
- openBoardHere: () => store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), io.clock),
+ openBoardHere: () => store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), io.clock, { isMain: info.isMain }),
register: store.register,
closeBoard: store.closeBoard,
});
@@ -1522,28 +1527,16 @@ function settingsCommand(io, { first, second, rest }) {
}
/**
- * Every spec id something cites (S8): commit headers since the spec's first commit, and every item
- * on the board, open or closed. Each must still be in the spec. The board is shared by every
- * checkout, so at an older commit an item may cite a row a later commit added: that id is not lost
- * here, only not written yet, and it counts once any ref has committed it (S10).
+ * Every spec id committed in a header since the spec's first commit (S8). Spec checking stays
+ * independent of the shared board, so an unmerged worktree can lint its spec without opening or
+ * migrating board data owned by the main checkout.
*
* @param {any} ctx
- * @param {{ ids: Map<string, string>, since: string | null }} history - this checkout's.
- * @returns {Map<string, string>} Each id, with who cites it.
+ * @param {{ since: string | null }} history - this checkout's spec history.
+ * @returns {Map<string, string>} Each id cited by a commit header.
*/
-function citations(ctx, { ids, since }) {
- const cited = since ? commitCitations(ctx.info.root, since) : new Map();
- if (!existsSync(ctx.file)) return cited;
- const byItems = new Map();
- for (const item of withBoard(ctx, (board) => store.listItems(board, { all: true }))) {
- for (const id of item.item_spec_ids ? item.item_spec_ids.split(',') : []) {
- if (!cited.has(id) && !byItems.has(id)) byItems.set(id, `item #${item.item_id}`);
- }
- }
- const unseen = [...byItems.keys()].some((id) => !ids.has(id));
- const elsewhere = unseen ? committedIds(ctx.info.root, ctx.config.spec, ['--all']).ids : new Map();
- for (const [id, where] of byItems) if (ids.has(id) || !elsewhere.has(id)) cited.set(id, where);
- return cited;
+function citations(ctx, { since }) {
+ return since ? commitCitations(ctx.info.root, since) : new Map();
}
/** Current board evidence, with each item's accepting receipts included once. */
@@ -1856,6 +1849,8 @@ export async function main(argv, streams) {
}
};
if (sync) await retry();
+ if (streams?.codeIsMain !== undefined) io.codeIsMain = streams.codeIsMain;
+ else if (process.env.PULLBOARD_CODE_IS_MAIN !== undefined) io.codeIsMain = process.env.PULLBOARD_CODE_IS_MAIN === '1';
const code = await runCommand(argv, io);
if (sync && code === 0) await retry();
io.flush(code);
diff --git a/src/json.js b/src/json.js
index 76d97dd9..2f8fb27d 100644
--- a/src/json.js
+++ b/src/json.js
@@ -83,7 +83,7 @@ export const JSON_SHAPES = {
/** Extract a concrete repair from existing refusals, retaining their original guidance. */
function nextStep(message) {
- const match = /(?:; |\. |: )((?:run|install|upgrade|fix|restore|commit|check out|set|give|use|ask your coordinator|answer from the main checkout|the coordinator|to keep looking|never work around)\b[\s\S]*)/i.exec(message);
+ const match = /(?:; |\. |: )((?:run|install|upgrade|fix|restore|commit|merge|test|check out|set|give|use|ask your coordinator|answer from the main checkout|the coordinator|to keep looking|never work around)\b[\s\S]*)/i.exec(message);
return match?.[1] ?? 'Run pullboard help, correct the reported problem, and retry the command.';
}
diff --git a/test/api.test.js b/test/api.test.js
index 1457f6b2..c1c15b4e 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { execFileSync, spawn, spawnSync } from 'node:child_process';
import {
chmodSync,
+ cpSync,
existsSync,
mkdirSync,
mkdtempSync,
@@ -12,6 +13,7 @@ import {
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
+import { DatabaseSync } from 'node:sqlite';
import { once } from 'node:events';
import { join, dirname, resolve, basename, delimiter } from 'node:path';
import { after, test } from 'node:test';
@@ -155,6 +157,133 @@ function parseOneDocument(stdout) {
return document;
}
+test('[A5, A6] a future-schema worktree cannot migrate the shared board; main can still upgrade it', () => {
+ const box = sandbox();
+ const repo = join(box.dir, 'repo');
+ const sourceRoot = resolve(import.meta.dirname, '..');
+ mkdirSync(repo);
+ for (const name of ['bin', 'src']) cpSync(join(sourceRoot, name), join(repo, name), { recursive: true });
+ cpSync(join(sourceRoot, 'package.json'), join(repo, 'package.json'));
+ writeFileSync(join(repo, 'pullboard.json'), `${JSON.stringify({
+ gate: 'true', spec: 'SPEC.md', practice: 'PRACTICE.md',
+ lanes: { app: { owns: ['src/'], specs: ['G1'] } }, shared: [],
+ }, null, 2)}\n`);
+ writeFileSync(join(repo, 'SPEC.md'), '# Schema fixture\n\n## G · Goals\n- G1 [approved, must] The board is preserved. | gate: true\n');
+ writeFileSync(join(repo, 'PRACTICE.md'), '');
+ box.git(repo, 'init', '-q', '-b', 'main');
+ box.git(repo, 'add', '-A');
+ box.git(repo, 'commit', '-q', '-m', 'chore: set up schema fixture');
+
+ /** Run the fixture's own CLI so each worktree imports its committed source. */
+ const runFixture = (cwd, ...args) => spawnSync(process.execPath, [join(cwd, 'bin/pullboard.js'), ...args], {
+ cwd, env: box.env, encoding: 'utf8',
+ });
+ const initialized = runFixture(repo, 'status', '--json');
+ assert.equal(initialized.status, 0, initialized.stderr + initialized.stdout);
+ const dbFile = join(repo, '.git', 'pullboard', 'board.sqlite');
+ const prior = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(prior.prepare('PRAGMA user_version').get().user_version, 2);
+ prior.close();
+
+ const older = new DatabaseSync(dbFile);
+ older.exec('ALTER TABLE item DROP COLUMN item_files; PRAGMA user_version = 1');
+ older.close();
+ const upgraded = runFixture(repo, 'status', '--json');
+ assert.equal(upgraded.status, 0, upgraded.stderr + upgraded.stdout);
+ const migrated = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(migrated.prepare('PRAGMA user_version').get().user_version, 2);
+ assert.ok(migrated.prepare('PRAGMA table_info(item)').all().some((column) => column.name === 'item_files'));
+ migrated.close();
+
+ const linked = join(box.dir, 'future');
+ box.git(repo, 'worktree', 'add', '-q', linked, '-b', 'schema/future');
+ assert.equal(box.git(repo, 'rev-parse', '--path-format=absolute', '--git-common-dir'), box.git(linked, 'rev-parse', '--path-format=absolute', '--git-common-dir'));
+ assert.notEqual(box.git(repo, 'rev-parse', '--path-format=absolute', '--git-dir'), box.git(linked, 'rev-parse', '--path-format=absolute', '--git-dir'));
+
+ const boardSource = join(linked, 'src/board.js');
+ const oldSource = readFileSync(boardSource, 'utf8');
+ const migration = " ['shout', 'shout_request_outcome', \"TEXT NOT NULL DEFAULT ''\"],\n ];";
+ assert.ok(oldSource.includes('export const SCHEMA_VERSION = 2;'));
+ assert.ok(oldSource.includes(migration));
+ const newSource = oldSource
+ .replace('export const SCHEMA_VERSION = 2;', 'export const SCHEMA_VERSION = 3;')
+ .replace(migration, migration.replace('\n ];', "\n ['item', 'item_unmerged_probe', 'INTEGER NOT NULL DEFAULT 0'],\n ];"));
+ assert.notEqual(newSource, oldSource, 'the unmerged worktree carries a real schema-3 migration');
+ writeFileSync(boardSource, newSource);
+ box.git(linked, 'add', 'src/board.js');
+ box.git(linked, 'commit', '-q', '-m', 'feat: simulate an unmerged schema bump');
+
+ const before = readFileSync(dbFile);
+ const specCheck = runFixture(linked, 'spec', 'check', '--json');
+ assert.equal(specCheck.status, 0, specCheck.stderr + specCheck.stdout);
+ assert.deepEqual(readFileSync(dbFile), before, 'spec check reads the spec without opening the shared board');
+
+ const surfaceProbe = join(linked, '.schema-surface-probe.mjs');
+ writeFileSync(surfaceProbe, `
+ import { serveApi } from './src/api.js';
+ const root = process.env.PULLBOARD_FIXTURE_REPO;
+ const project = { root, name: 'schema fixture', project: '', added: '2026-01-01T00:00:00.000Z' };
+ const api = await serveApi({ secret: 'api-probe', runCommand: async () => 0, projects: () => [project], isMain: false });
+ try {
+ const listing = await fetch(api.url).then((response) => response.json());
+ console.log(JSON.stringify({
+ apiWarnings: listing.warnings?.map((warning) => warning.error.error.code) ?? [],
+ }));
+ } finally {
+ await api.close();
+ }
+ `);
+ const surfaces = spawnSync(process.execPath, [surfaceProbe], {
+ cwd: linked,
+ env: { ...box.env, PULLBOARD_FIXTURE_REPO: repo },
+ encoding: 'utf8',
+ });
+ assert.equal(surfaces.status, 0, surfaces.stderr + surfaces.stdout);
+ const surfaceResult = JSON.parse(surfaces.stdout);
+ assert.deepEqual(surfaceResult.apiWarnings, ['BOARD_UNAVAILABLE'], 'API reads must report a future-schema board as unavailable');
+ assert.deepEqual(readFileSync(dbFile), before, 'API reads from the linked worktree must not migrate the shared board');
+
+ const refused = runFixture(linked, 'status', '--json');
+ assert.equal(refused.status, 1, refused.stderr + refused.stdout);
+ assert.equal(refused.stderr, '');
+ const document = JSON.parse(refused.stdout);
+ assert.equal(document.error.code, 'UNMERGED_SCHEMA');
+ assert.match(document.error.message, /worktree expects board schema 3, newer than the shared board's version 2/);
+ assert.match(document.error.next, /merge this code into the main checkout first, or test it against a throwaway board/);
+ assert.deepEqual(readFileSync(dbFile), before, 'the newer branch must leave every shared-board byte alone');
+ const unchanged = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(unchanged.prepare('PRAGMA user_version').get().user_version, 2);
+ assert.equal(unchanged.prepare('PRAGMA table_info(item)').all().some((column) => column.name === 'item_unmerged_probe'), false,
+ 'the branch migration would have installed this column without the refusal');
+ unchanged.close();
+
+ const unguarded = join(box.dir, 'unguarded');
+ box.git(repo, 'worktree', 'add', '-q', unguarded, '-b', 'schema/unguarded', 'schema/future');
+ const guardedSource = join(unguarded, 'src/board.js');
+ const guardedText = readFileSync(guardedSource, 'utf8');
+ const unguardedText = guardedText.replace(/ if \(file !== ':memory:' && isMain === false\) \{[\s\S]*?\n \}\n(?= if \(file !== ':memory:'\) mkdirSync)/, '');
+ assert.notEqual(unguardedText, guardedText, 'the mutation removes only the unmerged-schema guard');
+ writeFileSync(guardedSource, unguardedText);
+ const mutationProbe = join(unguarded, '.schema-mutation-probe.mjs');
+ writeFileSync(mutationProbe, `
+ import { openBoard, closeBoard } from './src/board.js';
+ const board = openBoard(process.env.PULLBOARD_FIXTURE_BOARD, undefined, { isMain: false });
+ closeBoard(board);
+ `);
+ const mutation = spawnSync(process.execPath, [mutationProbe], {
+ cwd: unguarded,
+ env: { ...box.env, PULLBOARD_FIXTURE_BOARD: dbFile },
+ encoding: 'utf8',
+ });
+ assert.equal(mutation.status, 0, mutation.stderr + mutation.stdout);
+ const mutated = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(mutated.prepare('PRAGMA user_version').get().user_version, 3,
+ 'removing the guard makes the linked worktree silently migrate the shared board');
+ assert.ok(mutated.prepare('PRAGMA table_info(item)').all().some((column) => column.name === 'item_unmerged_probe'),
+ 'the guard-removal mutation installs its real schema-3 probe column');
+ mutated.close();
+});
+
test('[A1] command results match the catalog across roots and subcommands', () => {
const box = project();
const { repo } = box;
@@ -660,7 +789,7 @@ test('[A2] moves run as the named worktree agent and requests stay visible until
const added = await (await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'add', args: { lane: 'app', title: 'Agent work' } }) })).json();
const claimedResponse = await apiFetch(api, `${path}/moves`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'next', args: {}, agent: 'app-1' }) });
- assert.equal(claimedResponse.status, 200);
+ assert.equal(claimedResponse.status, 200, await claimedResponse.clone().text());
const claimed = await claimedResponse.json();
assert.equal(claimed.event.event_by, 'app-1');
assert.equal(claimed.event.event_kind, 'claim');
diff --git a/test/e2e.test.js b/test/e2e.test.js
index a6593677..c54e9666 100644
--- a/test/e2e.test.js
+++ b/test/e2e.test.js
@@ -902,7 +902,7 @@ test('next --verify can reserve a named submitted review and default to the lowe
assert.match(lowest.out, new RegExp(`next to verify: #${first} First review, built by web-1`));
});
-test('a deleted spec row is refused at commit; spec check finds any id gone from history or cited [S8, S9]', () => {
+test('spec check reads committed history only; claim guards live item citations [S8, S9]', () => {
const box = project();
const spec = join(box.repo, 'SPEC.md');
writeFileSync(spec, SPEC.replace(/- G2 .*\n/, ''));
@@ -919,7 +919,10 @@ test('a deleted spec row is refused at commit; spec check finds any id gone from
assert.equal(check.code, 1);
assert.match(check.out, /SPEC.md: G2 error: was committed in [0-9a-f]{12} and is gone/);
assert.match(check.out, /SPEC.md: G7 error: commit [0-9a-f]{7,} cites it, but it was never committed/);
- assert.match(check.out, /SPEC.md: G3 error: item #1 cites it, but it was never committed/);
+ assert.doesNotMatch(check.out, /G3 error: item #1 cites it/, 'spec check reads committed history without opening the shared board');
+ const liveItem = box.run(box.web, 'claim', '1');
+ assert.equal(liveItem.code, 1);
+ assert.match(liveItem.err, /UNKNOWN_SPEC.*G3/ , 'a board operation still refuses to freeze an item whose cited row is gone');
writeFileSync(spec, `${SPEC.replace('- G2 [approved, must]', '- G2 [wont, must]')}- G3 [retired] Planned before the spec settled.\n- G7 [retired] Cited by mistake.\n`);
const fixed = box.run(box.repo, 'spec', 'check');
assert.equal(fixed.code, 0, fixed.out);
@@ -1336,7 +1339,7 @@ test('submit refuses a bar that moved since the claim, before any verifier runs;
assert.match(box.run(box.web, 'submit', '1').out, /submitted #1/);
});
-test('spec check at an older commit skips ids that items cite from a later commit; a never-committed id still fails [S10]', () => {
+test('spec check stays source-only at an older commit; claim still validates a later item citation [S10]', () => {
const box = project();
writeFileSync(join(box.repo, 'SPEC.md'), `${SPEC}- G3 [draft, must] The page has a footer.\n`);
box.git(box.repo, 'commit', '-qam', 'docs(spec): a footer row');
@@ -1346,9 +1349,12 @@ test('spec check at an older commit skips ids that items cite from a later commi
writeFileSync(join(box.repo, 'SPEC.md'), `${SPEC}- G3 [draft, must] The page has a footer.\n- G4 [draft, must] Not committed.\n`);
box.run(box.repo, 'add', 'web', 'Ghost', '--specs', 'G4');
const ghost = box.run(box.web, 'spec', 'check');
- assert.equal(ghost.code, 1);
- assert.match(ghost.out, /SPEC.md: G4 error: item #2 cites it, but it was never committed/);
+ assert.equal(ghost.code, 0, ghost.out);
+ assert.doesNotMatch(ghost.out, /G4 error: item #2 cites it/);
assert.doesNotMatch(ghost.out, /G3 error/);
+ const claim = box.run(box.web, 'claim', '2');
+ assert.equal(claim.code, 1);
+ assert.match(claim.err, /UNKNOWN_SPEC.*G4/);
});
test('check runs the item\'s own check command, yours by default, and prints a digest [N23]', () => {