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
feat(git): resolve primary trunk consistently [B34,P2,L3]
Corey Olson41d4c3d5fc52
diff --git a/src/check-baseline.js b/src/check-baseline.jsindex 49634d0f..35282779 100644--- a/src/check-baseline.js+++ b/src/check-baseline.js@@ -3,22 +3,24 @@ import { spawnSync } from 'node:child_process';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { gitChildEnv, tryGit } from './git.js';+import { gitChildEnv, mainCheckout, tryGit } from './git.js';import { runShell } from './gate.js';import { CONFIG_FILE } from './config.js';/**- * Capture the command and main commit once on the sender; replay only receives this observation.- * A missing main cannot turn a warning into a new gate, and the repo gate is already green there.+ * Capture the command and coordinator commit once on the sender; replay only receives this observation.+ * A detached coordinator checkout cannot turn an unavailable baseline into a new gate.** @param {string} root* @param {string} command* @returns {{command: string, main: string|null, result: string, reason?: string, seconds?: number}}*/export function checkBaseline(root, command) {- const main = tryGit(root, ['rev-parse', '--verify', 'refs/heads/main^{commit}']);- if (main.status !== 0) return { command, main: null, result: 'unavailable', reason: 'no main' };- const base = { command, main: main.stdout };+ const primary = mainCheckout(root);+ if (!primary) return { command, main: null, result: 'unavailable', reason: 'coordinator checkout is detached' };+ if (!primary.commit) return { command, main: null, result: 'unavailable', reason: 'no main' };+ const main = primary.commit;+ const base = { command, main };if (command === gateOnMain(root, base.main)) return { ...base, result: 'green', reason: 'repo gate' };const directory = mkdtempSync(join(tmpdir(), 'pullboard-check-base-'));const checkout = join(directory, 'checkout');diff --git a/src/git.js b/src/git.jsindex 9db1780e..28e8cfc3 100644--- a/src/git.js+++ b/src/git.js@@ -9,6 +9,41 @@ import { Refused } from './refused.js';const GIT_FLAGS = ['--no-replace-objects', '-c', 'core.quotepath=false'];+/** Clear inherited Git selectors while retaining ordinary user settings and exact-object behavior.+ *+ * @returns {NodeJS.ProcessEnv}+ */+export function cleanGitEnvironment() {+ const env = { ...process.env };+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_PREFIX', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_SHALLOW_FILE']) delete env[key];+ for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_/.test(key)) delete env[key];+ env.GIT_NO_REPLACE_OBJECTS = '1';+ return env;+}++/** Resolve the primary checkout's branch and commit without assuming its branch is named main.+ *+ * @param {string} root+ * @returns {{branch: string, commit: string|null}|null}+ */+export function mainCheckout(root) {+ const env = cleanGitEnvironment();+ /** Run one Git lookup with the sanitized environment. */+ const gitCall = (args) => spawnSync('git', [...GIT_FLAGS, ...args], {+ cwd: root, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,+ });+ const common = gitCall(['rev-parse', '--path-format=absolute', '--git-common-dir']);+ if (common.status !== 0) throw new Refused('NO_POLICY', 'the primary checkout cannot be located; restore the repository and ask the coordinator to retry');+ const commonDir = common.stdout.trim();+ const symbolic = gitCall(['--git-dir', commonDir, 'symbolic-ref', '--quiet', 'HEAD']);+ if (symbolic.status === 1) return null;+ if (symbolic.status !== 0) throw new Refused('NO_POLICY', 'the primary checkout branch cannot be read; restore its Git metadata and ask the coordinator to retry');+ const branch = symbolic.stdout.trim();+ const resolved = gitCall(['--git-dir', commonDir, 'rev-parse', '--verify', '--quiet', `${branch}^{commit}`]);+ 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, commit: resolved.status === 0 ? resolved.stdout.trim() : null };+}+/*** The environment for a gate or fixer: keep the user's settings, but remove Git's repository-local* variables so a child that changes folders cannot act on the hook's repository by accident.diff --git a/src/hooks.js b/src/hooks.jsindex 221875a8..3fab8157 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 } from 'node:path';-import { git, gitChildEnv, tryGit } from './git.js';+import { git, gitChildEnv, mainCheckout, tryGit } from './git.js';import { Refused } from './refused.js';import { outOfLane } from './lanes.js';import { citedIds, deletedIds, idProblems } from './spec.js';@@ -233,7 +233,7 @@ export function preCommitProblems({ root, isMain, config, agent, boardFile }) {}/**- * The commit being merged, only when it is already part of main's history.+ * The commit being merged, only when it is already part of the primary checkout's history.** @param {string} root* @returns {string | null}@@ -241,7 +241,10 @@ export function preCommitProblems({ root, isMain, config, agent, boardFile }) {function mainMergeBase(root) {const merge = tryGit(root, ['rev-parse', '--verify', 'MERGE_HEAD']);if (merge.status !== 0) return null;- return tryGit(root, ['merge-base', '--is-ancestor', merge.stdout, 'refs/heads/main']).status === 0+ let main;+ try { main = mainCheckout(root)?.commit; } catch { return null; }+ if (!main) return null;+ return tryGit(root, ['merge-base', '--is-ancestor', merge.stdout, main]).status === 0? merge.stdout: null;}diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex 2ee6b4a7..6023dd0f 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -4,18 +4,10 @@ import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { configFromSource } from './config.js';+import { cleanGitEnvironment, mainCheckout } from './git.js';import { outOfLane } from './lanes.js';import { Refused } from './refused.js';-/** Keep private checkouts independent of inherited Git repository and index bindings. */-function cleanGitEnvironment() {- const env = { ...process.env };- for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_PREFIX', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_SHALLOW_FILE']) delete env[key];- for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_/.test(key)) delete env[key];- env.GIT_NO_REPLACE_OBJECTS = '1'; // A pin identifies the underlying object, never refs/replace fiction.- return env;-}-/** Read raw Git output, retaining NUL-delimited names without exposing Git diagnostics. */function policyGit(root, args) {const result = spawnSync('git', ['-c', 'core.quotepath=false', ...args], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });@@ -25,12 +17,10 @@ function policyGit(root, args) {/** Resolve the primary checkout's committed HEAD, independently of a linked or detached checkout. */export function mainPolicy(root) {- const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();- let branch;- try { branch = policyGit(root, ['--git-dir', common, 'symbolic-ref', '--quiet', 'HEAD']).trim(); }- catch { throw new Refused('NO_POLICY', 'the coordinator checkout is detached for review; ask it to return to its main branch before claiming or running the project gate'); }- const commit = policyGit(root, ['--git-dir', common, 'rev-parse', '--verify', branch + '^{commit}']).trim();- return policyAt(root, commit);+ const checkout = mainCheckout(root);+ if (!checkout) throw new Refused('NO_POLICY', 'the coordinator checkout is detached for review; ask it to return to its main branch before claiming or running the project gate');+ if (!checkout.commit) throw new Refused('NO_POLICY', 'the coordinator checkout has no commit on ' + checkout.branch + '; create its first commit before claiming or running the project gate');+ return policyAt(root, checkout.commit);}/** Re-read coordinator settings from a pinned Git object; never from the candidate filesystem. */diff --git a/test/trunk.test.js b/test/trunk.test.jsnew file mode 100644index 00000000..96fca8f8--- /dev/null+++ b/test/trunk.test.js@@ -0,0 +1,137 @@+/** Branch-name-independent check baselines and lane merge ownership [B34,P2,L3]. */+import assert from 'node:assert/strict';+import { execFileSync, spawnSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { after, test } from 'node:test';+import { mainPolicy } from '../src/trusted-policy.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const TEMP_DIRS = [];+const SPEC = '# Trunk fixture\n\n## G · Goals\n- G1 [approved, must] The fixture works. | gate: true\n';++/** Remove isolated fixture repositories after their child processes finish. */+function cleanupFixtures() {+ for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });+}++after(cleanupFixtures);++/** Build an offline CLI fixture with private Git identity and machine settings. */+function sandbox() {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-trunk-'));+ TEMP_DIRS.push(dir);+ const bin = join(dir, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const env = { ...process.env };+ for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];+ Object.assign(env, {+ HOME: join(dir, 'home'),+ PULLBOARD_HOME: join(dir, 'pullboard-home'),+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Trunk fixture',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Trunk fixture',+ GIT_COMMITTER_EMAIL: '[email protected]',+ PATH: `${bin}:${process.env.PATH}`,+ });+ /** Run isolated Git commands. */+ function git(cwd, ...args) {+ return execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();+ }+ /** Run a real Pullboard CLI process in the fixture environment. */+ function run(cwd, ...args) {+ const result = spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 30_000 });+ return { code: result.status, out: result.stdout, err: result.stderr };+ }+ return { dir, env, git, run };+}++/** Quote a shell word for the fixture's local Pullboard executable. */+function shellWord(value) {+ return `'${String(value).replaceAll("'", "'\\''")}'`;+}++/** Initialize a committed repo whose primary branch has the supplied name. */+function project(branch) {+ const box = sandbox();+ const repo = join(box.dir, 'repo');+ mkdirSync(repo);+ box.git(repo, 'init', '-q', '-b', 'main');+ assert.equal(box.run(repo, 'init').code, 0);+ const configPath = join(repo, 'pullboard.json');+ const config = JSON.parse(readFileSync(configPath, 'utf8'));+ config.gate = 'true';+ config.lanes = { web: { owns: ['web/'], specs: ['G1'] } };+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');+ writeFileSync(join(repo, 'SPEC.md'), SPEC);+ mkdirSync(join(repo, 'web'));+ writeFileSync(join(repo, 'web', 'result.txt'), 'ready\n');+ box.git(repo, 'add', '-A');+ box.git(repo, 'commit', '-q', '-m', 'chore: initialize trunk fixture');+ if (branch !== 'main') box.git(repo, 'branch', '-m', branch);+ return { ...box, repo };+}++for (const branch of ['master', 'trunk']) {+ test(`[B34,P2] add --check captures the ${branch} baseline without a remote`, () => {+ const box = project(branch);+ const head = box.git(box.repo, 'rev-parse', 'HEAD');+ assert.equal(mainPolicy(box.repo).commit, head, 'trusted policy resolves the primary checkout rather than a fixed branch name');+ const added = box.run(box.repo, 'add', 'web', `baseline on ${branch}`, '--specs', 'G1', '--criterion', 'a real check baseline is recorded', '--check', 'node -e "process.exit(1)"', '--json');+ assert.equal(added.code, 0, `${added.out}${added.err}`);+ const item = JSON.parse(added.out).item;+ assert.equal(item.item_check_baseline.main, head, `${branch} baseline points at the primary checkout commit`);+ assert.equal(item.item_check_baseline.result, 'red', `${branch} baseline actually ran instead of being unavailable`);+ assert.notEqual(item.item_check_baseline.reason, 'no main');+ });+}++for (const branch of ['master', 'trunk']) {+ test(`[B34,P2,L3] a lane can resolve an owned conflict while retaining ${branch} files`, () => {+ const box = project(branch);+ const web = join(box.dir, 'web-worktree');+ box.git(box.repo, 'worktree', 'add', '-q', web, '-b', 'web/agent');+ assert.equal(box.run(web, 'join', 'web').code, 0);+ writeFileSync(join(web, 'web', 'result.txt'), `resolved by web lane from ${branch}\n`);+ box.git(web, 'add', 'web/result.txt');+ box.git(web, 'commit', '-q', '-m', 'feat(web): update owned fixture [G1]');+ writeFileSync(join(box.repo, 'web', 'result.txt'), `updated by ${branch}\n`);+ writeFileSync(join(box.repo, 'coordinator.txt'), `owned by ${branch}\n`);+ box.git(box.repo, 'add', 'web/result.txt', 'coordinator.txt');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: update trunk fixture');+ const trunkHead = box.git(box.repo, 'rev-parse', 'HEAD');+ const merged = spawnSync('git', ['merge', '--no-ff', '--no-commit', branch], {+ cwd: web, env: box.env, encoding: 'utf8', timeout: 30_000,+ });+ assert.equal(merged.status, 1, `${merged.stdout}${merged.stderr}`);+ assert.equal(box.git(web, 'rev-parse', 'MERGE_HEAD'), trunkHead, 'the merge is against the primary checkout tip');+ assert.ok(box.git(web, 'status', '--porcelain').includes('UU web/result.txt'), 'the primary and lane edits conflict on an owned file');+ writeFileSync(join(web, 'web', 'result.txt'), `resolved by web lane from ${branch}\n`);+ box.git(web, 'add', 'web/result.txt');++ const committed = spawnSync('git', ['commit', '-m', `Merge ${branch} into web/agent`], {+ cwd: web, env: box.env, encoding: 'utf8', timeout: 30_000,+ });+ assert.equal(committed.status, 0, `${committed.stdout}${committed.stderr}`);+ assert.equal(box.git(web, 'show', 'HEAD:web/result.txt'), `resolved by web lane from ${branch}`);+ assert.equal(box.git(web, 'show', 'HEAD:coordinator.txt'), `owned by ${branch}`);+ assert.equal(box.git(web, 'rev-list', '--parents', '-n', '1', 'HEAD').split(' ').length, 3, 'the lane committed a two-parent merge');+ });+}++test('[B34,P2] add --check reports an unavailable baseline for a detached coordinator', () => {+ const box = project('master');+ box.git(box.repo, 'checkout', '--detach', '-q', 'HEAD');+ const added = box.run(box.repo, 'add', 'web', 'detached baseline', '--specs', 'G1', '--criterion', 'detached baseline is unavailable', '--check', 'true', '--json');+ assert.equal(added.code, 0, `${added.out}${added.err}`);+ const item = JSON.parse(added.out).item;+ assert.deepEqual(item.item_check_baseline, {+ command: 'true', main: null, result: 'unavailable', reason: 'coordinator checkout is detached',+ });+});