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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(board): wait on hook reads [C7,B3]
Corey Olsonfa686d82a0da
diff --git a/src/board.js b/src/board.jsindex 0b6ac522..b79770fa 100644--- a/src/board.js+++ b/src/board.js@@ -22,6 +22,23 @@ export const PERSON = 'person';/** Version of the persisted append-only event record format; bump for incompatible format changes. */export const EVENT_LOG_VERSION = 1;+/** Maximum time a board connection waits for another process to release SQLite's lock. */+export const BOARD_BUSY_TIMEOUT_MS = 10_000;++/**+ * Replace SQLite's bare lock error with the board path and elapsed wait when the wait expires.+ *+ * @param {string} file+ * @param {number} startedAt+ * @param {Error & { errcode?: number }} error+ * @returns {Error}+ */+export function boardBusyError(file, startedAt, error) {+ const sqliteCode = Number.isInteger(error.errcode) ? error.errcode & 0xff : null;+ if (sqliteCode !== 5 && error.code !== 'SQLITE_BUSY' && !/database is locked/iu.test(error.message ?? '')) return error;+ return new Refused('BOARD_BUSY', `board file ${file} remained held by another process after ${Date.now() - startedAt}ms; wait for it to finish and retry`);+}+/*** Who can take an item (B13), as tiers in order of the model an item needs: `light` is work a small* or local model can build from its brief, `mid` needs a capable general model, and@@ -151,13 +168,17 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {let boardVersion = 0;let logVersion = 0;if (existsSync(file)) {- const current = new DatabaseSync(file, { readOnly: true });+ const startedAt = Date.now();+ let current;try {- current.exec('PRAGMA busy_timeout = 10000');+ current = new DatabaseSync(file, { readOnly: true });+ current.exec(`PRAGMA busy_timeout = ${BOARD_BUSY_TIMEOUT_MS}`);boardVersion = current.prepare('PRAGMA user_version').get().user_version;logVersion = readEventLogVersion(current);+ } catch (error) {+ throw boardBusyError(file, startedAt, error);} finally {- current.close();+ current?.close();}if (SCHEMA_VERSION > boardVersion) {throw new Refused(@@ -171,9 +192,11 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {}}if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });- const db = new DatabaseSync(file);+ const startedAt = Date.now();+ let db;try {- db.exec('PRAGMA busy_timeout = 10000');+ 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);@@ -183,8 +206,8 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {guardMoves(board);return board;} catch (error) {- db.close();- throw error;+ try { db?.close(); } catch {}+ throw boardBusyError(file, startedAt, error);}}diff --git a/src/cli.js b/src/cli.jsindex 8de793a1..dafdd966 100644--- a/src/cli.js+++ b/src/cli.js@@ -2742,9 +2742,15 @@ async function readStdin(stdin) {/** 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 read({ db, clock: ctx.clock }); }- finally { db.close(); }+ const startedAt = Date.now();+ let db;+ try {+ db = new DatabaseSync(ctx.file, { readOnly: true });+ db.exec(`PRAGMA busy_timeout = ${store.BOARD_BUSY_TIMEOUT_MS}`);+ return read({ db, clock: ctx.clock });+ } catch (error) {+ throw store.boardBusyError(ctx.file, startedAt, error);+ } finally { db?.close(); }}/**diff --git a/test/land.test.js b/test/land.test.jsindex 5e69ce45..ca06bc83 100644--- a/test/land.test.js+++ b/test/land.test.js@@ -115,6 +115,67 @@ function verifiedFour(box, { red, flaky, order = [0, 1, 2, 3] } = {}) {return entries;}+/**+ * Start a separate process holding a rollback-journal exclusive write on a private board.+ * @param {any} box+ * @param {string} boardFile+ * @param {string} name+ * @returns {{ child: any, closed: Promise<{code: number|null, signal: string|null, error: Error|null}>, ready: string, release: string, released: string }}+ */+function startExclusiveWriter(box, boardFile, name) {+ const ready = join(box.dir, `${name}-ready`);+ const release = join(box.dir, `${name}-release`);+ const released = join(box.dir, `${name}-released`);+ const source = [+ "const fs = require('node:fs'); const { DatabaseSync } = require('node:sqlite');",+ 'const [file, ready, release, released] = process.argv.slice(1);',+ 'const db = new DatabaseSync(file);',+ "try { const journal = db.prepare('PRAGMA journal_mode = DELETE').get().journal_mode;",+ "const locking = db.prepare('PRAGMA locking_mode = EXCLUSIVE').get().locking_mode;",+ "if (journal !== 'delete' || locking !== 'exclusive') throw new Error('fixture did not acquire rollback-journal exclusive mode');",+ "db.exec('BEGIN EXCLUSIVE'); db.exec('CREATE TABLE IF NOT EXISTS fixture_write (value INTEGER)'); db.exec('INSERT INTO fixture_write (value) VALUES (1)');",+ 'fs.writeFileSync(ready, JSON.stringify({ journal, locking })); const deadline = Date.now() + 20_000;',+ 'while (!fs.existsSync(release) && Date.now() < deadline) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);',+ "if (!fs.existsSync(release)) throw new Error('writer release was not received');",+ "db.exec('COMMIT'); db.close(); fs.writeFileSync(released, 'released');",+ '} catch (error) { try { db.close(); } catch {} process.stderr.write(error.stack + \'\\n\'); process.exitCode = 1; }',+ ].join('\n');+ const child = startFixtureChild(process.execPath, ['-e', source, boardFile, ready, release, released], {+ cwd: box.repo, env: box.env, detached: true, stdio: ['ignore', 'ignore', 'pipe'],+ });+ const closed = childOutcome(child);+ return { child, closed, ready, release, released };+}++/** Resolve when an owned child closes or fails to spawn, whichever happens first. */+function childOutcome(child) {+ return new Promise((resolveOutcome) => {+ let spawnError = null;+ child.once('error', (error) => { spawnError = error; });+ child.once('close', (code, signal) => resolveOutcome({ code, signal, error: spawnError }));+ });+}++/**+ * Launch the real hook command with the read-attempt preload and collect its terminal output.+ * @param {any} box+ * @param {string} probe+ * @param {string} marker+ * @returns {any}+ */+function launchHookProbe(box, probe, marker) {+ const env = { ...box.env, HOOK_READ_ATTEMPT: marker };+ const child = startFixtureChild(process.execPath, ['--import', probe, BIN, 'hook', 'pre-commit'], {+ cwd: box.web, env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ child.stdoutText = '';+ child.stderrText = '';+ child.stdout.setEncoding('utf8').on('data', (part) => { child.stdoutText += part; });+ child.stderr.setEncoding('utf8').on('data', (part) => { child.stderrText += part; });+ child.closed = childOutcome(child);+ return child;+}+/** Run a successful JSON command, retaining child context if any actual hook or check refuses. */function json(box, cwd, ...args) {const result = box.run(cwd, ...args, '--json');@@ -312,6 +373,107 @@ test('land adoption recovers an interrupted gate and keeps one receipt under a nassert.equal(json(box, box.repo, 'resume').landingBatches.at(-1).state, 'landed');});+test('a hook read waits while land holds the board [C7,B3]', { timeout: 40_000 }, // budget: 40s hang ceiling covers two real lock phases, each with the unchanged 10s SQLite timeout.+async (t) => {+ const box = landProject();+ const boardFile = join(box.repo, '.git', 'pullboard', 'board.sqlite');+ const probe = join(box.dir, 'observe-hook-read.mjs');+ const observedSql = join(box.dir, 'hook-read-attempted');+ writeFileSync(probe, [+ "import { writeFileSync } from 'node:fs';",+ "import { DatabaseSync } from 'node:sqlite';",+ 'const prepare = DatabaseSync.prototype.prepare;',+ 'DatabaseSync.prototype.prepare = function (sql, ...args) {',+ " if (String(sql) !== 'SELECT * FROM agent WHERE agent_path = ?') return Reflect.apply(prepare, this, [sql, ...args]);",+ " writeFileSync(process.env.HOOK_READ_ATTEMPT, JSON.stringify({ phase: 'prepare-started' }));",+ ' try {',+ ' const statement = Reflect.apply(prepare, this, [sql, ...args]);',+ ' const get = statement.get;',+ ' statement.get = function (...values) {',+ " writeFileSync(process.env.HOOK_READ_ATTEMPT, JSON.stringify({ phase: 'get-started' }));",+ ' try { return Reflect.apply(get, this, values); }',+ ' catch (error) { writeFileSync(process.env.HOOK_READ_ATTEMPT, JSON.stringify({ phase: \'error\', code: error.code ?? null, errcode: error.errcode ?? null, message: error.message })); throw error; }',+ ' };',+ ' return statement;',+ ' } catch (error) { writeFileSync(process.env.HOOK_READ_ATTEMPT, JSON.stringify({ phase: \'error\', code: error.code ?? null, errcode: error.errcode ?? null, message: error.message })); throw error; }',+ '};',+ ].join('\n'));+ const writers = [];+ const hooks = [];+ t.after(async () => {+ const settle = async (promise, timeoutMs) => {+ let timer;+ try { return await Promise.race([promise, new Promise((resolveTimeout) => { timer = setTimeout(() => resolveTimeout(false), timeoutMs); })]); }+ finally { clearTimeout(timer); }+ };+ for (const writer of writers) {+ writeFileSync(writer.release, 'release');+ if (!await settle(writer.closed, 1_000) && writer.child.exitCode === null && writer.child.signalCode === null) {+ try { process.kill(-writer.child.pid, 'SIGTERM'); } catch {}+ if (!await settle(writer.closed, 1_000) && writer.child.exitCode === null && writer.child.signalCode === null) {+ try { process.kill(-writer.child.pid, 'SIGKILL'); } catch {}+ await writer.closed;+ }+ }+ }+ for (const hook of hooks) {+ if (!await settle(hook.closed, 1_000) && hook.exitCode === null && hook.signalCode === null) {+ hook.kill('SIGTERM');+ if (!await settle(hook.closed, 1_000) && hook.exitCode === null && hook.signalCode === null) {+ hook.kill('SIGKILL');+ await hook.closed;+ }+ }+ }+ });+ /** Start both isolated processes and wait for the hook's exact agentAt query attempt. */+ const runHookWhileWriterHolds = async (name) => {+ const writer = startExclusiveWriter(box, boardFile, name);+ writers.push(writer);+ await waitFor(() => existsSync(writer.ready), `${name} exclusive writer`);+ const marker = `${observedSql}-${name}`;+ const hook = launchHookProbe(box, probe, marker);+ hooks.push(hook);+ await waitFor(() => existsSync(marker), `${name} hook agentAt query attempt`);+ return { writer, hook, marker };+ };++ const successful = await runHookWhileWriterHolds('successful-wait');+ // The preload marks the exact agentAt statement preparation; release follows a pending-read observation.+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 500));+ const successObservation = JSON.parse(readFileSync(successful.marker, 'utf8'));+ assert.equal(successful.hook.exitCode, null, `the hook must remain pending at agentAt while SQLite is exclusively locked: ${JSON.stringify(successObservation)} ${successful.hook.stderrText}`);+ assert.ok(['prepare-started', 'get-started'].includes(successObservation.phase), `the hook reached native SQLite prepare or get before release: ${JSON.stringify(successObservation)}`);+ writeFileSync(successful.writer.release, 'release');+ const [writerSuccess, hookSuccess] = await Promise.all([successful.writer.closed, successful.hook.closed]);+ assert.equal(writerSuccess.error, null, `the exclusive writer spawned: ${writerSuccess.error?.message ?? ''}`);+ assert.deepEqual({ code: writerSuccess.code, signal: writerSuccess.signal }, { code: 0, signal: null }, successful.writer.child.fixtureFailure ?? 'the exclusive writer commits and closes');+ assert.equal(hookSuccess.error, null, `the hook child spawned: ${hookSuccess.error?.message ?? ''}`);+ assert.deepEqual({ code: hookSuccess.code, signal: hookSuccess.signal }, { code: 0, signal: null }, successful.hook.stderrText);+ assert.ok(existsSync(successful.writer.released), 'the writer releases its exclusive lock only after commit and close');++ const timeout = await runHookWhileWriterHolds('timeout-diagnostic');+ let timeoutTimer;+ const timeoutResult = await Promise.race([+ timeout.hook.closed,+ new Promise((_, reject) => { timeoutTimer = setTimeout(() => reject(new Error('hook read exceeded the stated 10s busy timeout')), 15_000); }),+ ]).finally(() => clearTimeout(timeoutTimer));+ assert.equal(timeoutResult.error, null, `the timeout hook child spawned: ${timeoutResult.error?.message ?? ''}`);+ assert.equal(timeoutResult.code, 1, timeout.hook.stderrText);+ assert.match(timeout.hook.stderrText, /BOARD_BUSY/u);+ assert.match(timeout.hook.stderrText, /board file .*board\.sqlite.*another process.*after \d+ms/u);+ assert.match(timeout.hook.stderrText, /after (?:9\d{3}|1\d{4})ms/u, 'diagnostics report the actual prolonged lock wait');+ assert.doesNotMatch(timeout.hook.stderrText, /database is locked/u, 'a timed-out read never emits only SQLite’s bare lock error');+ const timeoutObservation = JSON.parse(readFileSync(timeout.marker, 'utf8'));+ assert.equal(timeoutObservation.phase, 'error', 'the preload observed the actual SQLite refusal');+ assert.ok((timeoutObservation.errcode & 0xff) === 5 || timeoutObservation.code === 'SQLITE_BUSY', `the underlying failure is SQLITE_BUSY/5: ${JSON.stringify(timeoutObservation)}`);+ writeFileSync(timeout.writer.release, 'release');+ const writerTimeout = await timeout.writer.closed;+ assert.equal(writerTimeout.error, null, `the diagnostic writer spawned: ${writerTimeout.error?.message ?? ''}`);+ assert.deepEqual({ code: writerTimeout.code, signal: writerTimeout.signal }, { code: 0, signal: null }, timeout.writer.child.fixtureFailure ?? 'the diagnostic fixture writer closes cleanly');+ assert.ok(existsSync(timeout.writer.released), 'the diagnostic writer releases after the hook reports its timeout');+});+test('landing diagnostics retain unknown failures and merge subjects obey typed 72-character headers [B3,R3]', () => {const root = '/private/landing';const failures = landingFailures(`not ok 1 - located failure\n location: ${root}/test/one.test.js:3:4\nnot ok 2 - unknown failure\n`, root);