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(core): pin admitted landing policy and branch [Q1,B3]

Corey Olsonfa581b3e058e
diff --git a/src/commands/land.js b/src/commands/land.js
index 93587894..ba26b500 100644
--- a/src/commands/land.js
+++ b/src/commands/land.js
@@ -16,9 +16,6 @@ import {
import {
Refused,
} from '../refused.js';
-import {
- mainPolicy,
-} from '../trusted-policy.js';
import {
staleVerdictRefusal,
} from '../verdict-freshness.js';
@@ -45,7 +42,7 @@ export async function run(io, { first, second, rest, values }) {
return 0;
}
if (values.until !== undefined || values.reason !== undefined || values.max !== undefined && (!/^[1-9][0-9]*$/u.test(values.max) || !Number.isSafeInteger(Number(values.max)))) throw new Refused('USAGE', 'use --max with a positive item count, or --waive with --until and --reason');
- const result = await land({ root: ctx.info.root, board, config: mainPolicy(ctx.info.root).config,
+ const result = await land({ root: ctx.info.root, board,
write: (operation, parameters) => ordered(ctx, board, operation, parameters), say: io.say, owner: agentSessionDigest() ?? `pid-${process.pid}`,
maximum: values.max === undefined ? Infinity : Number(values.max), dryRun: Boolean(values['dry-run']), adopt: Boolean(values.adopt), onWait: gateWaitReporter(io) });
io.result?.(result);
diff --git a/src/land.js b/src/land.js
index cca86a75..742d3eec 100644
--- a/src/land.js
+++ b/src/land.js
@@ -44,6 +44,7 @@ import { laneOf } from './lanes.js';
import { takeResource } from './resources.js';
import { runLandingWorker } from './landing-worker.js';
import { Refused } from './refused.js';
+import { policyAt } from './trusted-policy.js';
import { landingFileTimes } from './submit-invariants.js';
import {
flakeSource,
@@ -702,10 +703,9 @@ export async function land(options) {
}
/** Select only after admission, retaining the existing batch, proof and adoption rules. */
-export async function runLandingBatch({ root, board, config, write, say, owner, maximum = Infinity, dryRun = false, adopt = false, onWait, checkLease, checkLeaseNow }) {
- // Quarantine is read from the accepted main policy this landing runs under, never from a branch.
- board.quarantineEnabled = () => config.flakes?.quarantine === true;
+export async function runLandingBatch({ root, board, config, write, say, owner, maximum = Infinity, dryRun = false, adopt = false, onWait, checkLease, checkLeaseNow, fence }) {
let trunk = mainCheckout(root);
+ if (fence && trunk?.branch !== fence.branch) throw new Refused('LAND_LEASE_LOST', 'the trunk branch changed while landing waited; start a new land command for its current branch');
const recorded = store.landingBatches(board).findLast((batch) => batch.state === 'landed' && batch.base === trunk?.commit);
if (!dryRun && recorded && isClean(root) && !untracked(root).length) {
await checkLease();
@@ -713,7 +713,11 @@ export async function runLandingBatch({ root, board, config, write, say, owner,
trunk = mainCheckout(root);
}
if (!trunk?.commit) throw new Refused('LAND_TRUNK', 'landing needs the coordinator’s primary branch; return its checkout to the trunk');
+ // Pin accepted policy after any recorded-landed repair, never before admission or from candidate files.
+ config ??= policyAt(root, trunk.commit).config;
+ board.quarantineEnabled = () => config.flakes?.quarantine === true;
const unfinished = store.landingBatches(board).findLast((batch) => batch.state !== 'landed' && batch.state !== 'blocked');
+ if (fence && unfinished && unfinished.branch !== fence.branch) throw new Refused('LAND_LEASE_LOST', 'the interrupted batch belongs to another trunk branch; restore that branch and start a fresh land --adopt');
const selected = candidates(board, root, trunk.commit, maximum);
const stale = selected.blocked.find(item => item.code === 'STALE_VERDICT');
if (!selected.ready.length && stale) throw staleVerdictRefusal({ item_id: stale.id }, stale);
diff --git a/src/landing-worker.js b/src/landing-worker.js
index b9ab8fbd..c5b3f27f 100644
--- a/src/landing-worker.js
+++ b/src/landing-worker.js
@@ -3,7 +3,7 @@ import { spawn, spawnSync } from 'node:child_process';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as store from './board.js';
-import { invalidateGitFacts, repoInfo } from './git.js';
+import { invalidateGitFacts, mainCheckout, repoInfo } from './git.js';
import { Refused } from './refused.js';
import { parseProcessCensus } from './process-census.js';
@@ -156,10 +156,10 @@ async function workerMain(options) {
try {
const { runLandingBatch } = await import('./land.js');
/** Canonical catch-up may have moved proof or trunk while the request was in flight. */
- const checkLease = async () => { await call('check'); invalidateGitFacts(); assertWorkerFence(board, options.fence); };
+ const checkLease = async () => { await call('check'); invalidateGitFacts(); assertWorkerFence(board, options.fence, options.root); };
const result = await runLandingBatch({ ...options, board, write: (operation, args) => call(operation, args),
say: text => process.send({ type: 'say', text }), onWait: state => call('wait', [state]), checkLease,
- checkLeaseNow: () => assertWorkerFence(board, options.fence) });
+ checkLeaseNow: () => assertWorkerFence(board, options.fence, options.root) });
pipe.finish({ type: 'result', value: result });
} catch (error) {
process.exitCode = 1;
@@ -168,9 +168,12 @@ async function workerMain(options) {
}
/** Check the shared native board immediately before a physical Git action, with no intervening await. */
-function assertWorkerFence(board, fence) {
+function assertWorkerFence(board, fence, root) {
// This imported live binding is used only after module initialization, keeping board cycles inert.
- return assertLandingLease(board, fence);
+ const holder = assertLandingLease(board, fence);
+ invalidateGitFacts();
+ if (mainCheckout(root)?.branch !== fence.branch) throw new Refused('LAND_LEASE_LOST', 'the trunk branch changed; start a fresh land command for its current branch');
+ return holder;
}
import { assertLandingLease } from './landing-lease.js';
diff --git a/test/landing-queue-fixture.js b/test/landing-queue-fixture.js
index 03cc17bc..1f22bdac 100644
--- a/test/landing-queue-fixture.js
+++ b/test/landing-queue-fixture.js
@@ -1,9 +1,13 @@
/** Public, real-Git landing contention fixture; no private drill data is used [B3,R3,Q1,Q2,E8]. */
import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import * as store from '../src/board.js';
+import { invalidateGitFacts } from '../src/git.js';
+import { runLandingBatch } from '../src/land.js';
+import { assertLandingLease } from '../src/landing-lease.js';
/** Run an ordinary fixture command and retain its full refusal on failure. */
function run(box, root, ...args) {
@@ -37,7 +41,7 @@ function processObservation(pids) {
}
/** Build two independent items and accept the higher id first through actual CLI checks. */
-function acceptedPair(helpers, box, staleAfterFirst) {
+function acceptedPair(helpers, box, staleAfterFirst, policyAfterFirst) {
const entries = [1, 2].map(number => {
const root = join(box.dir, `queue-build-${number}`);
box.git(box.repo, 'worktree', 'add', '-q', '-b', `web/queue-${number}`, root, 'main');
@@ -52,6 +56,11 @@ function acceptedPair(helpers, box, staleAfterFirst) {
mkdirSync(join(root, 'web'), { recursive: true });
writeFileSync(join(root, 'web', 'queue-1.txt'), 'works changed\n');
}
+ if (number === 2 && policyAfterFirst) {
+ const configPath = join(root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, JSON.stringify({ ...config, gate: config.gate + ' --new-policy', flakes: { quarantine: true } }, null, 2));
+ }
const commit = helpers.commitFile(box, root, file, 'works\n', 'feat(web): build queue fixture [G1]');
assert.equal(commit.status, 0, commit.stderr);
run(box, root, 'submit', String(id));
@@ -67,17 +76,75 @@ function acceptedPair(helpers, box, staleAfterFirst) {
return entries;
}
+/** Use a real public lease and board for bounded internal boundary controls, never a fabricated grant. */
+async function withFixtureLease(box, branch, action) {
+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));
+ const request = { agentId: 'coordinator', action: 'request', branch, token: randomUUID(), pid: process.pid };
+ let fence;
+ try {
+ const grant = store.landingLeaseMove(board, request);
+ assert.equal(grant.acquired, true, 'the private fixture has no remaining lander');
+ fence = { ...request, generation: grant.generation };
+ invalidateGitFacts();
+ const check = () => assertLandingLease(board, fence);
+ return await action({ root: box.repo, board, fence, owner: 'private-boundary-control', say() {},
+ write: async (operation, args) => store[operation](board, ...args), checkLease: async () => { check(); invalidateGitFacts(); }, checkLeaseNow: check });
+ } finally {
+ if (fence) store.landingLeaseMove(board, { ...fence, action: 'release' });
+ store.closeBoard(board);
+ }
+}
+
+/** A lease for one branch cannot follow a same-commit branch switch or adopt another branch's batch. */
+async function interruptedBranchControls(box) {
+ const before = box.git(box.repo, 'rev-parse', 'HEAD');
+ try {
+ await withFixtureLease(box, 'refs/heads/main', async options => {
+ box.git(box.repo, 'switch', '-q', '-c', 'alternate-trunk');
+ invalidateGitFacts();
+ assert.equal(box.git(box.repo, 'rev-parse', 'HEAD'), before, 'only the actual branch identity changes');
+ await assert.rejects(runLandingBatch({ ...options, adopt: true }), error => error.code === 'LAND_LEASE_LOST');
+ });
+ await withFixtureLease(box, 'refs/heads/alternate-trunk', async options => {
+ await assert.rejects(runLandingBatch({ ...options, adopt: true }), error => error.code === 'LAND_LEASE_LOST');
+ assert.equal(store.landingBatches(options.board).length, 1, 'a branch mismatch creates no replacement batch');
+ });
+ } finally { box.git(box.repo, 'switch', '-q', 'main'); invalidateGitFacts(); }
+ assert.equal(box.git(box.repo, 'rev-parse', 'main'), before);
+}
+
+/** Resolve absent config from the repaired accepted tip; explicit direct-call config remains supported. */
+async function repairedPolicyControls(box, batch) {
+ box.git(box.repo, 'reset', '--hard', batch.base); // Only this private fixture simulates receipts preceding local Git repair.
+ await withFixtureLease(box, 'refs/heads/main', async options => {
+ const count = store.landingBatches(options.board).length;
+ const result = await runLandingBatch(options);
+ assert.equal(result.batch, null, 'all items were already durably landed');
+ assert.equal(box.git(box.repo, 'rev-parse', 'main'), batch.tip, 'the recorded landing repairs local Git');
+ assert.equal(options.board.quarantineEnabled(), true, 'policy comes from the repaired accepted tip, not its old base');
+ assert.equal(store.landingBatches(options.board).length, count, 'repair does not invent another batch');
+ });
+ const explicit = JSON.parse(readFileSync(join(box.repo, 'pullboard.json'), 'utf8'));
+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));
+ try {
+ await runLandingBatch({ root: box.repo, board, config: { ...explicit, flakes: { quarantine: false } }, dryRun: true });
+ assert.equal(board.quarantineEnabled(), false, 'explicit config and no-fence dry-run callers retain their behavior');
+ } finally { store.closeBoard(board); }
+}
+
/** Prove named waiting, exclusion and verdict order with two real overlapping land commands. */
-export async function landingQueueCase(t, helpers, { staleAfterFirst = false, killParent = false, killGuardian = false, suspendParent = false } = {}) {
+export async function landingQueueCase(t, helpers, { staleAfterFirst = false, killParent = false, killGuardian = false, suspendParent = false, policyAfterFirst = false } = {}) {
const sandbox = helpers.sandbox();
const arm = join(sandbox.dir, 'landing-armed');
const entered = join(sandbox.dir, 'landing-entered');
const release = join(sandbox.dir, 'landing-release');
const gatePid = join(sandbox.dir, 'landing-gate-pid');
const gateFile = join(sandbox.dir, 'landing-queue-gate.cjs');
+ const policyCalls = join(sandbox.dir, 'landing-policy-calls.jsonl');
writeFileSync(gateFile, [
"const fs = require('node:fs'); const assert = require('node:assert/strict');",
`const [arm,entered,release,gatePid] = ${JSON.stringify([arm, entered, release, gatePid])};`,
+ `fs.appendFileSync(${JSON.stringify(policyCalls)}, JSON.stringify(process.argv.slice(2)) + '\\n');`,
...(suspendParent ? ["if (fs.existsSync(gatePid)) { const old = Number(fs.readFileSync(gatePid,'utf8')); try { process.kill(old,0); throw new Error('the previous landing gate is still running when the successor gate starts'); } catch(error) { if (error.code !== 'ESRCH') throw error; } }"] : []),
// Budget: the suspended-parent control holds beyond the real 30s lease; 65s is a runaway ceiling, not a speed target.
`if (fs.existsSync(arm)) { fs.writeFileSync(gatePid, String(process.pid)); fs.writeFileSync(entered, process.cwd()); const end = Date.now() + ${suspendParent ? 65000 : 20000}; while (!fs.existsSync(release) && Date.now() < end) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20); assert.ok(fs.existsSync(release), 'owning test releases the gate'); }`,
@@ -86,11 +153,20 @@ export async function landingQueueCase(t, helpers, { staleAfterFirst = false, ki
"console.log('TAP version 13\\nok 1 - landed queue files keep their behavior\\n1..1\\n# tests 1\\n# pass 1\\n# fail 0');",
].join('\n'));
const box = helpers.project(`node ${JSON.stringify(gateFile)}`, sandbox);
+ if (policyAfterFirst) {
+ const file = join(box.repo, 'pullboard.json');
+ const config = JSON.parse(readFileSync(file, 'utf8'));
+ config.lanes.web.owns.push('pullboard.json');
+ writeFileSync(file, JSON.stringify(config, null, 2));
+ box.git(box.repo, 'add', 'pullboard.json');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: assign fixture policy ownership');
+ }
const remote = join(box.dir, 'queue-origin.git');
box.git(box.dir, 'init', '-q', '--bare', remote);
box.git(box.repo, 'remote', 'add', 'origin', remote);
box.git(box.repo, 'push', '-q', '-u', 'origin', 'main');
- const entries = acceptedPair(helpers, box, staleAfterFirst);
+ const entries = acceptedPair(helpers, box, staleAfterFirst, policyAfterFirst);
+ writeFileSync(policyCalls, '');
const base = box.git(box.repo, 'rev-parse', 'main');
const children = [];
t.after(async () => {
@@ -158,6 +234,7 @@ export async function landingQueueCase(t, helpers, { staleAfterFirst = false, ki
const waiting = await second.closed;
assert.equal(waiting.code, 1);
assert.match(second.stderrText, /LAND_ADOPT/u, 'a queued ordinary land preserves explicit interrupted-batch adoption');
+ if (killParent) await interruptedBranchControls(box);
rmSync(arm); // Future gates may run, but removing arm cannot unblock the old gate's release loop.
const adopted = JSON.parse(run(box, box.repo, 'land', '--adopt', '--json'));
assert.equal(adopted.batch.id, firstBatch.id);
@@ -183,6 +260,11 @@ export async function landingQueueCase(t, helpers, { staleAfterFirst = false, ki
assert.deepEqual(batches.flatMap(batch => batch.items.map(entry => entry.id)), [entries[1].id, entries[0].id]);
assert.equal(batches[1].base, batches[0].tip, 'the waiter selects against the completed first landing');
assert.equal(box.git(box.repo, 'rev-parse', 'main'), batches[1].tip);
+ if (policyAfterFirst) {
+ const calls = readFileSync(policyCalls, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ assert.deepEqual(calls, [[], ['--new-policy']], 'the waiter uses the policy accepted while it queued');
+ await repairedPolicyControls(box, batches[1]);
+ }
for (const entry of entries) {
assert.equal(readFileSync(join(box.repo, `web/queue-${entry.id}.txt`), 'utf8'), 'works\n');
assert.equal(readBoard(box, board => board.db.prepare("SELECT COUNT(*) AS n FROM event WHERE event_kind='merged' AND item_id=?").get(entry.id).n), 1);
diff --git a/test/team.test.js b/test/team.test.js
index f2bd33bb..6968c2b0 100644
--- a/test/team.test.js
+++ b/test/team.test.js
@@ -34,6 +34,9 @@ after(helpers.cleanup);
test('a trunk lands one batch at a time [B3,R3,Q1,Q2,E8]', { timeout: 120_000 }, // budget: hang ceiling for real private Git, CLI checks, both gate barriers and cleanup; no speed target.
async t => landingQueueCase(t, helpers));
+test('a queued landing uses admitted policy and repairs before pinning it [Q1,B3]', { timeout: 120_000 }, // budget: two real CLI landings and bounded recorded-tip repair, not a speed threshold.
+ async t => landingQueueCase(t, helpers, { policyAfterFirst: true }));
+
test('a queued landing rechecks freshness after its holder moves main [E8,Q1,Q2]', { timeout: 120_000 }, // budget: real private Git/CLI and deterministic gate barrier; no speed target.
async t => landingQueueCase(t, helpers, { staleAfterFirst: true }));