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(resume): reuse fresh command read facts [N26,A6,C7]

Corey Olson39b007ada950
diff --git a/src/cli.js b/src/cli.js
index b624b67a..ffa41ba6 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -139,6 +139,7 @@ import {
invalidateGitFacts,
isClean,
mainCheckout,
+ worktreeEntries,
repoInfo,
resolveCommit,
tryGit,
@@ -1903,10 +1904,7 @@ export function primaryCheckoutRoot(info) {
for (const candidate of candidates) {
if (typeof candidate !== 'string' || !isAbsolute(candidate)) continue;
try {
- const result = tryGit(candidate, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir']);
- const fields = result.stdout.split('\n');
- if (result.status !== 0 || fields.length !== 3 || fields.some((field) => !field)) continue;
- const [root, gitDir, candidateCommonDir] = fields;
+ const { root, gitDir, commonDir: candidateCommonDir } = repoInfo(candidate);
if (!existsSync(join(root, '.git'))
|| realpathSync.native(candidateCommonDir) !== commonDir
|| realpathSync.native(gitDir) !== realpathSync.native(candidateCommonDir)) continue;
@@ -1915,14 +1913,10 @@ export function primaryCheckoutRoot(info) {
}
return [...roots.values()];
};
- const worktrees = tryGit(info.root, ['worktree', 'list', '--porcelain', '-z']);
- if (worktrees.status === 0) {
- const candidates = worktrees.stdout.split('\0')
- .filter((field) => field.startsWith('worktree '))
- .map((field) => field.slice('worktree '.length));
- const found = matches(candidates);
+ try {
+ const found = matches(worktreeEntries(info.root).map(entry => entry.path));
if (found.length === 1) return found[0];
- }
+ } catch { /* Registry recovery below remains available when Git cannot enumerate worktrees. */ }
const registered = registeredProjectRootsSnapshot();
if (registered === null) return null;
const found = matches(registered);
diff --git a/src/commands/resume.js b/src/commands/resume.js
index 761b8223..77b6aa4d 100644
--- a/src/commands/resume.js
+++ b/src/commands/resume.js
@@ -25,6 +25,7 @@ import {
import {
repoInfo,
tryGit,
+ worktreeEntries,
} from '../git.js';
import {
scanHealthSentinel,
@@ -36,7 +37,7 @@ import {
takeDecisionNotices,
} from '../implies.js';
import {
- personNeedsState,
+ personNeedsSummary,
} from '../needs-state.js';
import {
personNeeds,
@@ -170,7 +171,7 @@ export async function resumeHere(io, view) {
const staleVerdicts = pendingMerges.filter(item => item.item_verdict_state);
const decisionSections = isMain ? coordinatorDecisionSections(board, ctx) : null;
const { shouts = [], ...decisions } = decisionSections ?? {};
- const needsState = personNeedsState(root, { board, includeRigorUndrafted: me.id === COORDINATOR });
+ const needsState = personNeedsSummary(root, { board, config: ctx.config, includeFit: true, includeRigorUndrafted: me.id === COORDINATOR });
return {
me,
all,
@@ -246,7 +247,7 @@ export async function resumeHere(io, view) {
if (!isMain) {
const branch = tryGit(root, ['rev-parse', '--abbrev-ref', 'HEAD']).stdout || 'HEAD';
// Against the main checkout's branch, not its HEAD, which is detached while the coordinator verifies.
- const mainRef = /^branch (.+)$/m.exec(tryGit(root, ['worktree', 'list', '--porcelain']).stdout.split('\n\n')[0])?.[1];
+ const mainRef = worktreeEntries(root)[0]?.branch;
const [behind = 0, ahead = 0] = mainRef ? tryGit(root, ['rev-list', '--left-right', '--count', `${mainRef}...HEAD`]).stdout.split(/\s+/).map(Number) : [];
const against = mainRef ? `${ahead} ahead of main, ${behind} behind${behind ? ' (merge main before you submit)' : ''}` : 'main is detached for a verification, so ahead and behind are unknown';
say(`branch ${branch}: ${against}${dirty ? `; ${plural(dirty, 'file')} uncommitted` : ''}`);
diff --git a/src/doctrine-rulings.js b/src/doctrine-rulings.js
index d599ff59..14a8ad44 100644
--- a/src/doctrine-rulings.js
+++ b/src/doctrine-rulings.js
@@ -19,7 +19,6 @@ import {
} from 'node:path';
import * as store from './board.js';
import {
- CONFIG_FILE,
DOCTRINE_FILE,
LEGACY_DOCTRINE_FILE,
} from './config.js';
@@ -29,8 +28,8 @@ import {
loadDoctrine,
} from './doctrine.js';
import {
- git,
mainCheckout,
+ worktreeEntries,
resolveCommit,
tryGit,
} from './git.js';
@@ -81,13 +80,17 @@ export function agentDoctrine(ctx, board) {
const commit = primary?.commit ?? (retained ? resolveCommit(root, retained) : null);
let doctrine = ctx.doctrine;
let name = doctrine.name;
- if (commit && tryGit(root, ['show', `${commit}:${CONFIG_FILE}`]).status === 0) {
- const read = doctrineAt(root, commit, policyAt(root, commit).config.practice);
+ let policy = null;
+ if (commit) {
+ try { policy = policyAt(root, commit); }
+ catch (error) { if (!(error instanceof Refused) || error.code !== 'NO_POLICY') throw error; }
+ }
+ if (policy) {
+ const read = doctrineAt(root, commit, policy.config.practice);
name = read.name;
doctrine = doctrineFromSource(read.source, name);
}
- const entry = git(root, ['worktree', 'list', '--porcelain', '-z']).split('\0')[0];
- const primaryRoot = entry.startsWith('worktree ') ? entry.slice('worktree '.length) : null;
+ const primaryRoot = worktreeEntries(root)[0]?.path ?? null;
const file = primaryRoot && join(primaryRoot, name);
const current = file && existsSync(file) ? readFileSync(file, 'utf8') : null;
return appliedDoctrine(doctrine, store.rowDecisions(board), current);
diff --git a/src/git.js b/src/git.js
index de73fbb1..f17dfacc 100644
--- a/src/git.js
+++ b/src/git.js
@@ -357,12 +357,36 @@ export function mainCheckout(root) {
return fact(`mainCheckout:${resolve(root)}`, () => readMainCheckout(root));
}
+/** Read one canonical worktree enumeration per command; sanitized authority facts have a separate key. */
+export function worktreeEntries(root, { clean = false } = {}) {
+ return fact(`worktreeEntries:${resolve(root)}:${clean}`, () => {
+ const result = tryGit(root, ['worktree', 'list', '--porcelain', '-z'], { env: clean ? cleanGitEnvironment() : process.env });
+ if (result.status !== 0) throw new Refused('NO_POLICY', 'the primary checkout cannot be located; restore the repository and ask the coordinator to retry');
+ return result.stdout.split('\0\0').filter(Boolean).map(block => {
+ const fields = block.split('\0');
+ return { path: fields.find(field => field.startsWith('worktree '))?.slice(9),
+ head: fields.find(field => field.startsWith('HEAD '))?.slice(5),
+ branch: fields.find(field => field.startsWith('branch '))?.slice(7),
+ bare: fields.includes('bare'), prunable: fields.some(field => /^prunable(?: |$)/u.test(field)) };
+ });
+ });
+}
+
/** 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 primary = worktreeEntries(root, { clean: true })[0];
+ if (primary && !primary.bare) {
+ if (!primary.path || !/^[a-f0-9]{40,64}$/u.test(primary.head ?? '')) throw new Refused('NO_POLICY', 'the primary checkout metadata is incomplete; restore its Git metadata and ask the coordinator to retry');
+ if (!primary.branch) return null;
+ const resolved = tryGit(root, ['rev-parse', '--verify', '--quiet', `${primary.branch}^{commit}`], { env: cleanGitEnvironment() });
+ if (resolved.status !== 0 && resolved.status !== 1) throw new Refused('NO_POLICY', 'the primary checkout commit cannot be read; restore its Git objects and ask the coordinator to retry');
+ return { branch: primary.branch, commit: resolved.status === 0 ? resolved.stdout : null };
+ }
+ // Bare repositories retain the existing explicit-ref fallback; their listing omits the branch.
const env = cleanGitEnvironment();
/** Run one Git lookup with the sanitized environment. */
const gitCall = (args) => spawnSync('git', [...GIT_FLAGS, ...args], {
diff --git a/src/health.js b/src/health.js
index 2a2df568..c4118800 100644
--- a/src/health.js
+++ b/src/health.js
@@ -6,7 +6,6 @@
* It reads the board through a read-only SQLite connection and asks git only questions that leave
* every checkout alone: merge-tree writes a tree object and never an index or a working tree.
*/
-import { execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { missedJobFindings } from './recurring-jobs.js';
import {
@@ -15,6 +14,7 @@ import {
} from './config.js';
import {
mainCheckout,
+ worktreeEntries,
tryGit,
} from './git.js';
import { gateControlFindings } from './gate-control.js';
@@ -450,6 +450,8 @@ function unlanded(item, { since, now, trunk, root, byId, stacked }) {
* tag (v1.2.3 or 1.2.3), and the work is every item first recorded merged after that tag.
*/
function releaseOverdue(db, root, now, deadlineMs, history) {
+ const merged = db.prepare("SELECT item_id FROM item WHERE item_status = 'verified' AND item_merged_commit IS NOT NULL ORDER BY item_id").all();
+ if (!merged.length) return null;
const tags = tryGit(root, ['for-each-ref', '--sort=-creatordate', '--format=%(refname:short)%09%(creatordate:iso-strict)', 'refs/tags']);
if (tags.status !== 0 || !tags.stdout) return null;
const latest = tags.stdout.split('\n').map((line) => line.split('\t')).find(([name]) => /^v?\d+\.\d+\.\d+$/u.test(name ?? ''));
@@ -458,7 +460,7 @@ function releaseOverdue(db, root, now, deadlineMs, history) {
const published = Date.parse(dated);
if (!Number.isFinite(published) || now - published < deadlineMs) return null;
const landed = [];
- for (const item of db.prepare("SELECT item_id FROM item WHERE item_status = 'verified' AND item_merged_commit IS NOT NULL ORDER BY item_id").all()) {
+ for (const item of merged) {
const first = history.get(item.item_id)?.firstMerged;
if (first && Date.parse(first) > published) landed.push(item.item_id);
}
@@ -519,7 +521,11 @@ function unansweredAsks(db) {
/** The primary checkout's branch and commit, or the retained trunk's, or null when neither reads. */
function trunkTip(root) {
let ref;
- try { ref = mainCheckout(root)?.branch ?? trunkRef(root); } catch { return null; /* A repo with no readable trunk skips merge checks. */ }
+ try {
+ const primary = mainCheckout(root);
+ ref = primary?.branch ?? trunkRef(root);
+ if (primary?.commit && ref.startsWith('refs/heads/')) return { name: ref.replace(/^refs\/heads\//u, ''), commit: primary.commit };
+ } catch { return null; /* A repo with no readable trunk skips merge checks. */ }
if (!ref?.startsWith('refs/heads/')) return null;
const tip = tryGit(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
return tip.status === 0 ? { name: ref.replace(/^refs\/heads\//u, ''), commit: tip.stdout } : null;
@@ -596,8 +602,7 @@ export function healthLines(report) {
*/
function goneWorktrees(root) {
try {
- const listing = execFileSync('git', ['worktree', 'list', '--porcelain'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
- return new Set(listing.split('\n\n').filter((block) => /^prunable\b/mu.test(block)).map((block) => /^worktree (.+)$/mu.exec(block)?.[1]).filter(Boolean));
+ return new Set(worktreeEntries(root).filter(entry => entry.prunable).map(entry => entry.path).filter(Boolean));
} catch { return new Set(); }
}
diff --git a/src/needs-state.js b/src/needs-state.js
index da50a011..18a3a0a0 100644
--- a/src/needs-state.js
+++ b/src/needs-state.js
@@ -46,16 +46,20 @@ export function personNeedsState(root, { board: providedBoard = null, includeRig
}
}
-/** Keep status's complete obligation list without dashboard history, Git ages, or release notes. */
-export function personNeedsSummary(root, { board, config }) {
+/** Keep complete obligations without dashboard history; resume also retains fit and undrafted Rigor. */
+export function personNeedsSummary(root, { board, config, includeFit = false, includeRigorUndrafted = false }) {
const spec = loadSpec(root, config);
const rows = projectRowDecisions(store.rowDecisions(board), { root, spec: spec.rows, practice: loadDoctrine(root, config).rows });
- const projected = projectSpecApprovals({ ...rows,
+ const state = { ...rows,
decisions: store.openDecisions(board, store.PERSON), holds: store.laneHolds(board),
agents: store.listAgents(board).map(agent => ({ ...agent, displayName: displayAgentName(agent, config.agents.names) })),
rigorDrafts: rigorDraftNeeds(rows), sentinelDrafts: sentinelDraftNeeds(sentinels(board)), blocks: recentBlocks(repoInfo(root).commonDir, board),
- }, specApprovalState(root, { board, config, spec }));
- return projected;
+ };
+ // Resume consumes obligations, not dashboard items; fit still projects every current row and proposal.
+ const fitted = includeFit ? projectFit(pendingFit(repoInfo(root).commonDir), { ...state, items: [] }) : state;
+ const projected = projectSpecApprovals(fitted, specApprovalState(root, { board, config, spec }));
+ return { ...projected, ...(includeRigorUndrafted
+ ? { rigorUndrafted: undraftedRigor(store.events(board), rows, { person: store.PERSON }) } : {}) };
}
/** The person's blocks from the last day, by the board's clock, for Needs you [C6]. */
diff --git a/test/git-calls.test.js b/test/git-calls.test.js
index 47fa3857..1a4cd528 100644
--- a/test/git-calls.test.js
+++ b/test/git-calls.test.js
@@ -118,6 +118,41 @@ test('help starts no Git and linked-worktree status spawns at most four Git proc
assert.equal(JSON.parse(status.result.stdout).me.id, 'core-1');
});
+test('primary checkout facts reuse one canonical listing and refresh on Git changes [C7,N26]', (t) => {
+ const box = fixture(t);
+ box.git(box.repo, 'branch', '-m', 'main', 'trunk');
+ const result = readFactScenario(box, box.worker, `
+import assert from 'node:assert/strict';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { mainCheckout, tryGit, worktreeEntries } from ${JSON.stringify(GIT_MODULE)};
+const root = process.argv[1];
+const primary = ${JSON.stringify(box.repo)};
+await withGitFacts(async () => {
+ writeFileSync(process.env.PULLBOARD_GIT_CALLS, '');
+ const first = mainCheckout(root);
+ assert.equal(first.branch, 'refs/heads/trunk');
+ assert.deepEqual(mainCheckout(root), first);
+ assert.equal(worktreeEntries(root, { clean: true })[0].branch, first.branch);
+ assert.equal(readFileSync(process.env.PULLBOARD_GIT_CALLS, 'utf8').trim().split('\\n').filter(Boolean).length, 2);
+ assert.equal(first.commit, headCommit(primary));
+ assert.equal(tryGit(primary, ['branch', '-m', 'trunk', 'renamed']).status, 0);
+ assert.equal(mainCheckout(root).branch, 'refs/heads/renamed');
+ assert.equal(tryGit(primary, ['checkout', '--detach', first.commit]).status, 0);
+ assert.equal(mainCheckout(root), null);
+ assert.equal(tryGit(primary, ['switch', 'renamed']).status, 0);
+ assert.equal(mainCheckout(root).branch, 'refs/heads/renamed');
+});
+console.log(JSON.stringify({ green: true }));`);
+ assert.equal(result.green, true);
+ const unborn = join(box.dir, 'unborn');
+ mkdirSync(unborn);
+ box.git(unborn, 'init', '-q', '-b', 'empty-trunk');
+ const empty = readFactScenario(box, unborn, `
+import { mainCheckout } from ${JSON.stringify(GIT_MODULE)};
+console.log(JSON.stringify(mainCheckout(process.argv[1])));`);
+ assert.deepEqual(empty, { branch: 'refs/heads/empty-trunk', commit: null });
+});
+
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',
diff --git a/test/sentinels.test.js b/test/sentinels.test.js
index f3bbaade..b7567523 100644
--- a/test/sentinels.test.js
+++ b/test/sentinels.test.js
@@ -1,7 +1,5 @@
/** Real board watches: exact person approval, automatic execution, owner notices and replay [A6,D1,D3,H16]. */
import assert from 'node:assert/strict';
-import childProcess from 'node:child_process';
-import { syncBuiltinESMExports } from 'node:module';
import { existsSync } from 'node:fs';
import { mkdirSync } from 'node:fs';
import { mkdtempSync } from 'node:fs';
@@ -85,32 +83,6 @@ function fixture(t, { agentRoute } = {}) {
run: () => runDueSentinels({ root, board, agentId: 'coordinator', ordered }) };
}
-/** Observe one private fixture call's synchronous child costs, delegating its exact inputs unchanged. */
-function traceFixtureProcesses() {
- const methods = ['spawnSync', 'execFileSync'];
- const originals = Object.fromEntries(methods.map(method => [method, childProcess[method]]));
- const calls = [];
- for (const method of methods) {
- /** Preserve the actual process call and record only bounded private-fixture Git arguments. */
- childProcess[method] = function (...args) {
- const began = performance.now();
- try { return Reflect.apply(originals[method], this, args); }
- finally {
- if (calls.length < 80) calls.push({ method, program: String(args[0]),
- ...(String(args[0]).split('/').at(-1) === 'git' ? { args: args[1] } : {}), ms: performance.now() - began });
- }
- };
- }
- syncBuiltinESMExports();
- return { calls,
- /** Restore every builtin before assertions, diagnostics, cleanup or a different command. */
- stop() {
- for (const method of methods) childProcess[method] = originals[method];
- syncBuiltinESMExports();
- },
- };
-}
-
/** Quote only a controlled fixture path as a shell word. */
function quote(word) { return `'${word.replaceAll("'", "'\\''")}'`; }
@@ -172,17 +144,9 @@ console.log('explicit trunk receipt: '+value);
assert.equal(approved.code, 0, approved.error || JSON.stringify(approved.document));
// The frozen bar measures ordinary in-process handling after setup, not module loading or cold CLI startup.
- const processTrace = traceFixtureProcesses();
const began = performance.now();
- let resumed;
- let elapsed;
- try { resumed = await box.cli(['resume'], undefined, agentRoot); }
- finally {
- elapsed = performance.now() - began;
- processTrace.stop();
- t.diagnostic(JSON.stringify({ observation: 'resume synchronous child calls', calls: processTrace.calls,
- qualification: 'delegated original arguments/options; observer overhead and unobserved JS/SQLite remain; overlapping calls are not additive' }));
- }
+ const resumed = await box.cli(['resume'], undefined, agentRoot);
+ const elapsed = performance.now() - began;
assert.equal(resumed.code, 0, resumed.error || JSON.stringify(resumed.document));
assert.ok(elapsed < 100, `resume took ${elapsed.toFixed(3)} ms with a due 30 s sentinel`); // budget: declared by item #1042 and coordinator24324: in-process resume under100ms after setup.
assert.equal(existsSync(marker), false, 'resume neither runs the watch nor detaches a checker into the agent session');