Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(board): preserve shared schema from branch code [A5,A6,C7]

Corey Olson7551775931d2
diff --git a/src/board-schema.js b/src/board-schema.js
new file mode 100644
index 00000000..aa340696
--- /dev/null
+++ b/src/board-schema.js
@@ -0,0 +1,63 @@
+/** Compare a worktree's declaration with shared trunk schema without changing it [A5,A6,C7]. */
+import { DatabaseSync } from 'node:sqlite';
+import { existsSync, realpathSync } from 'node:fs';
+import { basename, dirname, join, resolve } from 'node:path';
+
+const reported = new Set();
+
+/** Identify the repository-shared board without treating arbitrary private test files as shared. */
+export function isRepositoryBoard(file) {
+ if (file === ':memory:') return false;
+ const canonical = existsSync(file) ? realpathSync(file) : resolve(file);
+ const parent = dirname(canonical);
+ return basename(canonical) === 'board.sqlite' && basename(parent) === 'pullboard'
+ && existsSync(join(dirname(parent), 'HEAD'));
+}
+
+/** Read declared column shapes and persistent machine triggers; TEMP guards are connection-local. */
+export function boardSchema(db) {
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all();
+ const columns = new Map();
+ for (const { name } of tables) {
+ for (const row of db.prepare(`PRAGMA table_info("${name.replaceAll('"', '""')}")`).all()) {
+ columns.set(`${name}.${row.name}`, JSON.stringify([row.type, row.notnull, row.dflt_value, row.pk]));
+ }
+ }
+ const triggers = new Map(db.prepare("SELECT name, sql FROM sqlite_master WHERE type='trigger' AND name LIKE 'machine%' ORDER BY name")
+ .all().map(row => [row.name, row.sql]));
+ return { columns, triggers };
+}
+
+/** Materialize this code's declaration only in memory, never in the repository-shared database. */
+export function declaredBoardSchema(initialize) {
+ const db = new DatabaseSync(':memory:');
+ try { initialize(db); return boardSchema(db); }
+ finally { db.close(); }
+}
+
+/** List exact missing, extra, and changed declarations in one actionable compatibility notice. */
+export function sharedSchemaDiagnostic(db, expected) {
+ const actual = boardSchema(db);
+ const differences = [];
+ for (const kind of ['columns', 'triggers']) {
+ const label = kind === 'columns' ? 'column' : 'trigger';
+ for (const [name, value] of expected[kind]) {
+ if (!actual[kind].has(name)) differences.push(`${label} only in this worktree: ${name}`);
+ else if (actual[kind].get(name) !== value) differences.push(`different ${label}: ${name}`);
+ }
+ for (const name of actual[kind].keys()) {
+ if (!expected[kind].has(name)) differences.push(`${label} only in shared board: ${name}`);
+ }
+ }
+ return differences.length ? `[SHARED_SCHEMA_DIFFERENCE] ${differences.join('; ')}. Continuing with the shared board's trunk schema and triggers; merge schema changes into the main checkout before installing them.` : null;
+}
+
+/** Send a fallback notice once per shared board and declaration in a long-lived non-CLI process. */
+export function reportSharedSchema(file, diagnostic, onDiagnostic) {
+ if (!diagnostic) return;
+ const key = resolve(file) + '\n' + diagnostic;
+ if (onDiagnostic) onDiagnostic(diagnostic);
+ else if (!reported.has(key)) process.stderr.write(`pullboard: ${diagnostic}\n`);
+ reported.add(key);
+ if (reported.size > 128) reported.delete(reported.values().next().value);
+}
diff --git a/src/board.js b/src/board.js
index 0b6717bc..1a04e5ea 100644
--- a/src/board.js
+++ b/src/board.js
@@ -21,7 +21,9 @@ import {
existsSync,
mkdirSync,
} from 'node:fs';
-import { dirname } from 'node:path';
+import { dirname, join } from 'node:path';
+import { codeIsFromMain } from './git.js';
+import { isRepositoryBoard, declaredBoardSchema, sharedSchemaDiagnostic, reportSharedSchema } from './board-schema.js';
import { DatabaseSync } from 'node:sqlite';
import { boardNotWritable } from './board-access.js';
import {
@@ -276,10 +278,11 @@ export function openBoardReadOnly(file) {
*
* @param {string} file
* @param {{ now: () => Date }} [clock]
- * @param {{ isMain?: boolean }} [options] Only the main checkout may upgrade a shared board.
+ * @param {{ isMain?: boolean, onDiagnostic?: (message: string) => void }} [options] Only the main checkout may upgrade a shared board.
* @returns {{ db: DatabaseSync, clock: { now: () => Date } }}
*/
-export function openBoard(file, clock = systemClock, { isMain } = {}) {
+export function openBoard(file, clock = systemClock, { isMain, onDiagnostic } = {}) {
+ if (isRepositoryBoard(file)) isMain = isMain !== false && codeIsFromMain();
if (file !== ':memory:' && isMain === false) {
let boardVersion = 0;
let logVersion = 0;
@@ -306,18 +309,32 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {
}
}
}
+ if (file !== ':memory:' && isMain === false && !existsSync(file)) {
+ // A fresh private fixture or single-checkout project has no shared schema to preserve.
+ // A linked repository must have its trunk initialize the common board.
+ if (isRepositoryBoard(file) && existsSync(join(dirname(dirname(file)), 'worktrees'))) {
+ throw new Refused('UNMERGED_SCHEMA', 'the shared board is missing; run pullboard status from the main checkout to initialize it before using this worktree');
+ }
+ isMain = true;
+ }
if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });
const startedAt = Date.now();
let db;
try {
db = new DatabaseSync(file);
db.exec(`PRAGMA busy_timeout = ${BOARD_BUSY_TIMEOUT_MS}`);
- if (file !== ':memory:') db.exec('PRAGMA journal_mode = WAL');
- migrateEventLogVersion(db);
- migrate(db);
- db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('board_id', randomBytes(16).toString('hex'));
+ if (file !== ':memory:' && isMain !== false) db.exec('PRAGMA journal_mode = WAL');
const board = { db, clock };
- guardStore(board);
+ if (isMain !== false || file === ':memory:') {
+ migrateEventLogVersion(db);
+ migrate(db);
+ db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('board_id', randomBytes(16).toString('hex'));
+ guardStore(board);
+ } else {
+ // Read compatibility before any local effect; persistent schema belongs to trunk alone.
+ readEventLogVersion(db);
+ reportSharedSchema(file, sharedSchemaDiagnostic(db, expectedBoardSchema()), onDiagnostic);
+ }
guardMoves(board);
return board;
} catch (error) {
@@ -326,6 +343,17 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {
}
}
+let expectedSchema;
+
+/** Cache this source's complete declaration using a private in-memory database, without touching trunk. */
+function expectedBoardSchema() {
+ return expectedSchema ??= declaredBoardSchema(db => {
+ db.exec(SCHEMA);
+ migrate(db);
+ for (const { sql } of storeTriggers()) db.exec(sql);
+ });
+}
+
/**
* Make this connection refuse any change to an item's status that does not come through moveItem
* (M1). A TEMP trigger, which lives only in this process's connection, lets the status column
diff --git a/src/cli.js b/src/cli.js
index 7a902224..be31446b 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -837,7 +837,16 @@ function configHere(info) {
* @returns {T}
*/
export function withBoard(ctx, work) {
- const board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade });
+ const board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade,
+ /** Report each source mismatch once through this invocation's text or JSON diagnostics. */
+ onDiagnostic(message) {
+ ctx.io.schemaDiagnostics ??= new Set();
+ const key = ctx.file + '\n' + message;
+ if (ctx.io.schemaDiagnostics.has(key)) return;
+ ctx.io.schemaDiagnostics.add(key);
+ ctx.io.err(message);
+ },
+ });
// Whether a proven flake stops blocking a landing is the coordinator's setting, read from accepted main on first use.
let quarantine;
board.quarantineEnabled = () => quarantine ??= mainPolicy(ctx.info.root).config.flakes?.quarantine === true;
diff --git a/test/api.test.js b/test/api.test.js
index cd422324..77d71c28 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -551,7 +551,10 @@ test('[A5, A6] a future-schema worktree cannot migrate the shared board; main ca
box.git(repo, 'worktree', 'add', '-q', unguarded, '-b', 'schema/unguarded', 'schema/future');
const guardedSource = join(unguarded, 'src/board.js');
const guardedText = readFileSync(guardedSource, 'utf8');
- const unguardedText = guardedText.replace(/ if \(file !== ':memory:' && isMain === false\) \{[\s\S]*?\n \}\n(?= if \(file !== ':memory:'\) mkdirSync)/, '');
+ const unguardedText = guardedText.replace(
+ " if (isRepositoryBoard(file)) isMain = isMain !== false && codeIsFromMain();",
+ ' isMain = true;',
+ );
assert.notEqual(unguardedText, guardedText, 'the mutation removes only the unmerged-schema guard');
writeFileSync(guardedSource, unguardedText);
const mutationProbe = join(unguarded, '.schema-mutation-probe.mjs');
@@ -1529,7 +1532,11 @@ test('one move recomputes only the items it touched [A2,N26]', async (t) => {
const legacy = new DatabaseSync(boardFile);
try { legacy.exec('DROP INDEX event_item_id_event_id; DROP INDEX verdict_item_id_verdict_id;'); }
finally { legacy.close(); }
- const migrated = openBoard(boardFile, undefined, { isMain: true });
+ // This positive migration control uses a private database; branch code cannot repair
+ // persistent indexes on the repository-shared board by supplying isMain: true.
+ const privateLegacy = join(box.dir, 'index-migration.sqlite');
+ cpSync(boardFile, privateLegacy);
+ const migrated = openBoard(privateLegacy);
try {
const restored = migrated.db.prepare("SELECT name FROM sqlite_master WHERE type = 'index'").all().map(({ name }) => name);
assert.ok(restored.includes('event_item_id_event_id'), 'reopening an existing board restores the event item index');
diff --git a/test/board.test.js b/test/board.test.js
index 17792513..1186e1ac 100644
--- a/test/board.test.js
+++ b/test/board.test.js
@@ -19,7 +19,7 @@ import { main } from '../src/cli.js';
import { briefFiles } from '../src/brief.js';
import { JSON_SHAPES } from '../src/json.js';
import { AUTO_ESCALATE_ENGINE, ENGINE_VERSION, STRONG_REJECTION_NOTICE_ENGINE } from '../src/machine.js';
-import { pathToFileURL } from 'node:url';
+import { pathToFileURL, fileURLToPath } from 'node:url';
import { unpackRelease } from './release-archive.js';
const HOUR = 3_600_000;
@@ -1250,6 +1250,8 @@ test('[O3] declared families travel from join through submit and verdict, and ab
writeFileSync(join(repo, 'SPEC.md'), '# Family test\n\n## G · Goals\n- G1 [approved, must] Families are recorded. | gate: true\n');
git(repo, 'add', '-A');
git(repo, 'commit', '-q', '-m', 'chore: initialize family test');
+ const initialBoard = await runMain(repo, ['status', '--json']);
+ assert.equal(initialBoard.code, 0, initialBoard.stderr || initialBoard.stdout);
const savedWorktreeModel = process.env.PULLBOARD_MODEL;
delete process.env.PULLBOARD_MODEL;
@@ -1455,3 +1457,16 @@ test('[O2,O3] family policy controls review order and refuses unknown or matchin
note: 'checked unknown verifier family',
}), /O2_FAMILY_MATCH/);
});
+
+
+// The helper copies real candidate source into an isolated Git repository and linked worktree.
+test("a branch worktree never changes the shared board's schema or triggers [A5,A6,C7]", async t => {
+ const { assertBranchWorktreeBoardIsolation } = await import('./branch-worktree-isolation.js');
+ await assertBranchWorktreeBoardIsolation(t, fileURLToPath(new URL('..', import.meta.url)));
+});
+
+
+test('direct branch board opens preserve shared DDL while private databases still migrate [A5,A6,C7]', async t => {
+ const { assertDirectOpenBoardIsolation } = await import('./direct-open-board-regression.js');
+ assertDirectOpenBoardIsolation(t, fileURLToPath(new URL('..', import.meta.url)));
+});
diff --git a/test/branch-worktree-isolation.js b/test/branch-worktree-isolation.js
new file mode 100644
index 00000000..cb3ab38c
--- /dev/null
+++ b/test/branch-worktree-isolation.js
@@ -0,0 +1,139 @@
+/** Private-Git regression helper for a branch source whose unversioned DDL must not install [A5,A6,C7]. */
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+
+/** Run an isolated fixture command and retain both streams for a precise assertion. */
+function run(command, args, cwd, env) {
+ return spawnSync(command, args, { cwd, env, encoding: 'utf8' });
+}
+
+/** Create a real branch worktree with a same-version DDL/trigger delta and exercise shared-board operations. */
+export async function assertBranchWorktreeBoardIsolation(t, sourceRoot) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-branch-board-isolation-'));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const repo = join(directory, 'repo');
+ const branch = join(directory, 'branch');
+ mkdirSync(repo);
+ for (const name of ['bin', 'src', 'skills', 'package.json', 'CHANGELOG.md']) cpSync(resolve(sourceRoot, name), join(repo, name), { recursive: true });
+ writeFileSync(join(repo, 'pullboard.json'), `${JSON.stringify({
+ gate: 'true', spec: 'SPEC.md', practice: 'PRACTICE.md',
+ lanes: { web: { owns: ['web/'], specs: [] } }, shared: [],
+ }, null, 2)}\n`);
+ writeFileSync(join(repo, 'SPEC.md'), '# Worktree schema fixture\n\n## G · Goals\n- G1 [approved, must] Keep the shared board stable. | gate: true\n');
+ writeFileSync(join(repo, 'PRACTICE.md'), '');
+ const env = { ...process.env,
+ HOME: join(directory, 'home'), PULLBOARD_HOME: join(directory, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(directory, 'machine-home'),
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Board Isolation Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Board Isolation Fixture', GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ for (const name of Object.keys(env)) if (name.startsWith('GIT_') && !name.startsWith('GIT_CONFIG_')
+ && !name.startsWith('GIT_AUTHOR_') && !name.startsWith('GIT_COMMITTER_')) delete env[name];
+
+ /** Execute a real private Git operation without bypassing installed hooks. */
+ const gitAt = (cwd, ...args) => {
+ const result = run('git', args, cwd, env);
+ assert.equal(result.status, 0, result.stderr + result.stdout);
+ return result.stdout.trim();
+ };
+ /** Use the primary private repository for setup. */
+ const git = (...args) => gitAt(repo, ...args);
+ /** Run the chosen checkout's real command in a fresh process. */
+ const cli = (cwd, ...args) => run(process.execPath,
+ [join(cwd, 'bin/pullboard.js'), ...args, '--json'], cwd, env);
+ git('init', '-q', '-b', 'main');
+ git('add', '-A');
+ git('commit', '-q', '-m', 'chore: initialize board isolation fixture');
+
+ const initialized = cli(repo, 'init');
+ assert.equal(initialized.status, 0, initialized.stderr + initialized.stdout);
+ const linked = run('git', ['worktree', 'add', '-q', '-b', 'schema/drift', branch, 'main'], repo, env);
+ assert.equal(linked.status, 0, linked.stderr + linked.stdout);
+ const joined = cli(branch, 'join', 'web', '--model', 'fixture-worker');
+ assert.equal(joined.status, 0, joined.stderr + joined.stdout);
+ const joinedDocument = JSON.parse(joined.stdout);
+ const added = cli(repo, 'add', 'web', 'shared schema fixture item', '--criterion', 'the branch claim uses the shared board');
+ assert.equal(added.status, 0, added.stderr + added.stdout);
+ const itemId = JSON.parse(added.stdout).item.item_id;
+
+ const boardFile = join(repo, '.git', 'pullboard', 'board.sqlite');
+ /** Observe persistent DDL and ordinary effects through a read-only connection. */
+ const footprint = () => {
+ const db = new DatabaseSync(boardFile, { readOnly: true });
+ try {
+ return {
+ schemaVersion: db.prepare('PRAGMA user_version').get().user_version,
+ schemaCookie: db.prepare('PRAGMA schema_version').get().schema_version,
+ itemColumns: db.prepare('PRAGMA table_info(item)').all().map(column => column.name),
+ schemaObjects: db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name").all(),
+ triggers: db.prepare("SELECT name, sql FROM sqlite_master WHERE type='trigger' AND name LIKE 'machine%' ORDER BY name").all(),
+ item: db.prepare('SELECT item_id, item_status, item_owner FROM item WHERE item_id=?').get(itemId),
+ eventCount: db.prepare('SELECT count(*) AS n FROM event').get().n,
+ };
+ } finally { db.close(); }
+ };
+ const before = footprint();
+
+ const boardFileInBranch = join(branch, 'src', 'board.js');
+ const boardSource = readFileSync(boardFileInBranch, 'utf8');
+ const migration = " ['item', 'item_after', \"TEXT NOT NULL DEFAULT ''\"],";
+ assert.ok(boardSource.includes(migration), 'the candidate source contains the stable migration insertion point');
+ assert.match(boardSource, /export const SCHEMA_VERSION = \d+;/u);
+ assert.match(boardSource, /export const EVENT_LOG_VERSION = \d+;/u);
+ const branchBoardSource = boardSource.replace(migration,
+ `${migration}\n ['item', 'item_branch_probe', \"TEXT NOT NULL DEFAULT ''\"],`);
+ assert.notEqual(branchBoardSource, boardSource);
+ writeFileSync(boardFileInBranch, branchBoardSource);
+
+ const machineFileInBranch = join(branch, 'src', 'machine.js');
+ const machineSource = readFileSync(machineFileInBranch, 'utf8');
+ const triggerBody = "refuse('UNDECLARED_MOVE', `the moves are ${moves.join(', ')}`)";
+ const branchTriggerBody = "refuse('UNDECLARED_MOVE', `branch fixture moves are ${moves.join(', ')}`)";
+ assert.ok(machineSource.includes(triggerBody), 'the candidate machine source contains the named move-trigger clause');
+ writeFileSync(machineFileInBranch, machineSource.replace(triggerBody, branchTriggerBody));
+ const commonMain = gitAt(repo, 'rev-parse', '--path-format=absolute', '--git-common-dir');
+ const commonBranch = gitAt(branch, 'rev-parse', '--path-format=absolute', '--git-common-dir');
+ const dirMain = gitAt(repo, 'rev-parse', '--path-format=absolute', '--git-dir');
+ const dirBranch = gitAt(branch, 'rev-parse', '--path-format=absolute', '--git-dir');
+ assert.equal(commonMain, commonBranch, 'the real linked worktree shares the main Git common directory');
+ assert.notEqual(dirMain, dirBranch, 'the source roots have distinct Git directories');
+
+ const afterJoin = footprint();
+ assert.deepEqual({ schemaVersion: afterJoin.schemaVersion, schemaCookie: afterJoin.schemaCookie, itemColumns: afterJoin.itemColumns, schemaObjects: afterJoin.schemaObjects, triggers: afterJoin.triggers },
+ { schemaVersion: before.schemaVersion, schemaCookie: before.schemaCookie, itemColumns: before.itemColumns, schemaObjects: before.schemaObjects, triggers: before.triggers },
+ 'fixture setup and branch source commit did not alter the native board DDL');
+
+ const read = cli(branch, 'status');
+ assert.equal(read.status, 0, read.stderr + read.stdout);
+ const readDocument = JSON.parse(read.stdout);
+ assert.equal(readDocument.version, 1);
+ const afterRead = footprint();
+ assert.deepEqual({ schemaVersion: afterRead.schemaVersion, schemaCookie: afterRead.schemaCookie, itemColumns: afterRead.itemColumns, schemaObjects: afterRead.schemaObjects, triggers: afterRead.triggers },
+ { schemaVersion: before.schemaVersion, schemaCookie: before.schemaCookie, itemColumns: before.itemColumns, schemaObjects: before.schemaObjects, triggers: before.triggers },
+ 'branch read did not install its migration column or trigger SQL');
+ assert.equal(afterRead.eventCount, before.eventCount, 'a read changes no shared board events');
+
+ const move = cli(branch, 'claim', String(itemId));
+ assert.equal(move.status, 0, move.stderr + move.stdout);
+ assert.equal(JSON.parse(move.stdout).id, itemId, 'the ordinary branch move returns its shared item');
+ const afterMove = footprint();
+ assert.deepEqual({ schemaVersion: afterMove.schemaVersion, schemaCookie: afterMove.schemaCookie, itemColumns: afterMove.itemColumns, schemaObjects: afterMove.schemaObjects, triggers: afterMove.triggers },
+ { schemaVersion: before.schemaVersion, schemaCookie: before.schemaCookie, itemColumns: before.itemColumns, schemaObjects: before.schemaObjects, triggers: before.triggers },
+ 'normal move preserved main schema and machine triggers');
+ assert.equal(afterMove.eventCount, before.eventCount + 1, 'the ordinary claim has a normal shared-board event effect');
+ assert.equal(afterMove.item.item_status, 'claimed');
+ assert.equal(afterMove.item.item_owner, joinedDocument.agent);
+
+ for (const result of [read, move]) {
+ const output = [result.stdout, result.stderr].join('\n');
+ assert.equal(output.match(/item_branch_probe/gu)?.length ?? 0, 1,
+ 'one diagnostic per invocation names the uninstalled column exactly once');
+ assert.equal(output.match(/machine_item_move/gu)?.length ?? 0, 1,
+ 'the same diagnostic names the changed machine trigger exactly once');
+ }
+}
diff --git a/test/direct-open-board-regression.js b/test/direct-open-board-regression.js
new file mode 100644
index 00000000..a14f0ad0
--- /dev/null
+++ b/test/direct-open-board-regression.js
@@ -0,0 +1,171 @@
+/** Exercise the public no-options board opener from branch code on shared and private files [A5,A6,C7]. */
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+
+/** Run an isolated fixture command and retain its output for precise assertions. */
+function run(command, args, cwd, env) {
+ return spawnSync(command, args, { cwd, env, encoding: 'utf8' });
+}
+
+/**
+ * Prove direct openBoard calls distinguish the repository-shared file from a private database.
+ * The branch source adds same-version DDL and changes one machine trigger before opening either.
+ *
+ * @param {{ after: (cleanup: () => void) => void }} t
+ * @param {string} sourceRoot
+ */
+export function assertDirectOpenBoardIsolation(t, sourceRoot) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-direct-open-board-'));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const main = join(directory, 'repo');
+ const branch = join(directory, 'branch');
+ mkdirSync(main);
+ for (const name of ['bin', 'src', 'skills', 'package.json', 'CHANGELOG.md']) {
+ cpSync(resolve(sourceRoot, name), join(main, name), { recursive: true });
+ }
+ writeFileSync(join(main, 'pullboard.json'), `${JSON.stringify({
+ gate: 'true',
+ spec: 'SPEC.md',
+ lanes: { web: { owns: ['web/'], specs: [] } },
+ shared: [],
+ }, null, 2)}\n`);
+ writeFileSync(join(main, 'SPEC.md'), '# Direct opener fixture\n\n## G · Goals\n- G1 [approved, must] Keep shared DDL stable. | gate: true\n');
+ const env = {
+ ...process.env,
+ HOME: join(directory, 'home'),
+ PULLBOARD_HOME: join(directory, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(directory, 'machine-home'),
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Direct Opener Fixture',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Direct Opener Fixture',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ for (const name of Object.keys(env)) {
+ if (name.startsWith('GIT_') && !name.startsWith('GIT_CONFIG_')
+ && !name.startsWith('GIT_AUTHOR_') && !name.startsWith('GIT_COMMITTER_')) delete env[name];
+ }
+ /** Require each real private Git operation to succeed. */
+ const git = (cwd, ...args) => {
+ const result = run('git', args, cwd, env);
+ assert.equal(result.status, 0, result.stderr + result.stdout);
+ return result.stdout.trim();
+ };
+ /** Run each checkout source independently under the private environment. */
+ const cli = (cwd, ...args) => run(process.execPath, [join(cwd, 'bin/pullboard.js'), ...args, '--json'], cwd, env);
+
+ git(main, 'init', '-q', '-b', 'main');
+ git(main, 'add', '-A');
+ git(main, 'commit', '-q', '-m', 'chore: initialize direct opener fixture');
+ const initialized = cli(main, 'status');
+ assert.equal(initialized.status, 0, initialized.stderr + initialized.stdout);
+ const linked = run('git', ['worktree', 'add', '-q', '-b', 'schema/drift', branch, 'main'], main, env);
+ assert.equal(linked.status, 0, linked.stderr + linked.stdout);
+
+ const joined = cli(branch, 'join', 'web', '--model', 'fixture-worker');
+ assert.equal(joined.status, 0, joined.stderr + joined.stdout);
+ const { agent } = JSON.parse(joined.stdout);
+ const added = cli(main, 'add', 'web', 'direct opener shared move', '--criterion', 'the direct branch opener uses the native board');
+ assert.equal(added.status, 0, added.stderr + added.stdout);
+ const itemId = JSON.parse(added.stdout).item.item_id;
+ const sharedFile = join(main, '.git', 'pullboard', 'board.sqlite');
+ const privateFile = join(directory, 'private.sqlite');
+
+ const boardSourcePath = join(branch, 'src', 'board.js');
+ const originalBoardSource = readFileSync(boardSourcePath, 'utf8');
+ const migration = " ['item', 'item_after', \"TEXT NOT NULL DEFAULT ''\"],";
+ assert.ok(originalBoardSource.includes(migration), 'candidate source contains the stable migration insertion point');
+ const driftedBoardSource = originalBoardSource.replace(migration,
+ `${migration}\n ['item', 'item_branch_probe', \"TEXT NOT NULL DEFAULT ''\"],`);
+ assert.notEqual(driftedBoardSource, originalBoardSource);
+ writeFileSync(boardSourcePath, driftedBoardSource);
+ const machineSourcePath = join(branch, 'src', 'machine.js');
+ const originalMachineSource = readFileSync(machineSourcePath, 'utf8');
+ const triggerBody = "refuse('UNDECLARED_MOVE', `the moves are ${moves.join(', ')}`)";
+ const branchTriggerBody = "refuse('UNDECLARED_MOVE', `branch fixture moves are ${moves.join(', ')}`)";
+ assert.ok(originalMachineSource.includes(triggerBody), 'candidate trigger source contains the expected clause');
+ writeFileSync(machineSourcePath, originalMachineSource.replace(triggerBody, branchTriggerBody));
+ git(branch, 'add', 'src/board.js', 'src/machine.js');
+ git(branch, 'commit', '-q', '-m', 'feat: simulate branch-local schema declarations');
+
+ /** Observe shared DDL and effect evidence without invoking an opener. */
+ const footprint = (file, id = null) => {
+ const db = new DatabaseSync(file, { readOnly: true });
+ try {
+ return {
+ version: db.prepare('PRAGMA user_version').get().user_version,
+ schemaCookie: db.prepare('PRAGMA schema_version').get().schema_version,
+ columns: db.prepare('PRAGMA table_info(item)').all().map(row => row.name),
+ triggers: db.prepare("SELECT name, sql FROM sqlite_master WHERE type='trigger' AND name LIKE 'machine%' ORDER BY name").all(),
+ ...(id === null ? {} : { item: db.prepare('SELECT item_id, item_status, item_owner FROM item WHERE item_id=?').get(id) }),
+ events: db.prepare('SELECT count(*) AS n FROM event').get().n,
+ };
+ } finally { db.close(); }
+ };
+ const sharedBefore = footprint(sharedFile, itemId);
+
+ // Create a separate normal board from main code. The branch's new migration and trigger must
+ // still install here; only the repository-shared path is protected from unmerged declarations.
+ const createPrivate = run(process.execPath, ['--input-type=module', '-e', `
+ import { openBoard, closeBoard } from './src/board.js';
+ const board = openBoard(${JSON.stringify(privateFile)});
+ closeBoard(board);
+ `], main, env);
+ assert.equal(createPrivate.status, 0, createPrivate.stderr + createPrivate.stdout);
+ const privateBefore = footprint(privateFile);
+ assert.ok(!privateBefore.columns.includes('item_branch_probe'));
+ assert.ok(!privateBefore.triggers.find(row => row.name === 'machine_item_move').sql.includes('branch fixture moves'));
+
+ // This is deliberately a direct API caller: no options object and no CLI wrapper supplying
+ // isMain. It reads and performs an ordinary claim using the existing main-board schema.
+ const directProbe = run(process.execPath, ['--input-type=module', '-e', `
+ import { openBoard, closeBoard, getItem, claim } from './src/board.js';
+ const board = openBoard(${JSON.stringify(sharedFile)});
+ try {
+ const before = getItem(board, ${itemId});
+ const result = claim(board, ${itemId}, {
+ agentId: ${JSON.stringify(agent)}, lane: 'web', leaseMs: 3600000,
+ freeze: item => ({ text: item.item_title, digest: 'fixture:' + item.item_title }),
+ });
+ const after = getItem(board, ${itemId});
+ console.log(JSON.stringify({ before: before.item_status, result, after: after.item_status, owner: after.item_owner }));
+ } finally { closeBoard(board); }
+ `], branch, env);
+ assert.equal(directProbe.status, 0, directProbe.stderr + directProbe.stdout);
+ const directResult = JSON.parse(directProbe.stdout);
+ assert.equal(directResult.before, 'open');
+ assert.equal(directResult.after, 'claimed');
+ assert.equal(directResult.owner, agent);
+ assert.match(directProbe.stderr, /item_branch_probe/u);
+ assert.match(directProbe.stderr, /machine_item_move/u);
+ assert.equal(directProbe.stderr.match(/item_branch_probe/gu)?.length ?? 0, 1,
+ 'one direct open emits one diagnostic naming the uninstalled migration column');
+ assert.equal(directProbe.stderr.match(/machine_item_move/gu)?.length ?? 0, 1,
+ 'one direct open emits one diagnostic naming the changed trigger');
+
+ const sharedAfter = footprint(sharedFile, itemId);
+ assert.equal(sharedAfter.version, sharedBefore.version);
+ assert.equal(sharedAfter.schemaCookie, sharedBefore.schemaCookie,
+ 'the direct branch read-and-move made no shared schema changes');
+ assert.deepEqual(sharedAfter.columns, sharedBefore.columns);
+ assert.deepEqual(sharedAfter.triggers, sharedBefore.triggers);
+ assert.equal(sharedAfter.events, sharedBefore.events + 1, 'the normal claim still has its shared-board effect');
+
+ const privateProbe = run(process.execPath, ['--input-type=module', '-e', `
+ import { openBoard, closeBoard } from './src/board.js';
+ const board = openBoard(${JSON.stringify(privateFile)});
+ closeBoard(board);
+ `], branch, env);
+ assert.equal(privateProbe.status, 0, privateProbe.stderr + privateProbe.stdout);
+ const privateAfter = footprint(privateFile);
+ assert.ok(privateAfter.columns.includes('item_branch_probe'),
+ 'a private database still receives the branch migration');
+ assert.ok(privateAfter.triggers.find(row => row.name === 'machine_item_move').sql.includes('branch fixture moves'),
+ 'a private database still receives the branch machine trigger declaration');
+ assert.equal(privateAfter.version, privateBefore.version, 'same-version private migration remains supported');
+}