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.

feat(cli): land durable verified batches [B3,R3]

Corey Olsonea8190c3b2a2
diff --git a/docs/api.md b/docs/api.md
index a4e65299..09e3645b 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -86,6 +86,7 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec
| `done` | `version:number`, `id:number`, `commit:string`, `pin:string`, `gate:object` |
| `verify` | `version:number`, `id:number`, `decision:string`, `reason:string` |
| `merged` | `version:number`, `id:number`, `commit:string` |
+| `land` | `version:number`, `batch:object`, `landed:array`, `conflicts:array`, `blocked:array`, `culprits:array`, `flakes:array` |
| `withdraw` | `version:number`, `id:number`, `reason:string` |
| `refreeze` | `version:number`, `id:number`, `after:string` |
| `reopen` | `version:number`, `id:number`, `commit:string` |
@@ -280,3 +281,9 @@ A browser action's decoded response is `{version: 1, event, result: {request}}`;
Row approval and decline first record the person's exact decision through the same authenticated view boundary as the local view, without editing any file. They then create a person-to-coordinator request to run `spec apply`. That request is first in coordinator `resume` and `inbox`. Its status stays `waiting` until the coordinator applies it and answers `done`, or answers `declined <reason>`. Decline resolves the request as `refused` with `REQUEST_DECLINED`, the coordinator's reason and a next step. The browser and relay never run `spec apply`.
`pullboard hold <id> "reason"` holds one open or claimed item; `pullboard hold <id> --off` lifts that hold. Both retain the `hold` JSON shape (`lane`, `held`) and add `id` and `reason` (null when lifted). Held open items are skipped by `next` and refuse new claims with `ITEM_HELD`; an existing live holder can renew and submit. `show` and `list` include the hold actor and reason. Successful `next --json` results may include `reasons` naming skipped holds.
+
+### Landing batches
+
+`pullboard land [--max N] [--dry-run] [--adopt]` is coordinator-only. It merges verified items in verdict order in a separate landing worktree, gates the batch once and records pushed merges. Conflicts and stacked unverified items are named separately. Reproducible failures are bisected; a failing file which passes alone files one flake and holds the batch without retries. Resume includes `landingBatches`, each with its state, owner, exact tip, items and log path.
+
+Only the person can run `pullboard land --waive <test> --until <date> --reason "why"`. A waiver retains every test in the full gate. The batch records its exact tree and each failing test with its covering live waiver; pre-push validates that distinct proof and creates no ordinary green stamp. Expired waivers cannot authorize a push. Existing gate-stamped pushes and `pullboard merged` remain available.
diff --git a/docs/formats.md b/docs/formats.md
index c0d572ff..ab005a21 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -280,6 +280,10 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap
| `accept` | reviewer | `reason`, `commit` |
| `reject` | reviewer | `reason`, `commit` |
| `merged` | coordinator | `commit` |
+| `landing_batch` | coordinator | `batch` |
+| `landing_waiver` | person | `waiver` |
+| `landing_flake` | coordinator | `flake` |
+| `main-moved` | coordinator | `batch`, `items`, `sha` |
| `withdraw` | coordinator | `reason` |
| `refreeze` | coordinator | `before`, `after` |
| `hold` | coordinator | `lane`, `reason` |
@@ -337,3 +341,9 @@ The `pass` event is emitted by `passDecision` only for the coordinator; another
<!-- snapshot-files:end -->
The schema, trigger and parser tables are checked against live `openBoard(':memory:')` and `parseSpec` results. The static export is generated and its files, API v1 shapes and page readers are checked by `docs/formats.test.js`.
+
+### Landing records
+
+Engine 8 adds `recordLandingBatch`, `recordLandingWaiver`, `recordLandingFlake` and `finishLandingBatch`. Older engines stop before applying these operations. Their append-only events need no schema migration. A batch snapshot has version 1, identity, base and tip commits, trunk branch, landing worktree, items with their first-containing merge commits, state, owner, log path and revision. Additional owner-lease and environment fields can be added without changing version 1. A revision refuses stale updates. Successful push precedes the atomic merged receipts and single `main-moved` event.
+
+A person waiver records its identity, named test, expiry, reason and person channel. A distinct landing proof records the exact batch tree and each failing test with its covering waiver identity. Pre-push checks every waiver against the current time; this proof never writes an ordinary green-gate stamp. Flake records retain a test path, source digest, failing names and one defect item, so a repeated observation does not create another defect.
diff --git a/docs/formats.test.js b/docs/formats.test.js
index 2a931df2..d9797438 100644
--- a/docs/formats.test.js
+++ b/docs/formats.test.js
@@ -25,6 +25,10 @@ import {
holdLane,
holdItem,
merged,
+ recordLandingBatch,
+ recordLandingWaiver,
+ recordLandingFlake,
+ finishLandingBatch,
openBoard,
passDecision,
PERSON,
@@ -269,6 +273,11 @@ function recordEventContract() {
reserveReview(board, first, { agentId: reviewer, leaseMs: 60_000, policy: 'agents' });
verify(board, first, { agentId: reviewer, decision: 'ACCEPT', reason: ACCEPT_REASON, note: 'checked the example', head: acceptedCommit, digest: 'second', policy: 'agents' });
merged(board, first, { agentId: coordinator, commit: 'c'.repeat(40) });
+ const batch = recordLandingBatch(board, { agentId: coordinator, batch: { version: 1, id: 'format-example', base: 'a'.repeat(40), tip: 'c'.repeat(40),
+ root: '/landing', branch: 'refs/heads/main', state: 'pushed', owner: 'format-example', logPath: '/landing.log', items: [{ id: first, commit: acceptedCommit, merge: 'c'.repeat(40) }] } });
+ recordLandingWaiver(board, { agentId: PERSON, channel: 'terminal', id: 'format-waiver', test: 'test/flaky.test.js', until: '2099-01-01', reason: 'format example' });
+ recordLandingFlake(board, { agentId: coordinator, test: 'test/flaky.test.js', hash: 'd'.repeat(64), names: ['flaky example'], lane: 'docs', batchId: batch.id });
+ finishLandingBatch(board, { agentId: coordinator, id: batch.id, tip: batch.tip });
const rejected = addItem(board, { by: coordinator, lane: 'docs', title: 'Rejected example' });
claim(board, rejected, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('rejected') });
diff --git a/src/board.js b/src/board.js
index 94128826..4c186d7a 100644
--- a/src/board.js
+++ b/src/board.js
@@ -2402,3 +2402,129 @@ export function stats(board) {
const count = (decision) => verdicts.find((row) => row.decision === decision)?.total ?? 0;
return { items, accepted: count('ACCEPT'), rejected: count('REJECT') };
}
+
+/** Read the latest append-only snapshot of each landing batch [B3,R3,R2]. */
+export function landingBatches(board) {
+ const batches = new Map();
+ for (const row of board.db.prepare("SELECT event_detail FROM event WHERE event_kind = 'landing_batch' ORDER BY event_id").all()) {
+ const { batch } = JSON.parse(row.event_detail);
+ batches.set(batch.id, batch);
+ }
+ return [...batches.values()];
+}
+
+/** Append one coordinator-owned batch revision without changing the board schema [B3,R3]. */
+export function recordLandingBatch(board, { agentId, batch, revision = 0 }) {
+ coordinatorOnly(agentId, 'records landing batches');
+ if (!batch || batch.version !== 1 || typeof batch.id !== 'string' || !/^[a-zA-Z0-9_-]{1,80}$/u.test(batch.id)
+ || !['merging', 'gating', 'bisecting', 'flaky', 'blocked', 'ready', 'pushed', 'landed'].includes(batch.state)
+ || !/^[a-f0-9]{40,64}$/u.test(batch.base ?? '') || !/^[a-f0-9]{40,64}$/u.test(batch.tip ?? '')
+ || typeof batch.root !== 'string' || !batch.root || typeof batch.branch !== 'string' || !batch.branch.startsWith('refs/heads/')
+ || !Array.isArray(batch.items) || batch.items.some((entry) => !Number.isSafeInteger(entry?.id) || entry.id < 1 || !/^[a-f0-9]{40,64}$/u.test(entry.commit ?? ''))
+ || typeof batch.owner !== 'string' || !batch.owner || typeof batch.logPath !== 'string' || !batch.logPath
+ || !Number.isSafeInteger(revision) || revision < 0) {
+ throw new Refused('LAND_BATCH', 'a landing batch needs its exact base, tip, items, state, owner and log path; run pullboard land');
+ }
+ return atomic(board, () => {
+ const previous = landingBatches(board).find((entry) => entry.id === batch.id);
+ if ((previous?.revision ?? 0) !== revision || previous?.state === 'landed') {
+ throw new Refused('LAND_MOVED', 'the landing batch changed; read pullboard resume and adopt its current revision');
+ }
+ if (previous && (previous.base !== batch.base || previous.root !== batch.root || previous.branch !== batch.branch)) {
+ throw new Refused('LAND_BATCH', 'a batch keeps its original base and landing worktree; adopt it with pullboard land --adopt');
+ }
+ const recorded = { ...batch, revision: revision + 1, updatedAt: now(board) };
+ logEvent(board, agentId, 'landing_batch', null, { batch: recorded });
+ return recorded;
+ });
+}
+
+/** Record the person's expiring exception for one named failing test [B3,R3]. */
+export function recordLandingWaiver(board, { agentId, channel, id, test, until, reason }) {
+ if (agentId !== PERSON) throw new Refused('LAND_PERSON_ONLY', 'only the person waives a flaky test; use the person’s terminal or Pullboard View');
+ if (!['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_CHANNEL', 'waivers use the person’s terminal or view; run pullboard view');
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,80}$/u.test(id) || typeof test !== 'string' || !test.trim()
+ || test.startsWith('/') || test.includes('\\') || test.split('/').some((part) => !part || part === '..' || part === '.')
+ || !Number.isFinite(Date.parse(until)) || Date.parse(until) <= board.clock.now().getTime() || typeof reason !== 'string' || !reason.trim()) {
+ throw new Refused('LAND_WAIVER', 'name a test, a future --until date and a nonempty --reason; run pullboard land --waive <test> --until <date> --reason "why"');
+ }
+ return atomic(board, () => {
+ const waiver = { id, test, until: new Date(until).toISOString(), reason: reason.trim(), by: PERSON, channel };
+ logEvent(board, PERSON, 'landing_waiver', null, { waiver });
+ return waiver;
+ });
+}
+
+/** Read every person waiver, retaining expired entries as evidence [B3,R3]. */
+export function landingWaivers(board) {
+ return board.db.prepare("SELECT event_by,event_detail FROM event WHERE event_kind = 'landing_waiver' ORDER BY event_id").all()
+ .filter((row) => row.event_by === PERSON)
+ .map((row) => JSON.parse(row.event_detail).waiver);
+}
+
+/** Find a live person's waiver covering the exact failing file or test name [B3,R3]. */
+export function landingWaiverFor(board, failure) {
+ return landingWaivers(board).findLast((waiver) => Date.parse(waiver.until) > board.clock.now().getTime()
+ && (waiver.test === failure.file || waiver.test === failure.name)) ?? null;
+}
+
+/** File one durable defect per flaky test and retain its source digest [B3,R3]. */
+export function recordLandingFlake(board, { agentId, test, hash, names, lane, batchId }) {
+ coordinatorOnly(agentId, 'files landing flakes');
+ if (typeof test !== 'string' || !test || !/^[a-f0-9]{64}$/u.test(hash ?? '') || !Array.isArray(names) || !names.length || names.some((name) => typeof name !== 'string' || !name) || typeof batchId !== 'string') {
+ throw new Refused('LAND_FLAKE', 'a flake needs its named test, exact source digest and failing names; inspect the landing log');
+ }
+ return atomic(board, () => {
+ const existing = landingFlakes(board).find((entry) => entry.test === test);
+ if (existing?.hash === hash) return existing;
+ const item = existing?.item ?? addItem(board, { by: agentId, lane, title: `Flaky test: ${test}`,
+ criterion: `${test} passes in a full gate and alone without retries; failures: ${names.join(', ')}`, route: 'strong' });
+ const flake = { test, hash, names, item, batchId };
+ logEvent(board, agentId, 'landing_flake', item, { flake });
+ return flake;
+ });
+}
+
+/** Read the latest observation of each named flaky test [B3,R3]. */
+export function landingFlakes(board) {
+ const flakes = new Map();
+ for (const row of board.db.prepare("SELECT event_detail FROM event WHERE event_kind = 'landing_flake' ORDER BY event_id").all()) {
+ const { flake } = JSON.parse(row.event_detail);
+ flakes.set(flake.test, flake);
+ }
+ return [...flakes.values()];
+}
+
+/** Validate a distinct waived landing proof without creating an ordinary gate stamp [B3,R3]. */
+export function waivedLandingProof(board, tree) {
+ return landingBatches(board).findLast((batch) => ['ready', 'pushed', 'landed'].includes(batch.state)
+ && batch.proof?.tree === tree && Array.isArray(batch.proof.failures) && batch.proof.failures.length > 0
+ && batch.proof.failures.every((failure) => {
+ const waiver = landingWaivers(board).find((entry) => entry.id === failure.waiver);
+ return waiver && Date.parse(waiver.until) > board.clock.now().getTime()
+ && (waiver.test === failure.file || waiver.test === failure.name);
+ })) ?? null;
+}
+
+/** Atomically record a pushed batch's first-containing merges and one main-moved receipt [B3,R3]. */
+export function finishLandingBatch(board, { agentId, id, tip }) {
+ coordinatorOnly(agentId, 'finishes a landing');
+ return atomic(board, () => {
+ const batch = landingBatches(board).find((entry) => entry.id === id);
+ if (!batch || batch.tip !== tip) throw new Refused('LAND_BATCH', 'the pushed tip must match its recorded batch; run pullboard land --adopt');
+ if (batch.state === 'landed') return batch;
+ if (batch.state !== 'pushed') throw new Refused('LAND_NOT_PUSHED', 'record a successful push before landing receipts; run pullboard land --adopt');
+ for (const entry of batch.items) {
+ const item = itemById(board, entry.id);
+ if (item.item_commit !== entry.commit || item.item_status !== 'verified') {
+ throw new Refused('LAND_ITEM_MOVED', `item #${entry.id} changed after the batch was gated; rebuild its landing`);
+ }
+ if (item.item_merged_commit && item.item_merged_commit !== entry.merge) {
+ throw new Refused('LAND_ITEM_MOVED', `item #${entry.id} already has another landing receipt; read pullboard show ${entry.id}`);
+ }
+ if (!item.item_merged_commit) merged(board, entry.id, { agentId, commit: entry.merge });
+ }
+ logEvent(board, agentId, 'main-moved', null, { sha: tip, batch: id, items: batch.items.map((entry) => entry.id) });
+ return recordLandingBatch(board, { agentId, batch: { ...batch, state: 'landed' }, revision: batch.revision });
+ });
+}
diff --git a/src/cli.js b/src/cli.js
index af79f611..b3176bb6 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -2,7 +2,7 @@
* The pullboard command line: every command, bound to who is asking (B3, R3). The main checkout is the
* coordinator; every other worktree is the agent that joined from it.
*/
-import { createHash } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
@@ -78,6 +78,7 @@ import { readRelayMachine } from './relay-machine.js';
import { relayJoin, relayPair } from './relay-pairing-client.js';
import { executePersonRequests } from './relay-request-execution.js';
import { engineReceipt } from './engine.js';
+import { land } from './land.js';
const CHECKOUT_LEASES = new WeakMap();
@@ -209,6 +210,9 @@ const OPTIONS = {
check: { type: 'string' },
yes: { type: 'boolean' },
landing: { type: 'boolean' },
+ adopt: { type: 'boolean' },
+ waive: { type: 'string' },
+ until: { type: 'string' },
agent: { type: 'string' },
'agent-light': { type: 'string' },
'agent-mid': { type: 'string' },
@@ -490,7 +494,7 @@ async function bindCheckoutSession(io, positionals, values) {
throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');
}
const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'skills', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',
- 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];
+ 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];
if (!writes.includes(command) && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;
if (command === 'answer' && values.as === 'person') return;
const digest = agentSessionDigest();
@@ -502,7 +506,8 @@ async function bindCheckoutSession(io, positionals, values) {
let agent = info.isMain ? COORDINATOR : null;
if (!info.isMain) {
const ctx = context(io);
- agent = withBoard(ctx, (board) => store.agentAt(board, info.root)?.agent_id);
+ agent = withBoard(ctx, (board) => store.agentAt(board, info.root)?.agent_id
+ ?? (command === 'hook' && store.landingBatches(board).some((batch) => batch.root === info.root && !['landed', 'blocked'].includes(batch.state)) ? COORDINATOR : null));
if (!agent && command !== 'join') throw new Refused('NOT_JOINED', 'this worktree has not joined a lane; run pullboard join <lane> --model "<model name>"');
}
const lease = await bindLocalSession(info, { agent: agent ?? 'unjoined agent', digest, takeover: command === 'takeover', keepLease: !['run', 'next'].includes(command),
@@ -945,6 +950,7 @@ function resumeHere(io) {
awaiting: all.filter((item) => item.item_status === 'submitted' && item.item_built_by === me.id),
toVerify: all.filter((item) => item.item_status === 'submitted' && item.item_built_by !== me.id),
toMerge,
+ ...(isMain ? { landingBatches: store.landingBatches(board) } : {}),
open: all.filter((item) => item.item_status === 'open'),
hold: store.laneHold(board, me.lane),
holds: store.laneHolds(board),
@@ -993,6 +999,7 @@ function resumeHere(io) {
else if (!isMain) for (const item of card.stale) say(`stale: ${item.message}; next: ${item.next}`);
if (card.awaiting.length) say(`awaiting a verdict: ${card.awaiting.map((item) => `#${item.item_id} (${span(ctx, item.item_updated_at)})`).join(', ')}`);
if (isMain) {
+ for (const batch of card.landingBatches.filter((entry) => !['landed', 'blocked'].includes(entry.state))) say(`landing ${batch.id}: ${batch.state}, owner ${batch.owner}, tip ${batch.tip}; log ${batch.logPath}; next: pullboard land --adopt`);
/** Limit each text section; JSON keeps every record for a complete handoff. */
const section = (entries, line) => {
for (const entry of entries.slice(0, 3)) say(line(entry));
@@ -2162,6 +2169,25 @@ function workCommands(io, args) {
submit: async () => submitHere(context(io), idArg(first)),
done: async () => submitHere(context(io), idArg(first)),
verify: () => verifyHere(context(io), idArg(first), args),
+ land: () => act(async (ctx, board, me) => {
+ if (me.id !== COORDINATOR || !ctx.info.isMain) throw new Refused('COORDINATOR_ONLY', 'only the coordinator lands verified batches; ask your coordinator to run pullboard land');
+ if (first || second || rest.length) throw new Refused('USAGE', 'pullboard land [--max N] [--dry-run] [--adopt] | --waive <test> --until <date> --reason "why"');
+ if (values.waive !== undefined) {
+ requirePersonChannel(io.personChannel);
+ const waiver = await ordered(ctx, board, 'recordLandingWaiver', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal',
+ id: randomUUID(), test: values.waive, until: values.until, reason: values.reason }]);
+ io.result?.({ batch: null, landed: [], conflicts: [], blocked: [], culprits: [], flakes: [], waiver });
+ io.say(`waived ${waiver.test} until ${waiver.until}: ${waiver.reason}`);
+ 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,
+ 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);
+ if (!result.batch) io.say(result.items ? `would land: ${result.items.map((id) => `#${id}`).join(', ') || 'none'}` : 'no verified items ready to land');
+ return 0;
+ }),
merged: () => act(async (ctx, board, me) => {
const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
if (recovered) {
@@ -2576,7 +2602,8 @@ async function hookCommand(io, { first, second }) {
if (first === 'pre-commit' || first === 'pre-merge-commit') {
applyFixers(info.root, ctx.config.fix).forEach((note) => io.err(`pullboard pre-commit: ${note}`));
const agent = info.isMain ? null : withBoard(ctx, (board) => store.agentAt(board, info.root));
- problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent, boardFile: ctx.file });
+ const landing = withBoard(ctx, (board) => store.landingBatches(board).some((batch) => batch.root === info.root && !['landed', 'blocked'].includes(batch.state)));
+ problems = preCommitProblems({ root: info.root, isMain: info.isMain || landing, config: ctx.config, agent, boardFile: ctx.file });
} else if (first === 'commit-msg') {
const message = readFileSync(second ?? '', 'utf8');
const spec = loadSpec(info.root, ctx.config);
@@ -2588,9 +2615,15 @@ async function hookCommand(io, { first, second }) {
problems = prePushProblems(info.root, refsText);
if (!problems.length) {
const landing = pushesTrunk(refsText, trunkRef(info.root));
- const gate = await runGate(info.root, ctx.config, { landing, onWait: gateWaitReporter(io) });
- if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');
- if (!gate.isGreen) problems = [`the gate is red; fix it before pushing. ${gateReport(gate)}`];
+ const waived = landing && withBoard(ctx, (board) => store.waivedLandingProof(board, headTree(info.root)));
+ const recordedException = landing && withBoard(ctx, (board) => store.landingBatches(board).some((batch) => batch.proof?.tree === headTree(info.root) && batch.proof.failures?.length));
+ if (waived && isClean(info.root) && !untracked(info.root).length) io.say(`pre-push: exact landing tree covered by live person waivers in batch ${waived.id}; no ordinary green stamp`);
+ else if (recordedException) problems = ['the landing proof has an expired or missing person waiver; ask the person for a new expiring waiver'];
+ else {
+ const gate = await runGate(info.root, ctx.config, { landing, onWait: gateWaitReporter(io) });
+ if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');
+ if (!gate.isGreen) problems = [`the gate is red; fix it before pushing. ${gateReport(gate)}`];
+ }
}
} else {
throw new Refused('USAGE', 'pullboard hook pre-commit | pre-merge-commit | commit-msg <file> | pre-push');
diff --git a/src/engine.js b/src/engine.js
index 504eb130..5106f608 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -16,10 +16,11 @@ export const ENGINE_OPERATIONS = Object.freeze([
'withdraw', 'refreeze', 'reopen', 'shout', 'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'holdItem', 'releaseItemHold',
'addMilestone', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone',
'recordRowDecisions', 'applyRowDecisions', 'appendFact',
+ 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch',
]);
/** Engine version at which each ordered operation first has stable replay semantics. */
-const OPERATION_ENGINE = Object.freeze({ reopen: 8 });
+const OPERATION_ENGINE = Object.freeze({ reopen: 8, recordLandingBatch: 8, recordLandingWaiver: 8, recordLandingFlake: 8, finishLandingBatch: 8 });
/** Read a replica's committed prefix without trusting an independently saved transport cursor. */
export function appliedSequence(board) {
diff --git a/src/git.js b/src/git.js
index 900dd60f..ed286af9 100644
--- a/src/git.js
+++ b/src/git.js
@@ -160,12 +160,12 @@ export function git(cwd, args, { maxBuffer } = {}) {
*
* @param {string} cwd
* @param {string[]} args
- * @returns {{ status: number, stdout: string }}
+ * @returns {{ status: number, stdout: string, stderr: string }}
*/
export function tryGit(cwd, args) {
const result = spawnSync('git', [...GIT_FLAGS, ...args], { cwd, encoding: 'utf8' });
if (changesGitFacts(args)) invalidateGitFacts();
- return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim() };
+ return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim(), stderr: (result.stderr ?? '').trim() };
}
/**
diff --git a/src/help.js b/src/help.js
index 8ffec3fc..786986fe 100644
--- a/src/help.js
+++ b/src/help.js
@@ -92,6 +92,8 @@ Work
Coordinator
pullboard sweep --run "<checker>" --check "<checker on {file}>" [--route light] [--max 20] [--dry-run]
file one item per file a linter, type checker or test reporter flags
+ pullboard land [--max N] [--dry-run] [--adopt] gate and push a durable batch of verified items
+ pullboard land --waive <test> --until <date> --reason \"why\" the person records an expiring test waiver
pullboard merged <id> <commit> record where verified work landed
pullboard withdraw <id> <reason> drop an item nobody should build
pullboard refreeze <id> re-freeze a criterion after its spec rows changed
@@ -160,7 +162,7 @@ Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HE
const HELP_NAMES = [
'tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',
- 'serve', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next',
+ 'serve', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next', 'land',
'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import',
'sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view',
'spec show', 'spec unmet', 'spec signoff', 'spec signers', 'spec signers add', 'forget', 'prompt', 'gate', 'hook',
@@ -186,6 +188,7 @@ const HELP_EXAMPLES = {
status: 'pullboard status', view: 'pullboard view', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',
roadmap: 'pullboard roadmap', milestone: 'pullboard milestone add "0.7.0" --items 12,13',
edit: 'pullboard edit 12 --brief "Add the upload page"', release: 'pullboard release 12',
+ land: 'pullboard land --max 4',
reopen: 'pullboard reopen 12 --note "correct the frozen criterion"',
escalate: 'pullboard escalate 12 --note "needs a manual step"', next: 'pullboard next',
run: 'pullboard run --agent "node agent.js"', 'view export': 'pullboard view --export ./site',
diff --git a/src/json.js b/src/json.js
index 2db25e2e..a2e77c0e 100644
--- a/src/json.js
+++ b/src/json.js
@@ -53,6 +53,7 @@ export const JSON_SHAPES = {
done: shape({ id: 'number', commit: 'string', pin: 'string', gate: 'object' }),
verify: shape({ id: 'number', decision: 'string', reason: 'string' }),
merged: shape({ id: 'number', commit: 'string' }),
+ land: shape({ batch: 'object', landed: 'array', conflicts: 'array', blocked: 'array', culprits: 'array', flakes: 'array' }),
withdraw: shape({ id: 'number', reason: 'string' }),
refreeze: shape({ id: 'number', after: 'string' }),
reopen: shape({ id: 'number', commit: 'string' }),
diff --git a/src/land.js b/src/land.js
new file mode 100644
index 00000000..307942cf
--- /dev/null
+++ b/src/land.js
@@ -0,0 +1,332 @@
+/** Coordinator landing batches retain exact Git and gate receipts across interruptions [B3,R3]. */
+import { createHash, randomUUID } from 'node:crypto';
+import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { dirname, isAbsolute, join, relative } from 'node:path';
+import * as store from './board.js';
+import { git, headCommit, headTree, isClean, mainCheckout, repoInfo, tryGit, untracked } from './git.js';
+import { runGate, runProfiledShell, withGateSlot } from './gate.js';
+import { laneOf } from './lanes.js';
+import { Refused } from './refused.js';
+
+/** Quote a command argument without allowing shell interpolation. */
+function quote(value) { return `'${String(value).replaceAll("'", "'\\''")}'`; }
+
+/** Hash a test's current bytes, so a real correction can unblock its held batch. */
+function testHash(root, file) {
+ try { return createHash('sha256').update(readFileSync(join(root, file))).digest('hex'); }
+ catch { return null; }
+}
+
+/** Derive failing test identities from TAP names and source locations, refusing unknown paths. */
+export function landingFailures(output, root) {
+ const failures = [];
+ let active = null;
+ for (const line of output.split('\n')) {
+ const failed = /^\s*not ok\s+\d+\s+-\s+(.*)$/u.exec(line);
+ if (failed) {
+ active = { name: failed[1].replace(/\s+#.*$/u, ''), file: null };
+ failures.push(active);
+ if (/^(?:\.\/)?(?:test|tests)\/[^\r\n]+\.(?:[cm]?js|ts|py)$/u.test(active.name)) active.file = active.name.replace(/^\.\//u, '');
+ }
+ const location = /^\s*location:\s*['"]?(.+?):\d+(?::\d+)?['"]?\s*$/u.exec(line);
+ if (active && location) {
+ const path = location[1];
+ const file = isAbsolute(path) ? relative(root, path) : path.replace(/^\.\//u, '');
+ if (file && !file.startsWith('../') && !file.includes('\\')) active.file = file;
+ }
+ }
+ const unique = new Map(failures.map((entry) => [`${entry.file}\0${entry.name}`, entry]));
+ return [...unique.values()];
+}
+
+/** Produce a hook-valid lower-case merge subject at a word boundary [R3]. */
+export function landingSubject(item) {
+ const suffix = item.item_spec_ids ? ` [${item.item_spec_ids.split(/[\s,]+/u).filter(Boolean).join(',')}]` : '';
+ const prefix = 'chore(merge): ';
+ const budget = 72 - prefix.length - suffix.length;
+ if (budget < 1) throw new Refused('LAND_HEADER', `item #${item.item_id} cites too many rows for a merge header; shorten its cited set before landing`);
+ const words = item.item_title.toLowerCase().replace(/[\p{Extended_Pictographic}\u200d\uFE0E\uFE0F]/gu, '').replace(/[\r\n]+/gu, ' ').replace(/\[[^\]]*\]/gu, '').trim().split(/\s+/u);
+ let subject = '';
+ for (const word of words) {
+ if ((subject ? `${subject} ${word}` : word).length > budget) break;
+ subject = subject ? `${subject} ${word}` : word;
+ }
+ if (!subject) subject = `item ${item.item_id}`.length <= budget ? `item ${item.item_id}` : String(item.item_id);
+ if (subject.length > budget) throw new Refused('LAND_HEADER', `item #${item.item_id} has no title word that fits its merge header; shorten its cited set before landing`);
+ return `${prefix}${subject.replace(/\.$/u, '')}${suffix}`;
+}
+
+/** Select verified, unmerged candidates in verdict order, retaining dependency order [B3,R3]. */
+function candidates(board, root, base, maximum) {
+ const all = store.listItems(board, { all: true });
+ const pending = all.filter((item) => item.item_status === 'verified' && !item.item_merged_commit);
+ const order = new Map();
+ for (const event of store.events(board)) if (event.event_kind === 'accept') order.set(event.item_id, event.event_id);
+ pending.sort((left, right) => (order.get(left.item_id) ?? Infinity) - (order.get(right.item_id) ?? Infinity) || left.item_id - right.item_id);
+ const ready = [];
+ const blocked = [];
+ const knownReds = store.landingBatches(board).flatMap((batch) => batch.culprits ?? []);
+ for (const item of pending) {
+ const known = knownReds.find((entry) => entry.id === item.item_id && entry.commit === item.item_commit);
+ if (known && !known.tests.every((failure) => store.landingWaiverFor(board, failure))) {
+ blocked.push({ id: item.item_id, code: 'LAND_KNOWN_RED', tests: known.tests });
+ continue;
+ }
+ const dependencies = (item.item_after || '').split(',').filter(Boolean).map(Number);
+ if (dependencies.some((id) => !all.find((other) => other.item_id === id)?.item_merged_commit && !ready.some((other) => other.item_id === id))) continue;
+ const stacked = store.unverifiedSubmissions(board).find((other) => other.item_id !== item.item_id
+ && tryGit(root, ['merge-base', '--is-ancestor', other.item_commit, item.item_commit]).status === 0
+ && tryGit(root, ['merge-base', '--is-ancestor', other.item_commit, base]).status !== 0);
+ if (stacked) {
+ blocked.push({ id: item.item_id, code: 'STACKED_UNVERIFIED', stacked: stacked.item_id });
+ continue;
+ }
+ if (ready.length < maximum) ready.push(item);
+ }
+ return { ready, blocked };
+}
+
+/** Append a durable snapshot before or after each external side effect. */
+async function save(state, patch) {
+ const conflicts = [...new Map([...(state.batch.conflicts ?? []), ...(patch.conflicts ?? [])].map((entry) => [entry.id, entry])).values()];
+ state.batch = await state.write('recordLandingBatch', [{ agentId: 'coordinator', batch: { ...state.batch, ...patch, conflicts }, revision: state.batch.revision ?? 0 }]);
+ return state.batch;
+}
+
+/** Merge one ordered group from the immutable batch base, preserving each first-containing commit. */
+async function mergeGroup(state, items) {
+ const { batch } = state;
+ if (!isClean(batch.root) || untracked(batch.root).length) throw new Refused('LAND_DIRTY', 'the landing worktree has unfinished edits; inspect its recorded path before adopting');
+ git(batch.root, ['checkout', '--detach', batch.base]);
+ const merged = [];
+ const conflicts = [];
+ for (const entry of items) {
+ const item = store.getItem(state.board, entry.id ?? entry.item_id);
+ if (item.item_status !== 'verified' || item.item_commit !== (entry.commit ?? item.item_commit)) throw new Refused('LAND_ITEM_MOVED', `item #${item.item_id} changed; rebuild the batch from current verified work`);
+ const result = tryGit(batch.root, ['merge', '--no-ff', item.item_commit, '-m', landingSubject(item)]);
+ if (result.status !== 0) {
+ const files = tryGit(batch.root, ['diff', '--name-only', '--diff-filter=U']).stdout.split('\n').filter(Boolean);
+ if (!files.length) throw new Refused('LAND_MERGE', `merge of #${item.item_id} failed outside a conflict: ${result.stderr || result.stdout}; inspect ${batch.root} and its hooks before adopting`);
+ git(batch.root, ['merge', '--abort']);
+ conflicts.push({ id: item.item_id, files });
+ state.say(`conflict #${item.item_id}: ${files.join(', ')}`);
+ continue;
+ }
+ const first = git(batch.root, ['rev-list', '--first-parent', '--reverse', 'HEAD']).split('\n')
+ .find((commit) => tryGit(batch.root, ['merge-base', '--is-ancestor', item.item_commit, commit]).status === 0);
+ merged.push({ id: item.item_id, commit: item.item_commit, merge: first });
+ }
+ return { items: merged, conflicts, tip: headCommit(batch.root) };
+}
+
+/** Run one full landing gate and retain its complete output under this batch's immutable phase path. */
+async function gateGroup(state, label) {
+ const tree = headTree(state.batch.root);
+ if (state.gates.has(tree)) return state.gates.get(tree);
+ const directory = join(dirname(state.batch.root), 'logs');
+ mkdirSync(directory, { recursive: true });
+ const logPath = join(directory, `${label}-${state.batch.revision}.log`);
+ await save(state, { state: 'gating', tip: headCommit(state.batch.root), logPath });
+ const gate = await runGate(state.batch.root, state.config, { trustStamp: false, landing: true, onWait: state.onWait });
+ copyFileSync(gate.log, logPath);
+ if (gate.profilePath) copyFileSync(gate.profilePath, `${logPath}.profile.json`);
+ const result = { ...gate, failures: landingFailures(gate.output, state.batch.root), tree, logPath };
+ state.gates.set(tree, result);
+ await save(state, { gateResults: [...state.gates.values()].map(({ tree: testedTree, isGreen, failures, logPath: log }) => ({ tree: testedTree, isGreen, failures, logPath: log })) });
+ return result;
+}
+
+/** Run each failing file once alone, with the same queued machine capacity as other checks. */
+async function diagnose(state, failures) {
+ if (!failures.length || failures.some((entry) => !entry.file)) throw new Refused('LAND_DIAGNOSTIC', `the gate did not name a failing test file; inspect ${state.batch.logPath} and make its reporter name source files`);
+ const files = [...new Set(failures.map((entry) => entry.file))];
+ const flakes = [];
+ for (const file of files) {
+ if (state.diagnosed.has(file)) { if (state.diagnosed.get(file)) flakes.push(file); continue; }
+ const runner = state.config.affectedTests || (/\.[cm]?js$/u.test(file) ? 'node --test' : null);
+ if (!runner) throw new Refused('LAND_DIAGNOSTIC', `no runner can isolate ${file}; configure affectedTests for the project’s test runner`);
+ const result = await withGateSlot(state.batch.root, (lease) => runProfiledShell(state.batch.root, `${runner} ${quote(file)}`, {
+ waitMs: lease.waitMs, artifactDirectory: dirname(state.batch.logPath), artifactPrefix: 'diagnostic', persistLog: true, pipefail: true, gateSlotHeld: true,
+ }), { landing: true, onWait: state.onWait });
+ state.diagnosed.set(file, result.isGreen);
+ await save(state, { diagnostics: [...state.diagnosed].map(([test, isGreen]) => ({ test, isGreen })) });
+ if (result.isGreen) flakes.push(file);
+ }
+ return flakes;
+}
+
+/** Record every failure's exact live waiver rather than changing which tests the gate runs. */
+function waivedProof(state, gate) {
+ if (!gate.failures.length || gate.failures.some((entry) => !entry.file)) return null;
+ const failures = gate.failures.map((failure) => ({ ...failure, waiver: store.landingWaiverFor(state.board, failure)?.id }));
+ return failures.every((entry) => entry.waiver) ? { tree: gate.tree, failures, logPath: gate.logPath } : null;
+}
+
+/** Bisect a reproducible red without retrying any previously tested group. */
+async function bisect(state, items, failures, label = 'split') {
+ if (items.length === 1) {
+ const item = items[0];
+ const text = `Landing batch ${state.batch.id} reproduces failures: ${failures.map((failure) => `${failure.file}: ${failure.name}`).join('; ')}`;
+ if (!store.itemThread(state.board, item.id).some((entry) => entry.type === 'fact' && entry.text === text)) {
+ await state.write('appendFact', [item.id, { agentId: 'coordinator', kind: 'measurement', text }]);
+ }
+ if (!state.culprits.some((entry) => entry.id === item.id)) state.culprits.push({ id: item.id, commit: item.commit, tests: failures });
+ await save(state, { culprits: state.culprits });
+ state.say(`culprit #${item.id}: ${failures.map((failure) => failure.name).join(', ')}`);
+ return [];
+ }
+ const middle = Math.ceil(items.length / 2);
+ const green = [];
+ for (const [index, part] of [items.slice(0, middle), items.slice(middle)].entries()) {
+ const build = await mergeGroup(state, part);
+ await save(state, { ...build, state: 'bisecting' });
+ const gate = await gateGroup(state, `${label}-${index}`);
+ if (gate.isGreen || waivedProof(state, gate)) green.push(...build.items);
+ else {
+ const flakyFiles = await diagnose(state, gate.failures);
+ if (flakyFiles.length) {
+ await fileFlakes(state, gate, flakyFiles);
+ state.flaky = true;
+ return [];
+ }
+ green.push(...await bisect(state, build.items, gate.failures, `${label}-${index}`));
+ }
+ }
+ return green;
+}
+
+/** File a flake once against its named test and leave the batch stopped. */
+async function fileFlakes(state, gate, files) {
+ const flakes = [];
+ for (const file of files) {
+ const owner = laneOf(state.config, file);
+ const lane = owner === 'coordinator' ? store.getItem(state.board, state.batch.items[0].id).item_lane : owner;
+ flakes.push(await state.write('recordLandingFlake', [{ agentId: 'coordinator', test: file, hash: testHash(state.batch.root, file),
+ names: gate.failures.filter((entry) => entry.file === file).map((entry) => entry.name), lane, batchId: state.batch.id }]));
+ }
+ await save(state, { state: 'flaky', failures: gate.failures, flakes });
+ state.say(`flake: ${files.join(', ')}; nothing landed; fix the test or ask the person for an expiring waiver`);
+}
+
+/** Push the exact gated tip before recording receipts, then fast-forward only a clean unchanged main. */
+async function publish(state) {
+ let batch = state.batch;
+ const remote = tryGit(state.root, ['config', '--get', `branch.${batch.branch.replace(/^refs\/heads\//u, '')}.remote`]).stdout || 'origin';
+ if (batch.proof?.failures?.length && batch.state !== 'pushed') {
+ const failures = batch.proof.failures.map((failure) => ({ ...failure, waiver: store.landingWaiverFor(state.board, failure)?.id }));
+ if (!failures.every((failure) => failure.waiver)) throw new Refused('LAND_WAIVER', 'the landing proof has an expired or missing person waiver; ask the person for a new expiring waiver, then adopt the batch');
+ batch = await save(state, { proof: { ...batch.proof, failures } });
+ }
+ if (batch.state !== 'pushed') {
+ if (headCommit(batch.root) !== batch.tip || !isClean(batch.root) || untracked(batch.root).length) throw new Refused('LAND_MOVED', 'the gated landing tree changed; inspect the batch and adopt it again');
+ const current = mainCheckout(state.root);
+ if (current?.commit !== batch.base) throw new Refused('LAND_TRUNK_MOVED', 'main moved during the landing; rebuild the batch from its new tip');
+ const alreadyPushed = tryGit(batch.root, ['ls-remote', remote, batch.branch]).stdout.split(/\s+/u)[0] === batch.tip;
+ if (!alreadyPushed) {
+ const pushed = tryGit(batch.root, ['push', remote, `HEAD:${batch.branch}`]);
+ if (pushed.status !== 0) throw new Refused('LAND_PUSH', `the landing push failed: ${pushed.stderr || pushed.stdout}; inspect the remote and hooks, then run pullboard land --adopt`);
+ }
+ await save(state, { state: 'pushed' });
+ }
+ if (tryGit(batch.root, ['ls-remote', remote, batch.branch]).stdout.split(/\s+/u)[0] !== batch.tip) {
+ throw new Refused('LAND_REMOTE_MOVED', 'the remote no longer names the pushed batch tip; inspect it before adopting, without rewriting the remote');
+ }
+ state.batch = await state.write('finishLandingBatch', [{ agentId: 'coordinator', id: state.batch.id, tip: state.batch.tip }]);
+ const main = mainCheckout(state.root);
+ if (main?.commit === state.batch.base && isClean(state.root) && !untracked(state.root).length) git(state.root, ['merge', '--ff-only', state.batch.tip]);
+ state.say(`landed ${state.batch.items.map((entry) => `#${entry.id}`).join(', ')} at ${state.batch.tip}`);
+ return state.batch;
+}
+
+/** Build, gate, diagnose and durably land one coordinator batch; all external actions stay in its worktree. */
+export async function land({ root, board, config, write, say, owner, maximum = Infinity, dryRun = false, adopt = false, onWait }) {
+ let trunk = mainCheckout(root);
+ const recorded = store.landingBatches(board).findLast((batch) => batch.state === 'landed' && batch.base === trunk?.commit);
+ if (!dryRun && recorded && isClean(root) && !untracked(root).length) {
+ git(root, ['merge', '--ff-only', recorded.tip]);
+ trunk = mainCheckout(root);
+ }
+ if (!trunk?.commit) throw new Refused('LAND_TRUNK', 'landing needs the coordinator’s primary branch; return its checkout to the trunk');
+ const unfinished = store.landingBatches(board).findLast((batch) => batch.state !== 'landed' && batch.state !== 'blocked');
+ const selected = candidates(board, root, trunk.commit, maximum);
+ if (dryRun) {
+ const conflicts = [];
+ for (const item of selected.ready) {
+ const merge = tryGit(root, ['merge-tree', '--write-tree', '--name-only', '-z', trunk.commit, item.item_commit]);
+ if (merge.status === 1) {
+ const parts = merge.stdout.split('\0').slice(1);
+ const end = parts.indexOf('');
+ conflicts.push({ id: item.item_id, files: parts.slice(0, end < 0 ? parts.length : end) });
+ } else if (merge.status !== 0) throw new Refused('LAND_MERGE', 'Git could not preview the landing; restore its objects and retry the dry run');
+ }
+ return { batch: null, landed: [], conflicts, blocked: selected.blocked, culprits: [], flakes: [], items: selected.ready.map((item) => item.item_id) };
+ }
+ if (unfinished && !adopt && unfinished.state !== 'flaky') throw new Refused('LAND_ADOPT', `batch ${unfinished.id} is ${unfinished.state}; inspect pullboard resume, then run pullboard land --adopt`);
+ if (adopt && !unfinished) throw new Refused('LAND_ADOPT', 'there is no interrupted landing batch; run pullboard land');
+ let batch = unfinished;
+ if (batch?.state === 'flaky') {
+ const held = (batch.flakes ?? []).filter((flake) => {
+ const corrected = batch.base !== trunk.commit && testHash(root, flake.test) !== null && testHash(root, flake.test) !== flake.hash;
+ const failures = (batch.failures ?? []).filter((failure) => failure.file === flake.test);
+ return !corrected && (!failures.length || !failures.every((failure) => store.landingWaiverFor(board, failure)));
+ });
+ if (held.length) throw new Refused('LAND_FLAKE', `batch ${batch.id} is held by ${held.map((entry) => entry.test).join(', ')}; fix the test or ask the person for an expiring waiver; nothing retries`);
+ }
+ if (batch && batch.base !== trunk.commit && batch.state !== 'pushed') {
+ await write('recordLandingBatch', [{ agentId: 'coordinator', batch: { ...batch, state: 'blocked', supersededByMain: trunk.commit }, revision: batch.revision }]);
+ batch = null;
+ }
+ if (!batch && !selected.ready.length) {
+ for (const entry of selected.blocked) say(`${entry.code} #${entry.id}${entry.stacked ? ` carries #${entry.stacked}` : ''}`);
+ return { batch: null, landed: [], conflicts: [], blocked: selected.blocked, culprits: [], flakes: [] };
+ }
+ if (!batch) {
+ const id = randomUUID();
+ const directory = join(repoInfo(root).commonDir, 'pullboard', 'landings', id);
+ batch = { version: 1, id, base: trunk.commit, tip: trunk.commit, branch: trunk.branch, root: join(directory, 'worktree'),
+ candidates: selected.ready.map((item) => ({ id: item.item_id, commit: item.item_commit })),
+ items: selected.ready.map((item) => ({ id: item.item_id, commit: item.item_commit })), conflicts: [], blocked: selected.blocked,
+ state: 'merging', owner, logPath: join(directory, 'logs', 'batch.log'), revision: 0 };
+ batch = await write('recordLandingBatch', [{ agentId: 'coordinator', batch }]);
+ mkdirSync(directory, { recursive: true });
+ git(root, ['worktree', 'add', '--detach', batch.root, batch.base]);
+ }
+ const state = { root, board, config, write, say, onWait, batch, culprits: batch.culprits ?? [], flaky: false, gates: new Map((batch.gateResults ?? []).map((result) => [result.tree, result])), diagnosed: new Map((batch.diagnostics ?? []).map((result) => [result.test, result.isGreen])) };
+ await save(state, { owner });
+ if (state.batch.state === 'pushed' || state.batch.state === 'ready') await publish(state);
+ else {
+ const initialItems = state.batch.candidates ?? state.batch.items;
+ if (!existsSync(state.batch.root)) throw new Refused('LAND_WORKTREE', `the recorded landing worktree is missing at ${state.batch.root}; restore it before adopting`);
+ const build = await mergeGroup(state, initialItems);
+ await save(state, { ...build, conflicts: [...state.batch.conflicts, ...build.conflicts] });
+ for (const entry of state.batch.blocked ?? []) say(`${entry.code} #${entry.id}${entry.stacked ? ` carries #${entry.stacked}` : ''}`);
+ if (!build.items.length) await save(state, { state: 'blocked' });
+ else {
+ let gate = await gateGroup(state, 'batch');
+ let proof = gate.isGreen ? null : waivedProof(state, gate);
+ if (!gate.isGreen && !proof) {
+ const flakyFiles = await diagnose(state, gate.failures);
+ if (flakyFiles.length) { await fileFlakes(state, gate, flakyFiles); state.flaky = true; }
+ else {
+ const green = await bisect(state, build.items, gate.failures);
+ if (!state.flaky && green.length) {
+ const rebuilt = await mergeGroup(state, green);
+ await save(state, { ...rebuilt, culprits: state.culprits });
+ gate = await gateGroup(state, 'green-items');
+ proof = gate.isGreen ? null : waivedProof(state, gate);
+ if (!gate.isGreen && !proof) {
+ await save(state, { state: 'blocked', failures: gate.failures, culprits: state.culprits });
+ throw new Refused('LAND_INTERACTION', 'the individually green items fail together; nothing retries or lands; inspect the batch’s failing tests');
+ }
+ } else if (!state.flaky) await save(state, { state: 'blocked', culprits: state.culprits });
+ }
+ }
+ if (!state.flaky && (gate.isGreen || proof)) {
+ await save(state, { state: 'ready', proof: proof ?? { tree: gate.tree, failures: [], logPath: gate.logPath }, culprits: state.culprits });
+ await publish(state);
+ }
+ }
+ }
+ return { batch: state.batch, landed: state.batch.state === 'landed' ? state.batch.items.map((entry) => entry.id) : [],
+ conflicts: state.batch.conflicts ?? [], blocked: state.batch.blocked ?? [], culprits: state.culprits, flakes: state.batch.flakes ?? [] };
+}
diff --git a/src/relay-sender.js b/src/relay-sender.js
index 3b3d58f4..e6a284d3 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -9,7 +9,7 @@ export function relayMoveActor(move) {
if (move.operation === 'shout') return args[0]?.from ?? null;
if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';
if (move.operation === 'release') return args[1] ?? null;
- if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions'].includes(move.operation)) return args[0]?.agentId ?? null;
+ if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;
if (['completeCheckBaseline', 'appendFact', 'editItem', 'escalate', 'recordAttempt', 'claim', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze',
'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'holdItem', 'releaseItemHold', 'reopen', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone'].includes(move.operation)) return args[1]?.agentId ?? null;
return null;
diff --git a/src/relay.js b/src/relay.js
index 320373da..4bc471bf 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -34,7 +34,7 @@ const BASELINE_LOCAL_MOVES = new WeakSet();
const BASELINE_FAILURES = new WeakMap();
const AUTH_NOTICES = new WeakSet();
const ORDERED_MOVE_COMMANDS = new Set(['add', 'edit', 'fact', 'escalate', 'run', 'sweep', 'next', 'claim', 'hold', 'release',
- 'submit', 'done', 'verify', 'merged', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);
+ 'submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);
/** Require a trusted origin; HTTP exists only for loopback development and test relays. */
export function relayOrigin(address) {
@@ -779,7 +779,7 @@ async function sendPending(root, file, state, io) {
function credentialActor(move) {
const args = move.args;
if (move.personRequest || ['register', 'ensureCoordinator'].includes(move.operation)) return 'machine';
- if (move.operation === 'recordRowDecisions'
+ if (['recordRowDecisions', 'recordLandingWaiver'].includes(move.operation)
|| move.operation === 'answerDecision' && args[1]?.asPerson
|| move.operation === 'shout' && args[0]?.request) return 'person';
return relayMoveActor(move);
diff --git a/test/land.test.js b/test/land.test.js
new file mode 100644
index 00000000..5e69ce45
--- /dev/null
+++ b/test/land.test.js
@@ -0,0 +1,394 @@
+/** Exercise landing against real private Git worktrees, hooks, SQLite and bare remotes [B3,R3]. */
+import assert from 'node:assert/strict';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { after, test } from 'node:test';
+import * as store from '../src/board.js';
+import { applyRelayMove, prepareEngineMove } from '../src/engine.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { landingFailures, landingSubject } from '../src/land.js';
+import { createE2eHelpers } from './e2e-helpers.js';
+import { startFixtureChild, runFixtureChild } from './fixture-child.js';
+
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
+const { sandbox, project, commitFile, waitFor, BIN } = e2e;
+const FILES = [1, 2, 3, 4].map((n) => `web/land-${n}.test.js`);
+
+/** Read a private board through public functions, never by mutating its database. */
+function onBoard(box, action, clock) {
+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'), clock);
+ try { return action(board); } finally { store.closeBoard(board); }
+}
+
+/** Return append-only public events for receipt and replay assertions. */
+function events(box) { return onBoard(box, (board) => store.events(board)); }
+
+/** Parse the gate's actual command arguments to distinguish full runs from single-file diagnoses. */
+function calls(box) {
+ return existsSync(box.calls) ? readFileSync(box.calls, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line)) : [];
+}
+
+/** Emit real failing TAP and a separate single-file runner, recording every invocation. */
+function gateFixture(box) {
+ const gate = join(box.dir, 'land-gate.cjs');
+ const checks = join(box.dir, 'land-check.cjs');
+ const callPath = join(box.dir, 'land-gate-calls.jsonl');
+ const hold = join(box.dir, 'hold');
+ const entered = join(box.dir, 'entered');
+ const release = join(box.dir, 'release');
+ const trace = join(box.dir, 'gate-trace.jsonl');
+ writeFileSync(gate, [
+ "const fs = require('node:fs'); const path = require('node:path');",
+ `const calls = ${JSON.stringify(callPath)}; const hold = ${JSON.stringify(hold)}; const entered = ${JSON.stringify(entered)}; const release = ${JSON.stringify(release)}; const trace = ${JSON.stringify(trace)};`,
+ "const root = process.cwd(); const args = process.argv.slice(2); fs.appendFileSync(calls, JSON.stringify(args) + '\\n');",
+ "const alone = args.includes('--alone'); const web = path.join(root, 'web'); const files = alone ? args.filter(a => a !== '--alone') : (fs.existsSync(web) ? fs.readdirSync(web).filter(n => /^land-\\d+\\.test\\.js$/.test(n)).map(n => 'web/' + n) : []);",
+ "fs.appendFileSync(trace, JSON.stringify({ alone, files }) + '\\n'); const fullRuns = fs.readFileSync(trace, 'utf8').trim().split('\\n').map(line => JSON.parse(line)).filter(row => !row.alone).length;",
+ "if (!alone && fs.existsSync(hold) && (fs.readFileSync(hold, 'utf8') === 'armed' || Number(fs.readFileSync(hold, 'utf8')) === fullRuns)) { fs.writeFileSync(entered, root); const end = Date.now() + 20000; while (!fs.existsSync(release) && Date.now() < end) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); if (!fs.existsSync(release)) process.exit(24); }",
+ "console.log('TAP version 13'); let failed = 0;",
+ "files.forEach((file, i) => { const text = fs.readFileSync(path.resolve(root, file), 'utf8'); const red = process.env.LAND_SUPPRESS_RED !== '1' && (text.includes('RED') || !alone && text.includes('FLAKE')); console.log('# Subtest: ' + file + ' keeps the landed behavior'); console.log((red ? 'not ok ' : 'ok ') + (i + 1) + ' - ' + file + ' keeps the landed behavior'); if (red) { failed++; console.log(' ---'); console.log(' location: ' + path.resolve(root, file) + ':1:1'); console.log(' failureType: testCodeFailure'); console.log(' error: fixture behavior is red'); console.log(' ...'); } });",
+ "console.log('1..' + files.length); console.log('# tests ' + files.length); console.log('# pass ' + (files.length - failed)); console.log('# fail ' + failed); process.exitCode = failed ? 1 : 0;",
+ ].join('\n'));
+ writeFileSync(checks, "const fs = require('node:fs'); const file = process.argv[2]; if (!fs.existsSync(file) || !fs.readFileSync(file, 'utf8').trim()) process.exit(1);\n");
+ return { gate: `node ${JSON.stringify(gate)}`, affected: `node ${JSON.stringify(gate)} --alone`, checks, calls: callPath, hold, entered, release, trace };
+}
+
+/** Create a private initialized project with a real bare origin and active hooks. */
+function landProject() {
+ const box = sandbox();
+ const commands = gateFixture(box);
+ const fixture = project(commands.gate, box);
+ const path = join(fixture.repo, 'pullboard.json');
+ const config = JSON.parse(readFileSync(path, 'utf8'));
+ config.affectedTests = commands.affected;
+ writeFileSync(path, JSON.stringify(config, null, 2));
+ fixture.git(fixture.repo, 'add', 'pullboard.json');
+ fixture.git(fixture.repo, 'commit', '-q', '-m', 'chore: configure landing');
+ fixture.git(fixture.web, 'merge', '-q', '--ff-only', 'main');
+ const remote = join(box.dir, 'origin.git');
+ fixture.git(box.dir, 'init', '-q', '--bare', remote);
+ fixture.git(fixture.repo, 'remote', 'add', 'origin', remote);
+ const pushed = fixture.tryGit(fixture.repo, 'push', '-q', '-u', 'origin', 'main');
+ assert.equal(pushed.status, 0, pushed.stderr);
+ return { ...fixture, ...commands, remote };
+}
+
+/** Give one private item a distinct canonical lane identity and an independent main base. */
+function itemWorktree(box, number, file = FILES[number - 1], afterIds = []) {
+ const path = join(box.dir, `land-${number}`);
+ box.git(box.repo, 'worktree', 'add', '-q', '-b', `web/land-${number}`, path, 'main');
+ assert.equal(box.run(path, 'join', 'web').code, 0);
+ const added = box.run(box.repo, 'add', 'web', `Land fixture ${number}`, '--specs', 'G1', '--criterion', `land fixture ${number} remains valid`,
+ '--check', `node ${JSON.stringify(box.checks)} ${JSON.stringify(file)}`, ...(afterIds.length ? ['--after', afterIds.join(',')] : []), '--json');
+ assert.equal(added.code, 0, added.err);
+ const item = JSON.parse(added.out).item.item_id;
+ assert.equal(box.run(path, 'claim', String(item)).code, 0);
+ return { path, item, file };
+}
+
+/** Build and submit a private fixture through its real hooks and item check. */
+function submitItem(box, entry, contents = 'PASS\n') {
+ const committed = commitFile(box, entry.path, entry.file, contents, `feat(web): build land fixture ${entry.item} [G1]`);
+ assert.equal(committed.status, 0, committed.stderr);
+ entry.commit = box.git(entry.path, 'rev-parse', 'HEAD');
+ const submitted = box.run(entry.path, 'submit', String(entry.item));
+ assert.equal(submitted.code, 0, submitted.err);
+ return entry;
+}
+
+/** Verify only private fixture items at their actual submitted commits. */
+function acceptItem(box, entry) {
+ box.git(box.repo, 'switch', '-q', '--detach', entry.commit);
+ try {
+ const verdict = box.run(box.repo, 'verify', String(entry.item), 'accept', '--as', 'coordinator', '--note', 'private landing fixture check passed');
+ assert.equal(verdict.code, 0, verdict.err);
+ } finally { box.git(box.repo, 'switch', '-q', 'main'); }
+}
+
+/** Prepare four independent submitted items and accept them in a caller-selected verdict order. */
+function verifiedFour(box, { red, flaky, order = [0, 1, 2, 3] } = {}) {
+ box.env.LAND_SUPPRESS_RED = '1';
+ const entries = FILES.map((file, index) => itemWorktree(box, index + 1, file));
+ for (const [index, entry] of entries.entries()) submitItem(box, entry, index === red ? 'RED\n' : (Array.isArray(flaky) ? flaky.includes(index) : index === flaky) ? 'FLAKE\n' : 'PASS\n');
+ for (const index of order) acceptItem(box, entries[index]);
+ delete box.env.LAND_SUPPRESS_RED;
+ return entries;
+}
+
+/** Run a successful JSON command, retaining child context if any actual hook or check refuses. */
+function json(box, cwd, ...args) {
+ const result = box.run(cwd, ...args, '--json');
+ assert.equal(result.code, 0, `${result.err}\n${result.out}`);
+ return JSON.parse(result.out);
+}
+
+/** Read the actual first-parent merge sequence at the published tip. */
+function mergeSubjects(box, base, tip) {
+ return box.git(box.repo, 'log', '--reverse', '--first-parent', '--format=%s', `${base}..${tip}`).split('\n').filter(Boolean);
+}
+
+test('land pushes one exact batch in verdict order and records each first-containing merge once [B3,R3]', () => {
+ const box = landProject();
+ const entries = verifiedFour(box, { order: [3, 1, 0, 2] });
+ const base = box.git(box.repo, 'rev-parse', 'main');
+ const start = calls(box).length;
+ const result = json(box, box.repo, 'land', '--max', '4');
+ const order = [3, 1, 0, 2].map((index) => entries[index].item);
+ assert.deepEqual(result.landed, order);
+ assert.deepEqual(mergeSubjects(box, base, result.batch.tip), [4, 2, 1, 3].map((n) => `chore(merge): land fixture ${n} [G1]`));
+ assert.equal(result.batch.state, 'landed');
+ assert.equal(box.git(box.repo, 'rev-parse', 'main'), result.batch.tip);
+ assert.equal(box.git(box.remote, 'rev-parse', 'main'), result.batch.tip, 'real pre-push accepted the gated tip');
+ assert.ok(relative(join(box.repo, '.git', 'pullboard'), result.batch.root).startsWith('landings/'));
+ assert.notEqual(result.batch.root, box.repo);
+ assert.deepEqual(calls(box).slice(start), [[]], 'one full batch gate; pre-push reads its exact green tree stamp');
+ const merges = box.git(box.repo, 'rev-list', '--reverse', '--first-parent', `${base}..${result.batch.tip}`).split('\n');
+ for (const [index, id] of order.entries()) assert.equal(json(box, box.repo, 'show', String(id)).item_merged_commit, merges[index]);
+ const receipt = events(box).filter((event) => event.event_kind === 'main-moved');
+ assert.equal(receipt.length, 1);
+ assert.equal(JSON.parse(receipt[0].event_detail).sha, result.batch.tip);
+ assert.equal(json(box, box.repo, 'resume').landingBatches.at(-1).id, result.batch.id);
+ const eventCount = events(box).length;
+ assert.deepEqual(json(box, box.repo, 'land').landed, []);
+ assert.equal(events(box).length, eventCount, 'second invocation writes no duplicate receipts');
+ assert.deepEqual(calls(box).slice(start), [[]], 'second invocation runs no tests');
+ const lane = box.run(entries[0].path, 'land', '--json');
+ assert.equal(JSON.parse(lane.out).error?.code, 'COORDINATOR_ONLY');
+});
+
+test('land bisects a real red, skips named conflicts and refuses an unverified stack [B3,R3]', () => {
+ const box = landProject();
+ box.env.LAND_SUPPRESS_RED = '1';
+ const entries = FILES.map((file, index) => itemWorktree(box, index + 1, file));
+ for (const entry of entries.slice(0, 3)) submitItem(box, entry, entry === entries[2] ? 'RED\n' : 'PASS\n');
+ const hidden = itemWorktree(box, 5, 'web/unverified.js');
+ assert.equal(commitFile(box, hidden.path, hidden.file, 'unverified\n', 'feat(web): unverified ancestor [G1]').status, 0);
+ const hiddenSha = box.git(hidden.path, 'rev-parse', 'HEAD');
+ box.git(entries[3].path, 'merge', '--no-ff', hiddenSha, '-m', 'feat(web): include ancestor [G1]');
+ submitItem(box, entries[3]);
+ for (const entry of entries) acceptItem(box, entry);
+ assert.equal(box.run(hidden.path, 'submit', String(hidden.item)).code, 0);
+ delete box.env.LAND_SUPPRESS_RED;
+ assert.equal(commitFile(box, box.repo, FILES[1], 'different main content\n', 'chore: create a merge conflict').status, 0);
+ const base = box.git(box.repo, 'rev-parse', 'main');
+ const beforeEvents = events(box).length;
+ const beforeCalls = calls(box).length;
+ const dry = json(box, box.repo, 'land', '--max', '4', '--dry-run');
+ assert.deepEqual(dry.conflicts, [{ id: entries[1].item, files: [FILES[1]] }], JSON.stringify(dry));
+ assert.deepEqual(dry.blocked, [{ id: entries[3].item, code: 'STACKED_UNVERIFIED', stacked: hidden.item }]);
+ assert.equal(events(box).length, beforeEvents, 'dry run creates no board batch');
+ assert.equal(calls(box).length, beforeCalls, 'dry run runs no gate');
+ const result = json(box, box.repo, 'land', '--max', '4');
+ assert.deepEqual(result.landed, [entries[0].item]);
+ assert.deepEqual(result.conflicts, dry.conflicts);
+ assert.deepEqual(result.blocked, dry.blocked);
+ assert.deepEqual(result.culprits.map((entry) => entry.id), [entries[2].item]);
+ assert.equal(result.culprits[0].tests[0].file, FILES[2]);
+ assert.match(result.culprits[0].tests[0].name, /keeps the landed behavior/u);
+ assert.ok(json(box, box.repo, 'show', String(entries[2].item)).thread.some((entry) => entry.type === 'fact' && entry.text.includes(FILES[2])));
+ assert.deepEqual(calls(box).slice(beforeCalls), [[], ['--alone', FILES[2]], [], []], 'one red batch, one isolated diagnostic and two bisection gates; cached green tree is not retested');
+ assert.equal(json(box, box.repo, 'show', String(entries[0].item)).item_merged_commit, result.batch.tip);
+ for (const entry of entries.slice(1)) assert.equal(json(box, box.repo, 'show', String(entry.item)).item_merged_commit, null);
+ assert.equal(box.git(box.remote, 'rev-parse', 'main'), result.batch.tip);
+ assert.notEqual(result.batch.tip, base);
+ const afterCalls = calls(box).length;
+ const again = json(box, box.repo, 'land');
+ assert.deepEqual(again.landed, []);
+ assert.ok(again.blocked.some((entry) => entry.code === 'LAND_KNOWN_RED' && entry.id === entries[2].item));
+ assert.equal(calls(box).length, afterCalls, 'known unchanged red is not retried');
+});
+
+test('land holds a flake without retries and person waivers cover every failure at the exact tree [B3,R3]', () => {
+ const box = landProject();
+ const entries = verifiedFour(box, { flaky: [0, 1] });
+ const base = box.git(box.repo, 'rev-parse', 'HEAD');
+ const start = calls(box).length;
+ const held = json(box, box.repo, 'land');
+ assert.deepEqual(held.landed, []);
+ assert.equal(held.batch.state, 'flaky');
+ assert.deepEqual(held.flakes.map((flake) => flake.test), FILES.slice(0, 2));
+ assert.deepEqual(calls(box).slice(start), [[], ['--alone', FILES[0]], ['--alone', FILES[1]]]);
+ assert.equal(box.git(box.repo, 'rev-parse', 'HEAD'), base);
+ assert.equal(box.git(box.remote, 'rev-parse', 'main'), base);
+ const refused = box.run(box.repo, 'land', '--json');
+ assert.equal(JSON.parse(refused.out).error?.code, 'LAND_FLAKE');
+ assert.deepEqual(calls(box).slice(start), [[], ['--alone', FILES[0]], ['--alone', FILES[1]]], 'nothing retries');
+ assert.equal(events(box).filter((event) => event.event_kind === 'landing_flake').length, 2);
+ const flakeItem = json(box, box.repo, 'show', String(held.flakes.find((flake) => flake.test === FILES[1]).item));
+ assert.match(flakeItem.item_title, /Flaky test: web\/land-2/u);
+ box.env.CODEX_THREAD_ID = 'private-agent-waiver-attempt';
+ const agentAttempt = box.run(box.repo, 'land', '--waive', FILES[1], '--until', '2099-01-01', '--reason', 'private fixture exception', '--json');
+ assert.equal(JSON.parse(agentAttempt.out).error?.code, 'B26_PERSON_CHANNEL');
+ delete box.env.CODEX_THREAD_ID;
+ const waiver = json(box, box.repo, 'land', '--waive', FILES[1], '--until', '2099-01-01', '--reason', 'private fixture exception').waiver;
+ assert.equal(waiver.by, 'person');
+ assert.equal(box.git(box.repo, 'rev-parse', 'HEAD'), base, 'recording a waiver does not land');
+ const partial = box.run(box.repo, 'land', '--json');
+ assert.equal(JSON.parse(partial.out).error?.code, 'LAND_FLAKE', 'one waiver cannot cover the other failing test');
+ assert.deepEqual(calls(box).slice(start), [[], ['--alone', FILES[0]], ['--alone', FILES[1]]], 'partial waiver permits no retry');
+ const waiverZero = json(box, box.repo, 'land', '--waive', FILES[0], '--until', '2099-01-01', '--reason', 'second private fixture exception').waiver;
+ const landed = json(box, box.repo, 'land');
+ assert.deepEqual(landed.landed, entries.map((entry) => entry.item));
+ assert.deepEqual(calls(box).slice(start), [[], ['--alone', FILES[0]], ['--alone', FILES[1]]], 'waiver uses the recorded full gate at the same exact tree without retrying');
+ assert.deepEqual(landed.batch.proof.failures.map((failure) => failure.waiver), [waiverZero.id, waiver.id]);
+ assert.equal(landed.batch.proof.tree, box.git(landed.batch.root, 'rev-parse', 'HEAD^{tree}'));
+ assert.ok(onBoard(box, (board) => store.waivedLandingProof(board, landed.batch.proof.tree)));
+ assert.equal(onBoard(box, (board) => store.waivedLandingProof(board, 'f'.repeat(40))), null, 'proof cannot cover another tree');
+ const stamp = box.git(landed.batch.root, 'rev-parse', '--git-path', 'pullboard-gate-green');
+ assert.ok(!existsSync(stamp) || readFileSync(stamp, 'utf8').trim() !== landed.batch.proof.tree, 'red gate never writes an ordinary green stamp');
+ const expired = { now: () => new Date('2099-01-02T00:00:00Z') };
+ assert.equal(onBoard(box, (board) => store.waivedLandingProof(board, landed.batch.proof.tree), expired), null, 'every waiver must remain live');
+ const event = events(box).find((entry) => entry.event_kind === 'landing_waiver');
+ assert.equal(event.event_by, 'person');
+ assert.equal(commitFile(box, box.repo, 'docs/after-land.md', 'new exact tree\n', 'chore: advance the private tree').status, 0);
+ const laterTree = box.git(box.repo, 'rev-parse', 'HEAD^{tree}');
+ const beforeHook = calls(box).length;
+ onBoard(box, (board) => {
+ store.recordLandingWaiver(board, { agentId: 'person', channel: 'terminal', id: 'expired-hook-proof', test: FILES[1], until: '2000-01-02', reason: 'expired proof fixture' });
+ store.recordLandingBatch(board, { agentId: 'coordinator', batch: { ...landed.batch, id: 'expired-hook-batch', state: 'ready',
+ base: landed.batch.tip, tip: box.git(box.repo, 'rev-parse', 'HEAD'), revision: 0,
+ proof: { tree: laterTree, failures: [{ file: FILES[0], name: FILES[0], waiver: waiverZero.id }, { file: FILES[1], name: FILES[1], waiver: 'expired-hook-proof' }] } } });
+ }, { now: () => new Date('2000-01-01T00:00:00Z') });
+ const hook = runFixtureChild(process.execPath, [BIN, 'hook', 'pre-push'], { cwd: box.repo, env: box.env, encoding: 'utf8',
+ input: `refs/heads/main ${box.git(box.repo, 'rev-parse', 'HEAD')} refs/heads/main ${landed.batch.tip}\n` });
+ assert.equal(hook.status, 1, hook.stdout);
+ assert.match(hook.stderr, /expired or missing person waiver/u);
+ assert.equal(calls(box).length, beforeHook, 'expired proof is refused without rerunning the red gate');
+});
+
+test('land stops again with an expired waiver, and a changed test on main releases the held batch [B3,R3]', () => {
+ const box = landProject();
+ box.env.LAND_SUPPRESS_RED = '1';
+ assert.equal(commitFile(box, box.repo, FILES[0], 'FLAKE\n', 'chore: install a flaky fixture test').status, 0);
+ const entry = itemWorktree(box, 1, 'web/feature.js');
+ submitItem(box, entry);
+ acceptItem(box, entry);
+ delete box.env.LAND_SUPPRESS_RED;
+ const held = json(box, box.repo, 'land');
+ assert.equal(held.batch.state, 'flaky');
+ const past = { now: () => new Date('2000-01-01T00:00:00Z') };
+ onBoard(box, (board) => store.recordLandingWaiver(board, { agentId: 'person', channel: 'terminal', id: 'expired-example', test: FILES[0], until: '2000-01-02', reason: 'expired fixture approval' }), past);
+ const start = calls(box).length;
+ const refused = box.run(box.repo, 'land', '--json');
+ assert.equal(JSON.parse(refused.out).error?.code, 'LAND_FLAKE');
+ assert.equal(calls(box).length, start, 'expired waiver authorizes no retry');
+ assert.equal(commitFile(box, box.repo, FILES[0], 'PASS\n', 'chore: correct the flaky test').status, 0);
+ const landed = json(box, box.repo, 'land');
+ assert.deepEqual(landed.landed, [entry.item]);
+ assert.notEqual(landed.batch.id, held.batch.id);
+ assert.equal(landed.batch.proof.failures.length, 0);
+ assert.deepEqual(calls(box).slice(start), [[]], 'corrected test is gated afresh');
+});
+
+test('land adoption recovers an interrupted gate and keeps one receipt under a new coordinator [B3,R3]', async (t) => {
+ const box = landProject();
+ const entries = verifiedFour(box);
+ writeFileSync(box.hold, 'armed');
+ const child = startFixtureChild(process.execPath, [BIN, 'land', '--json'], { cwd: box.repo, env: box.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ child.stdout.resume(); child.stderr.resume();
+ const closed = new Promise((resolveClose) => child.once('close', (status, signal) => resolveClose({ status, signal })));
+ t.after(() => {
+ writeFileSync(box.release, 'release');
+ if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid, 'SIGKILL'); } catch {} }
+ });
+ await waitFor(() => existsSync(box.entered), 'landing gate entered');
+ const card = json(box, box.repo, 'resume');
+ const batch = card.landingBatches.at(-1);
+ assert.equal(batch.state, 'gating');
+ assert.match(batch.logPath, /batch-\d+\.log$/u);
+ assert.equal(batch.items.length, 4);
+ process.kill(-child.pid, 'SIGKILL');
+ assert.equal((await closed).signal, 'SIGKILL');
+ writeFileSync(box.release, 'release');
+ const refused = box.run(box.repo, 'land', '--json');
+ assert.equal(JSON.parse(refused.out).error?.code, 'LAND_ADOPT');
+ box.env.CODEX_THREAD_ID = 'private-adopting-coordinator';
+ const adopted = json(box, box.repo, 'land', '--adopt');
+ delete box.env.CODEX_THREAD_ID;
+ assert.equal(adopted.batch.id, batch.id);
+ assert.notEqual(adopted.batch.owner, batch.owner);
+ assert.deepEqual(adopted.landed, entries.map((entry) => entry.item));
+ assert.equal(events(box).filter((event) => event.event_kind === 'main-moved').length, 1);
+ assert.equal(json(box, box.repo, 'resume').landingBatches.at(-1).state, 'landed');
+});
+
+test('landing diagnostics retain unknown failures and merge subjects obey typed 72-character headers [B3,R3]', () => {
+ const root = '/private/landing';
+ const failures = landingFailures(`not ok 1 - located failure\n location: ${root}/test/one.test.js:3:4\nnot ok 2 - unknown failure\n`, root);
+ assert.deepEqual(failures, [{ name: 'located failure', file: 'test/one.test.js' }, { name: 'unknown failure', file: null }]);
+ const subject = landingSubject({ item_id: 91, item_title: 'A VERY LONG TITLE '.repeat(10), item_spec_ids: 'B3,R3' });
+ assert.equal(subject, 'chore(merge): a very long title a very long title a very long [B3,R3]');
+ assert.ok(subject.length <= 72);
+});
+
+test('land bisect adoption retains completed gates, isolated diagnostics and original candidates [B3,R3]', async (t) => {
+ const box = landProject();
+ const entries = verifiedFour(box, { red: 2 });
+ writeFileSync(box.trace, '');
+ writeFileSync(box.hold, '3');
+ const child = startFixtureChild(process.execPath, [BIN, 'land', '--json'], { cwd: box.repo, env: box.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ child.stdout.resume(); child.stderr.resume();
+ const closed = new Promise((resolveClose) => child.once('close', (status, signal) => resolveClose({ status, signal })));
+ t.after(() => {
+ writeFileSync(box.release, 'release');
+ if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid, 'SIGKILL'); } catch {} }
+ });
+ await waitFor(() => existsSync(box.entered), 'third full gate inside bisection', 20000);
+ const interrupted = json(box, box.repo, 'resume').landingBatches.at(-1);
+ assert.equal(interrupted.items.length, 2, 'the current half differs from the original four candidates');
+ assert.equal(interrupted.gateResults.length, 2);
+ assert.deepEqual(interrupted.diagnostics, [{ test: FILES[2], isGreen: false }]);
+ process.kill(-child.pid, 'SIGKILL');
+ assert.equal((await closed).signal, 'SIGKILL');
+ writeFileSync(box.release, 'release');
+ const result = json(box, box.repo, 'land', '--adopt');
+ assert.deepEqual(result.landed, [entries[0].item, entries[1].item, entries[3].item]);
+ const trace = readFileSync(box.trace, 'utf8').trim().split('\n').map((line) => JSON.parse(line));
+ assert.equal(trace.filter((row) => !row.alone && row.files.length === 4).length, 1, 'completed initial red is not retried');
+ assert.equal(trace.filter((row) => !row.alone && row.files.join(',') === FILES.slice(0, 2).join(',')).length, 1, 'completed green half is not retried');
+ assert.equal(trace.filter((row) => row.alone && row.files[0] === FILES[2]).length, 1, 'the isolated red is not retried');
+ assert.equal(json(box, box.repo, 'show', String(entries[2].item)).thread.filter((entry) => entry.type === 'fact').length, 1);
+});
+
+test('landing records replay identically with native sender and engine boundaries [B3,R3,H16]', (t) => {
+ const box = landProject();
+ const entry = itemWorktree(box, 1);
+ submitItem(box, entry);
+ acceptItem(box, entry);
+ const document = onBoard(box, (board) => exportBoard(board));
+ const boards = ['one', 'two'].map((name, index) => {
+ const board = store.openBoard(join(box.dir, `${name}.sqlite`), { now: () => new Date(index ? '2030-01-01' : '2020-01-01') });
+ importBoard(board, document);
+ return board;
+ });
+ t.after(() => boards.forEach((board) => store.closeBoard(board)));
+ const batch = { version: 1, id: 'replayed-batch', state: 'pushed', base: box.git(box.repo, 'rev-parse', 'HEAD'), tip: entry.commit,
+ root: join(box.repo, '.git', 'pullboard', 'landings', 'replayed-batch', 'worktree'), branch: 'refs/heads/main', owner: 'coordinator-fixture',
+ logPath: join(box.dir, 'replayed-gate.log'), items: [{ id: entry.item, commit: entry.commit, merge: entry.commit }] };
+ const operations = [
+ ['recordLandingBatch', [{ agentId: 'coordinator', batch }], 'coordinator'],
+ ['recordLandingWaiver', [{ agentId: 'person', channel: 'terminal', id: 'replayed-waiver', test: FILES[0], until: '2099-01-01', reason: 'private replay exception' }], 'person'],
+ ['recordLandingFlake', [{ agentId: 'coordinator', test: FILES[0], hash: 'd'.repeat(64), names: ['private failing test'], lane: 'web', batchId: batch.id }], 'coordinator'],
+ ['finishLandingBatch', [{ agentId: 'coordinator', id: batch.id, tip: entry.commit }], 'coordinator'],
+ ];
+ for (const [index, [operation, args, actor]] of operations.entries()) {
+ const move = prepareEngineMove(boards[0], operation, args, { id: `landing-replay-${index}`, actor });
+ const options = { sequence: index + 1, at: '2026-10-10T17:30:00.000Z', kind: 'move',
+ sender: actor === 'person' ? { kind: 'person', userId: 'fixture-person' } : { kind: 'agent', agent: actor, userId: 'fixture-person' } };
+ const one = applyRelayMove(boards[0], move, options);
+ const two = applyRelayMove(boards[1], move, options);
+ assert.equal(one.error, undefined, JSON.stringify(one));
+ assert.deepEqual(one, two);
+ const before = store.events(boards[0]);
+ assert.deepEqual(applyRelayMove(boards[0], move, options), one, 'replay of a receipt is idempotent');
+ assert.deepEqual(store.events(boards[0]), before);
+ }
+ assert.deepEqual(store.events(boards[0]), store.events(boards[1]), 'different local clocks produce the same authoritative events');
+ assert.equal(store.getItem(boards[0], entry.item).item_merged_commit, entry.commit);
+ assert.equal(store.events(boards[0]).filter((event) => event.event_kind === 'main-moved').length, 1);
+ const old = prepareEngineMove(boards[0], 'recordLandingBatch', [{ agentId: 'coordinator', batch: { ...batch, id: 'old-engine-batch' } }], { id: 'old-engine-landing', actor: 'coordinator' });
+ assert.throws(() => applyRelayMove(boards[0], { ...old, engine: 7 }, { sequence: 5, at: '2026-10-10T17:31:00.000Z', kind: 'move', sender: { kind: 'agent', userId: 'fixture-person', agent: 'coordinator' } }), { code: 'RELAY_MOVE' });
+ const forged = prepareEngineMove(boards[0], 'recordLandingWaiver', operations[1][1], { id: 'forged-landing-waiver', actor: 'person' });
+ const spoof = applyRelayMove(boards[0], forged, { sequence: 5, at: '2026-10-10T17:32:00.000Z', kind: 'move', sender: { kind: 'agent', userId: 'fixture-person', agent: 'web-1' } });
+ assert.equal(spoof.error?.code, 'RELAY_PERSON_ONLY');
+});