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
chore(merge): compose person signing on main [E22,C7,H16]
Corey Olson7f4eac708037
diff --cc docs/formats.mdindex c3ceb54c,e40efbc2..6f82ea58--- a/docs/formats.md+++ b/docs/formats.md@@@ -115,11 -115,9 +115,11 @@@ The version table is generated from th| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. || `board schema` | `3` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | On a write open of a board whose version is behind: create missing tables and indexes (version 3 adds the hot-path indexes), add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. Read opens never migrate; a board at the current version whose shape differs is reported once on stderr and left as it is. || `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |- | `move engine` | `127` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |+ | `move engine` | `128` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |<!-- format-versions:end -->+A signed board uses event-log format 2; older tools refuse it.+A builder never picks an engine number (#1101). An item that adds a board move adds its own `src/<name>-engine.js` leaf as `export const NAME_ENGINE = unassignedEngine();` (importing `unassignedEngine` from `./engine-next.js`); on its branch the leaf reads as one above the highest landed engine. The landing merge writes the next number into the leaf, in landing order, inside that item's merge commit, and sets the `move engine` row above to the highest landed number. A landed number never changes, so recorded moves replay as they were written. Moves are recorded under landed numbers only: code with an unnumbered engine is for its branch's own tests, and a move it records on a real board before landing may later read under another item's number, so the item lands before its moves are used.Relay transport capability `apiVersion: 2` is independent of these versions anddiff --cc relay/browser-client.jsindex 721e4549,abae0474..c8e23d6d--- a/relay/browser-client.js+++ b/relay/browser-client.js@@@ -24,38 -6,13 +24,40 @@@ importimport { ENGINE_VERSION } from './engine.js';import { Refused } from './refused.js';import { SNAPSHOT_BODY_BYTES } from './relay-limits.js';-import { enqueueStream, followStream } from './browser-stream.js';-import { recordBrowserReadFailure, clearBrowserReadFailure, emptyBoardStep, homeLineDismissed, homeScreenLine, noticeLines, rememberOwnedRequestId, showRelayScreen, storedOwnedRequestState } from './browser-notice.js';-import { registerApp, requestPairingPersistence } from './install.js';-import { browserJSON, withBrowserDeadline } from './browser-deadline.js';-import { phoneApprovalStatus, placePhoneApprovals, forgetPhoneApprovals } from './browser-approval-card.js';+import {+ enqueueStream,+ followStream,+} from './browser-stream.js';+import {++ recordBrowserReadFailure,++ clearBrowserReadFailure,+ emptyBoardStep,+ homeLineDismissed,+ homeScreenLine,+ noticeLines,+ rememberOwnedRequestId,+ showRelayScreen,+ storedOwnedRequestState,+} from './browser-notice.js';+import {+ registerApp,+ requestPairingPersistence,+} from './install.js';+import {+ browserJSON,+ withBrowserDeadline,+} from './browser-deadline.js';+import {+ phoneApprovalStatus,+ placePhoneApprovals,+ forgetPhoneApprovals,+} from './browser-approval-card.js';import { phoneSnapshotPages } from './browser-pages.js';import { createPhoneHistory } from './browser-history.js';+import {+ installPersonPasskeys,+ passkeyPresence,+} from './browser-passkeys.js';import { readUploadSize } from './browser-upload-status.js';import { deviceExcludedBoards } from './browser-devices.js';diff --cc src/cli.jsindex db803086,330f88f2..a23a8590--- a/src/cli.js+++ b/src/cli.js@@@ -1,3 -1,4 +1,5 @@@++import * as personIdentity from './person.js';+ import { dependencyValues } from './item-dependencies.js';import { computedReturnArgs } from './computed-conflict-return.js';import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';import { requireAgentGrant } from './agent-grant.js';@@@ -124,13 -125,11 +126,9 @@@ importholdDoctrine,ruleLine,} from './doctrine-checks.js';--import {-- AGENT_SESSION_IDS,-- agentSessionDigest,-- personCommand,--} from './person.js';+++import { signedMoveProblem } from './person-signing.js';+import { personAuthority } from './relay-sender.js';import {bindLocalSession,HOOK_CHECKOUT_WAIT_MS,@@@ -636,7 -632,7 +634,7 @@@ export async function ordered(ctx, boarif (requested && ctx.io.recordedMove) (await import('./cli-presence.js')).heartbeatCommand(ctx.io, { ctx, board });return result;};-- const digest = agentSessionDigest();++ const digest = personIdentity.agentSessionDigest();const boardOnly = CHECKOUT_BOARD_ONLY.get(ctx.io);const boardOnlyOperation = (boardOnly === 'shout' && operation === 'shout') || (boardOnly === 'fact' && operation === 'appendFact');const boardOnlyAgent = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id ?? 'unjoined agent';@@@ -661,7 -657,7 +659,7 @@@ export async function claimOrdered(ctx*/export async function bindWriteSession(io, positionals, values) {const [command, first] = positionals;-- const digest = agentSessionDigest();++ const digest = personIdentity.agentSessionDigest();if (!digest) {if (command === 'takeover' && !(repoInfo(io.cwd).isMain && relayLinked(repoInfo(io.cwd).root))) throw new Refused('AGENT_SESSION', 'takeover belongs to an agent session; run pullboard takeover from the agent’s shell');return;@@@ -1507,8 -1503,8 +1505,8 @@@ export function primaryCheckoutRoot(inf/** A real runtime session may route across its own local seats; marker-only shells stay isolated. */function nextSessionSeats(ctx, board) {if (ctx.info.isMain || ctx.io.personChannel === 'view' || ctx.io.personRequest-- || !AGENT_SESSION_IDS.some((name) => Boolean(process.env[name]))) return null;-- const digest = agentSessionDigest();++ || !personIdentity.AGENT_SESSION_IDS.some((name) => Boolean(process.env[name]))) return null;++ const digest = personIdentity.agentSessionDigest();return digest ? localSessionSeats(ctx.info, { agents: store.listAgents(board), digest }) : null;}@@@ -1529,7 -1525,7 +1527,7 @@@ async function nextSeatContext(ctx, boa}const target = agent.agent_path === ctx.info.root ? ctx : context({ ...ctx.io, cwd: agent.agent_path });if (target.info.commonDir !== ctx.info.commonDir) throw new Refused('NOT_YOUR_CHECKOUT', 'the selected lane seat no longer belongs to this board; run pullboard next again');-- await bindLocalSession(target.info, { agent: agent.agent_id, digest: agentSessionDigest() });++ await bindLocalSession(target.info, { agent: agent.agent_id, digest: personIdentity.agentSessionDigest() });return { context: target, seat: { agent: agent.agent_id, lane: agent.agent_lane, path: target.info.root, created } };}diff --cc src/commands/add.jsindex 8286f601,6f9c6622..c81d574a--- a/src/commands/add.js+++ b/src/commands/add.js@@@ -1,8 -1,4 +1,9 @@@+import {+ confirmBarEffect,+ executingBarEffect,+ personBarMode,+} from '../person-bar-cli.js';+ import { dependencyValues } from '../item-dependencies.js';/** The pullboard add command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';import {@@@ -59,9 -56,9 +60,9 @@@ export async function run(io, args)const problems = idProblems(loadSpec(ctx.info.root, ctx.config), specIds, ctx.doctrine);if (problems.length) throw new Refused('UNKNOWN_SPEC', `${problems.join('; ')}`);const parentId = values.parent ? idArg(values.parent, 'a parent item id') : null;- const after = idList(values.after).map((text) => idArg(text, 'an item id after --after'));+ const after = dependencyValues(idList(values.after));const title = [second, ...rest].filter(Boolean).join(' ');- const item = {+ let item = {by: io.personRequest?.phase === 'execute' ? store.PERSON : me.id,lane: first,title,diff --cc test/machine.test.jsindex 65cacad2,3f93cb18..1f19b9bb--- a/test/machine.test.js+++ b/test/machine.test.js@@@ -4,17 -4,9 +4,11 @@@* The item lifecycle's declaration (M1, M2, M4): sound on its own terms, each property shown* failing on a broken copy, and in step with the refusals the board, CLI and spec parser raise today.*/++import * as fs from 'node:fs';++import * as machineRules from '../src/machine.js';import { submitFixture } from './board-submit-fixture.js';import assert from 'node:assert/strict';- import {- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- realpathSync,- rmSync,- writeFileSync,- } from 'node:fs';-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';++import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { pathToFileURL } from 'node:url';@@@ -24,22 -16,8 +18,13 @@@ import * as store from '../src/board.jsimport { HELP } from '../src/cli.js';import { loadConfig } from '../src/config.js';import { Refused } from '../src/refused.js';- import {- BLANKS,- IN_STATE,- MACHINE,- effectiveGuards,- lifecycleHelp,- lifecycleMarkdown,- machineProblems,- storeTriggers,- } from '../src/machine.js';-import { BLANKS, IN_STATE, MACHINE, effectiveGuards, lifecycleHelp, lifecycleMarkdown, machineProblems, storeTriggers } from '../src/machine.js';-import { runFixtureExecFile as execFileSync, runFixtureChild as spawnSync, runFixtureChild, runFixtureGit } from './fixture-child.js';+++import {+ runFixtureExecFile as execFileSync,+ runFixtureChild as spawnSync,+ runFixtureChild,+ runFixtureGit,+} from './fixture-child.js';/*** Refusals that are not about an item's lifecycle, so no move declares them: command input, caller@@@ -271,7 -247,7 +258,7 @@@ function codeWalk(read, { caught = fals* @param {string} file* @returns {string}*/--const fromDisk = (file) => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');++const fromDisk = (file) => fs.readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');/*** The refusal codes the named moves declare, or the whole declaration's when none is named: their@@@ -283,7 -259,7 +270,7 @@@*/function declaredCodes(machine, verbs) {const moves = verbs ? machine.moves.filter((move) => verbs.includes(move.verb)) : machine.moves;-- const used = new Set(moves.flatMap((move) => effectiveGuards(move, machine)));++ const used = new Set(moves.flatMap((move) => machineRules.effectiveGuards(move, machine)));return new Set([...machine.guards.filter((guard) => !verbs || used.has(guard.id)).flatMap((guard) => [guard.refuse, ...(guard.alsoRefuses ?? []).map((entry) => entry.code)]),...moves.flatMap((move) => [move.refuse, ...(move.alsoRefuses ?? []).map((entry) => entry.code)]),@@@ -310,7 -286,7 +297,7 @@@ function codeProblems(machine, read = f}}}-- const commandFiles = readdirSync(new URL('../src/commands/', import.meta.url)).filter((name) => name.endsWith('.js') && name !== 'index.js').map((name) => `commands/${name}`);++ const commandFiles = fs.readdirSync(new URL('../src/commands/', import.meta.url)).filter((name) => name.endsWith('.js') && name !== 'index.js').map((name) => `commands/${name}`);const raised = new Set(['board.js', 'cli.js', 'spec.js', ...commandFiles].flatMap((file) => walk.functions(file).flatMap((name) => [...walk.refusalsOf(`${file}#${name}`)])));for (const code of declaredCodes(machine)) if (!raised.has(code)) problems.add(`${code} is declared but the board, CLI and spec parser never raise it`);return [...problems];@@@ -339,7 -315,7 +326,7 @@@ function editedSource(file, line, repla** @returns {any}*/--const copy = () => structuredClone(MACHINE);++const copy = () => structuredClone(machineRules.MACHINE);/*** The move with this verb.@@@ -401,13 -377,13 +388,13 @@@ const BROKEN =property: 'every non-final state has a way out',breaks: (machine) => {machine.states.push({ id: 'parked', means: 'set aside', requires: [] });-- machine.moves.push({ verb: 'park', from: ['open'], to: 'parked', by: ['agent', 'coordinator'], refuse: 'CLOSED', guards: ['joined', 'itemExists', IN_STATE] });++ machine.moves.push({ verb: 'park', from: ['open'], to: 'parked', by: ['agent', 'coordinator'], refuse: 'CLOSED', guards: ['joined', 'itemExists', machineRules.IN_STATE] });},says: /state parked is a trap/,},{property: 'nothing leaves a final state',-- breaks: (machine) => machine.moves.push({ verb: 'restore', from: ['withdrawn'], to: 'open', by: ['agent', 'coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', IN_STATE] }),++ breaks: (machine) => machine.moves.push({ verb: 'restore', from: ['withdrawn'], to: 'open', by: ['agent', 'coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', machineRules.IN_STATE] }),says: /final state withdrawn has a move out/,},{@@@ -427,7 -403,7 +414,7 @@@},{property: 'no second door into verified',-- breaks: (machine) => machine.moves.push({ verb: 'land', from: ['submitted'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED', guards: ['joined', 'itemExists', IN_STATE], sets: ['item_verified_by'] }),++ breaks: (machine) => machine.moves.push({ verb: 'land', from: ['submitted'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED', guards: ['joined', 'itemExists', machineRules.IN_STATE], sets: ['item_verified_by'] }),says: /land reaches verified without naming its exit guard atSubmittedCommit: a second door/,},{@@@ -460,7 -436,7 +447,7 @@@property: "every caller's move checks the item's state once",breaks: (machine) => {const release = moveOf(machine, 'release');-- release.guards = release.guards.filter((id) => id !== IN_STATE);++ release.guards = release.guards.filter((id) => id !== machineRules.IN_STATE);},says: /release checks the item's state 0 times, not once/,},@@@ -488,41 -464,41 +475,41 @@@];test('the declared lifecycle is sound: reachable, no traps, no second door, every refusal with a next step [M1, M2, M4]', () => {-- assert.deepEqual(machineProblems(), []);-- assert.deepEqual(MACHINE.states.map((state) => state.id), ['open', 'claimed', 'submitted', 'verified', 'withdrawn']);-- assert.deepEqual(MACHINE.states.filter((state) => state.final).map((state) => state.id), ['withdrawn']);-- assert.deepEqual(MACHINE.moves.map((move) => move.verb), ['intake', 'claim', 'release', 'lapse', 'submit', 'reserve', 'accept', 'reject', 'reopen', 'escalate', 'refreeze', 'refreeze', 'withdraw']);++ assert.deepEqual(machineRules.machineProblems(), []);++ assert.deepEqual(machineRules.MACHINE.states.map((state) => state.id), ['open', 'claimed', 'submitted', 'verified', 'withdrawn']);++ assert.deepEqual(machineRules.MACHINE.states.filter((state) => state.final).map((state) => state.id), ['withdrawn']);++ assert.deepEqual(machineRules.MACHINE.moves.map((move) => move.verb), ['intake', 'claim', 'release', 'lapse', 'submit', 'reserve', 'accept', 'reject', 'reopen', 'escalate', 'refreeze', 'refreeze', 'withdraw']);});for (const broken of BROKEN) {test(`a broken copy fails the check: ${broken.property} [M4]`, () => {const machine = copy();broken.breaks(machine);-- const problems = machineProblems(machine);++ const problems = machineRules.machineProblems(machine);assert.ok(problems.some((problem) => broken.says.test(problem)), `expected ${broken.says}, got:\n${problems.join('\n')}`);-- assert.deepEqual(machineProblems(), [], 'the real declaration stays sound');++ assert.deepEqual(machineRules.machineProblems(), [], 'the real declaration stays sound');});}test('a door declared without its exit guards still passes them [M2]', () => {const machine = copy();-- const land = { verb: 'land', from: ['submitted'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED', guards: ['joined', 'itemExists', IN_STATE] };++ const land = { verb: 'land', from: ['submitted'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED', guards: ['joined', 'itemExists', machineRules.IN_STATE] };machine.moves.push(land);-- const passes = effectiveGuards(land, machine);++ const passes = machineRules.effectiveGuards(land, machine);for (const id of machine.exitGuards.verified) assert.ok(passes.includes(id), `land passes ${id}`);assert.deepEqual(passes.slice(0, land.guards.length), land.guards, 'its own guards come first, in order');-- assert.deepEqual(effectiveGuards(moveOf(MACHINE, 'accept')), moveOf(MACHINE, 'accept').guards, 'accept names them all already, so nothing is added');++ assert.deepEqual(machineRules.effectiveGuards(moveOf(machineRules.MACHINE, 'accept')), moveOf(machineRules.MACHINE, 'accept').guards, 'accept names them all already, so nothing is added');});test('verified and withdrawn keep the exit guards their rules need, and a copy that drops one fails [V1, V3, V5, V7, M2, M4]', () => {-- assert.deepEqual(unpinned(MACHINE), []);++ assert.deepEqual(unpinned(machineRules.MACHINE), []);const broken = copy();broken.exitGuards.verified = broken.exitGuards.verified.filter((id) => id !== 'notBuilder');assert.deepEqual(unpinned(broken), ['verified no longer requires notBuilder (V1) of every move into it']);});test('accept and reject hold a verifier to the same checks until the verdict, and a copy that splits them fails [M1, M4]', () => {-- assert.deepEqual(verdictsDiverge(MACHINE), []);++ assert.deepEqual(verdictsDiverge(machineRules.MACHINE), []);const broken = copy();const accept = moveOf(broken, 'accept');accept.guards = accept.guards.filter((id) => id !== 'routeAllows');@@@ -530,7 -506,7 +517,7 @@@});test('every refusal a move raises today is declared on that move, and every declared code is raised [M1]', () => {-- assert.deepEqual(codeProblems(MACHINE), []);++ assert.deepEqual(codeProblems(machineRules.MACHINE), []);const walk = codeWalk(fromDisk);assert.ok(walk.refusalsOf('board.js#claim').has('UNKNOWN_SPEC'), 'the walk follows claim into the freezer the CLI hands it');assert.ok(walk.refusalsOf('board.js#refreeze').has('UNKNOWN_SPEC'), 'and refreeze too');@@@ -585,12 -561,26 +572,26 @@@ test('a broken copy of the declaration});test('a broken copy of the code fails the check: a refusal added wherever a move reaches [M1, M4]', () => {+ for (const [file, pattern] of [+ ['board-link-format.js', /^export function boardLinkRecord\(value\) \{$/m],+ ['board-link-state.js', /^export function readReceivedBoardState\(board, .*$/m],+ ]) {+ const inForeignReader = editedSource(file, pattern,+ "$&\n throw new Refused('MOON_PHASE', 'wait for the full moon');");- assert.deepEqual(codeProblems(MACHINE, inForeignReader), [], 'only the exact foreign evidence reader is caught as unavailable');++ assert.deepEqual(codeProblems(machineRules.MACHINE, inForeignReader), [], 'only the exact foreign evidence reader is caught as unavailable');+ }+ const inForeignCaller = editedSource('cross-repo-dependencies.js', /^function stateFor\(board, ref\) \{$/m,+ "$&\n throw new Refused('MOON_PHASE', 'wait for the full moon');");- assert.deepEqual(codeProblems(MACHINE, inForeignCaller).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inForeignCaller).sort(), [+ 'MOON_PHASE is raised by claim but not declared there',+ 'MOON_PHASE is raised by reserve but not declared there',+ ], 'the foreign-state caller is still audited outside its exact evidence catches');const inCaughtBaseline = editedSource('board-query.js', /^export function specApprovalBaseline\(board\) \{$/m,"$&\n if (!board) throw new Refused('MOON_PHASE', 'wait for the full moon');");-- assert.deepEqual(codeProblems(MACHINE, inCaughtBaseline), [], 'the real caller catches a Refused from the baseline reader');++ assert.deepEqual(codeProblems(machineRules.MACHINE, inCaughtBaseline), [], 'the real caller catches a Refused from the baseline reader');const inBaselineCaller = editedSource('spec-approval.js', /^export function specApprovalState\(root, .*$/m,"$&\n if (!root) throw new Refused('MOON_PHASE', 'wait for the full moon');");-- assert.deepEqual(codeProblems(MACHINE, inBaselineCaller).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inBaselineCaller).sort(), ['MOON_PHASE is raised by accept and reject but not declared there','MOON_PHASE is raised by claim but not declared there','MOON_PHASE is raised by refreeze but not declared there',@@@ -600,34 -590,34 +601,34 @@@const inHistoricalCaller = editedSource('rigor-auto-source.js',new RegExp(`^export function ${helper}\\(record\\) \\{$`, 'm'),"$&\n throw new Refused('MOON_PHASE', 'wait for the full moon');");-- assert.deepEqual(codeProblems(MACHINE, inHistoricalCaller).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inHistoricalCaller).sort(), ['MOON_PHASE is raised by accept and reject but not declared there','MOON_PHASE is raised by reopen but not declared there',], 'a new refusal outside the historical parser catch still reaches lifecycle moves');}const inFreeze = editedSource('spec.js', /^export function frozenCriterion\(spec, item, doctrine = null\) \{$/m, "$&\n if (item.item_title === 'moon') throw new Refused('MOON_PHASE', 'wait for the full moon');");-- assert.deepEqual(codeProblems(MACHINE, inFreeze).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inFreeze).sort(), ['MOON_PHASE is raised by claim but not declared there','MOON_PHASE is raised by refreeze but not declared there',], 'claim and refreeze let a freeze refusal through; submit and verify catch it');const inProof = editedSource('spec-approval.js', /^function approvalEvidence\(root, evidenceErrors\) \{$/m, "$&\n if (!root) throw new Refused('MOON_PHASE', 'wait for the full moon');");-- assert.deepEqual(codeProblems(MACHINE, inProof).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inProof).sort(), ['MOON_PHASE is raised by accept and reject but not declared there','MOON_PHASE is raised by claim but not declared there','MOON_PHASE is raised by refreeze but not declared there',], 'only caught proof readers are excluded; a new guard inside their caller is still audited');const inArrow = editedSource('route-escalation.js', /^export const canTake = .*$/m, "import { Refused } from './refused.js';\nexport const canTake = (agentRoute, itemRoute) => { if (!agentRoute) throw new Refused('NO_ROUTE', 'no route'); return ROUTES.indexOf(itemRoute) <= ROUTES.indexOf(agentRoute); };");-- assert.deepEqual(codeProblems(MACHINE, inArrow).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inArrow).sort(), ['NO_ROUTE is raised by accept and reject but not declared there','NO_ROUTE is raised by claim but not declared there','NO_ROUTE is raised by reserve but not declared there',], 'reserve reaches the route check through the reviewer checks it shares with a verdict');const doubleQuoted = editedSource('cli-read-context.js', /^(?:export )?const cdTo = .*$/m, "const cdTo = (root) => { if (!root) throw new Refused(\"NO_ROOT\", 'no root'); return 'cd ' + root + ' &&'; };");-- assert.deepEqual(codeProblems(MACHINE, doubleQuoted), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, doubleQuoted), ['NO_ROOT is raised by submit but not declared there','NO_ROOT is raised by accept and reject but not declared there',]);@@@ -652,7 -642,7 +653,7 @@@ const freeze = (item) => ({ text: item.* @returns {{ file: string, board: any, raw: () => DatabaseSync, done: () => void }}*/function boardOnDisk(clock) {-- const dir = mkdtempSync(join(tmpdir(), 'pullboard-machine-'));++ const dir = fs.mkdtempSync(join(tmpdir(), 'pullboard-machine-'));const file = join(dir, 'board.sqlite');const board = store.openBoard(file, clock);store.register(board, { lane: 'coordinator', path: '/repo' });@@@ -675,7 -665,7 +676,7 @@@// already closed by the test}}-- rmSync(dir, { recursive: true, force: true });++ fs.rmSync(dir, { recursive: true, force: true });},};}@@@ -790,7 -780,7 +791,7 @@@ test('an older board gets the triggersconst lab = boardOnDisk();try {const id = store.addItem(lab.board, { by: 'coordinator', lane: 'web', title: 'Page' });-- const every = storeTriggers().map(({ name }) => name).sort();++ const every = machineRules.storeTriggers().map(({ name }) => name).sort();assert.deepEqual(triggerNames(lab.board), every);store.closeBoard(lab.board);@@@ -829,16 -819,16 +830,16 @@@});test('the triggers come from the declaration, so a changed declaration changes them [M1, M3]', () => {-- const moveSql = (machine) => storeTriggers(machine).find(({ name }) => name === 'machine_item_move').sql;-- const pairs = MACHINE.moves.flatMap((move) => move.from.filter((from) => from !== move.to).map((from) => `'${from}>${move.to}'`));-- for (const pair of pairs) assert.ok(moveSql(MACHINE).includes(pair), `the move trigger allows ${pair}`);++ const moveSql = (machine) => machineRules.storeTriggers(machine).find(({ name }) => name === 'machine_item_move').sql;++ const pairs = machineRules.MACHINE.moves.flatMap((move) => move.from.filter((from) => from !== move.to).map((from) => `'${from}>${move.to}'`));++ for (const pair of pairs) assert.ok(moveSql(machineRules.MACHINE).includes(pair), `the move trigger allows ${pair}`);// Outside intake now legitimately declares open>submitted; claimed>verified still cannot bypass a submitted review.-- assert.ok(!moveSql(MACHINE).includes("'claimed>verified'"));++ assert.ok(!moveSql(machineRules.MACHINE).includes("'claimed>verified'"));const machine = copy();-- machine.moves.push({ verb: 'testDirectVerdict', from: ['claimed'], to: 'verified', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', IN_STATE], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'] });++ machine.moves.push({ verb: 'testDirectVerdict', from: ['claimed'], to: 'verified', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', machineRules.IN_STATE], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'] });assert.ok(moveSql(machine).includes("'claimed>verified'"));-- const names = storeTriggers().map(({ name }) => name);-- for (const state of MACHINE.states.filter((entry) => entry.requires.length)) assert.ok(names.includes(`machine_fields_${state.id}`), `${state.id} has a fields trigger`);++ const names = machineRules.storeTriggers().map(({ name }) => name);++ for (const state of machineRules.MACHINE.states.filter((entry) => entry.requires.length)) assert.ok(names.includes(`machine_fields_${state.id}`), `${state.id} has a fields trigger`);assert.ok(names.includes('machine_proof_verified'));});@@@ -892,29 -882,29 +893,29 @@@ test('a field a state needs cannot be btest("a blank field in the board file is exactly what JavaScript's trim removes [M3]", () => {const trimmed = [];for (let code = 0; code <= 0xffff; code += 1) if (String.fromCharCode(code).trim() === '') trimmed.push(code);-- assert.deepEqual(BLANKS, trimmed);++ assert.deepEqual(machineRules.BLANKS, trimmed);});const BIN = join(import.meta.dirname, '..', 'bin', 'pullboard.js');test('docs/lifecycle.md is the page the declaration generates, so a stale copy fails [M1, P4]', () => {-- const page = lifecycleMarkdown();-- const committed = readFileSync(new URL('../docs/lifecycle.md', import.meta.url), 'utf8');++ const page = machineRules.lifecycleMarkdown();++ const committed = fs.readFileSync(new URL('../docs/lifecycle.md', import.meta.url), 'utf8');assert.equal(committed, page, 'docs/lifecycle.md is stale; regenerate it: node bin/pullboard.js lifecycle > docs/lifecycle.md');assert.match(page, /```mermaid\nstateDiagram-v2\n {2}\[\*\] --> open\n/);-- for (const state of MACHINE.states) assert.match(page, new RegExp(`^\\| ${state.id}( \\(final\\))? \\|`, 'm'), `${state.id} has a row`);-- for (const move of MACHINE.moves) {++ for (const state of machineRules.MACHINE.states) assert.match(page, new RegExp(`^\\| ${state.id}( \\(final\\))? \\|`, 'm'), `${state.id} has a row`);++ for (const move of machineRules.MACHINE.moves) {assert.match(page, new RegExp(`^\\| ${move.verb} \\| ${move.from.join(', ')} \\| ${move.to} \\|`, 'm'), `${move.verb} has a row`);for (const from of move.from) assert.ok(page.includes(` ${from} --> ${move.to}: ${move.verb}`), `the diagram draws ${move.verb} from ${from}`);-- for (const id of effectiveGuards(move)) assert.ok(page.includes(id), `${move.verb}'s guard ${id} is listed`);++ for (const id of machineRules.effectiveGuards(move)) assert.ok(page.includes(id), `${move.verb}'s guard ${id} is listed`);}-- for (const [state, guards] of Object.entries(MACHINE.exitGuards)) assert.ok(page.includes(`| ${state} | ${guards.join(', ')} |`), `${state}'s exit guards are listed`);-- const codes = new Set([...MACHINE.guards.flatMap((guard) => [guard.refuse, ...(guard.alsoRefuses ?? []).map((entry) => entry.code)]), ...MACHINE.moves.flatMap((move) => [move.refuse, ...(move.alsoRefuses ?? []).map((entry) => entry.code)]), MACHINE.unknownMove.refuse].filter(Boolean));++ for (const [state, guards] of Object.entries(machineRules.MACHINE.exitGuards)) assert.ok(page.includes(`| ${state} | ${guards.join(', ')} |`), `${state}'s exit guards are listed`);++ const codes = new Set([...MACHINE.guards.flatMap((guard) => [guard.refuse, ...(guard.alsoRefuses ?? []).map((entry) => entry.code)]), ...MACHINE.moves.flatMap((move) => [move.refuse, ...(move.alsoRefuses ?? []).map((entry) => entry.code)]), machineRules.MACHINE.unknownMove.refuse].filter(Boolean));for (const code of codes) assert.match(page, new RegExp(`^\\| ${code} \\|`, 'm'), `${code} is in the refusal table`);});test('the lifecycle page limits family matching to require and explains unknown families [O2, O3]', () => {-- const page = lifecycleMarkdown();++ const page = machineRules.lifecycleMarkdown();assert.match(page, /^\| O2_FAMILY_MATCH \| the builder and verifier have different declared families; an undeclared family counts as a match, only when verify\.family is require \| ask the coordinator for a verifier from another declared family \|$/m);for (const verb of ['reserve', 'accept', 'reject']) {assert.match(page, new RegExp(`^\\| ${verb} \\| .*familyAllows \\(O2_FAMILY_MATCH\\)`, 'm'));@@@ -923,27 -913,27 +924,27 @@@test('the page and the help follow the declaration: a new move appears in both [M1, P4]', () => {const machine = copy();-- machine.moves.push({ verb: 'shelve', from: ['open'], to: 'withdrawn', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'noteGiven', 'itemExists', IN_STATE], sets: ['item_withdrawn_reason'] });-- assert.ok(!lifecycleMarkdown().includes('shelve'));-- assert.ok(lifecycleMarkdown(machine).includes(' open --> withdrawn: shelve'));-- assert.match(lifecycleMarkdown(machine), /^\| shelve \| open \| withdrawn \| coordinator \|/m);-- assert.match(lifecycleHelp(machine), /^ {2}coordinator +.*\bshelve\b/m);-- assert.doesNotMatch(lifecycleHelp(machine), /^ {2}agent +.*\bshelve\b/m);++ machine.moves.push({ verb: 'shelve', from: ['open'], to: 'withdrawn', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'noteGiven', 'itemExists', machineRules.IN_STATE], sets: ['item_withdrawn_reason'] });++ assert.ok(!machineRules.lifecycleMarkdown().includes('shelve'));++ assert.ok(machineRules.lifecycleMarkdown(machine).includes(' open --> withdrawn: shelve'));++ assert.match(machineRules.lifecycleMarkdown(machine), /^\| shelve \| open \| withdrawn \| coordinator \|/m);++ assert.match(machineRules.lifecycleHelp(machine), /^ {2}coordinator +.*\bshelve\b/m);++ assert.doesNotMatch(machineRules.lifecycleHelp(machine), /^ {2}agent +.*\bshelve\b/m);});test('pullboard help lists each role\'s moves from the declaration, and pullboard lifecycle prints the page [M1, P4]', () => {const help = runFixtureChild(process.execPath, [BIN, 'help', '--all'], { encoding: 'utf8' });assert.equal(help.status, 0, help.stderr);-- for (const role of MACHINE.roles) {++ for (const role of machineRules.MACHINE.roles) {const line = help.stdout.split('\n').find((text) => text.startsWith(` ${role} `));assert.ok(line, `help has a line for ${role}`);const listed = line.slice(role.length + 2).split(',').map((part) => part.trim().split(' ')[0]).filter(Boolean);-- assert.deepEqual(listed.sort(), [...new Set(MACHINE.moves.filter((move) => move.by.includes(role)).map((move) => move.verb))].sort(), `${role}'s moves`);++ assert.deepEqual(listed.sort(), [...new Set(machineRules.MACHINE.moves.filter((move) => move.by.includes(role)).map((move) => move.verb))].sort(), `${role}'s moves`);}-- assert.ok(HELP.all.includes(lifecycleHelp()), 'the full help screen carries the generated section, not a typed copy');++ assert.ok(HELP.all.includes(machineRules.lifecycleHelp()), 'the full help screen carries the generated section, not a typed copy');const printed = runFixtureChild(process.execPath, [BIN, 'lifecycle'], { encoding: 'utf8' });assert.equal(printed.status, 0, printed.stderr);-- assert.equal(printed.stdout, lifecycleMarkdown());++ assert.equal(printed.stdout, machineRules.lifecycleMarkdown());});/** Guards checked before the explicit transition: CLI facts and optional roadmap selection. */@@@ -962,10 -952,10 +963,10 @@@ const PRECHECKED =* @returns {string[]}*/function declaredBoardOrder(verb) {-- const move = moveOf(MACHINE, verb);-- return effectiveGuards(move)++ const move = moveOf(machineRules.MACHINE, verb);++ return machineRules.effectiveGuards(move).filter((id) => !PRECHECKED[verb].includes(id))-- .map((id) => (id === IN_STATE ? move.refuse : MACHINE.guards.find((guard) => guard.id === id).refuse));++ .map((id) => (id === machineRules.IN_STATE ? move.refuse : machineRules.MACHINE.guards.find((guard) => guard.id === id).refuse));}/**@@@ -1215,7 -1205,7 +1216,7 @@@ test('a reserved review refuses every o});test('next --verify reserves the review for the reviewLease and says until when; show names the holder; another verifier is passed over and refused [V15]', () => {-- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-reserve-')));++ const dir = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'pullboard-reserve-')));try {const env = {...process.env,@@@ -1232,10 -1222,10 +1233,10 @@@// The test runner's per-test timeout bounds hangs without killing this CLI early under load.const run = (cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });const repo = join(dir, 'repo');-- mkdirSync(repo);++ fs.mkdirSync(repo);git(repo, 'init', '-q', '-b', 'main');-- writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true', reviewLease: '45m', lanes: { web: { owns: ['web/'] } } }));-- writeFileSync(join(repo, 'SPEC.md'), '# Demo\n\n## G · Goals\n- G1 [approved, must] It greets. | gate: test\n');++ fs.writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true', reviewLease: '45m', lanes: { web: { owns: ['web/'] } } }));++ fs.writeFileSync(join(repo, 'SPEC.md'), '# Demo\n\n## G · Goals\n- G1 [approved, must] It greets. | gate: test\n');git(repo, 'add', '-A');git(repo, 'commit', '-q', '-m', 'chore: a spec');const [builder, holder, other] = ['web-1', 'web-2', 'web-3'].map((name) => {@@@ -1248,8 -1238,8 +1249,8 @@@const added = run(repo, 'add', 'web', 'Greet', '--specs', 'G1', '--criterion', 'It greets.');assert.equal(added.status, 0, added.stderr);assert.equal(run(builder, 'claim', '1').status, 0);-- mkdirSync(join(builder, 'web'));-- writeFileSync(join(builder, 'web', 'greet.txt'), 'hello\n');++ fs.mkdirSync(join(builder, 'web'));++ fs.writeFileSync(join(builder, 'web', 'greet.txt'), 'hello\n');git(builder, 'add', '-A');git(builder, 'commit', '-q', '-m', 'feat(web): greet [G1]');const commit = git(builder, 'rev-parse', 'HEAD');@@@ -1290,7 -1280,7 +1291,7 @@@const accepted = run(holder, 'verify', '1', 'accept', '--note', 'checked out the commit; web/greet.txt says hello');assert.equal(accepted.status, 0, accepted.stderr);} finally {-- rmSync(dir, { recursive: true, force: true });++ fs.rmSync(dir, { recursive: true, force: true });}});@@@ -1336,23 -1326,23 +1337,23 @@@ test('next --verify looks and reserves});test('the review lease is reviewLease in pullboard.json, 30 minutes unless the repo says otherwise [V15]', () => {-- const dir = mkdtempSync(join(tmpdir(), 'pullboard-review-lease-'));++ const dir = fs.mkdtempSync(join(tmpdir(), 'pullboard-review-lease-'));try {const leaseOf = (config) => {-- writeFileSync(join(dir, 'pullboard.json'), JSON.stringify({ gate: 'true', ...config }));++ fs.writeFileSync(join(dir, 'pullboard.json'), JSON.stringify({ gate: 'true', ...config }));return loadConfig(dir).reviewLeaseMs;};assert.equal(leaseOf({}), 30 * 60_000);assert.equal(leaseOf({ reviewLease: '2h' }), 2 * 3_600_000);assert.throws(() => leaseOf({ reviewLease: 'soon' }), { code: 'BAD_CONFIG', message: /reviewLease "soon" is not a duration/ });} finally {-- rmSync(dir, { recursive: true, force: true });++ fs.rmSync(dir, { recursive: true, force: true });}});test('the lifecycle page and the help show the reservation: reserve, and reviewFree on every verdict [V15, M1]', () => {-- const page = lifecycleMarkdown();- assert.match(page, /^\| reserve \| submitted \| submitted \| agent, coordinator \| .*reviewFree \(REVIEW_HELD\) \|$/m);++ const page = machineRules.lifecycleMarkdown();+ assert.match(page, /^\| reserve \| submitted \| submitted \| agent, coordinator \| .*reviewFree \(REVIEW_HELD\), result \(BAD_DEPENDENCIES\) \|$/m);for (const verb of ['accept', 'reject']) assert.match(page, new RegExp(`^\\| ${verb} \\| submitted, verified \\| .*policyAllows \\(COORDINATOR_VERIFIES\\), familyAllows \\(O2_FAMILY_MATCH\\), reviewFree \\(REVIEW_HELD\\), criterionUnchanged`, 'm'));assert.match(page, /^\| REVIEW_HELD \| no other agent holds its review under a live lease \| pullboard next --verify/m);assert.match(HELP.all, /^ {2}agent +intake, claim, release, submit, reserve, accept, reject, reopen, escalate, refreeze \(when a live claim has a pending coordinator correction\)$/m);@@@ -1364,8 -1354,8 +1365,8 @@@ test('the two conditional guards behavtry {const { board } = lab;const claimAs = (id, agentId, freezer) => outcome(() => store.claim(board, id, { agentId, lane: 'web', leaseMs: 7_200_000, freeze: freezer }));-- assert.match(MACHINE.guards.find((guard) => guard.id === 'laneOpen').when, /renewing its own live claim/);-- assert.match(MACHINE.guards.find((guard) => guard.id === 'rowsInForce').when, /where the criterion freezes/);++ assert.match(machineRules.MACHINE.guards.find((guard) => guard.id === 'laneOpen').when, /renewing its own live claim/);++ assert.match(machineRules.MACHINE.guards.find((guard) => guard.id === 'rowsInForce').when, /where the criterion freezes/);const mine = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });const theirs = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });@@@ -1401,7 -1391,7 +1402,7 @@@*/function statusWriters(read) {const writers = [];-- for (const file of readdirSync(new URL('../src/', import.meta.url)).filter((name) => name.endsWith('.js'))) {++ for (const file of fs.readdirSync(new URL('../src/', import.meta.url)).filter((name) => name.endsWith('.js'))) {const source = read(file);const allowedNames = file === 'board.js' ? ['moveItem', 'setItem'] : file === 'board-query.js' ? ['current'] : [];const allowed = allowedNames.map((name) => functionsIn(source).get(name));@@@ -1461,12 -1451,12 +1462,12 @@@ test('the board refuses a status writte});test('a helper added to the board that changes a status outside moveItem is refused when it runs [M1]', async () => {-- const dir = mkdtempSync(join(tmpdir(), 'pullboard-planted-'));++ const dir = fs.mkdtempSync(join(tmpdir(), 'pullboard-planted-'));try {-- for (const file of readdirSync(new URL('../src/', import.meta.url), { recursive: true }).filter((name) => name.endsWith('.js'))) {++ for (const file of fs.readdirSync(new URL('../src/', import.meta.url), { recursive: true }).filter((name) => name.endsWith('.js'))) {const source = fromDisk(file);-- mkdirSync(dirname(join(dir, file)), { recursive: true });-- writeFileSync(join(dir, file), file === 'board.js' ? `${source}\nexport function reopenByHand(board, id) {\n board.db.prepare("update item set item_status = 'open', item_owner = null, item_lease_until = null where item_id = ?").run(id);\n}\n` : source);++ fs.mkdirSync(dirname(join(dir, file)), { recursive: true });++ fs.writeFileSync(join(dir, file), file === 'board.js' ? `${source}\nexport function reopenByHand(board, id) {\n board.db.prepare("update item set item_status = 'open', item_owner = null, item_lease_until = null where item_id = ?").run(id);\n}\n` : source);}const copy = await import(pathToFileURL(join(dir, 'board.js')).href);const board = copy.openBoard(':memory:');@@@ -1478,7 -1468,7 +1479,7 @@@assert.equal(copy.getItem(board, id).item_status, 'claimed');copy.closeBoard(board);} finally {-- rmSync(dir, { recursive: true, force: true });++ fs.rmSync(dir, { recursive: true, force: true });}});@@@ -1486,7 -1476,7 +1487,7 @@@test('transport boundaries keep a new item refusal in ordered dispatch visible [M1,M4,H16]', () => {const inDispatch = editedSource('cli.js', /^(?:export )?async function ordered\(ctx, board, operation, args\) \{$/m,"$&\n if (args[0] === 999) throw new Refused('MOON_PHASE', 'wait for the full moon');");-- assert.deepEqual(codeProblems(MACHINE, inDispatch).sort(), [++ assert.deepEqual(codeProblems(machineRules.MACHINE, inDispatch).sort(), ['MOON_PHASE is raised by accept and reject but not declared there','MOON_PHASE is raised by submit but not declared there',], 'transport authentication is separate but a dispatcher item guard still belongs to the lifecycle');@@@ -1495,5 -1485,5 +1496,5 @@@test('Rigor historical data boundaries do not hide a new projection refusal [M1,M4]', () => {const broken = editedSource('rigor-counter-state.js', /export function rigorCounterKeys\(event, person\) \{/, "export function rigorCounterKeys(event, person) { if (event.event_kind === 'probe') throw new Refused('RIGOR_PROBE', 'new item eligibility rule');");-- assert.ok(codeProblems(MACHINE, broken).includes('RIGOR_PROBE is raised by claim but not declared there'));++ assert.ok(codeProblems(machineRules.MACHINE, broken).includes('RIGOR_PROBE is raised by claim but not declared there'));});diff --cc test/person-signing-case.jsindex 00000000,00000000..4d544b8enew file mode 100644--- /dev/null+++ b/test/person-signing-case.js@@@ -1,0 -1,0 +1,287 @@@++/** The complete person-signing case, extracted without changing its native fixtures or assertions [E22,H16]. */++import assert from 'node:assert/strict';++import { createHash, randomUUID } from 'node:crypto';++import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';++import { join } from 'node:path';++import { DatabaseSync } from 'node:sqlite';++import { relayClientFixture, relayFixtureChild } from './relay-client-fixture.js';++import { runFixtureChild, runFixtureGit } from './fixture-child.js';++import { grantChallenge, softwarePasskey } from './person-passkey-fixture.js';++import { refuseNamedSigners } from '../src/person-signing-cli.js';++import { relayWorkBudgetMs } from './relay-budget.js';++++/** Reuse the original test's paths, process helpers and request/credential assertions. */++export async function personSigningCase(t, { CLI, TRUSTED_CLI, helpers, passkeyRequest, holdsNoPersonCredential, relayCall }) {++ const box = await relayClientFixture(t);++ // The shipped command, handed the loopback fixture relay as an explicit trusted parameter in this test's own call path:++ // no environment variable or global can make the real CLI trust it (#408 rulings 38756cb3 and 28611).++ const trusted = [TRUSTED_CLI, box.origin];++ /** Run the command in the main checkout with a chosen environment, trusting only this fixture relay. */++ const cli = (env, ...args) => relayFixtureChild(box.root, env, [...trusted, ...args, '--json']);++ // S10a: an agent that cleared AI_AGENT and CLAUDECODE has exactly the person's shell markers.++ const cleared = { ...box.env };++ const marked = { ...box.env, AI_AGENT: '1', CLAUDECODE: '1' };++++ // Off, the default: person moves work as today, and status says once that they are not signed.++ const text = runFixtureChild(process.execPath, [CLI, 'status'], { cwd: box.root, env: box.env, encoding: 'utf8' });++ assert.equal(text.status, 0);++ assert.equal(text.stdout.split('\n').filter((line) => /person moves are not signed/u.test(line)).length, 1, 'status says it in one line');++ assert.equal((await box.cli('status')).document.person.signed, false);++ const early = (await box.cli('shout', 'person', 'A decision before signing', '--decision')).document.id;++ assert.equal((await cli(box.env, 'answer', String(early), 'Off answers as today', '--as', 'person')).code, 0, 'off: the terminal answers as the person');++++ // A board with no relay cannot turn signing on: only the relay can vouch for a passkey (#408 trust-anchor ruling).++ const offline = await cli(marked, 'settings', 'person.signed', 'on');++ assert.equal(offline.document.error?.code, 'PERSON_SIGNING_RELAY', `no relay, no signing: ${JSON.stringify(offline.document)}`);++ // Linked, turning signing on is allowed from the terminal, even an agent's; unlinking then still works with no tap.++ assert.equal((await box.link()).code, 0);++ const on = await cli(marked, 'settings', 'person.signed', 'on');++ assert.equal(on.code, 0, `an agent may turn signing on: ${JSON.stringify(on.document)}`);++ assert.equal(on.document.person.signed, true);++ const ask = (await box.cli('shout', 'person', 'A decision only the person answers', '--decision')).document.id;++ // The same board on a device that is not paired: its link set aside, restored below without linking again, and no++ // move succeeds meanwhile, so the relay and the board still agree when it returns.++ renameSync(box.linkFile, `${box.linkFile}.unpaired`);++++ // S10a and the on-and-unpaired case: every person move fails closed at once, naming how to pair a passkey.++ const calls = box.calls.length;++ for (const words of [['answer', String(ask), 'S10a cleared markers', '--as', 'person'], ['spec', 'approve', 'E1'], ['spec', 'approve', 'doctrine:D1'],++ ['spec', 'decline', 'E1', '--reason', 'no'], ['land', '--waive', 'test/x.test.js', '--until', '2099-01-01', '--reason', 'flaky'], ['settings', 'person.signed', 'off']]) {++ const refused = await cli(cleared, ...words);++ assert.equal(refused.code, 1, words.join(' '));++ assert.equal(refused.document.error.code, 'PERSON_SIGNED', `${words.join(' ')}: ${JSON.stringify(refused.document)}`);++ assert.match(refused.document.error.next, /relay on --all/u, 'unpaired: the next step pairs a phone or browser');++ assert.match(refused.document.error.next, /passkey/u);++ }++ assert.equal(box.calls.length, calls, 'refused locally, before any network call or wait');++ assert.equal((await cli(marked, 'answer', String(ask), 'marked agent', '--as', 'person')).document.error.code, 'PERSON_SIGNED', 'an agent shell is refused too');++ const remote = await cli({ ...cleared, SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22' }, 'answer', String(ask), 'from SSH', '--as', 'person');++ assert.equal(remote.document.error.code, 'PERSON_SIGNED', 'over SSH the same passkey step applies');++++ // No local file edit turns it off: not the project config, not machine settings.++ const config = join(box.root, 'pullboard.json');++ writeFileSync(config, JSON.stringify({ ...JSON.parse(readFileSync(config, 'utf8')), person: { signed: false } }, null, 2) + '\n');++ mkdirSync(box.env.PULLBOARD_MACHINE_HOME, { recursive: true });++ writeFileSync(join(box.env.PULLBOARD_MACHINE_HOME, 'settings.json'), JSON.stringify({ person: { signed: false } }) + '\n');++ assert.equal((await cli(cleared, 'answer', String(ask), 'after edits', '--as', 'person')).document.error.code, 'PERSON_SIGNED', 'edits leave it on');++ assert.equal((await box.cli('status')).document.person.signed, true);++++ // S10b: whatever the OS user can read, an agent can read, so the local view's channel is refused too.++ const viewed = await executeMove(box.root, { verb: 'answer', item: ask, args: { as: 'person', text: 'through the view secret' } }, main);++ assert.equal(viewed.body.error?.code, 'PERSON_SIGNED', 'the view channel is not the person once signing is on');++++ // Linked, a terminal person move goes to the passkey as an action-bound request and says where to confirm.++ renameSync(`${box.linkFile}.unpaired`, box.linkFile);++ assert.ok(holdsNoPersonCredential(box.root) && holdsNoPersonCredential(box.env.HOME), 'no file holds a person session or grant');++ const terminal = helpers.launch({ ...box, env: { ...cleared, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },++ box.root, process.execPath, [...trusted, 'answer', String(ask), 'Signed on the passkey', '--as', 'person', '--json']);++ t.after(async () => { if (terminal.exitCode === null && terminal.signalCode === null) terminal.kill('SIGTERM'); await terminal.closed; });++ /** Observe fixture SQLite directly; no second command may execute the waiting action. */++ const nativeRows = (sql, ...args) => {++ const db = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });++ try { return db.prepare(sql).all(...args); } finally { db.close(); }++ };++ /** Read durable request receipts without running status, export or another command. */++ const nativeRequests = () => Object.fromEntries(JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?',++ 'relay_person_requests')[0]?.meta_value ?? '[]').filter(record => !record.duplicateOf).map(record => [record.id, record]));++ await helpers.waitFor(() => {++ assert.equal(terminal.exitCode, null, terminal.stderrText);++ return terminal.stderrText.includes(box.origin) && terminal.stderrText.includes('this terminal is waiting');++ }, 'the original SSH terminal asks for one passkey confirmation', relayWorkBudgetMs(5));++ const proposals = JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0].meta_value);++ const proposal = proposals.at(-1);++ assert.deepEqual(proposal.move, { verb: 'answer', item: ask, args: { as: 'person', text: 'Signed on the passkey' } }, 'the exact move waits for the passkey');++++ // The person registers a passkey with user presence; agents and machines cannot ask for a grant.++ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));++ const phone = (await box.phoneSession()).token;++ const passkey = softwarePasskey(box.origin);++ const challenge = await relayCall(box, phone, 'POST', '/api/v1/passkeys/challenge', {});++ assert.equal(challenge.status, 200, JSON.stringify(challenge.document));++ const registered = await relayCall(box, phone, 'POST', '/api/v1/passkeys', { challenge: challenge.document.challenge, ...passkey.create(challenge.document.challenge) });++ assert.equal(registered.status, 200, JSON.stringify(registered.document));++ const document = { version: 1, type: 'person-request', id: proposal.id, move: proposal.move };++ const machineGrant = await relayCall(box, link.token, 'POST', `/api/v1/boards/${link.board}/person-grants`, { request: proposal.id, digest: 'a'.repeat(64) });++ assert.equal(machineGrant.document.error?.code, 'HUMAN_REQUIRED', 'the machine credential, which agents share, gets no grant');++ /** Ask the relay for a fresh single-use grant for this request and the digest of its exact intent. */++ const grantFor = async (document) => {++ const digest = createHash('sha256').update(JSON.stringify(document)).digest('hex');++ const issued = await relayCall(box, phone, 'POST', `/api/v1/boards/${link.board}/person-grants`, { request: document.id, digest });++ assert.equal(issued.status, 200, JSON.stringify(issued.document));++ assert.deepEqual(issued.document.credentials, [passkey.id]);++ return issued.document.grant;++ };++++ // Without user presence, or with no assertion at all, nothing acts as the person.++ const absent = await passkeyRequest(box, phone, document, { grant: await grantFor(document), ...passkey.get(grantChallenge('not-this-grant')) });++ assert.equal(absent.document.error?.code, 'PASSKEY_ASSERTION', 'an assertion over another challenge is refused');++ const grant = await grantFor(document);++ const noPresence = await passkeyRequest(box, phone, document, { grant, ...passkey.get(grantChallenge(grant), { presence: false }) });++ assert.equal(noPresence.document.error?.code, 'PASSKEY_PRESENCE', 'an authenticator answer with no user present is refused');++ const elsewhere = await passkeyRequest(box, phone, document, { grant, ...passkey.get(grantChallenge(grant), { origin: 'http://elsewhere.localhost' }) });++ assert.equal(elsewhere.document.error?.code, 'PASSKEY_ASSERTION', 'an answer made for another site is refused');++ const forgedSignature = { grant, ...passkey.get(grantChallenge(grant)), signature: passkey.get(grantChallenge('other bytes')).signature };++ assert.equal((await passkeyRequest(box, phone, document, forgedSignature)).document.error?.code, 'PASSKEY_ASSERTION', 'a signature over other bytes is refused');++ const unsigned = { version: 1, type: 'person-request', id: randomUUID(), move: proposal.move };++ assert.equal((await passkeyRequest(box, phone, unsigned)).status, 200, 'the relay stores a session request without a passkey');++ await helpers.waitFor(() => nativeRequests()[unsigned.id]?.status === 'refused', 'the waiting terminal refuses unsigned intent', relayWorkBudgetMs(5));++ let received = nativeRequests();++ assert.equal(received[unsigned.id].status, 'refused');++ assert.equal(received[unsigned.id].error.code, 'PERSON_SIGNED', 'without a passkey the native board refuses it');++++ // One confirmation on the passkey carries out the exact move, once.++ const presence = { grant, ...passkey.get(grantChallenge(grant)) };++ const signed = await passkeyRequest(box, phone, document, presence);++ assert.equal(signed.status, 200, JSON.stringify(signed.document));++ const terminalResult = await terminal.closed;++ assert.equal(terminalResult.code, 0, terminal.stderrText);++ assert.equal(JSON.parse(terminal.stdoutText).request, proposal.id, 'the original terminal reports its exact request');++ received = nativeRequests();++ assert.equal(received[proposal.id].status, 'done', JSON.stringify(received[proposal.id]));++ const answers = nativeRows('SELECT * FROM shout WHERE shout_answers=?', ask);++ assert.deepEqual(answers.map((row) => [row.shout_from, row.shout_text]), [['person', 'Signed on the passkey']]);++ const replay = await passkeyRequest(box, phone, { ...document, id: randomUUID() }, presence);++ assert.equal(replay.document.error?.code, 'PHONE_APPROVAL_USED', 'the grant is single-use');++ assert.ok(holdsNoPersonCredential(box.root) && holdsNoPersonCredential(box.env.HOME), 'the grant was never stored');++++ // A hand edit to the board file cannot forge a passkey request, turn signing off or swap the relay key.++ const raw = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'));++ try {++ /** One board metadata value, read straight from the file. */++ const meta = (key) => raw.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key)?.meta_value;++ assert.equal(meta('event_log_version'), '2', 'a Pullboard from before signed moves refuses this board');++ assert.throws(() => raw.prepare("UPDATE board_meta SET meta_value='{}' WHERE meta_key='person_authority_local'").run(), /PERSON_AUTHORITY/u, 'the pinned relay key stays');++ assert.throws(() => raw.prepare("INSERT OR REPLACE INTO board_meta(meta_key,meta_value) VALUES ('person_authority_local','{}')").run(), /PERSON_AUTHORITY/u);++ assert.throws(() => raw.prepare("DELETE FROM event WHERE event_kind='person_signing'").run(), /APPEND_ONLY/u, 'the signing history stays');++ const records = JSON.parse(meta('relay_person_requests'));++ const genuine = records.find((record) => record.id === proposal.id);++ const sender = JSON.parse(genuine.received).sender;++ // A genuine stamp copied into a hand-written off names the digest of another request.++ raw.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?,?,?,?,?)').run(new Date().toISOString(), 'person', 'person_signing', null,++ JSON.stringify({ signed: false, request: proposal.id, presence: sender.presence, intent: { version: 1, type: 'person-request', id: proposal.id, move: { verb: 'signing', args: { signed: 'off' } } } }));++ // The same stamp on a rewritten request: the same id, another answer, waiting to run again.++ const forged = structuredClone(document);++ forged.move.args.text = 'A forged second answer';++ const { result, resultSequence, executor, executorUntil, ...rest } = genuine;++ const rewritten = { ...rest, move: forged.move, encoded: JSON.stringify(forged), received: JSON.stringify({ document: forged, sender }), status: 'waiting' };++ raw.prepare('UPDATE board_meta SET meta_value=? WHERE meta_key=?').run(JSON.stringify(records.map((record) => record.id === genuine.id ? rewritten : record)), 'relay_person_requests');++ } finally { raw.close(); }++ assert.equal((await box.cli('status')).document.person.signed, true, 'the hand-written off turns nothing off');++ const waitingAgain = helpers.launch({ ...box, env: cleared }, box.root, process.execPath,++ [...trusted, 'answer', String(ask), 'still signed', '--as', 'person', '--json']);++ try {++ await helpers.waitFor(() => { assert.equal(waitingAgain.exitCode, null, waitingAgain.stderrText); return waitingAgain.stderrText.includes('this terminal is waiting'); },++ 'a cleared-marker terminal still waits for a new confirmation', relayWorkBudgetMs(5));++ assert.equal(nativeRows('SELECT * FROM shout WHERE shout_answers=?', ask).length, 1, 'waiting creates no second person answer');++ } finally { if (waitingAgain.exitCode === null && waitingAgain.signalCode === null) waitingAgain.kill('SIGTERM'); await waitingAgain.closed; }++ assert.equal((await box.cli('export')).document.tables.shout.filter((row) => row.shout_answers === ask).length, 1, 'the rewritten request never runs as the person');++++ // A signed row decision binds the exact rows the person saw; a row naming SSH signers is refused by name.++ const shown = { id: 'G1', text: 'A row the person decides on the passkey.' };++ writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8').replace('## G · Goals: what the client asked for\n',++ `## G · Goals: what the client asked for\n\n- G1 [draft, must] ${shown.text} | gate: review\n`));++ // The template's own placeholder G1 may sit beside it; the person sees the row this test wrote.++ shown.source = readFileSync(join(box.root, 'SPEC.md'), 'utf8').split(/\r?\n/u).find(line => line.startsWith('- G1 ') && line.includes(shown.text));++ const blind = { version: 1, type: 'person-request', id: randomUUID(), move: { verb: 'spec-approve', args: { ids: 'G1' } } };++ const seen = { ...blind, id: randomUUID(), rows: [shown] };++ for (const request of [blind, seen]) {++ const rowGrant = await grantFor(request);++ assert.equal((await passkeyRequest(box, phone, request, { grant: rowGrant, ...passkey.get(grantChallenge(rowGrant)) })).status, 200);++ }++ received = await receivedRequests(box, (...args) => cli(box.env, ...args));++ assert.equal(received[blind.id].error?.code, 'STALE_ROW_DECISION', 'a decision that does not name the rows shown is refused');++ assert.notEqual(received[seen.id].status, 'refused', JSON.stringify(received[seen.id]));++ const decided = (await box.cli('export')).document.tables.event.filter((row) => row.event_kind === 'row_decision');++ assert.deepEqual(decided.map((row) => [row.event_by, JSON.parse(row.event_detail).record.id]), [['person', 'G1']], 'the passkey decided exactly the row it showed');++ // The real CLI applies that decision, checked against the authority its relay vouches for, never a stored key (#408).++ const applied = await cli(box.env, 'spec', 'apply');++ assert.equal(applied.code, 0, JSON.stringify(applied.document));++ assert.match(readFileSync(join(box.root, 'SPEC.md'), 'utf8'), /- G1 \[approved, must\] A row the person decides on the passkey\./u, 'the native CLI applies the passkey approval');++ assert.throws(() => refuseNamedSigners([{ id: 'G2', signers: ['[email protected]'] }], ['G2']), { code: 'PERSON_SIGNER_REQUIRED', message: /G2 names its SSH signers alice@example\.com/u });++++ /** One live SSH command, one confirmation, no status/export/other CLI before its original exit. */++ async function confirmTerminal(argv, expectedVerb) {++ const beforeIds = new Set(JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0]?.meta_value ?? '[]').map(entry => entry.id));++ const child = helpers.launch({ ...box, env: { ...cleared, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },++ box.root, process.execPath, [...trusted, ...argv, '--json']);++ try {++ const proposal = await helpers.waitFor(() => {++ assert.equal(child.exitCode, null, child.stderrText);++ if (!child.stderrText.includes('this terminal is waiting')) return null;++ return JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0]?.meta_value ?? '[]').find(entry => !beforeIds.has(entry.id));++ }, 'the exact new terminal proposal', relayWorkBudgetMs(5));++ assert.equal(proposal.move.verb, expectedVerb);++ const request = { version: 1, type: 'person-request', id: proposal.id, move: proposal.move,++ ...(proposal.rows ? { rows: proposal.rows } : {}) };++ const actionGrant = await grantFor(request);++ assert.equal((await passkeyRequest(box, phone, request, { grant: actionGrant, ...passkey.get(grantChallenge(actionGrant)) })).status, 200);++ const outcome = await child.closed;++ assert.equal(outcome.code, 0, child.stderrText);++ const result = JSON.parse(child.stdoutText);++ assert.equal(result.request, proposal.id);++ assert.ok(['done', 'waiting'].includes(nativeRequests()[proposal.id].status));++ return result;++ } finally {++ if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');++ await child.closed;++ }++ }++ // Each newly mapped action must complete on its original terminal, with exact target/meaning.++ const factItem = (await box.cli('add', box.lane, 'SIGNED_FACT_TARGET')).document.item.item_id;++ const fact = await confirmTerminal(['fact', String(factItem), 'decision', 'Keep this exact rule', '--as', 'person', '--cause', 'row:G1', '--never-again'], 'fact');++ assert.equal(fact.item, factItem);++ assert.equal(fact.fact.text, 'Keep this exact rule');++ const held = await confirmTerminal(['hold', box.lane, '--as', 'person', '--reason', 'Wait for the exact reviewed rule'], 'hold');++ assert.equal(held.held, true);++ assert.equal(nativeRows('SELECT hold_reason,hold_by FROM hold WHERE hold_lane=?', box.lane)[0].hold_by, 'person');++ const unheld = await confirmTerminal(['hold', box.lane, '--as', 'person', '--off'], 'hold');++ assert.equal(unheld.held, false);++ assert.equal(nativeRows('SELECT * FROM hold WHERE hold_lane=?', box.lane).length, 0);++ for (const name of ['signed-watch-approved', 'signed-watch-declined']) {++ assert.equal((await box.cli('sentinel', 'propose', name, '--check', 'true', '--every', 'hourly', '--owner', 'coordinator')).code, 0);++ }++ const watch = await confirmTerminal(['sentinel', 'approve', 'signed-watch-approved'], 'sentinel-approve');++ assert.equal(watch.sentinel.status, 'approved');++ const declinedWatch = await confirmTerminal(['sentinel', 'decline', 'signed-watch-declined', '--reason', 'Do not run this exact watch'], 'sentinel-decline');++ assert.equal(declinedWatch.sentinel.status, 'declined');++ const question = 'Which store holds the data: SQLite. Choices: SQLite, Postgres.';++ writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8')++ + `\n- G2 [pending, must] ${question} | gate: review\n- G3 [draft, must] A terminal-approved row. | gate: review\n- G4 [draft, must] A terminal-declined row. | gate: review\n`);++ const answeredRow = await confirmTerminal(['spec', 'answer', 'G2', 'Postgres'], 'spec-answer');++ assert.equal(answeredRow.decisions[0].id, 'G2');++ assert.match(answeredRow.decisions[0].text, /data: Postgres/u);++ const approvedRow = await confirmTerminal(['spec', 'approve', 'G3'], 'spec-approve');++ assert.equal(approvedRow.decisions[0].decision, 'approve');++ const declinedRow = await confirmTerminal(['spec', 'decline', 'G4', '--reason', 'Do not approve this row'], 'spec-decline');++ assert.equal(declinedRow.decisions[0].decision, 'decline');++ writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8')++ + '\n- G5 [approved, must] An optional sign-off row. | gate: review\n- G6 [approved, must] A named-signature row. | gate: review | signers: [email protected]\n');++ mkdirSync(join(box.root, 'test'), { recursive: true });++ writeFileSync(join(box.root, 'test', 'signed-evidence.test.js'), '/** [G5] Cited evidence fixture; no test run is implied by optional sign-off. */\n');++ runFixtureGit(['add', 'test/signed-evidence.test.js'], { cwd: box.root, env: box.env });++ const sshFile = join(box.root, '.pullboard', 'signoffs.jsonl');++ const beforeSsh = existsSync(sshFile) ? readFileSync(sshFile, 'utf8') : null;++ const optionalSignoff = await confirmTerminal(['spec', 'signoff', 'G5'], 'spec-approve');++ assert.equal(optionalSignoff.count, 1);++ assert.equal(optionalSignoff.by, 'person');++ assert.equal(existsSync(sshFile) ? readFileSync(sshFile, 'utf8') : null, beforeSsh, 'passkey approval never writes an SSH signature');++ const namedSignoff = await cli(cleared, 'spec', 'signoff', 'G6');++ assert.equal(namedSignoff.document.error?.code, 'PERSON_SIGNER_REQUIRED');++ assert.match(namedSignoff.document.error.message, /G6 names its SSH signers alice@example\.com/u);++ const signerChange = await cli(cleared, 'spec', 'signers', 'add', '--by', '[email protected]', '--key', 'unread-key');++ assert.equal(signerChange.document.error?.code, 'PERSON_SIGNER_REQUIRED');++ assert.match(signerChange.document.error.message, /alice@example\.com/u);++++ const waiver = await confirmTerminal(['land', '--waive', 'gate:lint', '--until', '2099-01-01', '--reason', 'An explicit bounded fixture exception'], 'land-waive');++ assert.equal(waiver.waiver.test, 'gate:lint');++++ // Only the passkey turns signing off; unlinking offline keeps it on.++ const switchedOff = await confirmTerminal(['settings', 'person.signed', 'off'], 'signing');++ assert.equal(switchedOff.person.signed, false);++ assert.equal((await cli(box.env, 'status')).document.person.signed, false, 'the passkey turned signing off');++ assert.equal((await cli(marked, 'settings', 'person.signed', 'on')).code, 0);++ await box.stopRelay();++ await cli(cleared, 'relay', 'off');++ assert.equal(existsSync(box.linkFile), false, 'unlinking works offline with no tap');++ assert.equal((await box.cli('status')).document.person.signed, true, 'unlinking never turns signing off');++}diff --cc test/team.test.jsindex 7a3f9e87,f9da3b4a..50ba4c6a--- a/test/team.test.js+++ b/test/team.test.js@@@ -1,7 -1,8 +1,10 @@@-/** @pullboard-test-loads src/board.js src/engine.js src/exchange.js */++import { personSigningCase } from './person-signing-case.js';+/** @pullboard-test-loads src/board.js src/engine.js src/exchange.js src/person-signing.js relay/passkeys.js */import { submitFixture as submitBoardStateFixture } from './board-submit-fixture.js';/** Two independent Git/SQLite replicas derive verdict freshness without rewriting proof [E8]. */+import { memberHandoverCase } from './handover-membership-case.js';+ import { signedBoard, consent, linkRelay } from './board-link-fixture.js';+ import { submitFixture } from './board-submit-fixture.js';import assert from 'node:assert/strict';import childProcess from 'node:child_process';import { syncBuiltinESMExports } from 'node:module';@@@ -1094,315 -1030,120 +1097,158 @@@ test('a landing lease renewal or waiteassert.equal(state.line.length, 1, 'suppressing polling events does not discard the waiting command');});+/** Send one sealed person request with its passkey presence, returning the relay's answer. */+async function passkeyRequest(box, session, document, presence) {+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const head = await relayCall(box, session, 'GET', '/api/v2/boards/' + link.board + '/state');+ const events = await relayCall(box, session, 'GET', `/api/v1/boards/${link.board}/events?after=${head.document.state.sequence}`);+ const sequence = Math.max(head.document.state.sequence, ...(events.document.events ?? []).map((event) => event.event_id)) + 1;+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(document)), { boardId: link.board, kind: 'request', sequence })).toString('base64url');+ return relayCall(box, session, 'POST', `/api/v1/boards/${link.board}/requests`, { sequence, sealed, ...(presence ? { presence } : {}) });+}++/** True when no regular file under a directory holds a person session or a person grant. */+function holdsNoPersonCredential(directory) {+ return filesUnder(directory).every((file) => !/(?:ps_|pg_)[A-Za-z0-9_-]{43}/u.test(readFileSync(file).toString('latin1')));+}++test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(60) }, async (t) => { // budget: hang ceiling for real CLI runs and relay calls; not a speed target.- const box = await relayClientFixture(t);- // The shipped command, handed the loopback fixture relay as an explicit trusted parameter in this test's own call path:- // no environment variable or global can make the real CLI trust it (#408 rulings 38756cb3 and 28611).- const trusted = [TRUSTED_CLI, box.origin];- /** Run the command in the main checkout with a chosen environment, trusting only this fixture relay. */- const cli = (env, ...args) => relayFixtureChild(box.root, env, [...trusted, ...args, '--json']);- // S10a: an agent that cleared AI_AGENT and CLAUDECODE has exactly the person's shell markers.- const cleared = { ...box.env };- const marked = { ...box.env, AI_AGENT: '1', CLAUDECODE: '1' };-- // Off, the default: person moves work as today, and status says once that they are not signed.- const text = runFixtureChild(process.execPath, [CLI, 'status'], { cwd: box.root, env: box.env, encoding: 'utf8' });- assert.equal(text.status, 0);- assert.equal(text.stdout.split('\n').filter((line) => /person moves are not signed/u.test(line)).length, 1, 'status says it in one line');- assert.equal((await box.cli('status')).document.person.signed, false);- const early = (await box.cli('shout', 'person', 'A decision before signing', '--decision')).document.id;- assert.equal((await cli(box.env, 'answer', String(early), 'Off answers as today', '--as', 'person')).code, 0, 'off: the terminal answers as the person');-- // A board with no relay cannot turn signing on: only the relay can vouch for a passkey (#408 trust-anchor ruling).- const offline = await cli(marked, 'settings', 'person.signed', 'on');- assert.equal(offline.document.error?.code, 'PERSON_SIGNING_RELAY', `no relay, no signing: ${JSON.stringify(offline.document)}`);- // Linked, turning signing on is allowed from the terminal, even an agent's; unlinking then still works with no tap.- assert.equal((await box.link()).code, 0);- const on = await cli(marked, 'settings', 'person.signed', 'on');- assert.equal(on.code, 0, `an agent may turn signing on: ${JSON.stringify(on.document)}`);- assert.equal(on.document.person.signed, true);- const ask = (await box.cli('shout', 'person', 'A decision only the person answers', '--decision')).document.id;- // The same board on a device that is not paired: its link set aside, restored below without linking again, and no- // move succeeds meanwhile, so the relay and the board still agree when it returns.- renameSync(box.linkFile, `${box.linkFile}.unpaired`);-- // S10a and the on-and-unpaired case: every person move fails closed at once, naming how to pair a passkey.- const calls = box.calls.length;- for (const words of [['answer', String(ask), 'S10a cleared markers', '--as', 'person'], ['spec', 'approve', 'E1'], ['spec', 'approve', 'doctrine:D1'],- ['spec', 'decline', 'E1', '--reason', 'no'], ['land', '--waive', 'test/x.test.js', '--until', '2099-01-01', '--reason', 'flaky'], ['settings', 'person.signed', 'off']]) {- const refused = await cli(cleared, ...words);- assert.equal(refused.code, 1, words.join(' '));- assert.equal(refused.document.error.code, 'PERSON_SIGNED', `${words.join(' ')}: ${JSON.stringify(refused.document)}`);- assert.match(refused.document.error.next, /relay on --all/u, 'unpaired: the next step pairs a phone or browser');- assert.match(refused.document.error.next, /passkey/u);- }- assert.equal(box.calls.length, calls, 'refused locally, before any network call or wait');- assert.equal((await cli(marked, 'answer', String(ask), 'marked agent', '--as', 'person')).document.error.code, 'PERSON_SIGNED', 'an agent shell is refused too');- const remote = await cli({ ...cleared, SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22' }, 'answer', String(ask), 'from SSH', '--as', 'person');- assert.equal(remote.document.error.code, 'PERSON_SIGNED', 'over SSH the same passkey step applies');-- // No local file edit turns it off: not the project config, not machine settings.- const config = join(box.root, 'pullboard.json');- writeFileSync(config, JSON.stringify({ ...JSON.parse(readFileSync(config, 'utf8')), person: { signed: false } }, null, 2) + '\n');- mkdirSync(box.env.PULLBOARD_MACHINE_HOME, { recursive: true });- writeFileSync(join(box.env.PULLBOARD_MACHINE_HOME, 'settings.json'), JSON.stringify({ person: { signed: false } }) + '\n');- assert.equal((await cli(cleared, 'answer', String(ask), 'after edits', '--as', 'person')).document.error.code, 'PERSON_SIGNED', 'edits leave it on');- assert.equal((await box.cli('status')).document.person.signed, true);-- // S10b: whatever the OS user can read, an agent can read, so the local view's channel is refused too.- const viewed = await executeMove(box.root, { verb: 'answer', item: ask, args: { as: 'person', text: 'through the view secret' } }, main);- assert.equal(viewed.body.error?.code, 'PERSON_SIGNED', 'the view channel is not the person once signing is on');-- // Linked, a terminal person move goes to the passkey as an action-bound request and says where to confirm.- renameSync(`${box.linkFile}.unpaired`, box.linkFile);- assert.ok(holdsNoPersonCredential(box.root) && holdsNoPersonCredential(box.env.HOME), 'no file holds a person session or grant');- const terminal = helpers.launch({ ...box, env: { ...cleared, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },- box.root, process.execPath, [...trusted, 'answer', String(ask), 'Signed on the passkey', '--as', 'person', '--json']);- t.after(async () => { if (terminal.exitCode === null && terminal.signalCode === null) terminal.kill('SIGTERM'); await terminal.closed; });- /** Observe fixture SQLite directly; no second command may execute the waiting action. */- const nativeRows = (sql, ...args) => {- const db = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });- try { return db.prepare(sql).all(...args); } finally { db.close(); }- };- /** Read durable request receipts without running status, export or another command. */- const nativeRequests = () => Object.fromEntries(JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?',- 'relay_person_requests')[0]?.meta_value ?? '[]').filter(record => !record.duplicateOf).map(record => [record.id, record]));- await helpers.waitFor(() => {- assert.equal(terminal.exitCode, null, terminal.stderrText);- return terminal.stderrText.includes(box.origin) && terminal.stderrText.includes('this terminal is waiting');- }, 'the original SSH terminal asks for one passkey confirmation', relayWorkBudgetMs(5));- const proposals = JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0].meta_value);- const proposal = proposals.at(-1);- assert.deepEqual(proposal.move, { verb: 'answer', item: ask, args: { as: 'person', text: 'Signed on the passkey' } }, 'the exact move waits for the passkey');-- // The person registers a passkey with user presence; agents and machines cannot ask for a grant.- const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));- const phone = (await box.phoneSession()).token;- const passkey = softwarePasskey(box.origin);- const challenge = await relayCall(box, phone, 'POST', '/api/v1/passkeys/challenge', {});- assert.equal(challenge.status, 200, JSON.stringify(challenge.document));- const registered = await relayCall(box, phone, 'POST', '/api/v1/passkeys', { challenge: challenge.document.challenge, ...passkey.create(challenge.document.challenge) });- assert.equal(registered.status, 200, JSON.stringify(registered.document));- const document = { version: 1, type: 'person-request', id: proposal.id, move: proposal.move };- const machineGrant = await relayCall(box, link.token, 'POST', `/api/v1/boards/${link.board}/person-grants`, { request: proposal.id, digest: 'a'.repeat(64) });- assert.equal(machineGrant.document.error?.code, 'HUMAN_REQUIRED', 'the machine credential, which agents share, gets no grant');- /** Ask the relay for a fresh single-use grant for this request and the digest of its exact intent. */- const grantFor = async (document) => {- const digest = createHash('sha256').update(JSON.stringify(document)).digest('hex');- const issued = await relayCall(box, phone, 'POST', `/api/v1/boards/${link.board}/person-grants`, { request: document.id, digest });- assert.equal(issued.status, 200, JSON.stringify(issued.document));- assert.deepEqual(issued.document.credentials, [passkey.id]);- return issued.document.grant;- };-- // Without user presence, or with no assertion at all, nothing acts as the person.- const absent = await passkeyRequest(box, phone, document, { grant: await grantFor(document), ...passkey.get(grantChallenge('not-this-grant')) });- assert.equal(absent.document.error?.code, 'PASSKEY_ASSERTION', 'an assertion over another challenge is refused');- const grant = await grantFor(document);- const noPresence = await passkeyRequest(box, phone, document, { grant, ...passkey.get(grantChallenge(grant), { presence: false }) });- assert.equal(noPresence.document.error?.code, 'PASSKEY_PRESENCE', 'an authenticator answer with no user present is refused');- const elsewhere = await passkeyRequest(box, phone, document, { grant, ...passkey.get(grantChallenge(grant), { origin: 'http://elsewhere.localhost' }) });- assert.equal(elsewhere.document.error?.code, 'PASSKEY_ASSERTION', 'an answer made for another site is refused');- const forgedSignature = { grant, ...passkey.get(grantChallenge(grant)), signature: passkey.get(grantChallenge('other bytes')).signature };- assert.equal((await passkeyRequest(box, phone, document, forgedSignature)).document.error?.code, 'PASSKEY_ASSERTION', 'a signature over other bytes is refused');- const unsigned = { version: 1, type: 'person-request', id: randomUUID(), move: proposal.move };- assert.equal((await passkeyRequest(box, phone, unsigned)).status, 200, 'the relay stores a session request without a passkey');- await helpers.waitFor(() => nativeRequests()[unsigned.id]?.status === 'refused', 'the waiting terminal refuses unsigned intent', relayWorkBudgetMs(5));- let received = nativeRequests();- assert.equal(received[unsigned.id].status, 'refused');- assert.equal(received[unsigned.id].error.code, 'PERSON_SIGNED', 'without a passkey the native board refuses it');-- // One confirmation on the passkey carries out the exact move, once.- const presence = { grant, ...passkey.get(grantChallenge(grant)) };- const signed = await passkeyRequest(box, phone, document, presence);- assert.equal(signed.status, 200, JSON.stringify(signed.document));- const terminalResult = await terminal.closed;- assert.equal(terminalResult.code, 0, terminal.stderrText);- assert.equal(JSON.parse(terminal.stdoutText).request, proposal.id, 'the original terminal reports its exact request');- received = nativeRequests();- assert.equal(received[proposal.id].status, 'done', JSON.stringify(received[proposal.id]));- const answers = nativeRows('SELECT * FROM shout WHERE shout_answers=?', ask);- assert.deepEqual(answers.map((row) => [row.shout_from, row.shout_text]), [['person', 'Signed on the passkey']]);- const replay = await passkeyRequest(box, phone, { ...document, id: randomUUID() }, presence);- assert.equal(replay.document.error?.code, 'PHONE_APPROVAL_USED', 'the grant is single-use');- assert.ok(holdsNoPersonCredential(box.root) && holdsNoPersonCredential(box.env.HOME), 'the grant was never stored');-- // A hand edit to the board file cannot forge a passkey request, turn signing off or swap the relay key.- const raw = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'));- try {- /** One board metadata value, read straight from the file. */- const meta = (key) => raw.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key)?.meta_value;- assert.equal(meta('event_log_version'), '2', 'a Pullboard from before signed moves refuses this board');- assert.throws(() => raw.prepare("UPDATE board_meta SET meta_value='{}' WHERE meta_key='person_authority_local'").run(), /PERSON_AUTHORITY/u, 'the pinned relay key stays');- assert.throws(() => raw.prepare("INSERT OR REPLACE INTO board_meta(meta_key,meta_value) VALUES ('person_authority_local','{}')").run(), /PERSON_AUTHORITY/u);- assert.throws(() => raw.prepare("DELETE FROM event WHERE event_kind='person_signing'").run(), /APPEND_ONLY/u, 'the signing history stays');- const records = JSON.parse(meta('relay_person_requests'));- const genuine = records.find((record) => record.id === proposal.id);- const sender = JSON.parse(genuine.received).sender;- // A genuine stamp copied into a hand-written off names the digest of another request.- raw.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?,?,?,?,?)').run(new Date().toISOString(), 'person', 'person_signing', null,- JSON.stringify({ signed: false, request: proposal.id, presence: sender.presence, intent: { version: 1, type: 'person-request', id: proposal.id, move: { verb: 'signing', args: { signed: 'off' } } } }));- // The same stamp on a rewritten request: the same id, another answer, waiting to run again.- const forged = structuredClone(document);- forged.move.args.text = 'A forged second answer';- const { result, resultSequence, executor, executorUntil, ...rest } = genuine;- const rewritten = { ...rest, move: forged.move, encoded: JSON.stringify(forged), received: JSON.stringify({ document: forged, sender }), status: 'waiting' };- raw.prepare('UPDATE board_meta SET meta_value=? WHERE meta_key=?').run(JSON.stringify(records.map((record) => record.id === genuine.id ? rewritten : record)), 'relay_person_requests');- } finally { raw.close(); }- assert.equal((await box.cli('status')).document.person.signed, true, 'the hand-written off turns nothing off');- const waitingAgain = helpers.launch({ ...box, env: cleared }, box.root, process.execPath,- [...trusted, 'answer', String(ask), 'still signed', '--as', 'person', '--json']);- try {- await helpers.waitFor(() => { assert.equal(waitingAgain.exitCode, null, waitingAgain.stderrText); return waitingAgain.stderrText.includes('this terminal is waiting'); },- 'a cleared-marker terminal still waits for a new confirmation', relayWorkBudgetMs(5));- assert.equal(nativeRows('SELECT * FROM shout WHERE shout_answers=?', ask).length, 1, 'waiting creates no second person answer');- } finally { if (waitingAgain.exitCode === null && waitingAgain.signalCode === null) waitingAgain.kill('SIGTERM'); await waitingAgain.closed; }- assert.equal((await box.cli('export')).document.tables.shout.filter((row) => row.shout_answers === ask).length, 1, 'the rewritten request never runs as the person');-- // A signed row decision binds the exact rows the person saw; a row naming SSH signers is refused by name.- const shown = { id: 'G1', text: 'A row the person decides on the passkey.' };- writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8').replace('## G · Goals: what the client asked for\n',- `## G · Goals: what the client asked for\n\n- G1 [draft, must] ${shown.text} | gate: review\n`));- // The template's own placeholder G1 may sit beside it; the person sees the row this test wrote.- shown.source = readFileSync(join(box.root, 'SPEC.md'), 'utf8').split(/\r?\n/u).find(line => line.startsWith('- G1 ') && line.includes(shown.text));- const blind = { version: 1, type: 'person-request', id: randomUUID(), move: { verb: 'spec-approve', args: { ids: 'G1' } } };- const seen = { ...blind, id: randomUUID(), rows: [shown] };- for (const request of [blind, seen]) {- const rowGrant = await grantFor(request);- assert.equal((await passkeyRequest(box, phone, request, { grant: rowGrant, ...passkey.get(grantChallenge(rowGrant)) })).status, 200);- }- received = await receivedRequests(box, (...args) => cli(box.env, ...args));- assert.equal(received[blind.id].error?.code, 'STALE_ROW_DECISION', 'a decision that does not name the rows shown is refused');- assert.notEqual(received[seen.id].status, 'refused', JSON.stringify(received[seen.id]));- const decided = (await box.cli('export')).document.tables.event.filter((row) => row.event_kind === 'row_decision');- assert.deepEqual(decided.map((row) => [row.event_by, JSON.parse(row.event_detail).record.id]), [['person', 'G1']], 'the passkey decided exactly the row it showed');- // The real CLI applies that decision, checked against the authority its relay vouches for, never a stored key (#408).- const applied = await cli(box.env, 'spec', 'apply');- assert.equal(applied.code, 0, JSON.stringify(applied.document));- assert.match(readFileSync(join(box.root, 'SPEC.md'), 'utf8'), /- G1 \[approved, must\] A row the person decides on the passkey\./u, 'the native CLI applies the passkey approval');- assert.throws(() => refuseNamedSigners([{ id: 'G2', signers: ['[email protected]'] }], ['G2']), { code: 'PERSON_SIGNER_REQUIRED', message: /G2 names its SSH signers alice@example\.com/u });-- /** One live SSH command, one confirmation, no status/export/other CLI before its original exit. */- async function confirmTerminal(argv, expectedVerb) {- const beforeIds = new Set(JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0]?.meta_value ?? '[]').map(entry => entry.id));- const child = helpers.launch({ ...box, env: { ...cleared, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },- box.root, process.execPath, [...trusted, ...argv, '--json']);- try {- const proposal = await helpers.waitFor(() => {- assert.equal(child.exitCode, null, child.stderrText);- if (!child.stderrText.includes('this terminal is waiting')) return null;- return JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0]?.meta_value ?? '[]').find(entry => !beforeIds.has(entry.id));- }, 'the exact new terminal proposal', relayWorkBudgetMs(5));- assert.equal(proposal.move.verb, expectedVerb);- const request = { version: 1, type: 'person-request', id: proposal.id, move: proposal.move,- ...(proposal.rows ? { rows: proposal.rows } : {}) };- const actionGrant = await grantFor(request);- assert.equal((await passkeyRequest(box, phone, request, { grant: actionGrant, ...passkey.get(grantChallenge(actionGrant)) })).status, 200);- const outcome = await child.closed;- assert.equal(outcome.code, 0, child.stderrText);- const result = JSON.parse(child.stdoutText);- assert.equal(result.request, proposal.id);- assert.ok(['done', 'waiting'].includes(nativeRequests()[proposal.id].status));- return result;- } finally {- if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');- await child.closed;- }- }- // Each newly mapped action must complete on its original terminal, with exact target/meaning.- const factItem = (await box.cli('add', box.lane, 'SIGNED_FACT_TARGET')).document.item.item_id;- const fact = await confirmTerminal(['fact', String(factItem), 'decision', 'Keep this exact rule', '--as', 'person', '--cause', 'row:G1', '--never-again'], 'fact');- assert.equal(fact.item, factItem);- assert.equal(fact.fact.text, 'Keep this exact rule');- const held = await confirmTerminal(['hold', box.lane, '--as', 'person', '--reason', 'Wait for the exact reviewed rule'], 'hold');- assert.equal(held.held, true);- assert.equal(nativeRows('SELECT hold_reason,hold_by FROM hold WHERE hold_lane=?', box.lane)[0].hold_by, 'person');- const unheld = await confirmTerminal(['hold', box.lane, '--as', 'person', '--off'], 'hold');- assert.equal(unheld.held, false);- assert.equal(nativeRows('SELECT * FROM hold WHERE hold_lane=?', box.lane).length, 0);- for (const name of ['signed-watch-approved', 'signed-watch-declined']) {- assert.equal((await box.cli('sentinel', 'propose', name, '--check', 'true', '--every', 'hourly', '--owner', 'coordinator')).code, 0);- }- const watch = await confirmTerminal(['sentinel', 'approve', 'signed-watch-approved'], 'sentinel-approve');- assert.equal(watch.sentinel.status, 'approved');- const declinedWatch = await confirmTerminal(['sentinel', 'decline', 'signed-watch-declined', '--reason', 'Do not run this exact watch'], 'sentinel-decline');- assert.equal(declinedWatch.sentinel.status, 'declined');- const question = 'Which store holds the data: SQLite. Choices: SQLite, Postgres.';- writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8')- + `\n- G2 [pending, must] ${question} | gate: review\n- G3 [draft, must] A terminal-approved row. | gate: review\n- G4 [draft, must] A terminal-declined row. | gate: review\n`);- const answeredRow = await confirmTerminal(['spec', 'answer', 'G2', 'Postgres'], 'spec-answer');- assert.equal(answeredRow.decisions[0].id, 'G2');- assert.match(answeredRow.decisions[0].text, /data: Postgres/u);- const approvedRow = await confirmTerminal(['spec', 'approve', 'G3'], 'spec-approve');- assert.equal(approvedRow.decisions[0].decision, 'approve');- const declinedRow = await confirmTerminal(['spec', 'decline', 'G4', '--reason', 'Do not approve this row'], 'spec-decline');- assert.equal(declinedRow.decisions[0].decision, 'decline');- writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8')- + '\n- G5 [approved, must] An optional sign-off row. | gate: review\n- G6 [approved, must] A named-signature row. | gate: review | signers: [email protected]\n');- mkdirSync(join(box.root, 'test'), { recursive: true });- writeFileSync(join(box.root, 'test', 'signed-evidence.test.js'), '/** [G5] Cited evidence fixture; no test run is implied by optional sign-off. */\n');- runFixtureGit(['add', 'test/signed-evidence.test.js'], { cwd: box.root, env: box.env });- const sshFile = join(box.root, '.pullboard', 'signoffs.jsonl');- const beforeSsh = existsSync(sshFile) ? readFileSync(sshFile, 'utf8') : null;- const optionalSignoff = await confirmTerminal(['spec', 'signoff', 'G5'], 'spec-approve');- assert.equal(optionalSignoff.count, 1);- assert.equal(optionalSignoff.by, 'person');- assert.equal(existsSync(sshFile) ? readFileSync(sshFile, 'utf8') : null, beforeSsh, 'passkey approval never writes an SSH signature');- const namedSignoff = await cli(cleared, 'spec', 'signoff', 'G6');- assert.equal(namedSignoff.document.error?.code, 'PERSON_SIGNER_REQUIRED');- assert.match(namedSignoff.document.error.message, /G6 names its SSH signers alice@example\.com/u);- const signerChange = await cli(cleared, 'spec', 'signers', 'add', '--by', '[email protected]', '--key', 'unread-key');- assert.equal(signerChange.document.error?.code, 'PERSON_SIGNER_REQUIRED');- assert.match(signerChange.document.error.message, /alice@example\.com/u);-- const waiver = await confirmTerminal(['land', '--waive', 'gate:lint', '--until', '2099-01-01', '--reason', 'An explicit bounded fixture exception'], 'land-waive');- assert.equal(waiver.waiver.test, 'gate:lint');-- // Only the passkey turns signing off; unlinking offline keeps it on.- const switchedOff = await confirmTerminal(['settings', 'person.signed', 'off'], 'signing');- assert.equal(switchedOff.person.signed, false);- assert.equal((await cli(box.env, 'status')).document.person.signed, false, 'the passkey turned signing off');- assert.equal((await cli(marked, 'settings', 'person.signed', 'on')).code, 0);- await box.stopRelay();- await cli(cleared, 'relay', 'off');- assert.equal(existsSync(box.linkFile), false, 'unlinking works offline with no tap');- assert.equal((await box.cli('status')).document.person.signed, true, 'unlinking never turns signing off');++ await personSigningCase(t, { CLI, TRUSTED_CLI, helpers, passkeyRequest, holdsNoPersonCredential, relayCall });+});++/** Keep the initial-unpaired local-edit clause distinct from the post-pin trigger controls. */+test('person-only moves are signed before the first authority pin [E22,B26,H16]', firstUnpairedAuthorityInsertion);++test('person-only moves are signed only from the built-in relay over TLS [E22,B26,H16]', { timeout: relayWorkBudgetMs(8) }, firstPinNeedsBuiltInRelay); // budget: hang ceiling for one link and two refused CLI runs; not a speed target.++/** Optional SSH policy must accept a genuinely bound passkey row decision without using an SSH key. */+test('person-only moves are signed through optional SSH apply [E22,H16]', optionalPasskeyApply);++/** The actual CLI applies and projects the recorded passkey approval even with optional SSH enabled. */+test('person-only moves are signed: an unlinked CLI applies no passkey decision it cannot verify [E22,H16]', optionalPasskeyApplyThroughCli);++/** Initial trust and committed execution provenance are separate signing boundaries. */+test('person-only moves are signed against fabricated receipt metadata [E22,H16]', rejectFabricatedPasskeyMetadata);++/** A local event insertion is not an authenticated execution of a different row source. */+test('person-only moves are signed against synthetic execution events [E22,H16]', rejectSyntheticPasskeyEvent);++test('person-only moves are signed against consumed OFF replay [E22,H16]', rejectConsumedOffReplay);+ /** Cross-repository prerequisites use real signed E32 disclosure and never a same-number local item [B24,H16]. */+ test('an item waits across repos [B24,H16]', async t => {+ /** A private board clock makes exact canonical replay comparisons deterministic. */+ const clock = { now: () => new Date('2026-10-25T00:00:00Z') };+ const parent = signedBoard(t, 'app', clock);+ const child = signedBoard(t, 'service', clock);+ const local = parent.board, foreign = child.board;+ writeFileSync(join(parent.root, 'pullboard.json'), JSON.stringify({ name: 'app', project: 'fixture', gate: 'true', lanes: { web: { owns: ['web/'] } } }));+ writeFileSync(join(parent.root, 'SPEC.md'), '# Synthetic fixture\n\n- B24 [approved, must] Cross-repo fixture. | gate: test/team.test.js\n');+ parent.git('add', 'pullboard.json', 'SPEC.md');+ parent.git('commit', '-q', '-m', 'fixture: configure the private dependency API');+ for (const box of [parent, child]) {+ store.register(box.board, { lane: 'coordinator', path: box.root });+ store.register(box.board, { lane: 'web', path: join(box.root, 'synthetic-builder') });+ }+ const localId = store.addItem(local, { by: 'coordinator', lane: 'web', title: 'Local same-number item' });+ const foreignId = store.addItem(foreign, { by: 'coordinator', lane: 'web', title: 'Foreign prerequisite' });+ assert.equal(localId, foreignId, 'independent real Git/SQLite boards intentionally reuse the same item number');+ const dependent = store.addItem(local, { by: 'coordinator', lane: 'web', title: 'Wait for service', after: [`service#${foreignId}`] });+ assert.equal(store.getItem(local, dependent).item_after, `service#${foreignId}`);+ /** Explicit synthetic frozen bar; native moves below do not claim that this fixture ran a gate. */+ const freeze = item => ({ text: item.item_title, digest: `fixture:${item.item_title}` });+ /** Record an actual native verified transition, with a clearly synthetic build receipt. */+ function accept(board, id, root, title) {+ const box = root === parent.root ? parent : child;+ const commit = box.git('rev-parse', 'HEAD').trim();+ const tree = box.git('rev-parse', 'HEAD^{tree}').trim();+ store.claim(board, id, { agentId: 'web-1', lane: 'web', leaseMs: 60_000, head: commit, freeze });+ submitFixture(board, id, { agentId: 'web-1', commit, tree });+ const reviewer = store.register(board, { lane: 'web', path: join(root, 'synthetic-reviewer') });+ store.verify(board, id, { agentId: reviewer, decision: 'ACCEPT', reason: 'CRITERION_MET',+ note: 'synthetic board-state fixture; no gate execution', head: commit, digest: `fixture:${title}`, policy: 'any' });+ }+ accept(local, localId, parent.root, 'Local same-number item');+ store.merged(local, localId, { agentId: 'coordinator', commit: parent.git('rev-parse', 'HEAD').trim() });+ /** Assert the native claim guard and pull queue name the owning repository. */+ function blocked(id, label) {+ assert.throws(() => store.claim(local, id, { agentId: 'web-1', lane: 'web', leaseMs: 60_000, freeze }),+ error => error.code === 'BLOCKED' && error.message.includes(label));+ assert.ok(store.nextFor(local, { agentId: 'web-1', lane: 'web' }).reasons.some(reason => reason.includes(label)));+ }+ blocked(dependent, 'service#1');+ const missing = store.addItem(local, { by: 'coordinator', lane: 'web', title: 'Missing board', after: ['missing#999'] });+ blocked(missing, 'missing#999');+ const api = await import('../src/board-link.js');+ const transportApi = await import('../src/board-link-relay.js');+ const { createSshBoardLinkAuthority } = await import('../src/board-link-ssh.js');+ const { createBoardLinkCapability } = await import('../src/board-link-envelope.js');+ const { generateBoardKey } = await import('../src/seal.js');+ const authority = createSshBoardLinkAuthority([parent, child]);+ const record = await consent(api, authority, parent, child, 'dependency');+ await api.applyBoardLink(local, record, authority);+ await api.applyBoardLink(foreign, record, authority);+ const relay = await linkRelay(t, [parent, child], authority);+ const sender = transportApi.createBoardLinkRelayTransport(relay.states.get(child.reference.boardId));+ const receiver = transportApi.createBoardLinkRelayTransport(relay.states.get(parent.reference.boardId));+ await sender.publish(record);+ const capability = createBoardLinkCapability(record, await generateBoardKey());+ /** Send only actual child item states through the established authenticated E32 transport. */+ async function announce(position) {+ const context = { linkId: record.linkId, generation: record.generation, sourceBoardId: child.reference.boardId,+ destinationBoardId: parent.reference.boardId, position, correlationId: `state-${position}`,+ rows: [{ board: child.reference.boardId, id: foreignId, state: store.getItem(foreign, foreignId).item_status }] };+ await transportApi.deliverBoardState(foreign, context, { authority, capability, transport: sender });+ const deliveries = (await receiver.read()).deliveries;+ await transportApi.receiveBoardState(local, deliveries.at(-1), { authority, capability });+ }+ await announce(1);+ blocked(dependent, 'service#1');+ const builds = [];+ const localApi = await serveApi({ port: 0, runCommand: main, stateDetail: 'full',+ projects: () => [{ root: parent.root, name: 'app', project: 'fixture', added: '2026-10-25T00:00:00Z' }],+ onItemBuild: entry => builds.push(entry.itemId) });+ t.after(() => localApi.close());+ const address = new URL(localApi.url);+ /** Observe the real cached API projection without substituting an item builder. */+ async function readState() {+ const response = await fetchFresh(`${address.origin}/api/v1/boards/${parent.reference.boardId}/state?detail=full`,+ { headers: { 'x-pullboard-key': address.searchParams.get('k') } });+ const document = await response.json();+ assert.equal(response.status, 200, JSON.stringify(document));+ return document.state;+ }+ await readState();+ builds.length = 0;+ await readState();+ assert.deepEqual(builds, [], 'unchanged API reads actually reuse the warm item cache');+ accept(foreign, foreignId, child.root, 'Foreign prerequisite');+ blocked(dependent, 'service#1');+ await announce(2);+ await readState();+ assert.ok(builds.includes(dependent), 'an authenticated global state announcement rebuilds its cached foreign dependents');+ const replica = store.openBoard(':memory:', clock);+ t.after(() => store.closeBoard(replica));+ importBoard(replica, exportBoard(local));+ const options = { agentId: 'web-1', lane: 'web', leaseMs: 60_000, freeze };+ assert.equal(store.nextFor(local, { agentId: 'web-1', lane: 'web' }).item.item_id, dependent);+ assert.equal(store.nextFor(replica, { agentId: 'web-1', lane: 'web' }).item.item_id, dependent);+ const move = prepareEngineMove(local, 'claim', [dependent, options]);+ const { CROSS_REPO_DEPENDENCY_ENGINE } = await import('../src/cross-repo-dependency-engine.js');+ assert.ok(move.engine >= CROSS_REPO_DEPENDENCY_ENGINE, 'older replicas cannot flatten a foreign-dependent claim');+ const ordered = { sequence: 1, at: clock.now().toISOString() };+ assert.deepEqual(applyEngineMove(local, move, ordered), applyEngineMove(replica, move, ordered), 'one ordered claim returns the same receipt on both replicas');+ assert.equal(store.getItem(local, dependent).item_status, 'claimed');+ assert.equal(store.getItem(replica, dependent).item_status, 'claimed', 'replica uses canonical received state, not a local registry or foreign-board path');+ assert.deepEqual(exportBoard(replica), exportBoard(local), 'same canonical state and claim produce exact replica rows and event IDs');+ await readState();+ builds.length = 0;+ const revoked = await api.revokeBoardLink(record, parent.reference.boardId, authority, { by: parent.by, key: parent.key });+ await api.applyBoardLink(local, revoked, authority);+ await readState();+ assert.ok(builds.includes(dependent), 'a canonical link revocation invalidates cached foreign dependency status');+ });+/** Initialise a second repo in the first one's sandbox, so both register in the same machine home. */function siblingRepo(box, name, project) {const repo = join(box.dir, name);