Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(relay): run sealed person requests through CLI [H12]
Corey Olson095cc88aa1a4
diff --git a/docs/api.md b/docs/api.mdindex a3e04408..197b5b65 100644--- a/docs/api.md+++ b/docs/api.md@@ -197,3 +197,28 @@ HTTP refusals use the same versioned error envelope above: 400 for malformed calThe initial command output names `.pullboard/signers`, `.pullboard/first-commit` and `.pullboard/signers.initial` for staging and committing. Later sign-offs and signed signer-list changes are recorded in `.pullboard/signoffs.jsonl`; commit that file with the corresponding signer-list change.Every signed row and signer-list change binds the initial signer-list hash in its canonical text. Rewriting `.pullboard/signers.initial`, or relabelling that hash in earlier receipts, invalidates those receipts.++## Sealed person requests++A paired relay browser translates `add`, `shout`, `answer`, `hold` (including `args.off: true`), `spec-approve` and `spec-decline` into literal CLI intent. Its transport accepts `{verb, item?, args}` at the paired board's moves address and seals a separate request document before posting `{sequence, sealed}` to `/api/v1/boards/:board/requests`. It never sends plaintext arguments, an engine operation or the board key. The relay stores and orders that opaque envelope; it neither executes a command nor writes a repository. Agent credentials cannot submit person intent or person-attributed holds and releases.++The device-only request format is `{version: 1, type: "person-request", id, move: {verb, item?, args}}`. This request version is independent of the ordinary move engine version. The stable `id` survives interrupted sends and sequence collisions. Browser storage keeps each pending request's ciphertext separately, so another tab cannot replace or clear it. A later board read reconciles pending sends with the relay's acknowledged prefix before retrying.++The next ordinary local Pullboard command receives requests in relay order. One linked native device claims each request for ten minutes, measured exclusively from relay receipt timestamps, and runs its literal arguments through the actual CLI in the coordinator's primary checkout, outside the relay lock. Lane, brief, spec, person-channel and other CLI checks run there. Receiving a request never calls an engine operation directly. Its committed result travels as an ordinary move; durable request and move receipts prevent command retries from applying that result twice. A restarted device resumes its durable stages. After the executor lease expires, another linked device may claim the waiting request; each executor has distinct move ids, while the request’s atomic result and status prevent a late executor from creating another effect. Network or sign-in failures leave the request waiting.++Local `GET /api/v1/boards/:board/state` and the device-decrypted relay presentation expose additive `state.personRequests`. Each entry has:++| Field | Meaning |+| --- | --- |+| `id` | Stable request identity |+| `sequence`, `at` | Original relay position and timestamp |+| `by` | `person` for authenticated person intent; a refused sender names its authenticated actor |+| `move` | Literal `{verb, item?, args}`, or `null` for refused malformed input |+| `status` | `waiting`, `done` or `refused` |+| `error` | Present for refusal: the original `{code, message, next}` CLI guidance, or a typed format/sender refusal |+| `result`, `resultSequence` | Optional committed ordinary-move result and its relay position |+| `coordinatorRequest` | Optional local shout id for a repository-change request |++A browser action's decoded response is `{version: 1, event, result: {request}}`; `request` has the same status shape. `event` is the opaque acknowledgement, or `null` when reconciliation finds the earlier acknowledgement already in a sealed checkpoint. Direct actions become `done` when their actual CLI move commits. A refused add, for example, retains `UNKNOWN_SPEC` and the same explanation and next step as the terminal command, without creating an item. Answers always use the person channel; holds and releases keep the coordinator's execution guard while attributing the decision and event to the person.++Row approval and decline first record the person's exact decision through the same authenticated view boundary as the local view, without editing any file. They then create a person-to-coordinator request to run `spec apply`. That request is first in coordinator `resume` and `inbox`. Its status stays `waiting` until the coordinator applies it and answers `done`, or answers `declined <reason>`. Decline resolves the request as `refused` with `REQUEST_DECLINED`, the coordinator's reason and a next step. The browser and relay never run `spec apply`.diff --git a/relay/browser-client.js b/relay/browser-client.jsindex 6ab53d13..30e18297 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -1,11 +1,13 @@/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15]. */-import { decodeBoardKey, unseal } from './seal.js';+import { decodeBoardKey, seal, unseal } from './seal.js';+import { preparePersonRequest, validatePersonRequest } from './person-request.js';import { snapshotState, presentationState } from './model.js';import { ENGINE_VERSION } from './engine.js';import { Refused } from './refused.js';const KEYS = 'pullboard.relay.keys.v1';const PENDING = 'pullboard.relay.pair.v1';+const OUTBOX = 'pullboard.relay.requests.v1.';const BOARD = /^[0-9a-f]{32}$/;/** Read private browser storage without turning unavailable storage into a credential diagnostic. */@@ -35,13 +37,14 @@ function transportBytes(value) {}/** Fetch only same-origin API documents, retaining stable refusal guidance and no provider details. */-async function documentAt(path, onDenied) {- const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', redirect: 'error' });+async function documentAt(path, onDenied, options = {}) {+ const response = await fetch(path, { ...options, credentials: 'same-origin', cache: 'no-store', redirect: 'error' });const document = await response.json();if (!response.ok) {const error = document.error;if ([401, 403].includes(response.status) || error?.code === 'NO_BOARD') onDenied?.();- throw new Error(error ? '[' + error.code + '] ' + error.message : 'The relay did not answer. Sign in again or retry.');+ if (error) throw new Refused(error.code, error.message);+ throw new Refused('RELAY_UNAVAILABLE', 'The relay did not answer. Sign in again or retry.');}if (document.version !== 1) throw new Error('This relay API version is unsupported. Upgrade this browser client.');return document;@@ -75,7 +78,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {const element = document.getElementById('relay-notice');if (!element) return;element.replaceChildren();- const lines = ['Read-only relay view. Acting from the relay is coming.'];+ const lines = ['Requests from this device wait for a linked machine to run Pullboard.'];const unpaired = available.filter(board => !paired.has(board.id));for (const board of unpaired) lines.push(board.repository + ': pair this browser using a link or QR from a linked machine.');for (const warning of warnings) if (warning?.code === 'BOARD_INACTIVE' && Number.isInteger(warning.daysLeft)) {@@ -149,6 +152,21 @@ export async function createTransport({ onUpdate = () => {} } = {}) {const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: row.kind, sequence: row.event_id });const move = JSON.parse(new TextDecoder().decode(plain));if (accessLost) throw new Error('Sign in again to read this board.');+ if (row.kind === 'request') {+ let request;+ let error;+ try {+ request = validatePersonRequest(move);+ if (row.sender?.kind !== 'person' || typeof row.sender.userId !== 'string' || !row.sender.userId) throw new Refused('RELAY_PERSON_ONLY', 'Only the authenticated person sends requests. Sign in with the person session.');+ } catch (cause) { if (!(cause instanceof Refused)) throw cause; error = { code: cause.code, message: cause.message, next: 'Read the reason and send a revised request from the view.' }; }+ const record = { id: request?.id ?? 'refused-' + row.event_id, sequence: row.event_id, at: row.event_at,+ by: row.sender?.kind === 'person' ? 'person' : row.sender?.agent ?? '(unknown sender)',+ move: request?.move ?? null, status: error ? 'refused' : 'waiting', ...(error ? { error } : {}) };+ entry.state.personRequests ??= [];+ if (!entry.state.personRequests.some(value => value.id === record.id)) entry.state.personRequests.push(record);+ entry.cursor = row.event_id;+ return;+ }if (move.version !== 1 || !Number.isSafeInteger(move.engine) || move.engine < 1) throw new Error('This sealed move has an unsupported format. Refresh it from a linked machine.');if (move.engine !== ENGINE_VERSION) throw new Refused('RELAY_ENGINE_VERSION', 'This board needs engine ' + move.engine + '; this browser reads engine ' + ENGINE_VERSION + '. Upgrade the browser client.');if (move.presentation) {@@ -179,7 +197,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {entry.stream?.close();const stream = new EventSource('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor);entry.stream = stream;- entry.queue = Promise.resolve();+ entry.queue ??= Promise.resolve();stream.onmessage = event => {entry.queue = entry.queue.then(async () => {const document = JSON.parse(event.data);@@ -221,7 +239,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {const encoded = pair?.board === board.id ? pair.key : keys[board.id];if (!encoded) continue;try {- const entry = { id: board.id, key: decodeBoardKey(encoded), cursor: -1, state: null };+ const entry = { id: board.id, key: decodeBoardKey(encoded), cursor: -1, state: null, outbox: null };await snapshot(entry);await catchUp(entry);if (accessLost) throw new Error('Sign in again to read this board.');@@ -242,6 +260,94 @@ export async function createTransport({ onUpdate = () => {} } = {}) {};}+ /** Save only ciphertext on the device so an interrupted send retains its stable request id. */+ function saveOutbox(entry) {+ try {+ if (entry.outbox) localStorage.setItem(OUTBOX + entry.id + '.' + entry.outbox.id, JSON.stringify(entry.outbox));+ } catch { throw new Refused('REQUEST_STORAGE', 'This browser cannot save the sealed request. Enable device storage before sending it.'); }+ }++ /** Read each independently saved request so another tab cannot overwrite or clear its intent. */+ function pendingRequests(entry) {+ const values = [];+ try {+ const prefix = OUTBOX + entry.id + '.';+ for (let index = 0; index < localStorage.length; index += 1) {+ const key = localStorage.key(index);+ if (key?.startsWith(prefix)) {+ const value = stored(localStorage, key, null);+ if (!value || typeof value.id !== 'string' || key !== prefix + value.id) throw new Error('invalid saved request');+ values.push(value);+ }+ }+ } catch { throw new Refused('REQUEST_STORAGE', 'The browser cannot read its saved sealed requests. Restore device storage before sending again.'); }+ return values.sort((left, right) => left.sequence - right.sequence || left.id.localeCompare(right.id));+ }++ /** Remove only the acknowledged request's storage entry, preserving another tab's pending intent. */+ function acknowledge(entry, id) {+ try { localStorage.removeItem(OUTBOX + entry.id + '.' + id); }+ catch { throw new Refused('REQUEST_STORAGE', 'The request was received, but device storage could not record that acknowledgement. Retry this board.'); }+ entry.outbox = null;+ }++ /** Reconcile previously authorized sealed sends before returning state or accepting another action. */+ async function flushOutbox(entry) {+ for (const pending of pendingRequests(entry)) {+ entry.outbox = pending;+ await sendOutbox(entry);+ }+ }++ /** Serialize browser reads, sends and live events through the same per-board cursor owner. */+ function enqueue(entry, work) {+ const task = (entry.queue ?? Promise.resolve()).then(work);+ entry.queue = task.catch(() => {});+ return task;+ }++ /** Seal an unchanged intent at its current public sequence after another client wins the order. */+ async function requestEnvelope(entry, value, sequence) {+ const bytes = await seal(entry.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: entry.id, kind: 'request', sequence });+ let binary = '';+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return { id: value.id, sequence, sealed: btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '') };+ }++ /** Send a durable opaque intent, repairing order collisions without creating another request. */+ async function sendOutbox(entry) {+ const pending = entry.outbox;+ if (!pending) return null;+ const plain = await unseal(entry.key, transportBytes(pending.sealed), { boardId: entry.id, kind: 'request', sequence: pending.sequence });+ const value = validatePersonRequest(JSON.parse(new TextDecoder().decode(plain)));+ if (value.id !== pending.id) throw new Refused('REQUEST_STORAGE', 'The saved request is inconsistent. Pair this browser again.');+ for (let attempt = 0; attempt < 5; attempt += 1) {+ await snapshot(entry);+ await catchUp(entry);+ const received = entry.state.personRequests?.find(record => record.id === value.id);+ if (received) { acknowledge(entry, value.id); return { version: 1, event: null, result: { request: received } }; }+ if (entry.outbox.sequence !== entry.cursor + 1) {+ entry.outbox = await requestEnvelope(entry, value, entry.cursor + 1);+ saveOutbox(entry);+ }+ const envelope = entry.outbox;+ let response;+ try {+ response = await documentAt('/api/v1/boards/' + entry.id + '/requests', denied, {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sequence: envelope.sequence, sealed: envelope.sealed }),+ });+ } catch (error) { if (['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) continue; throw error; }+ if (response.event?.event_id !== envelope.sequence || response.event.kind !== 'request' || response.event.sealed !== envelope.sealed) throw new Refused('RELAY_RESPONSE', 'The relay acknowledgement differs from this request. Retry this board.');+ await receive(entry, response.event);+ const record = entry.state.personRequests.find(request => request.id === value.id);+ if (!record) throw new Refused('RELAY_RESPONSE', 'The request acknowledgement has no receipt. Retry this board.');+ acknowledge(entry, value.id);+ onUpdate();+ return { version: 1, event: response.event, result: { request: structuredClone(record) } };+ }+ throw new Refused('RELAY_BUSY', 'Other clients kept winning the relay order. Retry this saved request.');+ }+/** Pair a link opened in this already-loaded page as well as one opened on a fresh visit. */async function pairingChanged() {try { pair = rememberPairing() ?? pair; await listing(); onUpdate(); }@@ -251,21 +357,35 @@ export async function createTransport({ onUpdate = () => {} } = {}) {addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });await listing();return {- /** Supply the same decoded API documents as the local view, refusing every browser action. */+ /** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */async request(path, body) {- if (body !== undefined && body !== null) throw new Error('This is a read-only relay view. Acting from the relay is coming.');const url = new URL(path, location.origin);if (url.origin !== location.origin) throw new Error('Use this relay origin to read a board.');- if (url.pathname === '/api/v1/boards') return listing();- const match = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events)$/.exec(url.pathname);+ if (url.pathname === '/api/v1/boards') { if (body !== undefined && body !== null) throw new Refused('BAD_REQUEST', 'Send person intent to a paired board.'); return listing(); }+ const match = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events|moves|requests)$/.exec(url.pathname);const entry = match && paired.get(match[1]);if (!entry) throw new Error('Pair this browser to read that board.');- await entry.queue;- await snapshot(entry);- await catchUp(entry);- if (entry.stream?.readyState === EventSource.CLOSED) subscribe(entry);- if (match[2] === 'state') return { version: 1, state: entry.state };- return { version: 1, events: [...entry.state.events].reverse() };+ if (body !== undefined && body !== null) {+ if (!['moves', 'requests'].includes(match[2])) throw new Refused('BAD_REQUEST', 'Send person intent to this board’s moves endpoint.');+ const value = preparePersonRequest(body);+ const send = enqueue(entry, async () => {+ await flushOutbox(entry);+ await snapshot(entry); await catchUp(entry);+ entry.outbox = await requestEnvelope(entry, value, entry.cursor + 1);+ saveOutbox(entry);+ return sendOutbox(entry);+ });+ return send;+ }+ if (!['state', 'events'].includes(match[2])) throw new Refused('BAD_REQUEST', 'Read this board’s state or events endpoint.');+ return enqueue(entry, async () => {+ await flushOutbox(entry);+ await snapshot(entry);+ await catchUp(entry);+ if (entry.stream?.readyState === EventSource.CLOSED) subscribe(entry);+ if (match[2] === 'state') return { version: 1, state: entry.state };+ return { version: 1, events: [...entry.state.events].reverse() };+ });},};}diff --git a/relay/browser-page.js b/relay/browser-page.jsindex 67755c93..33b76926 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -27,6 +27,8 @@ export function createRelayBrowserHandler({ authenticate }) {['/relay/model.js', ['text/javascript', readFileSync(new URL('./browser-model.js', import.meta.url), 'utf8').replace("'../src/refused.js'", "'./refused.js'")]],['/relay/engine.js', ['text/javascript', 'export const ENGINE_VERSION = ' + ENGINE_VERSION + ';\n']],['/relay/seal.js', ['text/javascript', readFileSync(new URL('../src/seal.js', import.meta.url), 'utf8')]],+ ['/relay/api-moves.js', ['text/javascript', readFileSync(new URL('../src/api-moves.js', import.meta.url), 'utf8')]],+ ['/relay/person-request.js', ['text/javascript', readFileSync(new URL('../src/person-request.js', import.meta.url), 'utf8')]],['/relay/refused.js', ['text/javascript', readFileSync(new URL('../src/refused.js', import.meta.url), 'utf8')]],]);return async function handleBrowser(req, res) {diff --git a/src/api-moves.js b/src/api-moves.jsnew file mode 100644index 00000000..3f72fda0--- /dev/null+++ b/src/api-moves.js@@ -0,0 +1,58 @@+/** Literal API-to-CLI argument translation shared by native and sealed person requests [A2,H12]. */+import { Refused } from './refused.js';++/** Declarative CLI forms keep API calls on the same argument parser and engine as terminal moves. */+const MOVES = {+ 'spec-approve': { prefix: ['spec', 'approve'], positions: ['ids'], flags: ['by', 'text'] },+ 'spec-decline': { prefix: ['spec', 'decline'], positions: ['ids'], flags: ['reason'] },+ add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'] },+ edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'] },+ fact: { item: true, positions: ['kind', 'text'], flags: ['supersedes', 'ref'] },+ claim: { item: true },+ release: { item: true },+ submit: { item: true },+ done: { item: true },+ verify: { item: true, positions: ['decision'], flags: ['reason', 'note', 'as'] },+ merged: { item: true, positions: ['commit'] },+ withdraw: { item: true, positions: ['reason'] },+ refreeze: { item: true },+ escalate: { item: true, flags: ['note'] },+ hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },+ shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },+ answer: { item: true, positions: ['text'], flags: ['as'] },+ pass: { item: true, positions: ['note'] },+ next: { flags: ['as'], booleans: ['verify', 'build'] },+};++/** Reject unsupported fields, then pass values as distinct argv entries, never a shell command. */+export function moveArgs({ verb, item, args = {} }) {+ if (verb === 'accept' || verb === 'reject') return moveArgs({ verb: 'verify', item, args: { ...args, decision: verb } });+ const form = Object.hasOwn(MOVES, verb) ? MOVES[verb] : null;+ if (!form) throw new Refused('BAD_REQUEST', `no API move ${String(verb)}; use a board move such as add, claim, submit, verify, shout or answer`);+ if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Refused('BAD_REQUEST', 'args needs a JSON object containing this move\'s arguments');+ const allowed = [...(form.positions ?? []), ...(form.flags ?? []), ...(form.booleans ?? [])];+ for (const key of Object.keys(args)) if (!allowed.includes(key)) throw new Refused('BAD_REQUEST', `${verb} does not take args.${key}; use only this CLI move's arguments`);+ const argv = form.prefix ? [...form.prefix] : [verb];+ if (form.item) {+ if (!Number.isSafeInteger(item) || item < 1) throw new Refused('BAD_REQUEST', `${verb} needs a positive integer item; use the item id from the board state`);+ argv.push(String(item));+ } else if (item !== undefined && item !== null) throw new Refused('BAD_REQUEST', `${verb} does not take item; put its arguments in args`);+ const positional = [];+ for (const key of form.positions ?? []) {+ if (args[key] === undefined && form.optional?.includes(key)) continue;+ if (typeof args[key] !== 'string' || !args[key].trim()) throw new Refused('BAD_REQUEST', `${verb} needs args.${key} as nonempty text; supply the CLI move's argument`);+ positional.push(args[key]);+ }+ for (const key of form.flags ?? []) if (args[key] !== undefined) {+ if (typeof args[key] !== 'string') throw new Refused('BAD_REQUEST', `args.${key} needs text; supply the CLI flag's value`);+ argv.push(`--${key}=${args[key]}`);+ }+ for (const key of form.booleans ?? []) if (args[key] !== undefined) {+ if (typeof args[key] !== 'boolean') throw new Refused('BAD_REQUEST', `args.${key} needs true or false`);+ if (args[key]) argv.push(`--${key}`);+ }+ // Positionals follow -- so titles and notes beginning with a dash never become CLI flags.+ argv.push('--json', '--', ...positional);+ return argv;+}+diff --git a/src/api.js b/src/api.jsindex 29dbbd9b..2110b4b6 100644--- a/src/api.js+++ b/src/api.js@@ -14,6 +14,9 @@ import { projectRowDecisions } from './row-decisions.js';import { Refused } from './refused.js';import { codeAt, projectState } from './serve.js';import { createApiHandler } from './api-http.js';+import { moveArgs } from './api-moves.js';+import { personRequestStatuses } from './relay-requests.js';+export { moveArgs } from './api-moves.js';const ADDRESS = '127.0.0.1';const VERSION = 1;@@ -80,63 +83,8 @@ function agentPath(root, name = COORDINATOR) {});}-/** Declarative CLI forms keep API calls on the same argument parser and engine as terminal moves. */-const MOVES = {- 'spec-approve': { prefix: ['spec', 'approve'], positions: ['ids'], flags: ['by', 'text'] },- 'spec-decline': { prefix: ['spec', 'decline'], positions: ['ids'], flags: ['reason'] },- add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'] },- edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'] },- fact: { item: true, positions: ['kind', 'text'], flags: ['supersedes', 'ref'] },- claim: { item: true },- release: { item: true },- submit: { item: true },- done: { item: true },- verify: { item: true, positions: ['decision'], flags: ['reason', 'note', 'as'] },- merged: { item: true, positions: ['commit'] },- withdraw: { item: true, positions: ['reason'] },- refreeze: { item: true },- escalate: { item: true, flags: ['note'] },- hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },- shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },- answer: { item: true, positions: ['text'], flags: ['as'] },- pass: { item: true, positions: ['note'] },- next: { flags: ['as'], booleans: ['verify', 'build'] },-};--/** Reject unsupported fields, then pass values as distinct argv entries, never a shell command. */-export function moveArgs({ verb, item, args = {} }) {- if (verb === 'accept' || verb === 'reject') return moveArgs({ verb: 'verify', item, args: { ...args, decision: verb } });- const form = Object.hasOwn(MOVES, verb) ? MOVES[verb] : null;- if (!form) throw new Refused('BAD_REQUEST', `no API move ${String(verb)}; use a board move such as add, claim, submit, verify, shout or answer`);- if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Refused('BAD_REQUEST', 'args needs a JSON object containing this move\'s arguments');- const allowed = [...(form.positions ?? []), ...(form.flags ?? []), ...(form.booleans ?? [])];- for (const key of Object.keys(args)) if (!allowed.includes(key)) throw new Refused('BAD_REQUEST', `${verb} does not take args.${key}; use only this CLI move's arguments`);- const argv = form.prefix ? [...form.prefix] : [verb];- if (form.item) {- if (!Number.isSafeInteger(item) || item < 1) throw new Refused('BAD_REQUEST', `${verb} needs a positive integer item; use the item id from the board state`);- argv.push(String(item));- } else if (item !== undefined && item !== null) throw new Refused('BAD_REQUEST', `${verb} does not take item; put its arguments in args`);- const positional = [];- for (const key of form.positions ?? []) {- if (args[key] === undefined && form.optional?.includes(key)) continue;- if (typeof args[key] !== 'string' || !args[key].trim()) throw new Refused('BAD_REQUEST', `${verb} needs args.${key} as nonempty text; supply the CLI move's argument`);- positional.push(args[key]);- }- for (const key of form.flags ?? []) if (args[key] !== undefined) {- if (typeof args[key] !== 'string') throw new Refused('BAD_REQUEST', `args.${key} needs text; supply the CLI flag's value`);- argv.push(`--${key}=${args[key]}`);- }- for (const key of form.booleans ?? []) if (args[key] !== undefined) {- if (typeof args[key] !== 'boolean') throw new Refused('BAD_REQUEST', `args.${key} needs true or false`);- if (args[key]) argv.push(`--${key}`);- }- // Positionals follow -- so titles and notes beginning with a dash never become CLI flags.- argv.push('--json', '--', ...positional);- return argv;-}-/** Execute one actual CLI command and retain its emitted event without a latest-row race. */-async function executeMove(root, body, runCommand) {+export async function executeMove(root, body, runCommand) {if (Object.keys(body).some((key) => !['verb', 'item', 'args', 'agent'].includes(key))) throw new Refused('BAD_REQUEST', 'a move takes only verb, item, args and agent; remove the unknown fields');const argv = moveArgs(body);let cwd;@@ -204,11 +152,13 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =state.board = board.id;const projectData = withBoard(board.root, (db) => ({requests: store.openRequests(db),+ personRequests: personRequestStatuses(db),milestones: milestoneRoadmap(board.root, db),rowDecisions: store.rowDecisions(db),threads: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, store.itemThread(db, item.item_id)])),}));state.requests = projectData.requests;+ state.personRequests = projectData.personRequests;state.milestones = projectData.milestones;state = projectRowDecisions(projectData.rowDecisions, state);state.items = state.items.map((item) => ({ ...item, thread: projectData.threads.get(item.id) ?? [] }));diff --git a/src/board.js b/src/board.jsindex 97f7b2c2..73ce5896 100644--- a/src/board.js+++ b/src/board.js@@ -1762,10 +1762,12 @@ export function relatedItems(board, item, limit = 3) {** @param {any} board* @param {string} lane- * @param {{ agentId: string, reason: string }} hold+ * @param {{ agentId: string, reason: string, asPerson?: boolean, channel?: string }} hold*/-export function holdLane(board, lane, { agentId, reason }) {+export function holdLane(board, lane, { agentId, reason, asPerson = false, channel = 'terminal' }) {coordinatorOnly(agentId, 'holds a lane');+ if (asPerson && !['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_CHANNEL', 'record the person hold through the terminal or the view; run pullboard view');+ const by = asPerson ? PERSON : agentId;if (!String(reason ?? '').trim()) throw new Refused('USAGE', `a hold needs a reason: pullboard hold ${lane} --reason "why"`);atomic(board, () => {board.db@@ -1773,8 +1775,8 @@ export function holdLane(board, lane, { agentId, reason }) {`INSERT INTO hold (hold_lane, hold_reason, hold_by, hold_at) VALUES (?, ?, ?, ?)ON CONFLICT (hold_lane) DO UPDATE SET hold_reason = excluded.hold_reason, hold_by = excluded.hold_by, hold_at = excluded.hold_at`,)- .run(lane, reason.trim(), agentId, now(board));- logEvent(board, agentId, 'hold', null, { lane, reason: reason.trim() });+ .run(lane, reason.trim(), by, now(board));+ logEvent(board, by, 'hold', null, { lane, reason: reason.trim(), ...(asPerson ? { channel } : {}) });});}@@ -1783,14 +1785,16 @@ export function holdLane(board, lane, { agentId, reason }) {** @param {any} board* @param {string} lane- * @param {{ agentId: string }} who+ * @param {{ agentId: string, asPerson?: boolean, channel?: string }} who*/-export function releaseLane(board, lane, { agentId }) {+export function releaseLane(board, lane, { agentId, asPerson = false, channel = 'terminal' }) {coordinatorOnly(agentId, 'releases a lane');+ if (asPerson && !['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_CHANNEL', 'record the person release through the terminal or the view; run pullboard view');+ const by = asPerson ? PERSON : agentId;atomic(board, () => {const { changes } = board.db.prepare('DELETE FROM hold WHERE hold_lane = ?').run(lane);if (!changes) throw new Refused('NOT_HELD', `the ${lane} lane is not held`);- logEvent(board, agentId, 'unhold', null, { lane });+ logEvent(board, by, 'unhold', null, { lane, ...(asPerson ? { channel } : {}) });});}diff --git a/src/cli.js b/src/cli.jsindex 9d3bfd18..a2ea15c5 100644--- a/src/cli.js+++ b/src/cli.js@@ -61,6 +61,7 @@ import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';import { relayLinked, relayOff, relayOn, relayOperation, relayStatus, syncRelay } from './relay.js';+import { executePersonRequests } from './relay-request-execution.js';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));export const VERSION = PACKAGE.version;@@ -1763,7 +1764,7 @@ function workCommands(io, args) {const after = idList(values.after).map((text) => idArg(text, 'an item id after --after'));const title = [second, ...rest].filter(Boolean).join(' ');const item = {- by: me.id,+ by: io.personRequest?.phase === 'execute' ? store.PERSON : me.id,lane: first,title,criterion: values.criterion ?? '',@@ -1854,10 +1855,10 @@ function workCommands(io, args) {hold: () => act(async (ctx, board, me) => {if (!first || !isLane(ctx.config, first)) throw new Refused('NO_LANE', `no lane "${first ?? ''}"; see: pullboard lanes`);if (values.off) {- await ordered(ctx, board, 'releaseLane', [first, { agentId: me.id }]);+ await ordered(ctx, board, 'releaseLane', [first, { agentId: me.id, asPerson: io.personChannel === 'view', channel: io.personChannel ?? 'terminal' }]);io.say(`released the ${first} lane`);} else {- await ordered(ctx, board, 'holdLane', [first, { agentId: me.id, reason: values.reason ?? '' }]);+ await ordered(ctx, board, 'holdLane', [first, { agentId: me.id, reason: values.reason ?? '', asPerson: io.personChannel === 'view', channel: io.personChannel ?? 'terminal' }]);io.say(`holding the ${first} lane: ${values.reason}. Release it with: pullboard hold ${first} --off`);}io.result?.({ lane: first, held: !values.off, reason: values.off ? null : values.reason });@@ -1898,7 +1899,7 @@ function workCommands(io, args) {const hasRecipient = first && recipients.includes(first);const to = hasRecipient ? first : values.decision ? (me.id === COORDINATOR ? 'person' : COORDINATOR) : first ?? '';const text = [hasRecipient ? second : first, ...(hasRecipient ? rest : [second, ...rest])].filter(Boolean).join(' ');- const id = await ordered(ctx, board, 'shout', [{ from: me.id, to, text, lanes: laneNames(ctx.config), decision: Boolean(values.decision), evidence }]);+ const id = await ordered(ctx, board, 'shout', [{ from: io.personRequest?.phase === 'execute' ? store.PERSON : me.id, to, text, lanes: laneNames(ctx.config), decision: Boolean(values.decision), evidence }]);io.result?.({ id, decision: Boolean(values.decision) });io.say(values.decision ? `asked ${to} for a decision as #${id}; it stays open until someone runs: pullboard answer ${id} "<the decision>"` : `shouted to ${to}`);return 0;@@ -2295,7 +2296,7 @@ async function runCommand(argv, io) {if (command === 'relay') {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);+ 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);@@ -2340,7 +2341,11 @@ export async function main(argv, streams) {if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);}};- if (sync) await retry();+ if (sync) {+ await retry();+ try { await executePersonRequests(io.cwd, io, main); }+ catch (error) { if (!(error instanceof Refused)) throw error; io.err('pullboard: ' + error.message); }+ }const code = await runCommand(argv, io);if (sync && code === 0) await retry();io.flush(code);diff --git a/src/engine.js b/src/engine.jsindex 0e0e3cdb..aa913388 100644--- a/src/engine.js+++ b/src/engine.js@@ -4,6 +4,7 @@ import * as store from './board.js';import { refusalDocument } from './json.js';import { ENGINE_VERSION } from './machine.js';import { Refused } from './refused.js';+import { requestMoveProblem, recordRequestMove } from './relay-requests.js';import { relayMoveActor, relaySenderProblem } from './relay-sender.js';/** Only these public board operations may be requested by an encrypted move. */@@ -74,7 +75,7 @@ export function prepareEngineMove(board, operation, args, { id = randomUUID() }}/** Stop before interpreting actors or operations that a newer engine may have changed. */-function requireSupportedEngine(move) {+export function requireSupportedEngine(move) {if (Number.isSafeInteger(move?.engine) && move.engine > ENGINE_VERSION) throw new Refused('ENGINE_VERSION', `move engine version ${move.engine} is newer than this pullboard engine version ${ENGINE_VERSION}; upgrade pullboard before applying the relay order`);}@@ -167,12 +168,17 @@ export function applyEngineMove(board, move, { sequence, at }) {board.clock = { now: () => new Date(at) };const firstEvent = board.emittedEvents?.length ?? 0;try {- const result = store.atomic(board, () => store[move.operation](board, ...executableArgs(move)));+ const result = store.atomic(board, () => {+ const problem = requestMoveProblem(board, move);+ if (problem) throw problem;+ return store[move.operation](board, ...executableArgs(move));+ });outcome = { result: result ?? null, events: (board.emittedEvents?.slice(firstEvent) ?? []).map((event) => ({ ...event })) };} catch (error) {if (!(error instanceof Refused)) throw error;outcome = { error: refusalDocument(error).error };} finally { board.clock = clock; }+ recordRequestMove(board, move, outcome, sequence, at);metadata(board, 'relay_receipt_' + move.id, JSON.stringify({ sequence, move: encoded, outcome }));}metadata(board, 'relay_applied_sequence', String(sequence));diff --git a/src/person-request.js b/src/person-request.jsnew file mode 100644index 00000000..06f50cb9--- /dev/null+++ b/src/person-request.js@@ -0,0 +1,42 @@+/** Browser-sealed person intent is CLI input, never an executable engine move [H12,H16]. */+import { moveArgs } from './api-moves.js';+import { Refused } from './refused.js';++export const PERSON_REQUEST_VERSION = 1;+const VERBS = Object.freeze(['add', 'shout', 'answer', 'hold', 'spec-approve', 'spec-decline']);++/** Validate a narrow person intent while retaining literal arguments for the actual CLI parser. */+export function personRequestMove(body) {+ if (!body || typeof body !== 'object' || Array.isArray(body)+ || Object.keys(body).some(key => !['verb', 'item', 'args'].includes(key))+ || !VERBS.includes(body.verb)) {+ throw new Refused('BAD_REQUEST', 'a person request takes add, shout, answer, hold, spec-approve or spec-decline with item and args; use the view controls');+ }+ const move = structuredClone(body);+ move.args ??= {};+ if (typeof move.args !== 'object' || Array.isArray(move.args)) throw new Refused('BAD_REQUEST', 'args needs the move arguments as a JSON object; use the view controls');+ if (move.verb === 'answer') {+ if (move.args.as !== undefined && move.args.as !== 'person') throw new Refused('B26_PERSON_ANSWER', 'the relay person answers as person; use the view to answer the decision');+ move.args.as = 'person';+ }+ moveArgs(move);+ return move;+}++/** Create the distinct versioned request document before the browser seals it for request-kind AAD. */+export function preparePersonRequest(body, id = crypto.randomUUID()) {+ const document = { version: PERSON_REQUEST_VERSION, type: 'person-request', id, move: personRequestMove(body) };+ return validatePersonRequest(document);+}++/** Refuse malformed or newer request formats before any CLI can interpret their intent. */+export function validatePersonRequest(document) {+ if (document?.version !== PERSON_REQUEST_VERSION || document?.type !== 'person-request') {+ throw new Refused('PERSON_REQUEST_VERSION', 'this person request format is unsupported; upgrade Pullboard on the browser and linked machine');+ }+ if (typeof document.id !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(document.id)+ || Object.keys(document).some(key => !['version', 'type', 'id', 'move'].includes(key))) {+ throw new Refused('BAD_REQUEST', 'a sealed person request needs its stable id and literal move; reload the paired view and retry');+ }+ return { version: PERSON_REQUEST_VERSION, type: 'person-request', id: document.id, move: personRequestMove(document.move) };+}diff --git a/src/relay-presentation.js b/src/relay-presentation.jsindex 9b98342c..3324f936 100644--- a/src/relay-presentation.js+++ b/src/relay-presentation.js@@ -7,13 +7,14 @@ import { repoInfo } from './git.js';import { Refused } from './refused.js';import { loadConfig } from './config.js';import { projectState } from './serve.js';+import { personRequestStatuses } from './relay-requests.js';/** Capture spec, doctrine, config and board presentation without sending plaintext to a relay. */export function relayPresentation(root) {const state = projectState(root);const info = repoInfo(root);const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));- try { return { version: 1, state: store.projectItemThreads(board, state), config: loadConfig(root) }; }+ try { return { version: 1, state: { ...store.projectItemThreads(board, state), personRequests: personRequestStatuses(board) }, config: loadConfig(root) }; }finally { store.closeBoard(board); }}diff --git a/src/relay-request-execution.js b/src/relay-request-execution.jsnew file mode 100644index 00000000..7d23019e--- /dev/null+++ b/src/relay-request-execution.js@@ -0,0 +1,83 @@+/** Native person requests run the actual CLI outside the relay lock [H12,H16]. */+import { createHash, randomUUID } from 'node:crypto';+import { join } from 'node:path';+import * as store from './board.js';+import { executeMove } from './api.js';+import { loadConfig } from './config.js';+import { git, repoInfo } from './git.js';+import { laneNames } from './lanes.js';+import { refusalDocument } from './json.js';+import { Refused } from './refused.js';+import { relayLinked, relayOperation, relayRequestDevice } from './relay.js';+import { personRequestRecords } from './relay-requests.js';++/** Read durable intake without retaining a SQLite connection while the CLI runs. */+function requests(root) {+ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'));+ try { return personRequestRecords(board).filter(record => !record.duplicateOf); }+ finally { store.closeBoard(board); }+}++/** Give each request stage one stable ordinary-move id across command and device retries. */+function stageId(id, phase, executor) {+ return 'person-request-' + createHash('sha256').update(JSON.stringify([id, phase, executor])).digest('hex');+}++/** Publish an ordinary person shout as a durable intake, coordinator request or refusal receipt. */+async function receipt(root, record, executor, phase, io, error) {+ const text = phase === 'claim' ? 'Received a request from the paired view.'+ : phase === 'refuse' ? '[' + error.code + '] ' + error.message+ : 'Apply the person’s recorded row decision with pullboard spec apply, or decline this request with a reason. '+ + record.move.verb + ': ' + record.move.args.ids;+ const message = { from: 'person', to: 'coordinator', text: 'View request ' + record.id + ': ' + text, lanes: laneNames(loadConfig(root)), ...(phase === 'repo-request' ? { request: true } : {}) };+ return relayOperation(root, 'shout', [message], {+ ...io, personRequest: { id: record.id, executor, phase, ...(error ? { error } : {}) },+ personRequestMoveId: phase === 'claim' && record.executor && record.executor !== executor ? randomUUID() : stageId(record.id, phase, executor),+ });+}++/** Transport authorization and ordering failures leave intent waiting for a reachable signed-in device. */+function transportRefusal(error) {+ return /^(?:RELAY_|AUTH_|TOKEN_|BOARD_|PAIR_|SEQUENCE_)/u.test(error.code) || ['NO_REPO_ACCESS', 'NO_BOARD'].includes(error.code);+}++/** Fulfil queued browser intent once on its elected native device, preserving actual CLI refusals. */+export async function executePersonRequests(root, io, runCommand) {+ if (io.skipPersonRequests || !relayLinked(root)) return;+ const coordinatorRoot = git(root, ['worktree', 'list', '--porcelain']).split('\n')[0].slice('worktree '.length);+ const pending = requests(coordinatorRoot).filter(record => record.status === 'waiting' && !record.coordinatorRequest);+ if (!pending.length) return;+ const executor = await relayRequestDevice(coordinatorRoot);+ if (!executor) return;+ for (const initial of pending) {+ if (initial.status !== 'waiting') continue;+ try {+ if (initial.executor !== executor) await receipt(coordinatorRoot, initial, executor, 'claim', io);+ const record = requests(coordinatorRoot).find(entry => entry.id === initial.id);+ if (record.executor !== executor || record.status !== 'waiting') continue;+ if (!Object.hasOwn(record, 'result')) {+ const response = await executeMove(coordinatorRoot, record.move, (argv, streams) => runCommand(argv, {+ ...streams, skipPersonRequests: true,+ personRequest: { id: record.id, executor, phase: 'execute' },+ personRequestMoveId: stageId(record.id, 'execute', executor),+ }));+ if (response.status !== 200) {+ const error = response.body.error;+ if (transportRefusal(error) || error.code === 'PERSON_REQUEST_TAKEN') continue;+ if (requests(coordinatorRoot).find(entry => entry.id === record.id)?.status === 'waiting') await receipt(coordinatorRoot, record, executor, 'refuse', io, error);+ continue;+ }+ }+ const completed = requests(coordinatorRoot).find(entry => entry.id === record.id);+ if (['spec-approve', 'spec-decline'].includes(record.move.verb) && completed.status === 'waiting' && !completed.coordinatorRequest) {+ await receipt(coordinatorRoot, completed, executor, 'repo-request', io);+ }+ } catch (error) {+ if (!(error instanceof Refused)) throw error;+ if (['PERSON_REQUEST_TAKEN', 'PERSON_REQUEST_CLOSED', 'RELAY_PERSON_ONLY'].includes(error.code)) continue;+ if (transportRefusal(error)) { io.err('pullboard: ' + error.message); continue; }+ const record = requests(coordinatorRoot).find(entry => entry.id === initial.id);+ if (record?.executor === executor && record.status === 'waiting') await receipt(coordinatorRoot, record, executor, 'refuse', io, refusalDocument(error).error);+ }+ }+}diff --git a/src/relay-requests.js b/src/relay-requests.jsnew file mode 100644index 00000000..b48f3acc--- /dev/null+++ b/src/relay-requests.js@@ -0,0 +1,161 @@+/** Durable sealed request intake and ordinary-move receipts; no replica executes CLI intent [H12,H16]. */+import * as store from './board.js';+import { refusalDocument } from './json.js';+import { Refused } from './refused.js';+import { validatePersonRequest } from './person-request.js';+import { relayMoveActor } from './relay-sender.js';++const INDEX = 'relay_person_requests';++/** Read all durable request receipts so an offline browser can still resolve an old request. */+export function personRequestRecords(board) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(INDEX);+ return row ? JSON.parse(row.meta_value) : [];+}++/** Persist request receipts inside the caller's existing board transaction. */+function save(board, records) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value').run(INDEX, JSON.stringify(records));+}++/** Consume a request position atomically without running its command or touching a repository. */+export function receivePersonRequest(board, document, { sequence, at, sender }) {+ if (!Number.isSafeInteger(sequence) || sequence < 1 || !Number.isFinite(Date.parse(at))) throw new Refused('RELAY_MOVE', 'a request needs the relay sequence and timestamp; restore a consistent prefix');+ return store.atomic(board, () => {+ const cursor = Number(board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('relay_applied_sequence')?.meta_value ?? 0);+ const records = personRequestRecords(board);+ const received = JSON.stringify({ document, sender });+ const existingPosition = records.find(record => record.sequence === sequence);+ if (sequence <= cursor) {+ if (!existingPosition || existingPosition.received !== received) throw new Refused('RELAY_CURSOR', 'the earlier request has no durable receipt; restore a consistent snapshot');+ return existingPosition;+ }+ if (sequence !== cursor + 1) throw new Refused('RELAY_ORDER', 'fetch the missing relay prefix before receiving this request');+ let request;+ let error;+ try {+ if (sender?.kind !== 'person' || typeof sender.userId !== 'string' || !sender.userId || sender.userId.length > 256) throw new Refused('RELAY_PERSON_ONLY', 'only the authenticated person can send a relay request; use the paired view with the person session');+ request = validatePersonRequest(document);+ } catch (cause) {+ if (!(cause instanceof Refused)) throw cause;+ error = refusalDocument(cause).error;+ }+ const id = request?.id ?? (typeof document?.id === 'string' && /^[A-Za-z0-9_-]{1,80}$/u.test(document.id) ? document.id : 'refused-' + sequence);+ const previous = records.find(record => record.id === id);+ const encoded = JSON.stringify(request ?? document);+ let record;+ if (previous && !error && previous.encoded === encoded) {+ record = { ...previous, sequence, received, duplicateOf: previous.sequence };+ } else {+ if (previous) error = refusalDocument(new Refused('PERSON_REQUEST_ID', 'this request id already names different intent; reload the paired view and send a new request')).error;+ record = { id: previous ? id + '-' + sequence : id, sequence, at, by: sender?.kind === 'person' ? 'person' : sender?.agent ?? '(unknown sender)', move: request?.move ?? null,+ encoded, received, status: error ? 'refused' : 'waiting', ...(error ? { error } : {}) };+ if (error) {+ const clock = board.clock;+ board.clock = { now: () => new Date(at) };+ try { store.recordRelayRefusal(board, { by: sender?.kind === 'agent' ? sender.agent : 'person', sequence, kind: 'request', operation: document?.operation ?? null, actor: relayMoveActor(document), code: error.code }); }+ finally { board.clock = clock; }+ }+ }+ save(board, [...records, record]);+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value').run('relay_applied_sequence', String(sequence));+ return record;+ });+}++/** Compare the requested literal arguments with the ordinary effect produced by the CLI. */+function fulfilsIntent(record, move) {+ const intent = record.move;+ const args = intent.args;+ const value = move.args[0];+ const options = move.args[1];+ if (intent.verb === 'add') return value?.by === 'person' && value.lane === args.lane && value.title === args.title+ && value.criterion === (args.criterion ?? '') && value.brief === (args.brief ?? '')+ && value.route === (args.route ?? 'strong')+ && JSON.stringify(value.specIds) === JSON.stringify((args.specs ?? '').split(',').map(id => id.trim()).filter(Boolean));+ if (intent.verb === 'shout') return value?.from === 'person' && value.text === args.text+ && (args.to === undefined || value.to === args.to) && Boolean(value.decision) === Boolean(args.decision);+ if (intent.verb === 'answer') return value === intent.item && options?.asPerson === true && options.channel === 'view' && options.text === args.text;+ if (intent.verb === 'hold') return value === args.lane && options?.asPerson === true && options.channel === 'view'+ && (args.off || options.reason === (args.reason ?? ''));+ const rows = value?.decisions;+ const ids = args.ids.split(/[\s,]+/u).filter(Boolean);+ return value?.agentId === 'person' && value.channel === 'view' && Array.isArray(rows) && rows.length === ids.length+ && rows.every((row, index) => (row.kind === 'doctrine' ? 'doctrine:' : '') + row.id === ids[index]+ && row.decision === (intent.verb === 'spec-approve' ? 'approve' : 'decline')+ && (intent.verb !== 'spec-decline' || row.reason === args.reason.trim())+ && (args.text === undefined || row.text === args.text.trim()));+}++/** Require an existing person intent and its first elected native executor before an ordinary move. */+export function requestMoveProblem(board, move) {+ const tag = move.personRequest;+ if (!tag) return null;+ if (!tag || typeof tag !== 'object' || typeof tag.id !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(tag.id)+ || Object.keys(tag).some(key => !['id', 'executor', 'phase', 'error'].includes(key)) || typeof tag.executor !== 'string'+ || !/^[A-Za-z0-9_-]{1,80}$/u.test(tag.executor) || !['claim', 'execute', 'repo-request', 'refuse'].includes(tag.phase)) {+ return new Refused('PERSON_REQUEST_RECEIPT', 'the request receipt is malformed; upgrade the linked machine before fulfilling requests');+ }+ const record = personRequestRecords(board).find(entry => entry.id === tag.id && !entry.duplicateOf);+ if (!record || record.status !== 'waiting') return new Refused('PERSON_REQUEST_CLOSED', 'this request is missing or already resolved; read its original receipt');+ const actor = relayMoveActor(move);+ if (!['coordinator', 'person'].includes(actor)) return new Refused('PERSON_REQUEST_RECEIPT', 'only the coordinator fulfils an authenticated person request');+ if (tag.phase === 'execute') {+ const expected = { add: 'addItem', shout: 'shout', answer: 'answerDecision', hold: record.move.args.off ? 'releaseLane' : 'holdLane', 'spec-approve': 'recordRowDecisions', 'spec-decline': 'recordRowDecisions' }[record.move.verb];+ if (move.operation !== expected || !fulfilsIntent(record, move)) return new Refused('PERSON_REQUEST_RECEIPT', 'the ordinary move does not fulfil this request; execute its original CLI intent');+ }+ if (['claim', 'repo-request', 'refuse'].includes(tag.phase) && !(move.operation === 'shout' && move.args[0]?.from === 'person' && move.args[0]?.to === 'coordinator'+ && move.args[0]?.text?.startsWith('View request ' + tag.id + ': '))) return new Refused('PERSON_REQUEST_RECEIPT', 'publish the original person request stage with its matching id');+ if (tag.phase === 'refuse' && !['code', 'message', 'next'].every(key => typeof tag.error?.[key] === 'string' && tag.error[key])) return new Refused('PERSON_REQUEST_RECEIPT', 'publish the original CLI refusal code, reason and next step');+ if (tag.phase === 'repo-request' && !(move.args[0]?.from === 'person' && move.args[0]?.to === 'coordinator' && move.args[0]?.request)) return new Refused('PERSON_REQUEST_RECEIPT', 'repo changes must reach the coordinator as a person request');+ if (tag.phase === 'claim') {+ if (move.operation !== 'shout') return new Refused('PERSON_REQUEST_RECEIPT', 'claim a request with its ordinary coordinator receipt');+ if (record.executor && record.executor !== tag.executor && Date.parse(record.executorUntil ?? record.at) > board.clock.now().getTime()) return new Refused('PERSON_REQUEST_TAKEN', 'another linked machine is fulfilling this request; wait for its receipt');+ } else if (record.executor !== tag.executor) {+ return new Refused('PERSON_REQUEST_TAKEN', 'this linked machine did not win the request; wait for its original receipt');+ }+ if (['claim', 'repo-request', 'refuse'].includes(tag.phase) && move.operation !== 'shout') return new Refused('PERSON_REQUEST_RECEIPT', 'publish this request stage with an ordinary coordinator receipt');+ return null;+}++/** Associate an ordinary move's committed outcome with its request in the same transaction. */+export function recordRequestMove(board, move, outcome, sequence, at) {+ const tag = move.personRequest;+ if (!tag || outcome.error?.code?.startsWith('PERSON_REQUEST_')) return;+ const records = personRequestRecords(board);+ const index = records.findIndex(entry => entry.id === tag.id && !entry.duplicateOf);+ if (index < 0) return;+ const record = { ...records[index] };+ if (tag.phase === 'claim') {+ if (!outcome.error) {+ record.executor = tag.executor;+ record.executorUntil = new Date(Date.parse(at) + 10 * 60 * 1000).toISOString();+ }+ } else if (outcome.error || tag.phase === 'refuse') {+ record.status = 'refused';+ record.error = outcome.error ?? tag.error;+ } else if (tag.phase === 'execute') {+ record.result = outcome.result;+ record.resultSequence = sequence;+ if (!['spec-approve', 'spec-decline'].includes(record.move.verb)) record.status = 'done';+ } else if (tag.phase === 'repo-request') {+ record.coordinatorRequest = outcome.result;+ }+ records[index] = record;+ save(board, records);+}++/** Project the coordinator's final answer alongside direct CLI success or refusal receipts. */+export function personRequestStatuses(board) {+ return personRequestRecords(board).filter(record => !record.duplicateOf).map(record => {+ const { encoded, received, executor, executorUntil, ...publicRecord } = record;+ if (record.coordinatorRequest && record.status === 'waiting') {+ const answer = board.db.prepare("SELECT * FROM shout WHERE shout_answers=? AND shout_request_outcome != '' ORDER BY shout_id LIMIT 1").get(record.coordinatorRequest);+ if (answer) {+ publicRecord.status = answer.shout_request_outcome === 'done' ? 'done' : 'refused';+ if (publicRecord.status === 'refused') publicRecord.error = { code: 'REQUEST_DECLINED', message: answer.shout_text.replace(/^declined\s*/u, ''), next: 'Read the coordinator reason and send a revised request from the view.' };+ }+ }+ return publicRecord;+ });+}diff --git a/src/relay-sender.js b/src/relay-sender.jsindex a362c0a9..5ac1a9da 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -7,6 +7,7 @@ export function relayMoveActor(move) {if (!Array.isArray(args)) return null;if (move.operation === 'addItem') return args[0]?.by ?? null;if (move.operation === 'shout') return args[0]?.from ?? null;+ if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';if (move.operation === 'release') return args[1] ?? null;if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions'].includes(move.operation)) return args[0]?.agentId ?? null;if (['appendFact', 'editItem', 'escalate', 'recordAttempt', 'claim', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze',diff --git a/src/relay.js b/src/relay.jsindex 0aec80bf..ffab2980 100644--- a/src/relay.js+++ b/src/relay.js@@ -4,7 +4,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, wriimport { dirname, join } from 'node:path';import * as store from './board.js';import { exportBoard, restoreRelaySnapshot } from './exchange.js';-import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, startRelayEpoch } from './engine.js';+import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, requireSupportedEngine, startRelayEpoch } from './engine.js';import { ENGINE_VERSION } from './machine.js';import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';import { repoInfo, tryGit } from './git.js';@@ -13,6 +13,7 @@ import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';import { terminalQr } from './qr.js';import { Refused } from './refused.js';import { relaySenderProblem } from './relay-sender.js';+import { receivePersonRequest } from './relay-requests.js';export const DEFAULT_RELAY = 'https://app.pullboard.dev';const LINK_FILES = new WeakMap();@@ -341,8 +342,11 @@ async function catchUp(root, file, state, io) {}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);localRecords(root, (board) => {- applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind });+ if (record.kind === 'request') receivePersonRequest(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender });+ else applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind });});}state.sequence = localRecords(root, appliedSequence);@@ -384,7 +388,14 @@ export async function relayOperation(root, operation, args, io) {delete state.pending;saveLink(file, state);}- const move = localRecords(root, (board) => prepareEngineMove(board, operation, args));+ const previousReceipt = io.personRequestMoveId && localRecords(root, board => engineReceipt(board, io.personRequestMoveId));+ if (previousReceipt) {+ if (previousReceipt.outcome.error) throw new Refused(previousReceipt.outcome.error.code, previousReceipt.outcome.error.message);+ for (const event of previousReceipt.outcome.events ?? []) io.onEvent?.(event);+ return previousReceipt.outcome.result;+ }+ const move = localRecords(root, (board) => prepareEngineMove(board, operation, args, io.personRequestMoveId ? { id: io.personRequestMoveId } : {}));+ if (io.personRequest) move.personRequest = structuredClone(io.personRequest);const sequence = state.sequence + 1;state.pending = { move, sequence, sealed: await sealedRecord(readBoardKey(state.board), move, state, 'move', sequence) };saveLink(file, state);@@ -521,3 +532,16 @@ export async function relayOff(root, io) {...(state.alreadyDeleted ? { alreadyDeleted: true, notice: 'the relay had already deleted this board; this device is unlinked and the local board is complete' } : {}) };});}+++/** Keep the elected native executor stable across processes while other worktrees share its link. */+export async function relayRequestDevice(root) {+ const file = linkFile(root);+ if (!existsSync(file)) return null;+ return locked(file, async () => {+ const state = loadLink(file);+ if (!state || state.unlinking) return null;+ if (!state.requestDevice) { state.requestDevice = randomUUID(); saveLink(file, state); }+ return state.requestDevice;+ });+}diff --git a/test/person-request-receipts.test.js b/test/person-request-receipts.test.jsnew file mode 100644index 00000000..06f60a04--- /dev/null+++ b/test/person-request-receipts.test.js@@ -0,0 +1,167 @@+/** Durable relay intake and tagged coordinator outcomes use real SQLite receipts [H12,H16]. */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { COORDINATOR } from '../src/config.js';+import { appliedSequence, applyEngineMove, engineReceipt, prepareEngineMove } from '../src/engine.js';+import { refusalDocument } from '../src/json.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { preparePersonRequest } from '../src/person-request.js';+import { Refused } from '../src/refused.js';+import { personRequestRecords, personRequestStatuses, receivePersonRequest } from '../src/relay-requests.js';++const at = '2026-10-08T12:34:56.000Z';+const person = { kind: 'person', userId: 'github-person-1' };++/** Give each test a real, reopenable SQLite board and remove all side files afterward. */+function fixture(t) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-person-request-receipts-'));+ const file = join(directory, 'board.sqlite');+ let board = store.openBoard(file);+ store.register(board, { lane: COORDINATOR, path: join(directory, 'coordinator') });+ t.after(() => {+ try { store.closeBoard(board); } catch { /* A test may have closed before its final reopen. */ }+ rmSync(directory, { recursive: true, force: true });+ });+ return {+ get board() { return board; },+ reopen() { store.closeBoard(board); board = store.openBoard(file); return board; },+ };+}++/** Build a stable, versioned request in the exact form emitted by the paired browser. */+function request(id, title = 'Requested change') {+ return preparePersonRequest({ verb: 'add', args: { lane: 'web', title } }, id);+}++/** Build the ordinary engine move used to claim a request on the coordinator device. */+function claimMove(board, id, executor, moveId = 'claim-stage') {+ const move = prepareEngineMove(board, 'shout', [{+ from: 'person', to: 'coordinator', text: 'View request ' + id + ': Received a request from the paired view.', lanes: [],+ }], { id: moveId });+ move.personRequest = { id, executor, phase: 'claim' };+ return move;+}++test('[H12,H16] intake advances atomically and survives reopen, duplicates, and malformed senders', t => {+ const box = fixture(t);+ const initial = request('retry-1');+ assert.equal(receivePersonRequest(box.board, initial, { sequence: 1, at, sender: person }).status, 'waiting');+ assert.equal(appliedSequence(box.board), 1);++ const board = box.reopen();+ assert.throws(() => receivePersonRequest(board, request('retry-1', 'Changed earlier position'), { sequence: 1, at, sender: person }), error => error.code === 'RELAY_CURSOR');+ assert.equal(appliedSequence(board), 1, 'the replay cursor survives closing and reopening SQLite');+ const duplicate = receivePersonRequest(board, initial, { sequence: 2, at, sender: person });+ assert.equal(duplicate.duplicateOf, 1, 'the retry keeps the original request receipt');+ assert.equal(personRequestRecords(board).filter(record => !record.duplicateOf).length, 1);++ const changed = receivePersonRequest(board, request('retry-1', 'Changed intent'), { sequence: 3, at, sender: person });+ assert.equal(changed.status, 'refused');+ assert.equal(changed.error.code, 'PERSON_REQUEST_ID');++ const malformed = receivePersonRequest(board, {+ version: 1, type: 'person-request', id: 'engine-shaped',+ move: { operation: 'addItem', args: [{ by: 'coordinator', lane: 'web', title: 'Must not execute' }] },+ }, { sequence: 4, at, sender: person });+ assert.equal(malformed.status, 'refused');+ assert.equal(malformed.error.code, 'BAD_REQUEST');+ assert.deepEqual(store.listItems(board, { all: true }), [], 'an engine-shaped request never becomes a board action');++ const agentRequest = receivePersonRequest(board, request('agent-1'), {+ sequence: 5, at, sender: { kind: 'agent', userId: 'github-person-1', agent: 'remote-1' },+ });+ assert.equal(agentRequest.status, 'refused');+ assert.equal(agentRequest.error.code, 'RELAY_PERSON_ONLY');++ const before = personRequestRecords(board);+ assert.throws(() => receivePersonRequest(board, request('gap-1'), { sequence: 7, at, sender: person }),+ error => error instanceof Refused && error.code === 'RELAY_ORDER');+ assert.equal(appliedSequence(board), 5, 'a missing prefix cannot move the durable cursor');+ assert.deepEqual(personRequestRecords(board), before, 'a refused gap writes no partial request receipt');++ const reopened = box.reopen();+ assert.equal(appliedSequence(reopened), 5);+ assert.deepEqual(personRequestStatuses(reopened).map(record => record.status), ['waiting', 'refused', 'refused', 'refused']);+});++test('[H12,H16] elected executor commits one ordinary engine move and replay returns its receipt', t => {+ const box = fixture(t);+ const board = box.board;+ const document = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'Please review this' } }, 'shout-1');+ receivePersonRequest(board, document, { sequence: 1, at, sender: person });++ const claim = claimMove(board, document.id, 'device-a');+ assert.equal(claim.engine, ENGINE_VERSION);+ const claimed = applyEngineMove(board, claim, { sequence: 2, at });+ assert.ok(claimed.result);+ assert.equal(personRequestRecords(board)[0].executor, 'device-a');++ const badId = prepareEngineMove(board, 'shout', [{ from: 'person', to: 'coordinator', text: 'wrong request', lanes: [] }], { id: 'bad-request-id' });+ badId.personRequest = { id: 'missing-request', executor: 'device-a', phase: 'execute' };+ assert.equal(applyEngineMove(board, badId, { sequence: 3, at }).error?.code, 'PERSON_REQUEST_CLOSED');+ const wrongOperation = prepareEngineMove(board, 'addItem', [{ by: 'person', lane: 'web', title: 'Wrong action' }], { id: 'wrong-operation' });+ wrongOperation.personRequest = { id: document.id, executor: 'device-a', phase: 'execute' };+ assert.equal(applyEngineMove(board, wrongOperation, { sequence: 4, at }).error?.code, 'PERSON_REQUEST_RECEIPT');++ const wrongArguments = prepareEngineMove(board, 'shout', [{ from: 'person', to: 'coordinator', text: 'A different question', lanes: [] }], { id: 'wrong-arguments' });+ wrongArguments.personRequest = { id: document.id, executor: 'device-a', phase: 'execute' };+ assert.equal(applyEngineMove(board, wrongArguments, { sequence: 5, at }).error?.code, 'PERSON_REQUEST_RECEIPT', 'an ordinary move must fulfil the exact queued intent');++ const losingClaim = claimMove(board, document.id, 'device-b', 'claim-stage-other');+ const lost = applyEngineMove(board, losingClaim, { sequence: 6, at });+ assert.equal(lost.error.code, 'PERSON_REQUEST_TAKEN');+ assert.equal(personRequestRecords(board)[0].executor, 'device-a', 'a later device cannot replace the elected executor');++ const execution = prepareEngineMove(board, 'shout', [{+ from: 'person', to: 'coordinator', text: 'Please review this', lanes: [],+ }], { id: 'execute-shout-1' });+ execution.personRequest = { id: document.id, executor: 'device-a', phase: 'execute' };+ assert.equal(execution.engine, ENGINE_VERSION);+ const result = applyEngineMove(board, execution, { sequence: 7, at });+ assert.ok(result.result);+ assert.equal(personRequestStatuses(board)[0].status, 'done');+ const count = board.db.prepare("SELECT COUNT(*) AS count FROM shout WHERE shout_text='Please review this'").get().count;+ assert.equal(count, 1);++ const replayed = applyEngineMove(board, execution, { sequence: 7, at });+ assert.deepEqual(replayed, result, 'the same sequence and move ID return the committed outcome');+ assert.deepEqual(engineReceipt(board, execution.id).outcome, result);+ assert.equal(board.db.prepare("SELECT COUNT(*) AS count FROM shout WHERE shout_text='Please review this'").get().count, 1,+ 'replay cannot create a second result');++ const reopened = box.reopen();+ assert.equal(personRequestStatuses(reopened)[0].status, 'done');+ assert.equal(appliedSequence(reopened), 7);+});++test('[H12,H16] native CLI refusal fields remain attached to the durable request receipt', t => {+ const box = fixture(t);+ const board = box.board;+ const document = request('refused-1', 'A row that is no longer valid');+ receivePersonRequest(board, document, { sequence: 1, at, sender: person });+ applyEngineMove(board, claimMove(board, document.id, 'device-a'), { sequence: 2, at });++ const cliError = refusalDocument(new Refused('UNKNOWN_SPEC', 'G999 is not in SPEC.md')).error;+ const refusal = prepareEngineMove(board, 'shout', [{+ from: 'person', to: 'coordinator', text: `View request ${document.id}: [${cliError.code}] ${cliError.message}`, lanes: [],+ }], { id: 'refusal-stage' });+ refusal.personRequest = { id: document.id, executor: 'device-a', phase: 'refuse', error: cliError };+ assert.equal(refusal.engine, ENGINE_VERSION);+ const outcome = applyEngineMove(board, refusal, { sequence: 3, at });+ assert.ok(outcome.result);++ const saved = personRequestStatuses(board)[0];+ assert.equal(saved.status, 'refused');+ assert.deepEqual(saved.error, cliError, 'code, user-facing explanation, and next step stay intact');+ assert.equal(saved.error.code, 'UNKNOWN_SPEC');+ assert.match(saved.error.message, /G999 is not in SPEC\.md/);+ assert.ok(saved.error.next);++ const reopened = box.reopen();+ assert.deepEqual(personRequestStatuses(reopened)[0].error, cliError);+ assert.equal(appliedSequence(reopened), 3);+});diff --git a/test/person-request.test.js b/test/person-request.test.jsnew file mode 100644index 00000000..eb526e3f--- /dev/null+++ b/test/person-request.test.js@@ -0,0 +1,63 @@+/** Keep sealed person intent inside the CLI request boundary [H12,H16]. */+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { moveArgs } from '../src/api-moves.js';+import { personRequestMove, preparePersonRequest, validatePersonRequest } from '../src/person-request.js';+import { Refused } from '../src/refused.js';++test('[H12,H16] each supported person intent becomes literal CLI arguments', () => {+ const cases = [+ [{ verb: 'add', args: { lane: 'app', title: 'A title' } }, ['add', '--json', '--', 'app', 'A title']],+ [{ verb: 'shout', args: { to: 'coordinator', text: 'Please review' } }, ['shout', '--json', '--', 'coordinator', 'Please review']],+ [{ verb: 'answer', item: 7, args: { text: 'done' } }, ['answer', '7', '--as=person', '--json', '--', 'done']],+ [{ verb: 'hold', args: { lane: 'app', reason: 'Waiting for review' } }, ['hold', '--reason=Waiting for review', '--json', '--', 'app']],+ [{ verb: 'spec-approve', args: { ids: 'A4', by: 'person', text: 'Looks good' } }, ['spec', 'approve', '--by=person', '--text=Looks good', '--json', '--', 'A4']],+ [{ verb: 'spec-decline', args: { ids: 'A4', reason: 'Needs evidence' } }, ['spec', 'decline', '--reason=Needs evidence', '--json', '--', 'A4']],+ ];++ for (const [intent, expected] of cases) {+ assert.deepEqual(moveArgs(personRequestMove(intent)), expected, intent.verb);+ }+});++test('[H12,H16] person intent preserves literal leading-dash values and forces person answers', () => {+ const add = personRequestMove({ verb: 'add', args: { lane: 'app', title: '--looks-like-a-flag' } });+ assert.deepEqual(moveArgs(add), ['add', '--json', '--', 'app', '--looks-like-a-flag']);++ const shout = personRequestMove({ verb: 'shout', args: { text: '--not-a-recipient' } });+ assert.deepEqual(moveArgs(shout), ['shout', '--json', '--', '--not-a-recipient']);++ const answer = personRequestMove({ verb: 'answer', item: 9, args: { text: 'done' } });+ assert.equal(answer.args.as, 'person');+ assert.deepEqual(moveArgs(answer), ['answer', '9', '--as=person', '--json', '--', 'done']);+});++test('[H12,H16] request documents reject engine operations, impersonation and malformed arguments', () => {+ const refused = (call, code = 'BAD_REQUEST') => {+ assert.throws(call, error => error instanceof Refused && error.code === code);+ };++ refused(() => personRequestMove({ verb: 'claim', item: 1, args: {} }));+ refused(() => personRequestMove({ verb: 'answer', item: 1, agent: 'remote-1', args: { text: 'done' } }));+ refused(() => personRequestMove({ verb: 'answer', item: 1, args: { text: 'done', as: 'coordinator' } }), 'B26_PERSON_ANSWER');+ refused(() => personRequestMove({ verb: 'add', args: { lane: 'app', title: 'A title', mystery: true } }));+ refused(() => personRequestMove({ verb: 'add', args: ['app', 'A title'] }));+ refused(() => personRequestMove({ operation: 'verify', args: [1, {}] }));+});++test('[H12,H16] versioned person requests reject newer formats and unstable identifiers', () => {+ const request = preparePersonRequest({ verb: 'add', args: { lane: 'app', title: 'A title' } }, 'browser_req-1');+ assert.deepEqual(request, {+ version: 1,+ type: 'person-request',+ id: 'browser_req-1',+ move: { verb: 'add', args: { lane: 'app', title: 'A title' } },+ });+ assert.deepEqual(validatePersonRequest(request), request);++ assert.throws(() => validatePersonRequest({ ...request, version: 2 }), error => error instanceof Refused && error.code === 'PERSON_REQUEST_VERSION');+ for (const id of ['', '../request', 'request id', 'x'.repeat(81)]) {+ assert.throws(() => validatePersonRequest({ ...request, id }), error => error instanceof Refused && error.code === 'BAD_REQUEST');+ }+ assert.throws(() => validatePersonRequest({ ...request, unexpected: true }), error => error instanceof Refused && error.code === 'BAD_REQUEST');+});diff --git a/test/relay-browser.test.js b/test/relay-browser.test.jsindex b9ef1fab..b91f7b26 100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@ -113,7 +113,7 @@ test('real Chrome pairs, retains its device key, follows SSE without polling andassert.equal((await box.cli('add', box.lane, liveTitle)).code, 0);await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(liveTitle) + ')');- assert.equal(await chrome.evaluate("document.querySelector('#relay-notice').textContent.includes('Acting from the relay is coming')"), true);+ assert.equal(await chrome.evaluate("document.querySelector('#relay-notice').textContent.includes('Requests from this device wait for a linked machine')"), true);await chrome.navigate(box.origin);await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(liveTitle) + ')');assert.equal(await chrome.evaluate('location.hash === ""'), true, 'a later visit needs no new pairing link');diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 397c6eb3..ad3dc9f7 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -62,6 +62,7 @@ export async function relayClientFixture(t) {let override = null;let refuseEventReads = false;let refuseSnapshotWrites = false;+ let refuseRequestWrites = false;let signIn;let api;const calls = [];@@ -91,6 +92,11 @@ export async function relayClientFixture(t) {res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));return;}+ if (refuseRequestWrites && req.method === 'POST' && /\/api\/v1\/boards\/[0-9a-f]{32}\/requests$/.test(req.url ?? '')) {+ res.writeHead(503, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture request outage' } }));+ return;+ }if (refuseSnapshotWrites && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {res.writeHead(503, { 'content-type': 'application/json' });res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture snapshot outage' } }));@@ -193,6 +199,7 @@ export async function relayClientFixture(t) {advance(days) { time = Date.now() + days * 86400000; },overrideDelete(value) { override = value; },refuseSnapshotWrites(value) { refuseSnapshotWrites = value; },+ refuseRequestWrites(value) { refuseRequestWrites = value; },mainURL: new URL('../src/cli.js', import.meta.url).href,keyInRequest() { return keyLeaked; },/** Revoke the actual synthetic person session, including its current live streams. */diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.jsnew file mode 100644index 00000000..d608ce33--- /dev/null+++ b/test/relay-person-actions.test.js@@ -0,0 +1,187 @@+/** A paired person can use narrow CLI actions; agents cannot impersonate those actions [H12,H16,B26]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { test } from 'node:test';+import { prepareEngineMove } from '../src/engine.js';+import { openBoard, closeBoard } from '../src/board.js';+import { executeMove } from '../src/api.js';+import { main } from '../src/cli.js';+import { decodeBoardKey, seal } from '../src/seal.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';+import { relayClientFixture } from './relay-client-fixture.js';++/** Install only the private fixture's person cookie in the real browser. */+async function signIn(chrome, box) {+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const result = await chrome.send('Network.setCookie', {+ name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ });+ assert.equal(result.success, true);+}++/** Pair a real browser and initialize the same transport used by the relay cockpit. */+async function pairedTransport(chrome, box, title) {+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = readFileSync(box.keyFile, 'utf8').trim();+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');+ await chrome.evaluate(`(async () => {+ const { createTransport } = await import('/relay/client.js');+ window.__personActionTransport = await createTransport({ onUpdate: () => {} });+ return true;+ })()`);+ return link;+}++/** Submit literal person intent through the browser-owned transport. */+async function personAction(chrome, board, move) {+ return chrome.evaluate('window.__personActionTransport.request('+ + JSON.stringify('/api/v1/boards/' + board + '/moves') + ',' + JSON.stringify(move) + ')');+}++/** Wait until a native CLI visit has published the durable request status to the paired device. */+async function waitRequest(chrome, board, id, status) {+ const path = '/api/v1/boards/' + board + '/state';+ const testState = `(() => { const row = value.state?.personRequests?.find(entry => entry.id === ${JSON.stringify(id)}); return row?.status === ${JSON.stringify(status)}; })()`;+ await chrome.waitFor(`(async () => { try { const value = await window.__personActionTransport.request(${JSON.stringify(path)}); return ${testState}; } catch { return false; } })()`);+ return chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify(path) + ')');+}++test('real paired person adds, answers a person decision, and holds then releases a lane [H12,H16,B26]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const title = 'PERSON_ACTION_ITEM_FIXTURE';+ const decisionText = 'PERSON_ACTION_DECISION_FIXTURE';+ assert.equal((await box.cli('add', box.lane, 'PERSON_ACTION_BROWSER_READY')).code, 0);+ const asked = await box.cli('shout', 'person', decisionText, '--decision');+ assert.equal(asked.code, 0);+ const decision = asked.document.id;+ assert.ok(Number.isSafeInteger(decision));+ await box.link();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const link = await pairedTransport(chrome, box, 'PERSON_ACTION_BROWSER_READY');++ const added = await personAction(chrome, link.board, {+ verb: 'add', args: { lane: box.lane, title },+ });+ assert.equal(added.result.request.status, 'waiting');+ assert.equal((await box.cli('status')).code, 0);+ await waitRequest(chrome, link.board, added.result.request.id, 'done');+ let exported = (await box.cli('export')).document;+ const item = exported.tables.item.find(row => row.item_title === title);+ assert.ok(item, 'the actual CLI created the requested item');+ assert.equal(item.item_created_by, 'person');+ const addEvent = exported.tables.event.find(row => row.event_kind === 'add' && row.item_id === item.item_id);+ assert.equal(addEvent.event_by, 'person');++ const answered = await personAction(chrome, link.board, {+ verb: 'answer', item: decision, args: { text: 'PERSON_ACTION_ANSWER_FIXTURE' },+ });+ assert.equal(answered.result.request.status, 'waiting');+ assert.equal((await box.cli('status')).code, 0);+ await waitRequest(chrome, link.board, answered.result.request.id, 'done');+ exported = (await box.cli('export')).document;+ const answer = exported.tables.event.find(row => row.event_kind === 'answer' && row.event_by === 'person');+ assert.ok(answer);+ assert.equal(JSON.parse(answer.event_detail).channel, 'view');++ const held = await personAction(chrome, link.board, {+ verb: 'hold', args: { lane: box.lane, reason: 'PERSON_ACTION_HOLD_FIXTURE' },+ });+ assert.equal(held.result.request.status, 'waiting');+ assert.equal((await box.cli('status')).code, 0);+ await waitRequest(chrome, link.board, held.result.request.id, 'done');+ exported = (await box.cli('export')).document;+ assert.deepEqual(exported.tables.hold.map(row => [row.hold_lane, row.hold_by]), [[box.lane, 'person']]);+ const holdEvent = exported.tables.event.find(row => row.event_kind === 'hold' && JSON.parse(row.event_detail).reason === 'PERSON_ACTION_HOLD_FIXTURE');+ assert.equal(holdEvent.event_by, 'person');++ const released = await personAction(chrome, link.board, { verb: 'hold', args: { lane: box.lane, off: true } });+ assert.equal(released.result.request.status, 'waiting');+ assert.equal((await box.cli('status')).code, 0);+ await waitRequest(chrome, link.board, released.result.request.id, 'done');+ exported = (await box.cli('export')).document;+ assert.equal(exported.tables.hold.some(row => row.hold_lane === box.lane), false);+ const unholdEvent = exported.tables.event.find(row => row.event_kind === 'unhold' && JSON.parse(row.event_detail).lane === box.lane);+ assert.equal(unholdEvent.event_by, 'person');+ const actionEvents = exported.tables.event.filter(row => ['add', 'answer', 'hold', 'unhold'].includes(row.event_kind) && row.event_by === 'person');+ assert.deepEqual(actionEvents.map(row => row.event_kind), ['add', 'answer', 'hold', 'unhold']);++ const invalid = await personAction(chrome, link.board, {+ verb: 'hold', args: { lane: 'PERSON_ACTION_NO_SUCH_LANE', reason: 'must refuse' },+ });+ assert.equal((await box.cli('status')).code, 0);+ await waitRequest(chrome, link.board, invalid.result.request.id, 'refused');+ const state = await chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify('/api/v1/boards/' + link.board + '/state') + ')');+ const refusal = state.state.personRequests.find(row => row.id === invalid.result.request.id).error;+ assert.equal(refusal.code, 'NO_LANE');+ exported = (await box.cli('export')).document;+ assert.equal(exported.tables.event.some(row => row.event_kind === 'hold' && JSON.parse(row.event_detail).lane === 'PERSON_ACTION_NO_SUCH_LANE'), false);+ const brief = 'Files:\n- ../foreign.js\nTest:\n- Keep the file in its own lane';+ const foreign = await personAction(chrome, link.board, { verb: 'add', args: { lane: box.lane, title: 'PERSON_ACTION_FOREIGN_BRIEF', brief } });+ assert.equal((await box.cli('status')).code, 0);+ const rejected = (await chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify('/api/v1/boards/' + link.board + '/state') + ')')).state.personRequests.find(row => row.id === foreign.result.request.id);+ assert.equal(rejected.status, 'refused');+ assert.equal(rejected.error.code, 'BRIEF_LANE');+ const terminal = await box.cli('add', box.lane, 'PERSON_ACTION_FOREIGN_BRIEF', '--brief', brief);+ assert.equal(terminal.code, 1);+ assert.deepEqual(rejected.error, terminal.document.error, 'lane preflight retains the ordinary CLI refusal and repair');++});++test('local view attribution is person-only and an agent token cannot seal person-attributed holds [H12,H16,B26]', async t => {+ const box = await relayClientFixture(t);+ const localHold = await executeMove(box.root, { verb: 'hold', args: { lane: box.lane, reason: 'LOCAL_PERSON_HOLD_FIXTURE' } }, main);+ assert.equal(localHold.status, 200);+ assert.equal(localHold.body.event.event_by, 'person');+ assert.equal(JSON.parse(localHold.body.event.event_detail).channel, 'view');+ const localRelease = await executeMove(box.root, { verb: 'hold', args: { lane: box.lane, off: true } }, main);+ assert.equal(localRelease.status, 200);+ assert.equal(localRelease.body.event.event_by, 'person');+ assert.equal(JSON.parse(localRelease.body.event.event_detail).channel, 'view');++ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const tokenResponse = await fetch(box.origin + '/auth/tokens', {+ method: 'POST', headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },+ body: JSON.stringify({ board: link.board, agent: 'person-action-agent' }),+ });+ assert.equal(tokenResponse.status, 201);+ const agentToken = (await tokenResponse.json()).token;+ const stateResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {+ headers: { authorization: 'Bearer ' + link.token },+ });+ assert.equal(stateResponse.status, 200);+ let sequence = (await stateResponse.json()).state.sequence;+ const board = openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ let attempted;+ try {+ attempted = [+ prepareEngineMove(board, 'holdLane', [box.lane, { agentId: 'coordinator', asPerson: true, reason: 'forged person hold' }]),+ prepareEngineMove(board, 'releaseLane', [box.lane, { agentId: 'coordinator', asPerson: true }]),+ ];+ } finally { closeBoard(board); }+ for (const move of attempted) {+ sequence += 1;+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(move)), { boardId: link.board, kind: 'move', sequence })).toString('base64url');+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/moves', {+ method: 'POST', headers: { authorization: 'Bearer ' + agentToken, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence, sealed }),+ });+ assert.equal(response.status, 200, 'the relay stores the opaque agent-authenticated envelope');+ }+ assert.equal((await box.cli('status')).code, 0, 'native replay records both sender refusals');+ const exported = (await box.cli('export')).document;+ const refusals = exported.tables.event.filter(row => row.event_kind === 'relay_refused' && row.event_by === 'person-action-agent');+ assert.deepEqual(refusals.map(row => JSON.parse(row.event_detail).code), ['RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY']);+ assert.equal(exported.tables.event.some(row => ['hold', 'unhold'].includes(row.event_kind)+ && JSON.parse(row.event_detail).reason === 'forged person hold'), false);+ assert.equal(exported.tables.hold.some(row => row.hold_lane === box.lane && row.hold_reason === 'forged person hold'), false);+ assert.ok(Number.isSafeInteger(ENGINE_VERSION), 'the test follows the current engine envelope without pinning a version');+});diff --git a/test/relay-person-outbox.test.js b/test/relay-person-outbox.test.jsnew file mode 100644index 00000000..cc028ec9--- /dev/null+++ b/test/relay-person-outbox.test.js@@ -0,0 +1,93 @@+/** A paired browser retries only saved ciphertext after an interrupted person request [H12,H16,H17]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';+import { relayClientFixture } from './relay-client-fixture.js';++/** Install only the private fixture's person cookie in the real browser. */+async function signIn(chrome, box) {+ const session = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const result = await chrome.send('Network.setCookie', {+ name: 'pb_session', value: session.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ });+ assert.equal(result.success, true);+}++/** Pair a real browser and initialize the production transport without using UI actions. */+async function pairedTransport(chrome, box, title) {+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = readFileSync(box.keyFile, 'utf8').trim();+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');+ await installTransport(chrome);+ return link;+}++/** Initialize the real transport on the currently loaded document. */+async function installTransport(chrome) {+ await chrome.evaluate(`(async () => {+ const { createTransport } = await import('/relay/client.js');+ window.__personOutboxTransport = await createTransport({ onUpdate: () => {} });+ return true;+ })()`);+}++test('real Chrome keeps an interrupted person request sealed and retries it once after reload [H12,H16,H17]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const title = 'PERSON_OUTBOX_BROWSER_READY';+ const text = 'PERSON_OUTBOX_PRIVATE_REQUEST_TEXT';+ assert.equal((await box.cli('add', box.lane, title)).code, 0);+ await box.link();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const link = await pairedTransport(chrome, box, title);+ const outboxPrefix = 'pullboard.relay.requests.v1.' + link.board + '.';++ box.refuseRequestWrites(true);+ const interrupted = await chrome.evaluate(`window.__personOutboxTransport.request(+ ${JSON.stringify('/api/v1/boards/' + link.board + '/moves')},+ ${JSON.stringify({ verb: 'shout', args: { to: 'coordinator', text } })}+ ).then(() => ({ code: null }), error => ({ code: error.code }))`);+ assert.equal(interrupted.code, 'RELAY_UNAVAILABLE');+ let outbox = await chrome.evaluate(`(() => {+ const keys = Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i)).filter(key => key?.startsWith(${JSON.stringify(outboxPrefix)}));+ return keys.map(key => ({ key, record: JSON.parse(localStorage.getItem(key)) }));+ })()`);+ assert.equal(outbox.length, 1, 'the interrupted intent has one independently stored outbox record');+ assert.deepEqual(Object.keys(outbox[0].record).sort(), ['id', 'sealed', 'sequence']);+ assert.equal(outbox[0].key, outboxPrefix + outbox[0].record.id);+ assert.equal(outbox[0].record.sequence, 1);+ assert.doesNotMatch(JSON.stringify(outbox[0].record), new RegExp(text));+ assert.equal(JSON.stringify(outbox[0].record).includes(readFileSync(box.keyFile, 'utf8').trim()), false,+ 'the outbox keeps only the sealed request, never the pairing key');+ assert.equal(box.calls.some(call => call.method === 'POST' && call.path === `/api/v1/boards/${link.board}/requests`), true,+ 'the real request endpoint returned the fixture outage');++ box.refuseRequestWrites(false);+ await chrome.navigate(box.origin);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');+ await installTransport(chrome);+ const statePath = '/api/v1/boards/' + link.board + '/state';+ const state = await chrome.evaluate('window.__personOutboxTransport.request(' + JSON.stringify(statePath) + ')');+ const requestId = outbox[0].record.id;+ const receipt = state.state.personRequests.find(row => row.id === requestId);+ assert.equal(receipt?.status, 'waiting', 'a read flushes the saved request after the service recovers');+ assert.deepEqual(receipt.move, { verb: 'shout', args: { to: 'coordinator', text } });+ outbox = await chrome.evaluate(`(() => Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i))+ .filter(key => key?.startsWith(${JSON.stringify(outboxPrefix)})))()`);+ assert.deepEqual(outbox, [], 'the relay acknowledgement removes the device outbox entry');++ assert.equal((await box.cli('status')).code, 0, 'the native linked machine executes the recovered request');+ const exported = (await box.cli('export')).document;+ const shouts = exported.tables.shout.filter(row => row.shout_from === 'person' && row.shout_text === text);+ assert.equal(shouts.length, 1, 'one recovered intent creates exactly one authored person shout');+ const repeatedState = await chrome.evaluate('window.__personOutboxTransport.request(' + JSON.stringify(statePath) + ')');+ assert.equal(repeatedState.state.personRequests.find(row => row.id === requestId).status, 'done');+ assert.equal((await box.cli('status')).code, 0, 'repeated native replay stays idempotent');+ const repeatedExport = (await box.cli('export')).document;+ assert.equal(repeatedExport.tables.shout.filter(row => row.shout_from === 'person' && row.shout_text === text).length, 1);+});diff --git a/test/relay-person-recovery.test.js b/test/relay-person-recovery.test.jsnew file mode 100644index 00000000..b8937491--- /dev/null+++ b/test/relay-person-recovery.test.js@@ -0,0 +1,166 @@+/** A second linked native device safely takes over an expired person request [H12,H16]. */+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { preparePersonRequest } from '../src/person-request.js';+import { personRequestRecords, personRequestStatuses } from '../src/relay-requests.js';+import { decodeBoardKey, seal } from '../src/seal.js';+import { relayClientFixture } from './relay-client-fixture.js';++const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');+const BOARD_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/board.js')).href;+const EXCHANGE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/exchange.js')).href;+const RELAY_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay.js')).href;+const CONFIG_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/config.js')).href;+const LANES_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/lanes.js')).href;++/** Run an isolated fixture child without copying its private output into assertion diagnostics. */+function child(cwd, env, argv) {+ return new Promise((done, fail) => {+ const processChild = spawn(process.execPath, argv, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ const timer = setTimeout(() => processChild.kill('SIGKILL'), 25000);+ processChild.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ processChild.stderr.resume();+ processChild.once('error', error => { clearTimeout(timer); fail(error); });+ processChild.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return fail(new Error('private request recovery child exceeded its deadline'));+ try { done({ code, document: JSON.parse(stdout) }); }+ catch { fail(new Error('private request recovery child did not return its result')); }+ });+ });+}++/** Invoke the production CLI in a chosen private checkout and home. */+function cli(root, env, ...args) { return child(root, env, [CLI, ...args, '--json']); }++/** Receive the browser-format request, elect one executor, and stop immediately after its claim. */+function claimOnly(root, env, requestId) {+ const source = `+ const root = process.cwd();+ const { syncRelay, relayRequestDevice, relayOperation } = await import(${JSON.stringify(RELAY_MODULE)});+ const { loadConfig } = await import(${JSON.stringify(CONFIG_MODULE)});+ const { laneNames } = await import(${JSON.stringify(LANES_MODULE)});+ const sink = { isTTY: false, write() {} };+ const io = { cwd: root, stdout: sink, stderr: sink, say() {}, err() {}, onEvent() {} };+ await syncRelay(root, io);+ const executor = await relayRequestDevice(root);+ const message = { from: 'person', to: 'coordinator', text: ${JSON.stringify(`View request ${requestId}: Received a request from the paired view.`)}, lanes: laneNames(loadConfig(root)) };+ const result = await relayOperation(root, 'shout', [message], {+ ...io,+ personRequest: { id: ${JSON.stringify(requestId)}, executor, phase: 'claim' },+ personRequestMoveId: 'recovery-' + ${JSON.stringify(requestId)} + '-' + executor,+ });+ process.stdout.write(JSON.stringify({ executor, result: Number.isSafeInteger(result) }));+ `;+ return child(root, env, ['--input-type=module', '-e', source]);+}++/** Export the private board directly so inspection cannot trigger another request-processing pass. */+async function privateExport(root, env) {+ const source = `+ const { openBoard, closeBoard } = await import(${JSON.stringify(BOARD_MODULE)});+ const { exportBoard } = await import(${JSON.stringify(EXCHANGE_MODULE)});+ const board = openBoard(${JSON.stringify(join(root, '.git', 'pullboard', 'board.sqlite'))});+ try { process.stdout.write(JSON.stringify(exportBoard(board))); } finally { closeBoard(board); }+ `;+ return (await child(root, env, ['--input-type=module', '-e', source])).document;+}++test('[H12,H16] an expired native executor lease transfers once and the old device cannot repeat the shout', async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const requestId = 'takeover-request-1';+ const intent = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'RECOVERY_SHOUT_ONCE' } }, requestId);+ const envelopeBytes = await seal(key, new TextEncoder().encode(JSON.stringify(intent)), {+ boardId: link.board, kind: 'request', sequence: 1,+ });+ const envelope = Buffer.from(envelopeBytes).toString('base64url');+ const posted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {+ method: 'POST',+ headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: 1, sealed: envelope }),+ });+ assert.equal(posted.status, 200, 'the relay accepts the browser-format sealed request through the fixture person session');+ assert.equal((await posted.json()).event.kind, 'request');++ const originalClaim = await claimOnly(box.root, box.env, requestId);+ assert.equal(originalClaim.code, 0);+ assert.equal(originalClaim.document.result, true);+ const originalExecutor = originalClaim.document.executor;++ // Import a real private export into a second Git repository, then provision an independent link+ // and the same board key. Removing the device id makes its first native command elect a new one.+ const secondRoot = resolve(box.root, '..', 'request-recovery-device');+ const secondHome = resolve(box.root, '..', 'request-recovery-home');+ mkdirSync(secondRoot);+ mkdirSync(secondHome, { mode: 0o700 });+ t.after(() => { rmSync(secondRoot, { recursive: true, force: true }); rmSync(secondHome, { recursive: true, force: true }); });+ const secondEnv = {+ ...box.env,+ HOME: secondHome,+ PULLBOARD_HOME: join(secondHome, '.pullboard'),+ PULLBOARD_MACHINE_HOME: join(secondHome, 'machine'),+ };+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: secondRoot, env: secondEnv }).status, 0);+ assert.equal((await cli(secondRoot, secondEnv, 'init')).code, 0);+ const snapshot = join(secondRoot, 'native-board.json');+ writeFileSync(snapshot, JSON.stringify(await privateExport(box.root, box.env)), { mode: 0o600 });+ assert.equal((await cli(secondRoot, secondEnv, 'import', snapshot)).code, 0);++ const secondState = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ delete secondState.requestDevice;+ const secondLinkFile = join(secondRoot, '.git', 'pullboard', 'relay.json');+ mkdirSync(join(secondRoot, '.git', 'pullboard'), { recursive: true, mode: 0o700 });+ writeFileSync(secondLinkFile, JSON.stringify(secondState) + '\n', { mode: 0o600 });+ const keyDirectory = join(secondEnv.PULLBOARD_HOME, 'relay-keys');+ mkdirSync(keyDirectory, { recursive: true, mode: 0o700 });+ writeFileSync(join(keyDirectory, link.board + '.key'), readFileSync(box.keyFile), { mode: 0o600 });++ // Before the ten-minute lease expires, the independent device cannot run the request.+ assert.equal((await cli(secondRoot, secondEnv, 'status')).code, 0);+ const beforeExpiry = await privateExport(secondRoot, secondEnv);+ assert.equal(beforeExpiry.tables.shout.filter(row => row.shout_text === 'RECOVERY_SHOUT_ONCE').length, 0);+ let board = store.openBoard(join(secondRoot, '.git', 'pullboard', 'board.sqlite'));+ try { assert.equal(personRequestStatuses(board).find(record => record.id === requestId).status, 'waiting'); }+ finally { store.closeBoard(board); }++ box.advance(11 / 1440);+ assert.equal((await cli(secondRoot, secondEnv, 'status')).code, 0,+ 'the next native command after expiry claims and executes through the production CLI');+ const afterTakeover = await privateExport(secondRoot, secondEnv);+ assert.equal(afterTakeover.tables.shout.filter(row => row.shout_text === 'RECOVERY_SHOUT_ONCE').length, 1);+ const secondExecutor = JSON.parse(readFileSync(secondLinkFile, 'utf8')).requestDevice;+ assert.ok(secondExecutor);+ assert.notEqual(secondExecutor, originalExecutor, 'the copied device link elects an independent native executor');+ board = store.openBoard(join(secondRoot, '.git', 'pullboard', 'board.sqlite'));+ try {+ const status = personRequestStatuses(board).find(record => record.id === requestId);+ assert.equal(status.status, 'done');+ assert.notEqual(personRequestRecords(board).find(record => record.id === requestId).executor, originalExecutor);+ } finally { store.closeBoard(board); }++ // The original device catches up to the committed execution, sees a terminal request, and cannot+ // emit a second person shout even though its native identity is still present in its link file.+ const late = await box.script(`+ const { main } = await import(${JSON.stringify(pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href)});+ const code = await main(['shout', 'coordinator', 'RECOVERY_SHOUT_ONCE', '--json'], {+ cwd: process.cwd(), stdout: process.stdout, stderr: process.stderr, personChannel: 'view', skipPersonRequests: true,+ personRequest: { id: ${JSON.stringify(requestId)}, executor: ${JSON.stringify(originalExecutor)}, phase: 'execute' },+ personRequestMoveId: 'late-original-${originalExecutor}',+ });+ process.exitCode = code;+ `);+ assert.equal(late.code, 1, 'an explicitly retried late CLI stage refuses its terminal request');+ assert.equal(late.document.error.code, 'PERSON_REQUEST_CLOSED');+ assert.equal((await box.cli('status')).code, 0);+ const final = await privateExport(box.root, box.env);+ assert.equal(final.tables.shout.filter(row => row.shout_text === 'RECOVERY_SHOUT_ONCE').length, 1);+});diff --git a/test/relay-person-requests.test.js b/test/relay-person-requests.test.jsnew file mode 100644index 00000000..271f3346--- /dev/null+++ b/test/relay-person-requests.test.js@@ -0,0 +1,217 @@+/** A paired browser seals person intent; only native Pullboard executes it [H12,H16,B26]. */+import assert from 'node:assert/strict';+import { randomUUID } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { test } from 'node:test';+import { decodeBoardKey, seal } from '../src/seal.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';+import { relayClientFixture } from './relay-client-fixture.js';++/** Install the fixture's person session without exposing its cookie in browser diagnostics. */+async function signIn(chrome, box) {+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const result = await chrome.send('Network.setCookie', {+ name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ });+ assert.equal(result.success, true, 'the real person session is installed in the isolated browser');+}++/** Pair a real browser, then create the same transport module used by the relay cockpit. */+async function pairedTransport(chrome, box, title) {+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const encoded = readFileSync(box.keyFile, 'utf8').trim();+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');+ await chrome.evaluate(`(async () => {+ const { createTransport } = await import('/relay/client.js');+ window.__personRequestTransport = await createTransport({ onUpdate: () => {} });+ return true;+ })()`);+ return link;+}++/** Send one exact person intent through the browser transport rather than constructing a move. */+async function sendPersonIntent(chrome, board, move) {+ const path = '/api/v1/boards/' + board + '/moves';+ return chrome.evaluate('window.__personRequestTransport.request('+ + JSON.stringify(path) + ',' + JSON.stringify(move) + ')');+}++/** Poll the browser's authenticated, device-decrypted presentation for one durable receipt. */+async function waitForRequest(chrome, board, id, status, requireCoordinatorRequest = false) {+ const path = '/api/v1/boards/' + board + '/state';+ const predicate = `(() => { const row = documentValue.state?.personRequests?.find(entry => entry.id === ${JSON.stringify(id)}); return row?.status === ${JSON.stringify(status)}${requireCoordinatorRequest ? ' && Number.isSafeInteger(row.coordinatorRequest)' : ''}; })()`;+ await chrome.waitFor(`(async () => { try { const documentValue = await window.__personRequestTransport.request(${JSON.stringify(path)}); return ${predicate}; } catch { return false; } })()`);+ return chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(path) + ')');+}++/** Add a private pending spec row without changing shared or submitted repository files. */+function addPendingSpecRow(box, id) {+ const path = join(box.root, 'SPEC.md');+ const original = readFileSync(path, 'utf8');+ assert.equal(original.includes(id + ' ['), false, 'the synthetic row id is unused');+ writeFileSync(path, original + `\n## Person request fixture\n\n- ${id} [pending, aim] Person requests wait for coordinator application. | gate: review\n`);+ return { path, original };+}++test('real paired Chrome transports one person shout, and native status makes one authored shout [H12,H16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const title = 'PERSON_REQUEST_SHOUT_FIXTURE';+ assert.equal((await box.cli('add', box.lane, title)).code, 0);+ await box.link();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const link = await pairedTransport(chrome, box, title);+ const move = { verb: 'shout', args: { to: 'coordinator', text: 'PERSON_REQUEST_SHOUT_LITERAL' } };+ const receipt = await sendPersonIntent(chrome, link.board, move);++ assert.equal(receipt.version, 1);+ assert.equal(receipt.result.request.status, 'waiting');+ assert.deepEqual(receipt.result.request.move, move);+ assert.equal(typeof receipt.result.request.id, 'string');+ assert.equal(box.calls.some(call => call.method === 'POST' && call.path === `/api/v1/boards/${link.board}/requests`), true,+ 'the browser posts a sealed request document, not an executable engine move');+ assert.equal(box.keyInRequest(), false, 'the device key never enters an HTTP request');+ const session = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const rawResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + session.token } });+ assert.equal(rawResponse.status, 200);+ const raw = await rawResponse.json();+ assert.equal(JSON.stringify(raw).includes(move.args.text), false, 'the relay response contains opaque ciphertext rather than request text');+ const sealedRequest = raw.events.find(row => row.kind === 'request');+ assert.ok(sealedRequest && typeof sealedRequest.sealed === 'string');+++ assert.equal((await box.cli('status')).code, 0, 'the next native status receives and executes the queued intent');+ const latest = await waitForRequest(chrome, link.board, receipt.result.request.id, 'done');+ const personShouts = latest.state.shouts.filter(shout => shout.shout_from === 'person' && shout.shout_text === move.args.text);+ assert.equal(personShouts.length, 1, 'the authored person shout occurs exactly once');+ const exported = (await box.cli('export')).document;+ assert.equal(exported.tables.shout.filter(shout => shout.shout_from === 'person' && shout.shout_text === move.args.text).length, 1);+});++test('real paired Chrome approval remains pending until coordinator applies and answers; invalid add keeps its CLI refusal [H12,H16,B26]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const title = 'PERSON_REQUEST_APPROVAL_FIXTURE';+ const id = 'G98';+ const row = addPendingSpecRow(box, id);+ assert.equal((await box.cli('add', box.lane, title)).code, 0);+ await box.link();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const link = await pairedTransport(chrome, box, title);++ const before = readFileSync(row.path, 'utf8');+ const approval = await sendPersonIntent(chrome, link.board, { verb: 'spec-approve', args: { ids: id } });+ assert.equal(approval.result.request.status, 'waiting');+ assert.deepEqual(approval.result.request.move, { verb: 'spec-approve', args: { ids: id } });+ assert.equal((await box.cli('status')).code, 0);+ const pendingState = await waitForRequest(chrome, link.board, approval.result.request.id, 'waiting', true);+ assert.equal(readFileSync(row.path, 'utf8'), before, 'the received approval records a row decision but does not edit SPEC.md');+ const decisionEvents = (await box.cli('export')).document.tables.event.filter(event => event.event_kind === 'row_decision' && event.event_by === 'person');+ assert.equal(decisionEvents.length, 1, 'the native row decision is attributed to the person');+ assert.equal(JSON.parse(decisionEvents[0].event_detail).record.id, id);+ const coordinatorRequest = pendingState.state.personRequests.find(entry => entry.id === approval.result.request.id).coordinatorRequest;+ const resume = (await box.cli('resume')).document;+ assert.equal(resume.requests[0].shout_id, coordinatorRequest, 'coordinator resume presents the pending repository request first');+++ assert.equal((await box.cli('spec', 'apply')).code, 0, 'the coordinator applies the recorded decision locally');+ assert.match(readFileSync(row.path, 'utf8'), new RegExp(`- ${id} \\[approved, aim\\]`));+ const requestId = pendingState.state.personRequests.find(entry => entry.id === approval.result.request.id).coordinatorRequest;+ assert.equal((await box.cli('answer', String(requestId), 'done')).code, 0, 'the coordinator resolves the original request after applying it');+ const completed = await waitForRequest(chrome, link.board, approval.result.request.id, 'done');+ assert.equal(completed.state.personRequests.find(entry => entry.id === approval.result.request.id).status, 'done');++ const invalid = await sendPersonIntent(chrome, link.board, {+ verb: 'add', args: { lane: box.lane, title: 'PERSON_REQUEST_INVALID_SPEC', specs: 'G999' },+ });+ assert.equal(invalid.result.request.status, 'waiting');+ assert.equal((await box.cli('status')).code, 0, 'native CLI status records the exact command refusal without creating an item');+ const afterInvalid = (await box.cli('export')).document;+ assert.equal(afterInvalid.tables.item.some(item => item.item_title === 'PERSON_REQUEST_INVALID_SPEC'), false, 'the native CLI refuses unknown specs before an ordinary add move');+ const refused = await waitForRequest(chrome, link.board, invalid.result.request.id, 'refused');+ const refusal = refused.state.personRequests.find(entry => entry.id === invalid.result.request.id).error;+ assert.equal(refusal.code, 'UNKNOWN_SPEC');+ assert.equal(refusal.message, 'G999 is not in SPEC.md');+ const terminalRefusal = await box.cli('add', box.lane, 'PERSON_REQUEST_INVALID_SPEC', '--specs', 'G999');+ assert.equal(terminalRefusal.code, 1);+ assert.deepEqual(refusal, terminalRefusal.document.error, 'the request carries the same complete CLI refusal document');+ const local = (await box.cli('export')).document;+ assert.equal(local.tables.item.some(item => item.item_title === 'PERSON_REQUEST_INVALID_SPEC'), false);+ assert.equal(local.tables.event.some(event => event.event_kind === 'row_decision' && JSON.parse(event.event_detail).record.id === 'G999'), false);+});++test('an agent-sealed row approval is refused before any row receipt or spec edit [H12,H16,B26]', async t => {+ const box = await relayClientFixture(t);+ const id = 'G97';+ const row = addPendingSpecRow(box, id);+ const before = readFileSync(row.path, 'utf8');+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const personToken = link.token;+ const tokenResponse = await fetch(box.origin + '/auth/tokens', {+ method: 'POST', headers: { authorization: 'Bearer ' + personToken, 'content-type': 'application/json' },+ body: JSON.stringify({ board: link.board, agent: 'request-fixture-agent' }),+ });+ assert.equal(tokenResponse.status, 201, 'the signed-in person can issue a scoped agent token');+ const agentToken = (await tokenResponse.json()).token;+ const snapshotResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {+ headers: { authorization: 'Bearer ' + personToken },+ });+ assert.equal(snapshotResponse.status, 200);+ const sequence = (await snapshotResponse.json()).state.sequence + 1;+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const document = { version: 1, type: 'person-request', id: randomUUID(), move: { verb: 'spec-approve', args: { ids: id } } };+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(document)), {+ boardId: link.board, kind: 'request', sequence,+ })).toString('base64url');+ const uploaded = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {+ method: 'POST', headers: { authorization: 'Bearer ' + agentToken, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence, sealed }),+ });+ assert.equal(uploaded.status, 200, 'the opaque journal accepts authenticated ciphertext without interpreting it');+ assert.equal((await box.cli('status')).code, 0, 'native replay records the sender refusal');+ const exported = (await box.cli('export')).document;+ const receipts = JSON.parse(exported.tables.board_meta.find(row => row.meta_key === 'relay_person_requests').meta_value);+ const refused = receipts.find(entry => entry.id === document.id);+ assert.equal(refused.status, 'refused');+ assert.equal(refused.error.code, 'RELAY_PERSON_ONLY');+ assert.equal(exported.tables.event.some(event => event.event_kind === 'row_decision' && JSON.parse(event.event_detail).record.id === id), false);+ assert.equal(readFileSync(row.path, 'utf8'), before, 'agent intent cannot create a person receipt or change SPEC.md');+});++test('coordinator decline resolves a paired approval request with a reason and leaves repo files unchanged [H12,H16,B26]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const row = addPendingSpecRow(box, 'G96');+ const before = readFileSync(row.path, 'utf8');+ const title = 'PERSON_REQUEST_DECLINE_FIXTURE';+ assert.equal((await box.cli('add', box.lane, title)).code, 0);+ await box.link();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const link = await pairedTransport(chrome, box, title);+ const queued = await sendPersonIntent(chrome, link.board, { verb: 'spec-approve', args: { ids: 'G96' } });+ assert.equal((await box.cli('status')).code, 0);+ const statePath = '/api/v1/boards/' + link.board + '/state';+ const pending = (await chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(statePath) + ')')).state.personRequests.find(record => record.id === queued.result.request.id);+ assert.equal(pending.status, 'waiting');+ assert.ok(Number.isSafeInteger(pending.coordinatorRequest));+ const missingReason = await box.cli('answer', String(pending.coordinatorRequest), 'declined');+ assert.equal(missingReason.code, 1);+ assert.equal(missingReason.document.error.code, 'REQUEST_OUTCOME');+ const reason = 'Waiting for a revised requirement';+ assert.equal((await box.cli('answer', String(pending.coordinatorRequest), 'declined ' + reason)).code, 0);+ const completed = (await chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(statePath) + ')')).state.personRequests.find(record => record.id === queued.result.request.id);+ assert.equal(completed.status, 'refused');+ assert.deepEqual(completed.error, { code: 'REQUEST_DECLINED', message: reason, next: 'Read the coordinator reason and send a revised request from the view.' });+ assert.equal(readFileSync(row.path, 'utf8'), before, 'declining the repository request does not edit any row');+ assert.deepEqual((await box.cli('resume')).document.requests, [], 'the declined request leaves the open coordinator queue');+});diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.jsindex b2a5a467..46ed25f3 100644--- a/test/relay-sealed.test.js+++ b/test/relay-sealed.test.js@@ -240,7 +240,7 @@ test('two real clients refuse forged relay actors and person-only requests whilemoves = [prepareEngineMove(source, 'verify', [1, { agentId: 'coordinator', decision: 'ACCEPT', reason: 'CRITERION_MET', note: 'forged acceptance', head: 'a'.repeat(40), digest: 'd'.repeat(64), policy: 'any' }]),prepareEngineMove(source, 'answerDecision', [question, { agentId: 'coordinator', asPerson: true, text: 'forged person answer', lanes: [lane] }]),- prepareEngineMove(source, 'shout', [{ from: 'person', to: 'coordinator', request: true, text: 'forged person request', 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, 'shout', [{ from: 'remote-1', to: 'all', text: 'valid remote observation', lanes: [lane] }]),];