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
fix(relay): recover blocked positions in order [H16,H3]
Corey Olson419e92fecfa0
diff --cc docs/api.mdindex 4f866e40,daa7eff2..d7654858--- a/docs/api.md+++ b/docs/api.md@@@ -139,10 -149,22 +149,22 @@@ Only the coordinator sets or edits an i| `error` | `code:string`, `message:string`, `next:string` |<!-- api-refusal-shapes:end -->-`relay on`, `relay`, and `relay off` share the relay result shape. `status` adds a `relay` object with the current sequence and pending upload count. Successful results may include `diagnostics` for a relay refusal or inactivity notice; a local move still succeeds when its upload must wait. Device sign-in instructions are written immediately to stderr, including with `--json`, so the person can sign in before the command returns.+`relay on`, `relay`, and `relay off` share the relay result shape. Successful `pullboard relay recover --skip N` returns that same shape with optional `skipped: N` naming the explicitly refused sequence and `adopted: true` when it adopts a different authenticated person checkpoint that proves the same blocked refusal. Every relay result includes `recovery: { pending, skip, next }`; when a saved recovery is pending, `next` is the exact retry command. The `behind` count remains the number of pending uploads and does not include recovery. `status` includes this relay object alongside the local board summary. Human status and relay output show the recovery sequence and retry command when one is saved. The local `agent_last_shout_id` inbox read cursor is metadata: recovery ignores only that field in its guarded digest and preserves the greater valid cursor for matching agents. Other native changes remain protected; if a semantic local write changes while recovery is pending, the CLI preserves it and refuses automatic restoration. Exporting alone does not unblock that conflict; this prototype has no merge or discard command, so the person must reconcile the export and remote checkpoint before continuing. Successful results may include `diagnostics` for a relay refusal or inactivity notice; a local move still succeeds when its upload must wait. Device sign-in instructions are written immediately to stderr, including with `--json`, so the person can sign in before the command returns.+ `relay on --all [--url <address>]` returns `{version, linked: [{project, root, board}], failed: [{project, root, reason}], paired, autoLink: true}`. Its status is nonzero when a project failed; successful links remain available. With no paired phone, the command prints one tappable pairing link and QR, then waits in the foreground up to ten minutes. Interruption or expiration leaves completed links intact and exits zero when no link failed. Every explicit invocation signs in afresh; no person session is retained on the Mac. Later project registrations publish one sealed phone-link proposal and keep working locally until its single approval tap. `doctor` and `resume` name the waiting project and its expiry; expiration requires an explicit fresh sign-in rather than silently asking again. `relay off` excludes that project from automatic linking; explicit `relay on` clears the exclusion.++ `relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation waits for one tap on the paired phone and uses a short-lived, single-use, RAM-only grant for that exact device. A failed or interrupted approval needs an explicit retry. Revocation stops future wrapping; it cannot erase board keys already received.++ Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.++ `POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.++ A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. A refused foreground approval fails immediately with the original refusal code and reason plus its request id. A refused remote approval makes local unlinking or registration exit nonzero while retaining the completed local work: one line names that completion, the refusal code and reason, the request id and the next action. The JSON result preserves the local outcome and includes `remote: {code, reason, requestId}`. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.+The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.+ When `verify <id> accept` runs a frozen check and refuses with `CHECK_RED` or `CHECK_UNVERIFIED`, `error.message` includes its output digest, up to 40 sanitized tail lines, and `full output file: <path>`. The file is written with owner-only permissions. If diagnostic storage fails, the message says `full output file: (unavailable: CODE)` while retaining the bounded sanitized lines; the JSON error object remains `{ code, message, next }`. An item with no frozen check produces no check-output section.+## Local HTTP API v1Run `pullboard serve --port 0` to print a private API address on `127.0.0.1`. Authenticate each call with the address's `k` query parameter, an `X-Pullboard-Key` header, or `Authorization: Bearer <key>`. The secret belongs to that server session. Board ids are random 128-bit values stored in each board; reopening or moving a repo preserves its id.diff --cc docs/formats.mdindex 415223e2,c3a29297..272fa57b--- a/docs/formats.md+++ b/docs/formats.md@@@ -72,10 -76,10 +76,10 @@@ The board file is in the repository's G| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. || `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. || `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |- | `move engine` | `3` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |-| `move engine` | `7` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |++| `move engine` | `8` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |<!-- format-versions:end -->- Pullboard 0.6.1 released engine 1. The first change to released move semantics raises the engine once for the next release; later changes developed before that release keep the same version. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Older clients refuse engine-2 moves before changing rows or replay cursors; engine 2 still accepts engine-1 moves.-Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Pullboard 0.8.3 released engine 6, adding board-scoped machine credentials and permitting machine execution only for one exact, earlier authenticated phone request, including its payload digest. Engine 7 adds ordered item holds through `holdItem` and `releaseItemHold`; engine-6 clients stop with `ENGINE_VERSION` before interpreting either operation or advancing their replay cursor. Older request receipts retain their recorded engine semantics. Upgrade every linked device before using the new moves.++Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Pullboard 0.8.3 released engine 6, adding board-scoped machine credentials and permitting machine execution only for one exact, earlier authenticated phone request, including its payload digest. Engine 7 adds ordered item holds through `holdItem` and `releaseItemHold`; engine-6 clients stop with `ENGINE_VERSION` before interpreting either operation or advancing their replay cursor. Older request receipts retain their recorded engine semantics. Engine 8 adds durable refusal recovery for blocked relay positions; each explicit skip publishes the readable prefix even when another unsupported record follows. Upgrade every linked device before using the new moves.The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.A linked board requires at least engine 3 after issuing any agent token, including@@@ -95,12 -99,16 +99,22 @@@ Linked clients seal an executable operaA sealed checkpoint keeps the native export tables importable and may carry the local API presentation beside them. Its public sequence equals `relay_applied_sequence`, so clients can restore a compacted prefix and continue after it. The older local-first mirror drains only its already-durable outbox, then publishes a checkpoint covering the acknowledged prefix without executing those events again. A divergent old outbox is refused with the relay and local sequences; re-link from that machine or join by pairing.- For ordered sealed relays, ordinary `pullboard relay` stops at an unsupported future move-engine or seal-envelope version. It leaves the blocked sequence and native board unchanged so an upgraded client can replay it. A person in the main checkout may explicitly run `pullboard relay recover --skip N` for the exact blocked next sequence. Recovery refuses a record this version can replay; it records a deterministic refusal for only the selected unsupported or malformed record, replays the readable tail, then publishes an authenticated checkpoint. It never automatically skips a future version. Agent shells cannot use this command.++For ordered sealed relays, ordinary `pullboard relay` stops at an unsupported future move-engine or seal-envelope version. It leaves the blocked sequence and native board unchanged so an upgraded client can replay it. A person in the main checkout may explicitly run `pullboard relay recover --skip N` for the exact blocked next sequence. Recovery refuses a record this version can replay; it records a deterministic refusal for only the selected unsupported or malformed record, replays the readable tail up to the next unsupported record, then publishes an authenticated checkpoint. A later unsupported record cannot undo the selected refusal; it needs its own explicit recovery choice. It never automatically skips a future version. Agent shells cannot use this command.++If another person device has already published a different checkpoint for the same pending recovery, a retry adopts it only when its authenticated sender, supported engine, board identity, covered sequence, and durable refusal receipt for the selected blocker all validate. A concurrent local write prevents adoption; the CLI preserves it and reports that the local export and remote checkpoint need person-led reconciliation. Exporting alone does not clear the saved recovery, and this prototype has no command to merge or discard that conflict.++Recovery stages the replacement before publication and saves the exact sealed checkpoint candidate locally. A known publication failure leaves the native board untouched and keeps that candidate for retry; a lost acknowledgement retries the same ciphertext. Before restoring an acknowledged checkpoint, Pullboard compares semantic native state with the saved digest inside SQLite's write transaction. The local `agent_last_shout_id` inbox read cursor is metadata rather than a semantic write: the check ignores only that field, and recovery preserves the greater valid cursor for each agent present on both boards. Every other native row and field remains guarded; a concurrent semantic write is preserved and recovery refuses with `RELAY_LOCAL_CHANGED`. Ordinary relay sync also refuses while a recovery checkpoint is pending.++ Machine relay setup lives outside repositories in `$PULLBOARD_HOME/relay-machine/state.json` (default `~/.pullboard/relay-machine/state.json`), format `v: 2`. The directory is mode 700; state and the SQLite serialization lock are mode 600. State retains the auto-link setting, account and relay origin, stable machine id, excluded project roots, device roster, one pending ten-minute enrollment, pending remote revocations and non-person board-link proposals. Person sessions never persist on the Mac: old machine sessions, Git-directory sessions and retired per-board session files are scrubbed before use. Each linked board keeps a `pm_` credential bound to that board and machine; it can mint `pa_` agent credentials only for that board. `pa_` credentials cannot mint credentials. Explicit `relay on --all` always signs in afresh and preserves the paired phone key. Each roster entry contains `deviceId`, public P-256 JWK, SHA-256 fingerprint, label, creation timestamp, account and relay origin. No device private key is stored on the Mac. The phone retains its non-extractable ECDH P-256 private CryptoKey in IndexedDB database `pullboard-relay-device-v1`, store `keys`, key `device`.++ Enrollment HMAC-SHA256 uses an HKDF-SHA256 key derived from the QR-only 32-byte secret, locator-byte salt and UTF-8 JSON info `["pullboard-device-auth",1,account,locator]`. The authenticated enrollment is UTF-8 JSON `["pullboard-device-enroll",1,account,locator,deviceId,{kty,crv,x,y},label,createdAt]`. The Mac consumes its local secret atomically after checking the MAC; relay-supplied public keys are never used as wrapping recipients.++ Device wraps are `{v:1,board,device,engine,ephemeral,nonce,ciphertext}`. `ephemeral` is a fresh public P-256 JWK; `nonce` is 12 bytes and `ciphertext` is the 32-byte board key plus its 16-byte AES-GCM tag, both canonical base64url. ECDH yields HKDF-SHA256 input, the raw 65-byte ephemeral public point is salt, and UTF-8 JSON `["pullboard-wrap-v1",board,device]` is info. AES-256-GCM AAD is UTF-8 JSON `["pullboard-device-wrap",1,board,device,engine]`. The relay's private `devices.sqlite` stores only account/device identifiers, opaque wraps, expiring public enrollment transports and durable revocation tombstones. Unlink removes board grants; a device revocation atomically deletes all its grants and blocks stale uploads.++ Phone approval contexts contain exactly `id,account,publisher,board,device,action,target,machine,command,expires`. New-board link requests have one visible ten-minute proposal and may retain a private reply JWK because their reply grants only board-scoped machine power. Native revocation reply keys are non-extractable and RAM-only. One phone tap returns a `pg_` grant, limited to two minutes and bound to the entire immutable context; the relay retains only its hash and consumes it atomically before executing the exact action. Agent shells refuse native person actions before network access. `relay off` always removes the local link without a tap, including offline and in agent shells; the remote copy remains until a separate explicit phone deletion approval.++ Approval intents and replies use separate ECDH/HKDF-SHA256/AES-256-GCM domains. HKDF salt is UTF-8 JSON of the ephemeral public P-256 JWK; info is UTF-8 JSON `["pullboard-phone-approval-v1",direction,context]`. AES-GCM AAD is UTF-8 JSON `["pullboard-phone-approval",1,direction,context]`. The publishing board key authenticates the sealed intent with HMAC-SHA256 over UTF-8 JSON `["pullboard-phone-intent-v1",envelope]` before the phone displays an approval. Opaque encrypted replies never expose a native grant to durable storage. Journal format 3 permits machine sender attribution, upgrading format-2 CHECK constraints atomically while preserving history, snapshots and sequence heads.+The in-place upgrade behavior is exercised by `exerciseUpgrade` in `docs/formats.test.js`:<!-- upgrade-rules:start -->diff --cc src/cli.jsindex 0045285a,4d9de0fb..f22bdcbe--- a/src/cli.js+++ b/src/cli.js@@@ -62,8 -67,12 +67,12 @@@ import { proofStats } from './stats.js'import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';- import { relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayStatus, syncRelay } from './relay.js';-import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';++import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';+ import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';+ 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';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));export const VERSION = PACKAGE.version;@@@ -85,9 -134,15 +134,16 @@@ Set upullboard view --export <dir> a read-only snapshot with event replay, for any static hostpullboard serve [--port N] local API v1: boards, state, moves, requests and live events,behind the session secret in its printed address- pullboard relay [on|off] [--url <address>] link, inspect or unlink this board's sealed relay mirror+ pullboard relay [on|off|pair|join <code>] [--url <address>] link, inspect or unlink this board's sealed relay+ pullboard relay recover --skip <sequence> person-only recovery of one blocked next relay positionon signs in through GitHub; the address defaults to https://app.pullboard.dev+ pair prints a one-use machine code; join stores it in another clone+ pullboard relay on --all [--url <address>] link every registered project after one sign-in; pair the phone once+ keep this command open until pairing finishes; later projects link on registration+ pullboard relay devices list paired device ids and their public-key fingerprints+ pullboard relay revoke <device> stop future key delivery; already received keys remain known+ pullboard relay tokens list this board's agent token ids, agents and expiry, never credentials+ pullboard relay revoke <token-id> revoke one token from that list; other agents keep workingpullboard resume where you are: your claim, branch, uncommitted work, what came back,unread shouts, what to do next; run it to start any sessionpullboard hooks reinstall the git hooks (e.g. after a fresh clone)@@@ -181,8 -239,8 +240,8 @@@ Reject reasons: TEST_FAILURE, BEHAVIOR_--json prints one versioned document for every command; refusals include their code and next step.`;const HELP_NAMES = [- 'tour', 'init', 'worktree', 'join', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',+ 'tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',- 'serve', 'relay', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'show', 'next',+ 'serve', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'show', 'next','check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import','sweep', 'merged', 'withdraw', 'refreeze', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view','spec show', 'spec unmet', 'spec signoff', 'spec signers', 'spec signers add', 'forget', 'prompt', 'gate', 'hook',@@@ -1327,7 -1603,8 +1605,8 @@@ function readCommands(io, { first, secoio.result(summary);return 0;}- if (summary.relay.linked) io.say(`relay: sequence ${summary.relay.sequence}; ${summary.relay.behind} pending uploads${summary.relay.recovery.pending ? `; recovery pending for sequence ${summary.relay.recovery.skip}; retry ${summary.relay.recovery.next}` : ''}`);- if (summary.relay.linked) io.say(`relay: sequence ${summary.relay.sequence}; ${summary.relay.behind} pending uploads`);++ if (summary.relay.linked) io.say(`relay: sequence ${summary.relay.sequence}; ${summary.relay.behind} pending uploads${summary.relay.recovery?.pending ? `; recovery pending for sequence ${summary.relay.recovery.skip}; retry ${summary.relay.recovery.next}` : ''}`);+ if (summary.relay.oversizedSnapshot && !summary.relay.refusedCheckpoint) io.say(formatSnapshotLimit(summary.relay.oversizedSnapshot));const { items, accepted, rejected } = summary.stats;io.say(`${summary.me.id}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);@@@ -2396,24 -2772,54 +2774,65 @@@ async function runCommand(argv, io)if (command === 'hook') return await hookCommand(io, args);if (command === 'settings') return settingsCommand(io, args);if (command === 'relay') {+ if (first === 'recover') {- if (second || rest.length || !values.skip || values.url) throw new Refused('USAGE', 'pullboard relay recover --skip <exact blocked next sequence>');++ if (second || rest.length || !values.skip || values.url || values.all) throw new Refused('USAGE', 'pullboard relay recover --skip <exact blocked next sequence>');+ requirePersonChannel('terminal');+ const result = await relayRecover(context(io).info.root, Number(values.skip), io);+ io.result?.(result);+ io.say(result.adopted+ ? `relay recovery adopted the authenticated checkpoint at sequence ${result.sequence}; blocked sequence ${result.skipped} remains recorded as refused`+ : `relay recovery published at sequence ${result.sequence}; skipped blocked sequence ${result.skipped}`);+ return 0;+ }+ if (values.skip) throw new Refused('USAGE', '--skip is only valid with pullboard relay recover');+ if (first === 'devices') {+ if (second || rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay devices');+ const devices = readRelayMachine().devices.map(({ deviceId, label, fingerprint, createdAt }) => ({ deviceId, label, fingerprint, createdAt }));+ io.result?.({ devices });+ for (const device of devices) io.say(`${device.deviceId} ${device.label} ${device.fingerprint}`);+ if (!devices.length) io.say('no paired devices; run pullboard relay on --all');+ return 0;+ }+ if (first === 'revoke' && /^device-[0-9a-f]{32}$/u.test(second ?? '')) {+ if (rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay revoke <device>');+ const result = await revokeRelayDevice(second, io);+ io.result?.(result); io.say(result.notice); return 0;+ }+ if (values.all) {+ if (first !== 'on' || second || rest.length) throw new Refused('USAGE', 'pullboard relay on --all [--url <address>]');+ const result = await relayOnAll(values.url, io);+ io.result?.(result); return result.failed.length ? 1 : 0;+ }+ if (['tokens', 'revoke'].includes(first)) {+ if (rest.length || values.url || (first === 'tokens' && second) || (first === 'revoke' && !second)) {+ throw new Refused('USAGE', 'pullboard relay tokens, or pullboard relay revoke <token-id>');+ }+ const ctx = context(io);+ const result = first === 'tokens' ? await relayTokens(ctx.info.root, io) : await relayRevoke(ctx.info.root, second, io);+ io.result?.(result);+ if (first === 'tokens') {+ if (!result.tokens.length) io.say('no agent tokens on this board');+ for (const row of result.tokens) io.say(row.id + ' ' + row.agent + ' ' + (row.revoked ? 'revoked' : 'expires ' + new Date(row.expires).toISOString()));+ } else io.say('revoked token ' + result.id + '; other agent tokens are unchanged');+ return 0;+ }+ if (first === 'pair') {+ if (second || rest.length || values.url) throw new Refused('USAGE', 'pullboard relay pair');+ const ctx = context(io);+ return await relayPair(ctx.info.root, io);+ }+ if (first === 'join') {+ if (!second || rest.length) throw new Refused('USAGE', 'pullboard relay join <code> [--url <address>]');+ const ctx = context(io);+ return await relayJoin(ctx.info.root, second, values.url, io);+ }if (second || rest.length || (first && !['on', 'off'].includes(first)) || (values.url && first !== 'on')) throw new Refused('USAGE', 'pullboard relay [on|off] [--url <address>]');const ctx = context(io);if (!first) { await syncRelay(ctx.info.root, io); await executePersonRequests(ctx.info.root, io, main); }const result = first === 'on' ? await relayOn(ctx.info.root, values.url, io): first === 'off' ? await relayOff(ctx.info.root, io) : relayStatus(ctx.info.root);io.result?.(result);- io.say(result.linked ? `${result.link}\nrelay: sequence ${result.sequence}; ${result.behind} pending uploads${result.recovery.pending ? `; recovery pending for sequence ${result.recovery.skip}; retry ${result.recovery.next}` : ''}` : (result.notice || 'relay off; the local board is complete'));- io.say(result.linked ? `${result.link}\nrelay: sequence ${result.sequence}; ${result.behind} pending uploads` : (result.notice || 'relay off; the local board is complete'));++ io.say(result.linked ? `${result.link}\nrelay: sequence ${result.sequence}; ${result.behind} pending uploads${result.recovery?.pending ? `; recovery pending for sequence ${result.recovery.skip}; retry ${result.recovery.next}` : ''}` : (result.notice || 'relay off; the local board is complete'));return 0;}if (command === 'gate') {diff --cc src/engine.jsindex 1d9300b8,87e52c24..2023f9f4--- a/src/engine.js+++ b/src/engine.js@@@ -5,9 -5,7 +5,9 @@@ import { refusalDocument } from './jsonimport { ENGINE_VERSION } from './machine.js';import { Refused } from './refused.js';import { requestMoveProblem, recordRequestMove } from './relay-requests.js';-import { relayMoveActor, relaySenderProblem } from './relay-sender.js';+import { relayMoveActor, relaySenderProblem, validRelaySender } from './relay-sender.js';+- const ITEM_ID_FIRST_ARGUMENT = new Set(['editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze']);++const ITEM_ID_FIRST_ARGUMENT = new Set(['editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'appendFact']);/** Only these public board operations may be requested by an encrypted move. */export const ENGINE_OPERATIONS = Object.freeze([@@@ -160,14 -165,6 +164,15 @@@ export function refuseRelayMove(board,});}+/** Authorize each public relay position before replay, retaining refusals atomically with its cursor. */+export function applyRelayMove(board, move, { sequence, at, sender, kind, digest = null }) {+ requireSupportedEngine(move);- const problem = relaySenderProblem(move, sender, kind);++ const phoneReceipt = sender?.kind === 'machine' && move?.engine >= 6 && Boolean(move.personRequest) && !requestMoveProblem(board, move, { checkExecutorLease: false });++ const problem = relaySenderProblem(move, sender, kind, { phoneReceipt });+ if (!problem) return applyEngineMove(board, move, { sequence, at });+ return refuseRelayMove(board, move, { sequence, at, sender, kind, code: problem.code, digest, refusal: problem });+}+/*** Apply one relay position with the same board functions as the CLI, preserving its refusal.* A receipt and prefix commit atomically; duplicate ids return that receipt without another move.diff --cc src/machine.jsindex 06d019a8,e770f89b..aa7754a5--- a/src/machine.js+++ b/src/machine.js@@@ -9,8 -9,8 +9,8 @@@* broken copy, and checks the declaration against the refusals board.js and cli.js raise today.*/- /** Executable move semantics; bump once per release after a released move's meaning changes [H16]. */- export const ENGINE_VERSION = 3;+ /** Executable move semantics, carried by every sealed move and retained during replay [H16]. */-export const ENGINE_VERSION = 7;++export const ENGINE_VERSION = 8;/** @typedef {'agent' | 'coordinator' | 'clock'} Role */diff --cc src/relay-sender.jsindex 7af67fd1,e0d0135e..7a0be49e--- a/src/relay-sender.js+++ b/src/relay-sender.js@@@ -15,15 -15,11 +15,16 @@@ export function relayMoveActor(move)return null;}+/** Validate the complete relay-authenticated sender envelope before attributing a refusal. */+export function validRelaySender(sender) {- return Boolean(sender && ['person', 'agent'].includes(sender.kind) && typeof sender.userId === 'string' && sender.userId.length > 0 && sender.userId.length <= 256 &&- (sender.kind !== 'agent' || (typeof sender.agent === 'string' && sender.agent.length > 0 && sender.agent.length <= 256)));++ return Boolean(sender && ['person', 'agent', 'machine'].includes(sender.kind) && typeof sender.userId === 'string' && sender.userId.length > 0 && sender.userId.length <= 256 &&++ (sender.kind !== 'agent' || (typeof sender.agent === 'string' && sender.agent.length > 0 && sender.agent.length <= 256)) &&++ (sender.kind !== 'machine' || (typeof sender.machine === 'string' && sender.machine.length > 0 && sender.machine.length <= 256)));+}+/** Make the same authorization decision on every device, without inspecting its shell or checkout. */- export function relaySenderProblem(move, sender, kind) {+ export function relaySenderProblem(move, sender, kind, { phoneReceipt = false } = {}) {- if (!sender || !['person', 'agent', 'machine'].includes(sender.kind) || typeof sender.userId !== 'string' || !sender.userId.length || sender.userId.length > 256 ||- (sender.kind === 'agent' && (typeof sender.agent !== 'string' || !sender.agent.length || sender.agent.length > 256)) ||- (sender.kind === 'machine' && (typeof sender.machine !== 'string' || !sender.machine.length || sender.machine.length > 256))) {+ if (!validRelaySender(sender)) {return new Refused('RELAY_SENDER', 'this relay record has no authenticated sender; restore attribution before replaying it');}if (move?.operation === 'shout' && move.args?.[0]?.answers != null) {diff --cc src/relay.jsindex 0b7e5aee,54693e7f..8cbd7c2a--- a/src/relay.js+++ b/src/relay.js@@@ -1,10 -1,12 +1,12 @@@- /** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H16,P5]. */+ /** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';- import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';+ import { gunzipSync, gzipSync } from 'node:zlib';import * as store from './board.js';-import { exportBoard, restoreRelaySnapshot } from './exchange.js';-import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, requireSupportedEngine, startRelayEpoch } from './engine.js';+import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';+import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';+ import { relayMoveActor } from './relay-sender.js';import { ENGINE_VERSION } from './machine.js';import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';import { repoInfo, tryGit } from './git.js';@@@ -169,21 -187,230 +211,237 @@@ function behind(root, state)return localRecords(root, (board) => board.db.prepare('SELECT COUNT(*) AS count FROM event WHERE event_id > ?').get(state.cursor).count);}+/** Expose only the actionable recovery choice; checkpoint ciphertext and local digests stay private. */+function recoverySummary(state) {+ const skip = Number.isSafeInteger(state?.recovery?.skip) ? state.recovery.skip : 0;+ return { pending: skip > 0, skip, next: skip > 0 ? `pullboard relay recover --skip ${skip}` : '' };+}+- /** Expose pairing information while keeping the human relay credential out of output. */- function summary(root, state) {+ /** Expose key-free link status; only an explicit link operation includes its pairing carrier. */+ function summary(root, state, { pairing = false } = {}) {- if (!state) return { linked: false, board: '', url: '', link: '', sequence: 0, behind: 0 };- if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true };+ if (!state) return { linked: false, board: '', url: '', link: '', sequence: 0, behind: 0, recovery: recoverySummary(null) };+ if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true, recovery: recoverySummary(state) };- const key = encodeBoardKey(readBoardKey(state.board));+ const fragment = pairing ? '&key=' + encodeBoardKey(readBoardKey(state.board)) : '';+ const oversizedSnapshot = snapshotSize(state);return { linked: true, board: state.board, url: state.url,- link: 'https://app.pullboard.dev/#board=' + state.board + '&key=' + key,- sequence: state.sequence, behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),- recovery: recoverySummary(state) };+ link: 'https://app.pullboard.dev/#board=' + state.board + fragment,+ sequence: state.sequence, behind: (state.baselinePause ? behind(root, state) : state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),++ recovery: recoverySummary(state),+ ...(oversizedSnapshot ? { oversizedSnapshot } : {}),+ ...(state.baselinePause ? { pausedUpload: structuredClone(state.baselinePause) } : {}),+ ...(state.checkpointRefusal ? { refusedCheckpoint: checkpointProblem(state) } : {}) };+ }++ /** Measure a pending sealed snapshot against the relay's decoded journal limit. */+ function snapshotSize(state) {+ const sealed = state?.snapshot?.sealed ?? state?.checkpoint?.sealed;+ if (typeof sealed !== 'string') return null;+ const bytes = Buffer.from(sealed, 'base64url');+ if (bytes.toString('base64url') !== sealed || bytes.byteLength <= SEALED_SNAPSHOT_LIMIT) return null;+ return { board: state.board, sealedBytes: bytes.byteLength, limit: SEALED_SNAPSHOT_LIMIT };+ }++ /** Return the local pending snapshot's oversize details without contacting the relay. */+ export function pendingSnapshotSize(root) {+ return snapshotSize(loadLink(linkFile(root)));+ }++ /** Format a shared status line for an oversized sealed snapshot. */+ export function formatSnapshotLimit(problem, { paused = false } = {}) {+ const size = `${(problem.sealedBytes / 1_000_000).toFixed(1)} MB`;+ const limit = `${(problem.limit / 1_000_000).toFixed(1)} MB`;+ if (paused) return `relay paused for ${problem.board}: snapshot ${size} over the relay limit ${limit}; it resumes on its own once a snapshot fits`;+ return `relay snapshot for ${problem.board}: sealed snapshot ${size} over the relay limit ${limit}`;+ }++ /** Keep a permanent refusal only as a bounded, credential-free diagnostic. */+ function safePauseMessage(error) {+ const message = String(error.relayMessage ?? error.message ?? 'the relay refused the baseline upload')+ .replace(/https?:\/\/[^\s]+/gu, '[relay]')+ .replace(/\b(?:Bearer\s+)?(?:ps|pa|pm|pg)_[A-Za-z0-9_-]{20,}\b/gu, '[credential]')+ .replace(/[\r\n\t\x00-\x1f\x7f]+/gu, ' ')+ .replace(/\s+/gu, ' ').trim();+ return message.slice(0, 240) || 'the relay refused the baseline upload';+ }++ /** Pause only definitive baseline 4xx refusals; throttling and transient errors retain retries. */+ function permanentBaselineRefusal(error) {+ return Number.isInteger(error?.httpStatus) && error.httpStatus >= 400 && error.httpStatus < 500 &&+ ![408, 425, 429].includes(error.httpStatus);+ }++ /** Explain a refused later checkpoint without changing the ordered-move recovery policy. */+ function checkpointProblem(state) {+ const refusal = state.checkpointRefusal;+ const code = safePauseCode(refusal);+ const reason = safePauseMessage(refusal);+ const size = snapshotSize(state);+ const next = 'upgrade pullboard (npm i -g pullboard) or run pullboard relay off then relay on --all';+ const message = `relay checkpoint refused for ${state.board}: ${code} ${reason}`+ + (size ? '; ' + formatSnapshotLimit(size) : '')+ + '; moves still sync in order; a fresh checkpoint goes up on the next change; if it keeps failing, ' + next;+ return { code: size ? 'RELAY_SNAPSHOT_LIMIT' : 'RELAY_CHECKPOINT_REFUSED', message, next };+ }++ /** Project the current checkpoint repair for doctor without making another network request. */+ export function pendingCheckpointProblem(root) {+ const state = loadLink(linkFile(root));+ return state?.checkpointRefusal ? checkpointProblem(state) : null;+ }++ /** Deduplicate within one move, retaining its preflight notice and allowing later moves to warn. */+ function reportCheckpointRefusal(state, io) {+ let boards = CHECKPOINT_NOTICES.get(io);+ if (!boards) { boards = new Set(); CHECKPOINT_NOTICES.set(io, boards); }+ if (boards.has(state.board)) return;+ boards.add(state.board);+ const line = 'pullboard: ' + checkpointProblem(state).message;+ if (['status', 'doctor'].includes(io.relayCommand?.cliOperation) && io.relayJson === false) io.say(line);+ else io.err(line);+ }++ /** Name the safe next step for the saved permanent refusal. */+ function pauseFix(state) {+ const pause = state.baselinePause;+ if (pause.size || /(?:exceeds?|over|larger than|too large).{0,40}(?:bytes|snapshot|limit)|(?:snapshot|limit).{0,40}(?:exceeds?|over|too large)/iu.test(pause.message)) {+ return 'it resumes automatically once a snapshot fits';+ }+ if ([401, 403].includes(pause.status) || pause.code === 'AUTH_REQUIRED') return 'run pullboard relay on to sign in again';+ return 'upgrade Pullboard or run pullboard relay on again, then report the refusal if it persists';+ }++ /** Render one bounded line with board, safe refusal reason and recovery step. */+ function baselinePauseLine(state) {+ const pause = state.baselinePause;+ const code = /^[A-Z][A-Z0-9_]{0,63}$/.test(pause.code) ? pause.code : 'RELAY_REFUSED';+ const size = pause.size && Number.isSafeInteger(pause.size.sealedBytes) && Number.isSafeInteger(pause.size.limit)+ ? formatSnapshotLimit({ board: state.board, ...pause.size }, { paused: true }) : `relay paused for ${state.board} before its baseline upload`;+ return `pullboard: [${code}] ${size}: ${pause.message}; ${pauseFix(state)}`;+ }++ /** Report the durable pause once across preflight, move and postflight in one command. */+ function reportBaselinePause(state, io) {+ if (!BASELINE_NOTICES.has(io)) {+ BASELINE_NOTICES.add(io);+ io.err(baselinePauseLine(state));+ }+ }++ /** Limit a paused board to one fresh baseline attempt within this command. */+ function attemptedBaselineThisCommand(io, file) {+ let attempts = BASELINE_ATTEMPTS.get(io);+ if (!attempts) { attempts = new Set(); BASELINE_ATTEMPTS.set(io, attempts); }+ if (attempts.has(file)) return true;+ attempts.add(file);+ return false;+ }++ /** Retain an uncertain attempt in RAM so preflight failure cannot permit local fallback in this command. */+ function rememberBaselineFailure(io, file, error) {+ let failures = BASELINE_FAILURES.get(io);+ if (!failures) { failures = new Map(); BASELINE_FAILURES.set(io, failures); }+ failures.set(file, error);+ }++ /** Confirm absence through authenticated API v1; a lost ACK or another live device must stay ordered. */+ async function remoteBaselineAbsent(state, io) {+ try { await request(state, '/api/v1/boards/' + state.board + '/state', {}, io); }+ catch (error) {+ if (error.httpStatus === 404 && error.relayVersion === 1 && ['NO_BOARD', 'NO_SNAPSHOT'].includes(error.code)) return true;+ throw error;+ }+ return false;+ }++ /** Persist only a stable refusal code, never arbitrary relay text masquerading as a code. */+ function safePauseCode(error) {+ const code = error.relayCode ?? error.code;+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : 'RELAY_REFUSED';+ }++ /** Keep a conflicting remote baseline fenced across process restarts without discarding local work. */+ function requireUnconflictedBaseline(state) {+ if (state.baselineConflict) throw new Refused('RELAY_BASELINE_EXISTS', 'the relay already holds this board; save the local board with pullboard export, then run pullboard relay off to keep working locally; local moves stay off to protect its ordered history');+ }++ /** Preserve the unaccepted local candidate and persist a refusal across process restarts. */+ function fenceBaseline(file, state) {+ state.baselineAccepted = true;+ state.baselineConflict = true;+ delete state.baselinePause;+ saveLink(file, state);+ requireUnconflictedBaseline(state);+ }++ /** Fence another device's baseline before a retry can replace its sequence-zero snapshot. */+ async function requireAbsentBaseline(file, state, io) {+ if (!await remoteBaselineAbsent(state, io)) {+ fenceBaseline(file, state);+ }+ }++ /** Send the sequence-zero board image; only its first permanent HTTP refusal pauses relay sends. */+ async function uploadInitialBaseline(root, file, state, io) {+ attemptedBaselineThisCommand(io, file);+ try {+ await requireAbsentBaseline(file, state, io);+ const pending = state.snapshot;+ const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: pending, initialBaseline: true }, io);+ if (reply.state?.sequence !== pending.sequence || reply.state.sealed !== pending.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the initial snapshot; retry the configured relay');+ state.baselineAccepted = true;+ state.cursor = Number.isSafeInteger(state.baselineCursor) ? state.baselineCursor : localRecords(root, (board) => board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id);+ delete state.baselineCursor;+ delete state.baselinePause;+ delete state.snapshot;+ state.presentationDigest = state.snapshotPresentationDigest ?? state.presentationDigest;+ delete state.snapshotPresentationDigest;+ state.needsPresentation = false;+ saveLink(file, state);+ return true;+ } catch (error) {+ if (error.relayVersion === 1 && error.code === 'BASELINE_EXISTS') fenceBaseline(file, state);+ if (!permanentBaselineRefusal(error) || state.baselineAccepted) {+ rememberBaselineFailure(io, file, error);+ throw error;+ }+ try {+ await requireAbsentBaseline(file, state, io);+ } catch (uncertain) {+ rememberBaselineFailure(io, file, uncertain);+ throw uncertain;+ }+ const size = pendingSnapshotSize(root);+ state.baselinePause = {+ status: error.httpStatus,+ code: safePauseCode(error),+ message: safePauseMessage(error),+ ...(size ? { size: { sealedBytes: size.sealedBytes, limit: size.limit } } : {}),+ };+ delete state.snapshot;+ delete state.snapshotPresentationDigest;+ delete state.baselineCursor;+ saveLink(file, state);+ reportBaselinePause(state, io);+ return false;+ }+ }++ /** Rebuild from current local state once per command, so paused moves become the accepted baseline. */+ async function retryPausedBaseline(root, file, state, io) {+ if (!state.baselinePause || attemptedBaselineThisCommand(io, file)) return !state.baselinePause;+ try {+ const document = relaySnapshot(root);+ state.snapshot = { sequence: 0, sealed: await sealedRecord(readBoardKey(state.board), document, state, 'snapshot', 0) };+ state.snapshotPresentationDigest = presentationDigest(document.presentation);+ state.baselineCursor = document.tables.event.at(-1)?.event_id ?? 0;+ saveLink(file, state);+ const accepted = await uploadInitialBaseline(root, file, state, io);+ if (!accepted) reportBaselinePause(state, io);+ return accepted;+ } catch (error) {+ rememberBaselineFailure(io, file, error);+ throw error;+ }}/** Seal a client record at its proposed public sequence, with no board key in its envelope. */@@@ -283,32 -512,23 +543,43 @@@ async function decoded(key, record, staconst bytes = Buffer.from(record.sealed, 'base64url');if (!bytes.length || bytes.toString('base64url') !== record.sealed) throw new Refused('RELAY_RESPONSE', 'the relay returned invalid sealed bytes; fetch the board again');const plain = await unseal(key, bytes, { boardId: state.board, kind, sequence });- try { return JSON.parse(new TextDecoder().decode(plain)); }- catch { throw new Refused('RELAY_MOVE', 'the authenticated relay document is invalid; upgrade pullboard or restore a consistent snapshot'); }+ try {+ if (kind === 'snapshot') {+ if (plain[0] === 0x1f && plain[1] === 0x8b) return JSON.parse(gunzipSync(plain).toString('utf8'));+ if (plain[0] !== 0x7b) throw new Refused('SNAPSHOT_FORMAT', `the sealed snapshot starts with ${Buffer.from(plain.subarray(0, 4)).toString('hex') || 'no bytes'}; expected gzip magic 1f8b or legacy JSON starting with 7b`);+ }+ return JSON.parse(new TextDecoder().decode(plain));+ }+ catch (error) {+ if (error instanceof Refused) throw error;+ if (kind === 'snapshot') throw new Refused('SNAPSHOT_FORMAT', 'the sealed snapshot has gzip magic or legacy JSON bytes but cannot be read; refresh it from a linked machine');+ throw new Refused('RELAY_MOVE', 'the authenticated relay document is invalid; upgrade pullboard or restore a consistent snapshot');+ }}+/** Replay one authenticated record, auto-refusing only deterministic current-format record failures. */+async function replayRelayRecord(board, key, state, record) {+ let move;+ try {+ move = await decoded(key, record, state, record.kind, record.event_id);+ requireSupportedEngine(move);+ if (record.kind === 'request') return receivePersonRequest(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender });+ return applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind,+ digest: createHash('sha256').update(record.sealed).digest('hex') });+ } catch (error) {+ if (!(error instanceof Refused) || !['RELAY_MOVE', 'RELAY_RESPONSE', 'SEAL_FORMAT', 'SEAL_AUTH_FAILED'].includes(error.code)) throw error;+ return refuseRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind,+ code: error.code === 'SEAL_AUTH_FAILED' ? 'RELAY_SEAL' : error.code,+ digest: createHash('sha256').update(String(record.sealed)).digest('hex'),+ refusal: error.code === 'SEAL_AUTH_FAILED'+ ? new Refused('RELAY_SEAL', 'this relay record failed authentication and was logged as refused; run pullboard relay to continue with the next ordered record')+ : error });+ }+}+/** Persist the exact checkpoint before uploading, so a lost reply retries identical ciphertext. */async function publishCheckpoint(root, file, state, io) {+ if (!state.token?.startsWith('pm_') || process.env.PULLBOARD_RELAY_TOKEN) return;const document = relaySnapshot(root);const sequence = Number(document.tables.board_meta.find((row) => row.meta_key === 'relay_applied_sequence')?.meta_value ?? 0);const digest = presentationDigest(document.presentation);@@@ -388,12 -635,26 +686,22 @@@ async function catchUp(root, file, statif (localRecords(root, appliedSequence) <= after) throw new Refused('RELAY_RESPONSE', 'the relay checkpoint did not advance the missing prefix; fetch a consistent newer snapshot');return catchUp(root, file, state, io);}- if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string' || !record.sender || !['person', 'agent', 'machine'].includes(record.sender.kind) || typeof record.sender.userId !== 'string' || (record.sender.kind === 'agent' && typeof record.sender.agent !== 'string') || (record.sender.kind === 'machine' && typeof record.sender.machine !== 'string'))) {+ if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string')) {throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered prefix; fetch a consistent relay snapshot');}+ let pendingRefusal;for (const record of remote.events) {- const move = await decoded(key, record, state, record.kind, record.event_id);- // Legacy executable documents in the request channel still fail closed before attribution.- if (record.kind === 'request' && move?.engine !== undefined) requireSupportedEngine(move);- const outcome = localRecords(root, (board) => {- if (record.kind === 'request') return receivePersonRequest(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender });- else return applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind });- });- // Sender refusals have a sequence receipt, not an executable-ID receipt: never resend them.+ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'));- try { await replayRelayRecord(board, key, state, record); } finally { store.closeBoard(board); }++ let outcome;++ try { outcome = await replayRelayRecord(board, key, state, record); } finally { store.closeBoard(board); }++ // Exact ciphertext identifies an interrupted send even when its document was refused before replay.+ if (record.kind === 'move' && state.pending?.move && record.event_id === state.pending.sequence- && record.sealed === state.pending.sealed && JSON.stringify(move) === JSON.stringify(state.pending.move)- && outcome?.error && !localRecords(root, board => engineReceipt(board, move.id))) {++ && record.sealed === state.pending.sealed && outcome?.error++ && !localRecords(root, board => engineReceipt(board, state.pending.move.id))) {+ pendingRefusal = outcome.error;+ delete state.pending;+ delete state.recovered;+ }}state.sequence = localRecords(root, appliedSequence);if (state.pending?.move && localRecords(root, (board) => engineReceipt(board, state.pending.move.id))) {@@@ -463,8 -777,21 +824,22 @@@ export async function relayOperation(roreturn locked(file, async () => {const state = loadLink(file);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`);- await ensureOrdered(root, file, state, io);+ let moves = CHECKPOINT_MOVES.get(io);+ if (!moves) { moves = new Set(); CHECKPOINT_MOVES.set(io, moves); }+ if (moves.has(state.board)) CHECKPOINT_NOTICES.get(io)?.delete(state.board);+ moves.add(state.board);+ /** 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));+ if (!await ensureOrdered(root, file, state, io)) {+ // Preflight's notice covers the first move; long-running commands still name every later move.+ if (BASELINE_LOCAL_MOVES.has(io)) BASELINE_NOTICES.delete(io);+ reportBaselinePause(state, io);+ BASELINE_LOCAL_MOVES.add(io);+ return applyPausedMoveLocally();+ }await catchUp(root, file, state, io);if (state.pending) {delete state.pending;@@@ -524,8 -855,7 +903,8 @@@ export async function syncRelay(root, iif (!state) return null;if (state.unlinking) { io.err('pullboard: [RELAY_UNLINK_PENDING] the remote board is deleted; run pullboard relay off to finish forgetting this device key'); return summary(root, state); }try {+ if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', `a relay recovery for sequence ${state.recovery.skip} is pending; retry pullboard relay recover --skip ${state.recovery.skip} before syncing`);- await ensureOrdered(root, file, state, io);+ if (!await ensureOrdered(root, file, state, io)) return summary(root, state);await catchUp(root, file, state, io);if (state.pending) {// The complete prefix did not acknowledge this interrupted send. It must not run later.@@@ -538,14 -869,67 +918,68 @@@}catch (error) {if (!(error instanceof Refused)) throw error;- io.err(`pullboard: ${error.message}; run pullboard status to see pending uploads`);+ if (error.code === 'RELAY_KEY_MISSING') {+ if (!KEY_WARNED_COMMANDS.has(io)) {+ KEY_WARNED_COMMANDS.add(io);+ io.err(`pullboard: ${error.message}; moves are off until the key is reachable`);+ }+ } else io.err(`pullboard: ${error.message}; run pullboard status to see pending uploads`);return { linked: true, board: state.board, url: state.url, sequence: state.sequence,- behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)) };+ behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),+ recovery: recoverySummary(state) };}});}+ /** Return token-management context without opening a board-key pairing link or exposing any credential. */+ function tokenContext(state) {- return { linked: true, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0 };++ return { linked: true, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, recovery: recoverySummary(state) };+ }++ /** Require the existing board delegate before listing metadata or requesting an approved revocation. */+ function managementLink(file) {+ const state = loadLink(file);+ if (!state || state.unlinking) throw new Refused('RELAY_OFF', 'link this board with pullboard relay on before managing its agent tokens');+ return state;+ }++ /** List only this board’s agent-token metadata, never bearer values or the board key. */+ export async function relayTokens(root, io) {+ const file = linkFile(root);+ return locked(file, async () => {+ const state = managementLink(file);+ const listed = await request(state, '/auth/tokens?board=' + state.board, {}, io);+ if (!Array.isArray(listed.tokens) || listed.tokens.some((row) => !row || row.board !== state.board ||+ typeof row.id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(row.id) ||+ typeof row.agent !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(row.agent) ||+ !Number.isSafeInteger(row.expires) || (row.created !== null && !Number.isSafeInteger(row.created)) ||+ typeof row.revoked !== 'boolean')) throw new Refused('RELAY_RESPONSE', 'the relay token inventory is invalid; retry its configured address');+ const tokens = listed.tokens.map(({ id, board, agent, created, expires, revoked }) => ({ id, board, agent, created, expires, revoked }));+ return { ...tokenContext(state), tokens };+ });+ }++ /** Revoke one credential listed on this board while retaining its cache so it cannot be silently reminted. */+ export async function relayRevoke(root, id, io) {+ requirePersonChannel(io.personChannel);+ if (typeof id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) {+ throw new Refused('TOKEN_NOT_OWNED', 'name an opaque token id from pullboard relay tokens, never a credential value');+ }+ const file = linkFile(root);+ return locked(file, async () => {+ const state = managementLink(file);+ const listed = await request(state, '/auth/tokens?board=' + state.board, {}, io);+ if (!Array.isArray(listed.tokens) || !listed.tokens.some((row) => row.id === id)) {+ throw new Refused('TOKEN_NOT_OWNED', 'choose a token listed on this board by pullboard relay tokens');+ }+ const result = await nativePhoneAction(state, 'revoke-token', id, io, request);+ if (result.id !== id || result.revoked !== true) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge this token revocation; retry its opaque id');+ for (const credential of Object.values(state.agentTokens ?? {})) if (credential.id === id) credential.revoked = true;+ saveLink(file, state);+ return { ...tokenContext(state), id: result.id, revoked: result.revoked };+ });+ }+/** Read an acknowledged exact CLI result before changed spec, brief or Git refs can block it. */export async function relayCommandReceipt(root, command) {if (!command) return null;@@@ -587,88 -971,6 +1021,95 @@@ export async function relayCommandReceiexport function relayRecovered(root) {return loadLink(linkFile(root))?.recovered?.move ?? null;}++/** Explicitly refuse one blocked position, replay its valid tail on a private copy, then publish it. */+export async function relayRecover(root, skip, io) {+ const file = linkFile(root);+ return locked(file, async () => {+ const state = loadLink(file);+ if (!state || state.unlinking || state.mode !== 'ordered') throw new Refused('RELAY_LINKED', 'link this ordered relay board before recovering a blocked sequence');+ const boardFile = join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite');+ const source = store.openBoard(boardFile);+ const staged = store.openBoard(':memory:');+ try {+ const cursor = appliedSequence(source);+ const sourceDigest = nativeBoardDigest(source);+ if (!Number.isSafeInteger(skip) || skip !== cursor + 1) throw new Refused('RELAY_SEQUENCE', `only the blocked next sequence ${cursor + 1} can be skipped; inspect pullboard relay and retry`);+ if (state.recovery && (state.recovery.skip !== skip || state.recovery.cursor !== cursor)) {+ throw new Refused('RELAY_RECOVERY_PENDING', `finish the saved recovery for sequence ${state.recovery.skip} before choosing another; retry pullboard relay recover --skip ${state.recovery.skip}`);+ }+ if (state.recovery && state.recovery.sourceDigest !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery was pending; local rows are preserved, but this recovery cannot be retried from the changed board; keep an export and ask the person to reconcile the relay checkpoint');+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery started; no recovery data was published, retry after preserving that change');+ importBoard(staged, exportBoard(source));+ const key = readBoardKey(state.board);+ if (state.recovery) {+ const saved = await request(state, '/api/v1/boards/' + state.board + '/state', {}, io);+ if (Number.isSafeInteger(saved.state?.sequence) && saved.state.sequence >= state.recovery.sequence) {+ const ownAcknowledgement = saved.state.sequence === state.recovery.sequence && saved.state.sealed === state.recovery.sealed;+ const senderProblem = relaySenderProblem(null, saved.state.sender, 'snapshot');+ if (senderProblem) throw senderProblem;+ const native = await decoded(key, saved.state, state, 'snapshot', saved.state.sequence);+ if (!recoveryRefusalMatches(native, state.recovery) || (!ownAcknowledgement && !state.recovery.blockerDigest)) {+ throw new Refused('RELAY_RECOVERY_PENDING', 'the checkpoint does not prove this blocked sequence was refused; keep this device unchanged and ask the person to inspect the relay checkpoint');+ }+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery was pending; local rows are preserved, but this checkpoint cannot be adopted over those changes; keep an export and ask the person to reconcile the relay checkpoint');+ restoreRelaySnapshot(source, native, saved.state.sequence, sourceDigest);+ state.sequence = saved.state.sequence;+ state.cursor = saved.state.sequence;+ delete state.recovery;+ saveLink(file, state);+ return { ...summary(root, state), skipped: skip, ...(!ownAcknowledgement ? { adopted: true } : {}) };+ }+ }+ const remote = await request(state, '/api/v1/boards/' + state.board + '/events?after=' + cursor, {}, io);+ if (!Array.isArray(remote.events) || !remote.events.length || remote.events[0]?.event_id !== skip) throw new Refused('RELAY_SEQUENCE', `relay sequence ${skip} is not available as the next record; fetch the current relay prefix`);+ const blocker = remote.events[0];+ let decodedMove = null;+ let blockerCode = 'RELAY_RECORD';+ try {+ decodedMove = await decoded(key, blocker, state, blocker.kind, blocker.event_id);+ requireSupportedEngine(decodedMove);+ throw new Refused('RELAY_RECOVERY_HEALTHY', 'the selected record is readable by this pullboard version; run pullboard relay to replay it normally');+ } catch (error) {+ if (!(error instanceof Refused) || (error.code !== 'ENGINE_VERSION' && !['SEAL_VERSION', 'RELAY_MOVE', 'RELAY_RESPONSE', 'SEAL_FORMAT', 'SEAL_AUTH_FAILED'].includes(error.code))) throw error;+ blockerCode = error.code;+ // A person may explicitly bypass this one authenticated transport slot; it remains in the receipt log.+ }+ if (decodedMove?.engine > ENGINE_VERSION) blockerCode = 'ENGINE_VERSION';+ const blockerDigest = createHash('sha256').update(String(blocker.sealed)).digest('hex');+ refuseRelayMove(staged, decodedMove, { sequence: skip, at: blocker.event_at, sender: blocker.sender, kind: blocker.kind,+ code: blockerCode,+ digest: blockerDigest,+ refusal: new Refused(blockerCode, 'person recovery logged this blocked record as refused; run pullboard relay to apply the remaining ordered tail') });- for (const record of remote.events.slice(1)) await replayRelayRecord(staged, key, state, record);++ for (const record of remote.events.slice(1)) {++ try { await replayRelayRecord(staged, key, state, record); }++ catch (error) {++ // A later unsupported record needs its own explicit choice; it cannot undo this selected skip.++ if (!(error instanceof Refused) || !['ENGINE_VERSION', 'SEAL_VERSION'].includes(error.code)) throw error;++ break;++ }++ }+ const document = relaySnapshot(root, { board: staged });+ const sequence = appliedSequence(staged);+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed while recovery was staged; no recovery checkpoint was published, export the new local change and retry');+ const candidate = state.recovery?.sequence === sequence+ ? { sequence, sealed: state.recovery.sealed }+ : { sequence, sealed: await sealedRecord(key, document, state, 'snapshot', sequence) };+ state.recovery = { skip, cursor, sourceDigest, blockerDigest, ...candidate };+ saveLink(file, state);+ const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: candidate }, io);+ if (reply.state?.sequence !== sequence || reply.state.sealed !== candidate.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the recovery checkpoint; local board was left unchanged, retry recovery');+ if (nativeBoardDigest(source) !== sourceDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed before checkpoint acknowledgement; local rows are preserved, but the checkpoint may already be accepted and this recovery cannot be retried from the changed board; keep an export and ask the person to reconcile the relay checkpoint');+ restoreRelaySnapshot(source, document, sequence, sourceDigest);+ state.sequence = sequence;+ state.cursor = sequence;+ delete state.recovery;+ saveLink(file, state);+ return { ...summary(root, state), skipped: skip };+ } finally { store.closeBoard(staged); store.closeBoard(source); }+ });+}+/** Read the local link and lag without opening a network connection or revealing its relay token. */export function relayStatus(root) { return summary(root, loadLink(linkFile(root))); }@@@ -745,16 -1072,25 +1211,25 @@@ export async function relayOff(root, ioreturn locked(file, async () => {const state = loadLink(file);if (!state) return summary(root, null);- if (!state.unlinking) {- const deleted = await request(state, '/api/v1/boards/' + state.board, { method: 'DELETE', allowMissing: true }, io);- if (deleted.alreadyDeleted) state.alreadyDeleted = true;- state.unlinking = true;- saveLink(file, state);- }- forgetBoardKey(state.board, state.keyStorage);+ // Local unlink always completes, including agent shells, outages and a fenced remote baseline.+ let proposal;+ try { proposal = await phoneProposal(state, 'delete-board', state.board); }+ catch { /* Missing key or pairing cannot stop local unlinking. */ }rmSync(file, { force: true });- return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0,- ...(state.alreadyDeleted ? { alreadyDeleted: true, notice: 'the relay had already deleted this board; this device is unlinked and the local board is complete' } : {}) };+ try { forgetBoardKey(state.board, state.keyStorage); }+ catch { /* The local opt-out is complete even when secure key storage is temporarily locked. */ }+ let requested = false;+ let remote;+ try {+ if (!proposal) throw new Refused('PHONE_NOT_PAIRED', 'Manage the relay copy from your phone.');+ await publishPhoneApproval(state, proposal, io, request);+ requested = true;+ } catch (error) {+ if (proposal) remote = warnPhoneApproval(proposal, error, io, 'Local link removed. Manage the relay copy from the phone, or relink this board and run pullboard relay off again explicitly.');+ }- return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0,++ return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, recovery: recoverySummary(null),+ ...(remote ? { remote } : {}),+ notice: 'Local link removed. The relay copy stays until you approve deleting it on your phone.' + (requested ? '' : ' Open the phone to manage the relay copy.') };});}diff --cc test/api.test.jsindex 0fa6e375,46df3d18..ac5b3e25--- a/test/api.test.js+++ b/test/api.test.js@@@ -17,10 -18,11 +18,12 @@@ import { once } from 'node:events'import { join, dirname, resolve, basename, delimiter } from 'node:path';import { after, test } from 'node:test';import { resultCommands } from '../src/cli.js';-import { allShouts, closeBoard, EVENT_LOG_VERSION, openBoard } from '../src/board.js';+import { allShouts, EVENT_LOG_VERSION, closeBoard, openBoard } from '../src/board.js';import { presentationShout, relayPresentation } from '../src/relay-presentation.js';import { JSON_SHAPES } from '../src/json.js';+import { projectState } from '../src/serve.js';+ import { SSH_SHELL_MARKERS } from '../src/person.js';+ import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const TEMP_DIRS = [];diff --cc test/engine.test.jsindex 44a70782,e38f7eb3..b3b02778--- a/test/engine.test.js+++ b/test/engine.test.js@@@ -6,7 -8,7 +8,7 @@@ import { pathToFileURL } from 'node:urlimport { test } from 'node:test';import * as store from '../src/board.js';import { exportBoard, importBoard, restoreRelaySnapshot } from '../src/exchange.js';- import { applyEngineMove, applyRelayMove, prepareEngineMove, appliedSequence, engineReceipt, refuseRelayMove, startRelayEpoch } from '../src/engine.js';-import { applyEngineMove, applyRelayMove, prepareEngineMove, appliedSequence, engineReceipt, startRelayEpoch, checkpointSequence, ENGINE_OPERATIONS } from '../src/engine.js';++import { applyEngineMove, applyRelayMove, prepareEngineMove, appliedSequence, engineReceipt, refuseRelayMove, startRelayEpoch, checkpointSequence, ENGINE_OPERATIONS } from '../src/engine.js';import { ENGINE_VERSION } from '../src/machine.js';import { Refused } from '../src/refused.js';@@@ -179,34 -266,87 +267,115 @@@ test('future engine relay records stop}});+test('a refused answerDecision is not attributed to an item sharing its shout id [H16]', t => {+ const { copies, item, source } = engineCopies(t);+ const [board] = copies;+ const shoutId = store.shout(source, {+ from: 'coordinator', to: 'person', text: 'Private refusal fixture', decision: true, lanes: ['web'],+ });+ assert.equal(shoutId, item, 'fixture needs a coincident shout and item id');+ const move = prepareEngineMove(board, 'answerDecision', [shoutId, {+ agentId: 'coordinator', text: 'Approved', lanes: ['web'],+ }], { id: 'forged-answer' });+ const refused = applyRelayMove(board, move, {+ sequence: 1, at: CLAIM_AT, kind: 'move', sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' },+ });+ assert.equal(refused.error.code, 'RELAY_SENDER_MISMATCH');+ assert.equal(store.events(board).at(-1).item_id, null, 'a shout id must not be mistaken for an item id');+});++test('fallback refusal identity hashes operation arguments when no ciphertext digest is supplied [H16]', t => {+ const { copies, item } = engineCopies(t);+ const board = copies[0];+ const move = claimMove(board, item, 'web-1');+ const envelope = { sequence: 1, at: CLAIM_AT, sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' }, kind: 'move', code: 'RELAY_MOVE' };+ const initial = refuseRelayMove(board, move, envelope);+ assert.match(initial.error.message, /this relay record was refused and logged; run pullboard relay to continue/);+ const changed = { ...move, args: [item, { ...move.args[1], head: 'b'.repeat(40) }] };+ assert.throws(() => refuseRelayMove(board, changed, envelope), { code: 'RELAY_CURSOR' }, 'changed contents cannot reuse an earlier refusal receipt');+});++ test('released engine 3 stops a background completion before changing rows or its cursor [V2,H16]', async t => {+ const { directory, copies, item } = engineCopies(t);+ const archive = execFileSync('git', ['archive', 'v0.8.1'], { cwd: resolve(import.meta.dirname, '..'), maxBuffer: 32 * 1024 * 1024 });+ execFileSync('tar', ['-x', '-C', directory], { input: archive });+ const released = await import(pathToFileURL(join(directory, 'src/engine.js')).href);+ const releasedMachine = await import(pathToFileURL(join(directory, 'src/machine.js')).href);+ assert.equal(releasedMachine.ENGINE_VERSION, 3, 'exercise the actual released client');+ assert.equal(released.ENGINE_OPERATIONS.includes('completeCheckBaseline'), false);+ assert.ok(ENGINE_OPERATIONS.includes('completeCheckBaseline'));+ const expected = { command: 'true', main: 'a'.repeat(40), request: '12345678-1234-1234-1234-123456789abc' };+ const baseline = { ...expected, result: 'green' };+ const sender = { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' };+ for (const board of copies) {+ store.editItem(board, item, { agentId: 'coordinator', check: expected.command, checkBaseline: { ...expected, result: 'pending' } });+ checkpointSequence(board, 7);+ const currentMove = prepareEngineMove(board, 'completeCheckBaseline', [item, { agentId: 'coordinator', expected, baseline }]);+ assert.equal(currentMove.engine, ENGINE_VERSION);+ assert.ok(ENGINE_VERSION >= 4, 'the current engine supports background completions');+ const move = { ...currentMove, engine: 4 }; // Keep the actual v4-versus-released-v3 compatibility boundary.+ const before = exportBoard(board);+ assert.throws(() => released.applyRelayMove(board, move, { sequence: 8, at: CLAIM_AT, kind: 'move', sender }), error => {+ assert.equal(error.code, 'ENGINE_VERSION');+ assert.match(error.message, /version 4.*version 3.*upgrade/i);+ return true;+ });+ assert.deepEqual(exportBoard(board), before, 'no refusal, receipt, item or replay metadata changes');+ assert.equal(released.appliedSequence(board), 7);+ const receipt = applyRelayMove(board, move, { sequence: 8, at: CLAIM_AT, kind: 'move', sender });+ assert.equal(Boolean(receipt.error), false);+ assert.equal(receipt.result, true);+ assert.equal(appliedSequence(board), 8);+ assert.equal(store.events(board).at(-1).event_kind, 'check-baseline');+ }+ });++ test('an engine 6 client meets an item hold and is told to upgrade [H16,M1]', async t => {+ const { directory, copies, item } = engineCopies(t);+ const archive = execFileSync('git', ['archive', 'v0.8.3'], { cwd: resolve(import.meta.dirname, '..'), maxBuffer: 32 * 1024 * 1024 });+ execFileSync('tar', ['-x', '-C', directory], { input: archive });+ const released = await import(pathToFileURL(join(directory, 'src/engine.js')).href);+ const releasedMachine = await import(pathToFileURL(join(directory, 'src/machine.js')).href);+ assert.equal(releasedMachine.ENGINE_VERSION, 6, 'exercise the actual 0.8.3 client');+ assert.equal(released.ENGINE_OPERATIONS.includes('holdItem'), false);+ assert.equal(released.ENGINE_OPERATIONS.includes('releaseItemHold'), false);+ assert.ok(ENGINE_VERSION >= 7, 'the current engine supports item holds');+ assert.ok(ENGINE_OPERATIONS.includes('holdItem'));++ const board = copies[0];+ const oldMove = released.prepareEngineMove(board, 'claim', [item, {+ agentId: 'web-1', lane: 'web', leaseMs: 2 * HOUR, head: 'a'.repeat(40),+ freeze: () => ({ text: '{"rows":[]}', digest: 'f'.repeat(64) }),+ }], { id: 'engine-6-understood-claim' });+ assert.equal(oldMove.engine, 6);+ const sender = { kind: 'agent', userId: 'fixture-user', agent: 'web-1' };+ const oldOutcome = released.applyRelayMove(board, oldMove, { sequence: 1, at: CLAIM_AT, kind: 'move', sender });+ assert.equal(Boolean(oldOutcome.error), false, 'the old client still applies an operation it understands');+ assert.equal(appliedSequence(board), 1);++ const hold = prepareEngineMove(board, 'holdItem', [item, {+ agentId: 'coordinator', reason: 'review the release',+ }], { id: 'engine-7-item-hold', actor: 'coordinator' });+ assert.equal(hold.engine, ENGINE_VERSION);+ const engine7Hold = { ...hold, engine: 7 };+ const before = exportBoard(board);+ let refusal;+ let refusalOutcome;+ try {+ refusalOutcome = released.applyRelayMove(board, engine7Hold, {+ sequence: 2, at: CLAIM_AT, kind: 'move', sender: { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' },+ });+ } catch (error) {+ refusal = error;+ }+ const refusalCode = refusal?.code ?? refusalOutcome?.error?.code;+ const refusalMessage = refusal?.message ?? refusalOutcome?.error?.message ?? '';+ assert.equal(refusalCode, 'ENGINE_VERSION');+ assert.match(refusalMessage, /engine version 7.*engine version 6.*upgrade pullboard/i);+ assert.deepEqual(exportBoard(board), before, 'the old client refuses before changing item rows or replay receipts');+ assert.equal(appliedSequence(board), 1, 'the hold refusal does not advance the old client cursor');+ });+test('a relay refusal receipt failure rolls back its log and cursor together [H2,H16]', t => {const { copies, item } = engineCopies(t);const board = copies[0];diff --cc test/relay-sealed.test.jsindex e267838f,b9d59c8d..6545e2dc--- a/test/relay-sealed.test.js+++ b/test/relay-sealed.test.js@@@ -6,22 -6,20 +6,25 @@@ import { chmodSync, existsSync, mkdirSyimport { tmpdir } from 'node:os';import { delimiter, join, resolve } from 'node:path';import { pathToFileURL } from 'node:url';++import { gunzipSync } from 'node:zlib';import { createServer } from 'node:http';- import { test } from 'node:test';+ import { after, test } from 'node:test';import { serveRelay } from '../relay/service.js';import { createRelayAuth } from '../relay/auth.js';import { createGitHubClient } from '../relay/github.js';import { githubFixture } from './relay-fixture.js';+import { serveApi } from '../src/api.js';import * as store from '../src/board.js';-import { exportBoard } from '../src/exchange.js';-import { checkpointSequence, engineReceipt, prepareEngineMove } from '../src/engine.js';-import { seal as sealMove } from '../src/seal.js';++import { main } from '../src/cli.js';+import { exportBoard, restoreRelaySnapshot, semanticBoardDigest } from '../src/exchange.js';+import { appliedSequence, checkpointSequence, engineReceipt, prepareEngineMove, requireSupportedEngine } from '../src/engine.js';+import { seal as sealMove, unseal as openSealed } from '../src/seal.js';import { ENGINE_VERSION } from '../src/machine.js';+import { relayRecover, syncRelay } from '../src/relay.js';+ after(cleanupFixtureChildren);+/** Seal on the test client only; nonce, authentication tag and ciphertext are opaque to the server. */function seal(key, value, binding) {const nonce = randomBytes(12);@@@ -41,8 -39,8 +44,16 @@@ function unseal(key, value, binding)return JSON.parse(Buffer.concat([decipher.update(bytes.subarray(13, -16)), decipher.final()]).toString());}++/** Open actual sealed checkpoints, accepting compressed and released legacy JSON snapshots. */++async function openCheckpoint(box, snapshot) {++ const bytes = await openSealed(box.key, Buffer.from(snapshot.sealed, 'base64url'),++ { boardId: box.id, kind: 'snapshot', sequence: snapshot.sequence });++ const plain = bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes;++ return JSON.parse(new TextDecoder().decode(plain));++}++/** Create a real private CLI board, actual stand-in GitHub sign-in, and an ephemeral relay server. */- async function fixture(t) {+ async function fixture(t, { machineCredentials = true } = {}) {const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-sealed-http-')));const root = join(directory, 'repo');const home = join(directory, 'home');@@@ -394,20 -368,6 +381,20 @@@ test('two real clients stop before send}});+/** Link one private fixture to a real relay with an engine-99 blocker at sequence one. */+async function blockedRecoveryFixture(box) {+ mkdirSync(join(box.home, 'relay-keys'), { mode: 0o700 });+ writeFileSync(join(box.home, 'relay-keys', box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });+ writeFileSync(join(box.root, '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id,- url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });++ url: box.origin, repository: 'fixture/repository', token: box.machines[0].token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ const initial = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(box.document)), { boardId: box.id, kind: 'snapshot', sequence: 0 })).toString('base64url');+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: initial } })).status, 200);+ const future = { version: 1, engine: 99, id: 'future-engine-record', operation: 'futureOperation', args: [] };+ const sealed = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(future)), { boardId: box.id, kind: 'move', sequence: 1 })).toString('base64url');+ assert.equal((await box.call(box.path + '/moves', { method: 'POST', token: box.one.token, body: { sequence: 1, sealed } })).status, 200);+ return { future, sealed };+}+test('two real clients refuse forged relay actors and person-only requests while advancing identically [H2,H16]', async t => {const box = await fixture(t);const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));@@@ -424,6 -384,6 +411,7 @@@prepareEngineMove(source, 'answerDecision', [question, { agentId: 'coordinator', asPerson: true, text: 'forged person answer', lanes: [lane] }]),{ version: 1, type: 'person-request', id: 'forged-person-request', move: { verb: 'shout', args: { to: 'coordinator', text: 'forged person request' } } },prepareEngineMove(source, 'recordRowDecisions', [{ agentId: 'remote-1', channel: 'view', decisions: [] }]),++ prepareEngineMove(source, 'appendFact', [1, { agentId: 'coordinator', kind: 'note', text: 'forged fact' }]),prepareEngineMove(source, 'shout', [{ from: 'remote-1', to: 'all', text: 'valid remote observation', lanes: [lane] }]),];document = JSON.parse(JSON.stringify(exportBoard(source)));@@@ -462,11 -422,11 +450,17 @@@assert.equal(newShouts[0].shout_from, 'remote-1');assert.equal(newShouts[0].shout_text, 'valid remote observation');const refused = result.tables.event.filter(row => row.event_kind === 'relay_refused');-- assert.equal(refused.length, 4);++ assert.equal(refused.length, 5);assert.ok(refused.every(row => row.event_by === 'remote-1'), 'the log attributes every attempted forgery to its authenticated sender');-- assert.deepEqual(refused.map(row => JSON.parse(row.event_detail).code), ['RELAY_SENDER_MISMATCH', 'RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY']);++ assert.deepEqual(refused.map(row => JSON.parse(row.event_detail).code), ['RELAY_SENDER_MISMATCH', 'RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY', 'RELAY_SENDER_MISMATCH']);assert.equal(JSON.parse(refused[0].event_detail).actor, 'coordinator');-- assert.equal(result.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '5');++ assert.equal(result.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '6');++ assert.equal(refused[4].item_id, 1, 'a refused appendFact names its existing item');++ for (let index = 0; index < roots.length; index += 1) {++ const itemLog = await replayClient(roots[index], envs[index], 'log', '1');++ assert.ok(itemLog.events.some(row => row.event_kind === 'relay_refused' && JSON.parse(row.event_detail).operation === 'appendFact'),++ 'each real CLI item log includes the refused fact');++ }const log = await replayClient(roots[1], envs[1], 'log');assert.deepEqual(log.events.filter(row => row.event_kind === 'relay_refused'), refused, 'pullboard log exposes the sending agent and attempted actor');assert.deepEqual((await replayClient(roots[0], envs[0], 'export')).tables, result.tables, 'repeat catch-up does not duplicate refusals or actions');@@@ -631,501 -591,38 +625,592 @@@ test('two real clients enforce the veri]);});- test('person recovery explicitly skips one future-engine blocker and publishes a refusal checkpoint', async (t) => {++test('person recovery explicitly skips one future-engine blocker and publishes a refusal checkpoint [H3,H16]', async (t) => {+ const box = await fixture(t);+ const seededBoard = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ store.shout(seededBoard, { from: 'person', to: 'coordinator', text: 'read cursor recovery probe', lanes: ['web'], request: true });+ box.document = exportBoard(seededBoard);+ } finally { store.closeBoard(seededBoard); }+ const keyDirectory = join(box.home, 'relay-keys');+ mkdirSync(keyDirectory, { mode: 0o700 });+ writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });+ writeFileSync(join(box.root, '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id,- url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });++ url: box.origin, repository: 'fixture/repository', token: box.machines[0].token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token,+ body: { sequence: 0, sealed: Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(box.document)), { boardId: box.id, kind: 'snapshot', sequence: 0 })).toString('base64url') } })).status, 200);+ const future = { version: 1, engine: 99, id: 'future-engine-record', operation: 'unknownFromFuture', args: [] };+ assert.throws(() => requireSupportedEngine(future), { code: 'ENGINE_VERSION' });+ assert.equal((await box.call(box.path + '/moves', { method: 'POST', token: box.one.token,+ body: { sequence: 1, sealed: Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(future)), { boardId: box.id, kind: 'move', sequence: 1 })).toString('base64url') } })).status, 200);+ assert.equal((await box.call(box.path + '/events?after=0')).body.events.length, 1);+ const diagnostics = [];+ const io = { err: (message) => diagnostics.push(message), say: () => {} };+ const previousPullboardHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = box.home;+ t.after(() => { if (previousPullboardHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = previousPullboardHome; });+ const secondRoot = join(box.directory, 'recovery-replica');+ const secondHome = join(box.directory, 'recovery-replica-home');+ mkdirSync(secondRoot); mkdirSync(secondHome, { mode: 0o700 });+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: secondRoot, env: box.env }).status, 0);+ await replayClient(secondRoot, { ...box.env, HOME: secondHome, PULLBOARD_HOME: secondHome }, 'init');+ const initialFile = join(box.directory, 'recovery-initial.json');+ writeFileSync(initialFile, JSON.stringify(box.document), { mode: 0o600 });+ await replayClient(secondRoot, { ...box.env, HOME: secondHome, PULLBOARD_HOME: secondHome }, 'import', initialFile);+ const secondKeyDirectory = join(secondHome, 'relay-keys');+ mkdirSync(secondKeyDirectory, { mode: 0o700 });+ writeFileSync(join(secondKeyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });+ writeFileSync(join(secondRoot, '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id,- url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });++ url: box.origin, repository: 'fixture/repository', token: box.machines[0].token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ const blocked = await box.call(box.path + '/events?after=0');+ assert.equal(blocked.body.events.length, 1);+ const ordinary = await syncRelay(box.root, io);+ assert.match(diagnostics.join('\n'), /ENGINE_VERSION/);+ assert.equal(ordinary.sequence, 0, 'ordinary catch-up stops without advancing either replica');+ await assert.rejects(() => relayRecover(box.root, 2, io), /blocked next sequence 1/);+ const agentAttempt = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), 'relay', 'recover', '--skip', '1', '--json'],+ { cwd: box.root, env: { ...box.env, CODEX_THREAD_ID: 'private-agent-test' }, encoding: 'utf8' });+ assert.equal(agentAttempt.status, 1);+ assert.match(agentAttempt.stdout, /B26_PERSON_CHANNEL/);+ const originalBoard = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ const originalDocument = exportBoard(originalBoard);+ store.closeBoard(originalBoard);+ const realFetch = globalThis.fetch;+ t.after(() => { globalThis.fetch = realFetch; });+ globalThis.fetch = async (url, options = {}) => {+ if (options.method === 'PUT' && String(url).endsWith('/state')) {+ return new Response(JSON.stringify({ version: 1, error: { code: 'CHECKPOINT_TEMPORARY', message: 'temporary fixture refusal' } }),+ { status: 503, headers: { 'content-type': 'application/json' } });+ }+ return realFetch(url, options);+ };+ await assert.rejects(() => relayRecover(box.root, 1, io), { code: 'CHECKPOINT_TEMPORARY' });+ const savedBeforeRetry = JSON.parse(readFileSync(join(box.root, '.git/pullboard/relay.json'), 'utf8')).recovery;+ assert.equal(savedBeforeRetry.skip, 1, 'the exact staged recovery remains durable after a known publish failure');+ assert.equal((await box.call(box.path + '/state')).body.state.sequence, 0, 'a failed publish does not replace the remote checkpoint');+ globalThis.fetch = async (url, options = {}) => {+ if (options.method === 'PUT' && String(url).endsWith('/state')) {+ await realFetch(url, options);+ throw new Error('fixture dropped the checkpoint acknowledgement');+ }+ return realFetch(url, options);+ };+ await assert.rejects(() => relayRecover(box.root, 1, io), { code: 'RELAY_UNAVAILABLE' });+ globalThis.fetch = realFetch;+ const linkFile = join(box.root, '.git/pullboard/relay.json');+ const pendingRecovery = JSON.parse(readFileSync(linkFile, 'utf8')).recovery;+ assert.equal(pendingRecovery.skip, 1);+ globalThis.fetch = async (url, options = {}) => {+ const response = await realFetch(url, options);+ if (options.method !== 'GET' || !String(url).endsWith('/state')) return response;+ const document = await response.json();+ document.state.sender = { kind: 'agent', agent: 'client-one', userId: 'fixture-user' };+ return new Response(JSON.stringify(document), { status: response.status, headers: { 'content-type': 'application/json' } });+ };+ await assert.rejects(() => relayRecover(box.root, 1, io), { code: 'RELAY_PERSON_ONLY' },+ 'a lost-ACK checkpoint still requires the relay-authenticated person sender');+ globalThis.fetch = realFetch;+ const pendingStatus = await replayClient(box.root, { ...box.env, PULLBOARD_HOME: box.home }, 'status');+ assert.equal(pendingStatus.relay.behind, 0, 'recovery remains separate from pending upload count');+ assert.deepEqual(pendingStatus.relay.recovery, { pending: true, skip: 1, next: 'pullboard relay recover --skip 1' }, 'actual status JSON exposes the saved recovery retry');+ const humanStatus = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), 'status'],+ { cwd: box.root, env: { ...box.env, PULLBOARD_HOME: box.home }, encoding: 'utf8' });+ assert.equal(humanStatus.status, 0);+ assert.equal(humanStatus.stdout.includes('recovery pending for sequence 1; retry pullboard relay recover --skip 1'), true,+ 'human status shows the actionable recovery without counting it as an upload');+ const localApi = await serveApi({ runCommand: main, projects: () => [{ root: box.root, name: 'private recovery fixture' }] });+ try {+ const apiAddress = new URL(localApi.url);+ const apiRequest = await fetch(apiAddress.origin + '/api/v1/boards/' + box.id + '/requests', {+ method: 'POST', headers: { 'x-pullboard-key': apiAddress.searchParams.get('k'), 'content-type': 'application/json' },+ body: JSON.stringify({ text: 'request while recovery is pending' }),+ });+ const apiRequestResult = await apiRequest.json();+ assert.equal(apiRequestResult.error.code, 'RELAY_RECOVERY_PENDING', 'linked local API requests are guarded by the recovery lock');+ const afterApiRequest = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try { assert.deepEqual(exportBoard(afterApiRequest), originalDocument, 'the refused API request leaves native tables unchanged'); }+ finally { store.closeBoard(afterApiRequest); }+ } finally { await localApi.close(); }+ const beforeInbox = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ let cursorBeforeInbox;+ try { cursorBeforeInbox = beforeInbox.db.prepare("SELECT agent_last_shout_id FROM agent WHERE agent_id='coordinator'").get().agent_last_shout_id; }+ finally { store.closeBoard(beforeInbox); }+ const inboxCommand = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), 'inbox'],+ { cwd: box.root, env: { ...box.env, PULLBOARD_HOME: box.home }, encoding: 'utf8' });+ assert.equal(inboxCommand.status, 0, inboxCommand.stderr);+ assert.match(inboxCommand.stdout, /read cursor recovery probe/);+ const afterInbox = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ let cursorAfterInbox;+ try { cursorAfterInbox = afterInbox.db.prepare("SELECT agent_last_shout_id FROM agent WHERE agent_id='coordinator'").get().agent_last_shout_id; }+ finally { store.closeBoard(afterInbox); }+ assert.ok(cursorAfterInbox > cursorBeforeInbox, 'the actual inbox read advances the durable read cursor');+ const acceptedCheckpoint = (await box.call(box.path + '/state')).body.state;+ assert.equal(acceptedCheckpoint.sequence, pendingRecovery.sequence);+ assert.equal(acceptedCheckpoint.sealed, pendingRecovery.sealed, 'a lost ACK retains the exact sealed checkpoint candidate');+ const unchanged = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try { assert.equal(semanticBoardDigest(exportBoard(unchanged)), semanticBoardDigest(originalDocument), 'known failure and lost ACK do not change semantic native state'); }+ finally { store.closeBoard(unchanged); }+ const recovered = await relayRecover(box.root, 1, io);+ assert.equal(recovered.sequence, 1);+ assert.equal(recovered.skipped, 1);+ assert.deepEqual(recovered.recovery, { pending: false, skip: 0, next: '' }, 'successful recovery clears the public pending state');+ const cursorAfterRecovery = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ assert.equal(cursorAfterRecovery.db.prepare("SELECT agent_last_shout_id FROM agent WHERE agent_id='coordinator'").get().agent_last_shout_id,+ cursorAfterInbox, 'checkpoint restore retains the greater local inbox cursor');+ } finally { store.closeBoard(cursorAfterRecovery); }+ const events = await box.call(box.path + '/events?after=0');+ assert.equal(events.status, 409, 'person recovery publishes and compacts an ordinary sealed checkpoint');+ const snapshot = (await box.call(box.path + '/state')).body.state;+ assert.equal(snapshot.sequence, 1);- const document = JSON.parse(new TextDecoder().decode(await openSealed(box.key, Buffer.from(snapshot.sealed, 'base64url'), { boardId: box.id, kind: 'snapshot', sequence: 1 })));++ const document = await openCheckpoint(box, snapshot);+ assert.equal(document.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '1');+ assert.equal(document.tables.event.at(-1).event_kind, 'relay_refused');+ assert.equal(document.tables.event.at(-1).event_by, 'client-one');+ const blockedReason = JSON.parse(document.tables.board_meta.find(row => row.meta_key === 'relay_refusal_1').meta_value).outcome.error;+ assert.match(blockedReason.message, /person recovery logged this blocked record as refused; run pullboard relay/);+ const secondEnv = { ...box.env, HOME: secondHome, PULLBOARD_HOME: secondHome };+ await replayClient(secondRoot, secondEnv, 'relay');+ const firstBoard = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ const secondBoard = store.openBoard(join(secondRoot, '.git/pullboard/board.sqlite'));+ try {+ assert.equal(secondBoard.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='relay_applied_sequence'").get().meta_value, '1');+ assert.equal(secondBoard.db.prepare("SELECT agent_last_shout_id FROM agent WHERE agent_id='coordinator'").get().agent_last_shout_id,+ 0, 'the other replica retains its own checkpoint cursor rather than inheriting this device’s local read');+ assert.deepEqual(store.events(secondBoard).map(row => row.event_kind), store.events(firstBoard).map(row => row.event_kind));+ } finally { store.closeBoard(secondBoard); store.closeBoard(firstBoard); }+ process.env.PULLBOARD_HOME = box.home;+ const personRequest = (id, text) => ({ version: 1, type: 'person-request', id, move: { verb: 'shout', args: { to: 'coordinator', text } } });+ const later = personRequest('later-person-request', 'Later person move');+ assert.equal((await box.call(box.path + '/requests', { method: 'POST', token: box.person.token,+ body: { sequence: 2, sealed: Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(later)), { boardId: box.id, kind: 'request', sequence: 2 })).toString('base64url') } })).status, 200);+ const invalid = { version: 1, engine: 3, id: 'known-item-forged-claim', operation: 'claim', args: [1, { agentId: 'forged-agent' }] };+ const sealFor = async (value, kind, sequence) => Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: box.id, kind, sequence })).toString('base64url');+ const append = (sequence, kind, sealed, token = box.one.token) => box.call(box.path + (kind === 'request' ? '/requests' : '/moves'), { method: 'POST', token, body: { sequence, sealed } });+ assert.equal((await append(3, 'move', await sealFor(invalid, 'move', 3))).status, 200);+ assert.equal((await append(4, 'move', Buffer.from([1]).toString('base64url'), box.two.token)).status, 200, 'the relay stores current-version ciphertext opaquely');+ const repeated = personRequest('reused-content-id', 'First request');+ assert.equal((await append(5, 'request', await sealFor(repeated, 'request', 5), box.person.token)).status, 200);+ const changed = personRequest('reused-content-id', 'Changed request');+ assert.equal((await append(6, 'request', await sealFor(changed, 'request', 6), box.person.token)).status, 200);+ const unknownCurrent = { version: 1, engine: 3, id: 'unknown-current-operation', operation: 'notAnOperation', args: [] };+ assert.equal((await append(7, 'move', await sealFor(unknownCurrent, 'move', 7), box.one.token)).status, 200);+ let suppressCheckpointWrites = true;+ const proxy = createServer(async (incoming, outgoing) => {+ const chunks = [];+ for await (const chunk of incoming) chunks.push(chunk);+ const body = Buffer.concat(chunks);+ if (suppressCheckpointWrites && incoming.method === 'PUT' && incoming.url.endsWith('/state')) {+ outgoing.writeHead(503, { 'content-type': 'application/json' });+ outgoing.end(JSON.stringify({ version: 1, error: { code: 'CHECKPOINT_SUPPRESSED', message: 'private test keeps the event tail for both clients' } }));+ return;+ }+ const response = await fetch(box.origin + incoming.url, { method: incoming.method,+ headers: { ...(incoming.headers.authorization ? { authorization: incoming.headers.authorization } : {}),+ 'x-pullboard-engine': incoming.headers['x-pullboard-engine'] ?? '', ...(body.length ? { 'content-type': 'application/json' } : {}) },+ ...(body.length ? { body } : {}) });+ let payload = await response.text();+ if (incoming.url.includes('/events?after=')) {+ const document = JSON.parse(payload);+ const record = document.events?.find(event => event.event_id === 3);+ if (record) record.sender = { kind: 'agent', agent: 'client-one', userId: 'x'.repeat(257) };+ payload = JSON.stringify(document);+ }+ outgoing.writeHead(response.status, { 'content-type': 'application/json' });+ outgoing.end(payload);+ });+ await new Promise(resolve => proxy.listen(0, '127.0.0.1', resolve));+ t.after(() => proxy.close());+ const proxyUrl = 'http://127.0.0.1:' + proxy.address().port;+ for (const root of [box.root, secondRoot]) {+ const path = join(root, '.git/pullboard/relay.json');+ const link = JSON.parse(readFileSync(path, 'utf8'));+ link.url = proxyUrl;+ writeFileSync(path, JSON.stringify(link) + '\n', { mode: 0o600 });+ }+ await replayClient(box.root, { ...box.env, PULLBOARD_HOME: box.home }, 'relay');+ const one = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ assert.equal(appliedSequence(one), 11, diagnostics.join('\n'));+ const refusals = store.events(one).filter(row => row.event_kind === 'relay_refused');+ assert.deepEqual(refusals.map(row => JSON.parse(row.event_detail).code).slice(-4), ['RELAY_SENDER', 'SEAL_FORMAT', 'PERSON_REQUEST_ID', 'RELAY_SENDER_MISMATCH']);+ assert.ok(refusals.some(row => row.item_id === 1 && row.event_by === 'relay'), 'malformed sender is normalized to relay and refusal names existing item #1');+ const unsupportedOperation = JSON.parse(one.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='relay_refusal_7'").get().meta_value).outcome.error;+ assert.equal(unsupportedOperation.code, 'RELAY_SENDER_MISMATCH', 'an unknown operation is refused before a replica can interpret it');+ assert.equal(store.events(one).filter(row => row.event_kind === 'shout').length, 5, 'the two valid person requests each produce a claim and their real CLI shout');+ const requests = JSON.parse(one.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='relay_person_requests'").get().meta_value);+ assert.deepEqual(requests.map(({ id, status, error }) => ({ id, status, code: error?.code ?? null })), [+ { id: 'later-person-request', status: 'done', code: null },+ { id: 'reused-content-id', status: 'done', code: null },+ { id: 'reused-content-id-6', status: 'refused', code: 'PERSON_REQUEST_ID' },+ ], 'recovery and the native executor preserve person request identities and their outcomes');+ } finally { store.closeBoard(one); }+ await replayClient(secondRoot, { ...box.env, HOME: secondHome, PULLBOARD_HOME: secondHome }, 'relay');+ const firstAfterTail = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ const secondAfterTail = store.openBoard(join(secondRoot, '.git/pullboard/board.sqlite'));+ try {+ assert.equal(appliedSequence(secondAfterTail), 11);+ assert.deepEqual(store.events(secondAfterTail).map(row => row.event_detail), store.events(firstAfterTail).map(row => row.event_detail));+ assert.equal(semanticBoardDigest(exportBoard(secondAfterTail)), semanticBoardDigest(exportBoard(firstAfterTail)),+ 'both replicas converge on semantic state after later person moves; their inbox cursors remain local metadata');+ } finally { store.closeBoard(secondAfterTail); store.closeBoard(firstAfterTail); }+ const logged = await replayClient(box.root, { ...box.env, PULLBOARD_HOME: box.home }, 'log', '1');+ assert.ok(logged.events.some(row => row.event_kind === 'relay_refused' && row.item_id === 1), 'pullboard log #1 exposes the refusal');+ const current = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ const healthySequence = appliedSequence(current) + 1;+ store.closeBoard(current);+ const healthyRequest = personRequest('healthy-request-after-refusals', 'Healthy request must not be skipped');+ assert.equal((await append(healthySequence, 'request', await sealFor(healthyRequest, 'request', healthySequence), box.person.token)).status, 200);+ await assert.rejects(() => relayRecover(box.root, healthySequence, io), { code: 'RELAY_RECOVERY_HEALTHY' });+ const stillAtSeven = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try { assert.equal(appliedSequence(stillAtSeven), healthySequence - 1); }+ finally { store.closeBoard(stillAtSeven); }+ await replayClient(box.root, { ...box.env, PULLBOARD_HOME: box.home }, 'relay');+ await replayClient(secondRoot, secondEnv, 'relay');+ const beforeHeader = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ const futureSequence = appliedSequence(beforeHeader) + 1;+ store.closeBoard(beforeHeader);+ const futureSealHeader = Buffer.from([2]).toString('base64url');+ assert.equal((await append(futureSequence, 'move', futureSealHeader, box.one.token)).status, 200);+ const sealBlocked = await replayClient(box.root, { ...box.env, PULLBOARD_HOME: box.home }, 'relay');+ assert.ok(sealBlocked.diagnostics.some(line => line.includes('SEAL_VERSION')));+ const atEight = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try { assert.equal(appliedSequence(atEight), futureSequence - 1); }+ finally { store.closeBoard(atEight); }+ suppressCheckpointWrites = false;+ const headerRecovery = await replayClient(box.root, { ...box.env, PULLBOARD_HOME: box.home }, 'relay', 'recover', '--skip', String(futureSequence));+ assert.equal(headerRecovery.version, 1);+ assert.equal(headerRecovery.linked, true);+ assert.equal(headerRecovery.board, box.id);+ assert.equal(headerRecovery.sequence, futureSequence);+ assert.equal(headerRecovery.skipped, futureSequence);+ assert.equal(typeof headerRecovery.url, 'string');+ assert.equal(typeof headerRecovery.link, 'string');+ assert.equal(typeof headerRecovery.behind, 'number');+ await replayClient(secondRoot, secondEnv, 'relay');+ const restoredSecond = store.openBoard(join(secondRoot, '.git/pullboard/board.sqlite'));+ try { assert.equal(appliedSequence(restoredSecond), futureSequence, 'second CLI client restores the sealed future-header recovery checkpoint'); }+ finally { store.closeBoard(restoredSecond); }+ process.env.PULLBOARD_HOME = box.home;+ const local = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ assert.equal(appliedSequence(local), futureSequence);+ const requests = JSON.parse(local.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='relay_person_requests'").get().meta_value);+ assert.ok(requests.some(row => row.id === 'healthy-request-after-refusals' && row.status === 'done'), 'the later sealed person request was executed and receipted after recovery');+ } finally { store.closeBoard(local); }+});+++test('two future-engine blockers recover one durable position at a time on two real clients [H3,H16]', async t => {++ const box = await fixture(t);++ const roots = [box.root, join(box.directory, 'second-recovery-client')];++ const homes = [box.home, join(box.directory, 'second-recovery-home')];++ const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));++ const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));++ let document;++ try { checkpointSequence(source, 0); document = exportBoard(source); }++ finally { store.closeBoard(source); }++ mkdirSync(roots[1]); mkdirSync(homes[1], { mode: 0o700 });++ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: roots[1], env: envs[1] }).status, 0);++ await replayClient(roots[1], envs[1], 'init');++ const initial = join(box.directory, 'two-blockers-native.json');++ writeFileSync(initial, JSON.stringify(document), { mode: 0o600 });++ await replayClient(roots[1], envs[1], 'import', initial);++ for (let index = 0; index < roots.length; index += 1) {++ mkdirSync(join(homes[index], 'relay-keys'), { mode: 0o700 });++ writeFileSync(join(homes[index], 'relay-keys', box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });++ writeFileSync(join(roots[index], '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id,++ url: box.origin, repository: 'fixture/repository', token: box.machines[index].token, sequence: 0,++ cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });++ }++ /** Upload only sealed records through the real authenticated relay. */++ async function upload(value, kind, sequence, token) {++ const sealed = Buffer.from(await sealMove(box.key, Buffer.from(JSON.stringify(value)), { boardId: box.id, kind, sequence })).toString('base64url');++ const reply = await box.call(box.path + (kind === 'snapshot' ? '/state' : '/moves'), {++ method: kind === 'snapshot' ? 'PUT' : 'POST', token, body: { sequence, sealed },++ });++ assert.equal(reply.status, 200);++ }++ await upload(document, 'snapshot', 0, box.person.token);++ for (let sequence = 1; sequence <= 5; sequence += 1) await upload({ version: 1, engine: ENGINE_VERSION,++ id: 'prefix-' + sequence, operation: 'unknownCurrentOperation', args: [] }, 'move', sequence, box.one.token);++ for (let index = 0; index < roots.length; index += 1) await replayClient(roots[index], envs[index], 'relay');++ for (const sequence of [6, 7]) await upload({ version: 1, engine: 99, id: 'future-' + sequence,++ operation: 'futureOperation', args: [] }, 'move', sequence, box.one.token);++ await upload({ version: 1, engine: ENGINE_VERSION, id: 'later-person-eight', operation: 'shout',++ args: [{ from: 'person', to: 'coordinator', text: 'Person after two blockers', lanes: ['web'] }] }, 'move', 8, box.person.token);++ const previousHome = process.env.PULLBOARD_HOME;++ t.after(() => { if (previousHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = previousHome; });++ process.env.PULLBOARD_HOME = box.home;++ const io = { say: () => {}, err: () => {} };++ assert.equal((await syncRelay(box.root, io)).sequence, 5);++ const first = await relayRecover(box.root, 6, io);++ assert.equal(first.sequence, 6, 'later engine99 record cannot roll back the selected skip');++ assert.equal((await box.call(box.path + '/state')).body.state.sequence, 6, 'skip6 is durably published before skip7');++ await replayClient(roots[1], envs[1], 'relay');++ const afterFirst = await replayClient(roots[1], envs[1], 'export');++ assert.equal(afterFirst.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '6');++ assert.ok(afterFirst.tables.event.some(row => row.event_kind === 'relay_refused' && JSON.parse(row.event_detail).sequence === 6));++ assert.equal(afterFirst.tables.shout.some(row => row.shout_text === 'Person after two blockers'), false);++ const second = await relayRecover(box.root, 7, io);++ assert.equal(second.sequence, 8, 'the second explicit skip replays the later person move');++ const exports = [];++ for (let index = 0; index < roots.length; index += 1) exports.push(await replayClient(roots[index], envs[index], 'export'));++ assert.deepEqual(exports[0].tables, exports[1].tables, 'both native replicas converge without off/on');++ assert.equal(exports[0].tables.shout.filter(row => row.shout_text === 'Person after two blockers').length, 1);++ assert.deepEqual(exports[0].tables.event.filter(row => row.event_kind === 'relay_refused').map(row => JSON.parse(row.event_detail).sequence).slice(-2), [6, 7]);++});+++test('recovery collision status preserves the retry while the winner catches an appended tail [H16]', async (t) => {+ const box = await fixture(t);+ await blockedRecoveryFixture(box);+ const secondRoot = join(box.directory, 'recovery-collision-replica');+ const secondHome = join(box.directory, 'recovery-collision-home');+ mkdirSync(secondRoot);+ mkdirSync(secondHome, { mode: 0o700 });+ const secondEnv = { ...box.env, HOME: secondHome, PULLBOARD_HOME: secondHome };+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: secondRoot, env: secondEnv }).status, 0);+ await replayClient(secondRoot, secondEnv, 'init');+ const snapshotFile = join(box.directory, 'collision-initial.json');+ writeFileSync(snapshotFile, JSON.stringify(box.document), { mode: 0o600 });+ await replayClient(secondRoot, secondEnv, 'import', snapshotFile);+ mkdirSync(join(secondHome, 'relay-keys'), { mode: 0o700 });+ writeFileSync(join(secondHome, 'relay-keys', box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });+ writeFileSync(join(secondRoot, '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id,- url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });++ url: box.origin, repository: 'fixture/repository', token: box.machines[0].token, sequence: 0, cursor: box.document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });++ const previousHome = process.env.PULLBOARD_HOME;+ const previousFetch = globalThis.fetch;+ t.after(() => {+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ globalThis.fetch = previousFetch;+ });+ globalThis.fetch = async (url, options = {}) => {+ if (options.method === 'PUT' && String(url).endsWith('/state')) {+ return new Response(JSON.stringify({ version: 1, error: { code: 'CHECKPOINT_TEST', message: 'private collision fixture' } }),+ { status: 503, headers: { 'content-type': 'application/json' } });+ }+ return previousFetch(url, options);+ };+ process.env.PULLBOARD_HOME = box.home;+ await assert.rejects(() => relayRecover(box.root, 1, { err: () => {}, say: () => {} }), { code: 'CHECKPOINT_TEST' });+ process.env.PULLBOARD_HOME = secondHome;+ await assert.rejects(() => relayRecover(secondRoot, 1, { err: () => {}, say: () => {} }), { code: 'CHECKPOINT_TEST' });+ const firstLink = JSON.parse(readFileSync(join(box.root, '.git/pullboard/relay.json'), 'utf8'));+ const secondLink = JSON.parse(readFileSync(join(secondRoot, '.git/pullboard/relay.json'), 'utf8'));+ assert.notEqual(firstLink.recovery.sealed, secondLink.recovery.sealed, 'each replica stages its own exact encrypted checkpoint');++ globalThis.fetch = previousFetch;+ process.env.PULLBOARD_HOME = box.home;+ await relayRecover(box.root, 1, { err: () => {}, say: () => {} });+ const winningCheckpoint = (await box.call(box.path + '/state')).body.state;- const winningNative = JSON.parse(new TextDecoder().decode(await openSealed(box.key, Buffer.from(winningCheckpoint.sealed, 'base64url'),- { boardId: box.id, kind: 'snapshot', sequence: winningCheckpoint.sequence })));++ const winningNative = await openCheckpoint(box, winningCheckpoint);+ process.env.PULLBOARD_HOME = secondHome;+ const futureNative = structuredClone(winningNative);+ futureNative.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value = '99';+ const futureSeal = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(futureNative)),+ { boardId: box.id, kind: 'snapshot', sequence: 1 })).toString('base64url');+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 1, sealed: futureSeal } })).status, 200);+ await assert.rejects(() => relayRecover(secondRoot, 1, { err: () => {}, say: () => {} }), { code: 'ENGINE_VERSION' },+ 'an authenticated winning snapshot still stops at its newer engine version');+ const noProofNative = structuredClone(winningNative);+ noProofNative.tables.board_meta = noProofNative.tables.board_meta.filter((row) => row.meta_key !== 'relay_refusal_1');+ const noProofSeal = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(noProofNative)),+ { boardId: box.id, kind: 'snapshot', sequence: 1 })).toString('base64url');+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 1, sealed: noProofSeal } })).status, 200);+ await assert.rejects(() => relayRecover(secondRoot, 1, { err: () => {}, say: () => {} }), { code: 'RELAY_RECOVERY_PENDING' },+ 'a person checkpoint without the selected refusal proof cannot resolve the pending recovery');+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token,+ body: { sequence: winningCheckpoint.sequence, sealed: winningCheckpoint.sealed } })).status, 200);+ globalThis.fetch = async (url, options = {}) => {+ const response = await previousFetch(url, options);+ if (options.method !== 'GET' || !String(url).endsWith('/state')) return response;+ const document = await response.json();+ document.state.sender = { kind: 'agent', agent: 'client-two', userId: 'fixture-user' };+ return new Response(JSON.stringify(document), { status: response.status, headers: { 'content-type': 'application/json' } });+ };+ await assert.rejects(() => relayRecover(secondRoot, 1, { err: () => {}, say: () => {} }), { code: 'RELAY_PERSON_ONLY' },+ 'the checkpoint sender must be a person even when its ciphertext matches a saved recovery');+ globalThis.fetch = previousFetch;+ const markers = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT', 'CODEX_THREAD_ID', 'CODEX_SESSION_ID', 'CODEX_CI', 'CODEX_SHELL'];+ const previousMarkers = Object.fromEntries(markers.map((marker) => [marker, process.env[marker]]));+ t.after(() => markers.forEach((marker) => {+ if (previousMarkers[marker] === undefined) delete process.env[marker];+ else process.env[marker] = previousMarkers[marker];+ }));+ for (const marker of markers) delete process.env[marker];+ let adoptedOutput = '';+ const streams = { cwd: secondRoot, stdout: { isTTY: false, write: (text) => { adoptedOutput += text; } }, stderr: { isTTY: false, write: () => {} } };+ assert.equal(await main(['relay', 'recover', '--skip', '1'], streams), 0);+ assert.equal(adoptedOutput.includes('relay recovery adopted the authenticated checkpoint at sequence 1; blocked sequence 1 remains recorded as refused'), true,+ 'the CLI reports adoption rather than claiming it published the winner');+ const syncDiagnostics = [];+ const syncSummary = await syncRelay(secondRoot, { err: (line) => syncDiagnostics.push(line), say: () => {} });+ assert.deepEqual(syncSummary.recovery, { pending: false, skip: 0, next: '' }, 'adoption clears the durable recovery');+ assert.equal(syncDiagnostics.length, 0);+ const collisionStatus = await replayClient(secondRoot, secondEnv, 'status');+ assert.equal(collisionStatus.relay.behind, 0);+ assert.deepEqual(collisionStatus.relay.recovery, { pending: false, skip: 0, next: '' }, 'actual status reports the adopted checkpoint as complete');+ const humanStatus = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), 'status'],+ { cwd: secondRoot, env: secondEnv, encoding: 'utf8' });+ assert.equal(humanStatus.status, 0);+ assert.equal(humanStatus.stdout.includes('recovery pending for sequence 1; retry pullboard relay recover --skip 1'), false);+ const humanRelay = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), 'relay'],+ { cwd: secondRoot, env: secondEnv, encoding: 'utf8' });+ assert.equal(humanRelay.status, 0);+ assert.equal(humanRelay.stdout.includes('recovery pending for sequence 1; retry pullboard relay recover --skip 1'), false);+ const stillBlocked = store.openBoard(join(secondRoot, '.git/pullboard/board.sqlite'));+ try { assert.equal(appliedSequence(stillBlocked), 1, 'the losing client adopts the authenticated winning checkpoint'); }+ finally { store.closeBoard(stillBlocked); }++ const lane = Object.keys(JSON.parse(readFileSync(join(box.root, 'pullboard.json'), 'utf8')).lanes)[0];+ const tail = { version: 1, engine: 3, id: 'recovery-tail-after-collision', operation: 'shout',+ args: [{ from: 'person', to: 'coordinator', request: true, text: 'Tail after recovery checkpoint', lanes: [lane] }] };+ const sealed = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(tail)),+ { boardId: box.id, kind: 'request', sequence: 2 })).toString('base64url');+ assert.equal((await box.call(box.path + '/requests', { method: 'POST', token: box.person.token, body: { sequence: 2, sealed } })).status, 200);+ process.env.PULLBOARD_HOME = box.home;+ await replayClient(box.root, box.env, 'relay');+ process.env.PULLBOARD_HOME = secondHome;+ await replayClient(secondRoot, secondEnv, 'relay');+ const winner = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ const other = store.openBoard(join(secondRoot, '.git/pullboard/board.sqlite'));+ try {+ assert.equal(appliedSequence(winner), 2, 'the winner catches the appended tail after recovery');+ assert.equal(appliedSequence(other), 2, 'the adopted client also catches the appended person move');+ assert.deepEqual(exportBoard(other).tables, exportBoard(winner).tables, 'both actual clients converge on the same native rows');+ }+ finally { store.closeBoard(other); store.closeBoard(winner); }+});+- test('recovery preserves a local write racing its first staged publish', async (t) => {++test('recovery preserves a local write racing its first staged publish [H16]', async (t) => {+ const box = await fixture(t);+ await blockedRecoveryFixture(box);+ const priorHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = box.home;+ t.after(() => { if (priorHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = priorHome; });+ const priorFetch = globalThis.fetch;+ t.after(() => { globalThis.fetch = priorFetch; });+ let wrote = false;+ globalThis.fetch = async (url, options = {}) => {+ const response = await priorFetch(url, options);+ if (!wrote && String(url).includes('/events?after=0')) {+ wrote = true;+ const board = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ const lane = Object.keys(JSON.parse(readFileSync(join(box.root, 'pullboard.json'), 'utf8')).lanes)[0];+ store.addItem(board, { by: 'coordinator', lane, title: 'Concurrent local write', criterion: 'Keep this row' });+ } finally { store.closeBoard(board); }+ }+ return response;+ };+ await assert.rejects(() => relayRecover(box.root, 1, { err: () => {}, say: () => {} }), { code: 'RELAY_LOCAL_CHANGED' });+ globalThis.fetch = priorFetch;+ assert.equal((await box.call(box.path + '/state')).body.state.sequence, 0, 'no checkpoint is published after a local edit races staging');+ const board = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try { assert.ok(store.listItems(board, { all: true }).some(item => item.item_title === 'Concurrent local write')); }+ finally { store.closeBoard(board); }+ const diagnostics = [];+ await syncRelay(box.root, { err: line => diagnostics.push(line), say: () => {} });+ assert.match(diagnostics.join('\n'), /ENGINE_VERSION/);+ const afterSync = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try { assert.ok(store.listItems(afterSync, { all: true }).some(item => item.item_title === 'Concurrent local write')); }+ finally { store.closeBoard(afterSync); }+});+- test('lost-ACK recovery retry refuses to overwrite a concurrent local write', async (t) => {++test('lost-ACK recovery retry refuses to overwrite a concurrent local write [H16]', async (t) => {+ const box = await fixture(t);+ await blockedRecoveryFixture(box);+ const priorHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = box.home;+ t.after(() => { if (priorHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = priorHome; });+ const priorFetch = globalThis.fetch;+ t.after(() => { globalThis.fetch = priorFetch; });+ let wrote = false;+ globalThis.fetch = async (url, options = {}) => {+ const response = await priorFetch(url, options);+ if (!wrote && options.method === 'PUT' && String(url).endsWith('/state')) {+ wrote = true;+ const board = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ const lane = Object.keys(JSON.parse(readFileSync(join(box.root, 'pullboard.json'), 'utf8')).lanes)[0];+ store.addItem(board, { by: 'coordinator', lane, title: 'Write during lost ACK', criterion: 'Keep this row' });+ } finally { store.closeBoard(board); }+ throw new Error('fixture lost the accepted checkpoint ACK');+ }+ return response;+ };+ await assert.rejects(() => relayRecover(box.root, 1, { err: () => {}, say: () => {} }), { code: 'RELAY_UNAVAILABLE' });+ globalThis.fetch = priorFetch;+ const recovery = JSON.parse(readFileSync(join(box.root, '.git/pullboard/relay.json'), 'utf8')).recovery;+ assert.equal(recovery.skip, 1);+ assert.equal((await box.call(box.path + '/state')).body.state.sealed, recovery.sealed);+ await assert.rejects(() => relayRecover(box.root, 1, { err: () => {}, say: () => {} }),+ { code: 'RELAY_LOCAL_CHANGED', message: /cannot be retried from the changed board/ },+ 'a local change is preserved and the message does not suggest export alone will unblock retry');+ const diagnostics = [];+ await syncRelay(box.root, { err: line => diagnostics.push(line), say: () => {} });+ assert.match(diagnostics.join('\n'), /RELAY_RECOVERY_PENDING/);+ const board = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ assert.ok(store.listItems(board, { all: true }).some(item => item.item_title === 'Write during lost ACK'));+ assert.equal(appliedSequence(board), 0);+ } finally { store.closeBoard(board); }+});+- test('checkpoint restore checks native digest after BEGIN IMMEDIATE against a separate connection', async (t) => {++test('checkpoint restore checks native digest after BEGIN IMMEDIATE against a separate connection [H16]', async (t) => {+ const box = await fixture(t);+ await blockedRecoveryFixture(box);+ const database = join(box.root, '.git/pullboard/board.sqlite');+ const source = store.openBoard(database);+ const concurrent = store.openBoard(database);+ try {+ source.db.prepare("INSERT INTO board_meta (meta_key, meta_value) VALUES ('relay_applied_sequence', '0'), ('relay_engine_version', '3')").run();+ const expectedDocument = exportBoard(source);+ const expectedDigest = semanticBoardDigest(expectedDocument);+ const lane = Object.keys(JSON.parse(readFileSync(join(box.root, 'pullboard.json'), 'utf8')).lanes)[0];+ store.addItem(concurrent, { by: 'coordinator', lane, title: 'Write before transactional guard', criterion: 'Preserve this row' });+ assert.throws(() => restoreRelaySnapshot(source, expectedDocument, 0, expectedDigest), { code: 'RELAY_LOCAL_CHANGED' });+ assert.ok(store.listItems(source, { all: true }).some(item => item.item_title === 'Write before transactional guard'));+ assert.equal(appliedSequence(source), 0);+ } finally {+ store.closeBoard(concurrent);+ store.closeBoard(source);+ }+});++ test('relay accepts engine 4 clients carrying sealed background completions [V2,H16]', async t => {+ const box = await fixture(t, { machineCredentials: false });+ const headers = { 'x-pullboard-engine': '4' };+ assert.ok(ENGINE_VERSION >= 4, 'engine-4 background completions remain supported');+ const snapshot = await box.call(box.path + '/state', {+ method: 'PUT', token: box.person.token, headers,+ body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) },+ });+ assert.equal(snapshot.status, 200);+ const board = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ let move;+ try {+ const expected = { command: 'true', main: 'a'.repeat(40), request: '12345678-1234-1234-1234-123456789abc' };+ const prepared = prepareEngineMove(board, 'completeCheckBaseline', [1, {+ agentId: 'client-one', expected, baseline: { ...expected, result: 'green' },+ }]);+ assert.equal(prepared.engine, ENGINE_VERSION, 'new operations declare the current engine');+ move = { ...prepared, engine: 4 }; // Keep exercising the original engine-4 client.+ assert.equal(move.engine, 4);+ } finally { store.closeBoard(board); }+ const uploaded = await box.call(box.path + '/moves', {+ method: 'POST', headers, body: { sequence: 1, sealed: box.clientSeal(move, 'move', 1) },+ });+ assert.equal(uploaded.status, 200);+ const read = await box.call(box.path + '/events?after=0', { token: box.two.token, headers });+ assert.equal(read.status, 200);+ assert.equal(read.body.events.length, 1);+ const [record] = read.body.events;+ assert.deepEqual(record.sender, { kind: 'agent', userId: box.person.user.id, agent: 'client-one' });+ assert.deepEqual(box.clientOpen(record.sealed, record.kind, record.event_id), move);+ });+test('[A4,H7] two clients append sealed moves in one order and no plaintext or client key reaches storage', async (t) => {const box = await fixture(t);const listed = await box.call('/api/v1/boards');