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(core): schedule isolated landing prefixes in parallel [B3,V4]

Corey Olsond8fd0b38b260
diff --git a/src/config.js b/src/config.js
index 62381069..e8871535 100644
--- a/src/config.js
+++ b/src/config.js
@@ -203,9 +203,10 @@ export function configProblems(config) {
problems.push('"landingShards" is a whole number from 1 to 64: how many shards the landing gate splits its test files into');
}
if (typeof config.staticChecks !== 'string') problems.push('"staticChecks" is an optional project static-check command');
- if (config.landing !== undefined && (typeof config.landing !== 'object' || config.landing === null || Object.keys(config.landing).some(key => !['publish', 'timeout', 'cadence'].includes(key)) || ![undefined, 'separate'].includes(config.landing.publish))) {
- problems.push('"landing" has optional "timeout" and "cadence" durations, and "publish": "separate" to land locally and push through pullboard publish');
+ if (config.landing !== undefined && (typeof config.landing !== 'object' || config.landing === null || Object.keys(config.landing).some(key => !['publish', 'timeout', 'cadence', 'parallel'].includes(key)) || ![undefined, 'separate'].includes(config.landing.publish))) {
+ problems.push('"landing" has optional "timeout" and "cadence" durations, "parallel": true for concurrent candidate gates, and "publish": "separate" to land locally and push through pullboard publish');
}
+ if (config.landing?.parallel !== undefined && typeof config.landing.parallel !== 'boolean') problems.push('"landing.parallel" is a boolean; omit it or use false to keep serial landing');
for (const key of ['timeout', 'cadence']) {
const value = config.landing?.[key];
const match = typeof value === 'string' ? CHECK_TIMEOUT_RE.exec(value) : null;
diff --git a/src/land.js b/src/land.js
index 6dac5a5c..ffa2d241 100644
--- a/src/land.js
+++ b/src/land.js
@@ -11,6 +11,7 @@ import {
openSync,
readFileSync,
readSync,
+ realpathSync,
} from 'node:fs';
import {
dirname,
@@ -37,6 +38,7 @@ import {
runProfiledShell,
runStaticChecks,
withGateSlot,
+ isStampedGreen,
} from './gate.js';
import {
readGateReceipt,
@@ -50,11 +52,12 @@ import {
requireConfirmedLanding,
} from './landing-lease.js';
import { runLandingWorker } from './landing-worker.js';
+import { runLandingCandidateWorker } from './landing-candidates.js';
import { Refused } from './refused.js';
import { browserFreeChecksEnabled } from './settings.js';
import { tightenLandingDoctrine } from './landing-doctrine.js';
import { policyAt } from './trusted-policy.js';
-import { landingFileTimes } from './submit-invariants.js';
+import { landingFileTimes, validateLandingBatch, validateLandingRevision } from './submit-invariants.js';
import {
flakeSource,
observeNativeFailure,
@@ -349,6 +352,235 @@ async function gateGroup(state, label) {
return result;
}
+/** Merge and test one speculative prefix without giving its worker publication authority. */
+export async function runLandingCandidate({ root, board, config, batch, entries, write, say, onWait, checkLease, checkLeaseNow, claimGate, finishGate }) {
+ await checkLease();
+ if (!existsSync(batch.root)) {
+ mkdirSync(dirname(batch.root), { recursive: true });
+ checkLeaseNow();
+ git(root, ['worktree', 'add', '--detach', batch.root, batch.base]);
+ }
+ board.quarantineEnabled = () => config.flakes?.quarantine === true;
+ const state = { root, board, config, batch, write, say, onWait, checkLease, checkLeaseNow,
+ culprits: [], flaky: false, gates: new Map(), diagnosed: new Map() };
+ const build = await mergeGroup(state, entries);
+ await save(state, { ...build });
+ // A conflicting prefix is not its requested composition. Never test the smaller accidental tree.
+ if (build.conflicts.length || !build.items.length) return { batch: state.batch, gate: null };
+ const tree = headTree(batch.root);
+ const claimed = await claimGate(tree);
+ if (claimed.previous) state.gates.set(tree, claimed.previous);
+ const gate = claimed.cached ?? { ...await gateGroup(state, 'candidate'), proofRoot: state.batch.root, proofCommit: headCommit(state.batch.root) };
+ if (!claimed.cached) await finishGate(tree, gate);
+ await save(state, { state: gate.isGreen ? 'ready' : 'blocked' });
+ return { batch: state.batch, gate };
+}
+
+/** Read a completed speculative result from its immutable raw log, without another execution. */
+function savedCandidateResult(candidate) {
+ if (!candidate.complete) return null;
+ if (candidate.error) throw new Refused(candidate.error.code, candidate.error.message);
+ const gate = candidate.gate;
+ return { batch: candidate.snapshot, gate: gate ? { ...gate, output: readFileSync(gate.logPath, 'utf8') } : null };
+}
+
+/** Keep only small replayable gate metadata; the complete output remains in its immutable log. */
+function candidateGateRecord(gate) {
+ if (!gate) return null;
+ const { tree, isGreen, failures, accounted, complete, requiresGreen, logPath, flakeDiagnostics, timedOut, proofRoot, proofCommit } = gate;
+ return { tree, isGreen, failures, accounted, complete, requiresGreen, logPath,
+ ...(proofRoot ? { proofRoot, proofCommit } : {}),
+ ...(flakeDiagnostics ? { flakeDiagnostics } : {}), ...(timedOut ? { timedOut } : {}) };
+}
+
+/** Run all prefixes through normal admission, serializing their delta receipts under one batch. */
+async function parallelPrefixes(state, entries) {
+ let serial = Promise.resolve();
+ const claims = new Map();
+ /** A failed delta must not prevent other already-running children from sealing their receipts. */
+ const ordered = action => {
+ const pending = serial.then(action);
+ serial = pending.catch(() => {});
+ return pending;
+ };
+ const counts = badgeCounts(state.board);
+ const groups = entries.map((_, index) => entries.slice(0, index + 1));
+ const descriptors = groups.map(group => {
+ const key = createHash('sha256').update(JSON.stringify([state.batch.base, group, counts, liveWaiverProjection(state.board)])).digest('hex');
+ const previous = state.batch.parallelCandidates?.find(candidate => candidate.key === key);
+ if (previous) {
+ if (previous.gate) state.gates.set(previous.gate.tree, previous.gate);
+ return previous;
+ }
+ const directory = join(dirname(state.batch.root), 'candidates', key);
+ return { key, snapshot: { version: 1, id: randomUUID(), base: state.batch.base, tip: state.batch.base,
+ branch: state.batch.branch, root: join(directory, 'worktree'), items: group, candidates: group,
+ conflicts: [], blocked: [], state: 'merging', owner: state.batch.owner,
+ logPath: join(directory, 'logs', 'candidate.log'), revision: 0 } };
+ });
+ await save(state, { state: 'gating', parallelCandidates: [...(state.batch.parallelCandidates ?? []),
+ ...descriptors.filter(candidate => !state.batch.parallelCandidates?.some(previous => previous.key === candidate.key))] });
+ /** Replace only this child's descriptor; every sibling and the parent's evidence stay current. */
+ const update = (key, patch) => ordered(async () => {
+ const latest = state.batch.parallelCandidates.find(candidate => candidate.key === key);
+ const updated = { ...latest, ...patch };
+ await save(state, { parallelCandidates: state.batch.parallelCandidates.map(candidate => candidate.key === key ? updated : candidate) });
+ return updated;
+ });
+ const settled = await Promise.allSettled(descriptors.map(async descriptor => {
+ const previous = savedCandidateResult(descriptor);
+ if (previous) return previous;
+ const key = descriptor.key;
+ /** Virtual child batches append deltas to their one canonical parent, never overwrite it. */
+ const write = async (operation, args) => {
+ if (operation === 'claimGate') {
+ const [tree] = args;
+ const cached = state.gates.get(tree);
+ if (cached?.timedOut) throw new Refused('LAND_GATE_TIMEOUT', 'this exact tree has a recorded landing timeout; inspect its log before starting a new batch');
+ if (cached && (completeGate(cached) || !coveredFailures(state, cached))) return { cached };
+ const prior = claims.get(tree);
+ if (prior) return { cached: await prior.promise };
+ let resolveGate;
+ let rejectGate;
+ const promise = new Promise((resolveResult, rejectResult) => { resolveGate = resolveResult; rejectGate = rejectResult; });
+ void promise.catch(() => {});
+ claims.set(tree, { key, promise, resolveGate, rejectGate });
+ return { owner: true, ...(cached ? { previous: cached } : {}) };
+ }
+ if (operation === 'finishGate') {
+ const [tree, gate] = args;
+ const claim = claims.get(tree);
+ if (!claim || claim.key !== key || gate.tree !== tree) throw new Refused('LAND_CANDIDATE', 'a candidate returned another tree’s gate; inspect its checkpoint');
+ state.gates.set(tree, gate);
+ claim.resolveGate(gate);
+ return null;
+ }
+ if (operation !== 'recordLandingBatch') return await state.write(operation, args);
+ return await ordered(async () => {
+ const { batch, revision } = args[0];
+ const latest = state.batch.parallelCandidates.find(candidate => candidate.key === key);
+ const before = latest.snapshot;
+ validateLandingBatch(batch, revision);
+ validateLandingRevision(before, batch, revision);
+ const snapshot = { ...batch, revision: revision + 1 };
+ const evidence = state.batch.invariantEvidence ?? { version: 1, gates: [], diagnostics: [] };
+ const childEvidence = snapshot.invariantEvidence ?? { gates: [], diagnostics: [] };
+ const oldEvidence = before.invariantEvidence ?? { gates: [], diagnostics: [] };
+ for (const kind of ['gates', 'diagnostics']) {
+ if (JSON.stringify(childEvidence[kind].slice(0, oldEvidence[kind].length)) !== JSON.stringify(oldEvidence[kind])) {
+ throw new Refused('LAND_EVIDENCE', 'candidate evidence is append-only; inspect the saved prefix before adopting');
+ }
+ }
+ await save(state, { parallelCandidates: state.batch.parallelCandidates.map(candidate => candidate.key === key ? { ...candidate, snapshot } : candidate),
+ invariantEvidence: { ...evidence,
+ gates: [...evidence.gates, ...childEvidence.gates.slice(oldEvidence.gates.length)],
+ diagnostics: [...evidence.diagnostics, ...childEvidence.diagnostics.slice(oldEvidence.diagnostics.length)] } });
+ return snapshot;
+ });
+ };
+ try {
+ const result = await runLandingCandidateWorker({ root: state.root, config: state.config, batch: descriptor.snapshot,
+ entries: descriptor.snapshot.candidates, fence: state.fence }, {
+ write, checkLease: state.checkLease, say: state.say, onWait: state.onWait,
+ onStart: pid => update(key, { workerPid: pid }),
+ });
+ await update(key, { complete: true, gate: candidateGateRecord(result.gate) });
+ return result;
+ } catch (error) {
+ for (const claim of claims.values()) if (claim.key === key) claim.rejectGate(error);
+ await update(key, { complete: true, error: { code: error.code ?? 'LAND_CANDIDATE', message: error.message } });
+ throw error;
+ }
+ }));
+ await serial;
+ // All siblings have ended before authority returns to a physical merge or publication.
+ const failure = settled.find(result => result.status === 'rejected');
+ if (failure) throw failure.reason;
+ return settled.map(result => result.value);
+}
+
+/** Move the parent's fixed worktree to an already tested composition without rebuilding its tree. */
+async function promoteCandidate(state, candidate) {
+ await state.checkLease();
+ state.checkLeaseNow();
+ if (!isClean(state.batch.root) || untracked(state.batch.root).length) throw new Refused('LAND_DIRTY', 'the landing worktree changed; inspect it before adopting');
+ git(state.batch.root, ['checkout', '--detach', candidate.batch.tip]);
+ await save(state, { tip: candidate.batch.tip, items: candidate.batch.items,
+ conflicts: candidate.batch.conflicts ?? [], doctrineCounts: candidate.batch.doctrineCounts ?? [] });
+}
+
+/** Exclude a returned candidate and explicit or Git-stacked dependents from later speculation. */
+function withoutParallelBlocker(state, entries, removed) {
+ const blocked = new Set([removed.id]);
+ return entries.filter(entry => {
+ if (blocked.has(entry.id)) return false;
+ const item = store.getItem(state.board, entry.id);
+ const dependency = (item.item_after ?? '').split(',').filter(Boolean).map(Number).find(id => blocked.has(id));
+ const stacked = tryGit(state.root, ['merge-base', '--is-ancestor', removed.reviewedCommit ?? removed.commit, entry.reviewedCommit ?? entry.commit]).status === 0;
+ if (dependency || stacked) {
+ blocked.add(entry.id);
+ state.batch.blocked = [...state.batch.blocked, { id: entry.id, code: 'STACKED_UNVERIFIED', stacked: dependency ?? removed.id }];
+ return false;
+ }
+ return true;
+ });
+}
+
+/** Test prefixes together, remove only diagnosed blockers, and publish one exact green composition. */
+async function parallelLanding(state, initialItems) {
+ let remaining = initialItems;
+ // A death between returning B and saving survivors must never resurrect a C stacked on B.
+ const originals = state.batch.candidates ?? initialItems;
+ for (const id of new Set([...state.culprits.map(entry => entry.id), ...(state.batch.conflicts ?? []).map(entry => entry.id)])) {
+ const removed = originals.find(entry => entry.id === id);
+ if (removed) remaining = withoutParallelBlocker(state, remaining, removed);
+ }
+ const excluded = new Set((state.batch.blocked ?? []).map(entry => entry.id));
+ remaining = remaining.filter(entry => !excluded.has(entry.id));
+ // Restore every sealed tree, even when changed badge counts produce a new descriptor key.
+ for (const candidate of state.batch.parallelCandidates ?? []) {
+ for (const gate of candidate.snapshot.gateResults ?? []) {
+ if (!state.gates.has(gate.tree)) state.gates.set(gate.tree, { ...gate, proofRoot: candidate.snapshot.root,
+ proofCommit: candidate.snapshot.invariantEvidence?.gates.findLast(entry => entry.isGreen)?.commit });
+ }
+ if (candidate.gate) state.gates.set(candidate.gate.tree, candidate.gate);
+ }
+ await save(state, { parallelRemaining: remaining });
+ while (remaining.length) {
+ const results = await parallelPrefixes(state, remaining);
+ const conflicts = results.flatMap(result => result.batch.conflicts ?? []);
+ if (conflicts.length) {
+ const blocker = remaining.find(entry => conflicts.some(conflict => conflict.id === entry.id));
+ await save(state, { conflicts });
+ remaining = withoutParallelBlocker(state, remaining, blocker);
+ await save(state, { parallelRemaining: remaining });
+ continue;
+ }
+ const green = results.findLastIndex(result => result.gate?.isGreen || result.gate && waivedProof(state, result.gate));
+ if (green === results.length - 1) {
+ const candidate = results[green];
+ await promoteCandidate(state, candidate);
+ if (landsOnTrunk(state.config)) { await landOnTrunk(state); return; }
+ if (!await inlineDeferredGuards(state)) { await save(state, { state: 'blocked' }); return; }
+ const proof = candidate.gate.isGreen ? { tree: candidate.gate.tree, failures: [], logPath: candidate.gate.logPath } : waivedProof(state, candidate.gate);
+ if (!proof) throw new Refused('LAND_WAIVER', 'the candidate’s waiver expired; inspect the gate before adopting');
+ await save(state, { state: 'ready', proof, parallelProofRoot: candidate.gate.proofRoot ?? candidate.batch.root, culprits: state.culprits });
+ await publish(state);
+ return;
+ }
+ const boundary = results[green + 1];
+ await promoteCandidate(state, boundary);
+ const gate = boundary.gate;
+ const flakyFiles = await diagnose(state, gate.failures, gate);
+ if (flakyFiles.length) { await fileFlakes(state, gate, flakyFiles); state.flaky = true; return; }
+ const culprit = remaining[green + 1];
+ await bisect(state, [culprit], gate.failures);
+ remaining = withoutParallelBlocker(state, remaining, culprit);
+ await save(state, { parallelRemaining: remaining });
+ }
+ await save(state, { state: 'blocked', culprits: state.culprits });
+}
+
/** Run each failing file once alone, with the same queued machine capacity as other checks. */
async function diagnose(state, failures, gate) {
// The enabled observer already made the only allowed exact-target pair under the original lease.
@@ -620,6 +852,29 @@ function publicationInputs(state, batch) {
if (mainCheckout(state.root)?.commit !== batch.base) throw new Refused('LAND_TRUNK_MOVED', 'main moved during the landing; rebuild the batch from its new tip');
}
+/** Push from the actual gate-owning worktree, preserving its native stamp and canonical batch root. */
+function parallelPublicationRoot(state, batch) {
+ const root = batch.parallelProofRoot ?? batch.root;
+ if (root === batch.root) return root;
+ const owner = (batch.parallelCandidates ?? []).some(candidate => candidate.snapshot.root === root
+ && (candidate.gate?.tree === batch.proof?.tree || candidate.snapshot.gateResults?.some(gate => gate.tree === batch.proof?.tree)));
+ if (!owner || !existsSync(root) || realpathSync(repoInfo(root).commonDir) !== realpathSync(repoInfo(batch.root).commonDir)) {
+ throw new Refused('LAND_MOVED', 'the recorded gate-owning worktree is missing or belongs to another repository; restore it before adopting');
+ }
+ const tree = git(state.root, ['rev-parse', `${batch.tip}^{tree}`]);
+ if (batch.proof?.tree !== tree || headTree(root) !== tree || headTree(batch.root) !== tree || !isClean(root) || untracked(root).length) {
+ throw new Refused('LAND_MOVED', 'the speculative proof no longer matches both clean landing trees; restore the exact recorded composition before adopting');
+ }
+ // Existing native stamps prove trees. A duplicate composition may have different merge metadata;
+ // checking out its identical tree preserves that contract without creating or copying any stamp.
+ state.checkLeaseNow();
+ if (headCommit(root) !== batch.tip) git(root, ['checkout', '--detach', batch.tip]);
+ if (!(batch.proof.failures ?? []).length && !isStampedGreen(root)) {
+ throw new Refused('LAND_MOVED', 'the gate-owning worktree lost its native green stamp; inspect the recorded gate before adopting');
+ }
+ return root;
+}
+
/** Push the exact gated tip before recording receipts, then fast-forward only a clean unchanged main. */
async function publish(state) {
let batch = state.batch;
@@ -632,10 +887,11 @@ async function publish(state) {
if (batch.state !== 'pushed') {
await state.checkLease();
publicationInputs(state, batch);
+ const pushRoot = parallelPublicationRoot(state, batch);
const alreadyPushed = tryGit(batch.root, ['ls-remote', remote, batch.branch]).stdout.split(/\s+/u)[0] === batch.tip;
if (!alreadyPushed) {
state.checkLeaseNow();
- const pushed = tryGit(batch.root, ['push', remote, `HEAD:${batch.branch}`]);
+ const pushed = tryGit(pushRoot, ['push', remote, `HEAD:${batch.branch}`]);
if (pushed.status !== 0) throw pushRefused(pushed.stderr || pushed.stdout);
}
await save(state, { state: 'pushed' });
@@ -909,7 +1165,7 @@ export async function runLandingBatch({ root, board, config, write, say, owner,
mkdirSync(directory, { recursive: true });
git(root, ['worktree', 'add', '--detach', batch.root, batch.base]);
}
- const state = { root, board, config, write, say, onWait, checkLease, checkLeaseNow, 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])) };
+ const state = { root, board, config, write, say, onWait, checkLease, checkLeaseNow, fence, 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])) };
try {
await save(state, { owner });
await returnCulprits(state);
@@ -919,6 +1175,11 @@ export async function runLandingBatch({ root, board, config, write, say, owner,
const initialItems = (state.batch.candidates ?? state.batch.items)
.filter((entry) => !state.culprits.some((culprit) => culprit.id === entry.id && culprit.commit === entry.commit));
if (!existsSync(state.batch.root)) throw new Refused('LAND_WORKTREE', `the recorded landing worktree is missing at ${state.batch.root}; restore it before adopting`);
+ if (state.config.landing?.parallel === true) {
+ await parallelLanding(state, initialItems);
+ 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 ?? [] };
+ }
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}` : ''}`);
diff --git a/src/landing-candidates.js b/src/landing-candidates.js
new file mode 100644
index 00000000..ea81393a
--- /dev/null
+++ b/src/landing-candidates.js
@@ -0,0 +1,130 @@
+/** Isolate speculative landing gates while their one parent retains the board lease [B3,V4]. */
+import { spawn } from 'node:child_process';
+import { join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import * as store from './board.js';
+import { invalidateGitFacts, mainCheckout, repoInfo } from './git.js';
+import { assertLandingLease } from './landing-lease.js';
+import { Refused } from './refused.js';
+
+const FILE = fileURLToPath(import.meta.url);
+
+/** Run one exact prefix in the existing guardian's process group, never publishing it. */
+export async function runLandingCandidateWorker(options, { write, checkLease, say, onWait, onStart }) {
+ const child = spawn(process.execPath, [FILE, 'candidate'], {
+ cwd: options.root, env: process.env, stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
+ });
+ let value;
+ let failure;
+ let stderr = '';
+ const pending = new Set();
+ child.stderr.setEncoding('utf8').on('data', text => { stderr = (stderr + text).slice(-65536); });
+ /** Answer only this owned child, keeping every canonical move in the lease-owning parent. */
+ const answer = (id, result, error) => {
+ if (child.connected) child.send({ type: 'answer', id, value: result,
+ error: error ? { code: error.code ?? 'LAND_CANDIDATE', message: error.message } : null }, () => {});
+ };
+ child.on('message', message => {
+ if (message.type === 'result') { value = message.value; return; }
+ if (message.type === 'failure') { failure = new Refused(message.code, message.message); return; }
+ if (message.type === 'say') { say(message.text); return; }
+ if (message.type !== 'call') return;
+ /** Expose the same narrow receipt operations as an ordinary gate, with virtual batch saves. */
+ const act = async () => {
+ await checkLease();
+ if (message.operation === 'check') return null;
+ if (message.operation === 'wait') return await onWait?.(message.args[0]);
+ if (!['recordLandingBatch', 'recordGateRun', 'recordFlakeObservation', 'claimGate', 'finishGate'].includes(message.operation)) {
+ throw new Refused('LAND_CANDIDATE', 'a speculative gate requested a publishing operation; inspect the landing before adopting');
+ }
+ return await write(message.operation, message.args);
+ };
+ const request = act().then(result => answer(message.id, result), error => answer(message.id, null, error));
+ pending.add(request);
+ void request.finally(() => pending.delete(request));
+ });
+ const terminal = new Promise(resolveClose => {
+ child.once('error', error => { failure = error; });
+ child.once('close', (code, signal) => resolveClose({ code, signal }));
+ });
+ await new Promise((resolveSpawn, reject) => { child.once('spawn', resolveSpawn); child.once('error', reject); });
+ try {
+ await onStart?.(child.pid);
+ await checkLease();
+ child.send({ type: 'start', options }, error => { if (error) failure ??= error; });
+ } catch (error) {
+ // A child waiting for its initial message has no gate or Git descendants to interrupt.
+ child.disconnect();
+ await terminal;
+ throw error;
+ }
+ const status = await terminal;
+ await Promise.allSettled(pending);
+ if (failure) throw failure;
+ if (status.code !== 0 || status.signal || value === undefined) {
+ throw new Refused('LAND_CANDIDATE', `a speculative gate stopped without a result; inspect its saved checkpoint${stderr ? ': ' + stderr.trim() : ''}`);
+ }
+ return value;
+}
+
+/** Execute only through an owned IPC channel; a candidate can ask its parent, never publish. */
+function candidateMain(options) {
+ let next = 0;
+ const pending = new Map();
+ /** Ask the current landing owner to fence and acknowledge one operation. */
+ const call = (operation, args = []) => new Promise((resolveAnswer, reject) => {
+ const id = ++next;
+ pending.set(id, { resolveAnswer, reject });
+ process.send({ type: 'call', id, operation, args }, error => {
+ if (error) { pending.delete(id); reject(error); }
+ });
+ });
+ process.on('message', message => {
+ if (message.type !== 'answer') return;
+ const request = pending.get(message.id);
+ if (!request) return;
+ pending.delete(message.id);
+ if (message.error) request.reject(new Refused(message.error.code, message.error.message));
+ else request.resolveAnswer(message.value);
+ });
+ /** Recheck authority synchronously immediately before a physical Git action. */
+ const checkLeaseNow = board => {
+ if (!options.fence) return;
+ assertLandingLease(board, options.fence);
+ invalidateGitFacts();
+ if (mainCheckout(options.root)?.branch !== options.fence.branch) {
+ throw new Refused('LAND_LEASE_LOST', 'the trunk branch changed while a candidate waited; inspect the landing before adopting');
+ }
+ };
+ /** Keep the shared board read-only here; all receipts are acknowledged through the parent. */
+ const run = async () => {
+ const board = store.openBoardForRead(join(repoInfo(options.root).commonDir, 'pullboard', 'board.sqlite'));
+ if (!board) throw new Refused('LAND_CANDIDATE', 'the candidate cannot read its landing board; restore it before adopting');
+ try {
+ const { runLandingCandidate } = await import('./land.js');
+ return await runLandingCandidate({ ...options, board,
+ write: (operation, args) => call(operation, args),
+ claimGate: tree => call('claimGate', [tree]),
+ finishGate: (tree, gate) => call('finishGate', [tree, gate]),
+ checkLease: async () => { await call('check'); invalidateGitFacts(); checkLeaseNow(board); },
+ checkLeaseNow: () => checkLeaseNow(board),
+ say: text => process.send({ type: 'say', text }),
+ onWait: state => call('wait', [state]),
+ });
+ } finally { store.closeBoard(board); }
+ };
+ void run().then(value => process.send({ type: 'result', value }, () => process.disconnect()), error => {
+ process.exitCode = 1;
+ process.send({ type: 'failure', code: error.code ?? 'LAND_CANDIDATE', message: error.message }, () => process.disconnect());
+ });
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === FILE && process.argv[2] === 'candidate' && process.send) {
+ let started = false;
+ process.on('disconnect', () => { if (!started) process.exitCode = 1; });
+ process.once('message', message => {
+ if (message.type !== 'start') { process.disconnect(); return; }
+ started = true;
+ candidateMain(message.options);
+ });
+}
diff --git a/test/config.test.js b/test/config.test.js
new file mode 100644
index 00000000..c42ab574
--- /dev/null
+++ b/test/config.test.js
@@ -0,0 +1,14 @@
+/** Validate the explicit opt-in to speculative landing without changing serial defaults [B3,V4]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { configFromSource } from '../src/config.js';
+
+test('parallel candidate landing is opt-in and accepts only boolean settings [B3,V4]', () => {
+ assert.notEqual(configFromSource('{}').landing?.parallel, true);
+ for (const parallel of [true, false]) {
+ assert.equal(configFromSource(JSON.stringify({ landing: { parallel } })).landing.parallel, parallel);
+ }
+ for (const parallel of [null, 1, 'true', [], {}]) {
+ assert.throws(() => configFromSource(JSON.stringify({ landing: { parallel } })), { code: 'BAD_CONFIG', message: /landing\.parallel/u });
+ }
+});