Skip to content

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

fix(relay): agents cannot mint relay tokens from a worktree [H2,V1]

Corey Olson68aa0aa61f11
diff --git a/docs/api.md b/docs/api.md
index 49c927ae..2b35d3e4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -184,7 +184,15 @@ Only the coordinator sets or edits an item's `--check`. `pullboard check [id]` p
Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.
-`POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.
+`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.
+
+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. 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-13 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-13 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 13, or from before the board was linked, keep building; reviews need a fresh seat made that way. When the coordinator built an item, every seat it made shares its lineage, so the refusal says a seat from another machine's registration lineage, or the person, verifies it. 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 13 is refused, older unstamped records replay as they did, and a board with machine or agent credentials requires engine 13.
+
+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.
A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. A refused foreground approval fails immediately with the original refusal code and reason plus its request id. A refused remote approval makes local unlinking or registration exit nonzero while retaining the completed local work: one line names that completion, the refusal code and reason, the request id and the next action. The JSON result preserves the local outcome and includes `remote: {code, reason, requestId}`. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.
diff --git a/docs/formats.md b/docs/formats.md
index c3797a6c..c4b33347 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -102,7 +102,7 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo
| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. |
| `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. |
| `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |
-| `move engine` | `12` | `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` | `13` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |
<!-- format-versions:end -->
Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Pullboard 0.8.3 released engine 6, adding board-scoped machine credentials and permitting machine execution only for one exact, earlier authenticated phone request, including its payload digest. Engine 7 adds ordered item holds through `holdItem` and `releaseItemHold`; engine-6 clients stop with `ENGINE_VERSION` before interpreting either operation or advancing their replay cursor. Engine 8, shared by the 0.8.5 move changes, retains merged-item exception notes, selects the next review in roadmap order, and adds coordinator-only `reopen` for a submission returned without a verdict; engine-7 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Recorded engines 1 through 7 retain their original tier-first review selection. Engine 8 also adds durable refusal recovery for blocked relay positions; each explicit skip publishes the readable prefix even when another unsupported record follows. Engine 8 also permits coordinator criterion/check edits on a live claim as pending corrections; the holder cannot renew or submit until a refreeze adopts the correction while preserving the claim. Older request receipts retain their recorded engine semantics. Upgrade every linked device before using the new moves. Each release shares one engine bump across its changed moves. Engine 8 also retains declared model labels on registration and records each registered agent move's model snapshot; engines 1 through 7 retain their original registration and event details without these model fields. Pullboard 0.8.8 released engine 9, which allows resubmitting the same rejected commit after a corrected criterion is refrozen, but only when the rejection names a different frozen digest. Engine 8 retains its HEAD_NOT_NEW refusal and prior submit-event detail. Engine-9 submit events add `criterionDigest`, and engine-8 boards replay with the original refusal and event history.
@@ -113,9 +113,11 @@ Engine 11 permits resubmitting the same commit after a coordinator no-verdict re
Engine 12 records declined person row decisions without replacing the exact source text: the row becomes `wont` and the reason stays in the decision record. Engine-11 decline receipts retain their original reason-as-row-text validation and replay outcome. Engine-11 clients refuse engine-12 moves before interpreting them; upgrade linked clients before recording new decline decisions.
+Engine 13 records on each new seat the seat that created it (`createdBy`: an agent id, or `machine` for a join no seat made), lets a creator name the new seat (`id`), and applies verifier standing to relay-replayed verdicts, review reservations and offers on a linked board: the verifier's line of creating seats must reach the coordinator through seats enrolled by the relay, without the builder or a machine join. Replicas apply a register move by another seat only with the relay's receipt for its target, creator, position and digest. The relay stamps every record it stores with `policy: 13`; a stamped move below engine 13 is refused. Engine-12 and older moves, and unstamped records, replay as they did. On an unlinked board who may verify is unchanged.
+
The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.
-A linked board requires at least engine 3 after issuing any agent token, including
-revoked or expired tokens. Issuing any machine credential raises that board’s minimum to engine 6, including after revocation or expiry. The minimum survives reopening the auth database;
+A linked board requires at least engine 13 after issuing any agent token or machine credential, including
+revoked or expired ones; before engine 13 these minimums were 3 and 6. The minimum survives reopening the auth database;
unlink removes the board and ends its lifetime. A missing declaration is legacy
engine 1. Board-content requests below their minimum, and malformed declarations,
receive `ENGINE_VERSION` with upgrade guidance before records are returned or
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index b2af58f0..7bfe0cfc 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -55,9 +55,9 @@ Each move checks its guards in this order and refuses with the first one that do
| release | claimed | open | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) |
| lapse | claimed | open | clock, when its lease runs out | none |
| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), gateConfigured (NO_GATE), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |
-| reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), roadmapReadable (MILESTONES_CORRUPT), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD) |
-| accept | submitted | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), itemCheckGreen (CHECK_RED or CHECK_UNVERIFIED), proofNoted (PROOF_REQUIRED) |
-| reject | submitted | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED) |
+| reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), roadmapReadable (MILESTONES_CORRUPT), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY or VERIFIER_STANDING), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD) |
+| accept | submitted | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY or VERIFIER_STANDING), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), itemCheckGreen (CHECK_RED or CHECK_UNVERIFIED), proofNoted (PROOF_REQUIRED) |
+| reject | submitted | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY or VERIFIER_STANDING), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED) |
| reopen | submitted, verified | open | coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED) |
| escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED) |
| refreeze | open, claimed, submitted | open | coordinator, when there is no live claim awaiting a coordinator correction | joined (NOT_JOINED), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
@@ -132,7 +132,8 @@ Each move checks its guards in this order and refuses with the first one that do
| NO_POLICY | the caller's checkout contains the submitted commit | restore the frozen policy objects |
| BAD_CONFIG | the caller's checkout contains the submitted commit | repair the committed coordinator configuration |
| GIT_GRAFTS | the caller's checkout contains the submitted commit | ask the coordinator to remove the Git graft file before retrying |
-| SELF_VERIFY | the caller did not build it | another agent verifies it: pullboard next --verify |
+| SELF_VERIFY | the caller did not build it; on a linked board, at engine 13 or newer, the caller was enrolled through the relay by a line of creating seats from the coordinator that includes neither the builder nor a machine join | another agent verifies it: pullboard next --verify |
+| VERIFIER_STANDING | the caller did not build it; on a linked board, at engine 13 or newer, the caller was enrolled through the relay by a line of creating seats from the coordinator that includes neither the builder nor a machine join | the coordinator makes an independent verifier from the main checkout: pullboard worktree <lane> --model "<model name>" |
| COORDINATOR_VERIFIES | the repo's verify policy lets the caller verify this lane's work | the coordinator verifies it |
| 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 |
| REVIEW_HELD | no other agent holds its review under a live lease | pullboard next --verify, which passes over reviews another agent holds |
diff --git a/relay/auth-http.js b/relay/auth-http.js
index 1b0e6cb2..df911f39 100644
--- a/relay/auth-http.js
+++ b/relay/auth-http.js
@@ -67,7 +67,7 @@ export function createAuthHandler({ auth, publicOrigin }) {
const secure = origin.protocol === 'https:' ? '; Secure' : '';
const routes = new Set(['GET /auth/github/start', 'GET /auth/github/callback', 'POST /auth/device/start', 'POST /auth/device/poll', 'POST /auth/device/cancel',
'GET /auth/device/confirm', 'POST /auth/device/confirmation/open', 'POST /auth/device/confirmation/status', 'POST /auth/device/confirmation',
- 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);
+ 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'POST /auth/coordinators', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);
/** Resolve a bearer or cookie credential; cookie writes require an exact trusted Origin. */
function token(req, write = false) {
@@ -143,8 +143,13 @@ export function createAuthHandler({ auth, publicOrigin }) {
} else if (route === 'POST /auth/machines') {
const bearer = token(req, true);
json(res, 201, await auth.issueMachine(bearer, await body(req)));
+ } else if (route === 'POST /auth/coordinators') {
+ const bearer = token(req, true);
+ json(res, 201, await auth.issueCoordinator(bearer, await body(req)));
} else if (route === 'GET /auth/tokens') {
- json(res, 200, { tokens: await auth.listTokens(token(req), url.searchParams.get('board')) });
+ const bearer = token(req);
+ const board = url.searchParams.get('board');
+ json(res, 200, { tokens: await auth.listTokens(bearer, board), coordinatorEvents: await auth.coordinatorEvents(bearer, board) });
} else if (route === 'POST /auth/tokens') {
const bearer = token(req, true);
const input = await body(req);
diff --git a/relay/auth.js b/relay/auth.js
index 1a1ba65d..0e9378a3 100644
--- a/relay/auth.js
+++ b/relay/auth.js
@@ -6,6 +6,7 @@ import { DatabaseSync } from 'node:sqlite';
import { Refused } from '../src/refused.js';
import { repositoryName } from './github.js';
import { approvalContext } from '../src/relay-approval.js';
+import { VERIFIER_STANDING_ENGINE } from '../src/machine.js';
export const ACCESS_WINDOW_MS = 10 * 60_000;
const MAX_TTL = 30 * 24 * 3600_000;
@@ -46,7 +47,19 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
CREATE TABLE IF NOT EXISTS relay_credentials (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES relay_users(id), board TEXT REFERENCES relay_boards(id), agent TEXT, expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS relay_action_grants (hash TEXT PRIMARY KEY, request TEXT UNIQUE NOT NULL,
user_id TEXT NOT NULL, context TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);
+ CREATE TABLE IF NOT EXISTS relay_seats (board TEXT NOT NULL, agent TEXT NOT NULL,
+ origin TEXT NOT NULL CHECK(origin IN ('machine','registered','root')), creator TEXT, sequence INTEGER, digest TEXT,
+ first_id TEXT, first_created INTEGER, first_expires INTEGER, PRIMARY KEY (board, agent));
+ CREATE TABLE IF NOT EXISTS relay_coordinator_events (id TEXT PRIMARY KEY, board TEXT NOT NULL,
+ reason TEXT NOT NULL CHECK(reason IN ('bootstrap','reissue','reset')), session_id TEXT NOT NULL,
+ revoked TEXT NOT NULL, issued_id TEXT NOT NULL, at INTEGER NOT NULL);
`);
+ if (!db.prepare('PRAGMA table_info(relay_credentials)').all().some((column) => column.name === 'root')) {
+ db.exec('ALTER TABLE relay_credentials ADD COLUMN root INTEGER NOT NULL DEFAULT 0');
+ }
+ // Every seat that already held a token got it from the machine or a person mint: machine origin for good (#579).
+ db.exec(`INSERT OR IGNORE INTO relay_seats (board, agent, origin) SELECT DISTINCT board, agent, 'machine'
+ FROM relay_credentials WHERE kind = 'board' AND board IS NOT NULL AND agent IS NOT NULL`);
if (!db.prepare('PRAGMA table_info(relay_credentials)').all().some((column) => column.name === 'created')) {
db.exec('ALTER TABLE relay_credentials ADD COLUMN created INTEGER');
}
@@ -102,16 +115,37 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
}
/** Mint one independently expiring/revocable credential and persist only its hash. */
- function issue(user, kind, board, agent, ttl) {
+ function issue(user, kind, board, agent, ttl, root = false) {
open();
const token = random(kind === 'session' ? 'ps_' : kind === 'machine' ? 'pm_' : 'pa_');
const id = randomUUID();
const created = now();
const expires = created + ttl;
- db.prepare('INSERT INTO relay_credentials (id,hash,kind,user_id,board,agent,created,expires) VALUES (?,?,?,?,?,?,?,?)').run(id, hash(token), kind, user.id, board ?? null, agent ?? null, created, expires);
+ db.prepare('INSERT INTO relay_credentials (id,hash,kind,user_id,board,agent,created,expires,root) VALUES (?,?,?,?,?,?,?,?,?)').run(id, hash(token), kind, user.id, board ?? null, agent ?? null, created, expires, root ? 1 : 0);
return { token, id, created, expires };
}
+ /** The first-mint record of one seat on one board, which outlives every credential it names. */
+ function seat(board, agent) {
+ return db.prepare('SELECT * FROM relay_seats WHERE board=? AND agent=?').get(board, agent) ?? null;
+ }
+
+ /** Record a seat's first issuance; the seat row exists before its token is ever returned. */
+ function firstMint(user, board, agent, ttl, { origin, creator = null, sequence = null, digest = null, root = false }) {
+ const issued = issue(user, 'board', board, agent, ttl, root);
+ db.prepare(`INSERT INTO relay_seats (board,agent,origin,creator,sequence,digest,first_id,first_created,first_expires) VALUES (?,?,?,?,?,?,?,?,?)
+ ON CONFLICT(board, agent) DO UPDATE SET origin=excluded.origin, creator=excluded.creator, sequence=excluded.sequence, digest=excluded.digest,
+ first_id=excluded.first_id, first_created=excluded.first_created, first_expires=excluded.first_expires`)
+ .run(board, agent, origin, creator, sequence, digest, issued.id, issued.created, issued.expires);
+ return { ...issued, board, agent };
+ }
+
+ /** Validate an expiry request against the relay's thirty-day ceiling. */
+ function expiry(value, what) {
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TTL) throw new Refused('BAD_EXPIRY', `choose a ${what} expiry between one millisecond and thirty days`);
+ return value;
+ }
+
/** Learn the immutable GitHub identity, then drop the user access credential immediately. */
async function signedIn(result, { cancelled } = {}) {
if (!result || result.pending) throw new Refused('OAUTH_STATE', 'complete GitHub sign-in before creating a relay session');
@@ -431,7 +465,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
if (board !== null && board !== undefined && !db.prepare('SELECT 1 FROM relay_boards WHERE id=?').get(board)) throw new Refused('BOARD_NOT_LINKED', 'link this board again before using it');
credential(token); // A revocation or expiry during the awaited provider call must take effect.
}
- return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, ...(row.kind === 'machine' ? { machine: row.agent } : { agent: row.agent }) } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };
+ return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, ...(row.kind === 'machine' ? { machine: row.agent } : { agent: row.agent }) } : {}), ...(row.root ? { root: true } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };
},
/** Accept a link only from a signed-in human with current repository write access. */
async linkBoard(token, board, repository, deadline = Infinity) {
@@ -473,6 +507,9 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
lifecycle(() => {
db.prepare('INSERT OR IGNORE INTO relay_cleanup (board) VALUES (?)').run(board);
db.prepare('DELETE FROM relay_credentials WHERE board=?').run(board);
+ // A person unlinked the board; a later link starts its seats afresh with the new journal.
+ db.prepare('DELETE FROM relay_seats WHERE board=?').run(board);
+ db.prepare('DELETE FROM relay_coordinator_events WHERE board=?').run(board);
db.prepare('DELETE FROM relay_boards WHERE id=?').run(board);
});
for (const key of permissions.keys()) if (key.endsWith(':' + board)) permissions.delete(key);
@@ -501,7 +538,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
minimumEngineVersion(board) {
open();
identifier(board, 'BAD_BOARD');
- if (db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind='machine' LIMIT 1").get(board)) return 6;
+ // Machine and agent credentials now carry engine-13 seat provenance; older clients would skip it.
+ if (db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind IN ('machine','board') LIMIT 1").get(board)) return VERIFIER_STANDING_ENGINE;
return db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind='board' LIMIT 1").get(board) ? 3 : 1;
},
/** Give a foreground person one board-bound machine delegate, never another person credential. */
@@ -514,15 +552,107 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
credential(token);
return { ...issue(principal.user, 'machine', board, machine, expiresIn), board, machine };
},
- /** 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));
+ db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(current.id);
+ return { ...renewed, board, agent };
+ }
+ 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');
+ }
+ return firstMint(principal.user, board, agent, expiresIn, { origin: 'machine' });
+ });
+ },
+ /**
+ * 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);
+ 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), board, agent: 'coordinator' }
+ : firstMint(principal.user, board, 'coordinator', expiresIn, { origin: 'root', root: true });
+ 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) {
@@ -533,6 +663,15 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
return db.prepare('SELECT id,board,agent,created,expires,revoked FROM relay_credentials WHERE user_id=? AND kind=? AND board=? ORDER BY agent,id')
.all(principal.user.id, 'board', board).map((row) => ({ ...row, revoked: Boolean(row.revoked) }));
},
+ /** The person-made coordinator credential events on one board, with ids and times and no bearer values. */
+ async coordinatorEvents(token, board) {
+ identifier(board, 'BAD_BOARD');
+ 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 list agent token ids');
+ credential(token);
+ return db.prepare('SELECT id,reason,session_id,revoked,issued_id,at FROM relay_coordinator_events WHERE board=? ORDER BY at,rowid').all(board)
+ .map((row) => ({ id: row.id, reason: row.reason, session: row.session_id, revoked: JSON.parse(row.revoked), issued: row.issued_id, at: row.at }));
+ },
/** Mint a short-lived grant only after an authenticated phone approves an immutable action context. */
async issueActionGrant(token, value) {
const context = approvalContext(value);
diff --git a/relay/journal.js b/relay/journal.js
index 57e1dd51..570929e3 100644
--- a/relay/journal.js
+++ b/relay/journal.js
@@ -71,6 +71,11 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
DROP TABLE journal_snapshot_v2;
UPDATE journal_meta SET value='3' WHERE key='format';`);
}
+ // Engine-13 attribution (#579): the relay's policy stamp, the person-set coordinator flag and a
+ // seat receipt. Older records keep these empty, so they replay exactly as they did.
+ for (const [column, type] of [['sender_policy', 'INTEGER'], ['sender_root', 'INTEGER'], ['registration', 'TEXT']]) {
+ if (!db.prepare('PRAGMA table_info(journal_record)').all().some((saved) => saved.name === column)) db.exec(`ALTER TABLE journal_record ADD COLUMN ${column} ${type}`);
+ }
db.exec('INSERT OR IGNORE INTO journal_head (slot,sequence) SELECT 1, COALESCE(MAX(sequence),0) FROM journal_record');
if (!db.prepare('PRAGMA table_info(journal_head)').all().some((column) => column.name === 'last_activity_at')) {
db.exec('ALTER TABLE journal_head ADD COLUMN last_activity_at TEXT');
@@ -90,7 +95,9 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
function record(row) {
return { sequence: row.sequence, receivedAt: row.received_at, kind: row.kind ?? 'snapshot',
sender: { kind: row.sender_kind, userId: row.sender_user,
- ...(row.sender_kind === 'agent' ? { agent: row.sender_agent } : row.sender_kind === 'machine' ? { machine: row.sender_agent } : {}) }, bytes: Buffer.from(row.payload) };
+ ...(row.sender_kind === 'agent' ? { agent: row.sender_agent } : row.sender_kind === 'machine' ? { machine: row.sender_agent } : {}),
+ ...(row.sender_policy ? { policy: row.sender_policy } : {}), ...(row.sender_root ? { root: true } : {}) },
+ ...(row.registration ? { registration: JSON.parse(row.registration) } : {}), bytes: Buffer.from(row.payload) };
}
/** Require server-derived attribution, copying only its public identity and never a credential. */
@@ -102,7 +109,22 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
throw new Refused('RELAY_PRINCIPAL', 'supply the authenticated sender before storing a sealed record');
}
if (personOnly && !['person', 'machine'].includes(value.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential to replace its snapshot');
- return { kind: value.kind, userId: value.userId, agent: value.kind === 'agent' ? value.agent : value.kind === 'machine' ? value.machine : null };
+ if ((value.policy !== undefined && (!Number.isSafeInteger(value.policy) || value.policy < 1)) || (value.root !== undefined && value.root !== true)) {
+ throw new Refused('RELAY_PRINCIPAL', 'supply the relay policy stamp as a positive engine number');
+ }
+ return { kind: value.kind, userId: value.userId, agent: value.kind === 'agent' ? value.agent : value.kind === 'machine' ? value.machine : null,
+ policy: value.policy ?? null, root: value.root === true ? 1 : null };
+ }
+
+ /** Keep a seat receipt to its four public fields: target, creator, sequence and ciphertext digest. */
+ function receipt(value, sequence) {
+ if (value === undefined || value === null) return null;
+ const fields = ['creator', 'digest', 'sequence', 'target'];
+ if (typeof value !== 'object' || Object.keys(value).sort().join() !== fields.join() || value.sequence !== sequence ||
+ typeof value.target !== 'string' || typeof value.creator !== 'string' || !/^[0-9a-f]{64}$/.test(value.digest ?? '')) {
+ throw new Refused('BAD_REGISTRATION', 'attach a seat receipt naming its target, creator, this sequence and the ciphertext digest');
+ }
+ return JSON.stringify({ target: value.target, creator: value.creator, sequence: value.sequence, digest: value.digest });
}
/** Read the latest committed sequence, including an empty journal's initial cursor. */
@@ -124,12 +146,14 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
}
/** Serialize prefix checking or sequence allocation with the opaque append. */
- function insert(sequence, bytes, kind, principal) {
+ function insert(sequence, bytes, kind, principal, registration) {
open();
if (sequence !== null && (!Number.isSafeInteger(sequence) || sequence < 1)) throw new Refused('BAD_SEQUENCE', 'upload a positive safe integer sequence');
const sealed = payload(bytes);
const who = sender(principal);
if (!['move', 'request'].includes(kind)) throw new Refused('BAD_UPLOAD', 'use the move or request transport kind');
+ if (registration !== undefined && (sequence === null || kind !== 'move')) throw new Refused('BAD_REGISTRATION', 'attach a seat receipt only to a move at its named sequence');
+ const stored = receipt(registration, sequence);
db.exec('BEGIN IMMEDIATE');
try {
const next = latest() + 1;
@@ -139,7 +163,8 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
if (sequence > next) throw new Refused('SEQUENCE_GAP', 'send the next sequence after the latest committed record before later uploads');
const at = now();
if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');
- db.prepare('INSERT INTO journal_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent) VALUES (?,?,?,?,?,?,?)').run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent);
+ db.prepare('INSERT INTO journal_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent,sender_policy,sender_root,registration) VALUES (?,?,?,?,?,?,?,?,?,?)')
+ .run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent, who.policy, who.root, stored);
db.prepare('UPDATE journal_head SET sequence=?,last_activity_at=? WHERE slot=1').run(sequence, at.toISOString());
const result = record(db.prepare('SELECT * FROM journal_record WHERE sequence=?').get(sequence));
db.exec('COMMIT');
@@ -150,8 +175,15 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
}
}
- /** Append a transport retry only at its explicitly named next sequence. */
- function append(sequence, bytes, kind = 'move', principal) { return insert(sequence, bytes, kind, principal); }
+ /** Append a transport retry only at its explicitly named next sequence, with an optional seat receipt. */
+ function append(sequence, bytes, kind = 'move', principal, registration) { return insert(sequence, bytes, kind, principal, registration); }
+
+ /** Read one committed record, or null once compaction removed it, for an exact registration retry. */
+ function recordAt(sequence) {
+ open();
+ const row = db.prepare('SELECT * FROM journal_record WHERE sequence=?').get(sequence);
+ return row ? record(row) : null;
+ }
/** Allocate the next sequence under the same lock as the append, as the live relay requires. */
function appendNext(bytes, kind = 'move', principal) { return insert(null, bytes, kind, principal); }
@@ -199,5 +231,5 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
closed = true;
}
- return { board: id, latest, activity, append, appendNext, after, snapshot, saveSnapshot, close };
+ return { board: id, latest, activity, append, appendNext, recordAt, after, snapshot, saveSnapshot, close };
}
diff --git a/relay/service.js b/relay/service.js
index 450ef05a..50fb0b30 100644
--- a/relay/service.js
+++ b/relay/service.js
@@ -12,6 +12,7 @@ import { createDeviceHandler } from './device-http.js';
import { createPairingStore } from './pairing-store.js';
import { createPairingHandler } from './pairing-http.js';
import { createRelayBrowserHandler } from './browser-page.js';
+import { VERIFIER_STANDING_ENGINE } from '../src/machine.js';
const SNAPSHOT_BODY = 14_000_000;
const STORED_BYTES = 10_000_000;
@@ -53,8 +54,8 @@ function trustedOrigin(value) {
}
/** Decode only canonical transport bytes; sealed payloads are never parsed or unsealed. */
-function sealed(body) {
- const keys = ['sealed', 'sequence'];
+function sealed(body, allowRegistration = false) {
+ const keys = allowRegistration ? ['sealed', 'sequence', 'registration'] : ['sealed', 'sequence'];
if (!body || Object.keys(body).some((key) => !keys.includes(key)) || typeof body.sealed !== 'string' || !/^[A-Za-z0-9_-]+$/.test(body.sealed)) {
throw new Refused('BAD_UPLOAD', 'send only sequence and a nonempty base64url sealed payload; keep keys on your device');
}
@@ -64,7 +65,35 @@ function sealed(body) {
}
/** Give live events the common API cursor while keeping all board contents sealed. */
-function event(row) { return { event_id: row.sequence, event_at: row.receivedAt, kind: row.kind, sender: row.sender, sealed: row.bytes.toString('base64url') }; }
+function event(row) {
+ return { event_id: row.sequence, event_at: row.receivedAt, kind: row.kind, sender: row.sender,
+ ...(row.registration ? { registration: row.registration } : {}), sealed: row.bytes.toString('base64url') };
+}
+
+/**
+ * Check a seat receipt against what the relay itself knows (#579): the sending agent token is the
+ * creator, the target is another, non-coordinator seat, and sequence and digest name this exact
+ * upload. The relay never reads the sealed move; replicas bind the target to its contents.
+ */
+function seatReceipt(body, who) {
+ const value = body.registration;
+ const fields = ['creator', 'digest', 'sequence', 'target'];
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join() !== fields.join()) {
+ throw new Refused('BAD_REGISTRATION', 'send a seat receipt with exactly target, creator, sequence and digest');
+ }
+ const name = /^[A-Za-z0-9_.-]{1,128}$/;
+ if (who.kind !== 'board' || value.creator !== who.agent) throw new Refused('REGISTRATION_SENDER', 'register a seat with the creating seat\'s own token');
+ if (typeof value.target !== 'string' || !name.test(value.target) || ['.', '..', 'coordinator', who.agent].includes(value.target)) {
+ throw new Refused('BAD_REGISTRATION', 'name a new seat other than the creator and the coordinator');
+ }
+ if (value.sequence !== body.sequence || value.digest !== createHash('sha256').update(body.sealed).digest('hex')) {
+ throw new Refused('BAD_REGISTRATION', 'the seat receipt must name this upload\'s sequence and the SHA-256 of its sealed text');
+ }
+ if (value.creator === 'coordinator' && who.root !== true) {
+ throw new Refused('REGISTRATION_ROOT', 'only the coordinator credential the person set up creates seats; run pullboard relay on in the main checkout once');
+ }
+ return { target: value.target, creator: value.creator, sequence: value.sequence, digest: value.digest };
+}
/** Give a snapshot its coverage cursor; clients unseal it and replay the following sealed events. */
function state(row) { return { sequence: row.sequence, receivedAt: row.receivedAt, sender: row.sender, sealed: row.bytes.toString('base64url') }; }
@@ -73,7 +102,8 @@ function state(row) { return { sequence: row.sequence, receivedAt: row.receivedA
function sender(who, personOnly = false) {
if (personOnly && who.kind !== 'session' && !(personOnly === 'snapshot' && who.kind === 'machine')) throw new Refused('HUMAN_REQUIRED', 'approve this person action from the paired phone');
return { kind: who.kind === 'session' ? 'person' : who.kind === 'machine' ? 'machine' : 'agent', userId: who.user.id,
- ...(who.kind === 'board' ? { agent: who.agent } : who.kind === 'machine' ? { machine: who.machine } : {}) };
+ ...(who.kind === 'board' ? { agent: who.agent } : who.kind === 'machine' ? { machine: who.machine } : {}),
+ ...(personOnly === 'snapshot' ? {} : { policy: VERIFIER_STANDING_ENGINE, ...(who.root === true ? { root: true } : {}) }) };
}
/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */
@@ -172,12 +202,34 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
/** Append ciphertext under its server-allocated sequence, with no engine or filesystem access. */
async function append(board, body, who, kind = 'move') {
- const bytes = sealed(body);
+ const bytes = sealed(body, kind === 'move');
if (!Number.isSafeInteger(body.sequence) || body.sequence < 1) throw new Refused('BAD_SEQUENCE', 'seal this move for the next positive sequence after the latest committed prefix');
- const principal = sender(await authorized(who.credential, board.id, true));
+ const authenticated = await authorized(who.credential, board.id, true);
+ const principal = sender(authenticated);
+ if (body.registration === undefined) {
+ return withJournal(board.id, (journal) => {
+ const row = journal.append(body.sequence, bytes, kind, principal);
+ return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };
+ }, false, who.engineVersion);
+ }
+ // A registration move and its target's first token commit under one board lock; the token
+ // goes only to this authenticated creator, never into the public event (#579).
+ const receipt = seatReceipt(body, authenticated);
return withJournal(board.id, (journal) => {
- const row = journal.append(body.sequence, bytes, kind, principal);
- return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };
+ const prior = auth.seatRecord(board.id, receipt.target);
+ const retry = prior && prior.origin === 'registered' && prior.creator === receipt.creator && prior.sequence === receipt.sequence && prior.digest === receipt.digest;
+ if (prior && !retry) throw new Refused('SEAT_TAKEN', `the relay already issued ${receipt.target} a token, so it cannot be registered again; register the next free name`);
+ let row;
+ try { row = retry ? journal.recordAt(receipt.sequence) : journal.append(body.sequence, bytes, kind, principal, receipt); }
+ catch (error) {
+ // The move committed but its seat did not: finish the enrollment for the exact same upload.
+ const saved = error.code === 'SEQUENCE_REPEAT' ? journal.recordAt(receipt.sequence) : null;
+ if (!saved || !saved.bytes.equals(bytes) || JSON.stringify(saved.registration) !== JSON.stringify(receipt) || saved.sender.agent !== receipt.creator) throw error;
+ row = saved;
+ }
+ const enrollment = auth.enrollSeat(who.credential, board.id, receipt);
+ const committed = row ? event(row) : { event_id: receipt.sequence, kind, sender: principal, registration: receipt, sealed: body.sealed };
+ return { status: 200, body: { event: committed, result: { sequence: receipt.sequence }, enrollment } };
}, false, who.engineVersion);
}
diff --git a/src/board.js b/src/board.js
index 025ae554..6102e7b3 100644
--- a/src/board.js
+++ b/src/board.js
@@ -12,7 +12,7 @@ import { dirname } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { briefFiles, briefSections } from './brief.js';
import { COORDINATOR } from './config.js';
-import { ENGINE_VERSION, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, effectiveGuards, storeTriggers } from './machine.js';
+import { ENGINE_VERSION, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, VERIFIER_STANDING_ENGINE, effectiveGuards, storeTriggers } from './machine.js';
import { Refused } from './refused.js';
import { parseSpec } from './spec.js';
@@ -533,12 +533,19 @@ function saveAgentModel(board, id, model) {
* by the agent; the board neither names nor infers it. Registering again preserves the agent id;
* explicitly supplied family and model values update their declarations, while omission preserves them.
*
+ * From engine 13 a new seat records the seat that created it (`createdBy`: an agent id, or
+ * `machine` for a join no seat made), so a linked board can tell a builder's own seats from
+ * independent verifiers (#579). A creator may name the new seat (`id`, the lane's next form) when
+ * the relay already issued a token for the next name; ids then skip taken names.
+ *
* @param {any} board
- * @param {{ lane: string, path: string, route?: string, family?: string | null, model?: string | null }} who
+ * @param {{ lane: string, path: string, route?: string, family?: string | null, model?: string | null, createdBy?: string, id?: string }} who
* @returns {string} The agent's id.
*/
-export function register(board, { lane, path, route = 'strong', family, model }) {
- if ((board.executionEngineVersion ?? ENGINE_VERSION) < 8) model = undefined;
+export function register(board, { lane, path, route = 'strong', family, model, createdBy, id: named }) {
+ const engine = board.executionEngineVersion ?? ENGINE_VERSION;
+ if (engine < 8) model = undefined;
+ if (engine < VERIFIER_STANDING_ENGINE) { createdBy = undefined; named = undefined; }
checkRoute(route);
if (lane === COORDINATOR && route !== 'strong') {
throw new Refused('BAD_ROUTE', 'the coordinator plans, merges and verifies; it is always strong');
@@ -568,18 +575,156 @@ export function register(board, { lane, path, route = 'strong', family, model })
if (lane === COORDINATOR && total > 0) {
throw new Refused('ONE_COORDINATOR', 'the coordinator is the main checkout; it already has one');
}
- const id = lane === COORDINATOR ? COORDINATOR : `${lane}-${total + 1}`;
+ if (createdBy !== undefined && createdBy !== 'machine' && createdBy !== COORDINATOR && !board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(createdBy)) {
+ throw new Refused('NO_AGENT', `the creating seat ${createdBy} is not registered; create new seats from a joined worktree or the main checkout`);
+ }
+ const id = lane === COORDINATOR ? COORDINATOR
+ : engine < VERIFIER_STANDING_ENGINE ? `${lane}-${total + 1}` : newSeatId(board, lane, total, named);
board.db
.prepare(
'INSERT INTO agent (agent_id, agent_lane, agent_path, agent_route, agent_family, agent_created_at) VALUES (?, ?, ?, ?, ?, ?)',
)
.run(id, lane, path, route, family ?? null, now(board));
if ((board.executionEngineVersion ?? ENGINE_VERSION) >= 8) saveAgentModel(board, id, model);
+ if (createdBy !== undefined) board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_creator:${id}`, createdBy);
+ // Only a relay replica replaying a receipt-bound registration marks the seat enrolled.
+ if (board.relayEnrollment === id && createdBy !== undefined && createdBy !== 'machine') {
+ board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_enrolled:${id}`, createdBy);
+ }
logEvent(board, id, 'join', null, route === 'strong' ? { lane } : { lane, route });
return id;
});
}
+/**
+ * The id an engine-13 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}
+ */
+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-13 registration recorded it: an agent id,
+ * `machine` for a join no seat made, or null for a seat registered before engine 13.
+ *
+ * @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 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-13 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 }} standing
+ * @param {() => T} work
+ * @returns {T}
+ */
+export function withVerifierStanding(board, standing, work) {
+ const previous = board.verifierStanding;
+ board.verifierStanding = { root: standing.root === true };
+ 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 13 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
+ * @returns {Refused | null}
+ */
+function standingProblem(board, verifier, builder) {
+ 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) {
+ return new Refused('VERIFIER_STANDING', `${verifier} cannot verify work the coordinator built on this linked board: every seat the coordinator made shares its lineage; a seat from another machine's registration lineage, or the person, verifies it`);
+ }
+ 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;
+ }
+}
+
/**
* The coordinator, registered at the main checkout. Only the main checkout of this repo can reach
* this board, so when the repo moved on disk the coordinator follows it instead of refusing.
@@ -1389,7 +1534,8 @@ export function reviewOffer(board, { agentId, lane, policy = 'any', familyPolicy
function reviewerChecks(board, { agentId, policy, familyPolicy = 'off' }) {
const family = board.db.prepare('SELECT agent_family FROM agent WHERE agent_id = ?').get(agentId)?.agent_family ?? null;
return {
- notBuilder: (found) => (found.item_built_by === agentId ? new Refused('SELF_VERIFY', 'the builder never verifies its own work; another agent must') : null),
+ notBuilder: (found) => (found.item_built_by === agentId ? new Refused('SELF_VERIFY', 'the builder never verifies its own work; another agent must')
+ : standingProblem(board, agentId, found.item_built_by)),
routeAllows: (found) => {
const route = routeOf(board, agentId);
return canTake(route, found.item_route) ? null : new Refused('ROUTE', `item #${found.item_id} needs a ${found.item_route} verifier; you joined on the ${route} route`);
@@ -2166,7 +2312,9 @@ export function nextFor(board, { agentId, lane, verify = false, policy = 'any',
if (verify) {
const family = board.db.prepare('SELECT agent_family FROM agent WHERE agent_id = ?').get(agentId)?.agent_family ?? null;
const hasDifferentFamily = (entry) => Boolean(family && entry.item_builder_family && family !== entry.item_builder_family);
- let reviewable = items.filter((entry) => entry.item_status === 'submitted' && entry.item_built_by !== agentId);
+ const unrelated = items.filter((entry) => entry.item_status === 'submitted' && entry.item_built_by !== agentId);
+ const standingRefusal = unrelated.map((entry) => standingProblem(board, agentId, entry.item_built_by)).find(Boolean);
+ let reviewable = unrelated.filter((entry) => !standingProblem(board, agentId, entry.item_built_by));
if (policy === COORDINATOR && agentId !== COORDINATOR) reviewable = reviewable.filter((entry) => entry.item_lane === COORDINATOR);
if (familyPolicy === 'require') reviewable = reviewable.filter(hasDifferentFamily);
if (familyPolicy === 'prefer') reviewable.sort((first, second) => Number(hasDifferentFamily(second)) - Number(hasDifferentFamily(first)));
@@ -2185,7 +2333,8 @@ export function nextFor(board, { agentId, lane, verify = false, policy = 'any',
.map(({ entry, holder: reviewer }) => `${reviewer} holds the review of #${entry.item_id} until ${entry.item_review_until}`);
const cooling = candidates.filter((candidate) => candidate.cooldown)
.map(({ entry, cooldown }) => `you released the review of #${entry.item_id}; try again after ${cooldown}, or let another reviewer take it`);
- return { item: null, reasons: [`nothing ${routed}submitted that you did not build${held.length ? ' and no other agent is reviewing' : ''}`, ...held, ...cooling] };
+ return { item: null, reasons: [`nothing ${routed}submitted that you did not build${held.length ? ' and no other agent is reviewing' : ''}`,
+ ...(standingRefusal ? [standingRefusal.message] : []), ...held, ...cooling] };
}
const held = items.find((entry) => entry.item_status === 'claimed' && entry.item_owner === agentId && entry.item_parent_id === null);
if (held) return { item: held, reasons: [] };
diff --git a/src/cli.js b/src/cli.js
index 062d6c58..9f6d3cd5 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -567,6 +567,12 @@ function withBoard(ctx, work) {
/** Dispatch a board mutation locally, or seal it before any linked replica applies it. */
async function ordered(ctx, board, operation, args) {
+ // Every engine-13 registration records the seat that made it: the coordinator from the main
+ // checkout, the joined agent from its worktree, or `machine` for a join no seat made (#579).
+ if (operation === 'register' && args[0] && args[0].createdBy === undefined) {
+ const joined = store.agentAt(board, ctx.info.root)?.agent_id;
+ args = [{ ...args[0], createdBy: ctx.info.isMain ? COORDINATOR : joined ?? 'machine' }, ...args.slice(1)];
+ }
const command = ['add', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
/** Dispatch while this session holds the checkout, including long-running next/run loops. */
const execute = () => relayLinked(ctx.info.root)
@@ -2469,8 +2475,10 @@ async function nextOnce(ctx, values) {
const { item, reasons, shared } = store.nextFor(board, { agentId: me.id, lane: me.lane, runnable: values.runnable, routes: values.routes, warm,
priority: mainRedReworkItems(ctx.info.root, board) });
const held = item?.item_status === 'claimed';
- const offer = held ? null : store.reviewOffer(board, { agentId: me.id, lane: me.lane, policy: ctx.config.verify.policy,
+ /** Offer only reviews this seat may give; a linked board previews its engine-13 verifier standing (#579). */
+ const findOffer = () => store.reviewOffer(board, { agentId: me.id, lane: me.lane, policy: ctx.config.verify.policy,
familyPolicy: ctx.config.verify.family, ratio: ctx.config.verify.reviewRatio, runnable: values.runnable, routes: values.routes });
+ const offer = held ? null : relayLinked(ctx.info.root) ? store.withVerifierStanding(board, { root: true }, findOffer) : findOffer();
if (offer && !values.build) return { item: offer.item, offer, build: item ?? null };
if (!item) return { reasons };
const reviewSkipped = values.build && !held
@@ -3570,6 +3578,8 @@ async function runCommand(argv, io) {
const ctx = context(io);
const agents = withBoard(ctx, (board) => store.listAgents(board));
for (const row of result.tokens) io.say(row.id + ' ' + agentDisplayName(agents, ctx.config, row.agent) + ' ' + (row.revoked ? 'revoked' : 'expires ' + new Date(row.expires).toISOString()));
+ // The person-made coordinator credential events: who set it up, what it revoked, what it issued.
+ for (const row of result.coordinatorEvents ?? []) io.say(`coordinator ${row.reason} by person session ${row.session} at ${new Date(row.at).toISOString()}: issued ${row.issued}, revoked ${row.revoked.length ? row.revoked.join(', ') : 'none'}`);
} else io.say('revoked token ' + result.id + '; other agent tokens are unchanged');
return 0;
}
diff --git a/src/engine.js b/src/engine.js
index 3b5c167c..945e7c1a 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -1,8 +1,9 @@
/** Versioned, deterministic replay through the CLI's existing board engine [H3,H16]. */
import { createHash, randomUUID } from 'node:crypto';
import * as store from './board.js';
+import { COORDINATOR } from './config.js';
import { refusalDocument } from './json.js';
-import { ENGINE_VERSION } from './machine.js';
+import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';
import { Refused } from './refused.js';
import { requestMoveProblem, recordRequestMove } from './relay-requests.js';
import { relayMoveActor, relaySenderProblem, validRelaySender } from './relay-sender.js';
@@ -179,12 +180,49 @@ export function refuseRelayMove(board, move, { sequence, at, sender, kind, code,
});
}
+/**
+ * Bind an engine-13 registration to the relay's receipt (#579). A seat made by another seat names
+ * itself in the move (`id`) and arrives with the receipt the relay issued its first token under:
+ * same target, the authenticated creator, this position and these exact sealed bytes. A join no
+ * seat made is machine-sent and carries no receipt; a receipt on any other move is refused.
+ *
+ * @param {any} board
+ * @param {any} move
+ * @param {{ sender: any, registration?: any, sequence: number, digest: string | null }} record
+ * @returns {Refused | null}
+ */
+function registrationProblem(board, move, { sender, registration, sequence, digest }) {
+ const refuse = (why) => new Refused('RELAY_REGISTRATION', `${why}; register the seat again from its creating seat's checkout`);
+ const options = move?.operation === 'register' && move.engine >= VERIFIER_STANDING_ENGINE ? move.args?.[0] : null;
+ if (!options || sender?.kind === 'person') return registration === undefined || registration === null ? null : refuse('the relay attached a seat receipt to a move that registers no seat');
+ const existing = typeof options.path === 'string' ? store.agentAt(board, options.path) : null;
+ if (sender.kind === 'machine' || existing) {
+ if (registration !== undefined && registration !== null) return refuse('a machine join or a returning seat carries no seat receipt');
+ if (existing && sender.kind === 'agent' && existing.agent_id !== sender.agent) return refuse(`agent ${sender.agent} cannot register another seat's worktree`);
+ return null;
+ }
+ if (options.createdBy === COORDINATOR && sender.root !== true) {
+ return refuse('only the coordinator credential the person set up creates seats; run pullboard relay on in the main checkout once');
+ }
+ const receipt = registration ?? {};
+ if (typeof options.id !== 'string' || receipt.target !== options.id || receipt.creator !== sender.agent || receipt.creator !== options.createdBy ||
+ receipt.sequence !== sequence || typeof digest !== 'string' || receipt.digest !== digest) {
+ return refuse('a new seat needs the relay receipt its creator received for exactly this sealed move');
+ }
+ return null;
+}
+
/** Authorize each public relay position before replay, retaining refusals atomically with its cursor. */
-export function applyRelayMove(board, move, { sequence, at, sender, kind, digest = null }) {
+export function applyRelayMove(board, move, { sequence, at, sender, kind, digest = null, registration }) {
requireSupportedEngine(move);
const phoneReceipt = sender?.kind === 'machine' && move?.engine >= 6 && Boolean(move.personRequest) && !requestMoveProblem(board, move, { checkExecutorLease: false });
- const problem = relaySenderProblem(move, sender, kind, { phoneReceipt });
- if (!problem) return applyEngineMove(board, move, { sequence, at });
+ const problem = relaySenderProblem(move, sender, kind, { phoneReceipt }) ?? (kind === 'move' ? registrationProblem(board, move, { sender, registration, sequence, digest }) : null);
+ if (!problem) {
+ // Engine-13 relay moves run under linked verifier standing; older recorded moves replay as they did.
+ // The person is above every seat; their own moves act with the coordinator's standing.
+ const standing = move?.engine >= VERIFIER_STANDING_ENGINE ? { root: sender?.root === true || sender?.kind === 'person' } : null;
+ return applyEngineMove(board, move, { sequence, at, standing, enrollment: registration?.target ?? null });
+ }
return refuseRelayMove(board, move, { sequence, at, sender, kind, code: problem.code, digest, refusal: problem });
}
@@ -192,7 +230,7 @@ export function applyRelayMove(board, move, { sequence, at, sender, kind, digest
* Apply one relay position with the same board functions as the CLI, preserving its refusal.
* A receipt and prefix commit atomically; duplicate ids return that receipt without another move.
*/
-export function applyEngineMove(board, move, { sequence, at }) {
+export function applyEngineMove(board, move, { sequence, at, standing = null, enrollment = null }) {
validateMove(move);
if (!Number.isSafeInteger(sequence) || sequence < 1 || !Number.isFinite(Date.parse(at))) throw new Refused('RELAY_MOVE', 'supply a valid relay sequence and receipt timestamp');
return store.atomic(board, () => {
@@ -212,18 +250,21 @@ export function applyEngineMove(board, move, { sequence, at }) {
board.clock = { now: () => new Date(at) };
board.executionEngineVersion = move.engine;
const firstEvent = board.emittedEvents?.length ?? 0;
+ if (enrollment !== null) board.relayEnrollment = enrollment;
try {
- const result = store.atomic(board, () => {
+ const execute = () => store.atomic(board, () => {
const problem = requestMoveProblem(board, move);
if (problem) throw problem;
return store[move.operation](board, ...executableArgs(move, board));
});
+ const result = standing ? store.withVerifierStanding(board, standing, execute) : execute();
outcome = { result: result ?? null, events: (board.emittedEvents?.slice(firstEvent) ?? []).map((event) => ({ ...event })) };
} catch (error) {
if (!(error instanceof Refused)) throw error;
outcome = { error: refusalDocument(error).error };
} finally {
board.clock = clock;
+ delete board.relayEnrollment;
if (engineVersion === undefined) delete board.executionEngineVersion;
else board.executionEngineVersion = engineVersion;
}
diff --git a/src/machine.js b/src/machine.js
index 605bf80b..a5ea192e 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -10,7 +10,13 @@
*/
/** Executable move semantics, carried by every sealed move and retained during replay [H16]. */
-export const ENGINE_VERSION = 12;
+export const ENGINE_VERSION = 13;
+
+/**
+ * The engine whose relay moves carry seat provenance and verifier standing (#579). It is its own
+ * constant because engine slots are allotted per item: whoever lands second renumbers this line.
+ */
+export const VERIFIER_STANDING_ENGINE = 13;
/** @typedef {'agent' | 'coordinator' | 'clock'} Role */
@@ -127,7 +133,7 @@ export const GUARDS = [
{ id: 'childrenDone', refuse: 'CHILDREN_OPEN', rule: 'every child item is verified or withdrawn', next: 'finish the child items, or the coordinator withdraws them', source: 'board' },
{ id: 'headIsNew', refuse: 'HEAD_NOT_NEW', rule: 'a verifier has not rejected this commit at this bar; after a no-verdict reopen, the bar was refrozen', next: 'commit the rework, or refreeze the bar after a no-verdict reopen before resubmitting the same commit', source: 'board' },
{ id: 'atSubmittedCommit', refuse: 'NOT_AT_COMMIT', alsoRefuses: [{ code: 'OUTSIDE_LANE', next: 'restore foreign paths before accepting' }, { code: 'NO_POLICY', next: 'restore the frozen policy objects' }, { code: 'BAD_CONFIG', next: 'repair the committed coordinator configuration' }, { code: 'GIT_GRAFTS', next: 'ask the coordinator to remove the Git graft file before retrying' }], rule: "the caller's checkout contains the submitted commit", next: 'git switch --detach <commit>', source: 'cli' },
- { id: 'notBuilder', refuse: 'SELF_VERIFY', rule: 'the caller did not build it', next: 'another agent verifies it: pullboard next --verify', source: 'board' },
+ { id: 'notBuilder', refuse: 'SELF_VERIFY', alsoRefuses: [{ code: 'VERIFIER_STANDING', next: 'the coordinator makes an independent verifier from the main checkout: pullboard worktree <lane> --model "<model name>"' }], rule: 'the caller did not build it; on a linked board, at engine 13 or newer, the caller was enrolled through the relay by a line of creating seats from the coordinator that includes neither the builder nor a machine join', next: 'another agent verifies it: pullboard next --verify', source: 'board' },
{ id: 'policyAllows', refuse: 'COORDINATOR_VERIFIES', rule: "the repo's verify policy lets the caller verify this lane's work", next: 'the coordinator verifies it', source: 'board' },
{ id: 'familyAllows', refuse: 'O2_FAMILY_MATCH', rule: 'the builder and verifier have different declared families; an undeclared family counts as a match', next: 'ask the coordinator for a verifier from another declared family', source: 'board', when: 'only when verify.family is require' },
{ id: 'reviewFree', refuse: 'REVIEW_HELD', rule: 'no other agent holds its review under a live lease', next: 'pullboard next --verify, which passes over reviews another agent holds', source: 'board' },
diff --git a/src/relay-pairing-client.js b/src/relay-pairing-client.js
index a90d5395..b0f06538 100644
--- a/src/relay-pairing-client.js
+++ b/src/relay-pairing-client.js
@@ -9,7 +9,7 @@ import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
import { encodeBoardKey } from './seal.js';
import { createPairingCode, openPairingBundle, parsePairingCode, sealPairingBundle } from './pairing.js';
import { terminalQr } from './qr.js';
-import { DEFAULT_RELAY, originRepository, relayStatus, syncRelay } from './relay.js';
+import { DEFAULT_RELAY, originRepository, relayPersonCoordinator, relayStatus, syncRelay } from './relay.js';
import { ENGINE_VERSION } from './machine.js';
import { Refused } from './refused.js';
import { requirePersonChannel } from './person.js';
@@ -226,6 +226,8 @@ export async function relayJoin(root, code, address, io) {
}
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 };
io.result?.(result);
diff --git a/src/relay-sender.js b/src/relay-sender.js
index e6a284d3..39d82d32 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -1,10 +1,12 @@
/** Compare sealed actors with the relay's independently authenticated sender [H2,H16,B26]. */
+import { VERIFIER_STANDING_ENGINE } from './machine.js';
import { Refused } from './refused.js';
/** Read only the actor field used by each public engine operation; unknown operations fail closed. */
export function relayMoveActor(move) {
const args = move?.args;
if (!Array.isArray(args)) return null;
+ if (move.operation === 'register' && move.engine >= VERIFIER_STANDING_ENGINE) return args[0]?.createdBy === 'machine' ? null : args[0]?.createdBy ?? null;
if (move.operation === 'addItem') return args[0]?.by ?? null;
if (move.operation === 'shout') return args[0]?.from ?? null;
if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';
@@ -19,7 +21,9 @@ export function relayMoveActor(move) {
export function validRelaySender(sender) {
return Boolean(sender && ['person', 'agent', 'machine'].includes(sender.kind) && typeof sender.userId === 'string' && sender.userId.length > 0 && sender.userId.length <= 256 &&
(sender.kind !== 'agent' || (typeof sender.agent === 'string' && sender.agent.length > 0 && sender.agent.length <= 256)) &&
- (sender.kind !== 'machine' || (typeof sender.machine === 'string' && sender.machine.length > 0 && sender.machine.length <= 256)));
+ (sender.kind !== 'machine' || (typeof sender.machine === 'string' && sender.machine.length > 0 && sender.machine.length <= 256)) &&
+ (sender.policy === undefined || Number.isSafeInteger(sender.policy) && sender.policy > 0) &&
+ (sender.root === undefined || sender.root === true));
}
/** Make the same authorization decision on every device, without inspecting its shell or checkout. */
@@ -27,6 +31,10 @@ export function relaySenderProblem(move, sender, kind, { phoneReceipt = false }
if (!validRelaySender(sender)) {
return new Refused('RELAY_SENDER', 'this relay record has no authenticated sender; restore attribution before replaying it');
}
+ // The relay stamps its policy on every record it now stores; an older engine cannot skip it (#579).
+ if (sender.policy >= VERIFIER_STANDING_ENGINE && kind !== 'snapshot' && !(move?.engine >= VERIFIER_STANDING_ENGINE)) {
+ return new Refused('ENGINE_VERSION', `this relay stores engine-${VERIFIER_STANDING_ENGINE} records; upgrade pullboard before sending moves to it`);
+ }
if (move?.operation === 'shout' && move.args?.[0]?.answers != null) {
return new Refused('RELAY_ANSWER', 'a sealed shout cannot answer or pass a decision; use pullboard answer <id> "<answer>" or pullboard pass <id> --note "<reason>" so the decision rules are checked');
}
@@ -34,7 +42,8 @@ export function relaySenderProblem(move, sender, kind, { phoneReceipt = false }
if (sender.kind === 'machine') {
if (kind === 'snapshot') return null;
if (kind === 'move' && move?.engine >= 6 && (phoneReceipt ||
- move.operation === 'register' && typeof move.args?.[0]?.lane === 'string' && move.args[0].lane !== 'person' ||
+ move.operation === 'register' && typeof move.args?.[0]?.lane === 'string' && move.args[0].lane !== 'person' &&
+ (move.engine < VERIFIER_STANDING_ENGINE || move.args[0].createdBy === 'machine' && move.args[0].id === undefined) ||
move.operation === 'ensureCoordinator' && typeof move.args?.[0] === 'string')) return null;
return new Refused('RELAY_PERSON_ONLY', 'a machine cannot act as the person; approve this action on the paired phone');
}
diff --git a/src/relay.js b/src/relay.js
index 1157a99f..e1a9e8e1 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -8,7 +8,7 @@ import * as store from './board.js';
import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';
import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';
import { relayMoveActor } from './relay-sender.js';
-import { ENGINE_VERSION } from './machine.js';
+import { 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';
@@ -621,7 +621,7 @@ async function replayRelayRecord(board, key, state, record) {
requireSupportedEngine(move);
if (record.kind === 'request') return receivePersonRequest(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender });
return applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind,
- digest: createHash('sha256').update(record.sealed).digest('hex') });
+ digest: createHash('sha256').update(record.sealed).digest('hex'), registration: record.registration });
} catch (error) {
if (!(error instanceof Refused) || !['RELAY_MOVE', 'RELAY_RESPONSE', 'SEAL_FORMAT', 'SEAL_AUTH_FAILED'].includes(error.code)) throw error;
return refuseRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind,
@@ -800,26 +800,49 @@ async function sendPending(root, file, state, io) {
let renewedAgentToken = false;
for (let tries = 0; state.pending && tries < 100; tries += 1) {
const pending = state.pending;
+ const actor = credentialActor(pending.move);
try {
- const transport = await actorTransport(root, file, state, credentialActor(pending.move), io);
- const reply = await request(transport, '/api/v1/boards/' + state.board + '/moves', { method: 'POST', body: { sequence: pending.sequence, sealed: pending.sealed } }, io);
+ const transport = await actorTransport(root, file, state, actor, io);
+ const reply = await request(transport, '/api/v1/boards/' + state.board + '/moves', { method: 'POST',
+ body: { sequence: pending.sequence, sealed: pending.sealed, ...(pending.registration ? { registration: pending.registration } : {}) } }, io);
if (reply.event?.event_id !== pending.sequence || reply.event.sealed !== pending.sealed) throw new Refused('RELAY_RESPONSE', 'the relay acknowledgement differs from this executable send; fetch the configured relay');
+ if (pending.registration) {
+ const enrollment = reply.enrollment;
+ if (!enrollment || enrollment.board !== state.board || enrollment.agent !== pending.registration.target || typeof enrollment.id !== 'string') {
+ throw new Refused('RELAY_RESPONSE', 'the relay registered the seat without its issuance; repeat this command to recover its token');
+ }
+ // A retried registration returns the same issuance without a token; its creator reissues it on first use.
+ if (enrollment.token !== undefined) cacheSeatToken(file, state, pending.registration.target, enrollment);
+ }
} catch (error) {
- const actor = credentialActor(pending.move);
if (error.code === 'AUTH_REQUIRED' && !renewedAgentToken && actor !== 'machine' && actor !== 'person'
- && process.env.PULLBOARD_RELAY_TOKEN === undefined && state.token?.startsWith('pm_') && state.agentTokens?.[actor]?.token) {
- // A revoked/expired PA cache can be replaced once by this board's existing PM credential.
- delete state.agentTokens[actor];
+ && process.env.PULLBOARD_RELAY_TOKEN === undefined && state.agentTokens?.[actor]?.token) {
+ // An expired cache renews only through the seat's creator; a live one the relay refused was revoked.
+ if (state.agentTokens[actor].expires > Date.now()) {
+ state.agentTokens[actor].revoked = true;
+ saveLink(file, state);
+ 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`);
+ }
+ delete state.agentTokens[actor].token;
saveLink(file, state);
renewedAgentToken = true;
- await actorTransport(root, file, state, actor, io);
+ continue;
+ }
+ if (error.code === 'SEAT_TAKEN' && pending.registration) {
+ // The relay already gave this name a token (a machine first mint): take the next free name.
+ nameNextSeat(root, pending.move, Number(pending.move.args[0].id.slice(pending.move.args[0].lane.length + 1)) + 1);
+ pending.sealed = await sealedRecord(readBoardKey(state.board), pending.move, state, 'move', pending.sequence);
+ pending.registration = seatReceipt(pending.move, pending.sequence, pending.sealed);
+ saveLink(file, state);
continue;
}
if (!['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) throw error;
await catchUp(root, file, state, io);
if (state.pending) {
state.pending.sequence = state.sequence + 1;
+ if (state.pending.registration) nameNextSeat(root, state.pending.move, 0);
state.pending.sealed = await sealedRecord(readBoardKey(state.board), state.pending.move, state, 'move', state.pending.sequence);
+ state.pending.registration = seatReceipt(state.pending.move, state.pending.sequence, state.pending.sealed);
saveLink(file, state);
}
continue;
@@ -832,6 +855,10 @@ async function sendPending(root, file, state, io) {
/** Choose credentials only; main's relay sender policy remains the sole replay authorization. */
function credentialActor(move) {
const args = move.args;
+ if (move.operation === 'register' && move.engine >= VERIFIER_STANDING_ENGINE) {
+ const creator = args?.[0]?.createdBy;
+ return typeof creator === 'string' && creator !== 'machine' ? creator : 'machine';
+ }
if (move.personRequest || ['register', 'ensureCoordinator'].includes(move.operation)) return 'machine';
if (['recordRowDecisions', 'recordLandingWaiver'].includes(move.operation)
|| move.operation === 'answerDecision' && args[1]?.asPerson
@@ -839,7 +866,95 @@ function credentialActor(move) {
return relayMoveActor(move);
}
-/** Select a scoped credential; sendPending alone may renew a failed cached token once. */
+/**
+ * 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.
+ */
+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. */
+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. */
+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. */
+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. */
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');
@@ -864,20 +979,34 @@ async function actorTransport(root, file, state, actor, 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 };
}
- state.agentTokens ??= {};
- if (!state.agentTokens[actor]) {
- if (!localRecords(root, (board) => store.listAgents(board).some((agent) => agent.agent_id === actor))) {
- throw new Refused('RELAY_ACTOR', 'register this agent in the ordered board before obtaining its scoped token');
- }
- const issued = await request(state, '/auth/tokens', { method: 'POST', body: { board: state.board, agent: actor } }, io);
- 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; ask the person to retry enrollment');
- }
- state.agentTokens[actor] = { id: issued.id, token: issued.token, expires: issued.expires };
- saveLink(file, state);
+ 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.
+ */
+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; }
}
- return { ...state, token: state.agentTokens[actor].token, agent: actor };
+ 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' });
+}
+
+/** Set up this machine's coordinator token inside a paired join's own person sign-in (#579). */
+export async function relayPersonCoordinator(root, session, io) {
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = loadLink(file);
+ if (state && /^ps_[A-Za-z0-9_-]{43}$/u.test(session ?? '')) await ensurePersonCoordinator(file, state, session, io);
+ });
}
/** Compare caller intent without executing frozen callbacks or allocating another operation id. */
@@ -955,16 +1084,19 @@ export async function relayOperation(root, operation, args, io, command, applyLo
}
let move = recoveredMove(root, state, operation, args, command);
if (!move) {
- move = localRecords(root, (board) => prepareEngineMove(board, operation, args, io.personRequestMoveId ? { id: io.personRequestMoveId } : {}));
+ const sent = withSeatName(root, operation, args);
+ move = localRecords(root, (board) => prepareEngineMove(board, operation, sent, io.personRequestMoveId ? { id: io.personRequestMoveId } : {}));
if (io.personRequest) move.personRequest = structuredClone(io.personRequest);
const problem = move.personRequest && localRecords(root, board => requestMoveProblem(board, move, { checkExecutorLease: false }));
if (problem) throw problem;
move.actor = relayMoveActor(move) ?? credentialActor(move);
await actorTransport(root, file, state, credentialActor(move), io);
const sequence = state.sequence + 1;
+ const sealed = await sealedRecord(readBoardKey(state.board), move, state, 'move', sequence);
+ const registration = seatReceipt(move, sequence, sealed);
state.pending = { move, intent: operationIntent(operation, args),
...(command ? { command, commandIntent: operationIntent('cli:' + command.cliOperation, command) } : {}), sequence,
- sealed: await sealedRecord(readBoardKey(state.board), move, state, 'move', sequence) };
+ sealed, ...(registration ? { registration } : {}) };
saveLink(file, state);
try { await sendPending(root, file, state, io); }
catch (error) {
@@ -1063,7 +1195,15 @@ export async function relayTokens(root, io) {
!Number.isSafeInteger(row.expires) || (row.created !== null && !Number.isSafeInteger(row.created)) ||
typeof row.revoked !== 'boolean')) throw new Refused('RELAY_RESPONSE', 'the relay token inventory is invalid; retry its configured address');
const tokens = listed.tokens.map(({ id, board, agent, created, expires, revoked }) => ({ id, board, agent, created, expires, revoked }));
- return { ...tokenContext(state), tokens };
+ const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
+ const events = listed.coordinatorEvents ?? [];
+ if (!Array.isArray(events) || events.some((row) => !row || !['bootstrap', 'reissue', 'reset'].includes(row.reason) || !uuid.test(row.id ?? '') ||
+ !uuid.test(row.session ?? '') || !uuid.test(row.issued ?? '') || !Number.isSafeInteger(row.at) ||
+ !Array.isArray(row.revoked) || row.revoked.some((id) => !uuid.test(id ?? '')))) {
+ throw new Refused('RELAY_RESPONSE', 'the relay coordinator audit is invalid; retry its configured address');
+ }
+ const coordinatorEvents = events.map(({ id, reason, session, revoked, issued, at }) => ({ id, reason, session, revoked, issued, at }));
+ return { ...tokenContext(state), tokens, coordinatorEvents };
});
}
@@ -1359,6 +1499,8 @@ export async function relayOn(root, address, io, { session, credential, quiet =
state.machine = machine;
delete state.personReauth;
saveLink(file, state);
+ // The person's own sign-in sets up the coordinator's token, so no agent can mint it (#579).
+ if (/^ps_[A-Za-z0-9_-]{43}$/u.test(signed.token ?? '')) await ensurePersonCoordinator(file, state, signed.token, io);
let result;
try {
let ready = true;
diff --git a/test/agent-model-engine.test.js b/test/agent-model-engine.test.js
index e85e2e8d..3c1e9e62 100644
--- a/test/agent-model-engine.test.js
+++ b/test/agent-model-engine.test.js
@@ -10,9 +10,9 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-test('model declarations and event snapshots retain engines 1 through 11 semantics [O8,O3,H16]', (t) => {
- assert.equal(ENGINE_VERSION, 12, 'engine 12 preserves the released engine-8 through engine-11 model behavior');
- for (const version of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ENGINE_VERSION]) {
+test('model declarations and event snapshots retain engines 1 through 12 semantics [O8,O3,H16]', (t) => {
+ assert.equal(ENGINE_VERSION, 13, 'engine 13 preserves the released engine-8 through engine-12 model behavior');
+ for (const version of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ENGINE_VERSION]) {
const board = store.openBoard(':memory:');
t.after(() => store.closeBoard(board));
const registration = prepareEngineMove(board, 'register', [{ lane: 'web', path: '/web', model: 'First Model' }]);
diff --git a/test/machine.test.js b/test/machine.test.js
index 985d8fc1..7928772a 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -27,6 +27,7 @@ const NOT_MOVES = {
ALREADY_JOINED: 'registering who is asking, before any move',
BAD_ROUTE: 'registering who is asking, before any move',
ONE_COORDINATOR: 'registering who is asking, before any move',
+ BAD_SEAT_ID: 'registering who is asking, before any move; only a creator naming a new worktree seat raises it',
MACHINE_HOME_NOT_WRITABLE: 'machine-wide storage must be writable before a command runs',
BAD_MACHINE_SETTINGS: 'machine-wide settings checked before a command runs',
BAD_GATE_SLOTS: 'machine-wide gate capacity checked before a command runs',
diff --git a/test/pending-refreeze.test.js b/test/pending-refreeze.test.js
index 15ad01aa..fc90d13d 100644
--- a/test/pending-refreeze.test.js
+++ b/test/pending-refreeze.test.js
@@ -243,16 +243,16 @@ async function checkDependencyLegacyClients(cleanup, directory, snapshot, target
const oldFeature = legacyEngine.applyRelayMove(old, engine10Move, engine10Receipt);
const currentFeature = applyRelayMove(current, engine10Move, engine10Receipt);
assert.equal(oldFeature.error, undefined, JSON.stringify(oldFeature));
- assert.deepEqual(currentFeature, oldFeature, 'engine 12 reproduces engine 10 dependency additions and clears');
+ assert.deepEqual(currentFeature, oldFeature, 'engine 13 reproduces engine 10 dependency additions and clears');
assert.deepEqual(store.getItem(current, target), legacyStore.getItem(old, target));
- assert.deepEqual(store.events(current), legacyStore.events(old), 'engine 10 and engine 12 replay identical events');
+ assert.deepEqual(store.events(current), legacyStore.events(old), 'engine 10 and engine 13 replay identical events');
assert.equal(appliedSequence(current), legacyEngine.appliedSequence(old));
assert.deepEqual(engineReceipt(current, engine10Move.id), legacyEngine.engineReceipt(old, engine10Move.id),
- 'engine 10 and engine 12 retain the same dependency-move receipts');
+ 'engine 10 and engine 13 retain the same dependency-move receipts');
const oldSnapshot = legacyExchange.exportBoard(old);
const currentSnapshot = exportBoard(current);
assert.equal(oldSnapshot.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value, '10');
- assert.equal(currentSnapshot.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value, '12');
+ assert.equal(currentSnapshot.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value, '13');
assert.deepEqual(withoutEngineMarker(currentSnapshot), withoutEngineMarker(oldSnapshot),
'the sole snapshot difference is the intentionally newer writer-version marker');
}
@@ -261,7 +261,7 @@ async function checkDependencyLegacyClients(cleanup, directory, snapshot, target
}
test('dependency edits replay the same on every engine [B3,V2,H16]', async (t) => {
- assert.equal(ENGINE_VERSION, 12);
+ assert.equal(ENGINE_VERSION, 13);
const directory = mkdtempSync(join(tmpdir(), 'pullboard-dependency-engines-'));
const cleanup = [];
t.after(() => {
diff --git a/test/relay-agent.test.js b/test/relay-agent.test.js
index 5fb8dedf..9151bd40 100644
--- a/test/relay-agent.test.js
+++ b/test/relay-agent.test.js
@@ -200,10 +200,6 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act
submitStoredItem(seed, row.item_id, { agentId: builder, commit: submittedHead, tree: submittedTree });
}
} finally { closeBoard(seed); }
- const firstRoot = join(dirname(box.root), 'agent-one');
- const secondRoot = join(dirname(box.root), 'agent-two');
- git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-one', firstRoot, 'HEAD']);
- git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-two', secondRoot, 'HEAD']);
const personEnv = { ...box.env };
for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete personEnv[key];
@@ -228,30 +224,32 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act
'the native link holds only a machine credential');
assert.equal(Object.hasOwn(JSON.parse(readFileSync(machineFile, 'utf8')), 'session'), false,
'the phone session is not persisted in the machine state');
- const firstStart = box.calls.length;
- const firstJoin = await runCli(firstRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
- assert.equal(firstJoin.code, 0, firstJoin.failure ?? 'the first worktree joins through the real linked CLI');
- const firstAgent = firstJoin.document.agent;
- const firstCalls = box.calls.slice(firstStart);
- const firstRegistration = firstCalls.findIndex((call) => call.method === 'POST' && call.path.endsWith('/moves'));
- const firstMint = firstCalls.findIndex((call) => call.method === 'POST' && call.path === '/auth/tokens');
- assert.ok(firstRegistration >= 0 && firstMint > firstRegistration, 'the first token is minted after ordered registration');
-
- const secondStart = box.calls.length;
- const secondJoin = await runCli(secondRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
- assert.equal(secondJoin.code, 0, secondJoin.failure ?? 'the second worktree joins through the real linked CLI');
- const secondAgent = secondJoin.document.agent;
- const secondCalls = box.calls.slice(secondStart);
- const secondRegistration = secondCalls.findIndex((call) => call.method === 'POST' && call.path.endsWith('/moves'));
- const secondMint = secondCalls.findIndex((call) => call.method === 'POST' && call.path === '/auth/tokens');
- assert.ok(secondRegistration >= 0 && secondMint > secondRegistration, 'the second token is minted after ordered registration');
+ // Verifiers on a linked board are seats the coordinator made (#579); each gets its first token
+ // in the coordinator's own registration request, with no separate mint and no phone tap.
+ /** Make one verifier seat from the coordinator checkout through the real linked CLI. */
+ const coordinatorSeat = async (label) => {
+ const start = box.calls.length;
+ const made = await runCli(box.root, box.env, cli, ['worktree', box.lane, '--family', 'codex-fixture']);
+ assert.equal(made.code, 0, made.failure ?? `the coordinator makes the ${label} worktree through the real linked CLI`);
+ const calls = box.calls.slice(start);
+ assert.ok(calls.some((call) => call.method === 'POST' && call.path.endsWith('/moves')), `the ${label} seat is registered in order`);
+ assert.equal(calls.some((call) => call.method === 'POST' && call.path === '/auth/tokens'), false, `the ${label} seat needs no separate mint`);
+ assert.equal(calls.some((call) => call.path.endsWith('/authorize')), false, `the ${label} seat needs no phone tap`);
+ return made.document;
+ };
+ const firstSeat = await coordinatorSeat('first');
+ const secondSeat = await coordinatorSeat('second');
+ const firstAgent = firstSeat.agent;
+ const secondAgent = secondSeat.agent;
+ const firstRoot = firstSeat.path;
+ const secondRoot = secondSeat.path;
assert.notEqual(firstAgent, secondAgent);
const firstToken = scopedToken(box.linkFile, firstAgent);
const secondToken = scopedToken(box.linkFile, secondAgent);
const list = await box.cli('relay', 'tokens');
assert.equal(list.code, 0, list.failure ?? list.stderr);
- assert.deepEqual(list.document.tokens.map((row) => row.agent).sort(), [firstAgent, secondAgent].sort());
+ assert.deepEqual(list.document.tokens.map((row) => row.agent).sort(), ['coordinator', firstAgent, secondAgent].sort());
const personState = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const boardKey = readFileSync(box.keyFile, 'utf8').trim();
assertMetadataOnly(list.document, [firstToken, secondToken, personState.token, boardKey], 'CLI inventory exposes only scoped token metadata');
@@ -273,7 +271,7 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act
const apiListResponse = await fetchFresh(tokenUrl, { headers: apiHeaders });
assert.equal(apiListResponse.status, 200, 'local API reads the real relay token inventory');
const apiList = await apiListResponse.json();
- assert.deepEqual(apiList.tokens.map((row) => row.agent).sort(), [firstAgent, secondAgent].sort());
+ assert.deepEqual(apiList.tokens.map((row) => row.agent).sort(), ['coordinator', firstAgent, secondAgent].sort());
assertMetadataOnly(apiList, [firstToken, secondToken, personState.token, boardKey], 'local API exposes only token metadata');
const realGit = realpathSync(join(box.env.PATH, 'git'));
@@ -335,15 +333,15 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act
const cachedMintCount = box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length;
const cachedMoveCount = box.calls.filter((call) => call.method === 'POST' && call.path.endsWith('/moves')).length;
const beforeCachedRenewal = nativeEvents(boardFile);
- const cachedRenewal = await runCli(firstRoot, box.env, cli, ['shout', 'all', 'renew the revoked agent cache once']);
- assert.equal(cachedRenewal.code, 0, cachedRenewal.failure ?? 'the valid machine credential replaces one revoked cached agent token');
- assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, cachedMintCount + 1,
- 'one revoked cache causes exactly one replacement scoped token to be minted');
- assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path.endsWith('/moves')).length, cachedMoveCount + 2,
- 'the refused ordered send is retried exactly once with the replacement credential');
+ const cachedRenewal = await runCli(firstRoot, box.env, cli, ['shout', 'all', 'a revoked agent cache stays revoked']);
+ assert.equal(cachedRenewal.code, 1, 'the machine credential never replaces a revoked agent token (#579)');
+ assert.equal(cachedRenewal.document.error.code, 'TOKEN_REVOKED');
+ assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, cachedMintCount,
+ 'a revoked cache mints no replacement token');
+ assert.ok(box.calls.filter((call) => call.method === 'POST' && call.path.endsWith('/moves')).length <= cachedMoveCount + 1,
+ 'the refused ordered send is not retried with another credential');
const afterCachedRenewal = nativeEvents(boardFile);
- assert.equal(afterCachedRenewal.length, beforeCachedRenewal.length + 1,
- 'the authenticated retry writes exactly one native board event');
+ assert.equal(afterCachedRenewal.length, beforeCachedRenewal.length, 'the refused send writes no native board event');
const linkAfterRevoke = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const machineRevoked = await fetch(box.origin + '/auth/tokens/revoke', {
@@ -419,18 +417,17 @@ test('a token mint failure after registration preserves the agent for one clean
await box.link();
box.failTokenMints(1);
+ // A manual join is the one path with a separate first mint after registration: the machine
+ // credential's build-only mint (#579). A coordinator-made seat gets its token inside registration.
+ const agentRoot = join(dirname(box.root), `${basename(box.root)}-manual-join`);
+ git(box.root, box.env, ['worktree', 'add', '-q', '-b', `${box.lane}/manual`, agentRoot, 'HEAD']);
const firstStart = box.calls.length;
- const failedCreate = await box.cli('worktree', box.lane, '--family', 'codex-fixture');
- assert.equal(failedCreate.code, 1, 'the injected token service failure is reported after the real worktree registration');
+ const failedCreate = await runCli(agentRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
+ assert.equal(failedCreate.code, 1, 'the injected token service failure is reported after the real registration');
const firstCalls = box.calls.slice(firstStart);
assert.equal(firstCalls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, 1);
- const agentRoot = join(dirname(box.root), `${basename(box.root)}-${box.lane}-1`);
const agent = registeredAgent(boardFile, agentRoot);
assert.ok(agent, 'successful ordered registration remains canonical after token mint failure');
- assert.equal(existsSync(agentRoot), true, 'the registered worktree is retained for retry');
- const worktrees = gitText(box.root, box.env, ['worktree', 'list', '--porcelain']);
- assert.ok(worktrees.includes(agentRoot), 'Git still records the retained worktree');
- assert.match(worktrees, new RegExp(`branch refs/heads/${box.lane}/1`), 'the registered branch is retained too');
const joinRows = nativeEvents(boardFile).filter((row) => row.event_by === agent && row.event_kind === 'join');
assert.equal(joinRows.length, 1, 'the failed mint does not undo or duplicate ordered registration');
@@ -442,11 +439,11 @@ test('a token mint failure after registration preserves the agent for one clean
assert.equal(nativeEvents(boardFile).filter((row) => row.event_by === agent && row.event_kind === 'join').length, 1);
const linkState = JSON.parse(readFileSync(box.linkFile, 'utf8'));
- assert.deepEqual(Object.keys(linkState.agentTokens), [agent], 'the private link cache holds one usable token for the registered agent');
+ assert.deepEqual(Object.keys(linkState.agentTokens).sort(), ['coordinator', agent].sort(), 'the private link cache holds one usable token for the registered agent beside the coordinator');
const token = scopedToken(box.linkFile, agent);
const listed = await box.cli('relay', 'tokens');
assert.equal(listed.code, 0, listed.failure ?? listed.stderr);
- assert.deepEqual(listed.document.tokens.map((row) => row.agent), [agent]);
+ assert.deepEqual(listed.document.tokens.map((row) => row.agent).sort(), ['coordinator', agent].sort());
assertMetadataOnly(listed.document, [token, linkState.token], 'retry inventory exposes metadata only');
const usable = await runCli(agentRoot, { ...box.env, PULLBOARD_RELAY_TOKEN: token }, cli,
['claim', String(item.document.item.item_id)]);
diff --git a/test/relay-auth-expired.test.js b/test/relay-auth-expired.test.js
index 3857cf04..1b6f9216 100644
--- a/test/relay-auth-expired.test.js
+++ b/test/relay-auth-expired.test.js
@@ -49,50 +49,38 @@ test('reads and status answer when the relay sign-in expired [H16,H5]', async t
assert.equal(existsSync(view.document.path), true, 'the local view export is available after relay auth refusal');
});
-test('a move renews its agent token from the machine credential [H16,H5]', async t => {
+test('a revoked agent token is never reminted from the machine credential; the person reissues the coordinator [H16,H5,H2]', async t => {
const box = await relayClientFixture(t);
await box.link();
const seed = await box.cli('add', box.lane, 'seed agent credential');
- assert.equal(seed.code, 0, seed.failure ?? 'the initial move registers the coordinator token');
+ assert.equal(seed.code, 0, seed.failure ?? 'the coordinator token from relay on sends the first move');
const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const agent = state.agentTokens.coordinator;
assert.ok(agent?.id, 'the board link caches a scoped coordinator credential');
await revokeCredential(box, agent.id);
+ const before = (await box.cli('export')).document.tables;
const mintsBefore = box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length;
- const sendsBefore = box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length;
const acksBefore = box.moveAcks.length;
- const moved = await box.cli('add', box.lane, 'move after agent-token renewal');
- assert.equal(moved.code, 0, moved.failure ?? 'the machine credential renews the revoked scoped token');
- assert.equal(box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length, mintsBefore + 1,
- 'one machine-authenticated request mints one replacement agent token');
- assert.equal(box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length, sendsBefore + 2,
- 'the refused move is retried exactly once with the replacement token');
- assert.equal(box.moveAcks.length, acksBefore + 1, 'the ordered relay acknowledges exactly one move');
- const rows = (await box.cli('export')).document.tables.item;
- assert.equal(rows.filter(row => row.item_title === 'move after agent-token renewal').length, 1,
- 'the retried ordered move has one local effect');
- const beforeSecondRefusal = (await box.cli('export')).document.tables;
- const cached = JSON.parse(readFileSync(box.linkFile, 'utf8')).agentTokens.coordinator;
- await revokeCredential(box, cached.id);
- let refusedSends = 0;
- /** Revoke each actual scoped credential just before its real HTTP send. */
- async function revokeAtSend() {
- const current = JSON.parse(readFileSync(box.linkFile, 'utf8')).agentTokens.coordinator;
- await revokeCredential(box, current.id);
- refusedSends += 1;
- if (refusedSends === 1) box.beforeNextMove(revokeAtSend);
- }
- box.beforeNextMove(revokeAtSend);
- const mintsBeforeRefusal = box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length;
- const failed = await box.cli('add', box.lane, 'a second refusal must not retry forever');
- assert.equal(failed.code, 1, 'a replacement token refused again stops this command');
- assert.equal(failed.document.error.code, 'AUTH_REQUIRED');
- assert.equal(refusedSends, 2, 'there is one original send and one retry');
- assert.equal(box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length, mintsBeforeRefusal + 1,
- 'a second refusal never causes a second mint');
- assert.deepEqual((await box.cli('export')).document.tables, beforeSecondRefusal,
- 'neither refused send can change the local ordered board');
+ const refused = await box.cli('add', box.lane, 'move after agent-token revocation');
+ assert.equal(refused.code, 1, 'the machine credential never replaces a revoked seat token (#579)');
+ assert.equal(refused.document.error.code, 'TOKEN_REVOKED');
+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length, mintsBefore,
+ 'no replacement token is minted');
+ assert.equal(box.moveAcks.length, acksBefore, 'the relay acknowledges no move');
+ assert.deepEqual((await box.cli('export')).document.tables, before, 'the refused move changes no local board state');
+
+ // The person's own relay on reissues the coordinator token and records it.
+ const relink = await box.cli('relay', 'on', '--url', box.origin);
+ assert.equal(relink.code, 0, relink.failure ?? 'relay on reissues the coordinator token from the person sign-in');
+ const reissued = JSON.parse(readFileSync(box.linkFile, 'utf8')).agentTokens.coordinator;
+ assert.notEqual(reissued.id, agent.id, 'a new coordinator token replaces the revoked one');
+ const moved = await box.cli('add', box.lane, 'move after person reissue');
+ assert.equal(moved.code, 0, moved.failure ?? 'the reissued coordinator token sends moves again');
+ const tokens = await box.cli('relay', 'tokens');
+ assert.equal(tokens.code, 0, tokens.failure ?? 'the token inventory lists the coordinator audit');
+ assert.deepEqual(tokens.document.coordinatorEvents.map(row => row.reason), ['bootstrap', 'reissue']);
+ assert.equal(tokens.document.coordinatorEvents[1].issued, reissued.id);
});
test('a move without a machine credential refuses with the fix [H16,H5]', async t => {
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index 4ee0de8a..cfcb048e 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -699,7 +699,9 @@ async function threeReplicaFixture(t, timing) {
try {
store.register(seedBoard, { lane: 'coordinator', path: seed });
for (let index = 0; index < worktrees.length; index += 1) {
- store.register(seedBoard, { lane: 'web', path: worktrees[index], route: 'light' });
+ const seat = store.register(seedBoard, { lane: 'web', path: worktrees[index], route: 'light', createdBy: 'coordinator' });
+ // The seed stands in for seats the coordinator enrolled through the relay, so they may verify (#579).
+ seedBoard.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_enrolled:${seat}`, 'coordinator');
}
for (let id = 1; id <= 20; id += 1) {
store.addItem(seedBoard, {
@@ -743,8 +745,14 @@ async function threeReplicaFixture(t, timing) {
const machineCredential = await timing.wait(`issue the machine credential for clone ${index + 1}`, () => auth.issueMachine(person.token, { board: boardId, machine }));
cloneCredentials.push(machineCredential);
assert.match(machineCredential.token, /^pm_[A-Za-z0-9_-]{43}$/u);
+ // Each clone's person sign-in sets up its own coordinator token, as relay on does (#579).
+ const coordinator = await auth.issueCoordinator(person.token, { board: boardId });
+ // The seeded web seat stands in for one this coordinator enrolled: the relay records it the same way.
+ const seat = await auth.enrollSeat(coordinator.token, boardId, { target: `web-${index + 1}`, creator: 'coordinator', sequence: index + 1, digest: String(index).repeat(64) });
const state = {
version: 1, mode: 'ordered', board: boardId, url: relay.origin, repository: 'fixture/repository',
+ agentTokens: { coordinator: { id: coordinator.id, token: coordinator.token, expires: coordinator.expires, created: coordinator.created },
+ [`web-${index + 1}`]: { id: seat.id, token: seat.token, expires: seat.expires, created: seat.created } },
token: machineCredential.token, tokenId: machineCredential.id, account: person.user.id, machine,
keyStorage: 'file', sequence: 0,
cursor: snapshot.tables.event.at(-1)?.event_id ?? 0,
@@ -860,7 +868,7 @@ async function competingReplicaClaims(fixture, timing) {
const earlierSealed = Buffer.from(await timing.wait('seal the earlier coordinator move', () => seal(key, new TextEncoder().encode(JSON.stringify(earlier)), {
boardId, kind: 'move', sequence: next,
}))).toString('base64url');
- const coordinatorCredential = await timing.wait('issue the coordinator fixture credential', () => auth.issueToken(person.token, { board: boardId, agent: 'coordinator' }));
+ const coordinatorCredential = await timing.wait('issue the coordinator fixture credential', () => auth.issueCoordinator(person.token, { board: boardId }));
const headers = { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: 'Bearer ' + coordinatorCredential.token, 'content-type': 'application/json' };
assert.equal((await timing.wait('append the earlier coordinator move', () => fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {
method: 'POST', headers, body: JSON.stringify({ sequence: next, sealed: earlierSealed }),
@@ -1134,7 +1142,7 @@ async function finalReplicaOrder(fixture, timing) {
next = appliedSequence(updated) + 1;
future = { ...prepareEngineMove(updated, 'addItem', [{ by: 'coordinator', lane: 'web', title: 'Future engine item' }]), engine: ENGINE_VERSION + 1 };
} finally { store.closeBoard(updated); }
- const coordinatorCredential = await timing.wait('issue the coordinator fixture credential for the final order check', () => auth.issueToken(person.token, { board: boardId, agent: 'coordinator' }));
+ const coordinatorCredential = await timing.wait('issue the coordinator fixture credential for the final order check', () => auth.issueCoordinator(person.token, { board: boardId }));
const headers = { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: 'Bearer ' + coordinatorCredential.token, 'content-type': 'application/json' };
const futureSealed = Buffer.from(await timing.wait('seal the future-engine move', () => seal(key, new TextEncoder().encode(JSON.stringify(future)), {
boardId, kind: 'move', sequence: next,
diff --git a/test/relay-deploy.test.js b/test/relay-deploy.test.js
index 5179d324..c73ad09a 100644
--- a/test/relay-deploy.test.js
+++ b/test/relay-deploy.test.js
@@ -287,7 +287,7 @@ test('[H5,H18] the Railway checklist matches the container and relay runtime set
test('[H5,H18] the Railway smoke links, reads one unsealed move and unlinks locally', async (t) => {
const box = await relayClientFixture(t);
await box.link();
- assert.equal(await box.requireEngineThree(), 6, 'a machine-linked board requires the machine-aware replay engine');
+ assert.equal(await box.requireEngineThree(), 13, 'a machine-linked board requires the engine-13 seat-provenance replay engine');
const previous = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const legacy = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {
headers: { authorization: `Bearer ${previous.token}`, 'x-pullboard-engine': '2' },
diff --git a/test/relay-machine-auth.test.js b/test/relay-machine-auth.test.js
index 96b6aaa0..b7715248 100644
--- a/test/relay-machine-auth.test.js
+++ b/test/relay-machine-auth.test.js
@@ -57,7 +57,7 @@ test('machine credentials mint and list same-board agents but cannot link, revok
assert.equal(tokens.some(value => Object.hasOwn(value, 'token') || Object.hasOwn(value, 'hash')), false);
await assert.rejects(auth.listTokens(machine.token, beta), { code: 'TOKEN_BOARD' });
await assert.rejects(auth.issueToken(machine.token, { board: beta, agent: 'cross-board' }), { code: 'TOKEN_BOARD' });
- assert.equal(auth.minimumEngineVersion(alpha), 6);
+ assert.equal(auth.minimumEngineVersion(alpha), 13, 'machine and agent credentials require engine 13 (#579)');
await assert.rejects(auth.listTokens(agent.token, alpha), { code: 'HUMAN_REQUIRED' });
await assert.rejects(auth.revoke(machine.token, agent.id), { code: 'TOKEN_NOT_OWNED' });
diff --git a/test/relay-mint.test.js b/test/relay-mint.test.js
new file mode 100644
index 00000000..c327f298
--- /dev/null
+++ b/test/relay-mint.test.js
@@ -0,0 +1,295 @@
+/** An agent in its worktree cannot mint a relay token or borrow another seat's verifier standing [H2,V1,E3,E5,P6] (#579). */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { DatabaseSync } from 'node:sqlite';
+import { chmodSync, copyFileSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { appliedSequence, applyRelayMove } from '../src/engine.js';
+import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from '../src/machine.js';
+import { createRelayJournal } from '../relay/journal.js';
+import { runFixtureChild } from './fixture-child.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+const TOKEN = /^pa_[A-Za-z0-9_-]{43}$/u;
+const POLICY = { version: 1, commit: 'a'.repeat(40), verify: { policy: 'any', family: 'off' } };
+
+/** Run fixture Git with hooks off: this test is about relay credentials, not the installed hooks. */
+function git(root, env, args) {
+ const result = runFixtureChild('git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.failure ?? `fixture git ${args[0]} succeeds`);
+ return result.stdout.trim();
+}
+
+/** Send one credentialed request to the loopback relay; bearer values never enter a message. */
+async function call(origin, token, method, path, body) {
+ const response = await fetch(origin + path, {
+ method, headers: { authorization: `Bearer ${token}`, 'x-pullboard-engine': String(ENGINE_VERSION),
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, document: await response.json() };
+}
+
+/** Read the shared link file every worktree of this repository can read. */
+function link(box) { return JSON.parse(readFileSync(box.linkFile, 'utf8')); }
+
+/** Every file under a directory, for a scan that no person session sits on disk (#299). */
+function files(directory) {
+ if (!existsSync(directory)) return [];
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(directory, entry.name);
+ return entry.isDirectory() ? files(path) : entry.isFile() ? [path] : [];
+ });
+}
+
+/** Freeze a criterion with a valid verify policy, as the CLI does at claim. */
+function freezer() {
+ const text = JSON.stringify({ criterion: 'an independent seat accepts it', policy: POLICY });
+ return () => ({ text, digest: createHash('sha256').update(text).digest('hex') });
+}
+
+/** Put one item in submitted state on a board, built by `builder`. */
+function submitted(board, builder, lane) {
+ const added = store.addItem(board, { by: 'coordinator', lane, title: 'provenance review', criterion: 'an independent seat accepts it' });
+ const item = { item_id: typeof added === 'number' ? added : added.item_id };
+ store.claim(board, item.item_id, { agentId: builder, lane, leaseMs: 3_600_000, freeze: freezer(), head: 'a'.repeat(40) });
+ store.submit(board, item.item_id, { agentId: builder, commit: 'b'.repeat(40), tree: 'c'.repeat(40) });
+ return store.getItem(board, item.item_id);
+}
+
+test('an agent in its worktree cannot mint a relay token [H2,V1,E3,E5,P6]', async (t) => {
+ const box = await relayClientFixture(t);
+ const lane = box.lane;
+ git(box.root, box.env, ['add', '-A']);
+ git(box.root, box.env, ['commit', '-q', '-m', 'test: private relay mint fixture']);
+ const head = git(box.root, box.env, ['rev-parse', 'HEAD']);
+
+ // A seat the coordinator made before the board was linked: it builds, but it was never enrolled.
+ const prelinked = await box.cli('worktree', lane, '--model', 'Prelinked Seat');
+ assert.equal(prelinked.code, 0, prelinked.failure ?? 'the unlinked coordinator makes a worktree');
+ await box.link();
+ const start = link(box);
+ assert.match(start.agentTokens?.coordinator?.token ?? '', TOKEN, 'relay on sets up the coordinator token from the person sign-in');
+ const session = await call(box.origin, start.agentTokens.coordinator.token, 'GET', `/auth/session?board=${start.board}`);
+ assert.equal(session.document.session.root, true, 'the coordinator token is the person-made root');
+
+ // A manual join: no seat made it, so the machine credential gives it a build-only token, with no person action.
+ const manualRoot = join(dirname(box.root), 'manual-join');
+ git(box.root, box.env, ['worktree', 'add', '-q', '--detach', manualRoot, head]);
+ const before = box.transit.length;
+ const manualJoin = await box.cliAt(manualRoot, 'join', lane, '--model', 'Manual Seat');
+ assert.equal(manualJoin.code, 0, manualJoin.failure ?? 'a manual join enrolls with no person action');
+ const manual = manualJoin.document.agent;
+ const manualTraffic = box.transit.slice(before);
+ const manualMint = manualTraffic.find((entry) => entry.method === 'POST' && entry.path === '/auth/tokens');
+ assert.equal(JSON.parse(manualMint.request.toString('utf8')).agent, manual, 'the machine credential first-mints the manual seat');
+ assert.match(JSON.parse(manualMint.response.toString('utf8')).token ?? '', TOKEN);
+ assert.equal(manualTraffic.some((entry) => /approvals|authorize|\/auth\/device/u.test(entry.path)), false, 'no phone or person step');
+
+ // Fresh seats from their creators: the first token comes back in the creator's own registration request.
+ /** Make one seat from a creator's checkout and return its id, path and registration exchange. */
+ const created = async (cwd, model) => {
+ const from = box.transit.length;
+ const result = cwd === box.root ? await box.cli('worktree', lane, '--model', model) : await box.cliAt(cwd, 'worktree', lane, '--model', model);
+ assert.equal(result.code, 0, result.failure ?? `the creator makes ${model}`);
+ const traffic = box.transit.slice(from);
+ const registration = traffic.findLast((entry) => entry.method === 'POST' && entry.path.endsWith('/moves') && JSON.parse(entry.request.toString('utf8')).registration
+ && JSON.parse(entry.response.toString('utf8')).enrollment);
+ assert.ok(registration, 'the registration move carries its seat receipt');
+ const reply = JSON.parse(registration.response.toString('utf8'));
+ assert.equal(reply.enrollment.agent, result.document.agent, 'the registration reply enrolls the new seat');
+ assert.match(reply.enrollment.token ?? '', TOKEN, 'its creator receives the first token in that same request');
+ assert.equal(reply.event.registration.target, result.document.agent, 'the public event names the target');
+ assert.equal(JSON.stringify(reply.event).includes(reply.enrollment.token), false, 'the token never enters the public event');
+ assert.equal(traffic.some((entry) => entry.method === 'POST' && entry.path === '/auth/tokens'), false, 'no separate first mint');
+ assert.equal(traffic.some((entry) => /approvals|authorize|\/auth\/device/u.test(entry.path)), false, 'enrollment stays zero-tap');
+ return { id: result.document.agent, path: result.document.path, registration };
+ };
+ const builder = await created(box.root, 'Builder Seat');
+ const reviewer = await created(box.root, 'Reviewer Seat');
+ const child = await created(builder.path, 'Child Seat');
+ const grandchild = await created(child.path, 'Grandchild Seat');
+ const prelinkedActs = await box.cliAt(prelinked.document.path, 'shout', 'all', 'a seat from before the link keeps building');
+ assert.equal(prelinkedActs.code, 0, prelinkedActs.failure ?? 'an existing seat keeps working after the link');
+
+ const boardCopy = join(mkdtempSync(join(tmpdir(), 'pullboard-mint-board-')), 'board.sqlite');
+ t.after(() => rmSync(dirname(boardCopy), { recursive: true, force: true }));
+ copyFileSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), boardCopy);
+ const board = store.openBoard(boardCopy);
+ t.after(() => store.closeBoard(board));
+ assert.equal(store.agentCreator(board, manual), 'machine', 'a manual join records that no seat made it');
+ assert.equal(store.agentCreator(board, builder.id), 'coordinator');
+ assert.equal(store.agentCreator(board, reviewer.id), 'coordinator');
+ assert.equal(store.agentCreator(board, child.id), builder.id, 'every registration records the seat that created it');
+ assert.equal(store.agentCreator(board, grandchild.id), child.id);
+ assert.equal(store.seatEnrolled(board, child.id), true);
+ assert.equal(store.seatEnrolled(board, manual), false);
+ assert.equal(store.seatEnrolled(board, prelinked.document.agent), false, 'a seat made before linking was never enrolled');
+
+ await t.test('every credential a worktree can reach is refused against every existing seat', async () => {
+ const state = link(box);
+ const shared = readFileSync(box.linkFile, 'utf8');
+ for (const path of [box.linkFile, ...files(join(box.root, '.git', 'pullboard')), ...files(box.env.PULLBOARD_HOME), ...files(box.env.PULLBOARD_MACHINE_HOME)]) {
+ if (statSync(path).size < 2_000_000) assert.equal(/ps_[A-Za-z0-9_-]{43}/u.test(readFileSync(path, 'latin1')), false, 'no person session is stored where a worktree can read it');
+ }
+ assert.match(state.token, /^pm_[A-Za-z0-9_-]{43}$/u, 'the shared link file holds the machine credential');
+ const seats = Object.keys(state.agentTokens);
+ for (const seat of ['coordinator', manual, prelinked.document.agent, builder.id, reviewer.id, child.id, grandchild.id]) assert.ok(seats.includes(seat), `${seat} has a cached token`);
+ assert.equal(seats.length, store.listAgents(board).length, 'every registered seat holds a token');
+ const credentials = [['machine', state.token], ...seats.map((seat) => [seat, state.agentTokens[seat].token])];
+ const copied = JSON.parse(builder.registration.request.toString('utf8')).registration;
+ let attempts = 0;
+ for (const [holder, credential] of credentials) {
+ for (const target of seats) {
+ if (holder === target) continue; // A seat's own token renewing itself is the one decided exception (7bbf20c0).
+ for (const body of [{ board: state.board, agent: target }, { board: state.board, agent: target, recover: true }, { board: state.board, agent: target, registration: copied }]) {
+ if (body.recover && holder === 'coordinator' && [builder.id, reviewer.id].includes(target)) continue; // Its creator's reissue.
+ if (body.recover && holder === builder.id && target === child.id) continue;
+ if (body.recover && holder === child.id && target === grandchild.id) continue;
+ const attempt = await call(box.origin, credential, 'POST', '/auth/tokens', body);
+ attempts += 1;
+ assert.ok(attempt.status >= 400, `${holder} cannot mint for ${target}`);
+ assert.ok(['TOKEN_EXISTS', 'TOKEN_AGENT', 'REGISTRATION_IN_MOVE'].includes(attempt.document.error?.code), `${holder} is refused by name for ${target}`);
+ }
+ }
+ const root = await call(box.origin, credential, 'POST', '/auth/coordinators', { board: state.board });
+ assert.equal(root.status, 403, `${holder} cannot set up the coordinator credential`);
+ assert.equal(root.document.error?.code, 'HUMAN_REQUIRED');
+ }
+ assert.ok(attempts > 90, 'the sweep covers every reachable credential against every existing seat');
+ assert.equal(readFileSync(box.linkFile, 'utf8'), shared, 'no refused attempt changed the shared link file');
+ });
+
+ await t.test('a seat renews only with its own token, and only its creator reissues a lost one', async () => {
+ const state = link(box);
+ const own = state.agentTokens[grandchild.id].token;
+ const renewed = await call(box.origin, own, 'POST', '/auth/tokens', { board: state.board, agent: grandchild.id });
+ assert.equal(renewed.status, 201, 'the current token renews its own seat');
+ assert.equal((await call(box.origin, own, 'GET', `/auth/session?board=${state.board}`)).status, 401, 'renewal revokes the old token');
+ assert.equal((await call(box.origin, renewed.document.token, 'GET', `/auth/session?board=${state.board}`)).document.session.agent, grandchild.id);
+ const reissued = await call(box.origin, state.agentTokens[child.id].token, 'POST', '/auth/tokens', { board: state.board, agent: grandchild.id, recover: true });
+ assert.equal(reissued.status, 201, 'the creator reissues a lost token');
+ assert.equal((await call(box.origin, renewed.document.token, 'GET', `/auth/session?board=${state.board}`)).status, 401, 'reissue revokes the old one');
+ // Once every token of a seat is revoked or expired, the machine credential still cannot renew it.
+ const person = await box.phoneSession();
+ await box.auth.revoke(person.token, reissued.document.id);
+ const machineRenewal = await call(box.origin, state.token, 'POST', '/auth/tokens', { board: state.board, agent: grandchild.id });
+ assert.equal(machineRenewal.document.error?.code, 'TOKEN_EXISTS', 'the machine credential never renews a seat that held a token');
+ const manualRecover = await call(box.origin, state.agentTokens[manual].token, 'POST', '/auth/tokens', { board: state.board, agent: manual, recover: true });
+ assert.equal(manualRecover.document.error?.code, 'TOKEN_AGENT', 'a machine-origin seat has no creator to reissue it');
+ // Retrying the exact registration returns the same issuance, and no token.
+ const first = JSON.parse(reviewer.registration.response.toString('utf8')).enrollment;
+ const retry = await call(box.origin, state.agentTokens.coordinator.token, 'POST', reviewer.registration.path, JSON.parse(reviewer.registration.request.toString('utf8')));
+ assert.equal(retry.status, 200, 'an exact registration retry is accepted');
+ assert.equal(retry.document.enrollment.id, first.id, 'it returns the same issuance');
+ assert.equal(retry.document.enrollment.expires, first.expires);
+ assert.equal(retry.document.enrollment.token, undefined, 'the relay holds no token to return');
+ });
+
+ await t.test('a machine-origin seat stays build-only and its name cannot be registered', async () => {
+ const state = link(box);
+ const sealed = Buffer.from('opaque fixture move').toString('base64url');
+ const registration = { target: manual, creator: builder.id, sequence: state.sequence + 1, digest: createHash('sha256').update(sealed).digest('hex') };
+ const later = await call(box.origin, state.agentTokens[builder.id].token, 'POST', `/api/v1/boards/${state.board}/moves`, { sequence: registration.sequence, sealed, registration });
+ assert.equal(later.document.error?.code, 'SEAT_TAKEN', 'registering a machine-minted name is refused, not upgraded');
+ // A pre-mint of the next name makes the creator take the one after it, still with no person action.
+ const target = store.nextSeatId(board, lane);
+ const premint = await call(box.origin, state.token, 'POST', '/auth/tokens', { board: state.board, agent: target });
+ assert.equal(premint.status, 201, 'the machine credential first-mints a never-issued name');
+ const skipped = await created(box.root, 'After Premint');
+ assert.notEqual(skipped.id, target, 'the pre-minted name is skipped, not upgraded');
+ const claimed = await box.cliAt(manualRoot, 'shout', 'all', 'manual seat still builds');
+ assert.equal(claimed.code, 0, claimed.failure ?? 'the build-only seat keeps acting under its own token');
+ });
+
+ await t.test('linked verify refuses the builder line and seats without standing, in one line', () => {
+ const item = submitted(board, builder.id, lane);
+ /** The accept arguments a seat sends for this item. */
+ const verdict = (agentId) => [item.item_id, { agentId, decision: 'ACCEPT', reason: 'CRITERION_MET', note: 'checked the proof', head: 'd'.repeat(40), digest: item.item_frozen_digest }];
+ let id = 0;
+ /** Replay one stamped engine-13 relay move from an agent on the linked board copy. */
+ const move = (operation, args, sender) => applyRelayMove(board, { version: 1, engine: ENGINE_VERSION, id: `standing-${++id}`, operation, args }, {
+ sequence: appliedSequence(board) + 1, at: new Date().toISOString(), kind: 'move', sender: { kind: 'agent', userId: '1', policy: VERIFIER_STANDING_ENGINE, ...sender },
+ });
+ for (const seat of [child.id, grandchild.id, manual, prelinked.document.agent]) {
+ const refused = move('verify', verdict(seat), { agent: seat });
+ assert.equal(refused.error?.code, 'VERIFIER_STANDING', `${seat} has no verifier standing on the linked board`);
+ assert.equal(refused.error.message.includes('\n'), false, 'the refusal is one line');
+ assert.match(refused.error.message, /pullboard worktree <lane> --model "<model name>"/u, 'it names the coordinator command');
+ }
+ assert.equal(move('verify', verdict(builder.id), { agent: builder.id }).error?.code, 'SELF_VERIFY');
+ assert.equal(move('verify', verdict('coordinator'), { agent: 'coordinator' }).error?.code, 'VERIFIER_STANDING', 'a coordinator token the person did not set up has no standing');
+ const next = move('reserveNextReview', [{ agentId: child.id, lane, leaseMs: 60_000, policy: 'any' }], { agent: child.id });
+ assert.equal(next.result.item, null, 'next --verify offers the builder\'s child nothing');
+ assert.match(next.result.reasons.join('\n'), /pullboard worktree <lane> --model/u);
+ const forged = move('register', [{ lane, path: '/forged-seat', model: 'Forged', createdBy: builder.id, id: `${lane}-900` }], { agent: builder.id });
+ assert.equal(forged.error?.code, 'RELAY_REGISTRATION', 'a seat registered without its relay receipt is refused');
+ const accepted = move('verify', verdict(reviewer.id), { agent: reviewer.id });
+ assert.equal(accepted.result?.decision, 'ACCEPT', 'a seat the coordinator made outside the builder line verifies');
+ // The literal rule holds for the coordinator too (decision 11096): its seats share its lineage.
+ const own = submitted(board, 'coordinator', 'coordinator');
+ const ownVerdict = move('verify', [own.item_id, { ...verdict(reviewer.id)[1], digest: own.item_frozen_digest }], { agent: reviewer.id });
+ assert.equal(ownVerdict.error?.code, 'VERIFIER_STANDING', 'a coordinator-made seat cannot verify the coordinator\'s own work');
+ assert.match(ownVerdict.error.message, /another machine's registration lineage, or the person/u);
+ });
+
+ await t.test('an engine-11 journal replays as before', (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-mint-engine11-'));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const historical = store.openBoard(':memory:');
+ t.after(() => store.closeBoard(historical));
+ historical.executionEngineVersion = 11;
+ store.register(historical, { lane: 'coordinator', path: '/repo' });
+ const legacyBuilder = store.register(historical, { lane: 'web', path: '/repo-web-1', createdBy: 'machine' });
+ const legacyReviewer = store.register(historical, { lane: 'web', path: '/repo-web-2' });
+ delete historical.executionEngineVersion;
+ assert.equal(store.agentCreator(historical, legacyBuilder), null, 'engine 11 records no provenance');
+ const item = submitted(historical, legacyBuilder, 'web');
+ const recorded = { version: 1, engine: 11, id: 'engine-11-verify', operation: 'verify',
+ args: [item.item_id, { agentId: legacyReviewer, decision: 'ACCEPT', reason: 'CRITERION_MET', note: 'checked', head: 'd'.repeat(40), digest: item.item_frozen_digest }] };
+ const boardId = 'e'.repeat(32);
+ const path = join(directory, boardId + '.journal.sqlite');
+ const db = new DatabaseSync(path);
+ chmodSync(path, 0o600);
+ db.exec(`CREATE TABLE journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ CREATE TABLE journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('move','request')),
+ payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','agent','machine')), sender_user TEXT NOT NULL, sender_agent TEXT);
+ CREATE TABLE journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL, last_activity_at TEXT);
+ CREATE TABLE journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL, received_at TEXT NOT NULL, payload BLOB NOT NULL,
+ sender_kind TEXT NOT NULL, sender_user TEXT NOT NULL, sender_agent TEXT);`);
+ db.prepare('INSERT INTO journal_meta (key,value) VALUES (?,?),(?,?)').run('board', boardId, 'format', '3');
+ db.prepare("INSERT INTO journal_record VALUES (1,'2026-10-08T10:00:00.000Z','move',?,'agent','202',?)").run(Buffer.from(JSON.stringify(recorded)), legacyReviewer);
+ db.prepare("INSERT INTO journal_head VALUES (1,1,'2026-10-08T10:00:00.000Z')").run();
+ db.close();
+ const journal = createRelayJournal({ directory, boardId });
+ const [record] = journal.after();
+ journal.close();
+ assert.deepEqual(record.sender, { kind: 'agent', userId: '202', agent: legacyReviewer }, 'the old record gains no stamp');
+ assert.equal(record.registration, undefined);
+ assert.deepEqual(JSON.parse(record.bytes.toString('utf8')), recorded, 'its move bytes are unchanged');
+ const fresh = store.openBoard(':memory:');
+ t.after(() => store.closeBoard(fresh));
+ const stamped = applyRelayMove(fresh, { ...recorded, engine: 11 }, { sequence: 1, at: record.receivedAt, kind: 'move',
+ sender: { ...record.sender, policy: VERIFIER_STANDING_ENGINE } });
+ assert.equal(stamped.error?.code, 'ENGINE_VERSION', 'a newly stored record cannot claim an old engine');
+ const replayed = applyRelayMove(historical, JSON.parse(record.bytes.toString('utf8')), { sequence: 1, at: record.receivedAt, kind: record.kind, sender: record.sender });
+ assert.equal(replayed.error, undefined, 'the engine-11 verdict replays with its old rules');
+ assert.equal(replayed.result.decision, 'ACCEPT');
+ });
+
+ await t.test('an unlinked board verifies exactly as before', (t) => {
+ const local = store.openBoard(':memory:');
+ t.after(() => store.closeBoard(local));
+ store.register(local, { lane: 'coordinator', path: '/repo' });
+ const localBuilder = store.register(local, { lane: 'web', path: '/repo-web-1', createdBy: 'machine' });
+ const localReviewer = store.register(local, { lane: 'web', path: '/repo-web-2', createdBy: 'machine' });
+ const item = submitted(local, localBuilder, 'web');
+ const result = store.verify(local, item.item_id, { agentId: localReviewer, decision: 'ACCEPT', reason: 'CRITERION_MET', note: 'checked the proof',
+ head: 'd'.repeat(40), digest: item.item_frozen_digest, policy: 'any' });
+ assert.equal(result.decision, 'ACCEPT', 'an existing seat verifies another builder\'s item with no standing check');
+ assert.equal(store.reviewOffer(local, { agentId: localReviewer, lane: 'web', ratio: 0 }), null, 'nothing left to review');
+ });
+});
diff --git a/test/relay-retention.test.js b/test/relay-retention.test.js
index b2601ed0..c8641e07 100644
--- a/test/relay-retention.test.js
+++ b/test/relay-retention.test.js
@@ -60,7 +60,7 @@ async function fixture(t) {
/** Return status/body without ever placing credentials in diagnostic text or URLs. */
async function call(id, { path = '/state', method = 'GET', token = signed.token, body } = {}) {
const response = await fetch('http://127.0.0.1:' + relay.port + '/api/v1/boards' + (id ? '/' + id + path : ''), {
- method, headers: { 'x-pullboard-engine': '3', authorization: 'Bearer ' + token, ...(body ? { 'content-type': 'application/json' } : {}) },
+ method, headers: { 'x-pullboard-engine': '13', authorization: 'Bearer ' + token, ...(body ? { 'content-type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
return { status: response.status, body: await response.json() };
@@ -88,7 +88,7 @@ test('[H18] warnings begin at sixty days on authorized contact; compaction and r
warningTimeout.unref();
t.after(() => { clearTimeout(warningTimeout); controller.abort(); });
const stream = await fetch('http://127.0.0.1:' + box.relay.port + '/api/v1/boards/' + A + '/events?after=0', {
- headers: { 'x-pullboard-engine': '3', authorization: 'Bearer ' + box.signed.token, accept: 'text/event-stream' }, signal: controller.signal,
+ headers: { 'x-pullboard-engine': '13', authorization: 'Bearer ' + box.signed.token, accept: 'text/event-stream' }, signal: controller.signal,
});
const reader = stream.body.getReader();
let delivered = '';
diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.js
index 2dbaa441..02ffe84c 100644
--- a/test/relay-sealed.test.js
+++ b/test/relay-sealed.test.js
@@ -21,7 +21,7 @@ import { main } from '../src/cli.js';
import { exportBoard, restoreRelaySnapshot, semanticBoardDigest } from '../src/exchange.js';
import { appliedSequence, checkpointSequence, engineReceipt, prepareEngineMove, requireSupportedEngine } from '../src/engine.js';
import { seal as sealMove, unseal as openSealed } from '../src/seal.js';
-import { ENGINE_VERSION } from '../src/machine.js';
+import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from '../src/machine.js';
import { relayRecover, syncRelay } from '../src/relay.js';
after(cleanupFixtureChildren);
@@ -532,10 +532,12 @@ test('two real clients enforce the verify policy captured in the item freeze [H1
assert.notEqual(refreshed.item_frozen_digest, legacyDigest, 'explicit refreeze establishes a new digest for the newly captured policy');
store.submit(afterRefreeze, 1, { agentId: builderId, commit, tree, files: [] });
store.register(afterRefreeze, { lane: 'coordinator', path: box.root, family: 'Coordinator Family' });
- store.register(afterRefreeze, { lane, path: join(box.directory, 'verifier-same'), family: 'Builder Family' });
+ store.register(afterRefreeze, { lane, path: join(box.directory, 'verifier-same'), family: 'Builder Family', createdBy: 'coordinator' });
verifierSame = store.agentAt(afterRefreeze, join(box.directory, 'verifier-same')).agent_id;
- store.register(afterRefreeze, { lane, path: join(box.directory, 'verifier-other'), family: 'Reviewer Family' });
+ store.register(afterRefreeze, { lane, path: join(box.directory, 'verifier-other'), family: 'Reviewer Family', createdBy: 'coordinator' });
verifierOther = store.agentAt(afterRefreeze, join(box.directory, 'verifier-other')).agent_id;
+ // These seats stand in for verifiers the coordinator enrolled through the relay (#579 standing).
+ for (const seat of [verifierSame, verifierOther]) afterRefreeze.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_enrolled:${seat}`, 'coordinator');
/** Freeze test items with a specific historical policy document, keeping engine inputs deterministic. */
const makeFrozen = (verify, version = 1) => item => {
@@ -799,7 +801,7 @@ test('person recovery explicitly skips one future-engine blocker and publishes a
const later = personRequest('later-person-request', 'Later person move');
assert.equal((await box.call(box.path + '/requests', { method: 'POST', token: box.person.token,
body: { sequence: 2, sealed: Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(later)), { boardId: box.id, kind: 'request', sequence: 2 })).toString('base64url') } })).status, 200);
- const invalid = { version: 1, engine: 3, id: 'known-item-forged-claim', operation: 'claim', args: [1, { agentId: 'forged-agent' }] };
+ const invalid = { version: 1, engine: ENGINE_VERSION, id: 'known-item-forged-claim', operation: 'claim', args: [1, { agentId: 'forged-agent' }] };
const sealFor = async (value, kind, sequence) => Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: box.id, kind, sequence })).toString('base64url');
const append = (sequence, kind, sealed, token = box.one.token) => box.call(box.path + (kind === 'request' ? '/requests' : '/moves'), { method: 'POST', token, body: { sequence, sealed } });
assert.equal((await append(3, 'move', await sealFor(invalid, 'move', 3))).status, 200);
@@ -808,7 +810,7 @@ test('person recovery explicitly skips one future-engine blocker and publishes a
assert.equal((await append(5, 'request', await sealFor(repeated, 'request', 5), box.person.token)).status, 200);
const changed = personRequest('reused-content-id', 'Changed request');
assert.equal((await append(6, 'request', await sealFor(changed, 'request', 6), box.person.token)).status, 200);
- const unknownCurrent = { version: 1, engine: 3, id: 'unknown-current-operation', operation: 'notAnOperation', args: [] };
+ const unknownCurrent = { version: 1, engine: ENGINE_VERSION, id: 'unknown-current-operation', operation: 'notAnOperation', args: [] };
assert.equal((await append(7, 'move', await sealFor(unknownCurrent, 'move', 7), box.one.token)).status, 200);
let suppressCheckpointWrites = true;
const proxy = createServer(async (incoming, outgoing) => {
@@ -1194,9 +1196,10 @@ test('checkpoint restore checks native digest after BEGIN IMMEDIATE against a se
}
});
-test('relay accepts engine 4 clients carrying sealed background completions [V2,H16]', async t => {
+test('relay stores engine-4 sealed background completions opaquely [V2,H16]', async t => {
const box = await fixture(t, { machineCredentials: false });
- const headers = { 'x-pullboard-engine': '4' };
+ // A board with agent tokens requires an engine-13 client (#579); the sealed move keeps engine 4.
+ const headers = { 'x-pullboard-engine': String(ENGINE_VERSION) };
assert.ok(ENGINE_VERSION >= 4, 'engine-4 background completions remain supported');
const snapshot = await box.call(box.path + '/state', {
method: 'PUT', token: box.person.token, headers,
@@ -1222,7 +1225,7 @@ test('relay accepts engine 4 clients carrying sealed background completions [V2,
assert.equal(read.status, 200);
assert.equal(read.body.events.length, 1);
const [record] = read.body.events;
- assert.deepEqual(record.sender, { kind: 'agent', userId: box.person.user.id, agent: 'client-one' });
+ assert.deepEqual(record.sender, { kind: 'agent', userId: box.person.user.id, agent: 'client-one', policy: VERIFIER_STANDING_ENGINE });
assert.deepEqual(box.clientOpen(record.sealed, record.kind, record.event_id), move);
});
@@ -1319,7 +1322,7 @@ test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys o
});
assert.equal(request.status, 200);
assert.equal(request.body.event.kind, 'request');
- assert.deepEqual(request.body.event.sender, { kind: 'agent', userId: box.person.user.id, agent: 'client-one' });
+ assert.deepEqual(request.body.event.sender, { kind: 'agent', userId: box.person.user.id, agent: 'client-one', policy: VERIFIER_STANDING_ENGINE });
assert.deepEqual(box.clientOpen(request.body.event.sealed, request.body.event.kind, request.body.event.event_id), { request: true });
assert.throws(() => box.clientOpen(request.body.event.sealed, 'move', request.body.event.event_id));
@@ -1348,7 +1351,7 @@ test('[A4,H2,H7,H16] trusted sender attribution exposes impersonation and agent
method: 'POST', body: { sequence: 1, sealed: box.clientSeal(forged, 'move', 1) },
});
assert.equal(reply.status, 200, 'the relay stores opaque bytes without reading their claimed agent');
- const expected = { kind: 'agent', userId: box.person.user.id, agent: 'client-one' };
+ const expected = { kind: 'agent', userId: box.person.user.id, agent: 'client-one', policy: VERIFIER_STANDING_ENGINE };
assert.deepEqual(reply.body.event.sender, expected, 'the sender comes from the credential, not sealed contents');
const events = (await box.call(box.path + '/events?after=0')).body.events;
assert.equal(events.length, 1);
@@ -1372,7 +1375,7 @@ test('[A4,H2,H7,H16] trusted sender attribution exposes impersonation and agent
method: 'POST', token: box.person.token,
body: { sequence: 2, sealed: box.clientSeal({ person: true }, 'move', 2) },
});
- assert.deepEqual(personMove.body.event.sender, { kind: 'person', userId: box.person.user.id });
+ assert.deepEqual(personMove.body.event.sender, { kind: 'person', userId: box.person.user.id, policy: VERIFIER_STANDING_ENGINE });
assert.equal((await box.call(box.path, { method: 'DELETE', token: box.person.token })).status, 200);
});
diff --git a/test/relay-snapshot-recovery.test.js b/test/relay-snapshot-recovery.test.js
index fae8d3bc..61524906 100644
--- a/test/relay-snapshot-recovery.test.js
+++ b/test/relay-snapshot-recovery.test.js
@@ -65,13 +65,9 @@ test('a delayed native checkpoint recovers the real page after its visible timeo
let move;
try { move = prepareEngineMove(board, 'addItem', [{ by: 'coordinator', lane: box.lane, title: recovered }]); }
finally { closeBoard(board); }
- const coordinator = await fetch(box.origin + '/auth/tokens', {
- method: 'POST', headers: { authorization: 'Bearer ' + link.token,
- 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) },
- body: JSON.stringify({ board: link.board, agent: 'coordinator' }),
- });
- assert.equal(coordinator.status, 201, 'the board machine mints an ordinary coordinator token without a phone tap');
- const agent = await coordinator.json();
+ // relay on set up the coordinator's own token from the person sign-in, with no extra tap (#579).
+ const agent = link.agentTokens.coordinator;
+ assert.match(agent?.token ?? '', /^pa_[A-Za-z0-9_-]{43}$/u, 'relay on gives the coordinator its token without a phone tap');
const sent = await upload(box, { ...link, token: agent.token }, 'moves', 1, await encoded(key, move, link.board, 'move', 1));
const started = Date.now();
const timeoutText = 'The relay snapshot has not caught up to this move. Retry this board.';
diff --git a/test/relay-version.test.js b/test/relay-version.test.js
index efac9635..5f31771a 100644
--- a/test/relay-version.test.js
+++ b/test/relay-version.test.js
@@ -28,10 +28,10 @@ test('relay enforces the minimum engine ever required by each board [H16,H3]', a
await auth.revoke(person.token, historical.id);
time += 10;
assert.equal(auth.minimumEngineVersion(A), 1);
- assert.equal(auth.minimumEngineVersion(B), 3);
+ assert.equal(auth.minimumEngineVersion(B), 13, 'agent tokens now require engine 13 (#579)');
auth.close();
auth = createRelayAuth(authConfig);
- assert.equal(auth.minimumEngineVersion(B), 3, 'the minimum survives revocation, expiry and reopening the real auth database');
+ assert.equal(auth.minimumEngineVersion(B), 13, 'the minimum survives revocation, expiry and reopening the real auth database');
const relay = await serveRelay({ directory: join(directory, 'data'), auth, maintenanceMs: 0, pollMs: 10 });
t.after(async () => { await relay.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });
const base = `http://127.0.0.1:${relay.port}/api/v1/boards/`;
@@ -48,19 +48,19 @@ test('relay enforces the minimum engine ever required by each board [H16,H3]', a
}
// Seed opaque snapshots so eligible reads reach actual state and event handlers.
for (const board of [A, B]) {
- const seeded = await call(board, '/state', { engine: 3, method: 'PUT', body: JSON.stringify({ sequence: 0, sealed: opaque }) });
+ const seeded = await call(board, '/state', { engine: 13, method: 'PUT', body: JSON.stringify({ sequence: 0, sealed: opaque }) });
assert.equal(seeded.status, 200, seeded.text);
}
for (const board of [A, B]) {
- const currentState = await call(board, '/state', { engine: 3 });
+ const currentState = await call(board, '/state', { engine: 13 });
assert.equal(currentState.status, 200, currentState.text);
- assert.equal((await call(board, '/events?after=0', { engine: 3 })).status, 200);
+ assert.equal((await call(board, '/events?after=0', { engine: 13 })).status, 200);
}
for (const board of [A, B]) {
const controller = new AbortController();
const streamed = await fetch(base + board + '/events?after=0', {
- headers: { authorization: `Bearer ${person.token}`, 'x-pullboard-engine': '3', accept: 'text/event-stream' }, signal: controller.signal,
+ headers: { authorization: `Bearer ${person.token}`, 'x-pullboard-engine': '13', accept: 'text/event-stream' }, signal: controller.signal,
});
assert.equal(streamed.status, 200);
await streamed.body.cancel(); controller.abort();
diff --git a/test/relay.test.js b/test/relay.test.js
index 97c8b885..7a1db5cf 100644
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@ -823,7 +823,7 @@ test('revoking a board credential while its upload body is open stores nothing [
const origin = `http://127.0.0.1:${service.port}`;
const snapshot = await fetch(`${origin}/api/v1/boards/${board}/state`, {
method: 'PUT',
- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '13', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: JSON.stringify({ sequence: 0, sealed: 'AQ' }),
});
assert.equal(snapshot.status, 200);
@@ -843,7 +843,7 @@ test('revoking a board credential while its upload body is open stores nothing [
let stream;
const upload = fetch(`${origin}/api/v1/boards/${board}/moves`, {
method: 'POST',
- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${agent.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '13', authorization: `Bearer ${agent.token}`, 'content-type': 'application/json' },
body: new ReadableStream({ start(controller) { stream = controller; controller.enqueue(Buffer.from('{"sequence":1,"sealed":"')); } }),
duplex: 'half',
});
@@ -859,7 +859,7 @@ test('revoking a board credential while its upload body is open stores nothing [
assert.equal(response.status, 401, JSON.stringify(refusal));
assert.equal(refusal.error.code, 'AUTH_REQUIRED');
const events = await fetch(`${origin}/api/v1/boards/${board}/events?after=0`, {
- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}` },
+ headers: { 'x-pullboard-engine': '13', authorization: `Bearer ${person.token}` },
});
assert.equal(events.status, 200);
assert.deepEqual((await events.json()).events, [], 'the revoked upload never appends a move');
@@ -880,7 +880,7 @@ test('revoking a person token during snapshot upload preserves the prior snapsho
const origin = `http://127.0.0.1:${service.port}`;
const firstSnapshot = await fetch(`${origin}/api/v1/boards/${board}/state`, {
method: 'PUT',
- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '13', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: JSON.stringify({ sequence: 0, sealed: 'AQ' }),
});
assert.equal(firstSnapshot.status, 200);
@@ -900,7 +900,7 @@ test('revoking a person token during snapshot upload preserves the prior snapsho
let stream;
const upload = fetch(`${origin}/api/v1/boards/${board}/state`, {
method: 'PUT',
- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '13', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: new ReadableStream({ start(controller) { stream = controller; controller.enqueue(Buffer.from('{"sequence":0,"sealed":"')); } }),
duplex: 'half',
});
@@ -916,7 +916,7 @@ test('revoking a person token during snapshot upload preserves the prior snapsho
assert.equal(response.status, 401, JSON.stringify(refusal));
assert.equal(refusal.error.code, 'AUTH_REQUIRED');
const current = await fetch(`${origin}/api/v1/boards/${board}/state`, {
- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${observer.token}` },
+ headers: { 'x-pullboard-engine': '13', authorization: `Bearer ${observer.token}` },
});
assert.equal(current.status, 200);
const saved = await current.json();
@@ -995,7 +995,8 @@ test('write, maintain and admin accounts act and mint while private readers only
for (const permission of ['write', 'maintain', 'admin']) {
box.state.permission = permission;
assert.equal((await box.auth.authenticate(signed.token, { board: 'alpha', write: true })).permission, permission);
- existing = await box.auth.issueToken(signed.token, { board: 'alpha', agent: 'worker' });
+ // Each seat gets one first mint (#579), so each permission mints its own seat.
+ existing = await box.auth.issueToken(signed.token, { board: 'alpha', agent: 'worker-' + permission });
assert.equal((await box.auth.authenticate(existing.token, { board: 'alpha', write: true })).permission, permission);
await box.auth.revoke(signed.token, existing.id);
await assert.rejects(box.auth.authenticate(existing.token, { board: 'alpha' }), { code: 'AUTH_REQUIRED' });