Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(land): queue under a board landing lease [Q1,Q2,Q3]
Corey Olson29644da7a247
diff --git a/src/board.js b/src/board.jsindex 0b6717bc..2e2aa4d7 100644--- a/src/board.js+++ b/src/board.js@@ -13,6 +13,8 @@ import {checkedLandingCommit,} from './verdict-reviews.js';export { verdictReviewProblem, verdictsFor, acceptedVerdict, checkedLandingCommit };+export { landingLeaseMove, landingLeaseState } from './landing-lease.js';+import { guardLandingWrite } from './landing-lease.js';import {randomBytes,randomUUID,@@ -2678,7 +2680,7 @@ export { stats } from './board-stats.js';export { landingBatches };/** Append one coordinator-owned batch revision without changing the board schema [B3,R3]. */-export function recordLandingBatch(board, { agentId, batch, revision = 0 }) {+export function recordLandingBatch(board, { agentId, batch, revision = 0, landingFence }) {coordinatorOnly(agentId, 'records landing batches');if (carriesFlakeDiagnostics(batch) && (board.executionEngineVersion ?? ENGINE_VERSION) < NATIVE_FLAKE_ENGINE) {throw new Refused('ENGINE_VERSION', `typed landing diagnostics require engine ${NATIVE_FLAKE_ENGINE}; upgrade Pullboard`);@@ -2691,6 +2693,7 @@ export function recordLandingBatch(board, { agentId, batch, 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, () => {+ guardLandingWrite(board, landingFence);const previous = landingBatches(board).find((entry) => entry.id === batch.id);preserveInvariantEvidence(previous, evidence, board.executionEngineVersion ?? ENGINE_VERSION);validateLandingRevision(previous, batch, revision);@@ -2763,9 +2766,10 @@ export function waivedLandingProof(board, tree) {}/** Atomically record a pushed batch's first-containing merges and one main-moved receipt [B3,R3]. */-export function finishLandingBatch(board, { agentId, id, tip }) {+export function finishLandingBatch(board, { agentId, id, tip, landingFence }) {coordinatorOnly(agentId, 'finishes a landing');return atomic(board, () => {+ guardLandingWrite(board, landingFence);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;@@ -2795,6 +2799,6 @@ export function finishLandingBatch(board, { agentId, id, tip }) {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 });+ return recordLandingBatch(board, { agentId, batch: { ...batch, state: 'landed' }, revision: batch.revision, landingFence });});}diff --git a/src/cli.js b/src/cli.jsindex 4b200f2c..e691883b 100644--- a/src/cli.js+++ b/src/cli.js@@ -972,7 +972,7 @@ async function bindCheckoutSession(io, positionals, values) {CHECKOUT_BOARD_ONLY.set(io, command);return;}- const lease = await bindLocalSession(info, { agent: agent ?? 'unjoined agent', digest, takeover: command === 'takeover', keepLease: !['run', 'next'].includes(command), waitLimitMs: command === 'hook' ? HOOK_CHECKOUT_WAIT_MS : 0,+ const lease = await bindLocalSession(info, { agent: agent ?? 'unjoined agent', digest, takeover: command === 'takeover', keepLease: !['run', 'next', 'land'].includes(command), waitLimitMs: command === 'hook' ? HOOK_CHECKOUT_WAIT_MS : 0,/** Record the takeover; a linked main checkout takes the board's coordinator before its receipt shout, which the hold would refuse (#347). */recordTakeover: async () => (await import('./commands/takeover.js')).recordCheckoutTakeover(io, info),});diff --git a/src/engine.js b/src/engine.jsindex ed5129dd..eb8926ac 100644--- a/src/engine.js+++ b/src/engine.js@@ -66,6 +66,7 @@ import { LOCAL_LANDING_ENGINE } from './land-engine.js';import { REVIEW_SKIP_ENGINE } from './review-skip-engine.js';import { COORDINATOR_HOLD_ENGINE } from './coordinator-hold-engine.js';import { requireCoordinatorHold } from './coordinator-hold.js';+import { LANDING_LEASE_ENGINE } from './landing-lease-engine.js';const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);@@ -78,7 +79,7 @@ export const ENGINE_OPERATIONS = Object.freeze(['recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact', 'recordSpecApprovalBaseline','recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch', 'acceptCheck','recordHealthFindings', 'proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun',- 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator',+ 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove',]);/** Engine version at which each ordered operation first has stable replay semantics. */@@ -87,6 +88,7 @@ const OPERATION_ENGINE = Object.freeze({ draftSpecRow: ROW_DRAFT_ENGINE, orderMi/** Dependency edits, causes, sealed reviews, submission proofs, trunk conflicts, health observations and milestone targets retain distinct recorded engine meanings. */function minimumOperationEngine(operation, args, board, at) {+ if (operation === 'landingLeaseMove' || args[0]?.landingFence !== undefined) return LANDING_LEASE_ENGINE;if (['verify', 'reopen'].includes(operation) && args[1]?.reopenFirstRefusalMinutes !== undefined|| ['claim', 'release'].includes(operation) && board && firstRefusal(board, args[0], at)) return REOPEN_FIRST_REFUSAL_ENGINE;// A batch landed on the local trunk before it is published (#801).diff --git a/src/land.js b/src/land.jsindex 5140a842..53c3e5bd 100644--- a/src/land.js+++ b/src/land.js@@ -24,6 +24,7 @@ import {headCommit,headTree,isClean,+ invalidateGitFacts,mainCheckout,repoInfo,tryGit,@@ -40,6 +41,7 @@ import {receiptStore,} from './gate-run-receipt.js';import { laneOf } from './lanes.js';+import { takeResource } from './resources.js';import { Refused } from './refused.js';import { landingFileTimes } from './submit-invariants.js';import {@@ -155,12 +157,14 @@ async function save(state, patch) {/** Merge one ordered group from the immutable batch base, preserving each first-containing commit. */async function mergeGroup(state, items) {+ await state.checkLease();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) {+ await state.checkLease();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 checked = store.checkedLandingCommit(state.board, item);@@ -580,6 +584,7 @@ async function publish(state) {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) {+ await state.checkLease();const pushed = tryGit(batch.root, ['push', remote, `HEAD:${batch.branch}`]);if (pushed.status !== 0) throw pushRefused(pushed.stderr || pushed.stdout);}@@ -589,6 +594,7 @@ async function publish(state) {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 }]);+ await state.checkLease();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}`);@@ -639,18 +645,55 @@ async function landOnTrunk(state) {/** Record a tier-1 batch's merged receipts and move the local trunk to it; an adopted 'trunk' batch resumes here (#801). */async function finishTrunk(state) {state.batch = await state.write('finishLandingBatch', [{ agentId: 'coordinator', id: state.batch.id, tip: state.batch.tip }]);+ await state.checkLease();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} on the local trunk; pullboard publish pushes it once the whole suite passes`);}/** 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 }) {+export async function land(options) {+ if (options.dryRun) return landBatch(options);+ const branch = mainCheckout(options.root)?.branch;+ if (!branch) throw new Refused('LAND_TRUNK', 'landing needs the coordinator’s primary branch; return its checkout to the trunk');+ let lastWait = '';+ const lease = await takeResource({ name: 'landing', scope: 'board', capacity: 1, board: options.board, write: options.write, branch,+ /** Report a real ordered holder, without allocating machine test capacity to this waiter. */+ onWait({ holders, position }) {+ const message = `landing waiting: ${branch} held by ${holders[0]?.label ?? 'the previous landing'}; queued at place ${position}`;+ if (message !== lastWait) options.say(message);+ lastWait = message;+ } });+ let failed = false;+ try {+ await lease.assertHeld();+ invalidateGitFacts(); // The holder may have moved main while this command waited.+ /** Bind each batch transition to this acknowledged grant, never to an optimistic local result. */+ const write = async (operation, args) => {+ await lease.assertHeld();+ const values = ['recordLandingBatch', 'finishLandingBatch'].includes(operation)+ ? [{ ...args[0], landingFence: lease.fence }, ...args.slice(1)] : args;+ return options.write(operation, values);+ };+ return await landBatch({ ...options, write, checkLease: lease.assertHeld });+ } catch (error) { failed = true; throw error; }+ finally {+ try { await lease.release(); }+ catch (error) {+ if (!failed) throw error;+ options.say(`landing lease release was not acknowledged: ${error.code ?? 'ERROR'}; inspect pullboard resume before adopting`);+ }+ }+}++/** Select only after admission, retaining the existing batch, proof and adoption rules. */+async function landBatch({ root, board, config, write, say, owner, maximum = Infinity, dryRun = false, adopt = false, onWait, checkLease }) {// Quarantine is read from the accepted main policy this landing runs under, never from a branch.board.quarantineEnabled = () => config.flakes?.quarantine === true;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) {+ await checkLease();git(root, ['merge', '--ff-only', recorded.tip]);trunk = mainCheckout(root);}@@ -703,7 +746,7 @@ export async function land({ root, board, config, write, say, owner, maximum = ImkdirSync(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])) };+ const state = { root, board, config, write, say, onWait, checkLease, 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 });await returnCulprits(state);if (state.batch.state === 'trunk') await finishTrunk(state);diff --git a/src/landing-lease-engine.js b/src/landing-lease-engine.jsnew file mode 100644index 00000000..807ea3ae--- /dev/null+++ b/src/landing-lease-engine.js@@ -0,0 +1,2 @@+/** Board-ordered landing admission retains its own replay meaning [Q1,Q2,Q3]. */+export const LANDING_LEASE_ENGINE = 76;diff --git a/src/landing-lease.js b/src/landing-lease.jsnew file mode 100644index 00000000..4854d97e--- /dev/null+++ b/src/landing-lease.js@@ -0,0 +1,104 @@+/** Ordered board admission serializes one trunk independently of machine test capacity [Q1,Q2,Q3]. */+import { atomic, logEvent } from './board.js';+import { COORDINATOR } from './config.js';+import { coordinatorHolder } from './coordinator-hold.js';+import { Refused } from './refused.js';++const KEY = 'landing_lease';+export const LANDING_LEASE_MS = 30_000;++/** Read the durable queue without treating a corrupt record as an unoccupied trunk. */+export function landingLeaseState(board) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(KEY);+ if (!row) return { generation: 0, holder: null, line: [] };+ try {+ const state = JSON.parse(row.meta_value);+ if (!Number.isSafeInteger(state.generation) || state.generation < 0 || !Array.isArray(state.line)+ || state.holder && (!Number.isSafeInteger(state.holder.generation) || state.holder.generation < 1 || state.holder.generation !== state.generation)+ || [state.holder, ...state.line].filter(Boolean).some(entry => !validEntry(entry))+ || new Set([state.holder, ...state.line].filter(Boolean).map(entry => entry.token)).size !== state.line.length + Number(Boolean(state.holder))) throw new Error('invalid landing queue');+ return state;+ } catch { throw new Refused('LAND_LEASE_CORRUPT', 'the landing queue is unreadable; restore the board from a consistent export before landing'); }+}++/** Validate every queue identity before it becomes durable or controls admission. */+function validEntry(entry) {+ return entry && /^[a-f0-9-]{36}$/u.test(entry.token ?? '') && typeof entry.branch === 'string' && entry.branch.length > 0+ && entry.branch.length <= 256 && typeof entry.label === 'string' && entry.label.length > 0 && entry.label.length <= 160+ && !/[\r\n]/u.test(entry.label) && Number.isSafeInteger(entry.pid) && entry.pid > 0+ && (entry.lineage === null || typeof entry.lineage === 'string' && entry.lineage.length > 0 && entry.lineage.length <= 64)+ && Number.isFinite(Date.parse(entry.until)) && Number.isFinite(Date.parse(entry.since));+}++/** A fence must still identify the current, unexpired holder under the current coordinator. */+export function assertLandingLease(board, fence) {+ requireConfirmedLanding(board);+ const holder = landingLeaseState(board).holder;+ const lineage = coordinatorHolder(board)?.lineage ?? null;+ if (!holder || holder.token !== fence?.token || holder.generation !== fence?.generation || holder.branch !== fence?.branch+ || Date.parse(holder.until) <= board.clock.now().getTime() || holder.lineage !== lineage) {+ throw new Refused('LAND_LEASE_LOST', 'this command no longer holds the board landing lease; stop its external work, inspect pullboard resume and adopt only after the holder finishes');+ }+ return holder;+}++/** Pending local intents are not authority to merge, push or move the trunk (#1013 integration boundary). */+export function requireConfirmedLanding(board) {+ if (board.db.prepare("SELECT 1 FROM board_meta WHERE meta_key GLOB 'relay_local_intent_*' LIMIT 1").get()) {+ throw new Refused('RELAY_CONFIRMATION_PENDING', 'this board has local moves awaiting relay confirmation; wait for their ordered receipts before landing');+ }+}++/** Refuse an unowned new batch write while another invocation holds the trunk. */+export function guardLandingWrite(board, fence) {+ if (fence || landingLeaseState(board).holder) assertLandingLease(board, fence);+}++/** Persist a complete queue transition and a compact, append-only admission receipt. */+function save(board, state, action, token) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')+ .run(KEY, JSON.stringify(state));+ logEvent(board, COORDINATOR, 'landing_lease', null, { action, token, holder: state.holder?.label ?? null, generation: state.generation, queued: state.line.length });+}++/** Enqueue, renew, inspect ownership or release through one deterministic ordered operation. */+export function landingLeaseMove(board, { agentId, action, token, branch, pid, generation }) {+ if (agentId !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator takes a landing lease; ask your coordinator to run pullboard land');+ if (!['request', 'renew', 'release'].includes(action) || !/^[a-f0-9-]{36}$/u.test(token ?? '')) {+ throw new Refused('LAND_LEASE_REQUEST', 'a landing lease needs its command identity and a supported action; run pullboard land');+ }+ return atomic(board, () => {+ const state = landingLeaseState(board);+ const before = JSON.stringify(state);+ const at = board.clock.now();+ if (action === 'release') {+ if (state.holder?.token === token && state.holder.generation === generation) state.holder = null;+ state.line = state.line.filter(entry => entry.token !== token);+ } else if (action === 'renew') {+ const holder = assertLandingLease(board, { token, branch, generation });+ state.holder = { ...holder, until: new Date(at.getTime() + LANDING_LEASE_MS).toISOString() };+ } else {+ requireConfirmedLanding(board);+ if (state.holder && Date.parse(state.holder.until) <= at.getTime()) state.holder = null;+ state.line = state.line.filter(entry => Date.parse(entry.until) > at.getTime());+ const old = state.holder?.token === token ? state.holder : state.line.find(entry => entry.token === token);+ const holder = coordinatorHolder(board);+ const entry = { token, branch, pid, label: `${holder?.label ?? 'coordinator'} landing ${token.slice(0, 8)}`,+ lineage: holder?.lineage ?? null, since: old?.since ?? at.toISOString(), until: new Date(at.getTime() + LANDING_LEASE_MS).toISOString() };+ if (!validEntry(entry)) throw new Refused('LAND_LEASE_REQUEST', 'a landing request needs its trunk and process identity; run pullboard land');+ if (old && (old.branch !== branch || old.pid !== pid || old.lineage !== entry.lineage)) {+ throw new Refused('LAND_LEASE_REQUEST', 'this landing identity already belongs to another invocation; start a new pullboard land command');+ }+ if (state.holder?.token === token) state.holder = { ...entry, generation: state.holder.generation };+ else if (old) state.line = state.line.map(queued => queued.token === token ? entry : queued);+ else state.line.push(entry);+ if (!state.holder && state.line.length) {+ state.generation += 1;+ state.holder = { ...state.line.shift(), generation: state.generation };+ }+ }+ if (JSON.stringify(state) !== before) save(board, state, action, token);+ return { holder: state.holder, position: state.line.findIndex(entry => entry.token === token) + 1,+ acquired: state.holder?.token === token, generation: state.holder?.token === token ? state.holder.generation : null };+ });+}diff --git a/src/landing-resource.js b/src/landing-resource.jsnew file mode 100644index 00000000..fbd8ca2d--- /dev/null+++ b/src/landing-resource.js@@ -0,0 +1,55 @@+/** Wait for board admission without occupying a machine test slot [Q1,Q2,Q3]. */+import { randomUUID } from 'node:crypto';+import { setTimeout as pause } from 'node:timers/promises';+import { landingLeaseState } from './landing-lease.js';++/** A dead local owner can be released immediately on an unlinked board; never compare foreign PIDs. */+function deadLocalOwner(holder) {+ if (!holder || holder.lineage !== null) return false;+ try { process.kill(holder.pid, 0); return false; }+ catch (error) { return error.code === 'ESRCH'; }+}++/** Return a generation-bound lease whose renewal failures prevent later landing writes. */+export async function takeLandingResource({ board, write, branch, onWait }) {+ const token = randomUUID();+ const parameters = { agentId: 'coordinator', token, branch, pid: process.pid };+ let generation = null;+ let timer;+ let pending = Promise.resolve();+ let lost = null;+ /** Serialize heartbeats and explicit checks, retaining a failure until the command stops. */+ const assertHeld = () => {+ const task = pending.then(async () => {+ if (lost) throw lost;+ try { return await write('landingLeaseMove', [{ ...parameters, action: 'renew', generation }]); }+ catch (error) { lost = error; throw error; }+ });+ pending = task.catch(() => {});+ return task;+ };+ try {+ while (true) {+ const holder = landingLeaseState(board).holder;+ if (deadLocalOwner(holder)) await write('landingLeaseMove', [{ agentId: 'coordinator', action: 'release', token: holder.token, generation: holder.generation }]);+ const result = await write('landingLeaseMove', [{ ...parameters, action: 'request' }]);+ if (result.acquired) { generation = result.generation; break; }+ await onWait?.({ holders: result.holder ? [result.holder] : [], position: result.position });+ await pause(1000);+ }+ timer = setInterval(() => { void assertHeld().catch(() => {}); }, 5000);+ timer.unref();+ return { name: 'landing', scope: 'board', fence: { token, branch, generation }, assertHeld,+ /** End renewals before releasing; a stale generation never clears its successor. */+ async release() {+ clearInterval(timer);+ await pending;+ await write('landingLeaseMove', [{ ...parameters, action: 'release', generation }]);+ } };+ } catch (error) {+ clearInterval(timer);+ try { await write('landingLeaseMove', [{ ...parameters, action: 'release', generation }]); }+ catch { /* Preserve the admission failure; the ordered lease expires without a false grant. */ }+ throw error;+ }+}diff --git a/src/relay-sender.js b/src/relay-sender.jsindex c0f3c499..bdca0eab 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -10,7 +10,7 @@ export function relayMoveActor(move) {if (move.operation === 'addItem') return args[0]?.by ?? null;if (move.operation === 'shout') return args[0]?.from ?? null;if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(move.operation)) return args[0]?.agentId ?? null;- if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator'].includes(move.operation)) return args[0]?.agentId ?? null;+ if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove'].includes(move.operation)) return args[0]?.agentId ?? 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', 'draftSpecRow', 'recordSpecApprovalBaseline', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;diff --git a/src/relay.js b/src/relay.jsindex 00128d46..66f04dd8 100644--- a/src/relay.js+++ b/src/relay.js@@ -1148,12 +1148,14 @@ function outboxLink(root, file, state, io) {/** Send one board operation before executing it locally, and report its canonical engine result. */export async function relayOperation(root, operation, args, io, command, applyLocally) {const file = linkFile(root);+ const landingAuthority = operation === 'landingLeaseMove' || args?.[0]?.landingFence !== undefined;return locked(file, async () => {const state = loadLink(file);/** Apply through the CLI's existing board handle so local events and guards remain unchanged. */- const applyPausedMoveLocally = () => typeof applyLocally === 'function'- ? applyLocally()- : localRecords(root, (board) => store[operation](board, ...args));+ const applyPausedMoveLocally = () => {+ if (landingAuthority) throw new Refused('LAND_RELAY_REQUIRED', 'a linked landing lease needs an acknowledged relay order; restore the relay connection before landing');+ return typeof applyLocally === 'function' ? applyLocally() : localRecords(root, (board) => store[operation](board, ...args));+ };if (!state && deletedRecovery(root)) return deletedMoveResult(root, operation, args, command, io, applyPausedMoveLocally);if (!state || state.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish unlinking this device with pullboard relay off before sending a move');if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', `finish the saved recovery for sequence ${state.recovery.skip} before sending a linked move`);@@ -1166,7 +1168,10 @@ export async function relayOperation(root, operation, args, io, command, applyLomoves.add(state.board);try {let ordered;- const queue = (error, move) => queueMove(outboxLink(root, file, state, io), { operation, args, command, move, error, applyLocally: applyPausedMoveLocally });+ const queue = (error, move) => {+ if (landingAuthority) throw error;+ return queueMove(outboxLink(root, file, state, io), { operation, args, command, move, error, applyLocally: applyPausedMoveLocally });+ };try { ordered = await ensureOrdered(root, file, state, io); }catch (error) {if (outboxQueueable(state, error, operation, io)) return await queue(error);diff --git a/src/resources.js b/src/resources.jsindex 75f54ac2..804f3e4e 100644--- a/src/resources.js+++ b/src/resources.js@@ -25,6 +25,7 @@ import {withMachineHomeWrite,} from './machine-home.js';import { Refused } from './refused.js';+import { takeLandingResource } from './landing-resource.js';import { gateQueueSettings } from './queue-settings.js';import {ARRIVAL_ORDER,@@ -604,6 +605,7 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr*/export async function takeResource(options) {const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;+ if (scope === 'board' && name === 'landing' && capacity === 1 && options.board && typeof options.write === 'function') return takeLandingResource(options);if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');if (name.startsWith('runner:')) throw new Refused('RESERVED_RUNNER_RESOURCE', 'runner resource rows are managed by the machine gate; request name "gate"');if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');diff --git a/test/landing-lease.test.js b/test/landing-lease.test.jsnew file mode 100644index 00000000..21b4ef24--- /dev/null+++ b/test/landing-lease.test.js@@ -0,0 +1,85 @@+/** Real SQLite admission, expiry, release and replay controls for landing leases [Q1,Q2,Q3,H16]. */+import assert from 'node:assert/strict';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { assertLandingLease, guardLandingWrite, LANDING_LEASE_MS } from '../src/landing-lease.js';+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import { exportBoard, importBoard } from '../src/exchange.js';++/** Create isolated physical databases sharing an initial board and a controllable receipt clock. */+function fixture(t) {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-landing-lease-'));+ let at = Date.parse('2026-10-22T00:00:00.000Z');+ const boards = [0, 1].map(index => store.openBoard(join(dir, `${index}.sqlite`), { now: () => new Date(at) }));+ store.register(boards[0], { lane: 'coordinator', path: '/private-fixture/coordinator' });+ importBoard(boards[1], exportBoard(boards[0]));+ t.after(() => { for (const board of boards) store.closeBoard(board); rmSync(dir, { recursive: true, force: true }); });+ return { boards, advance(ms) { at += ms; }, now() { return new Date(at).toISOString(); } };+}++/** A real command's request identity, without borrowing any live session or queue token. */+function request() {+ return { agentId: 'coordinator', action: 'request', token: randomUUID(), branch: 'refs/heads/main', pid: process.pid };+}++test('landing admission is FIFO and stale releases cannot free a successor [Q1,Q2,Q3]', t => {+ const { boards: [board] } = fixture(t);+ const first = request(); const second = request(); const third = request();+ const acquired = store.landingLeaseMove(board, first);+ assert.equal(acquired.acquired, true);+ assert.equal(store.landingLeaseMove(board, second).position, 1);+ assert.equal(store.landingLeaseMove(board, third).position, 2);+ const fence = { ...first, generation: acquired.generation };+ assert.throws(() => guardLandingWrite(board), error => error.code === 'LAND_LEASE_LOST');+ assert.throws(() => assertLandingLease(board, { ...fence, branch: 'refs/heads/other' }), error => error.code === 'LAND_LEASE_LOST');+ store.landingLeaseMove(board, { ...fence, action: 'release' });+ assert.equal(store.landingLeaseMove(board, third).acquired, false, 'a later poll cannot jump the earlier ticket');+ const next = store.landingLeaseMove(board, second);+ assert.equal(next.acquired, true);+ assert.ok(next.generation > acquired.generation);+ store.landingLeaseMove(board, { ...fence, action: 'release' });+ assert.equal(store.landingLeaseState(board).holder.token, second.token);+ assert.throws(() => store.landingLeaseMove(board, { ...fence, action: 'renew' }), error => error.code === 'LAND_LEASE_LOST');+});++test('a landing lease expires without lending the old holder another grant [Q3]', t => {+ const { boards: [board], advance } = fixture(t);+ const first = request(); const second = request();+ const granted = store.landingLeaseMove(board, first);+ store.landingLeaseMove(board, second);+ advance(LANDING_LEASE_MS - 1000);+ store.landingLeaseMove(board, second); // The live waiter retains its FIFO ticket through the holder's expiry.+ advance(1001);+ const successor = store.landingLeaseMove(board, second);+ assert.equal(successor.acquired, true);+ assert.ok(successor.generation > granted.generation);+ assert.throws(() => assertLandingLease(board, { ...first, generation: granted.generation }), error => error.code === 'LAND_LEASE_LOST');+ assert.throws(() => store.landingLeaseMove(board, { ...first, agentId: 'web-1' }), error => error.code === 'COORDINATOR_ONLY');+});++test('ordered landing admission replays identically and a takeover fences the old invocation [Q1,Q2,H16,E19]', t => {+ const box = fixture(t);+ let sequence = 0;+ /** Replay one exact receipt to both independent replicas, retaining the authenticated coordinator lineage. */+ const move = (operation, options, lineage = 'private-first-lineage') => {+ const prepared = prepareEngineMove(box.boards[0], operation, [options]);+ const position = ++sequence;+ const outcomes = box.boards.map(board => applyEngineMove(board, prepared, { sequence: position, at: box.now(), standing: { root: true, lineage } }));+ assert.deepEqual(outcomes[0], outcomes[1]);+ assert.deepEqual(store.landingLeaseState(box.boards[0]), store.landingLeaseState(box.boards[1]));+ return outcomes[0];+ };+ const first = request(); const second = request();+ const acquired = move('landingLeaseMove', first).result;+ assert.equal(acquired.acquired, true);+ assert.equal(move('landingLeaseMove', second).result.position, 1);+ assert.equal(move('landingLeaseMove', second, 'private-other-lineage').error.code, 'COORDINATOR_HELD');+ assert.equal(move('takeCoordinator', { agentId: 'coordinator', machine: 'private-second-machine' }, 'private-other-lineage').error, undefined);+ const oldFence = { ...first, action: 'renew', generation: acquired.generation };+ assert.equal(move('landingLeaseMove', oldFence).error.code, 'COORDINATOR_HELD');+ assert.throws(() => assertLandingLease(box.boards[0], oldFence), error => error.code === 'LAND_LEASE_LOST');+});