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(cli): resolve primary checkout for landing [I1,B3]

Corey Olsoneebe35b319b3
diff --git a/src/cli.js b/src/cli.js
index 38cbfdae..7a93ed5b 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -4,7 +4,7 @@
*/
import { createHash, randomUUID } from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
-import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
import { loadavg } from 'node:os';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { performance } from 'node:perf_hooks';
@@ -63,7 +63,7 @@ import { parseProblems, sweepItems } from './sweep.js';
import { renderSpecView } from './view.js';
import { tour } from './tour.js';
import { commandOutput, refusalDocument } from './json.js';
-import { forgetProject, listApiProjects, registerProjectAndLink } from './projects.js';
+import { forgetProject, listApiProjects, registerProjectAndLink, registeredProjectRootsSnapshot } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
import { listResources } from './resources.js';
import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
@@ -2283,10 +2283,57 @@ async function verifyHere(ctx, id, { second, values }) {
* @returns {string}
*/
function landNext(info, item) {
- const mainRoot = resolve(info.commonDir, '..');
+ const mainRoot = primaryCheckoutRoot(info);
const branch = mainCheckout(info.root)?.branch ?? '';
- if (landingRemote(info.root, branch)) return `next: the coordinator lands it: ${cdTo(mainRoot)} pullboard land`;
- return `next: this repo has no remote for pullboard land to push to, so the coordinator merges it on ${branch.replace(/^refs\/heads\//u, '') || 'the trunk'}: ${cdTo(mainRoot)} git merge --no-ff ${item.item_commit} -m ${shellWord(landingSubject(item))} && pullboard merged ${item.item_id} HEAD`;
+ const remote = landingRemote(info.root, branch);
+ const command = remote
+ ? 'pullboard land'
+ : `git merge --no-ff ${item.item_commit} -m ${shellWord(landingSubject(item))} && pullboard merged ${item.item_id} HEAD`;
+ if (!mainRoot) return `next: could not safely locate the primary checkout; run from the main checkout: ${command}`;
+ if (remote) return `next: the coordinator lands it: ${cdTo(mainRoot)} ${command}`;
+ return `next: this repo has no remote for pullboard land to push to, so the coordinator merges it on ${branch.replace(/^refs\/heads\//u, '') || 'the trunk'}: ${cdTo(mainRoot)} ${command}`;
+}
+
+/** Resolve a usable primary checkout without trusting the Git metadata directory as a path. */
+function primaryCheckoutRoot(info) {
+ if (info.isMain) return info.root;
+ let commonDir;
+ try { commonDir = realpathSync.native(info.commonDir); }
+ catch { return null; }
+ /** Return unique validated primary checkouts among candidate repository paths.
+ *
+ * @param {string[]} candidates
+ * @returns {string[]}
+ */
+ const matches = (candidates) => {
+ const roots = new Map();
+ 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;
+ if (!existsSync(join(root, '.git'))
+ || realpathSync.native(candidateCommonDir) !== commonDir
+ || realpathSync.native(gitDir) !== realpathSync.native(candidateCommonDir)) continue;
+ roots.set(realpathSync.native(root), root);
+ } catch { /* A stale registry entry or Git metadata directory is not a usable checkout. */ }
+ }
+ 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);
+ if (found.length === 1) return found[0];
+ }
+ const registered = registeredProjectRootsSnapshot();
+ if (registered === null) return null;
+ const found = matches(registered);
+ return found.length === 1 ? found[0] : null;
}
/**
diff --git a/src/projects.js b/src/projects.js
index efbade79..d4dfa9fe 100644
--- a/src/projects.js
+++ b/src/projects.js
@@ -36,6 +36,15 @@ function readRegistry() {
}
}
+/** Read registered project roots without refreshing or pruning the machine registry.
+ *
+ * @returns {string[] | null} A snapshot of paths, or null when the registry cannot be trusted.
+ */
+export function registeredProjectRootsSnapshot() {
+ const state = readRegistry();
+ return state.readable ? state.projects.map((project) => project.root) : null;
+}
+
/**
* Open the small SQLite file that serializes registry mutations. SQLite releases its OS lock when
* a process exits, so a killed writer cannot strand a directory lock or evict a newer owner.
diff --git a/test/e2e-helpers.js b/test/e2e-helpers.js
index bcb8fc23..6c3f4771 100644
--- a/test/e2e-helpers.js
+++ b/test/e2e-helpers.js
@@ -78,10 +78,10 @@ const SPEC = `# Demo spec
* worktree joined to the web lane. The coordinator stays deliberately undeclared; later agents
* retain the runner's model, while initialization model coverage invokes init directly.
*/
-function project(gate = CONFIG.gate, box = sandbox()) {
+function project(gate = CONFIG.gate, box = sandbox(), { separateGitDir = false } = {}) {
const repo = join(box.dir, 'repo');
mkdirSync(repo);
- box.git(repo, 'init', '-q', '-b', 'main');
+ box.git(repo, 'init', '-q', '-b', 'main', ...(separateGitDir ? ['--separate-git-dir', join(box.dir, 'separate-git')] : []));
const inheritedModel = box.env.PULLBOARD_MODEL;
delete box.env.PULLBOARD_MODEL;
assert.equal(box.run(repo, 'init').code, 0);
diff --git a/test/land-next.test.js b/test/land-next.test.js
index 69a897cd..a4d97dfb 100644
--- a/test/land-next.test.js
+++ b/test/land-next.test.js
@@ -1,6 +1,7 @@
/** An accept names the exact landing step for its repo, and a dry run refuses a push the real land would refuse [I1,B3]. */
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
+import { rmSync } from 'node:fs';
import { join } from 'node:path';
import { after, test } from 'node:test';
import { createE2eHelpers } from './e2e-helpers.js';
@@ -13,7 +14,7 @@ const { project, commitFile } = e2e;
const literal = (text) => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
/** File, build, submit and accept one web item through the real CLI and hooks, returning the accept output. */
-function acceptedItem(box, file) {
+function acceptedItem(box, file, { beforeVerify = () => {} } = {}) {
const added = box.run(box.repo, 'add', 'web', `Write ${file}`, '--specs', 'G1', '--criterion', `${file} exists`, '--check', `test -f ${file}`, '--json');
assert.equal(added.code, 0, added.err);
const id = JSON.parse(added.out).item.item_id;
@@ -25,6 +26,7 @@ function acceptedItem(box, file) {
const submitted = box.run(box.web, 'submit', String(id));
assert.equal(submitted.code, 0, submitted.err);
box.git(box.review, 'switch', '-q', '--detach', commit);
+ beforeVerify();
const verdict = box.run(box.review, 'verify', String(id), 'accept', '--note', 'the file exists at the submitted commit');
assert.equal(verdict.code, 0, verdict.err);
return { id, commit, out: verdict.out };
@@ -79,3 +81,25 @@ test('an accept says how to land, and a dry run catches a missing origin [I1,B3]
assert.equal(preview.code, 0, preview.out);
assert.deepEqual(JSON.parse(preview.out).items, [second.id]);
});
+
+test('an accept names the primary checkout when Git metadata is stored separately [I1,B3]', () => {
+ const box = withReviewer(project(undefined, undefined, { separateGitDir: true }));
+ const accepted = acceptedItem(box, 'web/separate.txt');
+ const merge = new RegExp(`^next: this repo has no remote for pullboard land to push to, so the coordinator merges it on main: (cd ${literal(box.repo)} && git merge --no-ff ${accepted.commit} -m 'chore\\(merge\\): write web/separate\\.txt \\[G1\\]' && pullboard merged ${accepted.id} HEAD)$`, 'mu');
+ const printed = merge.exec(accepted.out);
+ assert.ok(printed, `the accept names the actual primary checkout for separate Git metadata:\n${accepted.out}`);
+
+ const ran = spawnSync('/bin/sh', ['-c', printed[1]], { cwd: box.dir, env: box.env, encoding: 'utf8' });
+ assert.equal(ran.status, 0, `${ran.stdout}${ran.stderr}`);
+ assert.equal(box.tryGit(box.repo, 'merge-base', '--is-ancestor', accepted.commit, 'main').status, 0, 'the exact printed command lands the accepted commit');
+
+ const unregistered = withReviewer(project(undefined, undefined, { separateGitDir: true }));
+ const fallback = acceptedItem(unregistered, 'web/fallback.txt', {
+ beforeVerify: () => rmSync(join(unregistered.env.PULLBOARD_HOME, 'projects.json'), { force: true }),
+ });
+ const mergeCommand = `git merge --no-ff ${fallback.commit} -m 'chore(merge): write web/fallback.txt [G1]' && pullboard merged ${fallback.id} HEAD`;
+ assert.ok(fallback.out.includes(`next: could not safely locate the primary checkout; run from the main checkout: ${mergeCommand}`), fallback.out);
+ assert.doesNotMatch(fallback.out, /\bcd\s/u, 'an unvalidated path is never guessed');
+ const ranFallback = spawnSync('/bin/sh', ['-c', mergeCommand], { cwd: unregistered.repo, env: unregistered.env, encoding: 'utf8' });
+ assert.equal(ranFallback.status, 0, `${ranFallback.stdout}${ranFallback.stderr}`);
+});