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): share waiting read-only connections [C7,B3]

Corey Olson8e00b4b0d3bb
diff --git a/src/approved-rows.js b/src/approved-rows.js
index 4bebc72e..da30b922 100644
--- a/src/approved-rows.js
+++ b/src/approved-rows.js
@@ -2,10 +2,9 @@
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { DatabaseSync } from 'node:sqlite';
import { spawnSync } from 'node:child_process';
import { parseSpec, SIGNOFFS_FILE } from './spec.js';
-import { rowDecisions } from './board.js';
+import { openBoardReadOnly, rowDecisions } from './board.js';
import { hasSignerFile, verifySignedRecords } from './signature.js';
import { Refused } from './refused.js';
import { CONFIG_FILE, configFromSource } from './config.js';
@@ -38,7 +37,7 @@ function rowSourceAt(root, revision, file, kind) {
/** Read the shared decision index without opening the board's migrator or changing its evidence. */
function boardApprovals(file) {
if (!file || !existsSync(file)) return [];
- const db = new DatabaseSync(file, { readOnly: true });
+ const db = openBoardReadOnly(file);
try { return rowDecisions({ db }); }
finally { db.close(); }
}
diff --git a/src/board.js b/src/board.js
index 0b6ac522..1a71583b 100644
--- a/src/board.js
+++ b/src/board.js
@@ -135,6 +135,18 @@ const SCHEMA = `
);
`;
+/** Open an existing board without migrations, waiting for the same locks as openBoard. */
+export function openBoardReadOnly(file) {
+ const db = new DatabaseSync(file, { readOnly: true });
+ try {
+ db.exec('PRAGMA busy_timeout = 10000');
+ return db;
+ } catch (error) {
+ db.close();
+ throw error;
+ }
+}
+
/**
* Open, or create, the board at `file`. Tests pass `:memory:`.
*
@@ -151,9 +163,8 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {
let boardVersion = 0;
let logVersion = 0;
if (existsSync(file)) {
- const current = new DatabaseSync(file, { readOnly: true });
+ const current = openBoardReadOnly(file);
try {
- current.exec('PRAGMA busy_timeout = 10000');
boardVersion = current.prepare('PRAGMA user_version').get().user_version;
logVersion = readEventLogVersion(current);
} finally {
diff --git a/src/cli.js b/src/cli.js
index 4cd799ca..3a484167 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -8,7 +8,6 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
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, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';
import { displayAgentName } from './agent-names.js';
@@ -2742,9 +2741,8 @@ async function readStdin(stdin) {
/** Wait up to the board's shared busy timeout while reading hook facts, without migrating its schema. */
function hookRead(ctx, read) {
if (!existsSync(ctx.file)) return null;
- const db = new DatabaseSync(ctx.file, { readOnly: true });
+ const db = store.openBoardReadOnly(ctx.file);
try {
- db.exec('PRAGMA busy_timeout = 10000');
return read({ db, clock: ctx.clock });
}
finally { db.close(); }
diff --git a/src/doctor.js b/src/doctor.js
index cc2b035d..8a46e64e 100644
--- a/src/doctor.js
+++ b/src/doctor.js
@@ -3,11 +3,10 @@ import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { DOCTRINE_FILE, LEGACY_DOCTRINE_FILE } from './config.js';
import { tryGit } from './git.js';
-import { DatabaseSync } from 'node:sqlite';
import { checkAtCommit, submissionPaths, dependencySnapshots } from './trusted-policy.js';
import { BLANKS, STATES, storeTriggers } from './machine.js';
-import { EVENT_LOG_VERSION, readEventLogVersion, SCHEMA_VERSION } from './board.js';
+import { EVENT_LOG_VERSION, openBoardReadOnly, readEventLogVersion, SCHEMA_VERSION } from './board.js';
import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
import { loadSpec } from './spec.js';
import { loadDoctrine } from './doctrine.js';
@@ -35,7 +34,7 @@ export function doctrineProblems(root, config) {
*/
export function doctorProblems(file, root, tryGit, config, { isMain = true } = {}) {
if (!existsSync(file)) return [finding('BOARD_MISSING', 'board file is missing', 'run pullboard status to create a new board')];
- const db = new DatabaseSync(file, { readOnly: true });
+ const db = openBoardReadOnly(file);
try {
const schemaProblems = versionProblems(db, isMain);
if (schemaProblems.length) return schemaProblems;
diff --git a/test/land.test.js b/test/land.test.js
index 6b4dc74f..16f1ab77 100644
--- a/test/land.test.js
+++ b/test/land.test.js
@@ -197,6 +197,77 @@ async (t) => {
assert.ok(existsSync(writer.released), 'writer releases its lock after commit and close');
});
+test('a staged approved-row hook read waits for another process\'s lock [C7,B3,S19]', { timeout: 40_000 }, // budget: hang-only ceiling covers native Git, the exclusive writer and fixture cleanup; no speed claim.
+async (t) => {
+ const box = landProject();
+ const specPath = join(box.repo, 'SPEC.md');
+ writeFileSync(specPath, readFileSync(specPath, 'utf8').replace('The page renders.', 'The changed page renders.'));
+ box.git(box.repo, 'add', 'SPEC.md');
+ const before = box.git(box.repo, 'rev-parse', 'HEAD');
+ const staged = box.git(box.repo, 'write-tree');
+ const control = box.tryGit(box.repo, 'commit', '-m', 'feat: change approved promise [G1]');
+ assert.equal(control.status, 1, control.stderr);
+ assert.match(control.stderr, /G1 changes approved text without the person's exact approval/);
+
+ const marker = join(box.dir, 'approved-read-attempted');
+ const probe = join(box.dir, 'observe-approved-read.mjs');
+ const ready = join(box.dir, 'approved-read-ready');
+ writeFileSync(probe, [
+ "import { existsSync, writeFileSync } from 'node:fs';",
+ "import { DatabaseSync } from 'node:sqlite';",
+ 'const prepare = DatabaseSync.prototype.prepare;',
+ 'DatabaseSync.prototype.prepare = function (sql, ...args) {',
+ " if (String(sql) !== 'SELECT meta_value FROM board_meta WHERE meta_key=?') return Reflect.apply(prepare, this, [sql, ...args]);",
+ " writeFileSync(process.env.APPROVED_READ_MARKER, JSON.stringify({ phase: 'before-lock' }));",
+ ' const deadline = Date.now() + 8000;',
+ ' while (!existsSync(process.env.APPROVED_READ_READY) && Date.now() < deadline) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);',
+ " if (!existsSync(process.env.APPROVED_READ_READY)) throw new Error('exclusive writer did not become ready');",
+ " writeFileSync(process.env.APPROVED_READ_MARKER, JSON.stringify({ phase: 'read-started' }));",
+ ' try { return Reflect.apply(prepare, this, [sql, ...args]); }',
+ " catch (error) { writeFileSync(process.env.APPROVED_READ_MARKER, JSON.stringify({ phase: 'error', code: error.code ?? null, errcode: error.errcode ?? null, message: error.message })); throw error; }",
+ '};',
+ ].join('\n'));
+ let writer;
+ let hook;
+ t.after(async () => {
+ if (writer) {
+ writeFileSync(writer.release, 'release');
+ await writer.closed;
+ }
+ if (hook && hook.exitCode === null && hook.signalCode === null) {
+ hook.kill('SIGKILL');
+ await hook.closed;
+ }
+ });
+ hook = startFixtureChild('git', ['commit', '-m', 'feat: change approved promise [G1]'], {
+ cwd: box.repo, env: { ...box.env, NODE_OPTIONS: `--import=${probe}`, APPROVED_READ_MARKER: marker, APPROVED_READ_READY: ready },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ hook.stderrText = '';
+ hook.stdout.resume();
+ hook.stderr.setEncoding('utf8').on('data', (part) => { hook.stderrText += part; });
+ hook.closed = childOutcome(hook);
+ await waitFor(() => existsSync(marker), 'native staged-approval hook query');
+ assert.equal(JSON.parse(readFileSync(marker, 'utf8')).phase, 'before-lock');
+ writer = startExclusiveBoardWriter(box, join(box.repo, '.git', 'pullboard', 'board.sqlite'), 'approved-read');
+ await waitFor(() => existsSync(writer.ready), 'approved-row exclusive writer');
+ await waitFor(() => JSON.parse(readFileSync(marker, 'utf8')).phase !== 'before-lock', 'approved-row read under the exclusive lock');
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 500));
+ const observation = JSON.parse(readFileSync(marker, 'utf8'));
+ const sqliteBusy = observation.code === 'SQLITE_BUSY' || ((observation.errcode ?? 0) & 0xff) === 5;
+ assert.equal(sqliteBusy, false, `staged approval read must wait, not return SQLITE_BUSY: ${JSON.stringify(observation)} ${hook.stderrText}`);
+ assert.equal(observation.phase, 'read-started');
+ assert.equal(hook.exitCode, null, `native hook remains pending during the writer: ${hook.stderrText}`);
+ writeFileSync(writer.release, 'release');
+ const [writerResult, hookResult] = await Promise.all([writer.closed, hook.closed]);
+ assert.deepEqual({ code: writerResult.code, signal: writerResult.signal }, { code: 0, signal: null }, writer.child.fixtureFailure);
+ assert.deepEqual({ code: hookResult.code, signal: hookResult.signal }, { code: 1, signal: null }, hook.stderrText);
+ assert.match(hook.stderrText, /G1 changes approved text without the person's exact approval/);
+ assert.doesNotMatch(hook.stderrText, /database is locked|restore valid staged SSH trust files/);
+ assert.equal(box.git(box.repo, 'rev-parse', 'HEAD'), before, 'normal approval refusal leaves the commit unchanged');
+ assert.equal(box.git(box.repo, 'write-tree'), staged, 'the staged approved-row change remains available for person approval');
+});
+
/** Give one private item a distinct canonical lane identity and an independent main base. */
function itemWorktree(box, number, file = FILES[number - 1], afterIds = []) {
const path = join(box.dir, `land-${number}`);