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
perf(core): bound resume reads and drain failures [C7,N19,N26,D1]
Corey Olson82e3110ede55
diff --git a/src/cli.js b/src/cli.jsindex f684fefa..d8b046fd 100644--- a/src/cli.js+++ b/src/cli.js@@ -1109,11 +1109,11 @@ export function recordSetupState(ctx, identity, state) {renameSync(temporary, file);}-/** Derive the next setup question from the real requirements, config, items and view receipt. */-export function boardSetup(ctx, card, identity) {+/** Derive setup from real inputs; a caller may share its already-read current decision snapshot. */+export function boardSetup(ctx, card, identity, { decisions: capturedDecisions } = {}) {const rows = loadSpec(ctx.info.root, ctx.config).rows;const approved = rows.filter(row => row.status === 'approved');- const decisions = withBoard(ctx, (board) => store.rowDecisions(board));+ const decisions = capturedDecisions ?? withBoard(ctx, (board) => store.rowDecisions(board));const open = setupDecisionRows(ctx.info.root, ctx.config, decisions, rows);const toApply = open.filter(row => row.decision);const drafted = open.filter(row => !row.decision);diff --git a/src/commands/resume.js b/src/commands/resume.jsindex bce00961..0888bd6a 100644--- a/src/commands/resume.js+++ b/src/commands/resume.js@@ -130,9 +130,10 @@ function keylessBookkeeping(send) {* @param {any} io* @param {Awaited<ReturnType<typeof keepViewRunning>>} view what keeping the background view running did* @param {boolean} diagnostics include explicit setup, hook and stale-work inspection+ * @param {{ json?: boolean }} options omit text-only calculations when the versioned result owns the output* @returns {number}*/-export async function resumeHere(io, view, diagnostics = false) {+export async function resumeHere(io, view, diagnostics = false, { json = false } = {}) {const ctx = context(io);const ordered = keylessBookkeeping(sendOrdered);const initialBaseline = withBoardRead(ctx, board => {@@ -151,11 +152,13 @@ export async function resumeHere(io, view, diagnostics = false) {let mainRoot = null;let worktreeConfig = null;let setupScope;+ let setupDecisions;let doctrine;let sources;const card = await withBoardRead(ctx, async (board) => {setupScope = diagnostics ? setupIdentity(board) : null;- sources = await readResumeSources(ctx, board);+ sources = await readResumeSources(ctx, board, { compareBranch: !json, includeHeadDoctrine: diagnostics });+ setupDecisions = diagnostics ? store.rowDecisions(board) : undefined;doctrine = sources.doctrine;if (diagnostics) {mainRoot = sources.primary;@@ -211,7 +214,7 @@ export async function resumeHere(io, view, diagnostics = false) {}const { me } = card;const name = (id) => agentDisplayName(card.agents, ctx.config, id);- if (diagnostics) card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows, staleDoctrineRows(ctx, doctrine)).map((item) => ({ ...item, ...staleItemFinding(item) }));+ if (diagnostics) card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows, staleDoctrineRows(ctx, doctrine, { headDoctrine: sources.headDoctrine })).map((item) => ({ ...item, ...staleItemFinding(item) }));if (isMain && diagnostics) {card.staleFollowUps = { count: card.stale.length + card.staleIntegrations.length,list: 'pullboard resume --diagnostics --json', items: card.stale, integrations: card.staleIntegrations };@@ -241,7 +244,7 @@ export async function resumeHere(io, view, diagnostics = false) {if (card.inbox) for (const line of coordinatorInboxLines(card.inbox, name, (at) => span(ctx, at), firstLine)) say(line);if (diagnostics) {say(`New agent worktrees: ${card.newWorktreeLocation}`);- card.setup = withBoardRead(ctx, board => withStarterWork(boardSetup(ctx, card, setupScope), { board, me, main: isMain, config: ctx.config, root, seat: ctx.io.callerRole() === 'seat' }));+ card.setup = withBoardRead(ctx, board => withStarterWork(boardSetup(ctx, card, setupScope, { decisions: setupDecisions }), { board, me, main: isMain, config: ctx.config, root, seat: ctx.io.callerRole() === 'seat' }));} else say('Setup, hook and stale-work diagnostics: pullboard resume --diagnostics.');if (!loadSpec(root, ctx.config).rows.length && card.all.length) say('Spec rows are optional; add a requirement later: pullboard spec draft "<text>".');if (card.setup) {@@ -252,7 +255,7 @@ export async function resumeHere(io, view, diagnostics = false) {if (card.setup.meanwhile) say(card.setup.meanwhile);}const dirty = diagnostics ? dirtyFiles(root).length : undefined;- if (!isMain) {+ if (!isMain && !json) {const { branch, mainRef, behind = 0, ahead = 0 } = sources;// Fresh command facts compare the actual primary branch, not an unrelated detached review HEAD.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';@@ -345,5 +348,5 @@ export async function resumeHere(io, view, diagnostics = false) {export async function run(io, { values }) {repoInfo(io.cwd);// JSON v1 retains its real diagnostic fields; only the default text card defers them.- return resumeHere(io, await keepViewRunning(), Boolean(values.diagnostics || values.json));+ return resumeHere(io, await keepViewRunning(), Boolean(values.diagnostics || values.json), { json: Boolean(values.json) });}diff --git a/src/committed-file-reader.js b/src/committed-file-reader.jsindex 5302feb6..dc49b979 100644--- a/src/committed-file-reader.js+++ b/src/committed-file-reader.js@@ -73,8 +73,12 @@ export async function withCommittedFiles(root, action) {finally {await pending;child.stdin.end();- child.stdout.resume();+ let drainError;+ try {+ // The iterator retains ownership of stdout even after a rejected frame; resume() does not drain it.+ while (!(await chunks.next()).done) { /* Discard remaining framed bytes after input closes. */ }+ } catch (error) { drainError = error; }const result = await finished;- if (!failed && (result.error || result.code !== 0)) throw new Refused('NO_POLICY', 'the committed-file reader failed; inspect the project with pullboard resume --diagnostics');+ if (!failed && (drainError || result.error || result.code !== 0)) throw new Refused('NO_POLICY', 'the committed-file reader failed; inspect the project with pullboard resume --diagnostics');}}diff --git a/src/doctrine-rulings.js b/src/doctrine-rulings.jsindex d599ff59..82f71fa9 100644--- a/src/doctrine-rulings.js+++ b/src/doctrine-rulings.js@@ -100,11 +100,12 @@ export function agentDoctrine(ctx, board) {** @param {any} ctx the CLI context* @param {any} doctrine the shared doctrine from agentDoctrine+ * @param {{ headDoctrine?: any }} options exact committed HEAD doctrine from the same fresh source batch* @returns {any[]}*/-export function staleDoctrineRows(ctx, doctrine) {+export function staleDoctrineRows(ctx, doctrine, { headDoctrine } = {}) {const working = loadDoctrine(ctx.info.root, ctx.config);- const committed = doctrineFromSource(doctrineAt(ctx.info.root, 'HEAD', working.name).source, working.name);+ const committed = headDoctrine ?? doctrineFromSource(doctrineAt(ctx.info.root, 'HEAD', working.name).source, working.name);const before = new Map(committed.rows.map(row => [row.id, row]));const current = new Map(working.rows.map(row => [row.id, row]));const rows = new Map(doctrine.rows.map(row => [row.id, row]));diff --git a/src/git.js b/src/git.jsindex 7a54a328..0522673a 100644--- a/src/git.js+++ b/src/git.js@@ -19,6 +19,7 @@ import {basename,dirname,join,+ isAbsolute,resolve,sep,} from 'node:path';@@ -534,21 +535,27 @@ export function repoInfo(cwd, { env } = {}) {/*** Read top level, worktree Git dir and shared Git dir in one process. With no inherited selector, the same process* also reads this checkout's HEAD commit and the primary checkout's branch and commit, and keeps them as this- * command's headCommit and mainCheckout facts, so a command learns where it is, its head and the trunk from one call.+ * command's headCommit, mainCheckout and effective hook-path facts, preserving Git's own configuration resolution.** @param {string} cwd* @returns {{ root: string, commonDir: string, gitDir: string, isMain: boolean }}*/function readRepoInfo(cwd, env) {const combined = !env && gitFacts.getStore()?.active && plainRepositoryEnvironment();- const primary = combined ? ['HEAD^{commit}', 'main-worktree/HEAD^{commit}', '--symbolic-full-name', 'main-worktree/HEAD'] : [];+ const primary = combined ? ['HEAD^{commit}', 'main-worktree/HEAD^{commit}', '--symbolic-full-name', 'main-worktree/HEAD', '--git-path', 'hooks'] : [];const info = tryGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir', ...primary], { env });// An unborn branch here or in the primary checkout fails the combined call after the paths; ask for the paths alone.if (combined && info.status !== 0 && info.stdout) return readRepoInfo(cwd, process.env);const fields = info.stdout.split('\n');- if (combined && info.status === 0 && [5, 6].includes(fields.length) && fields.slice(0, 5).every(Boolean)) {+ const combinedFields = [6, 7].includes(fields.length) && fields.slice(0, 5).every(Boolean)+ && isAbsolute(fields.at(-1)) && (fields.length === 6 || fields[5].startsWith('refs/'));+ // Unusual hook paths can contain newlines; retain the original path-only reader instead of guessing fields.+ if (combined && info.status === 0 && !combinedFields) return readRepoInfo(cwd, process.env);+ if (combined && info.status === 0 && combinedFields) {+ const hooks = fields.pop();const [root, , , head, commit, branch] = fields;const { facts } = gitFacts.getStore();+ facts.set(`gitPath:${JSON.stringify([resolve(root), 'hooks'])}`, resolve(root, hooks));facts.set(`headCommit:${resolve(root)}`, head);// A detached primary checkout names no branch, as symbolic-ref reports it.facts.set(`mainCheckout:${resolve(root)}`, branch?.startsWith('refs/') ? { branch, commit } : null);@@ -756,7 +763,8 @@ export function contains(root, ancestor, descendant) {* @returns {string}*/export function gitPath(root, name) {- return resolve(root, git(root, ['rev-parse', '--git-path', name]));+ return fact(`gitPath:${JSON.stringify([resolve(root), name])}`,+ () => resolve(root, git(root, ['rev-parse', '--git-path', name])));}/** Refuse lane-sensitive history checks while grafts can rewrite commit ancestry despite replacement guards [L3]. */diff --git a/src/resume-sources.js b/src/resume-sources.jsindex b96fb664..9bd0ac22 100644--- a/src/resume-sources.js+++ b/src/resume-sources.js@@ -13,6 +13,7 @@ import { configFromSource } from './config.js';import { withCommittedFiles } from './committed-file-reader.js';import { appliedDoctrine } from './doctrine.js';import { doctrineFromSource } from './doctrine.js';+import { loadDoctrine } from './doctrine.js';import { agentDoctrine } from './doctrine-rulings.js';import { cleanGitEnvironment } from './git.js';import { headCommit } from './git.js';@@ -50,28 +51,46 @@ async function primaryPath(info, listed) {return primaryCheckoutRoot(info);}-/** Read shared committed guidance and exact applied decisions through one Git child, not working-file authority. */-async function sharedDoctrine(ctx, board, primary, main) {- if (!main?.commit) return agentDoctrine(ctx, board);+/** Read the same default-name alias fallback as the existing synchronous doctrine reader. */+async function doctrineSourceAt(read, commit, name) {+ let source = await read(commit, name);+ if (source === null && [DOCTRINE_FILE, LEGACY_DOCTRINE_FILE].includes(name)) {+ const alias = name === DOCTRINE_FILE ? LEGACY_DOCTRINE_FILE : DOCTRINE_FILE;+ const other = await read(commit, alias);+ if (other !== null) return { name: alias, source: other };+ }+ return { name, source };+}++/** Read shared committed guidance and optional stale-overlay HEAD through one fresh Git child. */+async function sharedDoctrine(ctx, board, primary, main, includeHeadDoctrine) {+ if (!main?.commit) return { doctrine: agentDoctrine(ctx, board) };const snapshot = await withCommittedFiles(ctx.info.root, async read => {const config = await read(main.commit, CONFIG_FILE);- if (config === null) return ctx.doctrine;- let name = configFromSource(config).practice;- let source = await read(main.commit, name);- if (source === null && [DOCTRINE_FILE, LEGACY_DOCTRINE_FILE].includes(name)) {- const alias = name === DOCTRINE_FILE ? LEGACY_DOCTRINE_FILE : DOCTRINE_FILE;- const other = await read(main.commit, alias);- if (other !== null) { name = alias; source = other; }+ let shared = ctx.doctrine;+ if (config !== null) {+ const entry = await doctrineSourceAt(read, main.commit, configFromSource(config).practice);+ shared = doctrineFromSource(entry.source, entry.name);+ }+ let headDoctrine;+ if (includeHeadDoctrine) {+ const working = loadDoctrine(ctx.info.root, ctx.config);+ const head = headCommit(ctx.info.root);+ if (head) {+ const entry = await doctrineSourceAt(read, head, working.name);+ // The stale helper historically labels an alias read with the current working doctrine's name.+ headDoctrine = doctrineFromSource(entry.source, working.name);+ }}- return doctrineFromSource(source, name);+ return { shared, headDoctrine };});- const file = primary && join(primary, snapshot.name);+ const file = primary && join(primary, snapshot.shared.name);const current = file && existsSync(file) ? readFileSync(file, 'utf8') : null;- return appliedDoctrine(snapshot, store.rowDecisions(board), current);+ return { doctrine: appliedDoctrine(snapshot.shared, store.rowDecisions(board), current), headDoctrine: snapshot.headDoctrine };}/** Keep the command's verified trunk/HEAD snapshot, current branch and complete shared doctrine together. */-export async function readResumeSources(ctx, board) {+export async function readResumeSources(ctx, board, { compareBranch = true, includeHeadDoctrine = false } = {}) {const root = ctx.info.root;const main = mainCheckout(root);const listed = worktrees(root);@@ -81,12 +100,12 @@ export async function readResumeSources(ctx, board) {: tryGit(root, ['rev-parse', '--abbrev-ref', 'HEAD']).stdout || 'HEAD';let ahead;let behind;- if (main?.commit && !ctx.info.isMain) {+ if (compareBranch && main?.commit && !ctx.info.isMain) {const head = headCommit(root);const compared = head && tryGit(root, ['rev-list', '--left-right', '--count', `${main.commit}...${head}`]);const counts = compared?.status === 0 && /^([0-9]+)\s+([0-9]+)$/u.exec(compared.stdout);if (!counts) throw new Refused('NO_POLICY', 'the branch could not be compared with main; run pullboard resume --diagnostics');behind = Number(counts[1]); ahead = Number(counts[2]);}- return { doctrine: await sharedDoctrine(ctx, board, primary, main), primary, branch, mainRef: main?.branch, ahead, behind };+ return { ...await sharedDoctrine(ctx, board, primary, main, includeHeadDoctrine), primary, branch, mainRef: main?.branch, ahead, behind };}diff --git a/test/git-calls.test.js b/test/git-calls.test.jsindex 66f9262a..92bed1b9 100644--- a/test/git-calls.test.js+++ b/test/git-calls.test.js@@ -147,6 +147,17 @@ test('ordinary resume reads its indexed work card with at most four Git processeassert.deepEqual(card.stale, []);assert.equal(typeof card.newWorktreeLocation, 'string');assert.equal(typeof card.next, 'string');+ mkdirSync(join(box.worker, 'src'), { recursive: true });+ writeFileSync(join(box.worker, 'src/ahead.txt'), 'real branch divergence\n');+ box.git(box.worker, 'add', 'src/ahead.txt');+ box.git(box.worker, 'commit', '-q', '-m', 'test(core): retain real branch divergence [C7]');+ writeFileSync(join(box.worker, 'dirty.txt'), 'real untracked diagnostic\n');+ const diverged = resetAndCount(box, box.worker, 'resume', '--json');+ assert.ok(diverged.count <= 4, `diverged JSON v1 resume started ${diverged.count} Git processes`);+ assert.equal(JSON.parse(diverged.result.stdout).dirty, 1, 'v1 retains a real nonzero dirty value');+ const text = resetAndCount(box, box.worker, 'resume');+ assert.ok(text.count <= 4, `diverged text resume started ${text.count} Git processes`);+ assert.match(text.result.stdout, /1 ahead of main, 0 behind/u, 'text compares real differing HEAD and main');});/** Record schema-valid private fixture history, never represented as a real gate execution. */