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
refactor(resume): keep unrelated Git helpers on trunk [N19,N26]
Corey Olson4ce7fb28ccf9
diff --git a/src/cli.js b/src/cli.jsindex 3e3df7d1..4046dcab 100644--- a/src/cli.js+++ b/src/cli.js@@ -140,7 +140,6 @@ import {invalidateGitFacts,isClean,mainCheckout,- worktreeEntries,repoInfo,resolveCommit,tryGit,@@ -1904,7 +1903,10 @@ export function primaryCheckoutRoot(info) {for (const candidate of candidates) {if (typeof candidate !== 'string' || !isAbsolute(candidate)) continue;try {- const { root, gitDir, commonDir: candidateCommonDir } = repoInfo(candidate);+ 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;if (!existsSync(join(root, '.git'))|| realpathSync.native(candidateCommonDir) !== commonDir|| realpathSync.native(gitDir) !== realpathSync.native(candidateCommonDir)) continue;@@ -1913,10 +1915,14 @@ export function primaryCheckoutRoot(info) {}return [...roots.values()];};- try {- const found = matches(worktreeEntries(info.root).map(entry => entry.path));+ 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);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.jsindex f21c14e2..35512d67 100644--- a/src/commands/resume.js+++ b/src/commands/resume.js@@ -25,7 +25,6 @@ import {import {repoInfo,tryGit,- worktreeEntries,} from '../git.js';import {recordedHealthFindings,@@ -255,7 +254,7 @@ export async function resumeHere(io, view, diagnostics = false) {if (!isMain) {const branch = diagnostics ? tryGit(root, ['rev-parse', '--abbrev-ref', 'HEAD']).stdout || 'HEAD' : sources.branch;// Against the main checkout's branch, not its HEAD, which is detached while the coordinator verifies.- const mainRef = diagnostics ? worktreeEntries(root)[0]?.branch : sources.mainRef;+ const mainRef = diagnostics ? /^branch (.+)$/mu.exec(tryGit(root, ['worktree', 'list', '--porcelain']).stdout.split('\n\n')[0])?.[1] : sources.mainRef;const [behind = 0, ahead = 0] = diagnostics? mainRef ? tryGit(root, ['rev-list', '--left-right', '--count', `${mainRef}...HEAD`]).stdout.split(/\s+/).map(Number) : []: [sources.behind, sources.ahead];diff --git a/src/doctrine-rulings.js b/src/doctrine-rulings.jsindex 14a8ad44..d599ff59 100644--- a/src/doctrine-rulings.js+++ b/src/doctrine-rulings.js@@ -19,6 +19,7 @@ import {} from 'node:path';import * as store from './board.js';import {+ CONFIG_FILE,DOCTRINE_FILE,LEGACY_DOCTRINE_FILE,} from './config.js';@@ -28,8 +29,8 @@ import {loadDoctrine,} from './doctrine.js';import {+ git,mainCheckout,- worktreeEntries,resolveCommit,tryGit,} from './git.js';@@ -80,17 +81,13 @@ export function agentDoctrine(ctx, board) {const commit = primary?.commit ?? (retained ? resolveCommit(root, retained) : null);let doctrine = ctx.doctrine;let name = doctrine.name;- 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);+ if (commit && tryGit(root, ['show', `${commit}:${CONFIG_FILE}`]).status === 0) {+ const read = doctrineAt(root, commit, policyAt(root, commit).config.practice);name = read.name;doctrine = doctrineFromSource(read.source, name);}- const primaryRoot = worktreeEntries(root)[0]?.path ?? null;+ const entry = git(root, ['worktree', 'list', '--porcelain', '-z']).split('\0')[0];+ const primaryRoot = entry.startsWith('worktree ') ? entry.slice('worktree '.length) : 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.jsindex 806e26ab..55d56d5c 100644--- a/src/git.js+++ b/src/git.js@@ -357,36 +357,12 @@ 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.jsindex c4118800..2a2df568 100644--- a/src/health.js+++ b/src/health.js@@ -6,6 +6,7 @@* 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 {@@ -14,7 +15,6 @@ import {} from './config.js';import {mainCheckout,- worktreeEntries,tryGit,} from './git.js';import { gateControlFindings } from './gate-control.js';@@ -450,8 +450,6 @@ 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 ?? ''));@@ -460,7 +458,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 merged) {+ 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()) {const first = history.get(item.item_id)?.firstMerged;if (first && Date.parse(first) > published) landed.push(item.item_id);}@@ -521,11 +519,7 @@ 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 {- 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. */ }+ try { ref = mainCheckout(root)?.branch ?? trunkRef(root); } 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;@@ -602,7 +596,8 @@ export function healthLines(report) {*/function goneWorktrees(root) {try {- return new Set(worktreeEntries(root).filter(entry => entry.prunable).map(entry => entry.path).filter(Boolean));+ 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));} catch { return new Set(); }}diff --git a/test/git-calls.test.js b/test/git-calls.test.jsindex 6f54fa2a..155b36be 100644--- a/test/git-calls.test.js+++ b/test/git-calls.test.js@@ -134,41 +134,6 @@ test('ordinary resume reads its indexed work card with at most four Git processeassert.equal(typeof card.next, 'string');});-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',