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(core): integrate shared format migration guards [A5,A6]

Corey Olson1b791454d64e
diff --cc src/api.js
index 9ab6aeae,94cf85b8..f1b53169
--- a/src/api.js
+++ b/src/api.js
@@@ -2,12 -2,11 +2,12 @@@
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
import { join } from 'node:path';
+import { displayAgentName } from './agent-names.js';
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 { relayLinked, relayOperation, relayRevoke, relayTokens } from './relay.js';
import { laneNames } from './lanes.js';
import { listApiProjects } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
@@@ -83,11 -82,65 +88,11 @@@ function agentPath(root, name = COORDIN
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. */
-const MOVES = {
- 'spec-approve': { prefix: ['spec', 'approve'], positions: ['ids'], flags: ['by', 'text'] },
- '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'] },
- claim: { item: true },
- release: { item: true },
- submit: { item: true },
- done: { item: true },
- verify: { item: true, positions: ['decision'], flags: ['reason', 'note', 'as'] },
- merged: { item: true, positions: ['commit'] },
- withdraw: { item: true, positions: ['reason'] },
- refreeze: { item: true },
- escalate: { item: true, flags: ['note'] },
- hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },
- shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },
- answer: { item: true, positions: ['text'], flags: ['as'] },
- pass: { item: true, positions: ['note'] },
- next: { flags: ['as'], booleans: ['verify', 'build'] },
-};
-
-/** Reject unsupported fields, then pass values as distinct argv entries, never a shell command. */
-export function moveArgs({ verb, item, args = {} }) {
- if (verb === 'accept' || verb === 'reject') return moveArgs({ verb: 'verify', item, args: { ...args, decision: verb } });
- const form = Object.hasOwn(MOVES, verb) ? MOVES[verb] : null;
- if (!form) throw new Refused('BAD_REQUEST', `no API move ${String(verb)}; use a board move such as add, claim, submit, verify, shout or answer`);
- if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Refused('BAD_REQUEST', 'args needs a JSON object containing this move\'s arguments');
- const allowed = [...(form.positions ?? []), ...(form.flags ?? []), ...(form.booleans ?? [])];
- for (const key of Object.keys(args)) if (!allowed.includes(key)) throw new Refused('BAD_REQUEST', `${verb} does not take args.${key}; use only this CLI move's arguments`);
- const argv = form.prefix ? [...form.prefix] : [verb];
- if (form.item) {
- if (!Number.isSafeInteger(item) || item < 1) throw new Refused('BAD_REQUEST', `${verb} needs a positive integer item; use the item id from the board state`);
- argv.push(String(item));
- } else if (item !== undefined && item !== null) throw new Refused('BAD_REQUEST', `${verb} does not take item; put its arguments in args`);
- const positional = [];
- for (const key of form.positions ?? []) {
- if (args[key] === undefined && form.optional?.includes(key)) continue;
- if (typeof args[key] !== 'string' || !args[key].trim()) throw new Refused('BAD_REQUEST', `${verb} needs args.${key} as nonempty text; supply the CLI move's argument`);
- positional.push(args[key]);
- }
- for (const key of form.flags ?? []) if (args[key] !== undefined) {
- if (typeof args[key] !== 'string') throw new Refused('BAD_REQUEST', `args.${key} needs text; supply the CLI flag's value`);
- argv.push(`--${key}=${args[key]}`);
- }
- for (const key of form.booleans ?? []) if (args[key] !== undefined) {
- if (typeof args[key] !== 'boolean') throw new Refused('BAD_REQUEST', `args.${key} needs true or false`);
- if (args[key]) argv.push(`--${key}`);
- }
- // Positionals follow -- so titles and notes beginning with a dash never become CLI flags.
- argv.push('--json', '--', ...positional);
- return argv;
-}
-
/** Execute one actual CLI command and retain its emitted event without a latest-row race. */
- export async function executeMove(root, body, runCommand) {
-async function executeMove(root, body, runCommand, isMain) {
++export 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;
@@@ -148,48 -202,26 +154,48 @@@ 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 });
+ let state = projectState(board.root, { seen, isMain: codeIsMain });
+ const config = loadConfig(board.root);
+ state.agents = state.agents.map((agent) => ({
+ ...agent,
+ model: agent.agent_model ?? 'unknown',
+ displayName: displayAgentName(agent, config.agents.names),
+ }));
state.board = board.id;
const projectData = withBoard(board.root, (db) => ({
requests: store.openRequests(db),
+ personRequests: personRequestStatuses(db),
milestones: milestoneRoadmap(board.root, db),
rowDecisions: store.rowDecisions(db),
+ checks: new Map(store.listItems(db, { all: true }).map((item) => store.getItem(db, item.item_id)).map((item) => [item.item_id, {
+ check: item.item_check,
+ ...(item.item_check_baseline ? { checkBaseline: item.item_check_baseline } : {}),
+ }])),
+ proofStats: proofStats(db),
+ threads: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, store.itemThread(db, item.item_id)])),
- }));
+ }), codeIsMain);
+ state.proofStats = projectData.proofStats;
state.requests = projectData.requests;
+ state.personRequests = projectData.personRequests;
state.milestones = projectData.milestones;
+ state.items = state.items.map((item) => ({ ...item, ...projectData.checks.get(item.id) }));
state = projectRowDecisions(projectData.rowDecisions, state);
+ state.items = state.items.map((item) => ({ ...item, thread: projectData.threads.get(item.id) ?? [] }));
return state;
},
+ shout: (board, id) => relayLinked(board.root)
+ ? relayPresentationShout(board.root, id)
- : withBoard(board.root, (db) => store.shoutDetails(db, id)),
++ : withBoard(board.root, (db) => store.shoutDetails(db, id), codeIsMain),
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),
+ tokens: async (board) => (await relayTokens(board.root, { err() {} })).tokens,
+ revokeToken: (board, id) => relayRevoke(board.root, id, { personChannel: 'view', say() {}, err() {} }),
});
}
diff --cc src/board.js
index f9a876c8,a2ad59f9..73d4928d
--- a/src/board.js
+++ b/src/board.js
@@@ -6,8 -6,8 +6,8 @@@
* every move lands in an append-only event log (R2). The caller supplies what only git and the
* spec know: the commit, the verifier's checkout, the frozen criterion.
*/
-import { randomBytes } from 'node:crypto';
+import { randomBytes, randomUUID } 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';
diff --cc src/check-baseline-worker.js
index 55984ad8,00000000..5cd5bf1c
mode 100644,000000..100644
--- a/src/check-baseline-worker.js
+++ b/src/check-baseline-worker.js
@@@ -1,96 -1,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 { codeIsFromMain, 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);
++ const board = store.openBoard(locations(root).board, undefined, { isMain: codeIsFromMain() });
+ 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 --cc src/cli.js
index 2c35242a,c86f10da..07b279a6
--- a/src/cli.js
+++ b/src/cli.js
@@@ -8,15 -8,14 +8,16 @@@ 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 { CONFIG_FILE, COORDINATOR, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';
+import { displayAgentName } from './agent-names.js';
+import { doctrineHistory, loadDoctrine } from './doctrine.js';
+import { agentSessionDigest, requirePersonChannel } from './person.js';
+import { bindLocalSession } from './agent-session.js';
import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
-import { digestOf, gateReport, runGate, runShell } from './gate.js';
-import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';
+import { digestOf, gateReport, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';
- import { bareWorktreeFinding, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';
++import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';
import {
FIX_NOTE,
applyFixers,
@@@ -1179,7 -962,7 +1181,7 @@@ async function viewHere(io, values)
}
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 });
++ const view = await serveView({ port, isMain: codeIsFromMain() });
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.');
@@@ -1200,10 -983,10 +1202,10 @@@
async function serveHere(io, values) {
const ctx = context(io);
const mainRoot = git(ctx.info.root, ['worktree', 'list', '--porcelain']).split('\n')[0].slice('worktree '.length);
- registerProject(mainRoot, new Date(), loadConfig(mainRoot));
+ await registerProjectAndLink(mainRoot, new Date(), loadConfig(mainRoot), io);
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.allowSchemaUpgrade });
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.');
@@@ -1226,19 -1009,14 +1228,19 @@@
*/
function setupCommands(io, { first, values }) {
return {
- init: () => {
+ init: async () => {
const info = repoInfo(io.cwd);
+ const model = optionalModel(values.model);
+ const linked = relayLinked(info.root);
+ const ctx = linked && model !== undefined ? context(io) : null;
+ if (model !== undefined && linked) refuseRemoteCoordinatorModel(ctx, 'init');
const notes = initRepo({
info,
+ model,
- openBoardHere: () => store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), io.clock),
+ openBoardHere: () => store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), io.clock, { isMain: codeIsFromMain() }),
/** 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 (!linked) 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');
}
@@@ -1600,13 -1308,7 +1602,13 @@@ function readCommands(io, { first, seco
return 1;
}
const ctx = context(io);
- const problems = [...doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config), ...skillProblems(ctx.info.root), ...doctrineProblems(ctx.info.root, ctx.config), ...unlinkedRelayProjects()];
- const problems = doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config, { isMain: ctx.allowSchemaUpgrade });
++ const problems = [...doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config, { isMain: ctx.allowSchemaUpgrade }), ...skillProblems(ctx.info.root), ...doctrineProblems(ctx.info.root, ctx.config), ...unlinkedRelayProjects()];
+ const checkpointProblem = pendingCheckpointProblem(ctx.info.root);
+ if (checkpointProblem) problems.push(checkpointProblem);
+ const oversizedSnapshot = checkpointProblem ? null : pendingSnapshotSize(ctx.info.root);
+ if (oversizedSnapshot) problems.push({ code: 'RELAY_SNAPSHOT_LIMIT',
+ message: formatSnapshotLimit(oversizedSnapshot),
+ next: 'reduce the sealed board snapshot below the relay limit, then run pullboard status' });
io.result?.({ problems });
if (!problems.length) {
io.say('board is clean');
@@@ -2463,28 -1933,16 +2465,28 @@@ function settingsCommand(io, { first, s
}
/**
- * 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.
+ * 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
++ * on the board, open or closed. The connection is read-only: spec lint never migrates a shared board. 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).
*
* @param {any} ctx
- * @param {{ since: string | null }} history - this checkout's spec history.
- * @returns {Map<string, string>} Each id cited by a commit header.
+ * @param {{ ids: Map<string, string>, since: string | null }} history - this checkout's.
+ * @returns {Map<string, string>} Each id, with who cites it.
*/
-function citations(ctx, { since }) {
- return since ? commitCitations(ctx.info.root, since) : new Map();
+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 item of hookRead(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;
}
/** Current board evidence, with each item's accepting receipts included once. */
@@@ -2737,6 -2152,14 +2739,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) {
++/** Read hook identity and landing facts without migrating the shared board from newer source. */
++function hookRead(ctx, read) {
+ if (!existsSync(ctx.file)) return null;
+ const db = new DatabaseSync(ctx.file, { readOnly: true });
- try { return store.agentAt({ db }, ctx.info.root); }
++ try { return read({ db }); }
+ finally { db.close(); }
+ }
+
/**
* The hooks git runs. In a repo without pullboard.json they pass, so a stray hook never blocks.
*
@@@ -2754,34 -2177,22 +2764,34 @@@ async function hookCommand(io, { first
throw error;
}
let problems = [];
- if (first === 'pre-commit') {
+ if (first === 'pre-commit' || first === 'pre-merge-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));
- const landing = withBoard(ctx, (board) => store.landingBatches(board).some((batch) => batch.root === info.root && !['landed', 'blocked'].includes(batch.state)));
- const agent = info.isMain ? null : hookAgent(ctx);
- problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent, boardFile: ctx.file });
++ const agent = info.isMain ? null : hookRead(ctx, (board) => store.agentAt(board, info.root));
++ const landing = hookRead(ctx, (board) => store.landingBatches(board).some((batch) => batch.root === info.root && !['landed', 'blocked'].includes(batch.state)));
+ problems = preCommitProblems({ root: info.root, isMain: info.isMain || landing, 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) });
+ const spec = loadSpec(info.root, ctx.config);
+ commitCitationWarnings(message, { spec, doctrine: ctx.doctrine })
+ .forEach((warning) => io.say(`pullboard commit-msg: warning: ${warning}`));
+ problems = commitMsgProblems(message, { rules: ctx.config.commits, spec, doctrine: ctx.doctrine });
} else if (first === 'pre-push') {
- problems = prePushProblems(info.root, await readStdin(io.stdin));
+ const refsText = await readStdin(io.stdin);
+ problems = prePushProblems(info.root, refsText);
if (!problems.length) {
- const gate = await runGate(info.root, ctx.config, { onWait: gateWaitReporter(io) });
- if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');
- if (!gate.isGreen) problems = [`the gate is red; fix it before pushing. ${gateReport(gate)}`];
+ const landing = pushesTrunk(refsText, trunkRef(info.root));
+ const waived = landing && withBoard(ctx, (board) => store.waivedLandingProof(board, headTree(info.root)));
+ const recordedException = landing && withBoard(ctx, (board) => store.landingBatches(board).some((batch) => batch.proof?.tree === headTree(info.root) && batch.proof.failures?.length));
+ if (waived && isClean(info.root) && !untracked(info.root).length) io.say(`pre-push: exact landing tree covered by live person waivers in batch ${waived.id}; no ordinary green stamp`);
+ else if (recordedException) problems = ['the landing proof has an expired or missing person waiver; ask the person for a new expiring waiver'];
+ else {
+ const gate = await runGate(info.root, ctx.config, { landing, onWait: gateWaitReporter(io) });
+ if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');
+ if (!gate.isGreen) problems = [`the gate is red; fix it before pushing. ${gateReport(gate)}`];
+ }
}
} else {
- throw new Refused('USAGE', 'pullboard hook pre-commit | commit-msg <file> | pre-push');
+ throw new Refused('USAGE', 'pullboard hook pre-commit | pre-merge-commit | commit-msg <file> | pre-push');
}
if (!problems.length) return 0;
io.err(`pullboard ${first}: blocked\n${problems.map((problem) => ` - ${problem}`).join('\n')}\n${FIX_NOTE}`);
diff --cc src/doctor.js
index 4554ca00,25d47176..cc2b035d
--- a/src/doctor.js
+++ b/src/doctor.js
@@@ -7,21 -4,11 +7,21 @@@ import { DatabaseSync } from 'node:sqli
import { checkAtCommit, submissionPaths, dependencySnapshots } from './trusted-policy.js';
import { BLANKS, STATES, storeTriggers } from './machine.js';
- import { readEventLogVersion, 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';
+import { loadDoctrine } from './doctrine.js';
+import { preMergeHookProblems, unwiredHookProblems } from './hooks.js';
const blankCharacters = new Set(BLANKS.map((point) => String.fromCodePoint(point)));
+/** Offer a working tracked or untracked rename without rewriting the repo's doctrine [D1,D2]. */
+export function doctrineProblems(root, config) {
+ if (config.practice !== LEGACY_DOCTRINE_FILE || !existsSync(join(root, LEGACY_DOCTRINE_FILE))) return [];
+ const tracked = tryGit(root, ['ls-files', '--error-unmatch', '--', LEGACY_DOCTRINE_FILE]).status === 0;
+ const command = tracked ? 'git mv' : 'mv';
+ return [finding('DOCTRINE_LEGACY', `${LEGACY_DOCTRINE_FILE} is the legacy name for the repo doctrine`, `${command} -- ${LEGACY_DOCTRINE_FILE} ${DOCTRINE_FILE}`)];
+}
+
/**
* Check a board and its git pins without opening it through the migrator, which repairs boards on
* open. `doctor` must report the evidence it sees and leave that evidence untouched.
@@@ -45,8 -41,7 +54,9 @@@ export function doctorProblems(file, ro
}
const layout = layoutProblems(db);
return [
+ ...preMergeHookProblems(root),
+ ...unwiredHookProblems(root),
+ ...eventProblems,
...triggerProblems(db),
...layout.problems,
...(layout.itemFields ? itemProblems(db) : []),
diff --cc src/git.js
index ed286af9,ae1aab4e..0c5d0a3b
--- a/src/git.js
+++ b/src/git.js
@@@ -1,11 -1,11 +1,12 @@@
/**
* The few git facts pullboard needs: where the repo is, which worktree this is, what HEAD holds,
- * and whether the tree is clean. Every call is a plain `git` child process.
+ * and whether the tree is clean (R3). Every call is a plain `git` child process.
*/
import { execFileSync, spawnSync } from 'node:child_process';
-import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs';
+import { AsyncLocalStorage } from 'node:async_hooks';
- import { existsSync, readdirSync, statSync } from 'node:fs';
++import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
+ import { fileURLToPath } from 'node:url';
import { Refused } from './refused.js';
const GIT_FLAGS = ['--no-replace-objects', '-c', 'core.quotepath=false'];
@@@ -139,20 -75,17 +150,21 @@@ export function gitChildEnv(root)
*
* @param {string} cwd
* @param {string[]} args
- * @param {{ maxBuffer?: number }} [options] - Bound output captures for callers parsing larger diffs.
+ * @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, { maxBuffer, env = process.env } = {}) {
- return execFileSync('git', [...GIT_FLAGS, ...args], {
- cwd,
- env,
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'pipe'],
- ...(maxBuffer === undefined ? {} : { maxBuffer }),
- }).trim();
+ try {
+ return execFileSync('git', [...GIT_FLAGS, ...args], {
+ cwd,
++ env,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ ...(maxBuffer === undefined ? {} : { maxBuffer }),
+ }).trim();
+ } finally {
+ if (changesGitFacts(args)) invalidateGitFacts();
+ }
}
/**
@@@ -160,28 -93,12 +172,28 @@@
*
* @param {string} cwd
* @param {string[]} args
- * @param {{env?: NodeJS.ProcessEnv}} [options]
- * @returns {{ status: number, stdout: string }}
+ * @returns {{ status: number, stdout: string, stderr: string }}
*/
- export function tryGit(cwd, args) {
- const result = spawnSync('git', [...GIT_FLAGS, ...args], { cwd, encoding: 'utf8' });
+ export function tryGit(cwd, args, { env = process.env } = {}) {
+ const result = spawnSync('git', [...GIT_FLAGS, ...args], { cwd, env, encoding: 'utf8' });
- return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim() };
+ if (changesGitFacts(args)) invalidateGitFacts();
+ return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim(), stderr: (result.stderr ?? '').trim() };
+}
+
+/**
+ * Compute the stable patch id for a commit range, or null when Git cannot produce one.
+ *
+ * @param {string} root
+ * @param {string} base
+ * @param {string} commit
+ * @returns {string | null}
+ */
+export function patchId(root, base, commit) {
+ const env = cleanGitEnvironment();
+ const diff = spawnSync('git', [...GIT_FLAGS, 'diff', base, commit], { cwd: root, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
+ if (diff.status !== 0 || !diff.stdout) return null;
+ const result = spawnSync('git', [...GIT_FLAGS, 'patch-id', '--stable'], { cwd: root, env, encoding: 'utf8', input: diff.stdout });
+ return result.status === 0 ? result.stdout.trim().split(/\s+/u)[0] || null : null;
}
/**
@@@ -228,27 -145,43 +240,52 @@@ export function bareWorktreeFinding(cwd
* The main checkout's git dir is the common dir; a linked worktree has its own under it.
*
* @param {string} cwd
+ * @param {{env?: NodeJS.ProcessEnv}} [options]
* @returns {{ root: string, commonDir: string, gitDir: string, isMain: boolean }}
*/
- export function repoInfo(cwd) {
-export function repoInfo(cwd, { env = process.env } = {}) {
- const top = tryGit(cwd, ['rev-parse', '--show-toplevel'], { env });
- if (top.status !== 0) {
++export function repoInfo(cwd, { env } = {}) {
++ if (env) return readRepoInfo(cwd, env);
+ return fact(`repoInfo:${resolve(cwd)}`, () => readRepoInfo(cwd));
+}
+
+/** Read top level, worktree Git dir and shared Git dir in one process.
+ *
+ * @param {string} cwd
+ * @returns {{ root: string, commonDir: string, gitDir: string, isMain: boolean }}
+ */
- function readRepoInfo(cwd) {
- const info = tryGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir']);
++function readRepoInfo(cwd, env) {
++ const info = tryGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'], { env });
+ const fields = info.stdout.split('\n');
+ if (info.status !== 0 || fields.length !== 3 || fields.some((field) => !field)) {
const bare = bareWorktreeFinding(cwd);
if (bare) throw new Refused(bare.code, `${bare.message}; run ${bare.next}`);
throw new Refused('NOT_A_REPO', 'not inside a git work tree; run git init, or cd into a repo');
}
- const root = top.stdout;
- const commonDir = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir'], { env });
- const gitDir = git(root, ['rev-parse', '--path-format=absolute', '--git-dir'], { env });
- return { root, commonDir, gitDir, isMain: commonDir === gitDir };
+ const [root, gitDir, commonDir] = fields;
- return { root, commonDir, gitDir, isMain: commonDir === gitDir };
++ return { root, commonDir, gitDir, isMain: realpathSync.native(commonDir) === realpathSync.native(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 });
+ 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;
+ }
}
/**
diff --cc src/json.js
index da404bbf,cf1738cb..bf96d6b8
--- a/src/json.js
+++ b/src/json.js
@@@ -100,7 -92,7 +100,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|reject|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);
++ const match = /(?:; |\. |: )((?:run|install|upgrade|fix|restore|commit|merge|test|check out|set|give|use|reject|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 --cc src/relay-pairing-client.js
index 9b294f4a,00000000..a90d5395
mode 100644,000000..100644
--- a/src/relay-pairing-client.js
+++ b/src/relay-pairing-client.js
@@@ -1,234 -1,0 +1,234 @@@
+/** CLI pairing flow: the relay stores only a one-use client-encrypted package [H15,H17]. */
+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, importBoard } from './exchange.js';
- import { repoInfo } from './git.js';
++import { codeIsFromMain, repoInfo } from './git.js';
+import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
+import { encodeBoardKey } from './seal.js';
+import { createPairingCode, openPairingBundle, parsePairingCode, sealPairingBundle } from './pairing.js';
+import { terminalQr } from './qr.js';
+import { DEFAULT_RELAY, originRepository, relayStatus, syncRelay } from './relay.js';
+import { ENGINE_VERSION } from './machine.js';
+import { Refused } from './refused.js';
+import { requirePersonChannel } from './person.js';
+import { updateRelayMachine } from './relay-machine.js';
+
+const TOKEN = /^pm_[A-Za-z0-9_-]{43}$/;
+const BOARD = /^[0-9a-f]{32}$/;
+const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
+
+/** Restrict pairing traffic to a trusted HTTPS origin or a loopback test relay. */
+function relayOrigin(address) {
+ let url;
+ try { url = new URL(address); } catch { throw new Refused('RELAY_URL', 'use an HTTPS relay address, such as https://app.pullboard.dev'); }
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {
+ throw new Refused('RELAY_URL', 'use an HTTPS relay origin without credentials, path, query or fragment; loopback HTTP is for local testing');
+ }
+ return url.origin;
+}
+
+/** Locate the private link metadata shared by this repository's worktrees. */
+function linkFile(root) {
+ return join(repoInfo(root).commonDir, 'pullboard', 'relay.json');
+}
+
+/** Load and validate relay state before it supplies a destination or credential. */
+function loadState(file) {
+ if (!existsSync(file)) throw new Refused('RELAY_NOT_LINKED', 'link this board with pullboard relay on before pairing a device');
+ const stat = lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_STORAGE', 'restore relay.json as an owner-only regular file with mode 600');
+ let state;
+ try { state = JSON.parse(readFileSync(file, 'utf8')); } catch { throw new Refused('RELAY_STORAGE', 'restore valid relay link metadata before pairing this board'); }
+ if (!state || state.version !== 1 || !BOARD.test(state.board) || !TOKEN.test(state.token) ||
+ typeof state.repository !== 'string' || !REPOSITORY.test(state.repository) ||
+ (state.mode !== undefined && !['mirror', 'ordered'].includes(state.mode)) ||
+ !Number.isSafeInteger(state.sequence) || state.sequence < 0 || !Number.isSafeInteger(state.cursor) || state.cursor < 0) {
+ throw new Refused('RELAY_STORAGE', 'restore supported relay link metadata before pairing this board');
+ }
+ relayOrigin(state.url);
+ return state;
+}
+
+/** Persist a joined-device link with owner-only permissions and atomic replacement. */
+function saveState(file, state) {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ const temporary = file + '.' + randomUUID() + '.tmp';
+ try {
+ writeFileSync(temporary, JSON.stringify(state) + '\n', { flag: 'wx', mode: 0o600 });
+ renameSync(temporary, file);
+ } finally { rmSync(temporary, { force: true }); }
+}
+
+/** Send one authenticated, bounded JSON request without including credentials in errors. */
+async function relayRequest(url, token, path, body) {
+ let response;
+ try {
+ response = await fetch(new URL(path, url), {
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body: JSON.stringify(body),
+ });
+ } catch { throw new Refused('RELAY_UNAVAILABLE', 'the relay did not answer; retry pairing with the same code before it expires'); }
+ let document;
+ try { document = await response.json(); } catch { throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid pairing response; ask for a fresh code'); }
+ if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', document.error?.message || 'the relay refused pairing; ask the linked device for a fresh code');
+ if (document.version !== 1) throw new Refused('RELAY_VERSION', 'the relay pairing API version is unsupported; upgrade Pullboard before pairing');
+ return document;
+}
+
+/** Sign this device into the relay so its person session can fetch the encrypted package. */
+async function signIn(url, io) {
+ const start = await relayRequest(url, '', '/auth/device/start', {});
+ io.stderr.write(`Sign in with GitHub: open ${start.verificationURL} and enter ${start.userCode}\n`);
+ const deadline = Date.now() + start.expiresIn * 1000;
+ let wait = start.interval;
+ while (true) {
+ await new Promise((resolve) => setTimeout(resolve, Math.max(1, wait) * 1000));
+ if (Date.now() >= deadline) throw new Refused('OAUTH_EXPIRED', 'GitHub device sign-in expired; run pullboard relay join again with a fresh code');
+ const result = await relayRequest(url, '', '/auth/device/poll', { ticket: start.ticket });
+ if (!result.pending) {
+ if (!/^ps_[A-Za-z0-9_-]{43}$/.test(result.token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');
+ return result;
+ }
+ wait = result.retryAfter ?? start.interval;
+ }
+}
+
+/** Return an exported local board with its persistent identity. */
+function localSnapshot(root) {
+ const info = repoInfo(root);
- const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
++ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ try { return { board: store.boardId(board), snapshot: exportBoard(board) }; }
+ finally { store.closeBoard(board); }
+}
+
+/** Create a one-use code and publish only an encrypted board package to the relay. */
+export async function relayPair(root, io) {
+ await syncRelay(root, io);
+ const file = linkFile(root);
+ const state = loadState(file);
+ if (state.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish unlinking this board before creating a pairing code');
+ if (originRepository(root) !== state.repository) throw new Refused('RELAY_ORIGIN', 'the origin repository no longer matches this relay link; restore the linked GitHub origin first');
+ const local = localSnapshot(root);
+ if (local.board !== state.board) throw new Refused('RELAY_STORAGE', 'the local board identity differs from its relay link; restore the matching board before pairing');
+ const cursor = local.snapshot.tables.event.at(-1)?.event_id ?? 0;
+ if (cursor !== state.cursor) throw new Refused('PAIR_BUSY', 'a local move changed during pairing; run pullboard relay pair again after sync completes');
+ if (state.pending || state.pendingMove || state.snapshot || state.linkPending) {
+ throw new Refused('PAIR_PENDING', 'finish the pending relay acknowledgement or snapshot before creating a pairing code; retry relay sync first');
+ }
+ const metadata = new Map(local.snapshot.tables.board_meta.map((row) => [row.meta_key, row.meta_value]));
+ const applied = metadata.get('relay_applied_sequence');
+ const engine = metadata.get('relay_engine_version');
+ const ordered = state.mode === 'ordered' || (applied !== undefined && engine !== undefined);
+ let sequence = state.sequence;
+ if (ordered) {
+ const value = Number(applied);
+ if (engine !== String(ENGINE_VERSION) || !Number.isSafeInteger(value) || value < 0 || String(value) !== applied || value !== state.sequence) {
+ throw new Refused('PAIR_STATE', 'the ordered relay checkpoint does not match its acknowledged sequence; sync this device before pairing');
+ }
+ sequence = value;
+ }
+ const key = readBoardKey(state.board);
+ const bundle = {
+ version: 1, board: state.board, url: state.url, repository: state.repository,
+ mode: ordered ? 'ordered' : 'mirror', sequence, cursor, key: encodeBoardKey(key), snapshot: local.snapshot,
+ };
+ const code = createPairingCode(state.board);
+ const sealed = await sealPairingBundle(code.code, bundle);
+ const response = await relayRequest(state.url, state.token,
+ `/api/v1/pairings/${code.board}/${code.locator}`, { sealed });
+ const viewLink = relayStatus(root).link;
+ io.result?.({ code: code.code, link: viewLink, expiresIn: response.expiresIn });
+ io.say(`One-time code (10 minutes, one use): ${code.code}`);
+ io.say(`Phone link: ${viewLink}`);
+ io.say(terminalQr(viewLink));
+ return 0;
+}
+
+/** Refuse a nonempty target board before spending its one-use code. */
+function requireFreshTarget(root) {
+ const local = localSnapshot(root);
+ const tables = local.snapshot.tables;
+ const nonempty = Object.entries(tables).filter(([name, rows]) => !['board_meta', 'agent', 'event', 'sqlite_sequence'].includes(name) && rows.length);
+ const meta = tables.board_meta;
+ const metadata = new Map(meta.map((row) => [row.meta_key, row.meta_value]));
+ const agents = tables.agent;
+ const events = tables.event;
+ const sequence = tables.sqlite_sequence;
+ let initialDetail = false;
+ try {
+ const detail = JSON.parse(events[0]?.event_detail);
+ // Init has no declared model; engine 8 records that absence explicitly.
+ if (detail.model === undefined || detail.model === 'unknown') {
+ delete detail.model;
+ initialDetail = JSON.stringify(detail) === JSON.stringify({ lane: 'coordinator' });
+ }
+ }
+ catch { /* A non-init history cannot be safely replaced by a paired snapshot. */ }
+ if (meta.length !== 2 || !BOARD.test(metadata.get('board_id') ?? '') ||
+ metadata.get('event_log_version') !== String(store.EVENT_LOG_VERSION) ||
+ agents.length !== 1 || agents[0].agent_id !== 'coordinator' || agents[0].agent_lane !== 'coordinator' ||
+ agents[0].agent_route !== 'strong' || agents[0].agent_last_shout_id !== 0 || !agents[0].agent_path ||
+ events.length !== 1 || events[0].event_by !== 'coordinator' || events[0].event_kind !== 'join' ||
+ events[0].item_id !== null || !initialDetail || sequence.length !== 1 || sequence[0].name !== 'event' ||
+ sequence[0].seq !== 1 || nonempty.length) {
+ throw new Refused('IMPORT_NOT_EMPTY', 'pair into a freshly initialized clone with no board work; preserve this board and use another clone');
+ }
+}
+
+/** Refuse to overwrite an unrelated device key under the same persistent board id. */
+function requireMissingKey(board) {
+ try {
+ readBoardKey(board);
+ throw new Refused('RELAY_KEY_EXISTS', 'this clone already has a key for that board; preserve it and use a fresh device home');
+ } catch (error) {
+ if (error.code !== 'RELAY_KEY_MISSING') throw error;
+ }
+}
+
+/** Consume a printed one-time code, restore the board and save this device's own link. */
+export async function relayJoin(root, code, address, io) {
+ requirePersonChannel(io.personChannel);
+ const parsed = parsePairingCode(code);
+ const url = relayOrigin(address || DEFAULT_RELAY);
+ requireFreshTarget(root);
+ requireMissingKey(parsed.board);
+ const repository = originRepository(root);
+ const signed = await signIn(url, io);
+ const response = await relayRequest(url, signed.token,
+ `/api/v1/pairings/${parsed.board}/${parsed.locator}/consume`, {});
+ const bundle = await openPairingBundle(code, response.sealed);
+ if (bundle.repository !== repository) throw new Refused('PAIR_REPOSITORY', 'this code belongs to another GitHub repository and was consumed; ask the linked device for a fresh code, then join inside the matching clone');
+ if (new URL(bundle.url).origin !== new URL(url).origin) throw new Refused('PAIR_RELAY', 'this code belongs to another relay; rerun join with that relay address');
+ const file = linkFile(root);
+ if (existsSync(file)) throw new Refused('RELAY_LINKED', 'this clone already has relay link metadata; use a fresh clone to join another device');
+ const machine = updateRelayMachine(state => state.machine);
+ const issued = await relayRequest(url, signed.token, '/auth/machines', { board: bundle.board, machine });
+ if (!TOKEN.test(issued.token) || issued.board !== bundle.board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this joined board’s machine credential; pair again');
+ let keyStorage;
+ try {
+ keyStorage = storeBoardKey(bundle.board, Buffer.from(bundle.key, 'base64url'));
+ const info = repoInfo(root);
- const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
++ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ try { importBoard(board, bundle.snapshot); }
+ finally { store.closeBoard(board); }
+ saveState(file, {
+ version: 1, board: bundle.board, url: bundle.url, repository: bundle.repository,
+ mode: bundle.mode,
+ token: issued.token, tokenId: issued.id, machine, account: signed.user.id, keyStorage,
+ sequence: bundle.sequence, cursor: bundle.cursor,
+ });
+ } catch (error) {
+ if (keyStorage) {
+ try { forgetBoardKey(bundle.board, keyStorage); } catch { /* Keep the original refusal as the useful next step. */ }
+ }
+ throw error;
+ }
+ await syncRelay(root, io);
+ const result = { linked: true, board: bundle.board, url: bundle.url, sequence: bundle.sequence, behind: 0 };
+ io.result?.(result);
+ io.say(`paired board ${bundle.board}; run pullboard status to read it`);
+ return 0;
+}
diff --cc src/relay-presentation.js
index e1dbc5ec,96374e19..b89ed310
--- a/src/relay-presentation.js
+++ b/src/relay-presentation.js
@@@ -7,28 -7,13 +7,29 @@@ import { codeIsFromMain, repoInfo } fro
import { Refused } from './refused.js';
import { loadConfig } from './config.js';
import { projectState } from './serve.js';
+import { personRequestStatuses } from './relay-requests.js';
/** Capture spec, doctrine, config and board presentation without sending plaintext to a relay. */
-export function relayPresentation(root) {
+export function relayPresentation(root, { board: providedBoard = null } = {}) {
- const state = projectState(root, { board: providedBoard });
const info = repoInfo(root);
- const board = providedBoard ?? store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
- try { return { version: 1, state: { ...store.projectItemThreads(board, state), personRequests: personRequestStatuses(board) }, config: loadConfig(root), shouts: store.allShouts(board) }; }
- 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) };
++ const board = providedBoard ?? store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
++ try {
++ const state = projectState(root, { board });
++ return { version: 1, state: { ...store.projectItemThreads(board, state), personRequests: personRequestStatuses(board) }, config: loadConfig(root), shouts: store.allShouts(board) }; }
+ finally { if (!providedBoard) store.closeBoard(board); }
+}
+/** Resolve one shout from the complete history carried only inside the sealed presentation. */
+export function relayPresentationShout(root, id) {
+ return presentationShout(relayPresentation(root), id);
+}
+
+/** Resolve one addressed shout from an already decoded snapshot without local repository access. */
+export function presentationShout(presentation, id) {
+ if (!Array.isArray(presentation?.shouts)) throw new Refused('SHOUT_NOT_AVAILABLE', 'this snapshot does not include addressed shout history; refresh it with a current CLI');
+ const found = presentation.shouts.find((shout) => shout.shout_id === id);
+ if (!found) throw new Refused('NO_SHOUT', `no shout #${id}`);
+ const answer = found.shout_decision ? presentation.shouts.find((shout) => shout.shout_answers === id) ?? null : null;
+ return { ...found, decision_state: found.shout_decision ? (answer ? 'answered' : 'open') : null, decision_answer: answer };
}
/** Notice presentation-only changes, including a spec or doctrine edit without a board move. */
@@@ -37,17 -22,17 +38,17 @@@ export function presentationDigest(pres
}
/** Capture importable native tables beside matching API presentation, retrying a concurrent local move. */
-export function relaySnapshot(root) {
+export function relaySnapshot(root, { board: providedBoard = null } = {}) {
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'), undefined, { isMain: codeIsFromMain() });
+ const before = providedBoard ? null : relayPresentation(info.root);
- const board = providedBoard ?? store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));
++ const board = providedBoard ?? 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);
+ try { native = exportBoard(board); } finally { if (!providedBoard) store.closeBoard(board); }
+ const presentation = relayPresentation(info.root, { board: providedBoard });
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 };
+ (providedBoard || 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-request-execution.js
index 79e7eaf3,00000000..4d1a3271
mode 100644,000000..100644
--- a/src/relay-request-execution.js
+++ b/src/relay-request-execution.js
@@@ -1,79 -1,0 +1,79 @@@
+/** Native person requests run the actual CLI outside the relay lock [H12,H16]. */
+import { createHash, randomUUID } from 'node:crypto';
+import { join } from 'node:path';
+import * as store from './board.js';
+import { executeMove } from './api.js';
+import { loadConfig } from './config.js';
- import { git, repoInfo } from './git.js';
++import { codeIsFromMain, git, repoInfo } from './git.js';
+import { laneNames } from './lanes.js';
+import { refusalDocument } from './json.js';
+import { Refused } from './refused.js';
+import { relayLinked, relayOperation, relayRequestDevice } from './relay.js';
+import { personRequestRecords, requestIntentDigest, requestStageText } from './relay-requests.js';
+
+/** Read durable intake without retaining a SQLite connection while the CLI runs. */
+function requests(root) {
- const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'));
++ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ try { return personRequestRecords(board).filter(record => !record.duplicateOf); }
+ finally { store.closeBoard(board); }
+}
+
+/** Give each request stage one stable ordinary-move id across command and device retries. */
+function stageId(id, phase, executor) {
+ return 'person-request-' + createHash('sha256').update(JSON.stringify([id, phase, executor])).digest('hex');
+}
+
+/** Publish an ordinary person shout as a durable intake, coordinator request or refusal receipt. */
+async function receipt(root, record, executor, phase, io, error) {
+ const message = { from: 'person', to: 'coordinator', text: requestStageText(record, phase, error), lanes: laneNames(loadConfig(root)), ...(phase === 'repo-request' ? { request: true } : {}) };
+ return relayOperation(root, 'shout', [message], {
+ ...io, personRequest: { id: record.id, executor, phase, digest: requestIntentDigest(record), ...(error ? { error } : {}) },
+ personRequestMoveId: phase === 'claim' && record.executor && record.executor !== executor ? randomUUID() : stageId(record.id, phase, executor),
+ });
+}
+
+/** Transport authorization and ordering failures leave intent waiting for a reachable signed-in device. */
+function transportRefusal(error) {
+ return /^(?:RELAY_|AUTH_|TOKEN_|BOARD_|PAIR_|SEQUENCE_)/u.test(error.code) || ['NO_REPO_ACCESS', 'NO_BOARD'].includes(error.code);
+}
+
+/** Fulfil queued browser intent once on its elected native device, preserving actual CLI refusals. */
+export async function executePersonRequests(root, io, runCommand) {
+ if (io.skipPersonRequests || !relayLinked(root)) return;
+ const coordinatorRoot = git(root, ['worktree', 'list', '--porcelain']).split('\n')[0].slice('worktree '.length);
+ const pending = requests(coordinatorRoot).filter(record => record.status === 'waiting' && !record.coordinatorRequest);
+ if (!pending.length) return;
+ const executor = await relayRequestDevice(coordinatorRoot);
+ if (!executor) return;
+ for (const initial of pending) {
+ if (initial.status !== 'waiting') continue;
+ try {
+ if (initial.executor !== executor) await receipt(coordinatorRoot, initial, executor, 'claim', io);
+ const record = requests(coordinatorRoot).find(entry => entry.id === initial.id);
+ if (record.executor !== executor || record.status !== 'waiting') continue;
+ if (!Object.hasOwn(record, 'result')) {
+ const response = await executeMove(coordinatorRoot, record.move, (argv, streams) => runCommand(argv, {
+ ...streams, skipPersonRequests: true,
+ personRequest: { id: record.id, executor, phase: 'execute', digest: requestIntentDigest(record) },
+ personRequestMoveId: stageId(record.id, 'execute', executor),
+ }));
+ if (response.status !== 200) {
+ const error = response.body.error;
+ if (transportRefusal(error) || error.code === 'PERSON_REQUEST_TAKEN') continue;
+ if (requests(coordinatorRoot).find(entry => entry.id === record.id)?.status === 'waiting') await receipt(coordinatorRoot, record, executor, 'refuse', io, error);
+ continue;
+ }
+ }
+ const completed = requests(coordinatorRoot).find(entry => entry.id === record.id);
+ if (['spec-approve', 'spec-decline'].includes(record.move.verb) && completed.status === 'waiting' && !completed.coordinatorRequest) {
+ await receipt(coordinatorRoot, completed, executor, 'repo-request', io);
+ }
+ } catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ if (['PERSON_REQUEST_TAKEN', 'PERSON_REQUEST_CLOSED', 'RELAY_PERSON_ONLY'].includes(error.code)) continue;
+ if (transportRefusal(error)) { io.err('pullboard: ' + error.message); continue; }
+ const record = requests(coordinatorRoot).find(entry => entry.id === initial.id);
+ if (record?.executor === executor && record.status === 'waiting') await receipt(coordinatorRoot, record, executor, 'refuse', io, refusalDocument(error).error);
+ }
+ }
+}
diff --cc src/relay-setup.js
index 09cf5107,00000000..2e46a24c
mode 100644,000000..100644
--- a/src/relay-setup.js
+++ b/src/relay-setup.js
@@@ -1,176 -1,0 +1,176 @@@
+/** Set up a machine once, enroll its phone in the foreground and link later registrations [H5,H17]. */
+import { join } from 'node:path';
+import * as store from './board.js';
+import { phoneProposal, publishPhoneApproval, warnPhoneApproval } from './relay-phone.js';
+import { openApproval, restoreLinkReply } from './relay-approval.js';
+import { requirePersonChannel } from './person.js';
- import { repoInfo } from './git.js';
++import { codeIsFromMain, repoInfo } from './git.js';
+import { listApiProjects } from './projects.js';
+import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, updateRelayMachine } from './relay-machine.js';
+import { deliverDeviceWraps, relayDeviceRequest, relayMachineSignIn, relayMachineContext, relayRevokeDevice, relayOn, relayStatus, originRepository } from './relay.js';
+import { terminalQr } from './qr.js';
+import { Refused } from './refused.js';
+
+/** Return local opt-in gaps without contacting the relay or renewing a person session. */
+export function unlinkedRelayProjects() {
+ const machine = readRelayMachine();
+ if (!machine.autoLink) return [];
+ return listApiProjects().filter(project => !machine.excluded.includes(project.root)).flatMap(project => {
+ try { if (relayStatus(project.root).linked) return []; } catch { /* Preserve the registered project as a named finding. */ }
+ const pending = machine.approvals.find(entry => entry.root === project.root);
+ return [{ code: pending ? 'PHONE_APPROVAL_PENDING' : 'RELAY_NOT_LINKED', message: pending ? 'waiting for phone approval: ' + project.name + '; expires ' + new Date(pending.context.expires).toISOString() : 'not linked: ' + project.name + '; run pullboard relay on --all', next: pending && Date.now() < pending.context.expires ? 'Approve the named link on your paired phone.' : 'pullboard relay on --all' }];
+ });
+}
+
+/** Read the registered local board identity without executing any person action. */
+function projectBoard(root) {
- const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'));
++ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ try { return store.boardId(board); } finally { store.closeBoard(board); }
+}
+
+/** Link a new project only after the paired phone explicitly approves its one durable proposal. */
+export async function autoLinkProject(root, io) {
+ const machine = readRelayMachine();
+ if (!machine.autoLink) return;
+ const project = repoInfo(root).root;
+ if (machine.excluded.includes(project) || relayStatus(project).linked) return;
+ const name = listApiProjects().find(entry => entry.root === project)?.name ?? project;
+ let pending = machine.approvals.find(entry => entry.root === project);
+ try {
+ if (pending && Date.now() >= pending.context.expires) throw new Refused('PHONE_APPROVAL_EXPIRED', 'Link approval expired; run pullboard relay on --all explicitly to link this project.');
+ let source;
+ if (pending) source = relayMachineContext(pending.publisherRoot);
+ else {
+ const candidate = listApiProjects().map(entry => ({ ...entry, state: relayMachineContext(entry.root) }))
+ .find(entry => entry.state?.token?.startsWith('pm_') && entry.state.account === machine.owner?.account && entry.state.url === machine.owner?.url);
+ if (!candidate) throw new Refused('RELAY_SESSION', 'Run pullboard relay on --all to link this project and pair the phone.');
+ source = candidate.state;
+ const proposal = await phoneProposal(source, 'link', originRepository(project),
+ { board: projectBoard(project), command: 'Link ' + name + '? (pullboard init)', link: true });
+ const value = { root: project, publisherRoot: candidate.root, context: proposal.context, sealed: proposal.sealed, replyKey: proposal.reply.storedKey, published: false };
+ pending = updateRelayMachine(state => {
+ const existing = state.approvals.find(entry => entry.root === project);
+ if (existing) return existing;
+ state.approvals.push(value); return value;
+ });
+ source = relayMachineContext(pending.publisherRoot);
+ }
+ if (!source?.token?.startsWith('pm_')) throw new Refused('RELAY_SESSION', 'Restore the publishing board link or run pullboard relay on --all.');
+ if (!pending.published) {
+ await publishPhoneApproval(source, pending, io, relayDeviceRequest);
+ updateRelayMachine(state => { const entry = state.approvals.find(value => value.context.id === pending.context.id); if (entry) entry.published = true; });
+ }
+ const document = await relayDeviceRequest(source, '/api/v1/devices/approvals/' + pending.context.id, {}, io);
+ if (document.approval.state !== 'approved') {
+ io.err('waiting for phone approval: ' + name + '; expires ' + new Date(pending.context.expires).toISOString() + '; local work continues.'); return;
+ }
+ const privateKey = await restoreLinkReply(pending.replyKey);
+ const result = await openApproval(privateKey, JSON.parse(Buffer.from(document.approval.response, 'base64url').toString('utf8')), pending.context, 'reply');
+ const credential = { ...result.credential, account: pending.context.account, url: source.url };
+ await relayOn(project, source.url, io, { credential, quiet: true, strict: true });
+ updateRelayMachine(state => { state.approvals = state.approvals.filter(entry => entry.context.id !== pending.context.id); });
+ } catch (error) {
+ if (pending) {
+ warnPhoneApproval(pending, error, io, 'Local registration is complete; run pullboard relay on --all explicitly to link this project.');
+ return;
+ }
+ io.err('not linked: ' + name + '; ' + (error instanceof Refused ? error.message : 'Restore the pending phone approval or run pullboard relay on --all.'));
+ }
+}
+
+/** Retry only old deletion intents during an explicit foreground sign-in; never retain that session. */
+async function flushRevocations(session, io) {
+ for (const intent of readRelayMachine().revocations) {
+ if (session.account !== intent.account || session.url !== intent.url) continue;
+ await relayDeviceRequest(session, '/api/v1/devices/' + intent.deviceId, { method: 'DELETE' }, io);
+ updateRelayMachine(state => { state.revocations = state.revocations.filter(entry => entry.deviceId !== intent.deviceId); });
+ }
+}
+
+/** The native device revocation uses the same one-tap grant path as token revocation. */
+export async function revokeRelayDevice(deviceId, io) {
+ requirePersonChannel(io.personChannel);
+ const device = readRelayMachine().devices.find(entry => entry.deviceId === deviceId);
+ if (!device) throw new Refused('DEVICE_NOT_ENROLLED', 'Name a paired device from pullboard relay devices.');
+ const roots = [io.cwd, ...listApiProjects().map(entry => entry.root)];
+ for (const root of roots) {
+ let state;
+ try { state = relayMachineContext(root); } catch { continue; }
+ if (state?.token?.startsWith('pm_') && state.account === device.account && state.url === device.url) return relayRevokeDevice(root, deviceId, io);
+ }
+ throw new Refused('RELAY_NOT_LINKED', 'Link a board and pair the phone with pullboard relay on --all.');
+}
+
+/** Link every non-excluded registry entry, collecting project-specific partial failures. */
+async function linkProjects(session, io) {
+ const machine = readRelayMachine();
+ const linked = [];
+ const failed = [];
+ for (const project of listApiProjects()) {
+ if (machine.excluded.includes(project.root)) continue;
+ try {
+ const result = await relayOn(project.root, session.url, io, { session, quiet: true, strict: true });
+ linked.push({ project: project.name, root: project.root, board: result.board });
+ io.say(`linked: ${project.name}`);
+ } catch (error) {
+ const reason = error instanceof Refused ? error.message : 'Restore this registered project and retry.';
+ failed.push({ project: project.name, root: project.root, reason });
+ io.err(`not linked: ${project.name}; ${reason}`);
+ }
+ }
+ return { linked, failed };
+}
+
+/** Publish a one-use public locator and wait in this command; no service or unattended daemon is added. */
+async function pairFirstDevice(session, board, linked, io) {
+ const pending = beginDeviceEnrollment(board, session);
+ const path = '/api/v1/devices/enrollments/' + pending.locator;
+ await relayDeviceRequest(session, path, { method: 'POST', body: {} }, io);
+ const link = session.url + '/#device=' + pending.locator + '.' + pending.secret;
+ io.say('Pair your phone once: ' + link);
+ try { io.say(terminalQr(link)); }
+ catch (error) { if (error.code !== 'PAIR_LINK_LONG') throw error; io.say('Open the pairing link above.'); }
+ let interrupted = false;
+ /** End foreground pairing without discarding successful board links or saving a partial device. */
+ const stop = () => { interrupted = true; };
+ process.once('SIGINT', stop);
+ process.once('SIGTERM', stop);
+ try {
+ while (!interrupted && Date.now() < pending.expires) {
+ const result = await relayDeviceRequest(session, path, {}, io);
+ if (interrupted) break;
+ if (result.enrollment) {
+ const device = await acceptDeviceEnrollment(result.enrollment);
+ await relayDeviceRequest(session, '/api/v1/devices/' + device.deviceId, { method: 'POST', body: {} }, io);
+ await relayDeviceRequest(session, path, { method: 'DELETE' }, io);
+ for (const project of linked) await deliverDeviceWraps(project.root, io);
+ io.say('Phone paired; current and future linked boards will appear here.');
+ return { paired: true, deviceId: device.deviceId };
+ }
+ await new Promise(resolve => { setTimeout(resolve, 500); });
+ }
+ io.say('Boards linked; phone pairing stopped. Run pullboard relay on --all for a fresh code.');
+ return { paired: false, interrupted };
+ } finally {
+ process.off('SIGINT', stop); process.off('SIGTERM', stop);
+ updateRelayMachine(state => { if (state.pending?.locator === pending.locator) state.pending = null; });
+ // Best-effort remove the public locator. Its relay lifetime remains ten minutes on an outage.
+ try { await relayDeviceRequest(session, path, { method: 'DELETE' }, io); } catch { /* Never undo completed links after a pairing timeout. */ }
+ }
+}
+
+/** Explicit foreground sign-in repairs links; only board machine credentials survive this command. */
+export async function relayOnAll(address, io) {
+ requirePersonChannel(io.personChannel);
+ const prior = readRelayMachine();
+ // Scrub every registered legacy link before asking for or using fresh person authority.
+ for (const project of listApiProjects()) { try { relayMachineContext(project.root); } catch { /* linkProjects reports invalid projects. */ } }
+ const session = await relayMachineSignIn(address || prior.owner?.url, io);
+ updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = []; });
+ await flushRevocations(session, io);
+ const result = await linkProjects(session, io);
+ const devices = readRelayMachine().devices.filter(device => device.account === session.account && device.url === session.url);
+ const pairing = devices.length || !result.linked.length ? { paired: devices.length > 0 }
+ : await pairFirstDevice(session, result.linked[0].board, result.linked, io);
+ return { ...result, ...pairing, autoLink: true };
+}
diff --cc src/relay.js
index 4bc471bf,dfea978e..66d515d5
--- a/src/relay.js
+++ b/src/relay.js
@@@ -1,15 -1,13 +1,15 @@@
-/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H16,P5]. */
-import { randomUUID } from 'node:crypto';
-import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */
+import { createHash, randomUUID } from 'node:crypto';
+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
+import { gunzipSync, gzipSync } from 'node:zlib';
import * as store from './board.js';
-import { exportBoard, restoreRelaySnapshot } from './exchange.js';
-import { appliedSequence, applyEngineMove, checkpointSequence, engineReceipt, prepareEngineMove, startRelayEpoch } from './engine.js';
+import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';
+import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';
+import { relayMoveActor } from './relay-sender.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, unseal } from './seal.js';
import { terminalQr } from './qr.js';
@@@ -718,27 -301,15 +718,27 @@@ async function catchUp(root, file, stat
if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string')) {
throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered prefix; fetch a consistent relay snapshot');
}
+ let pendingRefusal;
for (const record of remote.events) {
- const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'));
- const move = await decoded(key, record, state, record.kind, record.event_id);
- localRecords(root, (board) => {
- applyEngineMove(board, move, { sequence: record.event_id, at: record.event_at });
- });
++ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
+ let outcome;
+ try { outcome = await replayRelayRecord(board, key, state, record); } finally { store.closeBoard(board); }
+ // Exact ciphertext identifies an interrupted send even when its document was refused before replay.
+ if (record.kind === 'move' && state.pending?.move && record.event_id === state.pending.sequence
+ && record.sealed === state.pending.sealed && outcome?.error
+ && !localRecords(root, board => engineReceipt(board, state.pending.move.id))) {
+ pendingRefusal = outcome.error;
+ delete state.pending;
+ delete state.recovered;
+ }
}
state.sequence = localRecords(root, appliedSequence);
- if (state.pending?.move && localRecords(root, (board) => engineReceipt(board, state.pending.move.id))) delete state.pending;
+ if (state.pending?.move && localRecords(root, (board) => engineReceipt(board, state.pending.move.id))) {
+ state.recovered = state.pending;
+ delete state.pending;
+ }
saveLink(file, state);
+ if (pendingRefusal) throw new Refused(pendingRefusal.code, pendingRefusal.message);
}
/** Finish a durable executable send; a collision reseals its unchanged id after applying the winner. */
@@@ -967,197 -388,10 +967,197 @@@ export async function syncRelay(root, i
}
catch (error) {
if (!(error instanceof Refused)) throw error;
- io.err(`pullboard: ${error.message}; run pullboard status to see pending uploads`);
+ if (error.code === 'RELAY_KEY_MISSING') {
+ if (!KEY_WARNED_COMMANDS.has(io)) {
+ KEY_WARNED_COMMANDS.add(io);
+ io.err(`pullboard: ${error.message}; moves are off until the key is reachable`);
+ }
+ } else if (error.code === 'AUTH_REQUIRED') {
+ if (!orderedMoveCommand(io)) reportExpiredSignIn(state, io);
+ } else io.err(`pullboard: ${error.message}; run pullboard status to see pending uploads`);
return { linked: true, board: state.board, url: state.url, sequence: state.sequence,
- behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)) };
+ behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),
+ recovery: recoverySummary(state) };
+ }
+ });
+}
+
+/** Return token-management context without opening a board-key pairing link or exposing any credential. */
+function tokenContext(state) {
+ return { linked: true, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, recovery: recoverySummary(state) };
+}
+
+/** Require the existing board delegate before listing metadata or requesting an approved revocation. */
+function managementLink(file) {
+ const state = loadLink(file);
+ if (!state || state.unlinking) throw new Refused('RELAY_OFF', 'link this board with pullboard relay on before managing its agent tokens');
+ return state;
+}
+
+/** List only this board’s agent-token metadata, never bearer values or the board key. */
+export async function relayTokens(root, io) {
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = managementLink(file);
+ const listed = await request(state, '/auth/tokens?board=' + state.board, {}, io);
+ if (!Array.isArray(listed.tokens) || listed.tokens.some((row) => !row || row.board !== state.board ||
+ typeof row.id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(row.id) ||
+ typeof row.agent !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(row.agent) ||
+ !Number.isSafeInteger(row.expires) || (row.created !== null && !Number.isSafeInteger(row.created)) ||
+ typeof row.revoked !== 'boolean')) throw new Refused('RELAY_RESPONSE', 'the relay token inventory is invalid; retry its configured address');
+ const tokens = listed.tokens.map(({ id, board, agent, created, expires, revoked }) => ({ id, board, agent, created, expires, revoked }));
+ return { ...tokenContext(state), tokens };
+ });
+}
+
+/** Revoke one credential listed on this board while retaining its cache so it cannot be silently reminted. */
+export async function relayRevoke(root, id, io) {
+ requirePersonChannel(io.personChannel);
+ if (typeof id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) {
+ throw new Refused('TOKEN_NOT_OWNED', 'name an opaque token id from pullboard relay tokens, never a credential value');
+ }
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = managementLink(file);
+ const listed = await request(state, '/auth/tokens?board=' + state.board, {}, io);
+ if (!Array.isArray(listed.tokens) || !listed.tokens.some((row) => row.id === id)) {
+ throw new Refused('TOKEN_NOT_OWNED', 'choose a token listed on this board by pullboard relay tokens');
+ }
+ const result = await nativePhoneAction(state, 'revoke-token', id, io, request);
+ if (result.id !== id || result.revoked !== true) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge this token revocation; retry its opaque id');
+ for (const credential of Object.values(state.agentTokens ?? {})) if (credential.id === id) credential.revoked = true;
+ saveLink(file, state);
+ return { ...tokenContext(state), id: result.id, revoked: result.revoked };
+ });
+}
+
+/** Read an acknowledged exact CLI result before changed spec, brief or Git refs can block it. */
+export async function relayCommandReceipt(root, command) {
+ if (!command) return null;
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = loadLink(file);
+ if (!state || state.unlinking) return null;
+ const recovered = state.recovered;
+ if (!recovered || recovered.commandIntent !== operationIntent('cli:' + command.cliOperation, command)) return null;
+ if (recovered.commandIntent !== operationIntent('cli:' + recovered.command?.cliOperation, recovered.command)) {
+ throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
+ }
+ const expected = { add: 'addItem', edit: 'editItem', merged: 'merged' }[command.cliOperation];
+ if (!recovered.move || recovered.move.operation !== expected) throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
+ const move = recoveredMove(root, state, recovered.move.operation, recovered.move.args, command);
+ const receipt = localRecords(root, board => engineReceipt(board, move.id));
+ if (receipt.outcome.error) {
+ delete state.recovered;
+ saveLink(file, state);
+ throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message);
}
+ return { result: receipt.outcome.result, events: receipt.outcome.events ?? [], move };
+ });
+}
+
+/** Consume the exact cached result after its original CLI outcome has been formatted. */
+export async function relayCommandReceiptReported(root, moveId) {
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = loadLink(file);
+ if (state?.recovered?.move?.id === moveId) {
+ delete state.recovered;
+ saveLink(file, state);
+ }
+ });
+}
+
+/** Expose only an unreported operation descriptor so CLI preconditions cannot strand its outcome. */
+export function relayRecovered(root) {
+ return loadLink(linkFile(root))?.recovered?.move ?? null;
+}
+
+/** Explicitly refuse one blocked position, replay its valid tail on a private copy, then publish it. */
+export async function relayRecover(root, skip, io) {
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = loadLink(file);
+ if (!state || state.unlinking || state.mode !== 'ordered') throw new Refused('RELAY_LINKED', 'link this ordered relay board before recovering a blocked sequence');
+ const boardFile = join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite');
- const source = store.openBoard(boardFile);
++ const source = store.openBoard(boardFile, undefined, { isMain: codeIsFromMain() });
+ const staged = store.openBoard(':memory:');
+ try {
+ const cursor = appliedSequence(source);
+ const sourceDigest = nativeBoardDigest(source);
+ if (!Number.isSafeInteger(skip) || skip !== cursor + 1) throw new Refused('RELAY_SEQUENCE', `only the blocked next sequence ${cursor + 1} can be skipped; inspect pullboard relay and retry`);
+ if (state.recovery && (state.recovery.skip !== skip || state.recovery.cursor !== cursor)) {
+ throw new Refused('RELAY_RECOVERY_PENDING', `finish the saved recovery for sequence ${state.recovery.skip} before choosing another; retry pullboard relay recover --skip ${state.recovery.skip}`);
+ }
+ if (state.recovery && state.recovery.sourceDigest !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery was pending; local rows are preserved, but this recovery cannot be retried from the changed board; keep an export and ask the person to reconcile the relay checkpoint');
+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery started; no recovery data was published, retry after preserving that change');
+ importBoard(staged, exportBoard(source));
+ const key = readBoardKey(state.board);
+ if (state.recovery) {
+ const saved = await request(state, '/api/v1/boards/' + state.board + '/state', {}, io);
+ if (Number.isSafeInteger(saved.state?.sequence) && saved.state.sequence >= state.recovery.sequence) {
+ const ownAcknowledgement = saved.state.sequence === state.recovery.sequence && saved.state.sealed === state.recovery.sealed;
+ const senderProblem = relaySenderProblem(null, saved.state.sender, 'snapshot');
+ if (senderProblem) throw senderProblem;
+ const native = await decoded(key, saved.state, state, 'snapshot', saved.state.sequence);
+ if (!recoveryRefusalMatches(native, state.recovery) || (!ownAcknowledgement && !state.recovery.blockerDigest)) {
+ throw new Refused('RELAY_RECOVERY_PENDING', 'the checkpoint does not prove this blocked sequence was refused; keep this device unchanged and ask the person to inspect the relay checkpoint');
+ }
+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery was pending; local rows are preserved, but this checkpoint cannot be adopted over those changes; keep an export and ask the person to reconcile the relay checkpoint');
+ restoreRelaySnapshot(source, native, saved.state.sequence, sourceDigest);
+ state.sequence = saved.state.sequence;
+ state.cursor = saved.state.sequence;
+ delete state.recovery;
+ saveLink(file, state);
+ return { ...summary(root, state), skipped: skip, ...(!ownAcknowledgement ? { adopted: true } : {}) };
+ }
+ }
+ const remote = await request(state, '/api/v1/boards/' + state.board + '/events?after=' + cursor, {}, io);
+ if (!Array.isArray(remote.events) || !remote.events.length || remote.events[0]?.event_id !== skip) throw new Refused('RELAY_SEQUENCE', `relay sequence ${skip} is not available as the next record; fetch the current relay prefix`);
+ const blocker = remote.events[0];
+ let decodedMove = null;
+ let blockerCode = 'RELAY_RECORD';
+ try {
+ decodedMove = await decoded(key, blocker, state, blocker.kind, blocker.event_id);
+ requireSupportedEngine(decodedMove);
+ throw new Refused('RELAY_RECOVERY_HEALTHY', 'the selected record is readable by this pullboard version; run pullboard relay to replay it normally');
+ } catch (error) {
+ if (!(error instanceof Refused) || (error.code !== 'ENGINE_VERSION' && !['SEAL_VERSION', 'RELAY_MOVE', 'RELAY_RESPONSE', 'SEAL_FORMAT', 'SEAL_AUTH_FAILED'].includes(error.code))) throw error;
+ blockerCode = error.code;
+ // A person may explicitly bypass this one authenticated transport slot; it remains in the receipt log.
+ }
+ if (decodedMove?.engine > ENGINE_VERSION) blockerCode = 'ENGINE_VERSION';
+ const blockerDigest = createHash('sha256').update(String(blocker.sealed)).digest('hex');
+ refuseRelayMove(staged, decodedMove, { sequence: skip, at: blocker.event_at, sender: blocker.sender, kind: blocker.kind,
+ code: blockerCode,
+ digest: blockerDigest,
+ refusal: new Refused(blockerCode, 'person recovery logged this blocked record as refused; run pullboard relay to apply the remaining ordered tail') });
+ for (const record of remote.events.slice(1)) {
+ try { await replayRelayRecord(staged, key, state, record); }
+ catch (error) {
+ // A later unsupported record needs its own explicit choice; it cannot undo this selected skip.
+ if (!(error instanceof Refused) || !['ENGINE_VERSION', 'SEAL_VERSION'].includes(error.code)) throw error;
+ break;
+ }
+ }
+ const document = relaySnapshot(root, { board: staged });
+ const sequence = appliedSequence(staged);
+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery was staged; no recovery checkpoint was published, export the new local change and retry');
+ const candidate = state.recovery?.sequence === sequence
+ ? { sequence, sealed: state.recovery.sealed }
+ : { sequence, sealed: await sealedRecord(key, document, state, 'snapshot', sequence) };
+ state.recovery = { skip, cursor, sourceDigest, blockerDigest, ...candidate };
+ saveLink(file, state);
+ const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: candidate }, io);
+ if (reply.state?.sequence !== sequence || reply.state.sealed !== candidate.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the recovery checkpoint; local board was left unchanged, retry recovery');
+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed before checkpoint acknowledgement; local rows are preserved, but the checkpoint may already be accepted and this recovery cannot be retried from the changed board; keep an export and ask the person to reconcile the relay checkpoint');
+ restoreRelaySnapshot(source, document, sequence, sourceDigest);
+ state.sequence = sequence;
+ state.cursor = sequence;
+ delete state.recovery;
+ saveLink(file, state);
+ return { ...summary(root, state), skipped: skip };
+ } finally { store.closeBoard(staged); store.closeBoard(source); }
});
}
diff --cc test/api.test.js
index 7c62469f,f2842078..4306b573
--- a/test/api.test.js
+++ b/test/api.test.js
@@@ -1,9 -1,9 +1,10 @@@
/** The public, versioned JSON surface of every pullboard command (A1). */
import assert from 'node:assert/strict';
-import { execFileSync, spawn, spawnSync } from 'node:child_process';
+import { runFixtureExecFile as execFileSync, startFixtureChild as spawn, runFixtureChild as spawnSync, reportFixtureChildFailure, runFixtureChild, runFixtureGit } from './fixture-child.js';
+import { performance } from 'node:perf_hooks';
import {
chmodSync,
+ cpSync,
existsSync,
mkdirSync,
mkdtempSync,
@@@ -101,11 -63,12 +102,13 @@@ 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'),
+ PULLBOARD_MACHINE_HOME: join(dir, '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' });
+ for (const marker of SSH_SHELL_MARKERS) delete env[marker];
+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env, encoding: 'utf8', stdio: 'pipe' });
+ const run = (cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
return { dir, env, git, run };
}
diff --cc test/doctor.test.js
index c83fd89b,24e8e0ec..e549a374
--- a/test/doctor.test.js
+++ b/test/doctor.test.js
@@@ -1,9 -1,9 +1,9 @@@
/** Integrity checks use throwaway git repositories and real board databases (A6). */
import assert from 'node:assert/strict';
-import { execFileSync, spawnSync } from 'node:child_process';
-import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { runFixtureChild, runFixtureGit } from './fixture-child.js';
- import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
++import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join, resolve } from 'node:path';
+import { delimiter, join, resolve } from 'node:path';
import { after, test } from 'node:test';
import { DatabaseSync } from 'node:sqlite';
import { SCHEMA_VERSION } from '../src/board.js';
@@@ -35,14 -36,11 +37,15 @@@ function boardBox({ initialize = true,
GIT_COMMITTER_NAME: 'Doctor Test',
GIT_COMMITTER_EMAIL: '[email protected]',
});
+ delete env.PULLBOARD_RELAY_TOKEN;
- const git = (...args) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8' }).trim();
- const run = (...args) => spawnSync(process.execPath, [BIN, ...args], { cwd: root, env, encoding: 'utf8' });
+ const git = (...args) => runFixtureGit(args, { cwd: root, env, encoding: 'utf8' });
+ const run = (...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd: root, env, encoding: 'utf8' });
git('init', '-q', '-b', 'main');
- writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', lanes: {} }, null, 2));
+ const mergeHook = join(root, '.git', 'hooks', 'pre-merge-commit');
+ mkdirSync(join(root, '.git', 'hooks'), { recursive: true });
+ writeFileSync(mergeHook, hookScript('pre-merge-commit'));
+ chmodSync(mergeHook, 0o755);
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', lanes }, null, 2));
git('add', '-A');
git('commit', '-q', '-m', 'chore: setup');
const dbFile = join(root, '.git', 'pullboard', 'board.sqlite');
@@@ -51,6 -49,14 +54,14 @@@
return { dir, root, env, git, run, dbFile };
}
+ /** Exercise installed-release repair advice independently of the checkout running this test. */
+ function runRelease(box, ...args) {
+ const release = join(box.dir, 'installed-release');
+ mkdirSync(release, { recursive: true });
+ for (const name of ['bin', 'src', 'package.json']) cpSync(resolve(import.meta.dirname, '..', name), join(release, name), { recursive: true });
- return spawnSync(process.execPath, [join(release, 'bin/pullboard.js'), ...args], { cwd: box.root, env: box.env, encoding: 'utf8' });
++ return runFixtureChild(process.execPath, [join(release, 'bin/pullboard.js'), ...args], { cwd: box.root, env: box.env, encoding: 'utf8' });
+ }
+
/**
* Open the test board directly so a fixture can model corruption that normal triggers prevent.
*/
diff --cc test/git-provenance.test.js
index 00000000,9b6a5769..66ed31fa
mode 000000,100644..100644
--- a/test/git-provenance.test.js
+++ b/test/git-provenance.test.js
@@@ -1,0 -1,61 +1,66 @@@
+ /** Running source provenance ignores inherited Git hook repository overrides [A5,A6]. */
+ import assert from 'node:assert/strict';
+ import { spawnSync } from 'node:child_process';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
++import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
+ import { tmpdir } from 'node:os';
+ import { join, resolve } from 'node:path';
+ import { pathToFileURL } from 'node:url';
+ import { test } from 'node:test';
+
+ /** Run Git in a disposable fixture without depending on user or system config. */
+ function git(cwd, args, env) {
+ return spawnSync('git', args, { cwd, env, encoding: 'utf8' });
+ }
+
+ /** Ask a fresh Node process for source provenance under inherited Git directory variables. */
+ function probe(moduleURL, root, env) {
+ const script = `import { codeIsFromMain } from ${JSON.stringify(moduleURL)}; process.stdout.write(String(codeIsFromMain(process.argv[1])));`;
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, root], { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ return result.stdout === 'true';
+ }
+
+ test('[A5,A6] code provenance strips inherited GIT_DIR in both worktree-to-main directions', (t) => {
+ const fixture = mkdtempSync(join(tmpdir(), 'pullboard-git-provenance-'));
+ t.after(() => rmSync(fixture, { recursive: true, force: true }));
+ const main = join(fixture, 'main');
+ const linked = join(fixture, 'linked');
+ mkdirSync(main);
+ const baseEnv = {
+ ...process.env,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Provenance test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Provenance test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ const init = git(main, ['init', '-q', '-b', 'main'], baseEnv);
+ assert.equal(init.status, 0, init.stderr);
+ writeFileSync(join(main, 'README.md'), 'fixture\n');
+ for (const args of [['add', 'README.md'], ['commit', '-q', '-m', 'fixture']]) {
+ const result = git(main, args, baseEnv);
+ assert.equal(result.status, 0, result.stderr);
+ }
+ const worktree = git(main, ['worktree', 'add', '-q', '-b', 'feature', linked], baseEnv);
+ assert.equal(worktree.status, 0, worktree.stderr);
+ const mainGitDir = git(main, ['rev-parse', '--path-format=absolute', '--git-dir'], baseEnv).stdout.trim();
+ const linkedGitDir = git(linked, ['rev-parse', '--path-format=absolute', '--git-dir'], baseEnv).stdout.trim();
+ const commonGitDir = git(main, ['rev-parse', '--path-format=absolute', '--git-common-dir'], baseEnv).stdout.trim();
++ const alias = join(fixture, 'MAIN');
++ if (existsSync(alias) && statSync(alias).ino === statSync(main).ino) {
++ assert.equal(probe(pathToFileURL(resolve(import.meta.dirname, '../src/git.js')).href, alias, baseEnv), true,
++ 'a case alias of the primary checkout remains primary on a case-insensitive volume');
++ }
+ const helperURL = pathToFileURL(resolve(import.meta.dirname, '../src/git.js')).href;
+
+ const worktreeAsMain = probe(helperURL, linked, {
+ ...baseEnv, GIT_DIR: mainGitDir, GIT_WORK_TREE: main, GIT_COMMON_DIR: mainGitDir,
+ });
+ assert.equal(worktreeAsMain, false, 'worktree source remains unmerged when its process inherits main checkout variables');
+
+ const mainAsWorktree = probe(helperURL, main, {
+ ...baseEnv, GIT_DIR: linkedGitDir, GIT_WORK_TREE: linked, GIT_COMMON_DIR: commonGitDir,
+ });
+ assert.equal(mainAsWorktree, true, 'main source can upgrade in a hook that inherits linked-worktree variables');
+ });
diff --cc test/machine.test.js
index 9f589a51,31e90d84..f149d165
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@@ -29,10 -29,8 +29,11 @@@ const NOT_MOVES =
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',
+ REMOTE_COORDINATOR_MODEL: 'a linked replica cannot redeclare the coordinator model; use the coordinator checkout',
EVENT_LOG_VERSION: 'the local board format is checked before opening it for an item move',
+ NOT_YOUR_CHECKOUT: 'the caller owns the checkout session, checked before any item move',
+ CHECKOUT_SESSION: 'the checkout-local session binding is readable before any item move',
+ UNMERGED_SCHEMA: 'shared-board schema compatibility checked before a command opens the database',
};
/**
diff --cc test/shared-version.test.js
index 00000000,dc13db58..77adce3c
mode 000000,100644..100644
--- a/test/shared-version.test.js
+++ b/test/shared-version.test.js
@@@ -1,0 -1,114 +1,130 @@@
+ /** 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 { chmodSync, 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');
+ const executables = join(dir, 'executables'); mkdirSync(executables);
+ writeFileSync(join(executables, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "$(git rev-parse --show-toplevel)/bin/pullboard.js" "$@"\n`);
+ chmodSync(join(executables, 'pullboard'), 0o755);
+ mkdirSync(root);
- for (const name of ['bin', 'src', 'skills', 'package.json']) cpSync(resolve(import.meta.dirname, '..', name), join(root, name), { recursive: true });
++ for (const name of ['bin', 'src', 'skills', 'package.json', 'CHANGELOG.md']) 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'), PATH: executables + ':' + process.env.PATH };
+ 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,
++ const supplied = original.replace(/export function relayPresentation\(root, \{ board: providedBoard = null \} = \{\}\) \{[\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);
+ });
++
++for (const [version, from, to] of [['SCHEMA_VERSION', 2, 3], ['EVENT_LOG_VERSION', 1, 2]]) {
++ test(`projectState refuses a linked-source ${version} upgrade despite caller isMain [A5,A6]`, t => {
++ const box = fixture(t); const before = box.versions(); box.bump(version, from, to);
++ const result = box.probe(`
++ import { projectState } from './src/serve.js';
++ try { projectState(${JSON.stringify(box.root)}, { isMain: true }); console.log(JSON.stringify({code:'OPENED'})); }
++ catch(error) { console.log(JSON.stringify({code:error.code})); }
++ `);
++ assert.equal(result.code, 'UNMERGED_SCHEMA', 'caller provenance must not override unmerged running source');
++ assert.deepEqual(box.versions(), before, 'the view projection leaves both persisted formats unchanged');
++ const primary = box.cli(box.root, box.root, 'status', '--json');
++ assert.equal(primary.status, 0, primary.stderr + primary.stdout);
++ assert.deepEqual(box.versions(), before, 'primary source remains able to open its board');
++ });
++}