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): a published seat receipt claims its seat [H2,V1]

Corey Olsonddb0d75e032b
diff --git a/docs/api.md b/docs/api.md
index 2b35d3e4..f79f0c62 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -186,11 +186,11 @@ Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed b
`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.
+A `pa_` token renews only its own seat: `POST /auth/tokens {board,agent}` naming itself returns a new token and revokes the one that asked (`TOKEN_AGENT` for any other seat). A seat's first token from another seat comes only with the move that registers it: `POST /api/v1/boards/:board/moves {sequence, sealed, registration}`, sent with the creating seat's token, where `registration` is `{target, creator, sequence, digest}` (the creator is the sender, the sequence is this upload's, and the digest is the SHA-256 of the `sealed` text). The relay appends the move and issues the target's first token in one board lock and returns it only in that reply as `enrollment`; the public event carries the receipt and never the token. An exact retry returns the same issuance id and expiry without a token. The receipt commits in the same journal transaction as the move and is kept through compaction, and it claims the target from that moment: the machine credential and a person are refused a first mint for any name a receipt claims, under the same board lock that appends receipts, so no failure between the append and the enrollment leaves a window. If enrollment fails after the append, the creator's exact retry, or its `recover:true` reissue, rolls the first mint forward from the journalled receipt. A lost token is reissued by its creator, `POST /auth/tokens {board,agent,recover:true}` with the creator's token, which revokes the old ones. `/auth/tokens` refuses a `registration` field (`REGISTRATION_IN_MOVE`), so a copied receipt never mints. Replicas apply an engine-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.
+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. Each person-made coordinator token carries a machine lineage (a reissue that replaces a token keeps it; another machine's token starts its own), and a seat enrolled from it, or from a seat in its line, records that lineage. A coordinator claim records the lineage of the machine that builds it. When the coordinator built an item, a seat from another machine's registration lineage, or the person, verifies it; a seat from the building machine's own lineage is refused and told so. On an unlinked board who may verify is unchanged. The relay stamps each record it stores with `policy` (and `root` for the person-made coordinator token); a stamped record below engine 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.
diff --git a/relay/auth.js b/relay/auth.js
index 0e9378a3..5299b728 100644
--- a/relay/auth.js
+++ b/relay/auth.js
@@ -57,6 +57,10 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
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');
}
+ // Which machine's person-set coordinator line a root token belongs to; renewals keep it (#579).
+ if (!db.prepare('PRAGMA table_info(relay_credentials)').all().some((column) => column.name === 'lineage')) {
+ db.exec('ALTER TABLE relay_credentials ADD COLUMN lineage TEXT');
+ }
// 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`);
@@ -78,6 +82,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
const deviceSessionReceipts = new Map();
let closed = false;
let locked = false;
+ // The relay journal's published seat receipts, read under the board lock (#579); none until wired.
+ let registrationClaim = () => null;
/** Refuse operation after closing instead of surfacing a raw SQLite error. */
function open() { if (closed) throw new Refused('RELAY_CLOSED', 'start the relay before signing in or using a credential'); }
@@ -115,13 +121,13 @@ 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, root = false) {
+ function issue(user, kind, board, agent, ttl, root = false, lineage = null) {
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,root) VALUES (?,?,?,?,?,?,?,?,?)').run(id, hash(token), kind, user.id, board ?? null, agent ?? null, created, expires, root ? 1 : 0);
+ db.prepare('INSERT INTO relay_credentials (id,hash,kind,user_id,board,agent,created,expires,root,lineage) VALUES (?,?,?,?,?,?,?,?,?,?)').run(id, hash(token), kind, user.id, board ?? null, agent ?? null, created, expires, root ? 1 : 0, root ? lineage : null);
return { token, id, created, expires };
}
@@ -131,8 +137,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
}
/** 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);
+ function firstMint(user, board, agent, ttl, { origin, creator = null, sequence = null, digest = null, root = false, lineage = null }) {
+ const issued = issue(user, 'board', board, agent, ttl, root, lineage);
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`)
@@ -465,7 +471,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 }) } : {}), ...(row.root ? { root: true } : {}), ...(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, ...(row.lineage ? { lineage: row.lineage } : {}) } : {}), ...(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) {
@@ -571,10 +577,16 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
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));
+ const renewed = issue(principal.user, 'board', board, agent, expiresIn, Boolean(current.root), current.lineage ?? null);
db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(current.id);
return { ...renewed, board, agent };
}
+ const claim = !existing && recover ? registrationClaim(board, agent) : null;
+ if (recover && claim?.creator === principal.agent && agent !== principal.agent) {
+ // A receipt published without its enrollment: the creator rolls the first mint forward.
+ return firstMint({ id: current.user_id }, board, agent, tokenTTL,
+ { origin: 'registered', creator: claim.creator, sequence: claim.sequence, digest: claim.digest });
+ }
if (recover && existing?.origin === 'registered' && existing.creator === principal.agent && agent !== principal.agent) {
db.prepare("UPDATE relay_credentials SET revoked=1 WHERE board=? AND kind='board' AND agent=?").run(board, agent);
return { ...issue(principal.user, 'board', board, agent, expiresIn), board, agent };
@@ -589,9 +601,18 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
? 'the coordinator already has a token; it renews with its own, or the person reissues it with pullboard relay on'
: 'this seat already had a token; it renews only with its own current token, or its creator reissues it');
}
+ // A published receipt claims its target even before enrollment finishes: no machine race.
+ if (registrationClaim(board, agent)) {
+ throw new Refused('TOKEN_EXISTS', 'a creator registered this seat; its first token comes only through that registration or its creator');
+ }
return firstMint(principal.user, board, agent, expiresIn, { origin: 'machine' });
});
},
+ /** Wire the relay journal's receipt lookup; token issuance then honors every published claim. */
+ setRegistrationClaims(reader) {
+ if (typeof reader !== 'function') throw new Refused('RELAY_CONFIG', 'configure a seat receipt reader');
+ registrationClaim = reader;
+ },
/**
* Give a registration move's target its first token, inside the board lock that appended the
* move (#579). The creator is the authenticated agent token that sent the move; the target
@@ -645,10 +666,13 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
// replaces, so each of the person's linked machines keeps its own coordinator token.
const revoked = db.prepare("SELECT id FROM relay_credentials WHERE board=? AND kind='board' AND agent='coordinator' AND revoked=0 AND expires>?").all(board, now())
.map((row) => row.id).filter((id) => reason === 'reset' || id === replaces);
+ // A replacement keeps its machine's lineage; a token for another machine starts a new one.
+ const replaced = replaces === undefined ? null : db.prepare("SELECT lineage FROM relay_credentials WHERE id=? AND board=? AND kind='board' AND agent='coordinator' AND root=1").get(replaces, board);
+ const lineage = reason !== 'reset' && replaced?.lineage ? replaced.lineage : randomUUID();
for (const id of revoked) db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(id);
const issued = reason === 'reissue'
- ? { ...issue(principal.user, 'board', board, 'coordinator', expiresIn, true), board, agent: 'coordinator' }
- : firstMint(principal.user, board, 'coordinator', expiresIn, { origin: 'root', root: true });
+ ? { ...issue(principal.user, 'board', board, 'coordinator', expiresIn, true, lineage), board, agent: 'coordinator' }
+ : firstMint(principal.user, board, 'coordinator', expiresIn, { origin: 'root', root: true, lineage });
db.prepare('INSERT INTO relay_coordinator_events (id,board,reason,session_id,revoked,issued_id,at) VALUES (?,?,?,?,?,?,?)')
.run(randomUUID(), board, reason, current.id, JSON.stringify(revoked), issued.id, issued.created);
return { ...issued, root: true, reason };
diff --git a/relay/journal.js b/relay/journal.js
index 570929e3..83ebb056 100644
--- a/relay/journal.js
+++ b/relay/journal.js
@@ -73,9 +73,13 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
}
// 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']]) {
+ for (const [column, type] of [['sender_policy', 'INTEGER'], ['sender_root', 'INTEGER'], ['sender_lineage', 'TEXT'], ['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}`);
}
+ // A published seat receipt claims its target for good: compaction keeps it, so no later machine
+ // first mint can take a name a creator registered, even if enrollment never finished (#579).
+ db.exec(`CREATE TABLE IF NOT EXISTS journal_registration (target TEXT PRIMARY KEY, creator TEXT NOT NULL,
+ sequence INTEGER NOT NULL UNIQUE, digest TEXT NOT NULL)`);
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');
@@ -96,7 +100,8 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
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 } : {}),
- ...(row.sender_policy ? { policy: row.sender_policy } : {}), ...(row.sender_root ? { root: true } : {}) },
+ ...(row.sender_policy ? { policy: row.sender_policy } : {}), ...(row.sender_root ? { root: true } : {}),
+ ...(row.sender_lineage ? { lineage: row.sender_lineage } : {}) },
...(row.registration ? { registration: JSON.parse(row.registration) } : {}), bytes: Buffer.from(row.payload) };
}
@@ -109,11 +114,12 @@ 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');
- if ((value.policy !== undefined && (!Number.isSafeInteger(value.policy) || value.policy < 1)) || (value.root !== undefined && value.root !== true)) {
+ if ((value.policy !== undefined && (!Number.isSafeInteger(value.policy) || value.policy < 1)) || (value.root !== undefined && value.root !== true) ||
+ (value.lineage !== undefined && (typeof value.lineage !== 'string' || !/^[0-9a-f-]{36}$/.test(value.lineage)))) {
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 };
+ policy: value.policy ?? null, root: value.root === true ? 1 : null, lineage: value.lineage ?? null };
}
/** Keep a seat receipt to its four public fields: target, creator, sequence and ciphertext digest. */
@@ -163,8 +169,15 @@ 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,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('INSERT INTO journal_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent,sender_policy,sender_root,sender_lineage,registration) VALUES (?,?,?,?,?,?,?,?,?,?,?)')
+ .run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent, who.policy, who.root, who.lineage, stored);
+ if (stored) {
+ const claim = JSON.parse(stored);
+ if (db.prepare('SELECT 1 FROM journal_registration WHERE target=?').get(claim.target)) {
+ throw new Refused('SEAT_TAKEN', `${claim.target} was already registered; register the next free name`);
+ }
+ db.prepare('INSERT INTO journal_registration (target,creator,sequence,digest) VALUES (?,?,?,?)').run(claim.target, claim.creator, claim.sequence, claim.digest);
+ }
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');
@@ -178,6 +191,13 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
/** 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); }
+ /** The committed seat receipt that claims this target, kept through compaction, or null. */
+ function registrationFor(target) {
+ open();
+ const row = db.prepare('SELECT target,creator,sequence,digest FROM journal_registration WHERE target=?').get(target);
+ return row ? { target: row.target, creator: row.creator, sequence: row.sequence, digest: row.digest } : null;
+ }
+
/** Read one committed record, or null once compaction removed it, for an exact registration retry. */
function recordAt(sequence) {
open();
@@ -231,5 +251,5 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
closed = true;
}
- return { board: id, latest, activity, append, appendNext, recordAt, after, snapshot, saveSnapshot, close };
+ return { board: id, latest, activity, append, appendNext, recordAt, registrationFor, after, snapshot, saveSnapshot, close };
}
diff --git a/relay/service.js b/relay/service.js
index 50fb0b30..997ecfae 100644
--- a/relay/service.js
+++ b/relay/service.js
@@ -103,7 +103,8 @@ 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 } : {}),
- ...(personOnly === 'snapshot' ? {} : { policy: VERIFIER_STANDING_ENGINE, ...(who.root === true ? { root: true } : {}) }) };
+ ...(personOnly === 'snapshot' ? {} : { policy: VERIFIER_STANDING_ENGINE,
+ ...(who.root === true ? { root: true, ...(who.lineage ? { lineage: who.lineage } : {}) } : {}) }) };
}
/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */
@@ -200,6 +201,19 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
});
}
+ /**
+ * Let token issuance see a published seat receipt under the same board lock that appends it, so
+ * a receipt claims its target before, and whether or not, its enrollment finishes (#579).
+ */
+ auth.setRegistrationClaims((id, target) => {
+ const file = join(root, identity(id) + '.journal.sqlite');
+ try { if (!lstatSync(file).isFile()) return null; } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
+ return auth.withBoard(id, () => {
+ const journal = createRelayJournal({ directory: root, boardId: id, maxBytes: STORED_BYTES, now: () => new Date(now()) });
+ try { return journal.registrationFor(target); } finally { journal.close(); }
+ });
+ });
+
/** 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, kind === 'move');
@@ -222,10 +236,11 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
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;
+ // The move and its receipt committed but the seat did not (any failure before enrollment):
+ // the creator's exact retry rolls the enrollment forward, even after compaction.
+ if (!['SEQUENCE_REPEAT', 'SEAT_TAKEN'].includes(error.code) || JSON.stringify(journal.registrationFor(receipt.target)) !== JSON.stringify(receipt)) throw error;
+ row = journal.recordAt(receipt.sequence);
+ if (row && !row.bytes.equals(bytes)) throw error;
}
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 };
diff --git a/src/board.js b/src/board.js
index 6102e7b3..ef1aa7e2 100644
--- a/src/board.js
+++ b/src/board.js
@@ -590,6 +590,9 @@ export function register(board, { lane, path, route = 'strong', family, model, c
// 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);
+ // The seat's machine lineage: the creating coordinator token's, or its creator seat's.
+ const lineage = createdBy === COORDINATOR ? board.verifierStanding?.lineage ?? null : seatLineage(board, createdBy);
+ if (lineage) board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_lineage:${id}`, lineage);
}
logEvent(board, id, 'join', null, route === 'strong' ? { lane } : { lane, route });
return id;
@@ -653,6 +656,18 @@ export function seatEnrolled(board, id) {
return Boolean(board.db.prepare('SELECT 1 FROM board_meta WHERE meta_key = ?').get(`agent_enrolled:${id}`));
}
+/**
+ * The machine registration lineage a relay-enrolled seat descends from: the person-set coordinator
+ * token of the machine that made its line (#579), or null when it was never recorded.
+ *
+ * @param {any} board
+ * @param {string} id
+ * @returns {string | null}
+ */
+export function seatLineage(board, id) {
+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_lineage:${id}`)?.meta_value ?? null;
+}
+
/**
* The id the next registration in a lane gets when it names none, for a creator that must
* predict it before sealing the move (the relay receipt names the target seat).
@@ -674,13 +689,14 @@ export function nextSeatId(board, lane) {
*
* @template T
* @param {any} board
- * @param {{ root: boolean }} standing
+ * @param {{ root: boolean, person?: boolean, lineage?: string | null }} standing
* @param {() => T} work
* @returns {T}
*/
export function withVerifierStanding(board, standing, work) {
const previous = board.verifierStanding;
- board.verifierStanding = { root: standing.root === true };
+ board.verifierStanding = { root: standing.root === true, person: standing.person === true,
+ lineage: typeof standing.lineage === 'string' ? standing.lineage : null };
try { return work(); }
finally {
if (previous === undefined) delete board.verifierStanding;
@@ -697,15 +713,27 @@ export function withVerifierStanding(board, standing, work) {
* @param {any} board
* @param {string} verifier
* @param {string} builder
+ * @param {number} itemId
* @returns {Refused | null}
*/
-function standingProblem(board, verifier, builder) {
+function standingProblem(board, verifier, builder, itemId) {
const standing = board.verifierStanding;
if (!standing || (board.executionEngineVersion ?? ENGINE_VERSION) < VERIFIER_STANDING_ENGINE) return null;
const refuse = (why) => new Refused('VERIFIER_STANDING',
`${verifier} cannot verify work built by ${builder} on this linked board: ${why}; ask the coordinator to make an independent verifier from the main checkout: pullboard worktree <lane> --model "<model name>"`);
if (builder === COORDINATOR) {
- 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`);
+ // The person stands above every seat; otherwise only a seat from another machine's line may.
+ if (standing.person) return null;
+ const refuseOwn = (why) => new Refused('VERIFIER_STANDING', `${verifier} cannot verify work the coordinator built on this linked board: ${why}; a seat from another machine's registration lineage, or the person, verifies it`);
+ const built = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_lineage:${itemId}`)?.meta_value ?? null;
+ const lineage = seatLineage(board, verifier);
+ if (!built || !lineage) return refuseOwn('the machine lineage of the build or of this seat was not recorded');
+ if (built === lineage) return refuseOwn('this seat shares the building machine\'s registration lineage');
+ for (let seat = verifier, seen = new Set(); seat !== COORDINATOR; seat = agentCreator(board, seat)) {
+ if (seen.has(seat) || !seatEnrolled(board, seat)) return refuseOwn(`${seat} was not enrolled through the relay`);
+ seen.add(seat);
+ }
+ return null;
}
const seen = new Set();
for (let seat = verifier; ;) {
@@ -1271,6 +1299,11 @@ export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null,
});
const renewed = isRenewal(item);
const digest = frozen ? frozen.digest : item.item_frozen_digest;
+ // A linked coordinator claim records which machine's coordinator lineage builds it (#579).
+ if (board.verifierStanding && agentId === COORDINATOR && (board.executionEngineVersion ?? ENGINE_VERSION) >= VERIFIER_STANDING_ENGINE) {
+ board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(`item_lineage:${id}`);
+ if (board.verifierStanding.lineage) board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`item_lineage:${id}`, board.verifierStanding.lineage);
+ }
logEvent(board, agentId, renewed ? 'renew' : 'claim', id, { leaseUntil, digest, ...(!renewed && reviewSkipped ? { reviewSkipped } : {}) });
return { leaseUntil, digest, renewed };
});
@@ -1535,7 +1568,7 @@ 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')
- : standingProblem(board, agentId, found.item_built_by)),
+ : standingProblem(board, agentId, found.item_built_by, found.item_id)),
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`);
@@ -2313,8 +2346,8 @@ export function nextFor(board, { agentId, lane, verify = false, policy = 'any',
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);
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));
+ const standingRefusal = unrelated.map((entry) => standingProblem(board, agentId, entry.item_built_by, entry.item_id)).find(Boolean);
+ let reviewable = unrelated.filter((entry) => !standingProblem(board, agentId, entry.item_built_by, entry.item_id));
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)));
diff --git a/src/engine.js b/src/engine.js
index 945e7c1a..687c8207 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -220,7 +220,8 @@ export function applyRelayMove(board, move, { sequence, at, sender, kind, digest
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;
+ const standing = move?.engine >= VERIFIER_STANDING_ENGINE ? { root: sender?.root === true || sender?.kind === 'person',
+ person: sender?.kind === 'person', lineage: sender?.root === true && typeof sender.lineage === 'string' ? sender.lineage : null } : 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 });
diff --git a/src/relay-sender.js b/src/relay-sender.js
index 39d82d32..71db5e15 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -23,7 +23,8 @@ export function validRelaySender(sender) {
(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.policy === undefined || Number.isSafeInteger(sender.policy) && sender.policy > 0) &&
- (sender.root === undefined || sender.root === true));
+ (sender.root === undefined || sender.root === true) &&
+ (sender.lineage === undefined || typeof sender.lineage === 'string' && sender.lineage.length > 0 && sender.lineage.length <= 64));
}
/** Make the same authorization decision on every device, without inspecting its shell or checkout. */
diff --git a/test/relay-mint.test.js b/test/relay-mint.test.js
index c327f298..2732b1ce 100644
--- a/test/relay-mint.test.js
+++ b/test/relay-mint.test.js
@@ -177,7 +177,11 @@ test('an agent in its worktree cannot mint a relay token [H2,V1,E3,E5,P6]', asyn
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');
+ assert.equal(machineRenewal.document.error?.code, 'TOKEN_EXISTS', 'the machine credential never renews a registered seat that held a token');
+ // A machine-minted seat has no receipt to fall back on: its first-mint history alone refuses.
+ await box.auth.revoke(person.token, state.agentTokens[prelinked.document.agent].id);
+ const machineRemint = await call(box.origin, state.token, 'POST', '/auth/tokens', { board: state.board, agent: prelinked.document.agent });
+ assert.equal(machineRemint.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.
@@ -205,14 +209,47 @@ test('an agent in its worktree cannot mint a relay token [H2,V1,E3,E5,P6]', asyn
assert.equal(claimed.code, 0, claimed.failure ?? 'the build-only seat keeps acting under its own token');
});
+ await t.test('a registration interrupted before enrollment still claims its seat from the machine', async () => {
+ // Causal control for the 5e76ff75 reject: fail after the journal append, before enrollment.
+ const enroll = box.auth.enrollSeat;
+ let injected = 0;
+ box.auth.enrollSeat = (...args) => {
+ if (injected++ === 0) throw new Error('injected failure between the journal append and enrollment');
+ return enroll.apply(box.auth, args);
+ };
+ const from = box.transit.length;
+ let interrupted;
+ try { interrupted = await box.cli('worktree', lane, '--model', 'Interrupted Seat'); }
+ finally { box.auth.enrollSeat = enroll; }
+ assert.notEqual(interrupted.code, 0, 'the creator sees the failed registration');
+ const failed = box.transit.slice(from).find((entry) => entry.method === 'POST' && entry.path.endsWith('/moves') && JSON.parse(entry.request.toString('utf8')).registration);
+ assert.ok(failed, 'the registration reached the relay');
+ const body = JSON.parse(failed.request.toString('utf8'));
+ const state = link(box);
+ const snapshot = await call(box.origin, state.token, 'GET', `/api/v1/boards/${state.board}/state`);
+ const events = await call(box.origin, state.token, 'GET', `/api/v1/boards/${state.board}/events?after=${snapshot.document.state.sequence}`);
+ assert.equal(events.status, 200, JSON.stringify(events.document.error ?? {}));
+ assert.ok(events.document.events.some((event) => event.registration?.target === body.registration.target), 'the move and its receipt were published');
+ assert.equal(box.auth.seatRecord(state.board, body.registration.target), null, 'no first-issuance history was written');
+ const race = await call(box.origin, state.token, 'POST', '/auth/tokens', { board: state.board, agent: body.registration.target });
+ assert.equal(race.document.error?.code, 'TOKEN_EXISTS', 'the machine credential cannot first-mint a name its published receipt claims');
+ const retry = await call(box.origin, state.agentTokens.coordinator.token, 'POST', failed.path, body);
+ assert.equal(retry.status, 200, 'the creator\'s exact retry is accepted');
+ assert.equal(retry.document.enrollment.agent, body.registration.target);
+ assert.match(retry.document.enrollment.token ?? '', TOKEN, 'the exact retry finishes the enrollment with the first token');
+ assert.equal(box.auth.seatRecord(state.board, body.registration.target).origin, 'registered');
+ const after = await call(box.origin, state.token, 'POST', '/auth/tokens', { board: state.board, agent: body.registration.target });
+ assert.equal(after.document.error?.code, 'TOKEN_EXISTS');
+ });
+
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 },
+ const move = (operation, args, sender, extra = {}) => 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 }, ...extra,
});
for (const seat of [child.id, grandchild.id, manual, prelinked.document.agent]) {
const refused = move('verify', verdict(seat), { agent: seat });
@@ -234,6 +271,40 @@ test('an agent in its worktree cannot mint a relay token [H2,V1,E3,E5,P6]', asyn
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);
+
+ // The positive half of 11099: the coordinator on machine A builds; a seat from machine B's
+ // registration lineage, or the person, verifies it, while machine A's own seats still cannot.
+ const machineA = { agent: 'coordinator', root: true, lineage: '11111111-1111-4111-8111-111111111111' };
+ const machineB = { agent: 'coordinator', root: true, lineage: '22222222-2222-4222-8222-222222222222' };
+ /** Enroll one seat through a replayed, receipt-bound coordinator registration from one machine. */
+ const enrollFrom = (sender, n) => {
+ const target = `${lane}-${n}`;
+ const digest = String(n % 10).repeat(64);
+ const sequence = appliedSequence(board) + 1;
+ const made = move('register', [{ lane, path: `/lineage-seat-${n}`, model: 'Lineage Seat', createdBy: 'coordinator', id: target }], sender,
+ { registration: { target, creator: 'coordinator', sequence, digest }, digest });
+ assert.equal(made.result, target, `machine ${sender.lineage.slice(0, 1)} enrolls ${target}`);
+ return target;
+ };
+ const seatA = enrollFrom(machineA, 801);
+ const seatB = enrollFrom(machineB, 802);
+ /** Claim and submit one coordinator item through replayed moves from machine A. */
+ const builtOnA = () => {
+ const itemId = store.addItem(board, { by: 'coordinator', lane: 'coordinator', title: 'coordinator-built on machine A', criterion: 'another lineage accepts it' });
+ const frozen = freezer()();
+ assert.equal(move('claim', [itemId, { agentId: 'coordinator', lane: 'coordinator', leaseMs: 3_600_000, head: 'a'.repeat(40), frozen, freezeError: null }], machineA).error, undefined);
+ assert.equal(move('submit', [itemId, { agentId: 'coordinator', commit: 'b'.repeat(40), tree: 'c'.repeat(40) }], machineA).error, undefined);
+ return store.getItem(board, itemId);
+ };
+ const coordinatorItem = builtOnA();
+ const accept = (item) => [item.item_id, { agentId: seatB, decision: 'ACCEPT', reason: 'CRITERION_MET', note: 'checked the proof', head: 'd'.repeat(40), digest: item.item_frozen_digest }];
+ const sameLine = move('verify', [coordinatorItem.item_id, { ...accept(coordinatorItem)[1], agentId: seatA }], { agent: seatA });
+ assert.equal(sameLine.error?.code, 'VERIFIER_STANDING', 'a seat from the building machine\'s own lineage is refused');
+ const otherMachine = move('verify', accept(coordinatorItem), { agent: seatB });
+ assert.equal(otherMachine.result?.decision, 'ACCEPT', 'a seat from another machine\'s registration lineage verifies coordinator-built work');
+ const forPerson = builtOnA();
+ const person = move('verify', [forPerson.item_id, { ...accept(forPerson)[1], agentId: seatA }], { kind: 'person', agent: undefined });
+ assert.equal(person.result?.decision, 'ACCEPT', 'the person verifies coordinator-built work');
});
await t.test('an engine-11 journal replays as before', (t) => {