Skip to content

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

chore(core): merge agent identity guards with current trunk [H2,V1]

Corey Olsonfe2eebf2ce35
diff --cc docs/api.md
index 303421bd,f52033d9..7a61c081
--- a/docs/api.md
+++ b/docs/api.md
@@@ -276,17 -277,9 +277,17 @@@ Only the coordinator sets or edits an i
Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.
- `POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can list only its board’s token ids and metadata, and through `POST /auth/tokens {board,agent}` it first-mints a `pa_` token only for a seat the relay never issued a token to, including after that token expired or was revoked (`TOKEN_EXISTS` otherwise). Such a seat (a manual `pullboard join`, or any name minted ahead) is machine-origin for good: it builds, never verifies on a linked board, and its name cannot later be registered (`SEAT_TAKEN`). The native client also checks that the seat is registered, which the relay cannot see. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints.
-`POST /auth/machines {board,machine,host?}` requires a foreground person session and returns a `pm_` credential bound to that board and machine; `relay join` sends its host name as `host`. `GET /api/v1/devices/<deviceId>` with a board's `pm_` credential returns `{version, seen, revoked}` for a phone of the same account, with null fields for an unknown id. `GET /api/v1/devices` with that credential returns `{version, devices: [{deviceId, seen, revoked}]}` for the phones holding that board's key, by id only; names stay on the computer that paired them. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.
++`POST /auth/machines {board,machine,host?}` requires a foreground person session and returns a `pm_` credential bound to that board and machine; `relay join` sends its host name as `host`. `GET /api/v1/devices/<deviceId>` with a board's `pm_` credential returns `{version, seen, revoked}` for a phone of the same account, with null fields for an unknown id. `GET /api/v1/devices` with that credential returns `{version, devices: [{deviceId, seen, revoked}]}` for the phones holding that board's key, by id only; names stay on the computer that paired them. This delegate can list only its board’s token ids and metadata, and through `POST /auth/tokens {board,agent}` it first-mints a `pa_` token only for a seat the relay never issued a token to, including after that token expired or was revoked (`TOKEN_EXISTS` otherwise). Such a seat (a manual `pullboard join`, or any name minted ahead) is machine-origin for good: it builds, never verifies on a linked board, and its name cannot later be registered (`SEAT_TAKEN`). The native client also checks that the seat is registered, which the relay cannot see. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints.
+
- A `pa_` token renews only its own seat: `POST /auth/tokens {board,agent}` naming itself returns a new token and revokes the one that asked (`TOKEN_AGENT` for any other seat). A seat's first token from another seat comes only with the move that registers it: `POST /api/v1/boards/:board/moves {sequence, sealed, registration}`, sent with the creating seat's token, where `registration` is `{target, creator, sequence, digest}` (the creator is the sender, the sequence is this upload's, and the digest is the SHA-256 of the `sealed` text). The relay appends the move and issues the target's first token in one board lock and returns it only in that reply as `enrollment`; the public event carries the receipt and never the token. An exact retry returns the same issuance id and expiry without a token. The receipt commits in the same journal transaction as the move and is kept through compaction, and it claims the target from that moment: the machine credential and a person are refused a first mint for any name a receipt claims, under the same board lock that appends receipts, so no failure between the append and the enrollment leaves a window. If enrollment fails after the append, the creator's exact retry, or its `recover:true` reissue, rolls the first mint forward from the journalled receipt. A lost token is reissued by its creator, `POST /auth/tokens {board,agent,recover:true}` with the creator's token, which revokes the old ones. `/auth/tokens` refuses a `registration` field (`REGISTRATION_IN_MOVE`), so a copied receipt never mints. Replicas apply an engine-27 registration by another seat only with the receipt that names its target, creator, position and digest, so the board's record of who created a seat matches the relay's.
++A `pa_` token renews only its own seat: `POST /auth/tokens {board,agent}` naming itself returns a new token and revokes the one that asked (`TOKEN_AGENT` for any other seat). A seat's first token from another seat comes only with the move that registers it: `POST /api/v1/boards/:board/moves {sequence, sealed, registration}`, sent with the creating seat's token, where `registration` is `{target, creator, sequence, digest}` (the creator is the sender, the sequence is this upload's, and the digest is the SHA-256 of the `sealed` text). The relay appends the move and issues the target's first token in one board lock and returns it only in that reply as `enrollment`; the public event carries the receipt and never the token. An exact retry returns the same issuance id and expiry without a token. The receipt commits in the same journal transaction as the move and is kept through compaction, and it claims the target from that moment: the machine credential and a person are refused a first mint for any name a receipt claims, under the same board lock that appends receipts, so no failure between the append and the enrollment leaves a window. If enrollment fails after the append, the creator's exact retry, or its `recover:true` reissue, rolls the first mint forward from the journalled receipt. A lost token is reissued by its creator, `POST /auth/tokens {board,agent,recover:true}` with the creator's token, which revokes the old ones. `/auth/tokens` refuses a `registration` field (`REGISTRATION_IN_MOVE`), so a copied receipt never mints. Replicas apply an engine-35 registration by another seat only with the receipt that names its target, creator, position and digest, so the board's record of who created a seat matches the relay's.
+
+`POST /auth/coordinators {board}` takes a person session only and issues the coordinator's token: the first one (`bootstrap`), a fresh one after loss, expiry or revocation (`reissue`), or the person's reset of a coordinator first minted by the machine (`reset`). It revokes every older coordinator token. `pullboard relay on` calls it inside its own sign-in, so a board needs no extra tap. `GET /auth/tokens` also returns `coordinatorEvents`, each with its reason, the person session id, the revoked token ids, the issued id and the time; `pullboard relay tokens` prints them.
+
- On a linked board, an engine-27 verdict, review reservation or review offer needs verifier standing: the verifier was enrolled through the relay by its creator, each creator up the line was too, the line ends at the coordinator, and neither the builder nor a machine join is on it. The coordinator stands on the token the person set up. A seat without standing is refused with `VERIFIER_STANDING` in one line that names the fix, `pullboard worktree <lane> --model "<model name>"` run by the coordinator from the main checkout. Seats from before engine 27, or from before the board was linked, keep building; reviews need a fresh seat made that way. Each person-made coordinator token carries a machine lineage (a reissue that replaces a token keeps it; another machine's token starts its own), and a seat enrolled from it, or from a seat in its line, records that lineage. A coordinator claim records the lineage of the machine that builds it. When the coordinator built an item, a seat from another machine's registration lineage, or the person, verifies it; a seat from the building machine's own lineage is refused and told so. On an unlinked board who may verify is unchanged. The relay stamps each record it stores with `policy` (and `root` for the person-made coordinator token); a stamped record below engine 27 is refused, older unstamped records replay as they did, and a board with machine or agent credentials requires engine 27.
++On a linked board, an engine-35 verdict, review reservation or review offer needs verifier standing: the verifier was enrolled through the relay by its creator, each creator up the line was too, the line ends at the coordinator, and neither the builder nor a machine join is on it. The coordinator stands on the token the person set up. A seat without standing is refused with `VERIFIER_STANDING` in one line that names the fix, `pullboard worktree <lane> --model "<model name>"` run by the coordinator from the main checkout. Seats from before engine 35, or from before the board was linked, keep building; reviews need a fresh seat made that way. Each person-made coordinator token carries a machine lineage (a reissue that replaces a token keeps it; another machine's token starts its own), and a seat enrolled from it, or from a seat in its line, records that lineage. A coordinator claim records the lineage of the machine that builds it. When the coordinator built an item, a seat from another machine's registration lineage, or the person, verifies it; a seat from the building machine's own lineage is refused and told so. On an unlinked board who may verify is unchanged. The relay stamps each record it stores with `policy` (and `root` for the person-made coordinator token); a stamped record below engine 35 is refused, older unstamped records replay as they did, and a board with machine or agent credentials requires engine 35.
+
+Residual: tokens on disk, in the repository's shared `relay.json`, are readable by every process of the same operating-system user, so a process that reads another seat's current `pa_` can act as that seat and renew it; signed moves (#408) close that. An agent holding the machine credential can still make a seat of its own, by a manual join or by minting a never-issued name, which also makes a creator skip that name. That seat cannot verify that agent's work, nor any work on a linked board, and cannot act as any existing seat. A sealed snapshot uploaded with the machine credential remains a trusted checkpoint for replicas that restore from it.
- `GET /auth/machines?board=<id>` returns `{version, machines: [{machine}]}` for the live computer credentials on that board, with duplicate computer ids listed once. It requires that board's machine credential or a person session with current repository write access; agent tokens and credentials from another board are refused. `relay off` excludes its own computer from the list and warns which joined computers lose the shared copy if the phone approves deletion. JSON also returns those ids in `affectedMachines`. Local unlink still succeeds when the relay cannot supply the list.
+ `GET /auth/machines?board=<id>` returns `{version, machines: [{machine, host, created, seen}]}` for the live computer credentials on that board, with duplicate computer ids listed once. `host` is the host name the computer sent when it joined, or null; `created` is its first join and `seen` its last relay contact, which moves at most once a minute. It requires that board's machine credential or a person session with current repository write access; agent tokens and credentials from another board are refused. `relay off` excludes its own computer from the list and warns which joined computers lose the shared copy if the phone approves deletion. The warning names each computer by its host name, or by the end of its id when the relay has no host for it. JSON also returns those ids in `affectedMachines` and the names in `joined`. Local unlink still succeeds when the relay cannot supply the list.
After phone-approved deletion, a previously live scoped credential receives HTTP 410 / `RELAY_BOARD_DELETED` for that deleted copy. The relay retains only its hash, board id and original expiry as a deletion receipt, prunes expired receipts, and grants no access through them. Unknown, already revoked and already expired credentials receive `AUTH_REQUIRED` as before. Only a versioned deletion response naming this link's own board turns a joined computer back into a local board. The CLI removes the inert link and its device key, excludes the project from automatic relinking, and retains a private credential-free notice that the relay copy was deleted; native board contents remain local. A successful explicit `relay on` starts a new link and clears that notice. A network outage or ordinary credential refusal does not authorize this transition. Before forgetting a deleted copy, the CLI commits any pending native move and its durable receipt locally. The notice keeps only the receipt id and intent digests, so interrupted cleanup or an explicit repeat can return the original outcome without applying that move twice; different local work can continue beside it.
diff --cc relay/auth.js
index 1fc5577b,906ca482..4290a08b
--- a/relay/auth.js
+++ b/relay/auth.js
@@@ -583,127 -552,19 +596,129 @@@ export function createRelayAuth({ datab
const principal = await auth.authenticate(token, { board, write: true });
if (!['session', 'machine'].includes(principal.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential or the signed-in phone to list joined computers');
credential(token);
- return db.prepare("SELECT DISTINCT agent AS machine FROM relay_credentials WHERE board=? AND kind='machine' AND revoked=0 AND expires>? ORDER BY agent").all(board, now());
+ // Each computer is listed once, by the host name it sent when it joined, with its first join and last contact.
+ return db.prepare("SELECT agent AS machine, MAX(host) AS host, MIN(created) AS created, MAX(seen) AS seen FROM relay_credentials WHERE board=? AND kind='machine' AND revoked=0 AND expires>? GROUP BY agent ORDER BY agent")
+ .all(board, now()).map(row => ({ machine: row.machine, host: row.host ?? null, created: row.created ?? null, seen: row.seen ?? null }));
},
- /** Mint an agent credential scoped to a single readable board and immutable human identity. */
- async issueToken(token, { board, agent, expiresIn = tokenTTL }) {
+ /**
+ * Mint an agent credential scoped to one board (#579). The machine credential, or a person,
+ * first-mints only a seat the relay never issued a token to, and that seat is machine-origin
+ * for good. A seat's own current token renews it, revoking itself. Its creator may reissue a
+ * lost token for a seat it registered, revoking the old ones. A seat's first token from a
+ * creator comes only with its registration move (`enrollSeat`), never from this route.
+ */
+ async issueToken(token, { board, agent, expiresIn = tokenTTL, recover = false, registration }) {
identifier(board, 'BAD_BOARD');
identifier(agent, 'BAD_AGENT');
- if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn > MAX_TTL) throw new Refused('BAD_EXPIRY', 'choose a token expiry between one millisecond and thirty days');
+ expiry(expiresIn, 'token');
+ if (registration !== undefined) throw new Refused('REGISTRATION_IN_MOVE', 'a seat receipt counts only inside its registration move; post the move with its receipt from the creating seat');
+ if (typeof recover !== 'boolean') throw new Refused('BAD_REQUEST', 'send recover as true or false');
const principal = await auth.authenticate(token, { board, write: true });
- if (!['session', 'machine'].includes(principal.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential to issue an agent token');
- credential(token);
- return { ...issue(principal.user, 'board', board, agent, expiresIn), board, agent };
+ return lifecycle(() => {
+ const current = credential(token);
+ const existing = seat(board, agent);
+ if (principal.kind === 'board') {
+ if (!recover && principal.agent === agent) {
+ const renewed = issue(principal.user, 'board', board, agent, expiresIn, Boolean(current.root), current.lineage ?? null);
+ db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(current.id);
+ return { ...renewed, board, agent };
+ }
+ const claim = !existing && recover ? registrationClaim(board, agent) : null;
+ if (recover && claim?.creator === principal.agent && agent !== principal.agent) {
+ // A receipt published without its enrollment: the creator rolls the first mint forward.
+ return firstMint({ id: current.user_id }, board, agent, tokenTTL,
+ { origin: 'registered', creator: claim.creator, sequence: claim.sequence, digest: claim.digest });
+ }
+ if (recover && existing?.origin === 'registered' && existing.creator === principal.agent && agent !== principal.agent) {
+ db.prepare("UPDATE relay_credentials SET revoked=1 WHERE board=? AND kind='board' AND agent=?").run(board, agent);
+ return { ...issue(principal.user, 'board', board, agent, expiresIn), board, agent };
+ }
+ throw new Refused('TOKEN_AGENT', recover
+ ? 'only the seat that registered this one reissues its token; ask its creator'
+ : 'an agent token renews only its own seat; a new seat gets its first token from its creator\'s registration');
+ }
+ if (recover) throw new Refused('TOKEN_AGENT', 'only the seat that registered this one reissues its token; ask its creator');
+ if (existing) {
+ throw new Refused('TOKEN_EXISTS', agent === 'coordinator'
+ ? 'the coordinator already has a token; it renews with its own, or the person reissues it with pullboard relay on'
+ : 'this seat already had a token; it renews only with its own current token, or its creator reissues it');
+ }
+ // A published receipt claims its target even before enrollment finishes: no machine race.
+ if (registrationClaim(board, agent)) {
+ throw new Refused('TOKEN_EXISTS', 'a creator registered this seat; its first token comes only through that registration or its creator');
+ }
+ return firstMint(principal.user, board, agent, expiresIn, { origin: 'machine' });
+ });
+ },
+ /** Wire the relay journal's receipt lookup; token issuance then honors every published claim. */
+ setRegistrationClaims(reader) {
+ if (typeof reader !== 'function') throw new Refused('RELAY_CONFIG', 'configure a seat receipt reader');
+ registrationClaim = reader;
+ },
+ /**
+ * Give a registration move's target its first token, inside the board lock that appended the
+ * move (#579). The creator is the authenticated agent token that sent the move; the target
+ * must be new to the relay. An exact retry returns the same issuance without a token.
+ */
+ enrollSeat(token, board, receipt) {
+ identifier(board, 'BAD_BOARD');
+ return lifecycle(() => {
+ const current = credential(token);
+ if (current.kind !== 'board' || current.agent !== receipt.creator || current.board !== board) {
+ throw new Refused('REGISTRATION_SENDER', 'register a seat with the creating seat\'s own token');
+ }
+ const existing = seat(board, receipt.target);
+ if (existing) {
+ if (existing.origin === 'registered' && existing.creator === receipt.creator && existing.sequence === receipt.sequence && existing.digest === receipt.digest) {
+ return { id: existing.first_id, created: existing.first_created, expires: existing.first_expires, board, agent: receipt.target, retried: true };
+ }
+ throw new Refused('SEAT_TAKEN', `the relay already issued ${receipt.target} a token, so it cannot be registered again; register the next free name`);
+ }
+ return firstMint({ id: current.user_id }, board, receipt.target, tokenTTL,
+ { origin: 'registered', creator: receipt.creator, sequence: receipt.sequence, digest: receipt.digest });
+ });
+ },
+ /** Read one seat's first-mint record for the registration check before a move is appended. */
+ seatRecord(board, agent) {
+ open();
+ identifier(board, 'BAD_BOARD');
+ identifier(agent, 'BAD_AGENT');
+ const row = seat(board, agent);
+ return row && { origin: row.origin, creator: row.creator, sequence: row.sequence, digest: row.digest };
+ },
+ /**
+ * Set up the coordinator's token from a person session only (#579): the first one on a board
+ * (bootstrap), a fresh one after loss, expiry or revocation, or for another of the person's
+ * machines (reissue), or the person's reset of a coordinator first minted by the machine
+ * (reset), which revokes every older coordinator token. A reissue revokes the token it names
+ * as replaced. Each issue leaves an audit row naming the session, the revoked ids and the new id.
+ */
+ async issueCoordinator(token, { board, expiresIn = tokenTTL, replaces }) {
+ identifier(board, 'BAD_BOARD');
+ expiry(expiresIn, 'coordinator');
+ const principal = await auth.authenticate(token, { board, write: true });
+ if (principal.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'only the person sets up the coordinator credential: run pullboard relay on in the main checkout');
+ return lifecycle(() => {
+ const current = credential(token);
+ const existing = seat(board, 'coordinator');
+ const reason = !existing ? 'bootstrap' : existing.origin === 'root' ? 'reissue' : existing.origin === 'machine' ? 'reset' : null;
+ if (!reason) throw new Refused('COORDINATOR_SEAT', 'the coordinator seat on this board was registered by another seat; unlink and link the board again');
+ if (replaces !== undefined && typeof replaces !== 'string') throw new Refused('BAD_REQUEST', 'name the coordinator token id this one replaces');
+ // A reset revokes every machine-minted coordinator token; a reissue revokes the one it
+ // replaces, so each of the person's linked machines keeps its own coordinator token.
+ const revoked = db.prepare("SELECT id FROM relay_credentials WHERE board=? AND kind='board' AND agent='coordinator' AND revoked=0 AND expires>?").all(board, now())
+ .map((row) => row.id).filter((id) => reason === 'reset' || id === replaces);
+ // A replacement keeps its machine's lineage; a token for another machine starts a new one.
+ const replaced = replaces === undefined ? null : db.prepare("SELECT lineage FROM relay_credentials WHERE id=? AND board=? AND kind='board' AND agent='coordinator' AND root=1").get(replaces, board);
+ const lineage = reason !== 'reset' && replaced?.lineage ? replaced.lineage : randomUUID();
+ for (const id of revoked) db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(id);
+ const issued = reason === 'reissue'
+ ? { ...issue(principal.user, 'board', board, 'coordinator', expiresIn, true, lineage), board, agent: 'coordinator' }
+ : firstMint(principal.user, board, 'coordinator', expiresIn, { origin: 'root', root: true, lineage });
+ db.prepare('INSERT INTO relay_coordinator_events (id,board,reason,session_id,revoked,issued_id,at) VALUES (?,?,?,?,?,?,?)')
+ .run(randomUUID(), board, reason, current.id, JSON.stringify(revoked), issued.id, issued.created);
+ return { ...issued, root: true, reason };
+ });
},
/** List only owned board-token metadata after a fresh repository write check, never bearer values or hashes. */
async listTokens(token, board) {
diff --cc src/board.js
index d519d291,61fb27ff..cdcab88f
--- a/src/board.js
+++ b/src/board.js
@@@ -13,16 -24,42 +24,52 @@@ import
import { dirname } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { boardNotWritable } from './board-access.js';
- import { briefFiles, briefSections } from './brief.js';
+ import {
+ briefFiles,
+ briefSections,
+ } from './brief.js';
import { COORDINATOR } from './config.js';
- import { ENGINE_VERSION, VERDICT_REVIEW_ENGINE, MILESTONE_RANK_ENGINE, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, VERIFIER_STANDING_ENGINE, effectiveGuards, storeTriggers } from './machine.js';
+ import {
+ ENGINE_VERSION,
+ VERDICT_REVIEW_ENGINE,
+ MILESTONE_RANK_ENGINE,
+ GUARDS,
+ IN_STATE,
+ MOVES,
+ STATES,
+ UNKNOWN_MOVE,
++ VERIFIER_STANDING_ENGINE,
+ effectiveGuards,
+ storeTriggers,
+ } from './machine.js';
import { Refused } from './refused.js';
- import { agentAt, agentModel, newSeatId, routeOf, saveAgentModel, seatLineage, standingProblem } from './seats.js';
- import { causeProblem, requireNeverAgain } from './rigor.js';
++import {
++ agentAt,
++ agentModel,
++ newSeatId,
++ routeOf,
++ saveAgentModel,
++ seatLineage,
++ standingProblem,
++} from './seats.js';
+ import {
+ causeProblem,
+ requireNeverAgain,
+ } from './rigor.js';
import { barCorrectionFields } from './bar-corrections.js';
import { factReference } from './fact-reference.js';
- import { factFromEvent, requestAnswerRefusal, tellAnswerImplications, tellFactImplications, tellVerdictImplications } from './implies.js';
- import { landingFlakes, landingWaiverCovers, landingWaiverKind } from './landing-exceptions.js';
+ import {
+ factFromEvent,
+ requestAnswerRefusal,
+ tellAnswerImplications,
+ tellFactImplications,
+ tellVerdictImplications,
+ } from './implies.js';
+ import {
+ landingFlakes,
+ landingWaiverCovers,
+ landingWaiverKind,
+ } from './landing-exceptions.js';
import { parseSpec } from './spec.js';
export { landingFlakes, landingWaiverCovers, landingWaiverKind };
export { acceptCheck } from './check-accept.js';
diff --cc src/engine.js
index 2b48ba49,e12ad878..7500545e
--- a/src/engine.js
+++ b/src/engine.js
@@@ -1,15 -1,35 +1,37 @@@
/** Versioned, deterministic replay through the CLI's existing board engine [H3,H16]. */
- import { createHash, randomUUID } from 'node:crypto';
+ import {
+ createHash,
+ randomUUID,
+ } from 'node:crypto';
import * as store from './board.js';
+import { COORDINATOR } from './config.js';
import { recordedRefusal } from './recorded-refusal.js';
- import { BAR_ENGINE, carriesBarReason } from './bar-corrections.js';
- import { carriesImplies, IMPLIES_ENGINE } from './implies.js';
+ import {
+ BAR_ENGINE,
+ carriesBarReason,
+ } from './bar-corrections.js';
+ import {
+ carriesImplies,
+ IMPLIES_ENGINE,
+ } from './implies.js';
import { CHECK_ACCEPT_ENGINE } from './check-accept.js';
- import { CAUSE_ENGINE, ENGINE_VERSION, VERIFIER_STANDING_ENGINE, VERDICT_REVIEW_ENGINE, MILESTONE_RANK_ENGINE } from './machine.js';
+ import {
+ CAUSE_ENGINE,
+ ENGINE_VERSION,
++ VERIFIER_STANDING_ENGINE,
+ VERDICT_REVIEW_ENGINE,
+ MILESTONE_RANK_ENGINE,
+ } from './machine.js';
import { Refused } from './refused.js';
- import { requestMoveProblem, recordRequestMove } from './relay-requests.js';
- import { relayMoveActor, relaySenderProblem, validRelaySender } from './relay-sender.js';
+ import {
+ requestMoveProblem,
+ recordRequestMove,
+ } from './relay-requests.js';
+ import {
+ relayMoveActor,
+ relaySenderProblem,
+ validRelaySender,
+ } from './relay-sender.js';
const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);
diff --cc src/relay-pairing-client.js
index 5fa32f6c,7563f4ff..e6b15598
--- a/src/relay-pairing-client.js
+++ b/src/relay-pairing-client.js
@@@ -1,15 -1,46 +1,47 @@@
/** CLI pairing flow: the relay stores only a one-use client-encrypted package [H15,H17]. */
import { randomUUID } from 'node:crypto';
- import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
- import { dirname, join } from 'node:path';
+ import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+ } from 'node:fs';
+ import { hostname } from 'node:os';
+ import {
+ dirname,
+ join,
+ } from 'node:path';
import * as store from './board.js';
- import { exportBoard, importBoard } from './exchange.js';
- import { codeIsFromMain, repoInfo } from './git.js';
- import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
+ import {
+ exportBoard,
+ importBoard,
+ } from './exchange.js';
+ import {
+ codeIsFromMain,
+ repoInfo,
+ } from './git.js';
+ import {
+ forgetBoardKey,
+ readBoardKey,
+ storeBoardKey,
+ } from './relay-key.js';
import { encodeBoardKey } from './seal.js';
- import { createPairingCode, openPairingBundle, parsePairingCode, sealPairingBundle } from './pairing.js';
+ import {
+ createPairingCode,
+ openPairingBundle,
+ parsePairingCode,
+ sealPairingBundle,
+ } from './pairing.js';
import { terminalQr } from './qr.js';
- import { DEFAULT_RELAY, originRepository, relayPersonCoordinator, syncRelay } from './relay.js';
+ import {
+ DEFAULT_RELAY,
+ originRepository,
++ relayPersonCoordinator,
+ syncRelay,
+ } from './relay.js';
import { ENGINE_VERSION } from './machine.js';
import { Refused } from './refused.js';
import { requirePersonChannel } from './person.js';
@@@ -244,11 -277,11 +278,13 @@@ export async function relayJoin(root, c
}
throw error;
}
+ // This machine's coordinator token comes from the same person sign-in, never the machine credential.
+ await relayPersonCoordinator(root, signed.token, io);
await syncRelay(root, io);
- const result = { linked: true, board: bundle.board, url: bundle.url, sequence: bundle.sequence, behind: 0 };
+ const name = listApiProjects().find(project => project.root === repoInfo(root).root)?.name ?? bundle.repository;
+ const notice = `Joined ${name}. This brought one board; for another, run pullboard relay pair in that board on the linked computer. Run pullboard status to read it.`;
+ const result = { linked: true, board: bundle.board, name, url: bundle.url, sequence: bundle.sequence, behind: 0, notice };
io.result?.(result);
- io.say(`paired board ${bundle.board}; run pullboard status to read it`);
+ io.say(notice);
return 0;
}
diff --cc src/relay-seats.js
index 248ecb4f,00000000..afa73c44
mode 100644,000000..100644
--- a/src/relay-seats.js
+++ b/src/relay-seats.js
@@@ -1,148 -1,0 +1,155 @@@
+/**
+ * Each seat's own relay credential (#579, H2, V1): the seat name a creator registers, the receipt
+ * that binds its first token to that registration, and which token a move is sent with. A live
+ * token renews itself; a lost one is reissued by its creator; the machine credential only
+ * first-mints a seat the relay never issued, build-only.
+ *
+ * Why the import back into relay.js: these use its link file and HTTP request, and relay.js calls
+ * them only at run time, never while the modules load, so the cycle is safe.
+ */
+import { createHash } from 'node:crypto';
+import * as store from './board.js';
- import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';
++import {
++ ENGINE_VERSION,
++ VERIFIER_STANDING_ENGINE,
++} from './machine.js';
+import { Refused } from './refused.js';
- import { localRecords, request, saveLink } from './relay.js';
++import {
++ localRecords,
++ request,
++ saveLink,
++} from './relay.js';
+
+/**
+ * Name the seat a creator registers (#579): the receipt names its target before the move is
+ * sealed, so the id travels in the move. A join no seat made, a returning worktree and the
+ * coordinator lane keep the board's own numbering.
+ */
+export function withSeatName(root, operation, args) {
+ // A registration that names no creator is a join no seat made.
+ if (operation === 'register' && args?.[0] && args[0].createdBy === undefined) args = [{ ...args[0], createdBy: 'machine' }, ...args.slice(1)];
+ const options = args?.[0];
+ if (operation !== 'register' || ENGINE_VERSION < VERIFIER_STANDING_ENGINE || !options || typeof options.createdBy !== 'string' ||
+ options.createdBy === 'machine' || options.lane === 'coordinator' || options.id !== undefined) return args;
+ const id = localRecords(root, (board) => store.agentAt(board, options.path) ? null : store.nextSeatId(board, options.lane));
+ return id ? [{ ...options, id }, ...args.slice(1)] : args;
+}
+
+/** Move a pending registration to the first name from `from` that this replica has not registered. */
+export function nameNextSeat(root, move, from) {
+ const options = move.args[0];
+ localRecords(root, (board) => {
+ let n = Math.max(from, Number(store.nextSeatId(board, options.lane).slice(options.lane.length + 1)));
+ while (store.listAgents(board).some((agent) => agent.agent_id === `${options.lane}-${n}`)) n += 1;
+ options.id = `${options.lane}-${n}`;
+ });
+}
+
+/** The public receipt a creator sends with a registration: target, creator, position and sealed digest. */
+export function seatReceipt(move, sequence, sealed) {
+ const options = move?.operation === 'register' && move.engine >= VERIFIER_STANDING_ENGINE ? move.args?.[0] : null;
+ if (!options || typeof options.id !== 'string' || typeof options.createdBy !== 'string' || options.createdBy === 'machine') return undefined;
+ return { target: options.id, creator: options.createdBy, sequence, digest: createHash('sha256').update(sealed).digest('hex') };
+}
+
+/** Cache one seat's own scoped token; nothing else is ever written into agentTokens. */
+export function cacheSeatToken(file, state, actor, issued) {
+ if (!/^pa_[A-Za-z0-9_-]{43}$/.test(issued?.token ?? '') || issued.board !== state.board || issued.agent !== actor ||
+ typeof issued.id !== 'string' || !Number.isSafeInteger(issued.expires)) {
+ throw new Refused('RELAY_RESPONSE', 'the relay did not issue this agent’s scoped credential; retry the command');
+ }
+ state.agentTokens ??= {};
+ state.agentTokens[actor] = { id: issued.id, token: issued.token, expires: issued.expires,
+ ...(Number.isSafeInteger(issued.created) ? { created: issued.created } : {}) };
+ saveLink(file, state);
+ return issued.token;
+}
+
+/** When a cached token renews itself: halfway through its life, or a minute before expiry when its start is unknown. */
+function renewalDue(cached) {
+ return Number.isSafeInteger(cached.created) && cached.expires > cached.created
+ ? cached.expires - (cached.expires - cached.created) / 2 : cached.expires - 60_000;
+}
+
+/**
+ * The current token of one registered seat (#579). A live token renews itself with itself; a lost
+ * or expired one is reissued by the seat that enrolled it, walking up to the coordinator, whose
+ * own token only the person reissues. A seat that never held a token gets its first, build-only
+ * one from the machine credential. Nothing here ever remints a seat through the machine.
+ */
+async function seatToken(root, file, state, actor, io, depth = 0) {
+ if (depth > 64) throw new Refused('RELAY_ACTOR', 'this seat\'s line of creators loops; ask the coordinator to make a fresh seat');
+ const cached = state.agentTokens?.[actor];
+ if (cached?.revoked) throw new Refused('TOKEN_REVOKED', `the relay token of ${actor} was revoked on this board; work from a seat with its own token, or ask the coordinator for a fresh worktree`);
+ if (cached?.token && cached.expires > Date.now()) {
+ if (Date.now() < renewalDue(cached)) return cached.token;
+ const renewed = await request({ ...state, token: cached.token, agent: actor }, '/auth/tokens', { method: 'POST', body: { board: state.board, agent: actor } }, io);
+ return cacheSeatToken(file, state, actor, renewed);
+ }
+ const seat = localRecords(root, (board) => {
+ const agent = store.listAgents(board).find((row) => row.agent_id === actor);
+ return agent ? { creator: store.agentCreator(board, actor), enrolled: store.seatEnrolled(board, actor) } : null;
+ });
+ if (!seat) throw new Refused('RELAY_ACTOR', 'register this agent in the ordered board before obtaining its scoped token');
+ if (seat.enrolled && actor !== 'coordinator') {
+ const creatorToken = await seatToken(root, file, state, seat.creator, io, depth + 1);
+ const reissued = await request({ ...state, token: creatorToken, agent: seat.creator }, '/auth/tokens',
+ { method: 'POST', body: { board: state.board, agent: actor, recover: true } }, io);
+ return cacheSeatToken(file, state, actor, reissued);
+ }
+ if (cached) {
+ throw new Refused('TOKEN_EXPIRED', actor === 'coordinator'
+ ? 'the coordinator relay token expired; the person reissues it: run pullboard relay on in the main checkout'
+ : `the relay token of ${actor} expired, and only a seat's own current token or its creator renews it; ask the coordinator for a fresh worktree: pullboard worktree <lane> --model "<model name>"`);
+ }
+ if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');
+ // The machine credential first-mints only a seat the relay never issued a token to; it stays build-only.
+ const issued = await request(state, '/auth/tokens', { method: 'POST', body: { board: state.board, agent: actor } }, io);
+ return cacheSeatToken(file, state, actor, issued);
+}
+
+/** Select a scoped credential: the machine's, a supplied agent token, or the seat's own token. */
+export async function actorTransport(root, file, state, actor, io) {
+ if (typeof actor !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(actor)) {
+ throw new Refused('RELAY_ACTOR', 'name the registered agent performing this move before sending it');
+ }
+ if (actor === 'person') {
+ throw new Refused('HUMAN_REQUIRED', 'send this person action from the paired phone');
+ }
+ if (actor === 'machine') {
+ if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');
+ return state;
+ }
+ const supplied = io?.ignoreRelayEnvironmentToken ? undefined : process.env.PULLBOARD_RELAY_TOKEN;
+ if (supplied !== undefined) {
+ if (!/^pa_[A-Za-z0-9_-]{43}$/.test(supplied)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token, without including it in command arguments');
+ const transport = { ...state, token: supplied, agent: actor };
+ const identity = await request(transport, '/auth/session?board=' + state.board, {}, io);
+ if (identity.session?.kind !== 'board' || identity.session.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');
+ return transport;
+ }
+ if (state.token?.startsWith('pa_')) {
+ const identity = await request(state, '/auth/session?board=' + state.board, {}, io);
+ if (identity.session?.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');
+ return { ...state, agent: actor };
+ }
+ return { ...state, token: await seatToken(root, file, state, actor, io), agent: actor };
+}
+
+/**
+ * Give the coordinator a token the person set up, once per board, inside relay on's own sign-in
+ * (#579): the first one, a reissue after loss or expiry, or the reset of a machine-minted one.
+ * A live person-made coordinator token is kept as it is.
+ */
+export async function ensurePersonCoordinator(file, state, session, io) {
+ const cached = state.agentTokens?.coordinator;
+ if (cached?.token && !cached.revoked && Date.now() < renewalDue(cached)) {
+ try {
+ const identity = await request({ ...state, token: cached.token }, '/auth/session?board=' + state.board, {}, io);
+ if (identity.session?.kind === 'board' && identity.session.agent === 'coordinator' && identity.session.root === true) return;
+ } catch (error) { if (error.code !== 'AUTH_REQUIRED') throw error; }
+ }
+ const issued = await request({ ...state, token: session }, '/auth/coordinators', { method: 'POST',
+ body: { board: state.board, ...(typeof cached?.id === 'string' ? { replaces: cached.id } : {}) } }, io);
+ cacheSeatToken(file, state, 'coordinator', { ...issued, agent: 'coordinator' });
+}
diff --cc src/relay.js
index 9637dfdb,e7936f72..4a619dfd
--- a/src/relay.js
+++ b/src/relay.js
@@@ -1,19 -1,69 +1,80 @@@
/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */
- import { createHash, randomUUID } from 'node:crypto';
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+ import {
+ createHash,
+ randomUUID,
+ } from 'node:crypto';
+ import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+ } from 'node:fs';
import { hostname } from 'node:os';
- import { basename, dirname, join } from 'node:path';
- import { gunzipSync, gzipSync } from 'node:zlib';
+ import {
+ basename,
+ dirname,
+ join,
+ } from 'node:path';
+ import {
+ gunzipSync,
+ gzipSync,
+ } from 'node:zlib';
import * as store from './board.js';
- import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';
- import { appliedSequence, applyEngineMove, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';
+ import {
+ exportBoard,
+ importBoard,
+ restoreRelaySnapshot,
+ semanticBoardDigest,
+ } from './exchange.js';
+ import {
+ appliedSequence,
+ applyEngineMove,
+ applyRelayMove,
+ checkpointSequence,
+ engineReceipt,
+ prepareEngineMove,
+ refuseRelayMove,
+ requireSupportedEngine,
+ startRelayEpoch,
+ } from './engine.js';
import { relayMoveActor } from './relay-sender.js';
- import { actorTransport, cacheSeatToken, ensurePersonCoordinator, nameNextSeat, seatReceipt, withSeatName } from './relay-seats.js';
- import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';
- import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';
- import { codeIsFromMain, repoInfo, tryGit } from './git.js';
- import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
- import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';
-import { ENGINE_VERSION } from './machine.js';
++import {
++ actorTransport,
++ cacheSeatToken,
++ ensurePersonCoordinator,
++ nameNextSeat,
++ seatReceipt,
++ withSeatName,
++} from './relay-seats.js';
++import {
++ ENGINE_VERSION,
++ VERIFIER_STANDING_ENGINE,
++} from './machine.js';
+ import {
+ presentationDigest,
+ relayPresentation,
+ relaySnapshot,
+ } from './relay-presentation.js';
+ import {
+ codeIsFromMain,
+ repoInfo,
+ tryGit,
+ } from './git.js';
+ import {
+ forgetBoardKey,
+ readBoardKey,
+ storeBoardKey,
+ } from './relay-key.js';
+ import {
+ encodeBoardKey,
+ generateBoardKey,
+ seal,
+ unseal,
+ } from './seal.js';
import { terminalQr } from './qr.js';
import { Refused } from './refused.js';
import { refusalFromReceipt } from './recorded-refusal.js';
diff --cc src/seats.js
index 68a98e19,00000000..52d46627
mode 100644,000000..100644
--- a/src/seats.js
+++ b/src/seats.js
@@@ -1,216 -1,0 +1,219 @@@
+/**
+ * Seats (B3, H2, V1): who each registered agent is on the board, read from the agent table and the
+ * metadata kept beside it: its model, its route, and from engine 35 the seat that created it, whether
+ * the relay enrolled it, and its machine lineage. Verifier standing on a linked board (#579) is
+ * decided here from that line of creators. board.js registers seats and re-exports the readers.
+ */
+import { COORDINATOR } from './config.js';
- import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';
++import {
++ ENGINE_VERSION,
++ VERIFIER_STANDING_ENGINE,
++} from './machine.js';
+import { Refused } from './refused.js';
+
+/**
+ * The agent registered for a worktree path, if any.
+ *
+ * @param {any} board
+ * @param {string} path
+ * @returns {any}
+ */
+export function agentAt(board, path) {
+ const agent = board.db.prepare('SELECT * FROM agent WHERE agent_path = ?').get(path);
+ return withModel(board, agent);
+}
+
+/** Read the model label kept beside other board metadata, avoiding any board-schema migration. */
+export function agentModel(board, id) {
+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_model:${id}`)?.meta_value ?? null;
+}
+
+/** Attach an agent's model to a row from the legacy stable agent table. */
+export function withModel(board, agent) {
+ return agent ? { ...agent, agent_model: agentModel(board, agent.agent_id) } : agent;
+}
+
+/** Save or clear a model label without changing the shared SQLite schema. */
+export function saveAgentModel(board, id, model) {
+ if (model === null || model === undefined) {
+ board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(`agent_model:${id}`);
+ return;
+ }
+ board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?) ON CONFLICT(meta_key) DO UPDATE SET meta_value = excluded.meta_value')
+ .run(`agent_model:${id}`, model);
+}
+
+/**
+ * Every registered agent, oldest first.
+ *
+ * @param {any} board
+ * @returns {any[]}
+ */
+export function listAgents(board) {
+ return board.db.prepare('SELECT * FROM agent ORDER BY rowid').all().map((agent) => withModel(board, agent));
+}
+
+/**
+ * The route an agent joined on; strong for the coordinator and for ids the board does not know.
+ *
+ * @param {any} board
+ * @param {string} agentId
+ * @returns {string}
+ */
+export function routeOf(board, agentId) {
+ return board.db.prepare('SELECT agent_route FROM agent WHERE agent_id = ?').get(agentId)?.agent_route ?? 'strong';
+}
+
+/**
+ * The id an engine-35 registration gives a new seat: the named one when it is the lane's form and
+ * free, otherwise the lane's first free number from its count. Skipping taken numbers keeps a named
+ * seat from colliding with the next unnamed one.
+ *
+ * @param {any} board
+ * @param {string} lane
+ * @param {number} total
+ * @param {string | undefined} named
+ * @returns {string}
+ */
+export function newSeatId(board, lane, total, named) {
+ if (named === undefined) return firstFreeSeatId(board, lane, total);
+ const number = typeof named === 'string' && named.startsWith(`${lane}-`) ? named.slice(lane.length + 1) : '';
+ if (!/^[1-9][0-9]{0,8}$/.test(number) || Number(number) <= total || board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(named)) {
+ throw new Refused('BAD_SEAT_ID', `a new ${lane} seat is named ${lane}-<n> above the lane's count and not yet taken; register again without a name`);
+ }
+ return named;
+}
+
+/**
+ * The lane's first seat number above its count that no seat holds yet.
+ *
+ * @param {any} board
+ * @param {string} lane
+ * @param {number} total
+ * @returns {string}
+ */
+function firstFreeSeatId(board, lane, total) {
+ let n = total + 1;
+ while (board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(`${lane}-${n}`)) n += 1;
+ return `${lane}-${n}`;
+}
+
+/**
+ * The seat that created this one, as its engine-35 registration recorded it: an agent id,
+ * `machine` for a join no seat made, or null for a seat registered before engine 35.
+ *
+ * @param {any} board
+ * @param {string} id
+ * @returns {string | null}
+ */
+export function agentCreator(board, id) {
+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_creator:${id}`)?.meta_value ?? null;
+}
+
+/**
+ * Whether a relay replica enrolled this seat from its creator's receipt-bound registration (#579).
+ *
+ * @param {any} board
+ * @param {string} id
+ * @returns {boolean}
+ */
+export function seatEnrolled(board, id) {
+ return Boolean(board.db.prepare('SELECT 1 FROM board_meta WHERE meta_key = ?').get(`agent_enrolled:${id}`));
+}
+
+/**
+ * The machine registration lineage a relay-enrolled seat descends from: the person-set coordinator
+ * token of the machine that made its line (#579), or null when it was never recorded.
+ *
+ * @param {any} board
+ * @param {string} id
+ * @returns {string | null}
+ */
+export function seatLineage(board, id) {
+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_lineage:${id}`)?.meta_value ?? null;
+}
+
+/**
+ * The id the next registration in a lane gets when it names none, for a creator that must
+ * predict it before sealing the move (the relay receipt names the target seat).
+ *
+ * @param {any} board
+ * @param {string} lane
+ * @returns {string}
+ */
+export function nextSeatId(board, lane) {
+ const { total } = board.db.prepare('SELECT COUNT(*) AS total FROM agent WHERE agent_lane = ?').get(lane);
+ return firstFreeSeatId(board, lane, total);
+}
+
+/**
+ * Run board work under linked-board verifier standing (#579): a relay replica replaying an
+ * engine-35 move, or a linked CLI previewing one. `root` says whether the acting coordinator's
+ * relay credential was set up by the person. Unlinked boards never enter this, so who may verify
+ * there is unchanged.
+ *
+ * @template T
+ * @param {any} board
+ * @param {{ root: boolean, person?: boolean, lineage?: string | null }} standing
+ * @param {() => T} work
+ * @returns {T}
+ */
+export function withVerifierStanding(board, standing, work) {
+ const previous = board.verifierStanding;
+ board.verifierStanding = { root: standing.root === true, person: standing.person === true,
+ lineage: typeof standing.lineage === 'string' ? standing.lineage : null };
+ try { return work(); }
+ finally {
+ if (previous === undefined) delete board.verifierStanding;
+ else board.verifierStanding = previous;
+ }
+}
+
+/**
+ * Why this seat may not verify the builder's item on a linked board, or null when it may. The
+ * seat's creators are walked up to the coordinator: the builder, a join no seat made (`machine`),
+ * or a seat registered before engine 35 anywhere on the way means no standing. The coordinator
+ * stands only on a credential the person set up.
+ *
+ * @param {any} board
+ * @param {string} verifier
+ * @param {string} builder
+ * @param {number} itemId
+ * @returns {Refused | null}
+ */
+export function standingProblem(board, verifier, builder, itemId) {
+ const standing = board.verifierStanding;
+ if (!standing || (board.executionEngineVersion ?? ENGINE_VERSION) < VERIFIER_STANDING_ENGINE) return null;
+ const refuse = (why) => new Refused('VERIFIER_STANDING',
+ `${verifier} cannot verify work built by ${builder} on this linked board: ${why}; ask the coordinator to make an independent verifier from the main checkout: pullboard worktree <lane> --model "<model name>"`);
+ if (builder === COORDINATOR) {
+ // The person stands above every seat; otherwise only a seat from another machine's line may.
+ if (standing.person) return null;
+ const refuseOwn = (why) => new Refused('VERIFIER_STANDING', `${verifier} cannot verify work the coordinator built on this linked board: ${why}; a seat from another machine's registration lineage, or the person, verifies it`);
+ const built = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_lineage:${itemId}`)?.meta_value ?? null;
+ const lineage = seatLineage(board, verifier);
+ if (!built || !lineage) return refuseOwn('the machine lineage of the build or of this seat was not recorded');
+ if (built === lineage) return refuseOwn('this seat shares the building machine\'s registration lineage');
+ for (let seat = verifier, seen = new Set(); seat !== COORDINATOR; seat = agentCreator(board, seat)) {
+ if (seen.has(seat) || !seatEnrolled(board, seat)) return refuseOwn(`${seat} was not enrolled through the relay`);
+ seen.add(seat);
+ }
+ return null;
+ }
+ const seen = new Set();
+ for (let seat = verifier; ;) {
+ if (seat === COORDINATOR) {
+ return standing.root || seat !== verifier ? null
+ : refuse('the coordinator credential was not set up by the person; run pullboard relay on in the main checkout once');
+ }
+ if (seen.has(seat)) return refuse('its line of creating seats loops');
+ seen.add(seat);
+ const creator = agentCreator(board, seat);
+ if (creator === 'machine') return refuse(`${seat} joined without a creating seat`);
+ if (creator === builder) return refuse(`${seat} was created by the builder`);
+ if (creator === null || !seatEnrolled(board, seat)) {
+ return refuse(`${seat} was not enrolled by its creating seat through the relay`);
+ }
+ seat = creator;
+ }
+}