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.

Merge branch 'main' into core/343-opus

Corey Olsonad4eda109063
diff --cc docs/formats.md
index 7f49e655,51ff039d..172ff6cd
--- a/docs/formats.md
+++ b/docs/formats.md
@@@ -113,7 -113,7 +113,7 @@@ The board file is in the repository's G
| `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` | `71` | `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` | `72` | `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` | `73` | `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 -->
Relay transport capability `apiVersion: 2` is independent of these versions and
@@@ -192,8 -192,8 +192,10 @@@ The relay outbox (#922, opt in with `re
Engine 69 (`REVIEW_SKIP_ENGINE`) lets `reserveNextReview` carry `skipIds`: the submitted items the reviewer's own agent session built, which `pullboard next --verify` never offers it. A move with a non-empty `skipIds` needs engine 69, so an older reader refuses it instead of reserving a different item; moves without `skipIds`, and every move recorded before engine 69, replay as before.
- Engine 71 (`PEOPLE_ENGINE`) names people and lets approvers alone act as the person. The relay stamps each stored record's sender with the GitHub login behind it, the engine the sender declared and, on a board that names approvers, `approver: true|false` for a person sender. Replaying a move made at engine 71 or later, every event it writes carries `person`, that login, beside `event_by`, the agent or seat. A move that carries out a recorded phone request carries the request sender's login instead, and a `relay_refused` event carries the login of the person who tried the move or request. `pullboard.json` may list `approvers`, GitHub logins, at most fifty; leaving it out keeps today's behaviour. On a board that names them, every replica refuses with `NOT_APPROVER` a person move (a row or sentinel decision, an answer, hold or fact as the person, a person request shout) or a phone request to answer, hold or decide rows whose sender is not an approver, and the relay refuses an unlink or snapshot replacement from anyone else. A record whose seal no key opens, from an engine no newer than the replica's, is set aside as `relay_refused` with code `RELAY_SEAL`, and replay goes on; one from a newer engine still asks for an upgrade.
+ Engine 72 (`COORDINATOR_HOLD_ENGINE`) holds a linked board's coordinator at one main checkout at a time. Each linked main checkout sends its coordinator moves under its own root coordinator credential, whose lineage the relay authenticates. The board keeps the holding lineage in `board_meta` as `coordinator_holder`, with the holder's name, `computer` and the end of its relay machine id. The first coordinator move at engine 72 takes the hold; a later one from another lineage is refused with `COORDINATOR_HELD`, naming the holder. Registering seats and recording the coordinator's path stay open to every linked main checkout. `takeCoordinator`, sent by `pullboard takeover` in a linked main checkout, moves the hold to the sender and logs a `coordinator-takeover` event naming both holders. Moves recorded before engine 72, and every move on an unlinked board, replay as before.
+
++Engine 73 (`PEOPLE_ENGINE`) names people and lets approvers alone act as the person. The relay stamps each stored record's sender with the GitHub login behind it, the engine the sender declared and, on a board that names approvers, `approver: true|false` for a person sender. Replaying a move made at engine 73 or later, every event it writes carries `person`, that login, beside `event_by`, the agent or seat. A move that carries out a recorded phone request carries the request sender's login instead, and a `relay_refused` event carries the login of the person who tried the move or request. `pullboard.json` may list `approvers`, GitHub logins, at most fifty; leaving it out keeps today's behaviour. On a board that names them, every replica refuses with `NOT_APPROVER` a person move (a row or sentinel decision, an answer, hold or fact as the person, a person request shout) or a phone request to answer, hold or decide rows whose sender is not an approver, and the relay refuses an unlink or snapshot replacement from anyone else. A record whose seal no key opens, from an engine no newer than the replica's, is set aside as `relay_refused` with code `RELAY_SEAL`, and replay goes on; one from a newer engine still asks for an upgrade.
+
The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.
A linked board requires at least engine 48 after issuing any agent token or machine credential, including
revoked or expired ones; before engine 48 these minimums were 3 and 6. The minimum survives reopening the auth database;
diff --cc relay/journal.js
index d17021e5,78136642..9492cf09
--- a/relay/journal.js
+++ b/relay/journal.js
@@@ -84,10 -84,7 +84,10 @@@ export function createRelayJournal({ di
db.prepare('UPDATE journal_meta SET value=? WHERE key=?').run(String(FORMAT), 'format');
// Engine-27 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.
- // Engine-71 people (#343): the GitHub login behind each record, and whether that person was one of the
- for (const [column, type] of [['sender_policy', 'INTEGER'], ['sender_root', 'INTEGER'], ['sender_lineage', 'TEXT'], ['registration', 'TEXT']]) {
++ // Engine-73 people (#343): the GitHub login behind each record, and whether that person was one of the
+ // board's approvers when it arrived. Older records keep them empty and replay as they did.
+ for (const [column, type] of [['sender_policy', 'INTEGER'], ['sender_root', 'INTEGER'], ['sender_lineage', 'TEXT'], ['registration', 'TEXT'],
+ ['sender_login', 'TEXT'], ['sender_approver', 'INTEGER'], ['sender_engine', 'INTEGER']]) {
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
diff --cc src/board.js
index 5ce29d56,3a887d6a..0b6717bc
--- a/src/board.js
+++ b/src/board.js
@@@ -529,8 -529,8 +529,8 @@@ export function atomic(board, work)
export function logEvent(board, by, kind, itemId, detail = {}, at) {
const model = agentModel(board, by);
const isAgent = Boolean(board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(by));
- const recorded = (board.executionEngineVersion ?? ENGINE_VERSION) >= 8 && isAgent
- ? { ...detail, model: model ?? 'unknown' } : detail;
+ const recorded = { ...detail, ...((board.executionEngineVersion ?? ENGINE_VERSION) >= 8 && isAgent ? { model: model ?? 'unknown' } : {}),
- ...(board.movePerson ? { person: board.movePerson } : {}) }; // The person behind a relayed move, from engine 71 (engine.js) [E3].
++ ...(board.movePerson ? { person: board.movePerson } : {}) }; // The person behind a relayed move, from engine 73 (engine.js) [E3].
const inserted = board.db
.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)')
.run(at ? at.toISOString() : now(board), by, kind, itemId, JSON.stringify(recorded));
@@@ -539,8 -539,8 +539,8 @@@
}
/** Log an authenticated relay refusal without making an item, shout or verdict move [H2,H16]. */
-export function recordRelayRefusal(board, { by, sequence, kind, operation, actor, code, itemId = null }) {
- logEvent(board, by, 'relay_refused', itemId, { sequence, kind, operation, actor, code });
+export function recordRelayRefusal(board, { by, sequence, kind, operation, actor, code, itemId = null, person = null }) {
- logEvent(board, by, 'relay_refused', itemId, { sequence, kind, operation, actor, code, ...(person ? { person } : {}) }); // who tried it, from engine 71 [E3]
++ logEvent(board, by, 'relay_refused', itemId, { sequence, kind, operation, actor, code, ...(person ? { person } : {}) }); // who tried it, from engine 73 [E3]
}
/**
diff --cc src/engine.js
index 0203d98c,208badde..ed5129dd
--- a/src/engine.js
+++ b/src/engine.js
@@@ -354,8 -350,6 +356,8 @@@ export function applyEngineMove(board,
board.executionEngineVersion = move.engine;
const firstEvent = board.emittedEvents?.length ?? 0;
if (enrollment !== null) board.relayEnrollment = enrollment;
- // From engine 71 every event of the move names its person; an older move replays without one.
++ // From engine 73 every event of the move names its person; an older move replays without one.
+ if (person !== null && move.engine >= PEOPLE_ENGINE) board.movePerson = person;
try {
const execute = () => store.atomic(board, () => {
const problem = requestMoveProblem(board, move);
diff --cc src/people-engine.js
index 257aab0f,00000000..cd8af068
mode 100644,000000..100644
--- a/src/people-engine.js
+++ b/src/people-engine.js
@@@ -1,2 -1,0 +1,2 @@@
+/** First engine for moves that name their person and boards whose approvers alone act as the person (#343) [E3,E4,E20]. */
- export const PEOPLE_ENGINE = 71;
++export const PEOPLE_ENGINE = 73;
diff --cc src/relay-requests.js
index f599eaf1,9041fad1..81d0a10c
--- a/src/relay-requests.js
+++ b/src/relay-requests.js
@@@ -21,30 -20,6 +21,30 @@@ export function personRequestRecords(bo
return row ? JSON.parse(row.meta_value) : [];
}
+/**
- * The GitHub login the relay stamped on a record from engine 71 on, or null: the person who made or tried it [E3].
++ * The GitHub login the relay stamped on a record from engine 73 on, or null: the person who made or tried it [E3].
+ *
+ * @param {any} sender
+ * @returns {string | null}
+ */
+export function relayPerson(sender) {
+ return typeof sender?.login === 'string' && sender.engine >= PEOPLE_ENGINE ? sender.login : null;
+}
+
+/**
+ * The person whose phone asked for this move, when the move carries out a recorded phone request, or null. The
+ * computer that carries the request out sends the move, but the move is the phone person's [E3].
+ *
+ * @param {any} board
+ * @param {any} move
+ * @returns {string | null}
+ */
+export function requestPerson(board, move) {
+ if (!move?.personRequest || requestMoveProblem(board, move, { checkExecutorLease: false })) return null;
+ const record = personRequestRecords(board).find((entry) => entry.id === move.personRequest.id && !entry.duplicateOf);
+ try { return relayPerson(JSON.parse(record.received).sender); } catch { return null; }
+}
+
/** Persist request receipts inside the caller's existing board transaction. */
function save(board, records) {
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(INDEX, JSON.stringify(records));
diff --cc test/team.test.js
index 2ffaa210,ac0b51d0..c8966e7d
--- a/test/team.test.js
+++ b/test/team.test.js
@@@ -22,13 -19,10 +22,16 @@@ import { snapshotState } from '../relay
import { unpackRelease } from './release-archive.js';
import { relayClientFixture } from './relay-client-fixture.js';
import { relayFixtureChild } from './relay-client-fixture.js';
+import { runFixtureGit } from './fixture-child.js';
+import { decodeBoardKey } from '../src/seal.js';
+import { seal } from '../src/seal.js';
+import { ENGINE_VERSION as PEOPLE_VERSION } from '../src/machine.js';
+ import { resolve } from 'node:path';
+ import { relayWorkBudgetMs } from './relay-budget.js';
+ import { hostname } from 'node:os';
+const CLI = join(import.meta.dirname, '..', 'bin', 'pullboard.js');
+
const helpers = createE2eHelpers();
after(helpers.cleanup);
@@@ -479,159 -473,75 +482,232 @@@ test('an older pushed landing shows sta
assert.equal(withBoard(box.repo, board => store.getItem(board, 1)).item_merged_commit, submitted);
});
+/** A person's own session, through the stand-in GitHub's real OAuth, signed in as `login`. */
+async function personSession(box, login) {
+ box.providerState.signer = login;
+ try {
+ const start = await fetch(box.origin + '/auth/github/start', { redirect: 'manual' });
+ const binding = start.headers.getSetCookie().find((value) => value.startsWith('pb_oauth_binding=')).split(';')[0];
+ const approved = await fetch(start.headers.get('location'), { redirect: 'manual' });
+ const callback = await fetch(approved.headers.get('location'), { redirect: 'manual', headers: { cookie: binding } });
+ assert.equal(callback.status, 303, `${login} signs in`);
+ return callback.headers.getSetCookie().find((value) => value.startsWith('pb_session=')).split(';')[0].slice('pb_session='.length);
+ } finally { box.providerState.signer = 'alice'; }
+}
+
+/** Call the relay as one credential, returning the status and document. */
+async function relayCall(box, token, method, path, body) {
+ const response = await fetch(box.origin + path, { method, headers: { authorization: 'Bearer ' + token, 'x-pullboard-engine': String(PEOPLE_VERSION),
+ ...(body ? { 'content-type': 'application/json' } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
+ let document = null;
+ try { document = await response.json(); } catch { /* An empty answer stays null. */ }
+ return { status: response.status, document };
+}
+
+/** Seal one phone request the way the paired view does and send it with this person's session. */
+async function phoneRequest(box, session, move) {
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const head = await relayCall(box, session, 'GET', '/api/v2/boards/' + link.board + '/state');
+ assert.equal(head.status, 200, `this person reads the board: ${JSON.stringify(head.document)}`);
+ const events = await relayCall(box, session, 'GET', `/api/v1/boards/${link.board}/events?after=${head.document.state.sequence}`);
+ const sequence = Math.max(head.document.state.sequence, ...(events.document.events ?? []).map((event) => event.event_id)) + 1;
+ const document = { version: 1, type: 'person-request', id: randomUUID(), move };
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(document)), { boardId: link.board, kind: 'request', sequence })).toString('base64url');
+ const sent = await relayCall(box, session, 'POST', `/api/v1/boards/${link.board}/requests`, { sequence, sealed });
+ assert.equal(sent.status, 200, `the relay stores the sealed request: ${JSON.stringify(sent.document)}`);
+ return document.id;
+}
+
+/** The phone requests this board has received, by id. */
+async function receivedRequests(box) {
+ assert.equal((await box.cli('status')).code, 0, 'the coordinator reads the relay');
+ const meta = (await box.cli('export')).document.tables.board_meta.find((row) => row.meta_key === 'relay_person_requests');
+ return Object.fromEntries((meta ? JSON.parse(meta.meta_value) : []).map((record) => [record.id, record]));
+}
+
+/** Two people with write access to the fixture repository, alice and bob, and alice's linked board. */
+async function teamBoard(t, approvers) {
+ const box = await relayClientFixture(t);
+ Object.assign(box.providerState, { people: { alice: { id: 7, permission: 'write' }, bob: { id: 8, permission: 'write' } }, signer: 'alice' });
+ if (approvers) {
+ const file = join(box.root, 'pullboard.json');
+ writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, 'utf8')), approvers }, null, 2) + '\n');
+ runFixtureGit(['add', 'pullboard.json'], { cwd: box.root, env: box.env });
+ runFixtureGit(['-c', 'core.hooksPath=/dev/null', 'commit', '-q', '-m', 'chore: name the approvers'], { cwd: box.root, env: box.env });
+ }
+ assert.equal((await box.link()).code, 0, 'alice links the board, signed in as herself');
+ return box;
+}
+
+test('the board knows its people: events name them, approvers decide [E3,E4,E20]', { timeout: 180_000 }, async (t) => { // budget: hang ceiling for two people's real CLI runs and relay calls; not a speed target.
+ const box = await teamBoard(t, ['alice']);
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const alice = await personSession(box, 'alice');
+ const bob = await personSession(box, 'bob');
+ assert.deepEqual((await relayCall(box, alice, 'GET', `/api/v1/boards/${link.board}/approvers`)).document.approvers, ['alice'], 'relay on gave the relay the approvers pullboard.json names');
+
+ // S4c: every move records the person who made it, and the agent if one did.
+ assert.equal((await box.cli('add', box.lane, 'An item alice adds')).code, 0);
+ const bobRoot = join(box.root, '..', 'bob-clone');
+ runFixtureGit(['clone', '-q', box.root, bobRoot], { cwd: box.root, env: box.env });
+ runFixtureGit(['remote', 'set-url', 'origin', '[email protected]:fixture/repository.git'], { cwd: bobRoot, env: box.env });
+ const bobHome = join(box.root, '..', 'bob-home');
+ const bobEnv = { ...box.env, HOME: bobHome, PULLBOARD_HOME: join(bobHome, '.pullboard'), PULLBOARD_MACHINE_HOME: join(bobHome, 'machine') };
+ cpSync(join(box.root, '.git', 'pullboard'), join(bobRoot, '.git', 'pullboard'), { recursive: true, filter: (path) => !path.endsWith('.lock') });
+ mkdirSync(join(bobEnv.PULLBOARD_HOME, 'relay-keys'), { recursive: true, mode: 0o700 });
+ cpSync(box.keyFile, join(bobEnv.PULLBOARD_HOME, 'relay-keys', link.board + '.key'));
+ box.providerState.signer = 'bob';
+ const bobOn = await relayFixtureChild(bobRoot, bobEnv, [CLI, 'relay', 'on', '--url', box.origin, '--json']);
+ box.providerState.signer = 'alice';
+ assert.equal(bobOn.code, 0, `bob signs in as himself on his own computer: ${bobOn.stderr}`);
+ assert.equal((await relayFixtureChild(bobRoot, bobEnv, [CLI, 'add', box.lane, 'An item bob adds', '--json'])).code, 0, 'bob adds an item');
+ const exported = (await box.cli('export')).document.tables;
+ const events = exported.event;
+ const madeBy = (title) => {
+ const id = exported.item.find((item) => item.item_title === title)?.item_id;
+ return events.filter((event) => event.event_kind === 'add' && event.item_id === id).map((event) => JSON.parse(event.event_detail).person);
+ };
+ assert.deepEqual(madeBy('An item alice adds'), ['alice'], 'alice’s move names alice');
+ assert.deepEqual(madeBy('An item bob adds'), ['bob'], 'bob’s move names bob');
+ assert.ok(events.filter((event) => event.event_kind === 'add').every((event) => event.event_by), 'each move still names the agent or seat that made it');
+
+ // S4b: only an approver answers the person's decisions, and only an approver decides rows.
+ const asked = await box.cli('shout', 'person', 'Ship the health endpoint as plain text or JSON?', '--decision');
+ assert.equal(asked.code, 0);
+ const decision = asked.document.id ?? asked.document.shout_id ?? asked.document.result?.id;
+ const fromBob = await phoneRequest(box, bob, { verb: 'answer', item: Number(decision), args: { text: 'JSON' } });
+ const fromAlice = await phoneRequest(box, alice, { verb: 'answer', item: Number(decision), args: { text: 'JSON' } });
+ const requests = await receivedRequests(box);
+ assert.equal(requests[fromBob].status, 'refused', 'bob, a writer but not an approver, cannot answer as the person');
+ assert.equal(requests[fromBob].error.code, 'NOT_APPROVER');
+ assert.notEqual(requests[fromAlice].status, 'refused', 'alice, an approver, answers as the person');
+ const rowFromBob = await phoneRequest(box, bob, { verb: 'spec-approve', args: { ids: 'G1' } });
+ assert.equal((await receivedRequests(box))[rowFromBob].error?.code, 'NOT_APPROVER', 'bob cannot approve a row');
+
+ // E4: a change to the list takes effect only once an existing approver makes it.
+ assert.equal((await relayCall(box, bob, 'PUT', `/api/v1/boards/${link.board}/approvers`, { approvers: ['bob'] })).document.error?.code, 'NOT_APPROVER', 'bob cannot make himself an approver');
+ assert.deepEqual((await relayCall(box, bob, 'GET', `/api/v1/boards/${link.board}/approvers`)).document.approvers, ['alice']);
+
+ // S9: a move no member can open is set aside, and only an approver unlinks the board or replaces its snapshot.
+ const bobMachine = JSON.parse(readFileSync(join(bobRoot, '.git', 'pullboard', 'relay.json'), 'utf8')).token;
+ const head = await relayCall(box, alice, 'GET', '/api/v2/boards/' + link.board + '/state');
+ const after = await relayCall(box, alice, 'GET', `/api/v1/boards/${link.board}/events?after=${head.document.state.sequence}`);
+ const next = Math.max(head.document.state.sequence, ...(after.document.events ?? []).map((event) => event.event_id)) + 1;
+ const junk = await relayCall(box, bobMachine, 'POST', `/api/v1/boards/${link.board}/moves`, { sequence: next, sealed: randomBytes(64).toString('base64url') });
+ assert.equal(junk.status, 200, 'a member’s credential can store bytes no key opens');
+ const afterJunk = await box.cli('add', box.lane, 'After the junk');
+ assert.equal(afterJunk.code, 0, `replay sets the unopenable move aside and the board moves on: ${afterJunk.stderr ?? ''}${JSON.stringify(afterJunk.document ?? {}).slice(0, 600)}`);
+ assert.ok((await box.cli('export')).document.tables.event.some((event) => event.event_kind === 'relay_refused' && JSON.parse(event.event_detail).sequence === next), 'the set-aside move is on the record');
+ const deleted = await relayCall(box, bob, 'DELETE', `/api/v1/boards/${link.board}`);
+ assert.equal(deleted.document?.error?.code, 'NOT_APPROVER', 'bob cannot unlink the board');
+ const replaced = await relayCall(box, bobMachine, 'PUT', `/api/v1/boards/${link.board}/state`, { sequence: next, sealed: randomBytes(64).toString('base64url') });
+ assert.equal(replaced.document?.error?.code, 'NOT_APPROVER', 'bob’s computer cannot replace the snapshot');
+ assert.equal((await box.cli('status')).code, 0, 'alice’s board still reads');
+});
+
+test('the board knows its people: a phone move names the phone’s person, refused or not [E3,E4]', { timeout: 180_000 }, async (t) => { // budget: hang ceiling for real CLI runs and relay calls; not a speed target.
+ const box = await teamBoard(t, ['alice']);
+ const bob = await personSession(box, 'bob');
+ // Bob's phone adds an item; alice's computer carries it out, so the move is sent with alice's credential.
+ const title = 'An item from bob’s phone';
+ const added = await phoneRequest(box, bob, { verb: 'add', args: { lane: box.lane, title } });
+ const asked = await box.cli('shout', 'person', 'Plain text or JSON?', '--decision');
+ assert.equal(asked.code, 0);
+ const decision = asked.document.id ?? asked.document.shout_id ?? asked.document.result?.id;
+ const denied = await phoneRequest(box, bob, { verb: 'answer', item: Number(decision), args: { text: 'JSON' } });
+ const requests = await receivedRequests(box);
+ assert.equal(requests[added].status, 'done', 'bob’s phone adds the item');
+ assert.equal(requests[denied].error?.code, 'NOT_APPROVER', 'bob’s phone cannot answer as the person');
+ const tables = (await box.cli('export')).document.tables;
+ const id = tables.item.find((item) => item.item_title === title)?.item_id;
+ const add = tables.event.find((event) => event.event_kind === 'add' && event.item_id === id);
+ const refused = tables.event.find((event) => event.event_kind === 'relay_refused' && JSON.parse(event.event_detail).sequence === requests[denied].sequence);
+ assert.ok(add && refused, 'both are on the record');
+ assert.equal(JSON.parse(add.event_detail).person, 'bob', 'the add names bob, whose phone asked for it, not alice, whose computer carried it out');
+ assert.equal(JSON.parse(refused.event_detail).person, 'bob', 'the refused answer still names bob, who tried it');
+});
+
+test('a board that names no approvers takes person moves as before [E4]', { timeout: 120_000 }, async (t) => { // budget: hang ceiling for real CLI runs and relay calls; not a speed target.
+ const box = await teamBoard(t, null);
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const bob = await personSession(box, 'bob');
+ assert.equal((await relayCall(box, bob, 'GET', `/api/v1/boards/${link.board}/approvers`)).document.approvers, null, 'the relay holds no approvers for this board');
+ const asked = await box.cli('shout', 'person', 'Plain text or JSON?', '--decision');
+ const decision = asked.document.id ?? asked.document.shout_id ?? asked.document.result?.id;
+ const fromBob = await phoneRequest(box, bob, { verb: 'answer', item: Number(decision), args: { text: 'JSON' } });
+ assert.notEqual((await receivedRequests(box))[fromBob].status, 'refused', 'any writer’s session answers as the person, as today');
+});
++
+ test('one coordinator per board across machines [E19]', { timeout: relayWorkBudgetMs(12) }, async t => { // budget: hang ceiling for two linked devices' real CLI and relay round trips; not a speed target.
+ const box = await relayClientFixture(t);
+ await box.link();
+ const pairing = await box.cli('relay', 'pair');
+ const other = await box.otherDeviceJoin(pairing.document.code);
+ /** A refusal's code and message as the CLI reports them. */
+ const refusal = result => ({ code: result.document?.error?.code, message: String(result.document?.error?.message ?? '') });
+
+ // The first device to act as coordinator holds it; the board keeps working there as it does today.
+ assert.equal((await box.cli('add', box.lane, 'Planned on the first machine')).code, 0, 'the first machine coordinates');
+ assert.equal((await box.cli('add', box.lane, 'Still planned on the first machine')).code, 0, 'the holder keeps coordinating');
+
+ // On one machine, the main checkout is held by one agent session at a time; takeover passes it between sessions.
+ /** Run the first machine's real CLI from a named agent session. */
+ const inSession = (session, ...args) => relayFixtureChild(box.root, { ...box.env, CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: session },
+ [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args, '--json']);
+ assert.equal((await inSession('first-session', 'add', box.lane, 'Planned in the first session')).code, 0, 'one agent session coordinates');
+ assert.equal(refusal(await inSession('second-session', 'add', box.lane, 'Planned in a second session')).code, 'NOT_YOUR_CHECKOUT',
+ 'a second session acting as coordinator in the same main checkout is refused');
+ assert.equal((await inSession('second-session', 'takeover')).code, 0, 'takeover passes the main checkout to the second session');
+ assert.equal((await inSession('second-session', 'add', box.lane, 'Planned in the second session after takeover')).code, 0, 'the new session coordinates');
+ assert.equal(refusal(await inSession('first-session', 'add', box.lane, 'Planned again in the first session')).code, 'NOT_YOUR_CHECKOUT',
+ 'the earlier session is refused after the takeover');
+
+ // A second machine's main checkout acting as coordinator is refused, by name.
+ const second = await other.cli('add', box.lane, 'Planned on the second machine');
+ assert.notEqual(second.code, 0, 'a second coordinator is refused');
+ assert.equal(refusal(second).code, 'COORDINATOR_HELD');
+ const firstName = `computer ${JSON.parse(readFileSync(box.linkFile, 'utf8')).machine.slice(-8)}`;
+ const secondName = `computer ${other.machine.slice(-8)}`;
+ assert.notEqual(firstName, secondName, 'the two linked computers have different names');
+ assert.ok(refusal(second).message.includes(firstName), `the refusal names the holding computer: ${refusal(second).message}`);
+ assert.doesNotMatch(refusal(second).message, new RegExp(hostname(), 'u'), 'the name carries no host name');
+ assert.match(refusal(second).message, /pullboard takeover/u, 'the refusal names the takeover');
+
+ // Takeover passes the coordinator to the second machine, and the first is then refused by name.
+ const taken = await other.cli('takeover');
+ assert.equal(taken.code, 0, `takeover passes the coordinator: ${JSON.stringify(taken.document)}`);
+ assert.equal(taken.document.coordinator, secondName, 'takeover reports the new holder');
+ assert.equal(taken.document.previous, firstName, 'takeover reports the holder it replaced');
+ assert.equal((await other.cli('add', box.lane, 'Planned on the second machine after takeover')).code, 0, 'the new holder coordinates');
+ const first = await box.cli('add', box.lane, 'Planned again on the first machine');
+ assert.equal(refusal(first).code, 'COORDINATOR_HELD', 'the earlier holder is now the second coordinator');
+ assert.ok(refusal(first).message.includes(secondName), `the refusal names the new holder: ${refusal(first).message}`);
+
+ // Both replicas agree on the items each holder made, and on no others.
+ for (const device of [box, other]) {
+ const titles = (await device.cli('list')).document.items.map(item => item.item_title);
+ assert.deepEqual(titles.filter(title => title.startsWith('Planned') || title.startsWith('Still')).sort(),
+ ['Planned in the first session', 'Planned in the second session after takeover', 'Planned on the first machine',
+ 'Planned on the second machine after takeover', 'Still planned on the first machine']);
+ }
+ });
+
+ test('an agent session on a computer that does not hold the coordinator takes it over [E19]', { timeout: relayWorkBudgetMs(12) }, async t => { // budget: hang ceiling for two linked devices' real CLI and relay round trips; not a speed target.
+ const box = await relayClientFixture(t);
+ await box.link();
+ const pairing = await box.cli('relay', 'pair');
+ const other = await box.otherDeviceJoin(pairing.document.code);
+ /** Run the second computer's real CLI from a named agent session. */
+ const inSession = (...args) => relayFixtureChild(other.root, { ...other.env, CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'second-computer-session' },
+ [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args, '--json']);
+ assert.equal((await box.cli('add', box.lane, 'Planned on the holding computer')).code, 0, 'the first computer holds the coordinator');
+ const held = await inSession('add', box.lane, 'Planned before the takeover');
+ assert.equal(held.document?.error?.code, 'COORDINATOR_HELD', 'the second computer is refused by name');
+ assert.match(held.document.error.message, /pullboard takeover/u, 'the refusal names the takeover');
+ const taken = await inSession('takeover');
+ assert.equal(taken.code, 0, `the takeover the refusal names succeeds from the agent session: ${JSON.stringify(taken.document)}`);
+ assert.equal(taken.document.coordinator, `computer ${other.machine.slice(-8)}`, 'the second computer now holds the coordinator');
+ assert.equal((await inSession('add', box.lane, 'Planned after the takeover')).code, 0, 'the new holder coordinates');
+ assert.equal((await box.cli('add', box.lane, 'Planned again on the first computer')).document?.error?.code, 'COORDINATOR_HELD', 'the earlier holder is refused');
+ });