Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
refactor(core): seat code moves to seats.js and relay-seats.js [H2,V1]
Corey Olson7399398037dd
diff --git a/src/board.js b/src/board.jsindex 6eb6c53e..8426c9de 100644--- a/src/board.js+++ b/src/board.js@@ -15,8 +15,12 @@ import { briefFiles, briefSections } from './brief.js';import { COORDINATOR } from './config.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 { agentAt, agentModel, newSeatId, routeOf, saveAgentModel, seatLineage, standingProblem } from './seats.js';import { parseSpec } from './spec.js';+/** The seat readers live in seats.js; the board re-exports them so `store.*` callers keep one import. */+export { agentAt, agentCreator, listAgents, nextSeatId, seatEnrolled, seatLineage, withVerifierStanding } from './seats.js';+export const ACCEPT_REASON = 'CRITERION_MET';export const PERSON = 'person';@@ -495,38 +499,6 @@ function current(board, item) {return { ...item, item_status: 'open', item_owner: null, item_lease_until: null };}-/**- * The agent registered for a worktree path, if any.- *- * @param {any} board- * @param {string} path- * @returns {any}- */-export function agentAt(board, path) {- const agent = board.db.prepare('SELECT * FROM agent WHERE agent_path = ?').get(path);- return withModel(board, agent);-}--/** Read the model label kept beside other board metadata, avoiding any board-schema migration. */-function agentModel(board, id) {- return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_model:${id}`)?.meta_value ?? null;-}--/** Attach an agent's model to a row from the legacy stable agent table. */-function withModel(board, agent) {- return agent ? { ...agent, agent_model: agentModel(board, agent.agent_id) } : agent;-}--/** Save or clear a model label without changing the shared SQLite schema. */-function saveAgentModel(board, id, model) {- if (model === null || model === undefined) {- board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(`agent_model:${id}`);- return;- }- board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?) ON CONFLICT(meta_key) DO UPDATE SET meta_value = excluded.meta_value')- .run(`agent_model:${id}`, model);-}-/*** Register a worktree as an agent (B3): the main checkout as the one coordinator, any other* worktree as the next agent in its lane (`web-1`, `web-2`, ...), on a route: the tier of model@@ -600,160 +572,6 @@ export function register(board, { lane, path, route = 'strong', family, model, c});}-/**- * 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 machine registration lineage a relay-enrolled seat descends from: the person-set coordinator- * token of the machine that made its line (#579), or null when it was never recorded.- *- * @param {any} board- * @param {string} id- * @returns {string | null}- */-export function seatLineage(board, id) {- return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_lineage:${id}`)?.meta_value ?? null;-}--/**- * The id the next registration in a lane gets when it names none, for a creator that must- * predict it before sealing the move (the relay receipt names the target seat).- *- * @param {any} board- * @param {string} lane- * @returns {string}- */-export function nextSeatId(board, lane) {- const { total } = board.db.prepare('SELECT COUNT(*) AS total FROM agent WHERE agent_lane = ?').get(lane);- return firstFreeSeatId(board, lane, total);-}--/**- * Run board work under linked-board verifier standing (#579): a relay replica replaying an- * engine-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, person?: boolean, lineage?: string | null }} standing- * @param {() => T} work- * @returns {T}- */-export function withVerifierStanding(board, standing, work) {- const previous = board.verifierStanding;- board.verifierStanding = { root: standing.root === true, person: standing.person === true,- lineage: typeof standing.lineage === 'string' ? standing.lineage : null };- try { return work(); }- finally {- if (previous === undefined) delete board.verifierStanding;- else board.verifierStanding = previous;- }-}--/**- * Why this seat may not verify the builder's item on a linked board, or null when it may. The- * seat's creators are walked up to the coordinator: the builder, a join no seat made (`machine`),- * or a seat registered before engine 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- * @param {number} itemId- * @returns {Refused | null}- */-function standingProblem(board, verifier, builder, itemId) {- const standing = board.verifierStanding;- if (!standing || (board.executionEngineVersion ?? ENGINE_VERSION) < VERIFIER_STANDING_ENGINE) return null;- const refuse = (why) => new Refused('VERIFIER_STANDING',- `${verifier} cannot verify work built by ${builder} on this linked board: ${why}; ask the coordinator to make an independent verifier from the main checkout: pullboard worktree <lane> --model "<model name>"`);- if (builder === COORDINATOR) {- // The person stands above every seat; otherwise only a seat from another machine's line may.- if (standing.person) return null;- const refuseOwn = (why) => new Refused('VERIFIER_STANDING', `${verifier} cannot verify work the coordinator built on this linked board: ${why}; a seat from another machine's registration lineage, or the person, verifies it`);- const built = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_lineage:${itemId}`)?.meta_value ?? null;- const lineage = seatLineage(board, verifier);- if (!built || !lineage) return refuseOwn('the machine lineage of the build or of this seat was not recorded');- if (built === lineage) return refuseOwn('this seat shares the building machine\'s registration lineage');- for (let seat = verifier, seen = new Set(); seat !== COORDINATOR; seat = agentCreator(board, seat)) {- if (seen.has(seat) || !seatEnrolled(board, seat)) return refuseOwn(`${seat} was not enrolled through the relay`);- seen.add(seat);- }- return null;- }- const seen = new Set();- for (let seat = verifier; ;) {- if (seat === COORDINATOR) {- return standing.root || seat !== verifier ? null- : refuse('the coordinator credential was not set up by the person; run pullboard relay on in the main checkout once');- }- if (seen.has(seat)) return refuse('its line of creating seats loops');- seen.add(seat);- const creator = agentCreator(board, seat);- if (creator === 'machine') return refuse(`${seat} joined without a creating seat`);- if (creator === builder) return refuse(`${seat} was created by the builder`);- if (creator === null || !seatEnrolled(board, seat)) {- return refuse(`${seat} was not enrolled by its creating seat through the relay`);- }- seat = creator;- }-}-/*** 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.@@ -774,16 +592,6 @@ export function ensureCoordinator(board, path) {return COORDINATOR;}-/**- * Every registered agent, oldest first.- *- * @param {any} board- * @returns {any[]}- */-export function listAgents(board) {- return board.db.prepare('SELECT * FROM agent ORDER BY rowid').all().map((agent) => withModel(board, agent));-}-/*** Refuse a route that is not one of ROUTES.*@@ -819,17 +627,6 @@ function checkRouted({ brief, route, criterion, check }) {}}-/**- * The route an agent joined on; strong for the coordinator and for ids the board does not know.- *- * @param {any} board- * @param {string} agentId- * @returns {string}- */-function routeOf(board, agentId) {- return board.db.prepare('SELECT agent_route FROM agent WHERE agent_id = ?').get(agentId)?.agent_route ?? 'strong';-}-/*** Add an item to a lane, optionally under a parent in the same lane, with a brief for whoever* builds it and a route saying who can (B10, B11). The caller has checked the lane and the specdiff --git a/src/relay-seats.js b/src/relay-seats.jsnew file mode 100644index 00000000..248ecb4f--- /dev/null+++ b/src/relay-seats.js@@ -0,0 +1,148 @@+/**+ * Each seat's own relay credential (#579, H2, V1): the seat name a creator registers, the receipt+ * that binds its first token to that registration, and which token a move is sent with. A live+ * token renews itself; a lost one is reissued by its creator; the machine credential only+ * first-mints a seat the relay never issued, build-only.+ *+ * Why the import back into relay.js: these use its link file and HTTP request, and relay.js calls+ * them only at run time, never while the modules load, so the cycle is safe.+ */+import { createHash } from 'node:crypto';+import * as store from './board.js';+import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';+import { Refused } from './refused.js';+import { localRecords, request, saveLink } from './relay.js';++/**+ * Name the seat a creator registers (#579): the receipt names its target before the move is+ * sealed, so the id travels in the move. A join no seat made, a returning worktree and the+ * coordinator lane keep the board's own numbering.+ */+export function withSeatName(root, operation, args) {+ // A registration that names no creator is a join no seat made.+ if (operation === 'register' && args?.[0] && args[0].createdBy === undefined) args = [{ ...args[0], createdBy: 'machine' }, ...args.slice(1)];+ const options = args?.[0];+ if (operation !== 'register' || ENGINE_VERSION < VERIFIER_STANDING_ENGINE || !options || typeof options.createdBy !== 'string' ||+ options.createdBy === 'machine' || options.lane === 'coordinator' || options.id !== undefined) return args;+ const id = localRecords(root, (board) => store.agentAt(board, options.path) ? null : store.nextSeatId(board, options.lane));+ return id ? [{ ...options, id }, ...args.slice(1)] : args;+}++/** Move a pending registration to the first name from `from` that this replica has not registered. */+export function nameNextSeat(root, move, from) {+ const options = move.args[0];+ localRecords(root, (board) => {+ let n = Math.max(from, Number(store.nextSeatId(board, options.lane).slice(options.lane.length + 1)));+ while (store.listAgents(board).some((agent) => agent.agent_id === `${options.lane}-${n}`)) n += 1;+ options.id = `${options.lane}-${n}`;+ });+}++/** The public receipt a creator sends with a registration: target, creator, position and sealed digest. */+export function seatReceipt(move, sequence, sealed) {+ const options = move?.operation === 'register' && move.engine >= VERIFIER_STANDING_ENGINE ? move.args?.[0] : null;+ if (!options || typeof options.id !== 'string' || typeof options.createdBy !== 'string' || options.createdBy === 'machine') return undefined;+ return { target: options.id, creator: options.createdBy, sequence, digest: createHash('sha256').update(sealed).digest('hex') };+}++/** Cache one seat's own scoped token; nothing else is ever written into agentTokens. */+export function cacheSeatToken(file, state, actor, issued) {+ if (!/^pa_[A-Za-z0-9_-]{43}$/.test(issued?.token ?? '') || issued.board !== state.board || issued.agent !== actor ||+ typeof issued.id !== 'string' || !Number.isSafeInteger(issued.expires)) {+ throw new Refused('RELAY_RESPONSE', 'the relay did not issue this agent’s scoped credential; retry the command');+ }+ state.agentTokens ??= {};+ state.agentTokens[actor] = { id: issued.id, token: issued.token, expires: issued.expires,+ ...(Number.isSafeInteger(issued.created) ? { created: issued.created } : {}) };+ saveLink(file, state);+ return issued.token;+}++/** When a cached token renews itself: halfway through its life, or a minute before expiry when its start is unknown. */+function renewalDue(cached) {+ return Number.isSafeInteger(cached.created) && cached.expires > cached.created+ ? cached.expires - (cached.expires - cached.created) / 2 : cached.expires - 60_000;+}++/**+ * The current token of one registered seat (#579). A live token renews itself with itself; a lost+ * or expired one is reissued by the seat that enrolled it, walking up to the coordinator, whose+ * own token only the person reissues. A seat that never held a token gets its first, build-only+ * one from the machine credential. Nothing here ever remints a seat through the machine.+ */+async function seatToken(root, file, state, actor, io, depth = 0) {+ if (depth > 64) throw new Refused('RELAY_ACTOR', 'this seat\'s line of creators loops; ask the coordinator to make a fresh seat');+ const cached = state.agentTokens?.[actor];+ if (cached?.revoked) throw new Refused('TOKEN_REVOKED', `the relay token of ${actor} was revoked on this board; work from a seat with its own token, or ask the coordinator for a fresh worktree`);+ if (cached?.token && cached.expires > Date.now()) {+ if (Date.now() < renewalDue(cached)) return cached.token;+ const renewed = await request({ ...state, token: cached.token, agent: actor }, '/auth/tokens', { method: 'POST', body: { board: state.board, agent: actor } }, io);+ return cacheSeatToken(file, state, actor, renewed);+ }+ const seat = localRecords(root, (board) => {+ const agent = store.listAgents(board).find((row) => row.agent_id === actor);+ return agent ? { creator: store.agentCreator(board, actor), enrolled: store.seatEnrolled(board, actor) } : null;+ });+ if (!seat) throw new Refused('RELAY_ACTOR', 'register this agent in the ordered board before obtaining its scoped token');+ if (seat.enrolled && actor !== 'coordinator') {+ const creatorToken = await seatToken(root, file, state, seat.creator, io, depth + 1);+ const reissued = await request({ ...state, token: creatorToken, agent: seat.creator }, '/auth/tokens',+ { method: 'POST', body: { board: state.board, agent: actor, recover: true } }, io);+ return cacheSeatToken(file, state, actor, reissued);+ }+ if (cached) {+ throw new Refused('TOKEN_EXPIRED', actor === 'coordinator'+ ? 'the coordinator relay token expired; the person reissues it: run pullboard relay on in the main checkout'+ : `the relay token of ${actor} expired, and only a seat's own current token or its creator renews it; ask the coordinator for a fresh worktree: pullboard worktree <lane> --model "<model name>"`);+ }+ if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');+ // The machine credential first-mints only a seat the relay never issued a token to; it stays build-only.+ const issued = await request(state, '/auth/tokens', { method: 'POST', body: { board: state.board, agent: actor } }, io);+ return cacheSeatToken(file, state, actor, issued);+}++/** Select a scoped credential: the machine's, a supplied agent token, or the seat's own token. */+export async function actorTransport(root, file, state, actor, io) {+ if (typeof actor !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(actor)) {+ throw new Refused('RELAY_ACTOR', 'name the registered agent performing this move before sending it');+ }+ if (actor === 'person') {+ throw new Refused('HUMAN_REQUIRED', 'send this person action from the paired phone');+ }+ if (actor === 'machine') {+ if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');+ return state;+ }+ const supplied = io?.ignoreRelayEnvironmentToken ? undefined : process.env.PULLBOARD_RELAY_TOKEN;+ if (supplied !== undefined) {+ if (!/^pa_[A-Za-z0-9_-]{43}$/.test(supplied)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token, without including it in command arguments');+ const transport = { ...state, token: supplied, agent: actor };+ const identity = await request(transport, '/auth/session?board=' + state.board, {}, io);+ if (identity.session?.kind !== 'board' || identity.session.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');+ return transport;+ }+ if (state.token?.startsWith('pa_')) {+ const identity = await request(state, '/auth/session?board=' + state.board, {}, io);+ if (identity.session?.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');+ return { ...state, agent: actor };+ }+ return { ...state, token: await seatToken(root, file, state, actor, io), agent: actor };+}++/**+ * Give the coordinator a token the person set up, once per board, inside relay on's own sign-in+ * (#579): the first one, a reissue after loss or expiry, or the reset of a machine-minted one.+ * A live person-made coordinator token is kept as it is.+ */+export async function ensurePersonCoordinator(file, state, session, io) {+ const cached = state.agentTokens?.coordinator;+ if (cached?.token && !cached.revoked && Date.now() < renewalDue(cached)) {+ try {+ const identity = await request({ ...state, token: cached.token }, '/auth/session?board=' + state.board, {}, io);+ if (identity.session?.kind === 'board' && identity.session.agent === 'coordinator' && identity.session.root === true) return;+ } catch (error) { if (error.code !== 'AUTH_REQUIRED') throw error; }+ }+ const issued = await request({ ...state, token: session }, '/auth/coordinators', { method: 'POST',+ body: { board: state.board, ...(typeof cached?.id === 'string' ? { replaces: cached.id } : {}) } }, io);+ cacheSeatToken(file, state, 'coordinator', { ...issued, agent: 'coordinator' });+}diff --git a/src/relay.js b/src/relay.jsindex c0c1dd83..00ffd79b 100644--- a/src/relay.js+++ b/src/relay.js@@ -8,6 +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 { actorTransport, cacheSeatToken, ensurePersonCoordinator, nameNextSeat, seatReceipt, withSeatName } from './relay-seats.js';import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';import { codeIsFromMain, repoInfo, tryGit } from './git.js';@@ -95,7 +96,7 @@ function loadLink(file) {}/** Atomically persist acknowledgements and an exact sealed retry before attempting its send. */-function saveLink(file, state) {+export function saveLink(file, state) {mkdirSync(dirname(file), { recursive: true, mode: 0o700 });const temporary = file + '.' + randomUUID() + '.tmp';try {@@ -156,7 +157,7 @@ function transportFailure(error) {}/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */-async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false, signal } = {}, io) {+export async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false, signal } = {}, io) {const supplied = io?.ignoreRelayEnvironmentToken ? undefined : process.env.PULLBOARD_RELAY_TOKEN;const readToken = method === 'GET' && path.startsWith('/api/v1/boards/') ? supplied : undefined;if (readToken !== undefined && !/^pa_[A-Za-z0-9_-]{43}$/.test(readToken)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token without including it in command arguments');@@ -868,140 +869,6 @@ function credentialActor(move) {return relayMoveActor(move);}-/**- * 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');- }- if (actor === 'person') {- throw new Refused('HUMAN_REQUIRED', 'send this person action from the paired phone');- }- if (actor === 'machine') {- if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');- return state;- }- const supplied = io?.ignoreRelayEnvironmentToken ? undefined : process.env.PULLBOARD_RELAY_TOKEN;- if (supplied !== undefined) {- if (!/^pa_[A-Za-z0-9_-]{43}$/.test(supplied)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token, without including it in command arguments');- const transport = { ...state, token: supplied, agent: actor };- const identity = await request(transport, '/auth/session?board=' + state.board, {}, io);- if (identity.session?.kind !== 'board' || identity.session.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');- return transport;- }- if (state.token?.startsWith('pa_')) {- const identity = await request(state, '/auth/session?board=' + state.board, {}, io);- if (identity.session?.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');- return { ...state, agent: actor };- }- return { ...state, token: await seatToken(root, file, state, actor, io), agent: actor };-}--/**- * Give the coordinator a token the person set up, once per board, inside relay on's own sign-in- * (#579): the first one, a reissue after loss or expiry, or the reset of a machine-minted one.- * A live person-made coordinator token is kept as it is.- */-async function ensurePersonCoordinator(file, state, session, io) {- const cached = state.agentTokens?.coordinator;- if (cached?.token && !cached.revoked && Date.now() < renewalDue(cached)) {- try {- const identity = await request({ ...state, token: cached.token }, '/auth/session?board=' + state.board, {}, io);- if (identity.session?.kind === 'board' && identity.session.agent === 'coordinator' && identity.session.root === true) return;- } catch (error) { if (error.code !== 'AUTH_REQUIRED') throw error; }- }- const issued = await request({ ...state, token: session }, '/auth/coordinators', { method: 'POST',- body: { board: state.board, ...(typeof cached?.id === 'string' ? { replaces: cached.id } : {}) } }, io);- cacheSeatToken(file, state, 'coordinator', { ...issued, agent: 'coordinator' });-}-/** 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);diff --git a/src/seats.js b/src/seats.jsnew file mode 100644index 00000000..0767f392--- /dev/null+++ b/src/seats.js@@ -0,0 +1,216 @@+/**+ * Seats (B3, H2, V1): who each registered agent is on the board, read from the agent table and the+ * metadata kept beside it: its model, its route, and from engine 13 the seat that created it, whether+ * the relay enrolled it, and its machine lineage. Verifier standing on a linked board (#579) is+ * decided here from that line of creators. board.js registers seats and re-exports the readers.+ */+import { COORDINATOR } from './config.js';+import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from './machine.js';+import { Refused } from './refused.js';++/**+ * The agent registered for a worktree path, if any.+ *+ * @param {any} board+ * @param {string} path+ * @returns {any}+ */+export function agentAt(board, path) {+ const agent = board.db.prepare('SELECT * FROM agent WHERE agent_path = ?').get(path);+ return withModel(board, agent);+}++/** Read the model label kept beside other board metadata, avoiding any board-schema migration. */+export function agentModel(board, id) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_model:${id}`)?.meta_value ?? null;+}++/** Attach an agent's model to a row from the legacy stable agent table. */+export function withModel(board, agent) {+ return agent ? { ...agent, agent_model: agentModel(board, agent.agent_id) } : agent;+}++/** Save or clear a model label without changing the shared SQLite schema. */+export function saveAgentModel(board, id, model) {+ if (model === null || model === undefined) {+ board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(`agent_model:${id}`);+ return;+ }+ board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?) ON CONFLICT(meta_key) DO UPDATE SET meta_value = excluded.meta_value')+ .run(`agent_model:${id}`, model);+}++/**+ * Every registered agent, oldest first.+ *+ * @param {any} board+ * @returns {any[]}+ */+export function listAgents(board) {+ return board.db.prepare('SELECT * FROM agent ORDER BY rowid').all().map((agent) => withModel(board, agent));+}++/**+ * The route an agent joined on; strong for the coordinator and for ids the board does not know.+ *+ * @param {any} board+ * @param {string} agentId+ * @returns {string}+ */+export function routeOf(board, agentId) {+ return board.db.prepare('SELECT agent_route FROM agent WHERE agent_id = ?').get(agentId)?.agent_route ?? 'strong';+}++/**+ * The id an engine-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}+ */+export function newSeatId(board, lane, total, named) {+ if (named === undefined) return firstFreeSeatId(board, lane, total);+ const number = typeof named === 'string' && named.startsWith(`${lane}-`) ? named.slice(lane.length + 1) : '';+ if (!/^[1-9][0-9]{0,8}$/.test(number) || Number(number) <= total || board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(named)) {+ throw new Refused('BAD_SEAT_ID', `a new ${lane} seat is named ${lane}-<n> above the lane's count and not yet taken; register again without a name`);+ }+ return named;+}++/**+ * The lane's first seat number above its count that no seat holds yet.+ *+ * @param {any} board+ * @param {string} lane+ * @param {number} total+ * @returns {string}+ */+function firstFreeSeatId(board, lane, total) {+ let n = total + 1;+ while (board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(`${lane}-${n}`)) n += 1;+ return `${lane}-${n}`;+}++/**+ * The seat that created this one, as its engine-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 machine registration lineage a relay-enrolled seat descends from: the person-set coordinator+ * token of the machine that made its line (#579), or null when it was never recorded.+ *+ * @param {any} board+ * @param {string} id+ * @returns {string | null}+ */+export function seatLineage(board, id) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_lineage:${id}`)?.meta_value ?? null;+}++/**+ * The id the next registration in a lane gets when it names none, for a creator that must+ * predict it before sealing the move (the relay receipt names the target seat).+ *+ * @param {any} board+ * @param {string} lane+ * @returns {string}+ */+export function nextSeatId(board, lane) {+ const { total } = board.db.prepare('SELECT COUNT(*) AS total FROM agent WHERE agent_lane = ?').get(lane);+ return firstFreeSeatId(board, lane, total);+}++/**+ * Run board work under linked-board verifier standing (#579): a relay replica replaying an+ * engine-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, person?: boolean, lineage?: string | null }} standing+ * @param {() => T} work+ * @returns {T}+ */+export function withVerifierStanding(board, standing, work) {+ const previous = board.verifierStanding;+ board.verifierStanding = { root: standing.root === true, person: standing.person === true,+ lineage: typeof standing.lineage === 'string' ? standing.lineage : null };+ try { return work(); }+ finally {+ if (previous === undefined) delete board.verifierStanding;+ else board.verifierStanding = previous;+ }+}++/**+ * Why this seat may not verify the builder's item on a linked board, or null when it may. The+ * seat's creators are walked up to the coordinator: the builder, a join no seat made (`machine`),+ * or a seat registered before engine 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+ * @param {number} itemId+ * @returns {Refused | null}+ */+export function standingProblem(board, verifier, builder, itemId) {+ const standing = board.verifierStanding;+ if (!standing || (board.executionEngineVersion ?? ENGINE_VERSION) < VERIFIER_STANDING_ENGINE) return null;+ const refuse = (why) => new Refused('VERIFIER_STANDING',+ `${verifier} cannot verify work built by ${builder} on this linked board: ${why}; ask the coordinator to make an independent verifier from the main checkout: pullboard worktree <lane> --model "<model name>"`);+ if (builder === COORDINATOR) {+ // The person stands above every seat; otherwise only a seat from another machine's line may.+ if (standing.person) return null;+ const refuseOwn = (why) => new Refused('VERIFIER_STANDING', `${verifier} cannot verify work the coordinator built on this linked board: ${why}; a seat from another machine's registration lineage, or the person, verifies it`);+ const built = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_lineage:${itemId}`)?.meta_value ?? null;+ const lineage = seatLineage(board, verifier);+ if (!built || !lineage) return refuseOwn('the machine lineage of the build or of this seat was not recorded');+ if (built === lineage) return refuseOwn('this seat shares the building machine\'s registration lineage');+ for (let seat = verifier, seen = new Set(); seat !== COORDINATOR; seat = agentCreator(board, seat)) {+ if (seen.has(seat) || !seatEnrolled(board, seat)) return refuseOwn(`${seat} was not enrolled through the relay`);+ seen.add(seat);+ }+ return null;+ }+ const seen = new Set();+ for (let seat = verifier; ;) {+ if (seat === COORDINATOR) {+ return standing.root || seat !== verifier ? null+ : refuse('the coordinator credential was not set up by the person; run pullboard relay on in the main checkout once');+ }+ if (seen.has(seat)) return refuse('its line of creating seats loops');+ seen.add(seat);+ const creator = agentCreator(board, seat);+ if (creator === 'machine') return refuse(`${seat} joined without a creating seat`);+ if (creator === builder) return refuse(`${seat} was created by the builder`);+ if (creator === null || !seatEnrolled(board, seat)) {+ return refuse(`${seat} was not enrolled by its creating seat through the relay`);+ }+ seat = creator;+ }+}