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(resume): validate pinned sources within the Git budget [N19,C7]

Corey Olson482af44a12a0
diff --git a/src/git.js b/src/git.js
index 0522673a..875021bd 100644
--- a/src/git.js
+++ b/src/git.js
@@ -377,6 +377,11 @@ export function mainCheckout(root) {
return fact(`mainCheckout:${resolve(root)}`, () => readMainCheckout(root));
}
+/** Read only source identities already captured by this command's combined Git lookup. */
+export function mainSourceBlobs(root) {
+ return gitFacts.getStore()?.facts.get(`mainSourceBlobs:${resolve(root)}`) ?? null;
+}
+
/** Resolve the primary checkout without assuming its branch is named main.
*
* @param {string} root
@@ -542,26 +547,30 @@ export function repoInfo(cwd, { env } = {}) {
*/
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', '--git-path', 'hooks'] : [];
+ const primary = combined ? ['HEAD^{commit}', 'main-worktree/HEAD^{commit}', '--git-path', 'hooks', 'main-worktree/HEAD:pullboard.json', 'main-worktree/HEAD:DOCTRINE.md', '--symbolic-full-name', 'main-worktree/HEAD'] : [];
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');
- 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;
+ /** Recognize full SHA-1 or SHA-256 object identities before accepting a partial optional response. */
+ const oid = value => /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value ?? '');
+ const baseValid = fields.length >= 6 && fields.slice(0, 3).every(isAbsolute)
+ && oid(fields[3]) && oid(fields[4]) && isAbsolute(fields[5]);
+ const optional = ['main-worktree/HEAD:pullboard.json', 'main-worktree/HEAD:DOCTRINE.md'];
+ const missingOptional = info.status !== 0 && (fields.length === 7 && fields[6] === optional[0]
+ || fields.length === 8 && oid(fields[6]) && fields[7] === optional[1]);
+ if (combined && (!baseValid || info.status !== 0 && !missingOptional)) return readRepoInfo(cwd, process.env);
+ if (combined && baseValid) {
+ const [root, , , head, commit, hooks, config, doctrine, branch] = fields;
+ const suffixValid = missingOptional || (fields.length === 8 || fields.length === 9)
+ && oid(config) && oid(doctrine) && (branch === undefined || branch.startsWith('refs/'));
+ if (!suffixValid) return readRepoInfo(cwd, process.env);
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);
+ if (!missingOptional) facts.set(`mainCheckout:${resolve(root)}`, branch?.startsWith('refs/') ? { branch, commit } : null);
+ if (oid(config) && oid(doctrine)) facts.set(`mainSourceBlobs:${resolve(root)}`, { commit, config, doctrine });
fields.length = 3;
}
- if (info.status !== 0 || fields.length !== 3 || fields.some((field) => !field)) {
+ if (info.status !== 0 && !missingOptional || 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');
diff --git a/src/resume-sources.js b/src/resume-sources.js
index 13407904..c8f20b26 100644
--- a/src/resume-sources.js
+++ b/src/resume-sources.js
@@ -1,4 +1,5 @@
/** Fresh, bounded Git facts for the ordinary resume card; detailed diagnostics stay explicit [N19,D1]. */
+import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { readFileSync } from 'node:fs';
@@ -17,6 +18,7 @@ import { loadDoctrine } from './doctrine.js';
import { agentDoctrine } from './doctrine-rulings.js';
import { cleanGitEnvironment } from './git.js';
import { headCommit } from './git.js';
+import { mainSourceBlobs } from './git.js';
import { mainCheckout } from './git.js';
import { tryGit } from './git.js';
import { Refused } from './refused.js';
@@ -62,10 +64,27 @@ async function doctrineSourceAt(read, commit, name) {
return { name, source };
}
+/** Use working bytes only after their exact Git blob identities match this command's committed snapshot. */
+function matchedDoctrine(ctx, primary, main, validatedPrimary) {
+ const blobs = mainSourceBlobs(ctx.info.root);
+ if (!blobs || blobs.commit !== main?.commit || !samePath(primary, validatedPrimary)) return null;
+ try {
+ const config = readFileSync(join(primary, CONFIG_FILE));
+ const doctrine = readFileSync(join(primary, DOCTRINE_FILE));
+ /** Git hashes the type and byte length together with the original bytes, in the repository's object format. */
+ const matches = (bytes, oid) => createHash(oid.length === 64 ? 'sha256' : 'sha1')
+ .update(`blob ${bytes.length}\0`).update(bytes).digest('hex') === oid;
+ if (!matches(config, blobs.config) || !matches(doctrine, blobs.doctrine)) return null;
+ if (configFromSource(config.toString('utf8')).practice !== DOCTRINE_FILE) return null;
+ return { shared: doctrineFromSource(doctrine.toString('utf8'), DOCTRINE_FILE) };
+ } catch { return null; } // Missing or unreadable working copies retain the committed Git reader and its refusals.
+}
+
/** Read shared committed guidance and optional stale-overlay HEAD through one fresh Git child. */
-async function sharedDoctrine(ctx, board, primary, main, includeHeadDoctrine) {
+async function sharedDoctrine(ctx, board, primary, main, includeHeadDoctrine, validatedPrimary) {
if (!main?.commit) return { doctrine: agentDoctrine(ctx, board) };
- const snapshot = await withCommittedFiles(ctx.info.root, async read => {
+ const matched = !includeHeadDoctrine && matchedDoctrine(ctx, primary, main, validatedPrimary);
+ const snapshot = matched || await withCommittedFiles(ctx.info.root, async read => {
const config = await read(main.commit, CONFIG_FILE);
let shared = ctx.doctrine;
if (config !== null) {
@@ -109,5 +128,5 @@ export async function readResumeSources(ctx, board, { compareBranch = true, incl
}
// Guidance follows Git's listed primary exactly as agentDoctrine does, even when placement cannot be proven.
const guidanceRoot = listed[0]?.path;
- return { ...await sharedDoctrine(ctx, board, guidanceRoot, main, includeHeadDoctrine), primary, branch, mainRef: main?.branch, ahead, behind };
+ return { ...await sharedDoctrine(ctx, board, guidanceRoot, main, includeHeadDoctrine, primary), primary, branch, mainRef: main?.branch, ahead, behind };
}
diff --git a/test/git-calls.test.js b/test/git-calls.test.js
index 92bed1b9..7ec75926 100644
--- a/test/git-calls.test.js
+++ b/test/git-calls.test.js
@@ -155,9 +155,46 @@ test('ordinary resume reads its indexed work card with at most four Git processe
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');
+ box.git(box.repo, 'branch', 'unrelated-upstream', 'core/worker');
+ box.git(box.worker, 'config', 'branch.core/worker.remote', '.');
+ box.git(box.worker, 'config', 'branch.core/worker.merge', 'refs/heads/unrelated-upstream');
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');
+ assert.match(text.result.stdout, /1 file uncommitted/u, 'an untracked file is counted within the same Git budget');
+ assert.equal(box.git(box.worker, 'config', 'branch.core/worker.merge'), 'refs/heads/unrelated-upstream', 'comparison leaves the real upstream unchanged');
+ box.git(box.worker, 'mv', 'src/ahead.txt', 'src/renamed \nfile.txt');
+ const renamed = resetAndCount(box, box.worker, 'resume');
+ assert.ok(renamed.count <= 4, `renamed-path resume started ${renamed.count} Git processes`);
+ assert.match(renamed.result.stdout, /2 files uncommitted/u, 'a renamed path with whitespace counts once alongside the new file');
+});
+
+/** Optional committed-source facts never replace Git's repository or detached-HEAD semantics. */
+test('combined Git source facts retain repository identity when optional doctrine is missing [C7,N19]', t => {
+ const box = fixture(t);
+ const script = `const { repoInfo, mainSourceBlobs, mainCheckout } = await import(${JSON.stringify(GIT_MODULE)});
+ console.log(JSON.stringify(await withGitFacts(() => { const info = repoInfo(process.argv[1]);
+ return { info, head: headCommit(info.root), main: mainCheckout(info.root), blobs: mainSourceBlobs(info.root) }; })));`;
+ const present = readFactScenario(box, box.worker, script);
+ assert.equal(present.head, box.git(box.worker, 'rev-parse', 'HEAD'));
+ assert.equal(present.blobs.config, box.git(box.repo, 'rev-parse', 'HEAD:pullboard.json'));
+ assert.equal(present.blobs.doctrine, box.git(box.repo, 'rev-parse', 'HEAD:DOCTRINE.md'));
+ box.git(box.repo, 'rm', 'DOCTRINE.md');
+ box.git(box.repo, 'commit', '-q', '-m', 'test(core): omit optional doctrine source [C7]');
+ const missing = readFactScenario(box, box.worker, script);
+ assert.equal(missing.blobs, null);
+ assert.equal(missing.main.commit, box.git(box.repo, 'rev-parse', 'HEAD'));
+ assert.equal(missing.head, present.head, 'missing primary doctrine does not discard the linked HEAD');
+ box.git(box.repo, 'config', 'core.hooksPath', `hooks\n${'a'.repeat(40)}\n${'b'.repeat(40)}`);
+ const unusual = readFactScenario(box, box.worker, script);
+ assert.equal(unusual.blobs, null, 'hook path lines never become trusted source object IDs');
+ assert.equal(unusual.main.commit, missing.main.commit, 'opaque hook paths preserve the validated Git fallback');
+ assert.equal(unusual.head, present.head);
+ box.git(box.repo, 'config', '--unset', 'core.hooksPath');
+ box.git(box.repo, 'switch', '-q', '--detach');
+ const detached = readFactScenario(box, box.worker, script);
+ assert.equal(detached.main, null, 'a detached primary never acquires an invented main branch');
+ assert.equal(detached.head, present.head);
});
/** Record schema-valid private fixture history, never represented as a real gate execution. */