Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(landing): keep heartbeats local and fence foreign holders [Q1,Q3]

Corey Olson250992f7f305
diff --git a/src/commands/land.js b/src/commands/land.js
index 95fd71d9..9ec251be 100644
--- a/src/commands/land.js
+++ b/src/commands/land.js
@@ -1,3 +1,4 @@
+import { syncRelay } from '../relay.js';
/** The pullboard land command, in its own module so an item adding another command never edits these lines. */
import * as store from '../board.js';
import {
@@ -43,7 +44,7 @@ export async function run(io, { first, second, rest, values }) {
}
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,
- write: (operation, parameters) => ordered(ctx, board, operation, parameters), say: io.say, owner: agentSessionDigest() ?? `pid-${process.pid}`,
+ write: (operation, parameters) => ordered(ctx, board, operation, parameters), refresh: () => syncRelay(ctx.info.root, io), 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);
for (const blocked of result.blocked ?? []) if (blocked.code === 'STALE_VERDICT') io.say(staleVerdictRefusal({ item_id: blocked.id }, blocked).message);
diff --git a/src/engine.js b/src/engine.js
index be957778..67f853d0 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -69,6 +69,7 @@ import { requireCoordinatorHold } from './coordinator-hold.js';
import { LANDING_ENVIRONMENT_ENGINE } from './landing-environment-engine.js';
import { carriesLandingEnvironment } from './execution-environment.js';
import { LANDING_LEASE_ENGINE } from './landing-lease-engine.js';
+import { LANDING_LOCAL_LEASE_ENGINE } from './landing-local-lease-engine.js';
const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);
@@ -98,6 +99,7 @@ function minimumOperationEngine(operation, args, board, at) {
const id = operation === 'recordLandingBatch' ? args[0]?.batch?.id : args[0]?.id;
if (store.landingBatches(board).some(batch => batch.id === id && carriesLandingEnvironment(batch))) return LANDING_ENVIRONMENT_ENGINE;
}
+ if (operation === 'landingLeaseMove' && args[0]?.localHeartbeat === true) return LANDING_LOCAL_LEASE_ENGINE;
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;
diff --git a/src/exchange.js b/src/exchange.js
index b65a7c0c..99742957 100644
--- a/src/exchange.js
+++ b/src/exchange.js
@@ -1,3 +1,4 @@
+import { LANDING_LOCAL_PREFIX } from './landing-local-lease.js';
import { PROOF_COUNTER_PREFIX } from './proof-counters.js';
import { rebuildProofCounters } from './proof-counters.js';
/**
@@ -47,8 +48,8 @@ function columnsOf(db, table) {
/** Read native rows without fetching large local proof projections into an export or digest. */
function nativeRows(db, table) {
- if (table === 'board_meta') return db.prepare('SELECT * FROM board_meta WHERE meta_key < ? OR meta_key >= ? ORDER BY rowid')
- .all(PROOF_COUNTER_PREFIX, 'local:proof-stats;');
+ if (table === 'board_meta') return db.prepare('SELECT * FROM board_meta WHERE (meta_key < ? OR meta_key >= ?) AND meta_key NOT GLOB ? ORDER BY rowid')
+ .all(PROOF_COUNTER_PREFIX, 'local:proof-stats;', LANDING_LOCAL_PREFIX + '*');
return db.prepare(`SELECT * FROM ${identifier(table)} ORDER BY ${table === 'sqlite_sequence' ? 'name' : 'rowid'}`).all();
}
@@ -81,7 +82,7 @@ export function semanticBoardDigest(document) {
...document,
tables: {
...tables,
- ...(Array.isArray(tables.board_meta) ? { board_meta: tables.board_meta.filter(row => !row.meta_key.startsWith(PROOF_COUNTER_PREFIX)) } : {}),
+ ...(Array.isArray(tables.board_meta) ? { board_meta: tables.board_meta.filter(row => !row.meta_key.startsWith(PROOF_COUNTER_PREFIX) && !row.meta_key.startsWith(LANDING_LOCAL_PREFIX)) } : {}),
agent: tables.agent.map(({ agent_last_shout_id, ...row }) => row),
},
};
@@ -222,6 +223,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigest
validateDocument(db, document, names);
db.exec('PRAGMA defer_foreign_keys = ON; BEGIN IMMEDIATE');
try {
+ const localLanding = db.prepare('SELECT * FROM board_meta WHERE meta_key GLOB ?').all(LANDING_LOCAL_PREFIX + '*');
let localAgentCursors = null;
if (expectedNativeDigest !== null) {
const current = { version: VERSION, tables: Object.fromEntries(names.map((table) => [
@@ -251,7 +253,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigest
const sql = `INSERT INTO ${identifier(table)} (${columns.map(identifier).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
const insert = db.prepare(sql);
for (const row of document.tables[table]) {
- if (table === 'board_meta' && row.meta_key.startsWith(PROOF_COUNTER_PREFIX)) continue;
+ if (table === 'board_meta' && (row.meta_key.startsWith(PROOF_COUNTER_PREFIX) || row.meta_key.startsWith(LANDING_LOCAL_PREFIX))) continue;
let restored = row;
if (replace && expectedNativeDigest !== null && table === 'agent' && localAgentCursors.has(row.agent_id)) {
const localCursor = localAgentCursors.get(row.agent_id);
@@ -267,6 +269,8 @@ function restoreDocument(board, document, replace = false, expectedNativeDigest
for (const row of document.tables.sqlite_sequence ?? []) {
if (!setSequence.run(row.seq, row.name).changes) db.prepare('INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)').run(row.name, row.seq);
}
+ const restoreLocal = db.prepare('INSERT OR REPLACE INTO board_meta(meta_key,meta_value) VALUES (?,?)');
+ for (const row of localLanding) restoreLocal.run(row.meta_key, row.meta_value);
rebuildProofCounters(board);
for (const { name, sql } of storeTriggers()) db.exec(sql);
db.exec('COMMIT');
diff --git a/src/land.js b/src/land.js
index 6cb1fa18..6b073cae 100644
--- a/src/land.js
+++ b/src/land.js
@@ -876,11 +876,13 @@ export async function land(options) {
}
let lastWait = '';
const controller = new AbortController();
- const lease = await takeLandingResource({ board: options.board, write: options.write, branch,
+ const lease = await takeLandingResource({ board: options.board, write: options.write, refresh: options.refresh, branch,
onLost: error => controller.abort(error),
/** 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}`;
+ const holder = holders[0];
+ const elapsed = holder ? Math.max(0, Math.floor((options.board.clock.now().getTime() - Date.parse(holder.since)) / 1000)) : 0;
+ const message = `landing waiting: ${branch} held by ${holder?.label ?? 'the previous landing'} on ${holder?.machine ?? (holder?.lineage ? 'the recorded coordinator machine (legacy identity)' : 'this machine')} for ${elapsed}s; queued at place ${position}; foreign holders require explicit release or pullboard takeover`;
if (message !== lastWait) options.say(message);
lastWait = message;
} });
diff --git a/src/landing-lease.js b/src/landing-lease.js
index 80b5e78a..aa198dde 100644
--- a/src/landing-lease.js
+++ b/src/landing-lease.js
@@ -6,12 +6,15 @@ import {
import { COORDINATOR } from './config.js';
import { coordinatorHolder } from './coordinator-hold.js';
import { Refused } from './refused.js';
+import { ENGINE_VERSION } from './machine.js';
+import { LANDING_LOCAL_LEASE_ENGINE } from './landing-local-lease-engine.js';
+import { localLandingEntry, rememberLocalLanding } from './landing-local-lease.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) {
+function sharedLandingLeaseState(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 {
@@ -24,6 +27,29 @@ export function landingLeaseState(board) {
} catch { throw new Refused('LAND_LEASE_CORRUPT', 'the landing queue is unreadable; restore the board from a consistent export before landing'); }
}
+/** Overlay only physical-board heartbeats; shared replay always reads the unmodified queue. */
+export function landingLeaseState(board) {
+ const state = sharedLandingLeaseState(board);
+ const local = entry => entry && { ...entry, until: localLandingEntry(board, entry)?.until ?? entry.until };
+ return { ...state, holder: local(state.holder), line: state.line.map(local) };
+}
+
+/** Renew an acknowledged invocation locally; this function never calls a relay or creates a grant. */
+export function renewLocalLanding(board, fence) {
+ return atomic(board, () => {
+ const holder = assertLandingLease(board, fence);
+ if (!localLandingEntry(board, holder)) throw new Refused('LAND_LEASE_LOST', 'this invocation has no acknowledged local landing grant; run pullboard land again');
+ const renewed = { ...holder, until: new Date(board.clock.now().getTime() + LANDING_LEASE_MS).toISOString() };
+ rememberLocalLanding(board, renewed);
+ if (holder.lineage === null) {
+ const state = sharedLandingLeaseState(board);
+ state.holder = renewed;
+ save(board, state, 'renew', holder.token, false);
+ }
+ return renewed;
+ });
+}
+
/** 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
@@ -35,12 +61,15 @@ function validEntry(entry) {
}
/** A fence must still identify the current, unexpired holder under the current coordinator. */
-export function assertLandingLease(board, fence) {
+export function assertLandingLease(board, fence, { shared = false } = {}) {
requireConfirmedLanding(board);
- const holder = landingLeaseState(board).holder;
+ const holder = (shared ? sharedLandingLeaseState(board) : landingLeaseState(board)).holder;
const lineage = coordinatorHolder(board)?.lineage ?? null;
+ const heartbeat = !shared && localLandingEntry(board, holder);
+ const legacyShared = shared && (board.executionEngineVersion ?? ENGINE_VERSION) < LANDING_LOCAL_LEASE_ENGINE;
+ const deadline = heartbeat?.until ?? holder?.until;
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) {
+ || ((holder.lineage === null || heartbeat || legacyShared) && Date.parse(deadline) <= 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;
@@ -59,10 +88,10 @@ export function guardLandingWrite(board, fence) {
}
/** Persist a complete queue transition and a compact, append-only admission receipt. */
-function save(board, state, action, token) {
+function save(board, state, action, token, event = true) {
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 });
+ if (event) 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. */
@@ -72,26 +101,32 @@ export function landingLeaseMove(board, { agentId, action, token, branch, pid, g
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 state = sharedLandingLeaseState(board);
+ const modern = (board.executionEngineVersion ?? ENGINE_VERSION) >= LANDING_LOCAL_LEASE_ENGINE;
+ const transition = value => JSON.stringify([value.generation, value.holder?.token ?? null, value.line.map(entry => entry.token)]);
+ const previousTransition = transition(state);
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' || action === 'bind') {
- const holder = assertLandingLease(board, { token, branch, generation });
+ const holder = assertLandingLease(board, { token, branch, generation }, { shared: true });
if (action === 'bind' && (!Number.isSafeInteger(guardianPid) || guardianPid < 1 || holder.guardianPid && holder.guardianPid !== guardianPid)) {
throw new Refused('LAND_LEASE_REQUEST', 'this landing already names its owned guardian; start a new pullboard land command');
}
state.holder = { ...holder, ...(action === 'bind' ? { guardianPid } : {}), 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 lineage = coordinatorHolder(board)?.lineage ?? null;
+ const expired = entry => modern && entry.lineage !== null
+ ? entry.lineage !== lineage : Date.parse(entry.until) <= at.getTime();
+ if (state.holder && expired(state.holder)) state.holder = null;
+ state.line = state.line.filter(entry => !expired(entry));
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, ...(old?.guardianPid ? { guardianPid: old.guardianPid } : {}),
+ lineage: holder?.lineage ?? null, ...(modern ? { machine: holder?.machine ?? null } : {}), ...(old?.guardianPid ? { guardianPid: old.guardianPid } : {}),
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)) {
@@ -105,7 +140,7 @@ export function landingLeaseMove(board, { agentId, action, token, branch, pid, g
state.holder = { ...state.line.shift(), generation: state.generation };
}
}
- if (JSON.stringify(state) !== before) save(board, state, action, token);
+ if (JSON.stringify(state) !== before) save(board, state, action, token, !modern || transition(state) !== previousTransition);
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-local-lease-engine.js b/src/landing-local-lease-engine.js
new file mode 100644
index 00000000..9c9d892f
--- /dev/null
+++ b/src/landing-local-lease-engine.js
@@ -0,0 +1,2 @@
+import { unassignedEngine } from './engine-next.js';
+export const LANDING_LOCAL_LEASE_ENGINE = unassignedEngine();
diff --git a/src/landing-local-lease.js b/src/landing-local-lease.js
new file mode 100644
index 00000000..d96b75a5
--- /dev/null
+++ b/src/landing-local-lease.js
@@ -0,0 +1,25 @@
+/** Physical-board heartbeat state never crosses a relay or export boundary [Q1,Q3,H16]. */
+export const LANDING_LOCAL_PREFIX = 'local:landing-lease:';
+
+/** Read only an exact invocation's local observation; malformed local state grants no authority. */
+export function localLandingEntry(board, entry) {
+ if (!entry) return null;
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(LANDING_LOCAL_PREFIX + entry.token);
+ try {
+ const value = row && JSON.parse(row.meta_value);
+ return value && value.branch === entry.branch && value.pid === entry.pid && value.lineage === entry.lineage
+ && value.generation === (entry.generation ?? null) && Number.isFinite(Date.parse(value.until)) ? value : null;
+ } catch { return null; }
+}
+
+/** Mark only a successfully acknowledged local request, then extend that invocation's local deadline. */
+export function rememberLocalLanding(board, entry) {
+ 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(LANDING_LOCAL_PREFIX + entry.token, JSON.stringify({ branch: entry.branch, pid: entry.pid, lineage: entry.lineage,
+ generation: entry.generation ?? null, until: entry.until }));
+}
+
+/** Forget a completed local invocation without changing shared native history. */
+export function forgetLocalLanding(board, token) {
+ board.db.prepare('DELETE FROM board_meta WHERE meta_key=?').run(LANDING_LOCAL_PREFIX + token);
+}
diff --git a/src/landing-resource.js b/src/landing-resource.js
index 31060c8e..5f09852b 100644
--- a/src/landing-resource.js
+++ b/src/landing-resource.js
@@ -4,12 +4,15 @@ import { setTimeout as pause } from 'node:timers/promises';
import {
assertLandingLease,
landingLeaseState,
+ renewLocalLanding,
} from './landing-lease.js';
import { Refused } from './refused.js';
+import { coordinatorHolder } from './coordinator-hold.js';
+import { localLandingEntry, rememberLocalLanding, forgetLocalLanding } from './landing-local-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;
+function deadLocalOwner(holder, local) {
+ if (!holder || holder.lineage !== null && !local) return false;
try { process.kill(holder.pid, 0); return false; }
catch (error) {
if (error.code !== 'ESRCH') return false;
@@ -22,9 +25,9 @@ function deadLocalOwner(holder) {
}
/** Return a generation-bound lease whose renewal failures prevent later landing writes. */
-export async function takeLandingResource({ board, write, branch, onWait, onLost }) {
+export async function takeLandingResource({ board, write, branch, onWait, onLost, refresh = async () => {} }) {
const token = randomUUID();
- const parameters = { agentId: 'coordinator', token, branch, pid: process.pid };
+ const parameters = { agentId: 'coordinator', token, branch, pid: process.pid, localHeartbeat: true };
let generation = null;
let timer;
let watchdog;
@@ -42,7 +45,7 @@ export async function takeLandingResource({ board, write, branch, onWait, onLost
const task = pending.then(async () => {
if (lost) throw lost;
try {
- const result = await write('landingLeaseMove', [{ ...parameters, action: 'renew', generation }]);
+ const result = renewLocalLanding(board, { ...parameters, generation });
if (lost) throw lost;
const holder = assertLandingLease(board, { token, branch, generation }); // A delayed recovered receipt is not a fresh grant.
confirmedUntil(holder.until);
@@ -54,10 +57,31 @@ export async function takeLandingResource({ board, write, branch, onWait, onLost
return task;
};
try {
+ let queued = false;
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 (queued) await refresh();
+ const state = landingLeaseState(board);
+ const holder = state.holder;
+ const local = localLandingEntry(board, holder);
+ if (deadLocalOwner(holder, local) || local && Date.parse(local.until) <= board.clock.now().getTime()) {
+ await write('landingLeaseMove', [{ agentId: 'coordinator', action: 'release', token: holder.token, generation: holder.generation }]);
+ }
+ let result;
+ const current = landingLeaseState(board);
+ const entry = current.line.find(value => value.token === token);
+ if (queued && current.holder && entry && current.holder.lineage === (coordinatorHolder(board)?.lineage ?? null)) {
+ if (current.holder.lineage === null) {
+ // An unlinked board has one physical authority; refresh the existing ticket without a relay.
+ const { landingLeaseMove } = await import('./landing-lease.js');
+ result = landingLeaseMove(board, { ...parameters, action: 'request' });
+ } else result = { holder: current.holder, position: current.line.indexOf(entry) + 1, acquired: false, generation: null };
+ rememberLocalLanding(board, { ...entry, until: new Date(board.clock.now().getTime() + 30_000).toISOString() });
+ } else {
+ result = await write('landingLeaseMove', [{ ...parameters, action: 'request' }]);
+ const acknowledged = result.acquired ? result.holder : landingLeaseState(board).line.find(value => value.token === token);
+ if (acknowledged) rememberLocalLanding(board, acknowledged);
+ queued = !result.acquired;
+ }
if (result.acquired) { generation = result.generation; confirmedUntil(result.holder.until); break; }
await onWait?.({ holders: result.holder ? [result.holder] : [], position: result.position });
await pause(1000);
@@ -90,6 +114,7 @@ export async function takeLandingResource({ board, write, branch, onWait, onLost
clearInterval(watchdog);
await pending;
await write('landingLeaseMove', [{ ...parameters, action: 'release', generation }]);
+ forgetLocalLanding(board, token);
} };
} catch (error) {
clearInterval(timer);
diff --git a/test/landing-local-lease.test.js b/test/landing-local-lease.test.js
new file mode 100644
index 00000000..9b8de8e1
--- /dev/null
+++ b/test/landing-local-lease.test.js
@@ -0,0 +1,81 @@
+/** Local heartbeat and foreign shared fencing use independent physical SQLite replicas [Q1,Q3,H16,E19]. */
+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 { applyEngineMove, prepareEngineMove } from '../src/engine.js';
+import { exportBoard, importBoard, semanticBoardDigest } from '../src/exchange.js';
+import { assertLandingLease } from '../src/landing-lease.js';
+import { LANDING_LOCAL_PREFIX } from '../src/landing-local-lease.js';
+import { takeLandingResource } from '../src/landing-resource.js';
+
+/** Give each test two physical boards and a private receipt clock, never a live coordinator credential. */
+function fixture(t) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-local-heartbeat-'));
+ let at = Date.parse('2026-01-01T00:00:00Z');
+ const boards = [0, 1].map(index => store.openBoard(join(dir, `${index}.sqlite`), { now: () => new Date(at) }));
+ store.register(boards[0], { lane: 'coordinator', path: dir });
+ let sequence = 0;
+ /** Apply a real ordered private engine receipt with the declared coordinator machine. */
+ const move = (board, operation, args, lineage = 'private-lineage-a', machine = 'private-machine-a') => {
+ const prepared = { ...prepareEngineMove(board, operation, args), holder: machine };
+ const result = applyEngineMove(board, prepared, { sequence: ++sequence, at: new Date(at).toISOString(), standing: { root: true, lineage } });
+ assert.equal(result.error, undefined, JSON.stringify(result.error));
+ return result.result;
+ };
+ t.after(() => { for (const board of boards) store.closeBoard(board); rmSync(dir, { recursive: true, force: true }); });
+ return { boards, move, advance(ms) { at += ms; } };
+}
+
+/** Drain promise continuations after advancing only this test's heartbeat intervals. */
+async function settle() { for (let turn = 0; turn < 12; turn += 1) await Promise.resolve(); }
+
+test('a relay stalled for 120 seconds cannot block the holder local landing heartbeat [Q1,Q3,H16]', async t => {
+ const box = fixture(t); const [board, replica] = box.boards;
+ t.mock.timers.enable({ apis: ['setInterval', 'Date'], now: Date.parse('2026-01-01T00:00:00Z') });
+ const actions = [];
+ const lease = await takeLandingResource({ board, branch: 'refs/heads/main',
+ write: async (operation, args) => {
+ actions.push(args[0].action);
+ if (args[0].action === 'renew') return new Promise(() => {}); // stand-in relay never acknowledges renewal.
+ return box.move(board, operation, args);
+ } });
+ try {
+ const shared = exportBoard(board);
+ const digest = semanticBoardDigest(shared);
+ for (let step = 0; step < 24; step += 1) {
+ box.advance(5000); t.mock.timers.tick(5000); await settle();
+ }
+ await lease.assertHeld();
+ assert.deepEqual(actions, ['request'], '120 seconds of heartbeats never invoked the stalled relay writer');
+ assert.equal(semanticBoardDigest(exportBoard(board)), digest, 'local deadlines do not change shared semantic state');
+ assert.ok(Date.parse(lease.assertCurrent().until) > board.clock.now().getTime());
+ assert.equal(shared.tables.board_meta.some(row => row.meta_key.startsWith(LANDING_LOCAL_PREFIX)), false);
+ importBoard(replica, shared);
+ assert.equal(replica.db.prepare('SELECT count(*) AS n FROM board_meta WHERE meta_key GLOB ?').get(LANDING_LOCAL_PREFIX + '*').n, 0);
+ importBoard(board, shared, true);
+ assertLandingLease(board, lease.fence); // checkpoint replacement retains only this physical board's local heartbeat.
+ const foreign = { agentId: 'coordinator', action: 'request', token: randomUUID(), branch: 'refs/heads/main', pid: process.pid };
+ assert.equal(store.landingLeaseMove(replica, foreign).acquired, false, 'a replica cannot grant past unseen local renewals using its expired shared clock');
+ store.landingLeaseMove(replica, { agentId: 'coordinator', action: 'release', ...lease.fence });
+ assert.equal(store.landingLeaseMove(replica, foreign).acquired, true, 'explicit release admits the foreign waiter');
+ } finally { await lease.release(); }
+});
+
+test('coordinator takeover fences an unreleased foreign landing without inventing a new expiry [Q1,Q3,E19]', t => {
+ const box = fixture(t); const [board, replica] = box.boards;
+ const first = { agentId: 'coordinator', action: 'request', token: randomUUID(), branch: 'refs/heads/main', pid: process.pid };
+ const grant = box.move(board, 'landingLeaseMove', [first]);
+ importBoard(replica, exportBoard(board));
+ box.advance(120_000);
+ const second = { ...first, token: randomUUID() };
+ assert.equal(store.landingLeaseMove(replica, second).acquired, false);
+ box.move(replica, 'takeCoordinator', [{ agentId: 'coordinator', machine: 'private-machine-b' }], 'private-lineage-b', 'private-machine-b');
+ assert.throws(() => assertLandingLease(replica, { ...first, generation: grant.generation }), error => error.code === 'LAND_LEASE_LOST');
+ const successor = box.move(replica, 'landingLeaseMove', [second], 'private-lineage-b', 'private-machine-b');
+ assert.equal(successor.acquired, true);
+ assert.ok(successor.generation > grant.generation);
+});