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): guard shared formats across source provenance [A5,A6]

Corey Olsonc5bcc2f55b40
diff --cc src/api.js
index 582c9aca,32ff0c96..f3dfa447
--- a/src/api.js
+++ b/src/api.js
@@@ -1,16 -1,13 +1,16 @@@
/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
-import { dirname, join } from 'node:path';
+import { join } from 'node:path';
import * as store from './board.js';
import { COORDINATOR, loadConfig } from './config.js';
- import { repoInfo } from './git.js';
+ import { codeIsFromMain, repoInfo } from './git.js';
import { refusalDocument } from './json.js';
+import { relayLinked, relayOperation } from './relay.js';
import { laneNames } from './lanes.js';
import { listApiProjects } from './projects.js';
+import { milestoneRoadmap } from './roadmap.js';
+import { projectRowDecisions } from './row-decisions.js';
import { Refused } from './refused.js';
import { codeAt, projectState } from './serve.js';
import { createApiHandler } from './api-http.js';
@@@ -45,9 -47,9 +50,9 @@@ function apiBoardListing(projects = lis
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}`);
+ } catch (cause) {
+ const error = cause.code === 'EVENT_LOG_VERSION' ? cause : 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) });
}
}
@@@ -67,17 -69,15 +72,17 @@@ function afterEvents(root, after, isMai
}
/** 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);
+ if (name === COORDINATOR && !relayLinked(root)) store.ensureCoordinator(board, root);
const agent = store.listAgents(board).find((entry) => entry.agent_id === name);
if (!agent) throw new Refused('NO_AGENT', `no registered agent ${name}; use the agents in this board's state or join a worktree first`);
+ // A clone shares the coordinator identity, but resolves its main checkout locally.
+ if (name === COORDINATOR && relayLinked(root)) return root;
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. */
@@@ -165,19 -161,12 +170,19 @@@ async function executeMove(root, body,
}
/** Create a person's coordinator request through the same shout transaction as the CLI. */
- async function createRequest(root, body) {
-function createRequest(root, body, isMain) {
++async 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"}');
+ const message = { from: 'person', to: COORDINATOR, text: body.text, request: true, lanes: laneNames(loadConfig(root)) };
+ if (relayLinked(root)) {
+ const id = await relayOperation(root, 'shout', [message], { err: () => {} });
+ return withBoard(root, (board) => ({ version: VERSION,
+ event: store.events(board).find((event) => JSON.parse(event.event_detail).shout === id),
- result: { id, request: true } }));
++ result: { id, request: true } }), isMain);
+ }
return withBoard(root, (board) => {
- const id = store.shout(board, { from: 'person', to: COORDINATOR, text: body.text, request: true, lanes: laneNames(loadConfig(root)) });
+ const id = store.shout(board, message);
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. */
@@@ -196,26 -186,18 +202,26 @@@ export function createLocalApiHandler(
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, codeIsMain),
+ board: (id) => findBoard(id, projects, codeIsMain),
state: (board, who, seen) => {
- let state = projectState(board.root, { seen });
- const state = projectState(board.root, { seen, isMain: codeIsMain });
++ let state = projectState(board.root, { seen, isMain: codeIsMain });
state.board = board.id;
- state.requests = withBoard(board.root, (db) => store.openRequests(db), codeIsMain);
+ const projectData = withBoard(board.root, (db) => ({
+ requests: store.openRequests(db),
+ milestones: milestoneRoadmap(board.root, db),
+ rowDecisions: store.rowDecisions(db),
- }));
++ }), codeIsMain);
+ state.requests = projectData.requests;
+ state.milestones = projectData.milestones;
+ state = projectRowDecisions(projectData.rowDecisions, state);
return state;
},
code: (board, ref) => codeAt(board.root, ref),
- events: (board, after) => afterEvents(board.root, after),
+ events: (board, after) => afterEvents(board.root, after, codeIsMain),
+ eventLogVersion: () => store.EVENT_LOG_VERSION,
- move: (board, body) => executeMove(board.root, body, runCommand),
- request: (board, body) => createRequest(board.root, body),
+ move: (board, body) => executeMove(board.root, body, runCommand, codeIsMain),
+ request: (board, body) => createRequest(board.root, body, codeIsMain),
});
}
diff --cc src/board.js
index 60db3e95,a232f89f..a2ad59f9
--- a/src/board.js
+++ b/src/board.js
@@@ -139,25 -138,39 +139,49 @@@ 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;
++ let logVersion = 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;
++ logVersion = readEventLogVersion(current);
+ } 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 (EVENT_LOG_VERSION > logVersion) {
++ throw new Refused('UNMERGED_SCHEMA', `this worktree expects event log ${EVENT_LOG_VERSION}, newer than the shared board's version ${logVersion}; 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');
- if (file !== ':memory:') db.exec('PRAGMA journal_mode = WAL');
- db.exec(SCHEMA);
- migrate(db);
- db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('board_id', randomBytes(16).toString('hex'));
- const board = { db, clock };
- guardStore(board);
- guardMoves(board);
- return board;
+ try {
+ db.exec('PRAGMA busy_timeout = 10000');
+ if (file !== ':memory:') db.exec('PRAGMA journal_mode = WAL');
+ migrateEventLogVersion(db);
+ migrate(db);
+ db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('board_id', randomBytes(16).toString('hex'));
+ const board = { db, clock };
+ guardStore(board);
+ guardMoves(board);
+ return board;
+ } catch (error) {
+ db.close();
+ throw error;
+ }
}
/**
diff --cc src/cli.js
index ac2e81c4,198652d0..c86f10da
--- a/src/cli.js
+++ b/src/cli.js
@@@ -8,13 -7,11 +8,14 @@@ import { existsSync, mkdirSync, readFil
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
++import { DatabaseSync } from 'node:sqlite';
import * as store from './board.js';
import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
import { loadDoctrine } from './doctrine.js';
+import { requirePersonChannel } from './person.js';
+import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
import { digestOf, gateReport, runGate, runShell } from './gate.js';
- import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';
+ import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';
import {
FIX_NOTE,
applyFixers,
@@@ -618,26 -388,15 +620,26 @@@ 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);
+ /** Forward committed events before releasing either synchronous or asynchronous work. */
+ const finish = () => {
for (const event of board.emittedEvents?.slice(firstEvent) ?? []) ctx.io.onEvent?.(event);
- return result;
- } finally {
store.closeBoard(board);
- }
+ };
+ let result;
+ try { result = work(board); }
+ catch (error) { finish(); throw error; }
+ if (result && typeof result.then === 'function') return result.finally(finish);
+ finish();
+ return result;
+}
+
+/** Dispatch a board mutation locally, or seal it before any linked replica applies it. */
+async function ordered(ctx, board, operation, args) {
+ return relayLinked(ctx.info.root)
+ ? relayOperation(ctx.info.root, operation, args, ctx.io)
+ : store[operation](board, ...args);
}
/**
@@@ -1009,15 -757,8 +1013,15 @@@ function setupCommands(io, { first, val
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: codeIsFromMain() }),
- register: store.register,
+ /** Keep a linked coordinator's canonical identity without writing a clone-local path. */
+ register: (board, options) => {
+ if (!relayLinked(info.root)) return store.register(board, options);
+ if (!board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(COORDINATOR)) {
+ throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before initializing');
+ }
+ return COORDINATOR;
+ },
closeBoard: store.closeBoard,
});
io.result?.({ root: info.root, notes });
@@@ -1304,7 -1017,7 +1308,7 @@@ function readCommands(io, { first, seco
return 1;
}
const ctx = context(io);
- const problems = doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config);
- const problems = doctorProblems(ctx.file, ctx.info.root, tryGit);
++ const problems = doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config, { isMain: ctx.allowSchemaUpgrade });
io.result?.({ problems });
if (!problems.length) {
io.say('board is clean');
@@@ -2160,6 -1691,6 +2152,14 @@@ async function readStdin(stdin)
return Buffer.concat(chunks).toString('utf8');
}
++/** Read a lane identity without upgrading the shared board from a newer checkout's hook. */
++function hookAgent(ctx) {
++ if (!existsSync(ctx.file)) return null;
++ const db = new DatabaseSync(ctx.file, { readOnly: true });
++ try { return store.agentAt({ db }, ctx.info.root); }
++ finally { db.close(); }
++}
++
/**
* The hooks git runs. In a repo without pullboard.json they pass, so a stray hook never blocks.
*
@@@ -2179,8 -1710,8 +2179,8 @@@ async function hookCommand(io, { first
let problems = [];
if (first === 'pre-commit') {
applyFixers(info.root, ctx.config.fix).forEach((note) => io.err(`pullboard pre-commit: ${note}`));
-- const agent = info.isMain ? null : withBoard(ctx, (board) => store.agentAt(board, info.root));
- problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent });
++ const agent = info.isMain ? null : hookAgent(ctx);
+ problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent, boardFile: ctx.file });
} else if (first === 'commit-msg') {
const message = readFileSync(second ?? '', 'utf8');
problems = commitMsgProblems(message, { rules: ctx.config.commits, spec: loadSpec(info.root, ctx.config) });
diff --cc src/doctor.js
index de5c3959,c3442e9f..a361897a
--- a/src/doctor.js
+++ b/src/doctor.js
@@@ -1,12 -1,9 +1,12 @@@
/** Read-only integrity checks for a pullboard board file (A6). */
import { existsSync } from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
+import { checkAtCommit, submissionPaths, dependencySnapshots } from './trusted-policy.js';
import { BLANKS, STATES, storeTriggers } from './machine.js';
- import { readEventLogVersion, SCHEMA_VERSION } from './board.js';
-import { SCHEMA_VERSION } from './board.js';
++import { EVENT_LOG_VERSION, readEventLogVersion, SCHEMA_VERSION } from './board.js';
+import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
+import { loadSpec } from './spec.js';
const blankCharacters = new Set(BLANKS.map((point) => String.fromCodePoint(point)));
/**
@@@ -16,20 -13,14 +16,28 @@@
* @param {string} file
* @param {string} root
* @param {(root: string, args: string[]) => { status: number, stdout: string }} tryGit
+ * @param {any} [config] - Compare frozen rows with this checkout's current source when supplied.
++ * @param {{ isMain?: boolean }} [options] - Give older-board repair steps for the running source.
* @returns {{ code: string, message: string, next: string }[]}
*/
- export function doctorProblems(file, root, tryGit, config) {
-export function doctorProblems(file, root, tryGit) {
++export function doctorProblems(file, root, tryGit, config, { isMain = true } = {}) {
if (!existsSync(file)) return [finding('BOARD_MISSING', 'board file is missing', 'run pullboard status to create a new board')];
const db = new DatabaseSync(file, { readOnly: true });
try {
-- const schemaProblems = versionProblems(db);
++ const schemaProblems = versionProblems(db, isMain);
if (schemaProblems.length) return schemaProblems;
- try { readEventLogVersion(db); }
++ try {
++ const version = readEventLogVersion(db);
++ if (version < EVENT_LOG_VERSION) {
++ const next = isMain ? 'run pullboard status to upgrade this event log'
++ : 'merge this code into the main checkout first, then run pullboard status there; or test it against a throwaway board';
++ return [finding('EVENT_LOG_VERSION', `event log version is ${version}; this pullboard expects ${EVENT_LOG_VERSION}`, next)];
++ }
++ }
+ catch (error) {
+ if (error.code !== 'EVENT_LOG_VERSION') throw error;
+ return [finding(error.code, error.message, 'upgrade pullboard to read this event log, or restore a compatible board')];
+ }
const layout = layoutProblems(db);
return [
...triggerProblems(db),
@@@ -91,11 -79,11 +99,11 @@@ function layoutProblems(db)
* @param {DatabaseSync} db
* @returns {{ code: string, message: string, next: string }[]}
*/
--function versionProblems(db) {
++function versionProblems(db, isMain) {
const version = db.prepare('PRAGMA user_version').get().user_version;
if (version === SCHEMA_VERSION) return [];
const repair = version < SCHEMA_VERSION
-- ? 'run pullboard status to upgrade this board'
++ ? (isMain ? 'run pullboard status to upgrade this board' : 'merge this code into the main checkout first, then run pullboard status there; or test it against a throwaway board')
: 'use a pullboard version that supports this board schema';
return [finding('SCHEMA_VERSION', `schema version is ${version}; this pullboard expects ${SCHEMA_VERSION}`, repair)];
}
diff --cc src/git.js
index 28e8cfc3,b6c7dbd6..ae1aab4e
--- a/src/git.js
+++ b/src/git.js
@@@ -3,46 -3,13 +3,48 @@@
* and whether the tree is clean. Every call is a plain `git` child process.
*/
import { execFileSync, spawnSync } from 'node:child_process';
--import { existsSync, readdirSync, statSync } from 'node:fs';
++import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
+ import { fileURLToPath } from 'node:url';
import { Refused } from './refused.js';
-const GIT_FLAGS = ['-c', 'core.quotepath=false'];
+const GIT_FLAGS = ['--no-replace-objects', '-c', 'core.quotepath=false'];
+
+/** Clear inherited Git selectors while retaining ordinary user settings and exact-object behavior.
+ *
+ * @returns {NodeJS.ProcessEnv}
+ */
+export function cleanGitEnvironment() {
+ const env = { ...process.env };
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_PREFIX', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_SHALLOW_FILE']) delete env[key];
+ for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_/.test(key)) delete env[key];
+ env.GIT_NO_REPLACE_OBJECTS = '1';
+ return env;
+}
+
+/** Resolve the primary checkout's branch and commit without assuming its branch is named main.
+ *
+ * @param {string} root
+ * @returns {{branch: string, commit: string|null}|null}
+ */
+export function mainCheckout(root) {
+ const env = cleanGitEnvironment();
+ /** Run one Git lookup with the sanitized environment. */
+ const gitCall = (args) => spawnSync('git', [...GIT_FLAGS, ...args], {
+ cwd: root, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
+ });
+ const common = gitCall(['rev-parse', '--path-format=absolute', '--git-common-dir']);
+ if (common.status !== 0) throw new Refused('NO_POLICY', 'the primary checkout cannot be located; restore the repository and ask the coordinator to retry');
+ const commonDir = common.stdout.trim();
+ const symbolic = gitCall(['--git-dir', commonDir, 'symbolic-ref', '--quiet', 'HEAD']);
+ if (symbolic.status === 1) return null;
+ if (symbolic.status !== 0) throw new Refused('NO_POLICY', 'the primary checkout branch cannot be read; restore its Git metadata and ask the coordinator to retry');
+ const branch = symbolic.stdout.trim();
+ const resolved = gitCall(['--git-dir', commonDir, 'rev-parse', '--verify', '--quiet', `${branch}^{commit}`]);
+ if (resolved.status !== 0 && resolved.status !== 1) throw new Refused('NO_POLICY', 'the primary checkout commit cannot be read; restore its Git objects and ask the coordinator to retry');
+ return { branch, commit: resolved.status === 0 ? resolved.stdout.trim() : null };
+}
+ const CODE_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
/**
* The environment for a gate or fixer: keep the user's settings, but remove Git's repository-local
@@@ -54,8 -21,16 +56,17 @@@
*/
export function gitChildEnv(root) {
const env = { ...process.env };
- for (const name of git(root, ['rev-parse', '--local-env-vars']).split('\n')) delete env[name];
- env.GIT_NO_REPLACE_OBJECTS = '1'; // Exact-tree receipts must never resolve replacement refs.
+ const discoveryEnv = { ...env };
+ for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR']) delete discoveryEnv[name];
+ const result = spawnSync('git', ['rev-parse', '--local-env-vars'], {
+ cwd: root,
+ env: discoveryEnv,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ if (result.status === 0) for (const name of result.stdout.split('\n')) delete env[name];
+ else for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_PREFIX']) delete env[name];
++ env.GIT_NO_REPLACE_OBJECTS = '1'; // Exact-tree receipts never resolve replacement refs.
return env;
}
@@@ -64,15 -39,15 +75,16 @@@
*
* @param {string} cwd
* @param {string[]} args
- * @param {{ maxBuffer?: number }} [options] - Bound output captures for callers parsing larger diffs.
- * @param {{env?: NodeJS.ProcessEnv}} [options]
++ * @param {{ maxBuffer?: number, env?: NodeJS.ProcessEnv }} [options] - Bound output captures for callers parsing larger diffs.
* @returns {string}
*/
- export function git(cwd, args, { maxBuffer } = {}) {
-export function git(cwd, args, { env = process.env } = {}) {
++export function git(cwd, args, { maxBuffer, env = process.env } = {}) {
return execFileSync('git', [...GIT_FLAGS, ...args], {
cwd,
+ env,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
+ ...(maxBuffer === undefined ? {} : { maxBuffer }),
}).trim();
}
@@@ -147,6 -124,17 +161,29 @@@ export function repoInfo(cwd, { env = p
return { root, commonDir, gitDir, isMain: commonDir === gitDir };
}
+ /** Determine code provenance without letting a caller's active hook redirect Git's repository.
+ *
+ * @param {string} [root]
+ * @returns {boolean}
+ */
+ export function codeIsFromMain(root = CODE_ROOT) {
+ const env = gitChildEnv(root);
+ const top = tryGit(root, ['rev-parse', '--show-toplevel'], { env });
- return top.status !== 0 || repoInfo(root, { env }).isMain;
++ if (top.status === 0) return repoInfo(root, { env }).isMain;
++ let folder = resolve(root);
++ while (true) {
++ try {
++ lstatSync(join(folder, '.git'));
++ throw new Refused('UNMERGED_SCHEMA', 'the running code has Git metadata that cannot be read; restore its Git link before retrying, or install a released pullboard outside this checkout');
++ } catch (error) {
++ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
++ }
++ const parent = dirname(folder);
++ if (parent === folder) return true;
++ folder = parent;
++ }
+ }
+
/**
* The full id of a commit-ish, or null when it names no commit here.
*
diff --cc src/relay-presentation.js
index 276fbe8e,00000000..96374e19
mode 100644,000000..100644
--- a/src/relay-presentation.js
+++ b/src/relay-presentation.js
@@@ -1,35 -1,0 +1,38 @@@
+/** Device-sealed presentation uses the same API state as the local view [A4,H5,H15]. */
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import * as store from './board.js';
+import { exportBoard } from './exchange.js';
- import { repoInfo } from './git.js';
++import { codeIsFromMain, repoInfo } from './git.js';
+import { Refused } from './refused.js';
+import { loadConfig } from './config.js';
+import { projectState } from './serve.js';
+
+/** Capture spec, doctrine, config and board presentation without sending plaintext to a relay. */
+export function relayPresentation(root) {
++ const info = repoInfo(root);
++ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
++ store.closeBoard(board);
+ return { version: 1, state: projectState(root), config: loadConfig(root) };
+}
+
+/** Notice presentation-only changes, including a spec or doctrine edit without a board move. */
+export function presentationDigest(presentation) {
+ return createHash('sha256').update(JSON.stringify(presentation)).digest('hex');
+}
+
+/** Capture importable native tables beside matching API presentation, retrying a concurrent local move. */
+export function relaySnapshot(root) {
+ const info = repoInfo(root);
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const before = relayPresentation(info.root);
- const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
++ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ let native;
+ try { native = exportBoard(board); } finally { store.closeBoard(board); }
+ const presentation = relayPresentation(info.root);
+ const event = native.tables.event.at(-1)?.event_id ?? 0;
+ if (event === (presentation.state.events[0]?.event_id ?? 0) &&
+ presentationDigest(before) === presentationDigest(presentation)) return { ...native, presentation };
+ }
+ throw new Refused('RELAY_SNAPSHOT_BUSY', 'the local board changed while its presentation was captured; retry the command to publish a consistent sealed checkpoint');
+}
diff --cc src/relay.js
index 61985dde,e519a30a..dfea978e
--- a/src/relay.js
+++ b/src/relay.js
@@@ -3,13 -3,10 +3,13 @@@ import { randomUUID } from 'node:crypto
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import * as store from './board.js';
-import { exportBoard } from './exchange.js';
+import { exportBoard, restoreRelaySnapshot } from './exchange.js';
+import { appliedSequence, applyEngineMove, checkpointSequence, engineReceipt, prepareEngineMove, startRelayEpoch } from './engine.js';
+import { ENGINE_VERSION } from './machine.js';
+import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';
- import { repoInfo, tryGit } from './git.js';
+ import { codeIsFromMain, repoInfo, tryGit } from './git.js';
import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
-import { encodeBoardKey, generateBoardKey, seal } from './seal.js';
+import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';
import { terminalQr } from './qr.js';
import { Refused } from './refused.js';
diff --cc src/roadmap.js
index 4ed46a27,00000000..36ec3839
mode 100644,000000..100644
--- a/src/roadmap.js
+++ b/src/roadmap.js
@@@ -1,32 -1,0 +1,32 @@@
+/** Read milestone references across the boards registered on this machine. */
+import { basename, resolve, join } from 'node:path';
+import { closeBoard, getItem, openBoard, roadmap } from './board.js';
- import { repoInfo } from './git.js';
++import { codeIsFromMain, repoInfo } from './git.js';
+import { listApiProjects } from './projects.js';
+
+/** Resolve a repo-qualified milestone item against this machine's registered boards. */
+export function milestoneRoadmap(root, board) {
+ const projects = listApiProjects();
+ const resolveExternal = (reference) => {
+ const match = /^(.+)#([1-9]\d*)$/.exec(reference);
+ if (!match) return { id: reference, title: reference, status: 'unavailable' };
+ const [, repo, number] = match;
+ const candidates = projects.filter((project) => project.name === repo || basename(project.root) === repo);
+ if (candidates.length !== 1) return { id: reference, title: `#${number} (${repo})`, status: 'unavailable' };
+ try {
+ const info = repoInfo(candidates[0].root);
+ const other = resolve(candidates[0].root) === resolve(root)
+ ? board
- : openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
++ : openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ try {
+ const item = getItem(other, Number(number));
+ return { id: reference, title: item.item_title, status: item.item_status };
+ } finally {
+ if (other !== board) closeBoard(other);
+ }
+ } catch {
+ return { id: reference, title: `#${number} (${repo})`, status: 'unavailable' };
+ }
+ };
+ return roadmap(board, resolveExternal);
+}
diff --cc test/api.test.js
index a1a9cb49,c56298e0..84987b4f
--- a/test/api.test.js
+++ b/test/api.test.js
@@@ -62,7 -63,7 +63,10 @@@ function sandbox()
GIT_COMMITTER_NAME: 'API Test',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(dir, 'home'),
++ HOME: join(dir, 'private-home'),
++ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
};
++ delete env.PULLBOARD_RELAY_TOKEN;
const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
return { dir, env, git, run };
@@@ -95,56 -96,6 +99,59 @@@ function project()
return { ...box, repo, initialized };
}
+/** Read the event-log marker without going through openBoard's version guard. */
+function readEventLogVersion(file) {
+ const db = new DatabaseSync(file);
+ try { return db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('event_log_version')?.meta_value; }
+ finally { db.close(); }
+}
+
+/** Set a private fixture's event-log marker to model another reader's persisted format. */
+function setEventLogVersion(file, version) {
+ const db = new DatabaseSync(file);
+ try {
+ db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?) ON CONFLICT(meta_key) DO UPDATE SET meta_value = excluded.meta_value')
+ .run('event_log_version', String(version));
+ } finally { db.close(); }
+}
+
+test('[A5] board opens upgrade older event logs and refuse future event logs before migration', () => {
+ const box = project();
+ const file = join(box.repo, '.git', 'pullboard', 'board.sqlite');
+ assert.equal(readEventLogVersion(file), String(EVENT_LOG_VERSION));
+
+ const future = EVENT_LOG_VERSION + 1;
+ setEventLogVersion(file, future);
+ const refused = box.run(box.repo, 'status', '--json');
+ assert.equal(refused.status, 1, refused.stderr);
+ const refusal = JSON.parse(refused.stdout).error;
+ assert.equal(refusal.code, 'EVENT_LOG_VERSION');
+ assert.match(refusal.message, new RegExp(`event log version ${future}.*version ${EVENT_LOG_VERSION}`));
+ assert.match(refusal.next, /upgrade pullboard/i);
+ assert.equal(readEventLogVersion(file), String(future), 'a future-format refusal leaves the stored version untouched');
+
+ const partialFile = join(box.dir, 'partial-future.sqlite');
+ const partial = new DatabaseSync(partialFile);
+ partial.exec("CREATE TABLE board_meta (meta_key TEXT PRIMARY KEY, meta_value TEXT NOT NULL)");
+ partial.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('event_log_version', String(future));
+ partial.close();
+ assert.throws(() => openBoard(partialFile), { code: 'EVENT_LOG_VERSION' });
+ const unchanged = new DatabaseSync(partialFile);
+ try {
+ assert.equal(unchanged.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'item'").get(), undefined,
+ 'refusing a future event log rolls back schema creation on an older database');
+ assert.equal(unchanged.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('event_log_version').meta_value, String(future));
+ } finally { unchanged.close(); }
+
+ setEventLogVersion(file, EVENT_LOG_VERSION - 1);
- const older = box.run(box.repo, 'status', '--json');
++ const release = join(box.dir, 'installed-release');
++ mkdirSync(release);
++ for (const name of ['bin', 'src', 'package.json']) cpSync(resolve(import.meta.dirname, '..', name), join(release, name), { recursive: true });
++ const older = spawnSync(process.execPath, [join(release, 'bin/pullboard.js'), 'status', '--json'], { cwd: box.repo, env: box.env, encoding: 'utf8' });
+ assert.equal(older.status, 0, older.stderr);
- assert.equal(readEventLogVersion(file), String(EVENT_LOG_VERSION), 'opening an older event log upgrades its marker in place');
++ assert.equal(readEventLogVersion(file), String(EVENT_LOG_VERSION), 'an installed release opens an older event log and upgrades its marker in place');
+});
+
/** Resolve the catalog entry for either a root command or a documented subcommand. */
function shapeFor(command, subcommand) {
const candidates = [
@@@ -208,6 -157,233 +215,236 @@@ 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', 'skills']) 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 installed = join(box.dir, 'installed-pullboard');
+ mkdirSync(installed);
+ for (const name of ['bin', 'src']) cpSync(join(sourceRoot, name), join(installed, name), { recursive: true });
+ cpSync(join(sourceRoot, 'package.json'), join(installed, 'package.json'));
+ const olderInstalled = new DatabaseSync(dbFile);
+ olderInstalled.exec('ALTER TABLE item DROP COLUMN item_files; PRAGMA user_version = 1');
+ olderInstalled.close();
+ const installedRun = spawnSync(process.execPath, [join(installed, 'bin/pullboard.js'), 'status', '--json'], {
+ cwd: repo, env: box.env, encoding: 'utf8',
+ });
+ assert.equal(installedRun.status, 0, installedRun.stderr + installedRun.stdout);
+ const migratedInstalled = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(migratedInstalled.prepare('PRAGMA user_version').get().user_version, 2,
+ 'a copied installed release without Git metadata can upgrade an older board');
+ assert.ok(migratedInstalled.prepare('PRAGMA table_info(item)').all().some((column) => column.name === 'item_files'));
+ migratedInstalled.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 olderAgain = new DatabaseSync(dbFile);
+ olderAgain.exec('ALTER TABLE item DROP COLUMN item_files; PRAGMA user_version = 1');
+ olderAgain.close();
+ const mainCodeFromWorktree = spawnSync(process.execPath, [join(repo, 'bin/pullboard.js'), 'join', 'app', '--family', 'codex', '--json'], {
+ cwd: linked, env: box.env, encoding: 'utf8',
+ });
+ assert.equal(mainCodeFromWorktree.status, 0, mainCodeFromWorktree.stderr + mainCodeFromWorktree.stdout);
+ const migratedFromWorktree = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(migratedFromWorktree.prepare('PRAGMA user_version').get().user_version, 2,
+ 'the main checkout code may upgrade its shared board even when cwd is a linked worktree');
+ assert.ok(migratedFromWorktree.prepare('PRAGMA table_info(item)').all().some((column) => column.name === 'item_files'));
+ migratedFromWorktree.close();
+
+ 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');
+
+ let before = readFileSync(dbFile);
+ const mainGitDir = box.git(repo, 'rev-parse', '--path-format=absolute', '--git-dir');
+ const linkedGitDir = box.git(linked, 'rev-parse', '--path-format=absolute', '--git-dir');
+ const commonGitDir = box.git(linked, 'rev-parse', '--path-format=absolute', '--git-common-dir');
+ const inheritedMain = {
+ ...box.env, GIT_DIR: mainGitDir, GIT_WORK_TREE: repo, GIT_COMMON_DIR: mainGitDir,
+ };
+ const inheritedLinked = {
+ ...box.env, GIT_DIR: linkedGitDir, GIT_WORK_TREE: linked, GIT_COMMON_DIR: commonGitDir,
+ };
+ const spoofedWorktree = spawnSync(process.execPath, [join(linked, 'bin/pullboard.js'), 'status', '--json'], {
+ cwd: repo, env: inheritedMain, encoding: 'utf8',
+ });
+ assert.equal(spoofedWorktree.status, 1, spoofedWorktree.stderr + spoofedWorktree.stdout);
+ assert.equal(JSON.parse(spoofedWorktree.stdout).error.code, 'UNMERGED_SCHEMA',
+ 'GIT_DIR pointing at main cannot make unmerged worktree source appear merged');
+ assert.deepEqual(readFileSync(dbFile), before, 'inherited main Git variables cannot migrate from worktree source');
+
++ const olderForHook = new DatabaseSync(dbFile);
++ olderForHook.exec('ALTER TABLE item DROP COLUMN item_files; PRAGMA user_version = 1');
++ olderForHook.close();
+ const mainFromHook = spawnSync(process.execPath, [join(repo, 'bin/pullboard.js'), 'status', '--json'], {
+ cwd: linked, env: inheritedLinked, encoding: 'utf8',
+ });
+ assert.equal(mainFromHook.status, 0, mainFromHook.stderr + mainFromHook.stdout);
+ const upgradedFromHook = new DatabaseSync(dbFile, { readOnly: true });
+ assert.equal(upgradedFromHook.prepare('PRAGMA user_version').get().user_version, 2,
+ 'main source upgrades even when a linked-worktree hook exports its Git directory');
+ upgradedFromHook.close();
+ before = readFileSync(dbFile);
+
+ const worktreeCodeFromMain = spawnSync(process.execPath, [join(linked, 'bin/pullboard.js'), 'status', '--json'], {
+ cwd: repo, env: box.env, encoding: 'utf8',
+ });
+ assert.equal(worktreeCodeFromMain.status, 1, worktreeCodeFromMain.stderr + worktreeCodeFromMain.stdout);
+ assert.equal(JSON.parse(worktreeCodeFromMain.stdout).error.code, 'UNMERGED_SCHEMA',
+ 'a future-schema worktree refuses migration even when invoked from the main checkout directory');
+ assert.deepEqual(readFileSync(dbFile), before, 'cwd cannot make worktree code migrate the shared board');
+
+ const initFromMain = spawnSync(process.execPath, [join(linked, 'bin/pullboard.js'), 'init', '--json'], {
+ cwd: repo, env: box.env, encoding: 'utf8',
+ });
+ assert.equal(initFromMain.status, 1, initFromMain.stderr + initFromMain.stdout);
+ assert.equal(JSON.parse(initFromMain.stdout).error.code, 'UNMERGED_SCHEMA',
+ 'the setup command uses the running source identity when it opens the board');
+ assert.deepEqual(readFileSync(dbFile), before, 'setup cannot migrate the shared board from unmerged code');
+
+ const envBypass = spawnSync(process.execPath, [join(linked, 'bin/pullboard.js'), 'status', '--json'], {
+ cwd: repo, env: { ...box.env, PULLBOARD_CODE_IS_MAIN: '1' }, encoding: 'utf8',
+ });
+ assert.equal(envBypass.status, 1, envBypass.stderr + envBypass.stdout);
+ assert.equal(JSON.parse(envBypass.stdout).error.code, 'UNMERGED_SCHEMA',
+ 'PULLBOARD_CODE_IS_MAIN cannot impersonate main-checkout source provenance');
+ assert.deepEqual(readFileSync(dbFile), before, 'the removed environment override cannot migrate the shared board');
+
+ const relayProbe = join(linked, '.schema-relay-probe.mjs');
+ writeFileSync(relayProbe, `
+ import { localRecords } from './src/relay.js';
+ try {
+ localRecords(process.env.PULLBOARD_FIXTURE_REPO, (board) => board.db.prepare('PRAGMA user_version').get());
+ console.log(JSON.stringify({ code: 'UNEXPECTED_OPEN' }));
+ } catch (error) {
+ console.log(JSON.stringify({ code: error.code, message: error.message }));
+ }
+ `);
+ const relayRecords = spawnSync(process.execPath, [relayProbe], {
+ cwd: repo, env: { ...box.env, PULLBOARD_FIXTURE_REPO: repo }, encoding: 'utf8',
+ });
+ assert.equal(relayRecords.status, 0, relayRecords.stderr + relayRecords.stdout);
+ const relayRefusal = JSON.parse(relayRecords.stdout);
+ assert.equal(relayRefusal.code, 'UNMERGED_SCHEMA', 'relay localRecords uses its source worktree identity even from main cwd');
+ assert.match(relayRefusal.message, /worktree expects board schema 3, newer than the shared board's version 2/);
+ assert.deepEqual(readFileSync(dbFile), before, 'relay localRecords refuses before it can migrate the shared board');
+
+ 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: true });
+ 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;
diff --cc test/machine.test.js
index 01a0e795,aca377db..31e90d84
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@@ -28,8 -28,7 +28,9 @@@ const NOT_MOVES =
ONE_COORDINATOR: 'registering who is asking, before any move',
BAD_MACHINE_SETTINGS: 'machine-wide settings checked before a command runs',
BAD_GATE_SLOTS: 'machine-wide gate capacity checked before a command runs',
+ NO_AGENT: 'a linked coordinator must already be registered before an item move',
+ EVENT_LOG_VERSION: 'the local board format is checked before opening it for an item move',
+ UNMERGED_SCHEMA: 'shared-board schema compatibility checked before a command opens the database',
};
/**
diff --cc test/shared-version.test.js
index 00000000,00000000..e302dc94
new file mode 100644
--- /dev/null
+++ b/test/shared-version.test.js
@@@ -1,0 -1,0 +1,111 @@@
++/** Unmerged source protects both shared formats, including indirect openers and real hooks [A5,A6]. */
++import assert from 'node:assert/strict';
++import { spawnSync } from 'node:child_process';
++import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
++import { tmpdir } from 'node:os';
++import { join, resolve } from 'node:path';
++import { DatabaseSync } from 'node:sqlite';
++import { test } from 'node:test';
++
++/** Copy the actual candidate into an isolated primary and linked source checkout. */
++function fixture(t) {
++ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-shared-version-')));
++ t.after(() => rmSync(dir, { recursive: true, force: true }));
++ const root = join(dir, 'repo'); const lane = join(dir, 'lane');
++ mkdirSync(root);
++ for (const name of ['bin', 'src', 'skills', 'package.json']) cpSync(resolve(import.meta.dirname, '..', name), join(root, name), { recursive: true });
++ const env = { ...process.env, HOME: join(dir, 'home'), PULLBOARD_HOME: join(dir, 'board-home'), PULLBOARD_MACHINE_HOME: join(dir, 'machine-home') };
++ for (const name of Object.keys(env)) if (name.startsWith('GIT_')) delete env[name];
++ delete env.PULLBOARD_RELAY_TOKEN;
++ Object.assign(env, { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Version Fixture', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Version Fixture', GIT_COMMITTER_EMAIL: '[email protected]' });
++ /** Execute a fixture command and retain its real status and diagnostic. */
++ const run = (cwd, program, args) => spawnSync(program, args, { cwd, env, encoding: 'utf8' });
++ /** Require a real Git operation to succeed without bypassing hooks. */
++ const git = (cwd, ...args) => { const r = run(cwd, 'git', args); assert.equal(r.status, 0, r.stderr + r.stdout); return r.stdout.trim(); };
++ /** Run source from the chosen checkout, independently of the command's working directory. */
++ const cli = (code, cwd, ...args) => run(cwd, process.execPath, [join(code, 'bin/pullboard.js'), ...args]);
++ git(root, 'init', '-q', '-b', 'main');
++ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', lanes: { core: { owns: ['src/'] } } }));
++ writeFileSync(join(root, 'SPEC.md'), '# Version fixture\n\n## G · Goals\n- G1 [approved, must] Preserve the shared board. | gate: true\n');
++ git(root, 'add', '-A'); git(root, 'commit', '-q', '-m', 'chore: initialize source fixture');
++ const initialized = cli(root, root, 'init'); assert.equal(initialized.status, 0, initialized.stderr);
++ git(root, 'add', '-A'); git(root, 'commit', '-q', '-m', 'chore: install source fixture hooks');
++ git(root, 'worktree', 'add', '-q', '-b', 'core/future', lane, 'main');
++ const joined = cli(root, lane, 'join', 'core', '--json'); assert.equal(joined.status, 0, joined.stderr + joined.stdout);
++ const file = join(root, '.git/pullboard/board.sqlite');
++ /** Run a source-level probe in a fresh process, always under the private fixture environment. */
++ const probe = (source) => { const path = join(lane, 'probe.mjs'); writeFileSync(path, source); const r = run(lane, process.execPath, [path]); assert.equal(r.status, 0, r.stderr + r.stdout); return JSON.parse(r.stdout); };
++ /** Read persistent formats without invoking a writable opener. */
++ const versions = () => { const db = new DatabaseSync(file, { readOnly: true }); try { return { schema: db.prepare('PRAGMA user_version').get().user_version, log: db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='event_log_version'").get().meta_value }; } finally { db.close(); } };
++ /** Change only one version constant in the uncommitted linked source. */
++ const bump = (name, from, to) => { const path = join(lane, 'src/board.js'); const text = readFileSync(path, 'utf8'); const updated = text.replace(`export const ${name} = ${from};`, `export const ${name} = ${to};`); assert.notEqual(updated, text); writeFileSync(path, updated); };
++ return { dir, root, lane, env, file, run, cli, git, probe, versions, bump };
++}
++
++test('an event-log-only worktree refuses upgrades and primary source still opens [A5,A6]', t => {
++ const box = fixture(t); const before = box.versions(); box.bump('EVENT_LOG_VERSION', 1, 2);
++ const r = box.cli(box.lane, box.root, 'status', '--json');
++ assert.equal(r.status, 1, r.stderr + r.stdout); const error = JSON.parse(r.stdout).error;
++ assert.equal(error.code, 'UNMERGED_SCHEMA'); assert.match(error.message, /event log 2.*version 1/);
++ assert.deepEqual(box.versions(), before);
++ const doctor = box.cli(box.lane, box.lane, 'doctor', '--json');
++ assert.equal(doctor.status, 1, doctor.stderr + doctor.stdout);
++ const finding = JSON.parse(doctor.stdout).problems.find(p => p.code === 'EVENT_LOG_VERSION');
++ assert.ok(finding); assert.match(finding.next, /merge.*main checkout.*status there/);
++ assert.deepEqual(box.versions(), before);
++ const primary = box.cli(box.root, box.lane, 'status', '--json'); assert.equal(primary.status, 0, primary.stderr + primary.stdout);
++ assert.deepEqual(box.versions(), before);
++});
++
++test('a broken Git link cannot impersonate an installed release and upgrade a board [A5,A6]', t => {
++ const box = fixture(t); const before = box.versions(); box.bump('SCHEMA_VERSION', 2, 3);
++ const broken = join(box.dir, 'broken'); mkdirSync(broken);
++ for (const name of ['bin', 'src', 'package.json']) cpSync(join(box.lane, name), join(broken, name), { recursive: true });
++ writeFileSync(join(broken, '.git'), 'gitdir: /nonexistent/pullboard-pruned-link\n');
++ const r = box.cli(broken, box.root, 'status', '--json'); assert.equal(r.status, 1, r.stderr + r.stdout);
++ assert.equal(JSON.parse(r.stdout).error.code, 'UNMERGED_SCHEMA'); assert.match(JSON.parse(r.stdout).error.next, /restore its Git link/);
++ assert.deepEqual(box.versions(), before);
++});
++
++test('a newer lane can make a real checked commit and doctor gives a working main-checkout step [A5,A6]', t => {
++ const box = fixture(t); const before = box.versions(); box.bump('SCHEMA_VERSION', 2, 3);
++ writeFileSync(join(box.lane, '.githooks/pre-commit'), `#!/bin/sh\nexec "${process.execPath}" "$(git rev-parse --show-toplevel)/bin/pullboard.js" hook pre-commit\n`);
++ box.git(box.lane, 'add', 'src/board.js'); box.git(box.lane, 'commit', '-q', '-m', 'feat: propose a future schema [G1]');
++ assert.deepEqual(box.versions(), before, 'the actual checkout hook must not migrate the shared board');
++ const r = box.cli(box.lane, box.lane, 'doctor', '--json'); assert.equal(r.status, 1, r.stderr + r.stdout);
++ const finding = JSON.parse(r.stdout).problems.find(p => p.code === 'SCHEMA_VERSION');
++ assert.ok(finding); assert.match(finding.next, /merge.*main checkout.*status there/);
++ assert.doesNotMatch(finding.next, /^run pullboard status/); assert.deepEqual(box.versions(), before);
++});
++
++test('relay snapshot guards its native board open even when presentation is already supplied [A5,A6]', t => {
++ const box = fixture(t); const before = box.versions(); box.bump('EVENT_LOG_VERSION', 1, 2);
++ const relay = join(box.lane, 'src/relay-presentation.js');
++ const original = readFileSync(relay, 'utf8');
++ const supplied = original.replace(/export function relayPresentation\(root\) \{[\s\S]*?\n\}/u,
++ 'export function relayPresentation() { return {version:1,state:{events:[]}}; }');
++ assert.notEqual(supplied, original, 'supply presentation without replacing the actual snapshot opener');
++ writeFileSync(relay, supplied);
++ const result = box.probe(`import { relaySnapshot } from './src/relay-presentation.js'; try { relaySnapshot(${JSON.stringify(box.root)}); console.log(JSON.stringify({code:'OPENED'})); } catch(e) { console.log(JSON.stringify({code:e.code})); }`);
++ assert.equal(result.code, 'UNMERGED_SCHEMA'); assert.deepEqual(box.versions(), before);
++});
++
++test('relay presentation refuses before asking the view projection to open a newer board [A5,A6]', t => {
++ const box = fixture(t); const before = box.versions(); box.bump('EVENT_LOG_VERSION', 1, 2);
++ const result = box.probe(`import { relayPresentation } from './src/relay-presentation.js'; try { relayPresentation(${JSON.stringify(box.root)}); console.log(JSON.stringify({code:'OPENED'})); } catch(e) { console.log(JSON.stringify({code:e.code})); }`);
++ assert.equal(result.code, 'UNMERGED_SCHEMA'); assert.deepEqual(box.versions(), before);
++});
++
++test('a roadmap external-board open refuses unmerged event-log source [A5,A6]', t => {
++ const box = fixture(t); const before = box.versions(); box.bump('EVENT_LOG_VERSION', 1, 2);
++ const result = box.probe(`
++ import { openBoard, closeBoard, addMilestone } from './src/board.js';
++ import { registerProject } from './src/projects.js';
++ import { milestoneRoadmap } from './src/roadmap.js';
++ registerProject(${JSON.stringify(box.root)}, new Date(), {name:'external'});
++ const board = openBoard(':memory:');
++ addMilestone(board, {agentId:'coordinator',name:'External',items:['repo#1']});
++ try { console.log(JSON.stringify(milestoneRoadmap(${JSON.stringify(box.lane)}, board))); } finally {closeBoard(board);}
++ `);
++ assert.equal(result[0].items[0].status, 'unavailable'); assert.deepEqual(box.versions(), before);
++});