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): a read opens the board read-only, no lock [C7]

Corey Olson4dc2a57875dc
diff --git a/src/api.js b/src/api.js
index 900af9ea..0a5ef02b 100644
--- a/src/api.js
+++ b/src/api.js
@@ -664,7 +664,11 @@ const VERSION = 1;
function withBoard(root, read, isMain) {
const info = repoInfo(root);
loadConfig(info.root);
- const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: isMain !== false && codeIsFromMain() });
+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');
+ // A read takes no write lock and runs no migration (#1047); a read that writes after all runs again on a write open.
+ const current = store.openCurrentBoardReadOnly(file);
+ if (current) try { return read(current, info); } catch (error) { if (!store.writeRefused(error)) throw error; } finally { store.closeBoard(current); }
+ const board = store.openBoard(file, undefined, { isMain: isMain !== false && codeIsFromMain() });
try { return read(board, info); } finally { store.closeBoard(board); }
}
diff --git a/src/board-migrate.js b/src/board-migrate.js
new file mode 100644
index 00000000..d5f7e6c0
--- /dev/null
+++ b/src/board-migrate.js
@@ -0,0 +1,108 @@
+/**
+ * The board's column migration and the digest that says a board needs none [C7].
+ *
+ * Why: opening the board for every command ran the schema, 23 PRAGMA table_info and an insert under
+ * the write lock, so a read waited out any writer (3.5 s behind a 3 s hold). A board stamped with
+ * this code's stamp and user_version skips all of it, and a read opens the file read-only.
+ */
+import { createHash } from 'node:crypto';
+
+/** Columns added after a board's first schema, in the order an older board gains them. */
+const ADDED_COLUMNS = [
+ ['item', 'item_after', "TEXT NOT NULL DEFAULT ''"],
+ ['item', 'item_brief', "TEXT NOT NULL DEFAULT ''"],
+ ['item', 'item_route', "TEXT NOT NULL DEFAULT 'strong'"],
+ ['item', 'item_check', "TEXT NOT NULL DEFAULT ''"],
+ ['agent', 'agent_route', "TEXT NOT NULL DEFAULT 'strong'"],
+ ['agent', 'agent_family', 'TEXT'],
+ ['item', 'item_builder_family', 'TEXT'],
+ ['verdict', 'verdict_verifier_family', 'TEXT'],
+ ['item', 'item_claim_head', 'TEXT'],
+ ['item', 'item_files', "TEXT NOT NULL DEFAULT ''"],
+ ['item', 'item_review_by', 'TEXT'],
+ ['item', 'item_review_until', 'TEXT'],
+ ['item', 'item_hold_reason', 'TEXT'],
+ ['item', 'item_hold_by', 'TEXT'],
+ ['item', 'item_hold_at', 'TEXT'],
+ ['shout', 'shout_decision', 'INTEGER NOT NULL DEFAULT 0'],
+ ['shout', 'shout_answers', 'INTEGER'],
+ ['shout', 'shout_evidence_kind', 'TEXT'],
+ ['shout', 'shout_evidence_outcome', 'TEXT'],
+ ['shout', 'shout_evidence_item', 'INTEGER'],
+ ['shout', 'shout_evidence_commit', 'TEXT'],
+ ['shout', 'shout_request', 'INTEGER NOT NULL DEFAULT 0'],
+ ['shout', 'shout_request_outcome', "TEXT NOT NULL DEFAULT ''"],
+];
+
+/**
+ * Bring a board made by an older version up to the current schema, one added column at a time, so
+ * an upgrade never needs a fresh board.
+ *
+ * @param {import('node:sqlite').DatabaseSync} db
+ */
+export function migrate(db) {
+ for (const [table, column, type] of ADDED_COLUMNS) {
+ const columns = db.prepare(`PRAGMA table_info(${table})`).all().map((entry) => entry.name);
+ if (!columns.includes(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
+ }
+}
+
+/**
+ * A digest of everything a migration applies: the schema text, the added columns and the event log
+ * version. Why: a new index or column changes it, so a board stamped by older code migrates once.
+ *
+ * @param {string} schema
+ * @param {number} eventLogVersion
+ * @returns {string}
+ */
+export function schemaDigest(schema, eventLogVersion) {
+ return createHash('sha256').update(JSON.stringify([schema, ADDED_COLUMNS, eventLogVersion])).digest('hex');
+}
+
+/**
+ * A nonzero 32-bit stamp of this code's schema digest and the board's actual shape: every table,
+ * index and trigger as SQLite stores it, its event log version and whether it has an id. Why: a
+ * dropped index, a lost trigger or an older event log changes it, so a damaged board still heals.
+ *
+ * @param {import('node:sqlite').DatabaseSync} db
+ * @param {string} digest
+ * @returns {number}
+ */
+function schemaStamp(db, digest) {
+ const shape = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name").all();
+ const meta = shape.some((entry) => entry.type === 'table' && entry.name === 'board_meta')
+ ? db.prepare("SELECT meta_key, meta_value FROM board_meta WHERE meta_key IN ('board_id', 'event_log_version') ORDER BY meta_key").all()
+ .map((entry) => (entry.meta_key === 'board_id' ? 'board_id' : entry.meta_value))
+ : [];
+ return createHash('sha256').update(JSON.stringify([digest, shape, meta])).digest().readInt32BE(0) || 1;
+}
+
+/**
+ * True when the board already carries this code's schema: its user_version is current and its
+ * PRAGMA application_id holds the stamp of `digest` and its present shape. Reads only, so it takes
+ * no write lock. The stamp lives in the file header, not in board_meta, so exports never see it.
+ *
+ * @param {import('node:sqlite').DatabaseSync} db
+ * @param {string} digest
+ * @param {number} schemaVersion
+ * @returns {boolean}
+ */
+export function boardIsCurrent(db, digest, schemaVersion) {
+ if (db.prepare('PRAGMA user_version').get().user_version < schemaVersion) return false;
+ return db.prepare('PRAGMA application_id').get().application_id === schemaStamp(db, digest);
+}
+
+/**
+ * Stamp the board once its migration and trigger audit have run.
+ *
+ * @param {import('node:sqlite').DatabaseSync} db
+ * @param {string} digest
+ */
+export function recordSchemaStamp(db, digest) {
+ db.exec(`PRAGMA application_id = ${schemaStamp(db, digest)}`);
+}
+
+/** True when SQLite refused a write because the board was opened read-only. */
+export function writeRefused(error) {
+ return (error?.errcode & 0xff) === 8;
+}
diff --git a/src/board.js b/src/board.js
index 0b6717bc..e476dd44 100644
--- a/src/board.js
+++ b/src/board.js
@@ -24,6 +24,13 @@ import {
import { dirname } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { boardNotWritable } from './board-access.js';
+import {
+ boardIsCurrent,
+ migrate,
+ recordSchemaStamp,
+ schemaDigest,
+} from './board-migrate.js';
+export { writeRefused } from './board-migrate.js';
import {
briefFiles,
briefSections,
@@ -254,6 +261,23 @@ const SCHEMA = `
);
`;
+/** This code's schema digest: a board stamped with it and its present shape needs no migration. */
+const SCHEMA_DIGEST = schemaDigest(SCHEMA, EVENT_LOG_VERSION);
+
+/**
+ * Open the board for a command that only reads: read-only, with no write lock and no migration, so
+ * a writer holding the lock never stalls it (#1047). Null when there is no board yet or it needs a
+ * migration, which only a write open runs.
+ */
+export function openCurrentBoardReadOnly(file, clock = systemClock) {
+ if (file === ':memory:' || !existsSync(file)) return null;
+ const db = openBoardReadOnly(file);
+ let current = false;
+ try { current = boardIsCurrent(db, SCHEMA_DIGEST, SCHEMA_VERSION); }
+ finally { if (!current) db.close(); }
+ return current ? { db, clock, readOnly: true } : null;
+}
+
/** Open an existing board without migrations, waiting for the same locks as openBoard. */
export function openBoardReadOnly(file) {
const startedAt = Date.now();
@@ -313,11 +337,15 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {
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'));
+ // A board this code already migrated skips the migration, its write lock and the trigger audit (#1047).
+ const current = boardIsCurrent(db, SCHEMA_DIGEST, SCHEMA_VERSION);
+ if (!current) {
+ migrateEventLogVersion(db);
+ migrate(db);
+ db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run('board_id', randomBytes(16).toString('hex'));
+ }
const board = { db, clock };
- guardStore(board);
+ if (!current) { guardStore(board); recordSchemaStamp(db, SCHEMA_DIGEST); }
guardMoves(board);
return board;
} catch (error) {
@@ -385,44 +413,6 @@ function guardStore(board) {
});
}
-/**
- * Bring a board made by an older version up to the current schema, one added column at a time, so
- * an upgrade never needs a fresh board.
- *
- * @param {DatabaseSync} db
- */
-function migrate(db) {
- const added = [
- ['item', 'item_after', "TEXT NOT NULL DEFAULT ''"],
- ['item', 'item_brief', "TEXT NOT NULL DEFAULT ''"],
- ['item', 'item_route', "TEXT NOT NULL DEFAULT 'strong'"],
- ['item', 'item_check', "TEXT NOT NULL DEFAULT ''"],
- ['agent', 'agent_route', "TEXT NOT NULL DEFAULT 'strong'"],
- ['agent', 'agent_family', 'TEXT'],
- ['item', 'item_builder_family', 'TEXT'],
- ['verdict', 'verdict_verifier_family', 'TEXT'],
- ['item', 'item_claim_head', 'TEXT'],
- ['item', 'item_files', "TEXT NOT NULL DEFAULT ''"],
- ['item', 'item_review_by', 'TEXT'],
- ['item', 'item_review_until', 'TEXT'],
- ['item', 'item_hold_reason', 'TEXT'],
- ['item', 'item_hold_by', 'TEXT'],
- ['item', 'item_hold_at', 'TEXT'],
- ['shout', 'shout_decision', 'INTEGER NOT NULL DEFAULT 0'],
- ['shout', 'shout_answers', 'INTEGER'],
- ['shout', 'shout_evidence_kind', 'TEXT'],
- ['shout', 'shout_evidence_outcome', 'TEXT'],
- ['shout', 'shout_evidence_item', 'INTEGER'],
- ['shout', 'shout_evidence_commit', 'TEXT'],
- ['shout', 'shout_request', 'INTEGER NOT NULL DEFAULT 0'],
- ['shout', 'shout_request_outcome', "TEXT NOT NULL DEFAULT ''"],
- ];
- for (const [table, column, type] of added) {
- const columns = db.prepare(`PRAGMA table_info(${table})`).all().map((entry) => entry.name);
- if (!columns.includes(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
- }
-}
-
/**
* Read the persisted event format without migrating it, so integrity checks enforce the same
* compatibility rule as the writable opener while leaving older or damaged evidence intact.
diff --git a/src/cli.js b/src/cli.js
index 7a902224..305ddc29 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -834,10 +834,10 @@ function configHere(info) {
* @template T
* @param {any} ctx
* @param {(board: any) => T} work
+ * @param {any} [board] an already-open board, as withBoardRead passes
* @returns {T}
*/
-export function withBoard(ctx, work) {
- const board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade });
+export function withBoard(ctx, work, board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade })) {
// 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;
@@ -859,6 +859,18 @@ export function withBoard(ctx, work) {
return result;
}
+/**
+ * withBoard for a command that only reads: the board opens read-only, without the write lock or a
+ * migration (#1047). A board that needs a migration, or work that writes after all (a first
+ * coordinator registration), runs again through withBoard; SQLite refused the write, so nothing ran twice.
+ */
+export function withBoardRead(ctx, work) {
+ const board = store.openCurrentBoardReadOnly(ctx.file, ctx.clock);
+ if (!board) return withBoard(ctx, work);
+ try { return withBoard(ctx, work, board); }
+ catch (error) { if (store.writeRefused(error)) return withBoard(ctx, work); throw error; }
+}
+
/**
* Reserve a new row's id on the board in one write transaction before any file names it, so writers
* that plan the same id at the same moment get distinct ids (#878). written: the caller writes the row
@@ -2001,7 +2013,7 @@ export function sayReviewOffer(ctx, found) {
const offer = { item: found.item.item_id, command, queue: found.offer.queue, ratio: found.offer.ratio };
ctx.io.result?.({ item: found.item, review: true, held: false, shared: [], offer, build: found.build });
ctx.io.say(`${reviewQueueLine(ctx, offer.queue, span)}; ratio ${offer.ratio} reached (zero active reviewers counts as one)`);
- const agents = withBoard(ctx, (board) => store.listAgents(board));
+ const agents = withBoardRead(ctx, (board) => store.listAgents(board));
ctx.io.say(`review offered: #${found.item.item_id} ${found.item.item_title}, built by ${agentDisplayName(agents, ctx.config, found.item.item_built_by)}; reserve it explicitly: ${command}`);
if (found.build) ctx.io.say(`build available: #${found.build.item_id} ${found.build.item_title}; claim it explicitly: pullboard next --build`);
else ctx.io.say('no build is currently free in your lane; this review is available');
@@ -2015,7 +2027,7 @@ export function sayReviewOffer(ctx, found) {
* @param {any} ctx
*/
export function refuseWhileBuilding(ctx) {
- const building = withBoard(ctx, (board) => {
+ const building = withBoardRead(ctx, (board) => {
const me = whoAmI(ctx, board).id;
const items = store.listItems(board);
if (items.some((item) => item.item_status === 'submitted' && item.item_built_by !== me)) return [];
diff --git a/src/commands/decisions.js b/src/commands/decisions.js
index 0bc298bc..38ea3d4e 100644
--- a/src/commands/decisions.js
+++ b/src/commands/decisions.js
@@ -7,13 +7,13 @@ import {
personMode,
span,
whoAmI,
- withBoard,
+ withBoardRead,
} from '../cli.js';
/** Run `pullboard decisions` and return its exit code. */
export function run(io, { values }) {
const ctx = context(io);
- const { asks, agents } = withBoard(ctx, (board) => {
+ const { asks, agents } = withBoardRead(ctx, (board) => {
const me = whoAmI(ctx, board);
const asPerson = personMode(ctx, me, values);
return { asks: store.openDecisions(board, asPerson ? 'person' : [me.id, me.lane]), agents: store.listAgents(board) };
diff --git a/src/commands/list.js b/src/commands/list.js
index 0271f8bd..f1cf9d51 100644
--- a/src/commands/list.js
+++ b/src/commands/list.js
@@ -10,13 +10,13 @@ import {
agentDisplayName,
context,
itemLine,
- withBoard,
+ withBoardRead,
} from '../cli.js';
/** Run `pullboard list` and return its exit code. */
export function run(io, { first, values }) {
const ctx = context(io);
- const { items, agents, merging } = withBoard(ctx, (board) => ({
+ const { items, agents, merging } = withBoardRead(ctx, (board) => ({
items: store.listItems(board, { lane: first, all: values.all }).map(verdictProjector(ctx.info.root, board).project),
agents: store.listAgents(board), merging: new Set(store.listItems(board, { lane: first }).filter((item) => mainMergeFor(board, item.item_id)).map((item) => item.item_id)),
}));
diff --git a/src/commands/log.js b/src/commands/log.js
index 6af747be..9f71df0e 100644
--- a/src/commands/log.js
+++ b/src/commands/log.js
@@ -4,14 +4,14 @@ import {
agentDisplayName,
context,
idArg,
- withBoard,
+ withBoardRead,
} from '../cli.js';
/** Run `pullboard log` and return its exit code. */
export function run(io, { first }) {
const ctx = context(io);
const itemId = first ? idArg(first) : undefined;
- const { rows, agents } = withBoard(ctx, (board) => ({ rows: store.events(board, { itemId }), agents: store.listAgents(board) }));
+ const { rows, agents } = withBoardRead(ctx, (board) => ({ rows: store.events(board, { itemId }), agents: store.listAgents(board) }));
io.result?.({ events: rows });
rows.forEach((event) => io.say(`${event.event_at.slice(0, 19)} ${agentDisplayName(agents, ctx.config, event.event_by).padEnd(24)} ${event.event_kind.padEnd(9)} ${event.item_id ? `#${event.item_id}` : ''} ${event.event_detail === '{}' ? '' : event.event_detail}`.trimEnd()));
return 0;
diff --git a/src/commands/next.js b/src/commands/next.js
index 2be7a27f..b2c8e57f 100644
--- a/src/commands/next.js
+++ b/src/commands/next.js
@@ -23,6 +23,7 @@ import {
sayReviewOffer,
span,
withBoard,
+ withBoardRead,
} from '../cli.js';
/**
@@ -57,7 +58,7 @@ export async function nextHere(io, values) {
if (found.item) {
if (found.offer) { sayReviewOffer(ctx, found); return 0; }
const item = found.item;
- const agents = withBoard(ctx, (board) => store.listAgents(board));
+ const agents = withBoardRead(ctx, (board) => store.listAgents(board));
io.result?.({ item, review: Boolean(values.verify), held: Boolean(found.held), shared: found.shared ?? [], reasons: found.reasons ?? [], ...(found.seat ? { seat: found.seat } : {}) });
for (const reason of found.reasons ?? []) io.say(displayedWait(reason, agents, ctx.config));
const here = cdTo(ctx.info.root);
@@ -84,7 +85,7 @@ export async function nextHere(io, values) {
}
if (!found.retry && (found.laneWork || Date.now() >= deadline)) {
if (values.verify) refuseWhileBuilding(ctx);
- const agents = withBoard(ctx, (board) => store.listAgents(board));
+ const agents = withBoardRead(ctx, (board) => store.listAgents(board));
return refuseNextIdle(io, found.reasons, found.reasons.map((reason) => displayedWait(reason, agents, ctx.config)), { minutes, verify: values.verify, laneWork: found.laneWork });
}
if (!found.retry) await new Promise((done) => setTimeout(done, 5000));
diff --git a/src/commands/show.js b/src/commands/show.js
index ff7a7780..1bded843 100644
--- a/src/commands/show.js
+++ b/src/commands/show.js
@@ -31,7 +31,7 @@ import {
idArg,
itemLine,
sayBrief,
- withBoard,
+ withBoardRead,
} from '../cli.js';
import { relayStatus } from '../relay.js';
@@ -39,7 +39,7 @@ import { relayStatus } from '../relay.js';
export function run(io, { first, values }) {
const ctx = context(io);
const id = idArg(first);
- const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoard(ctx, (board) => ({
+ const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoardRead(ctx, (board) => ({
item: verdictProjector(ctx.info.root, board).project(store.getItem(board, id)),
verdicts: store.verdictsFor(board, id),
moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),
diff --git a/src/commands/status.js b/src/commands/status.js
index bcafd7f2..5eadeb43 100644
--- a/src/commands/status.js
+++ b/src/commands/status.js
@@ -24,13 +24,13 @@ import {
context,
span,
whoAmI,
- withBoard,
+ withBoardRead,
} from '../cli.js';
/** Run `pullboard status` and return its exit code. */
export function run(io, { values }) {
const ctx = context(io);
- const summary = withBoard(ctx, (board) => {
+ const summary = withBoardRead(ctx, (board) => {
const me = whoAmI(ctx, board);
const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);
const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });
@@ -55,7 +55,7 @@ export function run(io, { values }) {
io.say('optional: add a GitHub origin and run pullboard relay on to link this board');
}
if (Object.keys(ctx.config.products).length) {
- const all = withBoard(ctx, (board) => store.listItems(board, { all: true }));
+ const all = withBoardRead(ctx, (board) => store.listItems(board, { all: true }));
productSummaries(ctx.config, loadSpec(ctx.info.root, ctx.config), all).forEach((product) => io.say(productLine(product)));
}
return 0;
diff --git a/test/api-http.test.js b/test/api-http.test.js
index 631b47be..de1d93a3 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -30,6 +30,7 @@ import { execFileSync } from 'node:child_process';
import { basename, resolve } from 'node:path';
import { performance } from 'node:perf_hooks';
import { pathToFileURL } from 'node:url';
+import { DatabaseSync } from 'node:sqlite';
const require = createRequire(import.meta.url);
const childProcess = require('node:child_process');
@@ -170,6 +171,11 @@ try {
const { apiBoards } = await import(new URL('./api.js', pathToFileURL(serveFile)));
const { withGitReadFacts } = await import(new URL('./git.js', pathToFileURL(serveFile)));
for (const status of [undefined, true]) {
+ // A current board opens read-only with no authority to decide; a cleared stamp makes each need a write open (#1047).
+ for (const { root } of projects) {
+ const db = new DatabaseSync(resolve(execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: root, encoding: 'utf8' }).trim(), 'pullboard', 'board.sqlite'));
+ try { db.exec('PRAGMA application_id = 0'); } finally { db.close(); }
+ }
counters.git = 0;
counters.node = 0;
counters.other = 0;
diff --git a/test/api.test.js b/test/api.test.js
index cd422324..5c6b6c45 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -416,16 +416,18 @@ test('[A5, A6] a future-schema worktree cannot migrate the shared board; main ca
migratedFromWorktree.close();
const boardSource = join(linked, 'src/board.js');
+ const migrateSource = join(linked, 'src/board-migrate.js');
const oldSource = readFileSync(boardSource, 'utf8');
- const migration = " ['shout', 'shout_request_outcome', \"TEXT NOT NULL DEFAULT ''\"],\n ];";
+ const oldMigrations = readFileSync(migrateSource, 'utf8');
+ const migration = " ['shout', 'shout_request_outcome', \"TEXT NOT NULL DEFAULT ''\"],\n];";
assert.ok(oldSource.includes('export const SCHEMA_VERSION = 2;'));
- assert.ok(oldSource.includes(migration));
- const newSource = oldSource
- .replace('export const SCHEMA_VERSION = 2;', 'export const SCHEMA_VERSION = 3;')
- .replace(migration, migration.replace('\n ];', "\n ['item', 'item_unmerged_probe', 'INTEGER NOT NULL DEFAULT 0'],\n ];"));
- assert.notEqual(newSource, oldSource, 'the unmerged worktree carries a real schema-3 migration');
+ assert.ok(oldMigrations.includes(migration));
+ const newSource = oldSource.replace('export const SCHEMA_VERSION = 2;', 'export const SCHEMA_VERSION = 3;');
+ const newMigrations = oldMigrations.replace(migration, migration.replace('\n];', "\n ['item', 'item_unmerged_probe', 'INTEGER NOT NULL DEFAULT 0'],\n];"));
+ assert.notEqual(newMigrations, oldMigrations, 'the unmerged worktree carries a real schema-3 migration');
writeFileSync(boardSource, newSource);
- box.git(linked, 'add', 'src/board.js');
+ writeFileSync(migrateSource, newMigrations);
+ box.git(linked, 'add', 'src/board.js', 'src/board-migrate.js');
box.git(linked, 'commit', '-q', '-m', 'feat: simulate an unmerged schema bump');
let before = readFileSync(dbFile);
diff --git a/test/board-read-lock.test.js b/test/board-read-lock.test.js
new file mode 100644
index 00000000..2bcecb22
--- /dev/null
+++ b/test/board-read-lock.test.js
@@ -0,0 +1,106 @@
+/** @pullboard-test-input source-tree */
+/** @pullboard-test-loads src/cli.js src/board.js src/board-migrate.js src/commands/status.js src/commands/show.js */
+/** A read command opens the board read-only, so a writer holding the lock never stalls it [C7]. */
+import assert from 'node:assert/strict';
+import { performance } from 'node:perf_hooks';
+import { after, test } from 'node:test';
+import { DatabaseSync } from 'node:sqlite';
+import { cpSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import * as store from '../src/board.js';
+import { main } from '../src/cli.js';
+import { createE2eHelpers } from './e2e-helpers.js';
+import { runFixtureChild, startFixtureChild as spawn } from './fixture-child.js';
+
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
+
+/** Hold the board's write lock from another process for `ms`; resolves once it is held, with the holder's exit. */
+async function holdWriteLock(file, ms) {
+ const script = [
+ "const { DatabaseSync } = require('node:sqlite');",
+ 'const [file, ms] = process.argv.slice(1);',
+ 'const db = new DatabaseSync(file);',
+ "db.exec('BEGIN IMMEDIATE');",
+ "db.exec(\"INSERT INTO shout (shout_from, shout_to, shout_text, shout_at) VALUES ('holder', 'all', 'held', '2026-10-22T00:00:00Z')\");",
+ "process.stdout.write('held\\n');",
+ 'Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(ms));',
+ "db.exec('COMMIT');",
+ ].join('\n');
+ const child = spawn(process.execPath, ['-e', script, file, String(ms)], { stdio: ['ignore', 'pipe', 'pipe'] });
+ let stderr = '';
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
+ const closed = new Promise((done) => child.once('close', (code) => done({ code, stderr })));
+ await new Promise((held, fail) => {
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { if (chunk.includes('held')) held(); });
+ child.once('close', (code) => fail(new Error(`the lock holder exited ${code} before holding: ${stderr}`)));
+ });
+ return { closed };
+}
+
+const HOMES = ['PULLBOARD_HOME', 'PULLBOARD_MACHINE_HOME'];
+
+/**
+ * Run one CLI command in this process under the fixture's homes, with the time it took. Why in
+ * process: a fresh node's startup varies by hundreds of ms on a loaded machine, the lock does not.
+ */
+async function timed(box, cwd, ...argv) {
+ const saved = HOMES.map((name) => process.env[name]);
+ for (const name of HOMES) process.env[name] = box.env[name];
+ let out = '';
+ let err = '';
+ const startedAt = performance.now();
+ try {
+ const code = await main(argv, { cwd, stdout: { isTTY: false, write: (text) => { out += text; } }, stderr: { write: (text) => { err += text; } } });
+ return { code, out, err, ms: performance.now() - startedAt };
+ } finally {
+ HOMES.forEach((name, index) => { if (saved[index] === undefined) delete process.env[name]; else process.env[name] = saved[index]; });
+ }
+}
+
+/** The fastest of two runs of each read, so one scheduling stall is not read as the lock. */
+async function reads(box) {
+ const runs = [];
+ for (let round = 0; round < 2; round += 1) runs.push([await timed(box, box.repo, 'status'), await timed(box, box.repo, 'show', '1')]);
+ const fastest = (index) => runs.map((pair) => pair[index]).reduce((best, run) => (run.ms < best.ms ? run : best));
+ return { status: fastest(0), show: fastest(1) };
+}
+
+test('a read answers while a writer holds the lock [C7]', async (t) => {
+ const box = e2e.project();
+ assert.equal(box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1', '--criterion', 'renders').code, 0);
+ const file = join(box.repo, '.git', 'pullboard', 'board.sqlite');
+ // Both reads without a writer first: what is left over under the lock is the lock's cost.
+ const free = await reads(box);
+ for (const [name, run] of Object.entries(free)) assert.equal(run.code, 0, `${name}: ${run.err}`);
+
+ const holder = await holdWriteLock(file, 3000);
+ const startedAt = performance.now();
+ const { status, show } = await reads(box);
+ const heldFor = performance.now() - startedAt;
+ assert.equal((await holder.closed).code, 0, 'the holder kept the lock and committed');
+ assert.ok(heldFor < 3000, `every read finished inside the 3 s hold (${Math.round(heldFor)} ms)`);
+ assert.equal(status.code, 0, status.err);
+ assert.match(status.out, /board: 1 open/u);
+ assert.equal(show.code, 0, show.err);
+ assert.match(show.out, /^#1 /mu);
+ for (const [name, run] of Object.entries({ status, show })) {
+ const waited = run.ms - free[name].ms;
+ t.diagnostic(`${name}: ${Math.round(run.ms)} ms under a held write lock, ${Math.round(free[name].ms)} ms unlocked`);
+ assert.ok(run.ms < 200 || waited < 200, `${name} under a held write lock took ${Math.round(run.ms)} ms, ${Math.round(waited)} ms more than unlocked`);
+ }
+
+ // An older board is still migrated by the next command that writes. Only trunk code migrates a
+ // shared board, so the write runs from a released copy outside any checkout.
+ const db = new DatabaseSync(file);
+ db.exec('PRAGMA user_version = 1');
+ db.close();
+ const release = join(box.dir, 'release');
+ for (const path of ['src', 'bin', 'package.json']) cpSync(resolve(import.meta.dirname, '..', path), join(release, path), { recursive: true });
+ const write = runFixtureChild(process.execPath, [join(release, 'bin', 'pullboard.js'), 'add', 'web', 'Footer', '--specs', 'G1', '--criterion', 'renders'],
+ { cwd: box.repo, env: box.env, encoding: 'utf8' });
+ assert.equal(write.status, 0, write.failure ?? write.stderr);
+ const migrated = store.openBoardReadOnly(file);
+ try { assert.equal(migrated.prepare('PRAGMA user_version').get().user_version, store.SCHEMA_VERSION); }
+ finally { migrated.close(); }
+});