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.

perf(api): reuse validated read-only git facts [A2,N26]

Corey Olsone53340f97fed
diff --git a/src/api.js b/src/api.js
index beb0ab8e..dea4a9d8 100644
--- a/src/api.js
+++ b/src/api.js
@@ -6,7 +6,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
import { displayAgentName } from './agent-names.js';
import * as store from './board.js';
import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
-import { codeIsFromMain, repoInfo, resolveCommit } from './git.js';
+import { codeIsFromMain, repoInfo, resolveCommit, withGitReadFacts } from './git.js';
import { refusalDocument } from './json.js';
import { relayLinked, relayOperation, relayRevoke, relayTokens } from './relay.js';
import { laneNames } from './lanes.js';
@@ -1006,19 +1006,22 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
if (req.headers.origin && req.headers.origin !== 'http://' + req.headers.host && !permittedOrigins.has(req.headers.origin)) throw new Refused('API_ORIGIN', 'use the API from its own origin');
return { local: true };
},
- boards: () => apiBoardListing(projects, codeIsMain),
- board: (id) => findBoard(id, projects, codeIsMain),
- state: (board, who, seen, options) => localState(board, seen, options).state,
- stateJson: (board, who, seen, options) => localState(board, seen, options).json,
- watchRevision: (board) => watchLocalStateRevision(board),
- delta: (board, who, seen, options) => localDelta(board, seen, options),
- item: (board, id) => localItem(board, id),
- search: (board, text) => localSearch(board, text),
- shout: (board, id) => relayLinked(board.root)
+ boards: () => withGitReadFacts(() => apiBoardListing(projects, codeIsMain)),
+ board: (id) => withGitReadFacts(() => findBoard(id, projects, codeIsMain)),
+ state: (board, who, seen, options) => withGitReadFacts(() => localState(board, seen, options).state),
+ stateJson: (board, who, seen, options) => withGitReadFacts(() => localState(board, seen, options).json),
+ watchRevision: (board) => {
+ const watcher = withGitReadFacts(() => watchLocalStateRevision(board));
+ return { ...watcher, revision: () => withGitReadFacts(() => watcher.revision()) };
+ },
+ delta: (board, who, seen, options) => withGitReadFacts(() => localDelta(board, seen, options)),
+ item: (board, id) => withGitReadFacts(() => localItem(board, id)),
+ search: (board, text) => withGitReadFacts(() => localSearch(board, text)),
+ shout: (board, id) => withGitReadFacts(() => relayLinked(board.root)
? relayPresentationShout(board.root, id)
- : withBoard(board.root, (db) => store.shoutDetails(db, id), codeIsMain),
- code: (board, ref) => codeAt(board.root, ref),
- events: (board, after) => afterEvents(board.root, after, codeIsMain),
+ : withBoard(board.root, (db) => store.shoutDetails(db, id), codeIsMain)),
+ code: (board, ref) => withGitReadFacts(() => codeAt(board.root, ref)),
+ events: (board, after) => withGitReadFacts(() => afterEvents(board.root, after, codeIsMain)),
eventLogVersion: () => store.EVENT_LOG_VERSION,
move: (board, body) => executeMove(board.root, body, runCommand, codeIsMain, personChannel),
request: (board, body) => createRequest(board.root, body, codeIsMain, personChannel),
diff --git a/src/git.js b/src/git.js
index 7b375425..4016669f 100644
--- a/src/git.js
+++ b/src/git.js
@@ -1,16 +1,27 @@
/**
- * The few git facts pullboard needs: where the repo is, which worktree this is, what HEAD holds,
- * and whether the tree is clean (R3). Every call is a plain `git` child process.
+ * The few Git facts pullboard needs: repository/worktree identity, selected refs and tree cleanliness.
*/
import { execFileSync, spawnSync } from 'node:child_process';
import { AsyncLocalStorage } from 'node:async_hooks';
-import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
-import { dirname, join, resolve } from 'node:path';
+import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
+import { basename, 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'];
const gitFacts = new AsyncLocalStorage();
+const gitReadFacts = new AsyncLocalStorage();
+const READ_FACT_LIMIT = 512;
+const persistentReadFacts = new Map();
+
+/** Mark API read work so selected facts use the bounded process-lifetime, filesystem-validated cache.
+ *
+ * @param {() => any} work
+ * @returns {any}
+ */
+export function withGitReadFacts(work) {
+ return gitReadFacts.run(true, work);
+}
/** Reuse facts within one CLI invocation, while isolating concurrent commands and expiring settled ones.
*
@@ -19,18 +30,204 @@ const gitFacts = new AsyncLocalStorage();
*/
export async function withGitFacts(work) {
const cache = { active: true, facts: new Map() };
- return gitFacts.run(cache, async () => {
+ const run = () => gitFacts.run(cache, async () => {
try { return await work(); }
finally {
cache.active = false;
cache.facts.clear();
}
});
+ // CLI authority must always use fresh Git facts, even when invoked from an API read callback.
+ return gitReadFacts.getStore() === true ? gitReadFacts.run(null, run) : run();
}
/** Drop facts after this command changes Git state such as refs, configuration, or worktrees. */
export function invalidateGitFacts() {
gitFacts.getStore()?.facts.clear();
+ persistentReadFacts.clear();
+}
+
+/** Return a stable, cheap signature for a path, including file contents against coarse timestamps. */
+function fileSignature(path, includeContents = true) {
+ try {
+ const stat = lstatSync(path, { bigint: true });
+ let target = null;
+ let targetIsFile = false;
+ if (stat.isSymbolicLink()) {
+ try {
+ const followed = statSync(path, { bigint: true });
+ target = [String(followed.dev), String(followed.ino), String(followed.mode), String(followed.size), String(followed.mtimeNs), String(followed.ctimeNs)];
+ targetIsFile = followed.isFile();
+ } catch (error) {
+ target = ['unreadable', error.code ?? 'ERROR'];
+ }
+ }
+ let contents = null;
+ if (includeContents && (stat.isFile() || targetIsFile)) contents = readFileSync(path, 'utf8');
+ return [String(stat.dev), String(stat.ino), String(stat.mode), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs), contents, target];
+ } catch (error) {
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null;
+ return ['unreadable', error.code ?? 'ERROR'];
+ }
+}
+
+/** Refuse caching when config includes external files or selects a ref backend this signature cannot track. */
+function configNeedsFallback(path) {
+ try {
+ const source = readFileSync(path, 'utf8');
+ return /^\s*\[\s*include(?:if\b|[\s\]])/imu.test(source)
+ || /^\s*refstorage\s*=\s*reftable\s*$/imu.test(source);
+ } catch (error) {
+ return error.code !== 'ENOENT' && error.code !== 'ENOTDIR';
+ }
+}
+
+/** Describe worktree discovery and ref files without invoking Git, so a warm read can validate facts. */
+function repositorySignature(cwd, info = null, includeHead = false) {
+ const markers = [];
+ try { markers.push(['physical-cwd', realpathSync.native(cwd)]); }
+ catch (error) { markers.push(['physical-cwd', error.code ?? 'ERROR']); }
+ let folder = resolve(cwd);
+ let discoveredGitDir = null;
+ let discoveredCommonDir = null;
+ while (true) {
+ const markerPath = join(folder, '.git');
+ const marker = fileSignature(markerPath);
+ markers.push([markerPath, marker]);
+ if (marker) {
+ if (info && folder === resolve(info.root)) {
+ discoveredGitDir = info.gitDir;
+ discoveredCommonDir = info.commonDir;
+ } else {
+ let isDirectory = marker[2] && (BigInt(marker[2]) & 0o170000n) === 0o040000n;
+ if (!isDirectory) {
+ try { isDirectory = statSync(markerPath).isDirectory(); } catch { /* Git reports malformed or missing metadata. */ }
+ }
+ if (isDirectory) {
+ try {
+ discoveredGitDir = realpathSync.native(markerPath);
+ discoveredCommonDir = discoveredGitDir;
+ } catch {
+ discoveredGitDir = null;
+ discoveredCommonDir = null;
+ }
+ } else if (typeof marker[6] === 'string') {
+ const pointer = /^gitdir: (.+)\n?$/u.exec(marker[6]);
+ if (pointer) {
+ try {
+ discoveredGitDir = realpathSync.native(resolve(folder, pointer[1]));
+ const common = fileSignature(join(discoveredGitDir, 'commondir'));
+ discoveredCommonDir = common?.[6]
+ ? realpathSync.native(resolve(discoveredGitDir, common[6].trim()))
+ : discoveredGitDir;
+ } catch {
+ // Let Git's normal reader report malformed or inaccessible worktree metadata.
+ discoveredGitDir = null;
+ discoveredCommonDir = null;
+ }
+ }
+ }
+ }
+ break;
+ }
+ const parent = dirname(folder);
+ if (parent === folder) break;
+ folder = parent;
+ }
+ const rootPath = info?.root ?? folder;
+ const gitDir = info?.gitDir ?? discoveredGitDir;
+ const commonDir = info?.commonDir ?? discoveredCommonDir;
+ if (!gitDir || !commonDir) return JSON.stringify(markers);
+ const configPaths = [join(gitDir, 'config'), join(commonDir, 'config'), join(gitDir, 'config.worktree')];
+ if (configPaths.some(configNeedsFallback)) return null;
+ for (const path of [rootPath, gitDir, commonDir]) markers.push([path, fileSignature(path, false)]);
+ for (const path of [join(gitDir, 'commondir'), ...configPaths]) {
+ markers.push([path, fileSignature(path, basename(path) === 'commondir')]);
+ }
+ if (includeHead) {
+ const headPath = join(gitDir, 'HEAD');
+ const headMark = fileSignature(headPath);
+ markers.push([headPath, headMark]);
+ const head = headMark?.[6];
+ const symbolic = typeof head === 'string' ? /^ref: (.+)\n?$/u.exec(head) : null;
+ if (symbolic) {
+ const ref = symbolic[1];
+ if (!ref.startsWith('refs/') || ref.includes('\\')
+ || !ref.split('/').every((part) => part && part !== '.' && part !== '..')) return null;
+ for (const path of [join(gitDir, ref), join(commonDir, ref), join(commonDir, 'packed-refs')]) {
+ const marker = fileSignature(path, path !== join(commonDir, 'packed-refs'));
+ markers.push([path, marker]);
+ if (marker?.[6]?.startsWith('ref: ')) return null;
+ }
+ }
+ }
+ return JSON.stringify(markers);
+}
+
+/** Describe relevant Git environment/config so harmless process settings can still share read facts. */
+function readCacheContext() {
+ const env = process.env;
+ const discoverySelectors = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_CEILING_DIRECTORIES',
+ 'GIT_DISCOVERY_ACROSS_FILESYSTEM', 'GIT_IMPLICIT_WORK_TREE', 'GIT_OBJECT_DIRECTORY',
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE'];
+ if (discoverySelectors.some((name) => env[name] !== undefined && env[name] !== '')) return null;
+
+ const names = Object.keys(env).filter((name) => name === 'GIT_CONFIG' || name === 'GIT_CONFIG_PARAMETERS'
+ || name === 'GIT_CONFIG_COUNT' || name === 'GIT_CONFIG_GLOBAL' || name === 'GIT_CONFIG_SYSTEM'
+ || name === 'GIT_CONFIG_NOSYSTEM' || /^GIT_CONFIG_(?:KEY|VALUE)_\d+$/u.test(name)).sort();
+ const values = names.map((name) => [name, env[name]]);
+ if (env.GIT_CONFIG_PARAMETERS) return null;
+ const count = env.GIT_CONFIG_COUNT === undefined ? 0 : Number(env.GIT_CONFIG_COUNT);
+ if (!Number.isSafeInteger(count) || count < 0 || count > 16) return null;
+ // Identity validation and automatic housekeeping do not select repositories or Git objects.
+ const safeOverrides = new Set(['user.useconfigonly', 'gc.auto', 'maintenance.auto']);
+ for (let index = 0; index < count; index += 1) {
+ const key = env[`GIT_CONFIG_KEY_${index}`];
+ const value = env[`GIT_CONFIG_VALUE_${index}`];
+ if (!key || value === undefined || !safeOverrides.has(key.toLowerCase())) return null;
+ }
+ const files = new Set();
+ if (env.GIT_CONFIG) files.add(env.GIT_CONFIG);
+ if (env.GIT_CONFIG_GLOBAL) files.add(env.GIT_CONFIG_GLOBAL);
+ else {
+ const xdg = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : null);
+ if (xdg) files.add(join(xdg, 'git', 'config'));
+ if (env.HOME) files.add(join(env.HOME, '.gitconfig'));
+ }
+ if (env.GIT_CONFIG_NOSYSTEM !== '1') {
+ if (env.GIT_CONFIG_SYSTEM) files.add(env.GIT_CONFIG_SYSTEM);
+ else if (process.platform !== 'win32') files.add('/etc/gitconfig');
+ }
+ const paths = [...files].sort();
+ if (paths.some(configNeedsFallback)) return null;
+ const fileMarkers = paths.map((path) => [path, fileSignature(path, false)]);
+ return JSON.stringify({ cwd: process.cwd(), values, home: env.HOME ?? null, xdg: env.XDG_CONFIG_HOME ?? null, files: fileMarkers });
+}
+
+/** Return a validated cached read fact, refreshing it when its filesystem signature changes. */
+function readFact(key, signature, read) {
+ if (gitReadFacts.getStore() !== true) return read();
+ const context = readCacheContext();
+ if (context === null) return read();
+ key = `${context}\0${key}`;
+ const cached = persistentReadFacts.get(key);
+ const before = signature(cached?.value);
+ if (before === null) return read();
+ if (cached && cached.signature === before) {
+ persistentReadFacts.delete(key);
+ persistentReadFacts.set(key, cached);
+ return cached.value;
+ }
+ const value = read();
+ const after = signature(value);
+ if (before === after) {
+ persistentReadFacts.delete(key);
+ persistentReadFacts.set(key, { signature: after, value });
+ while (persistentReadFacts.size > READ_FACT_LIMIT) persistentReadFacts.delete(persistentReadFacts.keys().next().value);
+ } else {
+ persistentReadFacts.delete(key);
+ }
+ return value;
}
/** Return one cached value for this command, or compute it when no command scope is active.
@@ -245,7 +442,11 @@ export function bareWorktreeFinding(cwd) {
*/
export function repoInfo(cwd, { env } = {}) {
if (env) return readRepoInfo(cwd, env);
- return fact(`repoInfo:${resolve(cwd)}`, () => readRepoInfo(cwd));
+ const key = `repoInfo:${resolve(cwd)}`;
+ if (gitReadFacts.getStore() === true) {
+ return readFact(key, () => repositorySignature(cwd), () => readRepoInfo(cwd));
+ }
+ return fact(key, () => readRepoInfo(cwd));
}
/** Read top level, worktree Git dir and shared Git dir in one process.
@@ -271,27 +472,34 @@ function readRepoInfo(cwd, env) {
* @returns {boolean}
*/
export function codeIsFromMain(root = CODE_ROOT) {
- return fact(`codeIsFromMain:${resolve(root)}`, () => {
- const env = gitChildEnv(root);
- const info = tryGit(root, ['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.every(Boolean)) {
- return realpathSync.native(fields[2]) === realpathSync.native(fields[1]);
- }
- if (info.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;
+ const key = `codeIsFromMain:${resolve(root)}`;
+ if (gitReadFacts.getStore() === true) {
+ return readFact(key, () => repositorySignature(root), () => readCodeIsFromMain(root));
+ }
+ return fact(key, () => readCodeIsFromMain(root));
+}
+
+/** Determine whether the code is from its main checkout, retaining the non-repository fallback. */
+function readCodeIsFromMain(root) {
+ const env = gitChildEnv(root);
+ const info = tryGit(root, ['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.every(Boolean)) {
+ return realpathSync.native(fields[2]) === realpathSync.native(fields[1]);
+ }
+ if (info.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;
+ }
}
/**
@@ -316,10 +524,16 @@ export function resolveCommit(root, ref) {
* @returns {string | null}
*/
export function headCommit(root) {
- return fact(`headCommit:${resolve(root)}`, () => {
+ const key = `headCommit:${resolve(root)}`;
+ const read = () => {
const result = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);
return result.status === 0 ? result.stdout : null;
- });
+ };
+ if (gitReadFacts.getStore() === true) {
+ const info = repoInfo(root);
+ return readFact(key, () => repositorySignature(root, info, true), read);
+ }
+ return fact(key, read);
}
/**
@@ -329,10 +543,16 @@ export function headCommit(root) {
* @returns {string | null}
*/
export function headTree(root) {
- return fact(`headTree:${resolve(root)}`, () => {
+ const key = `headTree:${resolve(root)}`;
+ const read = () => {
const result = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{tree}']);
return result.status === 0 ? result.stdout : null;
- });
+ };
+ if (gitReadFacts.getStore() === true) {
+ const info = repoInfo(root);
+ return readFact(key, () => repositorySignature(root, info, true), read);
+ }
+ return fact(key, read);
}
/**
diff --git a/test/api-http.test.js b/test/api-http.test.js
index b85d5021..2d0ebb57 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -21,6 +21,171 @@ import { fetchFresh } from './http-fixture.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+/** Run a private view in a child process with child-process accounting enabled only for warmed reads. */
+const REPEATED_READ_HARNESS = `
+import assert from 'node:assert/strict';
+import { createRequire, syncBuiltinESMExports } from 'node:module';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { basename, resolve } from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { pathToFileURL } from 'node:url';
+
+const require = createRequire(import.meta.url);
+const childProcess = require('node:child_process');
+const gitIdentity = { ...process.env, GIT_AUTHOR_NAME: 'HTTP Agent', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'HTTP Agent', GIT_COMMITTER_EMAIL: '[email protected]' };
+const counters = { git: 0, node: 0, other: 0, methods: {} };
+let counting = false;
+const childMethods = ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork'];
+/** Count one child-process API call by its executable class while measurement is enabled. */
+function countChild(method, args) {
+ const raw = method === 'fork' ? process.execPath : String(args[0] ?? '');
+ const command = raw.trim().split(/\\s+/u)[0].replace(/^['"]|['"]$/gu, '');
+ const base = basename(command).replace(/\\.exe$/iu, '').toLowerCase();
+ const kind = base === 'git' ? 'git' : (command === process.execPath || base === 'node' ? 'node' : 'other');
+ counters[kind] += 1;
+ counters.methods[method] = (counters.methods[method] ?? 0) + 1;
+}
+for (const method of childMethods) {
+ const original = childProcess[method];
+ /** Count this built-in call when measured, then preserve its original behavior. */
+ childProcess[method] = function (...args) {
+ if (counting) countChild(method, args);
+ return Reflect.apply(original, this, args);
+ };
+}
+syncBuiltinESMExports();
+
+const [serveFile, projectJson] = process.argv.slice(1);
+const projects = JSON.parse(projectJson);
+const { serveView } = await import(pathToFileURL(serveFile).href);
+const view = await serveView({ port: 0 });
+const address = new URL(view.url);
+const key = address.searchParams.get('k');
+let requestCount = 0;
+/** Fetch one authenticated API response and reject failed fixture requests. */
+async function readApi(path) {
+ requestCount += 1;
+ const response = await fetch(address.origin + path, { headers: { 'x-pullboard-key': key, connection: 'close' } });
+ const document = await response.json();
+ assert.equal(response.status, 200, JSON.stringify(document));
+ return document;
+}
+/** Fetch the actual local view page and require a successful response. */
+async function readPage() {
+ requestCount += 1;
+ const response = await fetch(view.url, { headers: { connection: 'close' } });
+ assert.equal(response.status, 200);
+ assert.match(await response.text(), /<!doctype html>/iu);
+}
+/** Read each selected board state and one known item detail. */
+async function readAllRoutes(boards) {
+ await readApi('/api/v1/boards');
+ for (const project of projects) {
+ const board = boards.find((entry) => resolve(entry.root) === resolve(project.root));
+ assert.ok(board, 'the private registry lists every fixture project');
+ const path = '/api/v1/boards/' + board.id;
+ await readApi(path + '/state');
+ await readApi(path + '/items/' + project.item);
+ }
+ await readPage();
+}
+
+try {
+ const initial = await readApi('/api/v1/boards');
+ assert.equal(initial.boards.length, 3);
+ const boards = initial.boards;
+ await readAllRoutes(boards);
+ const measuredRequests = requestCount;
+ counters.git = 0;
+ counters.node = 0;
+ counters.other = 0;
+ counters.methods = {};
+ requestCount = 0;
+ const started = performance.now();
+ counting = true;
+ try {
+ await readAllRoutes(boards);
+ await readAllRoutes(boards);
+ } finally { counting = false; }
+ const elapsedMs = performance.now() - started;
+ const measurement = { boards: boards.length, routes: 'GET /api/v1/boards; 3x GET state; 3x GET item detail; GET /',
+ warmupRequests: measuredRequests, requests: requestCount,
+ rounds: 2, elapsedMs: Number(elapsedMs.toFixed(2)), processes: { ...counters, methods: { ...counters.methods } } };
+ process.stdout.write(JSON.stringify({ measurement }) + '\\n');
+
+ const target = projects[0];
+ const board = boards.find((entry) => resolve(entry.root) === resolve(target.root));
+ const boardPath = '/api/v1/boards/' + board.id;
+ const specPath = resolve(target.root, 'SPEC.md');
+ const configPath = resolve(target.root, 'pullboard.json');
+ const doctrinePath = resolve(target.root, 'DOCTRINE.md');
+ /** Read the target state and return its payload. */
+ async function state() { return (await readApi(boardPath + '/state')).state; }
+ /** Change the target SPEC.md with a new approved goal row. */
+ function writeSpec(id) {
+ writeFileSync(specPath, '# HTTP fixture\\n\\n## Goals\\n- G1 [approved, must] Keep the board. | gate: true\\n- ' + id + ' [approved, must] Keep reads current. | gate: true\\n');
+ }
+ writeSpec('G2');
+ execFileSync('git', ['add', 'SPEC.md'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-q', '-m', 'docs: refresh fixture spec [A2]'], { cwd: target.root, env: gitIdentity, stdio: 'ignore' });
+ let current = await state();
+ let head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: target.root, env: process.env, encoding: 'utf8' }).trim();
+ assert.ok(current.spec.some((row) => row.id === 'G2'));
+ assert.equal(current.rowAgesAt['SPEC.md'], head, 'a new commit refreshes the file HEAD');
+
+ execFileSync('git', ['switch', '-q', '-c', 'freshness-branch'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ writeSpec('G3');
+ execFileSync('git', ['add', 'SPEC.md'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-q', '-m', 'docs: update branch fixture spec [A2]'], { cwd: target.root, env: gitIdentity, stdio: 'ignore' });
+ current = await state();
+ head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: target.root, env: process.env, encoding: 'utf8' }).trim();
+ assert.ok(current.spec.some((row) => row.id === 'G3'));
+ assert.equal(current.rowAgesAt['SPEC.md'], head, 'a branch switch refreshes the selected HEAD');
+
+ execFileSync('git', ['pack-refs', '--all', '--prune'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ assert.ok(readFileSync(resolve(target.root, '.git', 'packed-refs'), 'utf8').includes(' refs/heads/main\\n'),
+ 'the private fixture has a packed main ref');
+ execFileSync('git', ['switch', '-q', 'main'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ current = await state();
+ assert.ok(current.spec.some((row) => row.id === 'G2'), 'switching back refreshes the original branch state');
+ execFileSync('git', ['pack-refs', '--all', '--prune'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ const packedRefs = readFileSync(resolve(target.root, '.git', 'packed-refs'), 'utf8');
+ assert.ok(packedRefs.includes(' refs/heads/freshness-branch\\n'), 'the alternate ref is packed while main is checked out');
+ execFileSync('git', ['switch', '-q', 'freshness-branch'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+ current = await state();
+ assert.ok(current.spec.some((row) => row.id === 'G3'), 'switching to a packed ref refreshes the selected state');
+ execFileSync('git', ['switch', '-q', 'main'], { cwd: target.root, env: process.env, stdio: 'ignore' });
+
+ writeSpec('G4');
+ current = await state();
+ assert.ok(current.spec.some((row) => row.id === 'G4'), 'an uncommitted SPEC.md edit appears on the next read');
+ writeFileSync(doctrinePath, '# Local rules\\n\\n## Team Rules\\n\\n- LOCAL1 [approved, must] Keep the board readable. | gate: true\\n');
+ current = await state();
+ assert.ok(current.practice.some((row) => row.id === 'LOCAL1'), 'a DOCTRINE.md edit appears on the next read');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, JSON.stringify({ ...config, lanes: { ...config.lanes, ops: { owns: [] } } }));
+ current = await state();
+ assert.ok(current.lanes.includes('ops'), 'a pullboard.json edit appears on the next read');
+
+ const linked = projects[2];
+ const linkedBoard = boards.find((entry) => resolve(entry.root) === resolve(linked.root));
+ const linkedPath = '/api/v1/boards/' + linkedBoard.id + '/state';
+ execFileSync('git', ['switch', '-q', '-c', 'linked-refresh'], { cwd: linked.root, env: process.env, stdio: 'ignore' });
+ writeFileSync(resolve(linked.root, 'SPEC.md'), '# HTTP fixture\\n\\n## Goals\\n- G1 [approved, must] Keep the board. | gate: true\\n- G5 [approved, must] Keep the linked worktree current. | gate: true\\n');
+ execFileSync('git', ['add', 'SPEC.md'], { cwd: linked.root, env: process.env, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-q', '-m', 'docs: refresh linked worktree [A2]'], { cwd: linked.root, env: gitIdentity, stdio: 'ignore' });
+ const linkedState = (await readApi(linkedPath)).state;
+ const linkedHead = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: linked.root, env: process.env, encoding: 'utf8' }).trim();
+ assert.ok(linkedState.spec.some((row) => row.id === 'G5'));
+ assert.equal(linkedState.rowAgesAt['SPEC.md'], linkedHead, 'a linked worktree branch change refreshes its state');
+ process.stdout.write(JSON.stringify({ fresh: true }) + '\\n');
+} finally {
+ await view.close();
+}
+`;
+
/** Quote an executable path literally for the fixture's source-bin hook shim. */
function shellWord(value) {
return "'" + value.replace(/'/g, "'\\''") + "'";
@@ -137,6 +302,56 @@ async function viewHttpBox(t, existing = null) {
return { ...box, api: view, origin, key, id, call, path: '/api/v1/boards/' + id };
}
+/** Prove warmed reads across three registered projects start no child processes and changes refresh state. */
+test('a repeated read spawns no process [A2,N26]', (t) => {
+ const box = fixture(t);
+ const roots = [box.root];
+ for (const number of [2, 3]) {
+ const root = join(box.dir, 'repo-' + number);
+ mkdirSync(root);
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, env: box.env, stdio: 'pipe' });
+ box.cli(root, 'init');
+ const configPath = join(root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, JSON.stringify({ ...config, gate: 'true', lanes: { app: { owns: ['app/'] }, review: { owns: [] } } }));
+ writeFileSync(join(root, 'SPEC.md'), '# HTTP fixture\n\n## Goals\n- G1 [approved, must] Keep the board. | gate: true\n');
+ writeFileSync(join(root, 'DOCTRINE.md'), '');
+ runFixtureGit(['add', '-A'], { cwd: root, env: box.env, stdio: 'pipe' });
+ runFixtureGit(['commit', '-q', '-m', 'chore: private HTTP fixture [A2]'], { cwd: root, env: box.env, stdio: 'pipe' });
+ if (number === 3) {
+ const linked = join(box.dir, 'repo-3-linked');
+ runFixtureGit(['worktree', 'add', '-q', '-b', 'view-feature', linked], { cwd: root, env: box.env, stdio: 'pipe' });
+ roots.push(linked);
+ } else roots.push(root);
+ }
+
+ const previousHome = process.env.PULLBOARD_HOME;
+ process.env.PULLBOARD_HOME = box.env.PULLBOARD_HOME;
+ try { for (const root of roots) registerProject(root); }
+ finally {
+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;
+ else process.env.PULLBOARD_HOME = previousHome;
+ }
+
+ const projects = roots.map((root, index) => {
+ const added = box.cli(root, 'add', 'app', 'Read fixture item ' + (index + 1), '--criterion', 'appears in item detail', '--specs', 'G1');
+ return { root, item: added.item.item_id };
+ });
+ // Keep the fixture's ordinary private Git config and identity; run-tests removes inherited repo/object selectors.
+ const result = runFixtureChild(process.execPath, [
+ '--input-type=module', '-e', REPEATED_READ_HARNESS,
+ resolve(import.meta.dirname, '../src/serve.js'), JSON.stringify(projects),
+ ], { cwd: box.root, env: box.env, encoding: 'utf8' });
+ const lines = result.stdout.trim().split('\n');
+ const measurement = JSON.parse(lines[0]).measurement;
+ process.stderr.write(`a repeated read spawns no process: boards=${measurement.boards}, routes=${measurement.routes}, requests=${measurement.requests}, rounds=${measurement.rounds}, processes=${JSON.stringify(measurement.processes)}, elapsed=${measurement.elapsedMs}ms\n`);
+ assert.deepEqual({ git: measurement.processes.git, node: measurement.processes.node, other: measurement.processes.other },
+ { git: 0, node: 0, other: 0 }, 'repeated board-list, state, item-detail, and page reads start no child process after warm-up');
+ assert.equal(result.status, 0, result.failure ?? result.stderr);
+ const report = JSON.parse(lines.at(-1));
+ assert.equal(report.fresh, true, 'commit, packed refs, linked worktree, SPEC.md, DOCTRINE.md, and pullboard.json changes appear on the next read');
+});
+
test('[A2] a stale registered folder does not hide another readable board', async (t) => {
const box = await httpBox(t, { includeMissing: true });
const listed = await box.call('/api/v1/boards');
diff --git a/test/git-calls.test.js b/test/git-calls.test.js
index 28842293..6f49e976 100644
--- a/test/git-calls.test.js
+++ b/test/git-calls.test.js
@@ -92,6 +92,21 @@ function resetAndCount(box, cwd, ...args) {
return { result, count };
}
+/** Run one isolated Node scenario with the real Git-counting shim and only repository-redirect selectors cleared. */
+function readFactScenario(box, root, body) {
+ const script = `import { codeIsFromMain, headCommit, withGitFacts, withGitReadFacts } from ${JSON.stringify(GIT_MODULE)};\n${body}`;
+ const env = { ...box.env };
+ // Keep the fixture's config and author settings; clear only selectors that redirect repository discovery.
+ for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_CEILING_DIRECTORIES',
+ 'GIT_DISCOVERY_ACROSS_FILESYSTEM', 'GIT_IMPLICIT_WORK_TREE', 'GIT_OBJECT_DIRECTORY',
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE']) delete env[name];
+ const result = runFixtureChild(process.execPath, ['--input-type=module', '-e', script, root], {
+ cwd: box.dir, env, encoding: 'utf8',
+ });
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ return JSON.parse(result.stdout.trim());
+}
+
test('help starts no Git and linked-worktree status spawns at most four Git processes [C7]', (t) => {
const box = fixture(t);
const version = resetAndCount(box, box.dir, '--version');
@@ -242,3 +257,54 @@ test('settled and concurrent commands do not share Git-fact caches [C7]', async
assert.deepEqual(await b, [thirdCommit, thirdCommit], 'a concurrent command has a separate fact scope');
assert.equal(headCommit(box.repo), fourthCommit, 'outside a command scope Git facts are read directly');
});
+
+test('API read facts persist across request scopes and refresh after ref changes [A2,N26,C7]', (t) => {
+ const box = fixture(t);
+ const result = readFactScenario(box, box.repo, `
+import { execFileSync } from 'node:child_process';
+import { readFileSync, writeFileSync } from 'node:fs';
+const root = process.argv[1];
+const calls = process.env.PULLBOARD_GIT_CALLS;
+const readRequest = () => withGitFacts(() => withGitReadFacts(() => headCommit(root)));
+const initial = await readRequest();
+writeFileSync(calls, '');
+const repeated = await readRequest();
+const repeatedCalls = readFileSync(calls, 'utf8').trim().split('\\n').filter(Boolean).length;
+const mutation = await withGitReadFacts(async () => {
+ const before = headCommit(root);
+ const realGit = process.env.PULLBOARD_REAL_GIT;
+ const git = (args, input) => execFileSync(realGit, args, { cwd: root, input, encoding: 'utf8' }).trim();
+ const parent = git(['rev-parse', 'HEAD']);
+ const tree = git(['rev-parse', 'HEAD^{tree}']);
+ const next = git(['-c', 'user.name=Test Agent', '-c', '[email protected]', 'commit-tree', tree, '-p', parent], 'external ref change');
+ git(['update-ref', 'refs/heads/main', next]);
+ const command = await withGitFacts(() => headCommit(root));
+ const after = headCommit(root);
+ return { before, next, command, after };
+});
+console.log(JSON.stringify({ initial, repeated, repeatedCalls, mutation }));
+`);
+ assert.ok(result.initial, 'the fixture starts with a committed HEAD');
+ assert.equal(result.repeated, result.initial, 'a fresh API request reads the same HEAD');
+ assert.equal(result.repeatedCalls, 0, 'a warm read-fact cache starts no Git process on the next request');
+ assert.notEqual(result.mutation.next, result.mutation.before, 'the fixture advances its branch outside Pullboard');
+ assert.equal(result.mutation.command, result.mutation.next, 'a nested command scope bypasses the API read cache');
+ assert.equal(result.mutation.after, result.mutation.next, 'the next API read sees and refreshes the changed ref');
+});
+
+test('an installed-source provenance miss is reused outside Git [A2,N26,C7]', (t) => {
+ const box = fixture(t);
+ const result = readFactScenario(box, box.dir, `
+import { readFileSync, writeFileSync } from 'node:fs';
+const root = process.argv[1];
+const calls = process.env.PULLBOARD_GIT_CALLS;
+const first = withGitReadFacts(() => codeIsFromMain(root));
+writeFileSync(calls, '');
+const repeated = withGitReadFacts(() => codeIsFromMain(root));
+const repeatedCalls = readFileSync(calls, 'utf8').trim().split('\\n').filter(Boolean).length;
+console.log(JSON.stringify({ first, repeated, repeatedCalls }));
+`);
+ assert.equal(result.first, true, 'source without Git metadata has installed-source provenance');
+ assert.equal(result.repeated, true, 'the same negative repository discovery remains consistent');
+ assert.equal(result.repeatedCalls, 0, 'a repeated installed-source read does not retry Git discovery');
+});