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(core): cache Git facts per command [C7]

Corey Olson9ebc852ee73f
diff --git a/src/cli.js b/src/cli.js
index 71560c17..1e459227 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -14,7 +14,7 @@ import { doctrineHistory, loadDoctrine } from './doctrine.js';
import { requirePersonChannel } from './person.js';
import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
import { digestOf, gateReport, runGate, runShell, withGateSlot } from './gate.js';
-import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked } from './git.js';
+import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';
import {
FIX_NOTE,
applyFixers,
@@ -1717,6 +1717,7 @@ async function sweepHere(ctx, board, me, values) {
}
const max = values.max === undefined ? 20 : idArg(values.max, 'a number after --max');
const ran = spawnSync(report, { cwd: ctx.info.root, shell: true, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
+ invalidateGitFacts();
const problems = parseProblems(`${ran.stdout ?? ''}\n${ran.stderr ?? ''}`, ctx.info.root);
if (!problems.length) {
ctx.io.say(`the checker reported no problems I can read (exit ${ran.status}); nothing to file`);
@@ -1734,6 +1735,7 @@ async function sweepHere(ctx, board, me, values) {
const blind = [];
for (const item of items) {
const canary = spawnSync(item.check, { cwd: ctx.info.root, shell: true, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+ invalidateGitFacts();
if (canary.status === 0) {
blind.push(item.file);
continue;
@@ -2440,8 +2442,14 @@ function rememberTrunk(io) {
/** Run one command and emit its single versioned JSON result when requested (A1). */
export async function main(argv, streams) {
+ return withGitFacts(() => runMain(argv, streams));
+}
+
+/** Parse, synchronize and execute one command inside its isolated Git-fact cache. */
+async function runMain(argv, streams) {
const io = commandOutput(argv, streams);
let sync = true;
+ let needsRepo = true;
try {
const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
const command = parsed.positionals[0];
@@ -2449,7 +2457,8 @@ export async function main(argv, streams) {
positionals: parsed.positionals.slice(1),
values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };
sync = Boolean(command) && !parsed.values.help && !parsed.values.version && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command);
- } catch { sync = false; }
+ needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');
+ } catch { sync = false; needsRepo = false; }
/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
const retry = async () => {
try { await syncRelay(io.cwd, io); }
@@ -2458,7 +2467,7 @@ export async function main(argv, streams) {
if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);
}
};
- rememberTrunk(io);
+ if (needsRepo) rememberTrunk(io);
if (sync) {
await retry();
try { await executePersonRequests(io.cwd, io, main); }
diff --git a/src/gate.js b/src/gate.js
index ff91eccb..63834625 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -6,7 +6,7 @@
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
-import { gitChildEnv, gitPath, headTree, isClean, untracked } from './git.js';
+import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';
import { Refused } from './refused.js';
import { takeResource } from './resources.js';
import { loadMachineSettings } from './settings.js';
@@ -97,6 +97,7 @@ export function runShell(root, command) {
const started = Date.now();
// Newlines, not spaces, around the command, so a trailing comment in it cannot swallow the `)`.
const result = spawnSync(`(\n${command}\n) 2>&1`, { cwd: root, env: gitChildEnv(root), shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', maxBuffer: 2 ** 30 });
+ invalidateGitFacts();
return { isGreen: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}`, seconds: Math.round((Date.now() - started) / 1000) };
}
diff --git a/src/git.js b/src/git.js
index 00ebf3aa..bd425b4d 100644
--- a/src/git.js
+++ b/src/git.js
@@ -3,11 +3,77 @@
* and whether the tree is clean. Every call is a plain `git` child process.
*/
import { execFileSync, spawnSync } from 'node:child_process';
+import { AsyncLocalStorage } from 'node:async_hooks';
import { existsSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { Refused } from './refused.js';
const GIT_FLAGS = ['--no-replace-objects', '-c', 'core.quotepath=false'];
+const gitFacts = new AsyncLocalStorage();
+
+/** Reuse facts within one CLI invocation, while isolating concurrent commands and expiring settled ones.
+ *
+ * @param {() => unknown} work
+ * @returns {Promise<unknown>}
+ */
+export async function withGitFacts(work) {
+ const cache = { active: true, facts: new Map() };
+ return gitFacts.run(cache, async () => {
+ try { return await work(); }
+ finally {
+ cache.active = false;
+ cache.facts.clear();
+ }
+ });
+}
+
+/** Drop facts after this command changes Git state such as refs, configuration, or worktrees. */
+export function invalidateGitFacts() {
+ gitFacts.getStore()?.facts.clear();
+}
+
+/** Return one cached value for this command, or compute it when no command scope is active.
+ *
+ * @param {string} key
+ * @param {() => any} read
+ * @returns {any}
+ */
+function fact(key, read) {
+ const cache = gitFacts.getStore();
+ if (!cache?.active) return read();
+ if (cache.facts.has(key)) return cache.facts.get(key);
+ const value = read();
+ cache.facts.set(key, value);
+ return value;
+}
+
+/** Read one Git config value with its status, reusing the same query for this command.
+ *
+ * @param {string} root
+ * @param {string} key
+ * @param {{ local?: boolean, clean?: boolean, flags?: boolean, noReplace?: boolean }} [options]
+ * @returns {{ status: number, stdout: string }}
+ */
+export function gitConfig(root, key, { local = false, clean = false, flags = true, noReplace = false } = {}) {
+ const args = [...(noReplace ? ['--no-replace-objects'] : []), ...(flags ? GIT_FLAGS : []), 'config', ...(local ? ['--local'] : []), '--get', key];
+ const cacheKey = JSON.stringify(['config', resolve(root), args, clean]);
+ return fact(cacheKey, () => {
+ const result = spawnSync('git', args, { cwd: root, env: clean ? cleanGitEnvironment() : process.env, encoding: 'utf8' });
+ return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim() };
+ });
+}
+
+/** Git operations whose successful completion can change a cached repository fact. */
+function changesGitFacts(args) {
+ const words = args.filter((arg, index) => !arg.startsWith('-') && args[index - 1] !== '-c');
+ const [command, subcommand] = words;
+ if (['checkout', 'switch', 'commit', 'reset', 'update-ref', 'merge', 'rebase', 'cherry-pick', 'stash'].includes(command)) return true;
+ if (command === 'worktree') return ['add', 'remove', 'prune', 'move', 'lock', 'unlock'].includes(subcommand);
+ if (command === 'config') return !args.some((arg) => ['--get', '--get-all', '--get-regexp', '--list', '--show-origin', '--show-scope'].includes(arg));
+ if (command === 'branch') return !args.includes('--list') && !args.includes('-a') && !args.includes('-r');
+ if (command === 'symbolic-ref') return !args.some((arg) => ['--quiet', '-q', '--short'].includes(arg));
+ return false;
+}
/** Clear inherited Git selectors while retaining ordinary user settings and exact-object behavior.
*
@@ -27,6 +93,15 @@ export function cleanGitEnvironment() {
* @returns {{branch: string, commit: string|null}|null}
*/
export function mainCheckout(root) {
+ return fact(`mainCheckout:${resolve(root)}`, () => readMainCheckout(root));
+}
+
+/** Resolve the primary checkout without assuming its branch is named main.
+ *
+ * @param {string} root
+ * @returns {{ branch: string, commit: string | null } | null}
+ */
+function readMainCheckout(root) {
const env = cleanGitEnvironment();
/** Run one Git lookup with the sanitized environment. */
const gitCall = (args) => spawnSync('git', [...GIT_FLAGS, ...args], {
@@ -68,12 +143,16 @@ export function gitChildEnv(root) {
* @returns {string}
*/
export function git(cwd, args, { maxBuffer } = {}) {
- return execFileSync('git', [...GIT_FLAGS, ...args], {
- cwd,
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'pipe'],
- ...(maxBuffer === undefined ? {} : { maxBuffer }),
- }).trim();
+ try {
+ return execFileSync('git', [...GIT_FLAGS, ...args], {
+ cwd,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ ...(maxBuffer === undefined ? {} : { maxBuffer }),
+ }).trim();
+ } finally {
+ if (changesGitFacts(args)) invalidateGitFacts();
+ }
}
/**
@@ -85,6 +164,7 @@ export function git(cwd, args, { maxBuffer } = {}) {
*/
export function tryGit(cwd, args) {
const result = spawnSync('git', [...GIT_FLAGS, ...args], { cwd, encoding: 'utf8' });
+ if (changesGitFacts(args)) invalidateGitFacts();
return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim() };
}
@@ -135,15 +215,23 @@ export function bareWorktreeFinding(cwd) {
* @returns {{ root: string, commonDir: string, gitDir: string, isMain: boolean }}
*/
export function repoInfo(cwd) {
- const top = tryGit(cwd, ['rev-parse', '--show-toplevel']);
- if (top.status !== 0) {
+ return fact(`repoInfo:${resolve(cwd)}`, () => readRepoInfo(cwd));
+}
+
+/** Read top level, worktree Git dir and shared Git dir in one process.
+ *
+ * @param {string} cwd
+ * @returns {{ root: string, commonDir: string, gitDir: string, isMain: boolean }}
+ */
+function readRepoInfo(cwd) {
+ const info = tryGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir']);
+ const fields = info.stdout.split('\n');
+ if (info.status !== 0 || fields.length !== 3 || fields.some((field) => !field)) {
const bare = bareWorktreeFinding(cwd);
if (bare) throw new Refused(bare.code, `${bare.message}; run ${bare.next}`);
throw new Refused('NOT_A_REPO', 'not inside a git work tree; run git init, or cd into a repo');
}
- const root = top.stdout;
- const commonDir = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
- const gitDir = git(root, ['rev-parse', '--path-format=absolute', '--git-dir']);
+ const [root, gitDir, commonDir] = fields;
return { root, commonDir, gitDir, isMain: commonDir === gitDir };
}
@@ -155,8 +243,11 @@ export function repoInfo(cwd) {
* @returns {string | null}
*/
export function resolveCommit(root, ref) {
- const result = tryGit(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
- return result.status === 0 ? result.stdout : null;
+ if (ref === 'HEAD') return headCommit(root);
+ return fact(`resolveCommit:${resolve(root)}:${ref}`, () => {
+ const result = tryGit(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
+ return result.status === 0 ? result.stdout : null;
+ });
}
/**
@@ -166,7 +257,10 @@ export function resolveCommit(root, ref) {
* @returns {string | null}
*/
export function headCommit(root) {
- return resolveCommit(root, 'HEAD');
+ return fact(`headCommit:${resolve(root)}`, () => {
+ const result = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);
+ return result.status === 0 ? result.stdout : null;
+ });
}
/**
@@ -176,8 +270,10 @@ export function headCommit(root) {
* @returns {string | null}
*/
export function headTree(root) {
- const result = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{tree}']);
- return result.status === 0 ? result.stdout : null;
+ return fact(`headTree:${resolve(root)}`, () => {
+ const result = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{tree}']);
+ return result.status === 0 ? result.stdout : null;
+ });
}
/**
diff --git a/src/hooks.js b/src/hooks.js
index 7546addc..415a46a3 100644
--- a/src/hooks.js
+++ b/src/hooks.js
@@ -6,7 +6,7 @@
import { spawnSync } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
-import { git, gitChildEnv, gitPath, mainCheckout, refuseGrafts, tryGit } from './git.js';
+import { git, gitChildEnv, gitPath, gitConfig, invalidateGitFacts, mainCheckout, refuseGrafts, tryGit } from './git.js';
import { CONFIG_FILE, configFromSource, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE } from './config.js';
import { Refused } from './refused.js';
import { outOfLane } from './lanes.js';
@@ -335,6 +335,7 @@ export function applyFixers(root, fixers) {
encoding: 'utf8',
timeout: 120_000,
});
+ invalidateGitFacts();
if (result.status === 0) git(root, ['add', '--', ...files]);
else notes.push(`fixer "${fixer.run}" failed (${result.status ?? 'timed out'}); staged nothing from it, so the gate will name what it could not fix`);
}
@@ -453,7 +454,7 @@ export function installHooks(root, onWrite = () => {}) {
onWrite(`${HOOKS_DIR}/${hook}`);
notes.push(`wrote ${HOOKS_DIR}/${hook}`);
}
- const current = tryGit(root, ['config', '--get', 'core.hooksPath']).stdout;
+ const current = gitConfig(root, 'core.hooksPath').stdout;
if (current && current !== HOOKS_DIR) {
notes.push(`core.hooksPath is ${current}; left as is. Call pullboard hook <name> from those hooks`);
} else {
diff --git a/src/run.js b/src/run.js
index 9f590e38..cc7760be 100644
--- a/src/run.js
+++ b/src/run.js
@@ -17,7 +17,7 @@ import { briefFiles } from './brief.js';
import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
import { doctrineText, loadDoctrine } from './doctrine.js';
import { digestOf, runGate } from './gate.js';
-import { contains, git, headCommit, isClean, tryGit, untracked } from './git.js';
+import { contains, git, headCommit, invalidateGitFacts, isClean, tryGit, untracked } from './git.js';
import { laneNames, outOfLane } from './lanes.js';
import { Refused } from './refused.js';
@@ -85,6 +85,7 @@ function runCommand(command, { cwd, env = process.env, timeoutMs, log }) {
}, timeoutMs);
child.on('close', (status) => {
clearTimeout(timer);
+ invalidateGitFacts();
done({ status, output, timedOut, seconds: Math.round((Date.now() - started) / 1000) });
});
});
@@ -209,7 +210,10 @@ function commitWork(root, item, config, paths) {
let output = '';
for (const plain of [false, true]) {
const result = spawnSync('git', ['commit', '-q', '-m', commitHeader(item, config.commits, plain)], { cwd: root, encoding: 'utf8' });
- if (result.status === 0) return { ok: true, output: '' };
+ invalidateGitFacts();
+ if (result.status === 0) {
+ return { ok: true, output: '' };
+ }
output = `${result.stdout}${result.stderr}`;
}
return { ok: false, output };
@@ -260,8 +264,12 @@ async function mergeDependencies(ctx, item, deps) {
.filter((before) => before.item_commit && !contains(root, before.item_commit, 'HEAD'));
for (const before of needed) {
const merged = spawnSync('git', ['merge', '--no-edit', '-q', before.item_commit], { cwd: root, encoding: 'utf8' });
- if (merged.status === 0) continue;
+ invalidateGitFacts();
+ if (merged.status === 0) {
+ continue;
+ }
spawnSync('git', ['merge', '--abort'], { cwd: root });
+ invalidateGitFacts();
await deps.withBoard(ctx, async (board) => deps.ordered ? deps.ordered(ctx, board, 'release', [item.item_id, deps.whoAmI(ctx, board).id]) : store.release(board, item.item_id, deps.whoAmI(ctx, board).id));
throw new Refused('MERGE_CONFLICT', `#${item.item_id} waits on #${before.item_id}, whose commit ${before.item_commit.slice(0, 12)} conflicts with this worktree; the coordinator integrates it, then run again`);
}
diff --git a/src/signature.js b/src/signature.js
index 5ad0fd1b..4226e841 100644
--- a/src/signature.js
+++ b/src/signature.js
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
import { homedir, tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
+import { gitConfig } from './git.js';
import { Refused } from './refused.js';
export const SIGNERS_FILE = '.pullboard/signers';
@@ -36,8 +37,8 @@ function runTool(command, args, { cwd, input, inherit = false } = {}) {
/** Read Git's configured identity or signing key from its normal config chain. */
function gitSetting(root, key) {
- const result = spawnSync('git', ['config', '--get', key], { cwd: root, encoding: 'utf8' });
- return result.status === 0 ? result.stdout.trim() : '';
+ const result = gitConfig(root, key, { flags: false });
+ return result.status === 0 ? result.stdout : '';
}
/** Resolve the public or private key path supplied by the caller or the repo's Git settings. */
diff --git a/src/trusted-policy.js b/src/trusted-policy.js
index 841038e4..99f72cd3 100644
--- a/src/trusted-policy.js
+++ b/src/trusted-policy.js
@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { configFromSource } from './config.js';
-import { cleanGitEnvironment, mainCheckout, refuseGrafts } from './git.js';
+import { cleanGitEnvironment, gitConfig, invalidateGitFacts, mainCheckout, refuseGrafts } from './git.js';
import { outOfLane } from './lanes.js';
import { Refused } from './refused.js';
@@ -27,15 +27,14 @@ export function mainPolicy(root) {
/** Retain the local primary branch outside replicated board data and read-only diagnostics [B34,V6]. */
export function trunkRef(root, branch) {
- const read = spawnSync('git', ['--no-replace-objects', 'config', '--local', '--get', 'pullboard.trunk'], {
- cwd: root, env: cleanGitEnvironment(), encoding: 'utf8',
- });
+ const read = gitConfig(root, 'pullboard.trunk', { local: true, clean: true, flags: false, noReplace: true });
if (read.status !== 0 && read.status !== 1) throw new Refused('NO_POLICY', 'the retained trunk cannot be read; restore the local Git configuration and retry');
const current = read.status === 0 ? read.stdout.trim() : null;
if (branch === undefined || branch === current) return current;
const saved = spawnSync('git', ['--no-replace-objects', 'config', '--local', '--replace-all', 'pullboard.trunk', branch], {
cwd: root, env: cleanGitEnvironment(), encoding: 'utf8',
});
+ invalidateGitFacts();
if (saved.status !== 0) throw new Refused('NO_POLICY', 'the trunk branch cannot be recorded; restore writable local Git configuration and retry');
return branch;
}
diff --git a/test/git-calls.test.js b/test/git-calls.test.js
new file mode 100644
index 00000000..13d2df70
--- /dev/null
+++ b/test/git-calls.test.js
@@ -0,0 +1,177 @@
+/** Count real Git child processes and prove command-scoped facts refresh after a commit [C7]. */
+import assert from 'node:assert/strict';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { delimiter, join, resolve } from 'node:path';
+import { tmpdir } from 'node:os';
+import { test } from 'node:test';
+import { headCommit, withGitFacts } from '../src/git.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+
+/** Find the real Git executable before the fixture adds its counting shim to PATH. */
+function realGitPath() {
+ const path = process.env.PATH.split(delimiter).map((entry) => join(entry || '.', 'git'));
+ const found = path.find((candidate) => existsSync(candidate));
+ assert.ok(found, 'the test environment has Git on PATH');
+ return found;
+}
+
+/** Build a private real repo and linked agent worktree with an instrumented Git executable. */
+function fixture(t) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-git-calls-'));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const repo = join(dir, 'repo');
+ const worker = join(dir, 'worker');
+ const home = join(dir, 'home');
+ const shims = join(dir, 'shims');
+ const calls = join(dir, 'git-calls.log');
+ mkdirSync(repo);
+ mkdirSync(shims);
+ const realGit = realGitPath();
+ const gitShim = join(shims, 'git');
+ const pullboardShim = join(shims, 'pullboard');
+ writeFileSync(gitShim, '#!/bin/sh\nprintf "git\\n" >> "$PULLBOARD_GIT_CALLS"\nexec "$PULLBOARD_REAL_GIT" "$@"\n');
+ chmodSync(gitShim, 0o755);
+ writeFileSync(pullboardShim, `#!/bin/sh\nexec '${process.execPath}' '${BIN}' "$@"\n`);
+ chmodSync(pullboardShim, 0o755);
+ const env = {
+ ...process.env,
+ HOME: home,
+ USERPROFILE: home,
+ PULLBOARD_HOME: join(home, '.pullboard'),
+ PULLBOARD_MACHINE_HOME: join(home, '.pullboard-machine'),
+ PULLBOARD_GIT_CALLS: calls,
+ PULLBOARD_REAL_GIT: realGit,
+ PATH: `${shims}${delimiter}${process.env.PATH}`,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Test Agent',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test Agent',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({
+ spec: 'SPEC.md', practice: 'DOCTRINE.md', gate: 'true',
+ lanes: { core: { owns: ['src/'], specs: ['C7'] } },
+ }));
+ writeFileSync(join(repo, 'SPEC.md'), '# Test spec\n\n## C · Core\n- C7 [approved, must] A command reads each Git fact once. | gate: test/git-calls.test.js\n');
+ const git = (cwd, ...args) => execFileSync(realGit, args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
+ const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 60_000 });
+ const ok = (cwd, ...args) => {
+ const result = run(cwd, ...args);
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ return result;
+ };
+ git(repo, 'init', '-q', '-b', 'main');
+ ok(repo, 'init');
+ git(repo, 'add', '-A');
+ git(repo, 'commit', '-q', '-m', 'chore(repo): initialize Git-call fixture');
+ git(repo, 'worktree', 'add', '-q', '-b', 'core/worker', worker);
+ ok(worker, 'join', 'core', '--route', 'light', '--family', 'codex');
+ return { dir, repo, worker, calls, env, git, run, ok };
+}
+
+/** Clear the per-command count and read the number of Git processes the CLI started. */
+function resetAndCount(box, cwd, ...args) {
+ writeFileSync(box.calls, '');
+ const result = box.run(cwd, ...args);
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+ const count = readFileSync(box.calls, 'utf8').trim().split('\n').filter(Boolean).length;
+ return { result, count };
+}
+
+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');
+ assert.equal(version.count, 0, '--version has no repository work to do');
+ const help = resetAndCount(box, box.dir, 'help');
+ assert.equal(help.count, 0, 'global help has no repository work to do');
+ const status = resetAndCount(box, box.worker, 'status', '--json');
+ assert.ok(status.count <= 4, `linked-worktree status started ${status.count} Git processes`);
+ assert.equal(JSON.parse(status.result.stdout).me.id, 'core-1');
+});
+
+test('a runner sees the new HEAD after it commits its item [C7]', (t) => {
+ const box = fixture(t);
+ box.ok(box.repo, 'add', 'core', 'Refresh cached HEAD', '--specs', 'C7', '--route', 'light',
+ '--criterion', 'the runner reads the commit it just made', '--check', 'test -f src/result.txt',
+ '--brief', 'Files: src/result.txt\nTest: the runner creates the result file.');
+ const agent = join(box.dir, 'agent.sh');
+ writeFileSync(agent, '#!/bin/sh\nmkdir -p src\nprintf result > src/result.txt\n');
+ chmodSync(agent, 0o700);
+ const run = box.ok(box.worker, 'run', '--agent-light', `sh ${agent}`, '--items', '1', '--attempts', '1', '--minutes', '1');
+ assert.match(run.stdout, /submitted #1/u);
+ const current = box.git(box.worker, 'rev-parse', 'HEAD');
+ const shown = JSON.parse(box.ok(box.repo, 'show', '1', '--json').stdout);
+ assert.equal(shown.item_commit, current, 'submit records the HEAD created by this command');
+});
+
+/** Create a promise gate for a deterministic overlap between command fact scopes. */
+function deferred() {
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+/** Advance the fixture branch using real Git plumbing without running its checkout hooks. */
+function advanceHead(box, label) {
+ const parent = box.git(box.repo, 'rev-parse', 'HEAD');
+ const tree = box.git(box.repo, 'rev-parse', 'HEAD^{tree}');
+ const commit = execFileSync(box.env.PULLBOARD_REAL_GIT, ['commit-tree', tree, '-p', parent], {
+ cwd: box.repo, env: box.env, input: label, encoding: 'utf8',
+ }).trim();
+ box.git(box.repo, 'update-ref', 'refs/heads/main', commit);
+ return commit;
+}
+
+test('settled and concurrent commands do not share Git-fact caches [C7]', async (t) => {
+ const box = fixture(t);
+ const settledRead = deferred();
+ const releaseSettled = deferred();
+ const settledAgain = deferred();
+ let delayed;
+ await withGitFacts(async () => {
+ const initial = headCommit(box.repo);
+ delayed = (async () => {
+ await releaseSettled.promise;
+ const first = headCommit(box.repo);
+ settledRead.resolve(first);
+ await settledAgain.promise;
+ return headCommit(box.repo);
+ })();
+ assert.equal(headCommit(box.repo), initial, 'facts are reused while this command remains active');
+ });
+ const firstCommit = advanceHead(box, 'expire command cache one');
+ releaseSettled.resolve();
+ assert.equal(await settledRead.promise, firstCommit, 'a callback inherited from a settled command reads fresh Git state');
+ const secondCommit = advanceHead(box, 'expire command cache two');
+ settledAgain.resolve();
+ assert.equal(await delayed, secondCommit, 'the expired callback does not retain its first late read');
+
+ const aRead = deferred();
+ const releaseA = deferred();
+ const bRead = deferred();
+ const releaseB = deferred();
+ const a = withGitFacts(async () => {
+ const first = headCommit(box.repo);
+ aRead.resolve();
+ await releaseA.promise;
+ return [first, headCommit(box.repo)];
+ });
+ await aRead.promise;
+ const thirdCommit = advanceHead(box, 'concurrent command cache one');
+ const b = withGitFacts(async () => {
+ const first = headCommit(box.repo);
+ bRead.resolve();
+ await releaseB.promise;
+ return [first, headCommit(box.repo)];
+ });
+ await bRead.promise;
+ const fourthCommit = advanceHead(box, 'concurrent command cache two');
+ releaseA.resolve();
+ releaseB.resolve();
+ assert.deepEqual(await a, [secondCommit, secondCommit], 'one active command keeps its own fact values');
+ 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');
+});