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.

feat(cli): bind a checkout to one agent session [B3,B7]

Corey Olsonad7b68f51369
diff --git a/docs/api.md b/docs/api.md
index 197b5b65..b5ed14f1 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -20,6 +20,7 @@ When `add` or `edit` supplies a new nonempty check, Pullboard measures it once i
| `init` | `version:number`, `root:string`, `notes:array` |
| `hooks` | `version:number`, `notes:array` |
| `join` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string` |
+| `takeover` | `version:number`, `agent:string`, `path:string` |
| `worktree` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `branch:string`, `prompt:string` |
| `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `stale:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `dirty:number`, `next:string` |
| `whoami` | `version:number`, `id:string`, `lane:string`, `path:string` |
@@ -88,6 +89,8 @@ When `add` or `edit` supplies a new nonempty check, Pullboard measures it once i
`join` and `worktree` accept an optional free-text `--family` declaration. Rejoining the same worktree preserves its agent id; a supplied family updates the declaration, while omitting `--family` preserves it. `resume` includes it as `me.family`; `show` includes `item_builder_family` and each verdict's `verdict_verifier_family`. These recorded fields are `null` when the agent did not declare a family, and later declarations do not rewrite prior submissions or verdicts.
+Each checkout is bound to the first agent session that writes there. The local Git directory holds only its session digest, agent id and timestamp; bindings are absent from board exports and relay snapshots. Another agent session gets `NOT_YOUR_CHECKOUT` and the command to make its own worktree. The same agent starting a new session runs `pullboard takeover`; the existing ordered shout records the takeover, addressed to the person for the main checkout or the coordinator for a lane checkout. Markerless terminals, reads, the view and person requests keep their existing behavior. A shout or decision addressed to its sender is refused with `SELF_SHOUT`.
+
`status.reviewQueue` contains `pending`, `reviewing` (distinct agents with live review leases), `reserved`, `oldestSubmittedAt` and `ageMs`. Age starts at each outstanding item's latest submit event; reserving or renewing its review does not reset it. An empty queue has `oldestSubmittedAt: null` and `ageMs: 0`.
When outstanding reviews reach `verify.reviewRatio` times the active reviewers (default 3, with zero reviewers counting as one), `next` first offers a review the agent may take. This creates no claim or reservation. Its additive v1 `offer` has the review's `item` id, exact `command` to reserve it, `queue` and `ratio`; `build` previews the otherwise available build or is `null`. `next --verify <id>` reserves explicitly. `next --build` claims explicitly; a fresh claim's event detail records `reviewSkipped` with the offered id (or `null`), ratio and queue snapshot. Renewing an existing claim creates no new skip.
diff --git a/src/agent-session.js b/src/agent-session.js
new file mode 100644
index 00000000..d94020ae
--- /dev/null
+++ b/src/agent-session.js
@@ -0,0 +1,50 @@
+/** A checkout belongs to one local agent session; bindings never enter the shared board [B3,B7]. */
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { takeResource } from './resources.js';
+import { Refused } from './refused.js';
+
+/** Keep each worktree's binding in its own Git directory rather than the shared common directory. */
+export function checkoutSessionFile(info) {
+ return join(info.gitDir, 'pullboard-checkout-session.json');
+}
+
+/** Read only a digest and local agent identity; damaged bindings need an explicit takeover. */
+function readBinding(file, takeover) {
+ if (!existsSync(file)) return null;
+ try {
+ const value = JSON.parse(readFileSync(file, 'utf8'));
+ if (value.version !== 1 || typeof value.agent !== 'string' || !/^[a-f0-9]{64}$/.test(value.digest) || !Number.isFinite(Date.parse(value.at))) throw new Error('invalid binding');
+ return value;
+ } catch {
+ if (takeover) return null;
+ throw new Refused('CHECKOUT_SESSION', 'this checkout’s local session binding is unreadable; run pullboard takeover from the same agent’s new session');
+ }
+}
+
+/** Serialize local binding changes, record an explicit takeover, and replace complete JSON atomically. */
+export async function bindLocalSession(info, { agent, digest, takeover = false, recordTakeover, keepLease = false }) {
+ const file = checkoutSessionFile(info);
+ const name = 'checkout-session:' + createHash('sha256').update(info.gitDir).digest('hex');
+ const lease = await takeResource({ name, capacity: 1, scope: 'repo', root: info.root, agent });
+ let retained = false;
+ /** Atomically replace the complete local record, keeping identifiers out of durable state. */
+ function persist(identity) {
+ const pending = file + '.' + process.pid + '.tmp';
+ writeFileSync(pending, JSON.stringify({ version: 1, agent: identity, digest, at: new Date().toISOString() }) + '\n', { mode: 0o600 });
+ renameSync(pending, file);
+ }
+ try {
+ const previous = readBinding(file, takeover);
+ if (!takeover && previous && previous.digest !== digest) {
+ throw new Refused('NOT_YOUR_CHECKOUT', `this checkout belongs to ${previous.agent} in another agent session; run pullboard worktree <lane> and work there, or, if you are the same agent in a new session, run pullboard takeover`);
+ }
+ if (takeover) await recordTakeover();
+ if (!previous || takeover || previous.agent !== agent) persist(agent);
+ if (keepLease) {
+ retained = true;
+ return { release: lease.release, updateAgent: persist };
+ }
+ } finally { if (!retained) lease.release(); }
+}
diff --git a/src/board.js b/src/board.js
index f4fa81bb..77cea6bb 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1346,6 +1346,7 @@ export function verdictsFor(board, id) {
*/
function insertShout(board, { from, to, text, lanes, decision = false, answers = null, evidence = null, request = false, channel = 'terminal' }) {
if (!text.trim()) throw new Refused('EMPTY_SHOUT', 'a shout needs text');
+ if (to === from) throw new Refused('SELF_SHOUT', `a shout cannot be addressed to its sender ${from}; name another agent, a lane or all`);
if (request && (from !== 'person' || to !== COORDINATOR || decision || answers !== null)) {
throw new Refused('BAD_REQUEST', 'a request goes from the person to the coordinator; use the board requests endpoint with its text');
}
diff --git a/src/cli.js b/src/cli.js
index 8ef4d045..124c6472 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -11,7 +11,8 @@ import { parseArgs } from 'node:util';
import * as store from './board.js';
import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
import { doctrineHistory, loadDoctrine } from './doctrine.js';
-import { requirePersonChannel } from './person.js';
+import { agentSessionDigest, requirePersonChannel } from './person.js';
+import { bindLocalSession } from './agent-session.js';
import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
import { digestOf, gateReport, runGate, runShell } from './gate.js';
import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';
@@ -65,6 +66,7 @@ import { executePersonRequests } from './relay-request-execution.js';
const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
export const VERSION = PACKAGE.version;
+const CHECKOUT_LEASES = new WeakMap();
const ALL_HELP = `pullboard ${VERSION}: the local-first work board for teams of coding agents.
Nothing ships until a second agent verifies it.
@@ -76,6 +78,7 @@ Set up
pullboard join <lane> [--route light] [--family <name>] register this worktree as an agent
--route sets which work the model can take; --family records its name
pullboard whoami | lanes | status who you are, the lanes, the board at a glance
+ pullboard takeover rebind this checkout when the same agent starts a new session
pullboard resources local resource holders and their FIFO queues
pullboard settings [gateSlots <n>] view or set this machine's gate slots (default 2)
pullboard view [--port N] [--no-open] every project on this machine in your browser: items, shouts, doctrine,
@@ -177,7 +180,7 @@ Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HE
--json prints one versioned document for every command; refusals include their code and next step.`;
const HELP_NAMES = [
- 'tour', 'init', 'worktree', 'join', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',
+ 'tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',
'serve', 'relay', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'show', 'next',
'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import',
'sweep', 'merged', 'withdraw', 'refreeze', 'hold', 'ledger', 'log', 'spec', 'spec check', 'spec view',
@@ -641,9 +644,60 @@ function withBoard(ctx, work) {
/** Dispatch a board mutation locally, or seal it before any linked replica applies it. */
async function ordered(ctx, board, operation, args) {
- return relayLinked(ctx.info.root)
- ? relayOperation(ctx.info.root, operation, args, ctx.io)
- : store[operation](board, ...args);
+ /** Dispatch while this session holds the checkout, including long-running next/run loops. */
+ const execute = () => relayLinked(ctx.info.root)
+ ? relayOperation(ctx.info.root, operation, args, ctx.io) : store[operation](board, ...args);
+ const digest = agentSessionDigest();
+ if (CHECKOUT_LEASES.has(ctx.io) || !digest || ctx.io.personChannel === 'view' || ctx.io.personRequest) return execute();
+ const agent = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id ?? 'unjoined agent';
+ const lease = await bindLocalSession(ctx.info, { agent, digest, keepLease: true });
+ try { return await execute(); }
+ finally { lease.release(); }
+}
+
+/** Check ownership before sync or command side effects; reads and authenticated person channels keep their identity. */
+async function bindCheckoutSession(io, positionals, values) {
+ if (values.help || values.version || io.personChannel === 'view' || io.personRequest) return;
+ const [command, first] = positionals;
+ if (command === 'takeover' && (positionals.length !== 1 || Object.keys(values).some((key) => key !== 'json'))) {
+ throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');
+ }
+ const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',
+ 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'merged', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];
+ if (!writes.includes(command) && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;
+ if (command === 'answer' && values.as === 'person') return;
+ const digest = agentSessionDigest();
+ if (!digest) {
+ if (command === 'takeover') throw new Refused('AGENT_SESSION', 'takeover belongs to an agent session; run pullboard takeover from the agent’s shell');
+ return;
+ }
+ const info = repoInfo(io.cwd);
+ let agent = info.isMain ? COORDINATOR : null;
+ if (!info.isMain) {
+ const ctx = context(io);
+ agent = withBoard(ctx, (board) => store.agentAt(board, info.root)?.agent_id);
+ if (!agent && command !== 'join') throw new Refused('NOT_JOINED', 'this worktree has not joined a lane; run pullboard join <lane>');
+ }
+ const lease = await bindLocalSession(info, { agent: agent ?? 'unjoined agent', digest, takeover: command === 'takeover', keepLease: !['run', 'next'].includes(command),
+ /** Use an existing ordered shout so takeover has a receipt without changing the board format. */
+ recordTakeover: async () => {
+ const ctx = context(io);
+ await withBoard(ctx, async (board) => {
+ const me = whoAmI(ctx, board);
+ const message = { from: me.id, to: info.isMain ? 'person' : COORDINATOR,
+ text: `${me.id} took over this checkout in a new agent session.`, lanes: laneNames(ctx.config) };
+ if (relayLinked(info.root)) await relayOperation(info.root, 'shout', [message], io);
+ else store.shout(board, message);
+ });
+ },
+ });
+ if (agent) return { lease };
+ /** Replace the temporary identity after a successful first join, retaining the winning session. */
+ return { lease, finish: async () => {
+ const ctx = context(io);
+ const me = withBoard(ctx, (board) => whoAmI(ctx, board));
+ lease.updateAgent(me.id);
+ } };
}
/**
@@ -1054,6 +1108,13 @@ function setupCommands(io, { first, values }) {
return 0;
},
worktree: () => worktreeFor(io, first, values.route ?? 'strong', values.family ?? null),
+ takeover: () => {
+ const ctx = context(io);
+ const me = withBoard(ctx, (board) => whoAmI(ctx, board));
+ io.result?.({ agent: me.id, path: ctx.info.root });
+ io.say(`${me.id} took over this checkout for the current agent session`);
+ return 0;
+ },
};
}
@@ -2338,31 +2399,52 @@ async function runCommand(argv, io) {
export async function main(argv, streams) {
const io = commandOutput(argv, streams);
let sync = true;
+ let parsed;
+ let checkoutSession;
try {
- const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
const command = parsed.positionals[0];
sync = Boolean(command) && !parsed.values.help && !parsed.values.version && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command);
} catch { sync = false; }
- /** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
- const retry = async () => {
- try { await syncRelay(io.cwd, io); }
- catch (error) {
- if (!(error instanceof Refused)) throw error;
- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);
+ if (parsed) {
+ try {
+ checkoutSession = await bindCheckoutSession(io, parsed.positionals, parsed.values);
+ if (checkoutSession?.lease) CHECKOUT_LEASES.set(io, checkoutSession.lease);
}
- };
- if (sync) {
- await retry();
- try { await executePersonRequests(io.cwd, io, main); }
catch (error) {
if (!(error instanceof Refused)) throw error;
- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err('pullboard: ' + error.message);
+ io.refusal(error);
+ io.err(`pullboard: ${error.message}`);
+ io.flush(1);
+ return 1;
+ }
+ }
+ try {
+ /** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
+ const retry = async () => {
+ try { await syncRelay(io.cwd, io); }
+ catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);
+ }
+ };
+ if (sync) {
+ await retry();
+ try { await executePersonRequests(io.cwd, io, main); }
+ catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err('pullboard: ' + error.message);
+ }
}
+ const code = await runCommand(argv, io);
+ if (code === 0) await checkoutSession?.finish?.();
+ if (sync && code === 0) await retry();
+ io.flush(code);
+ return code;
+ } finally {
+ CHECKOUT_LEASES.delete(io);
+ checkoutSession?.lease?.release();
}
- const code = await runCommand(argv, io);
- if (sync && code === 0) await retry();
- io.flush(code);
- return code;
}
/** Result-producing command names, including aliases, for API contract coverage (A1). */
diff --git a/src/json.js b/src/json.js
index 2231fe4f..db6a0067 100644
--- a/src/json.js
+++ b/src/json.js
@@ -14,6 +14,7 @@ export const JSON_SHAPES = {
init: shape({ root: 'string', notes: 'array' }),
hooks: shape({ notes: 'array' }),
join: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string' }),
+ takeover: shape({ agent: 'string', path: 'string' }),
worktree: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', branch: 'string', prompt: 'string' }),
resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', stale: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: 'string' }),
whoami: shape({ id: 'string', lane: 'string', path: 'string' }),
diff --git a/src/person.js b/src/person.js
index fe0972a2..15500649 100644
--- a/src/person.js
+++ b/src/person.js
@@ -1,12 +1,24 @@
/** Person actions use the view when the terminal belongs to an agent [B26]. */
+import { createHash } from 'node:crypto';
import { Refused } from './refused.js';
/** Markers carried by Claude Code and Codex agent subprocesses, rather than user configuration. */
export const AGENT_SHELL_MARKERS = Object.freeze([
- 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT',
+ 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_SESSION_ID', 'AI_AGENT',
'CODEX_THREAD_ID', 'CODEX_SESSION_ID', 'CODEX_CI', 'CODEX_SHELL',
]);
+/** Session identifiers belong beside the shell markers; only their digest reaches the local checkout binding. */
+export const AGENT_SESSION_IDS = Object.freeze(['CLAUDE_CODE_SESSION_ID', 'CODEX_THREAD_ID', 'CODEX_SESSION_ID']);
+
+/** Distinguish agent sessions, including one stable session for an agent shell with no identifier. */
+export function agentSessionDigest(environment = process.env) {
+ if (!AGENT_SHELL_MARKERS.some((name) => Boolean(environment[name]))) return null;
+ const name = AGENT_SESSION_IDS.find((key) => Boolean(environment[key]));
+ const identity = name ? [name, environment[name]] : ['agent-shell-without-session'];
+ return createHash('sha256').update(JSON.stringify(identity)).digest('hex');
+}
+
/** Refuse terminal person actions in an agent shell; only the authenticated view adapter supplies view. */
export function requirePersonChannel(channel = 'terminal', environment = process.env) {
if (!['terminal', 'view'].includes(channel)) {
diff --git a/test/agent-session.test.js b/test/agent-session.test.js
new file mode 100644
index 00000000..ca9275c0
--- /dev/null
+++ b/test/agent-session.test.js
@@ -0,0 +1,298 @@
+/** Checkout-session ownership and takeover behavior [B3,B7]. */
+import assert from 'node:assert/strict';
+import { execFileSync, spawn, spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, readdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { pathToFileURL } from 'node:url';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+import { DatabaseSync } from 'node:sqlite';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const DIRS = [];
+const MARKERS = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT', 'CODEX_THREAD_ID', 'CODEX_SESSION_ID', 'CODEX_CI', 'CODEX_SHELL'];
+const SPEC = '# Session fixture\n\n## G · Goals\n- G1 [approved, must] The fixture works. | gate: true\n';
+const CONFIG = { gate: 'true', spec: 'SPEC.md', verify: 'any', lease: '2h', lanes: { web: { owns: ['web/'], specs: ['G1'] } }, shared: ['docs/'] };
+
+after(() => { for (const dir of DIRS) rmSync(dir, { recursive: true, force: true }); });
+
+/** Build a private CLI environment without ambient agent/session or Git selectors. */
+function sandbox() {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-agent-session-'));
+ DIRS.push(dir);
+ const bin = join(dir, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec '${process.execPath.replaceAll("'", "'\\''")}' '${BIN.replaceAll("'", "'\\''")}' "$@"\n`);
+ chmodSync(join(bin, 'pullboard'), 0o755);
+ const base = { ...process.env };
+ for (const key of Object.keys(base)) if (key.startsWith('GIT_') || MARKERS.includes(key) || key === 'CLAUDE_CODE_SESSION_ID') delete base[key];
+ Object.assign(base, {
+ PULLBOARD_HOME: join(dir, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'), PATH: `${bin}:${process.env.PATH}`,
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Session fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Session fixture', GIT_COMMITTER_EMAIL: '[email protected]',
+ });
+ /** Run real Git with the private environment. */
+ function git(cwd, ...args) {
+ return execFileSync('git', args, { cwd, env: base, encoding: 'utf8', stdio: 'pipe' }).trim();
+ }
+ /** Run the actual CLI with an explicit agent session or markerless terminal. */
+ function run(cwd, args, { session, sessionKey = 'CLAUDE_CODE_SESSION_ID', agent = true } = {}) {
+ const env = { ...base };
+ if (agent) {
+ env.CLAUDECODE = '1';
+ if (session !== undefined) env[sessionKey] = session;
+ }
+ return spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 15_000 });
+ }
+ return { dir, base, git, run };
+}
+
+/** Create the main checkout and one joined lane worktree with a private board. */
+function project() {
+ const box = sandbox();
+ const repo = join(box.dir, 'repo');
+ mkdirSync(repo);
+ box.git(repo, 'init', '-q', '-b', 'main');
+ assert.equal(box.run(repo, ['init'], { agent: false }).status, 0);
+ writeFileSync(join(repo, 'pullboard.json'), `${JSON.stringify(CONFIG, null, 2)}\n`);
+ writeFileSync(join(repo, 'SPEC.md'), SPEC);
+ mkdirSync(join(repo, 'web'));
+ writeFileSync(join(repo, 'web', 'page.txt'), 'ready\n');
+ box.git(repo, 'add', '-A');
+ box.git(repo, 'commit', '-q', '-m', 'chore: initialize session fixture');
+ const added = box.run(repo, ['add', 'web', 'fixture item', '--specs', 'G1', '--json'], { agent: false });
+ assert.equal(added.status, 0, `${added.stdout}${added.stderr}`);
+ const web = join(box.dir, 'web-agent');
+ box.git(repo, 'worktree', 'add', '-q', web, '-b', 'web/session');
+ const joined = box.run(web, ['join', 'web'], { agent: false });
+ assert.equal(joined.status, 0, `${joined.stdout}${joined.stderr}`);
+ return { ...box, repo, web, boardFile: resolve(repo, box.git(repo, 'rev-parse', '--git-common-dir'), 'pullboard', 'board.sqlite') };
+}
+
+/** Capture stable board counts so a refused write proves no event, row, or shout was added. */
+function boardSnapshot(file) {
+ const db = new DatabaseSync(file, { readOnly: true });
+ try {
+ return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(({name}) => [name, db.prepare(`SELECT * FROM ${name} ORDER BY rowid`).all()]));
+ } finally { db.close(); }
+}
+
+/** Keep raw ids out of SQLite and local files; only the current digest lives in this checkout’s Git directory. */
+function assertNoRawSession(box, cwd, secrets, sessionKey = 'CLAUDE_CODE_SESSION_ID') {
+ const file = box.boardFile;
+ const dir = file.slice(0, file.lastIndexOf('/'));
+ const files = readdirSync(dir).filter((name) => /board\.sqlite(?:-(?:wal|shm))?$/u.test(name));
+ assert.ok(files.length, 'private SQLite board files were created');
+ for (const name of files) {
+ const bytes = readFileSync(join(dir, name));
+ for (const secret of secrets) assert.equal(bytes.includes(Buffer.from(secret)), false, `raw session id is not persisted in ${name}`);
+ }
+ const db = new DatabaseSync(file, { readOnly: true });
+ try {
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all().map((row) => row.name);
+ const stored = tables.flatMap((table) => db.prepare(`SELECT * FROM \"${table.replaceAll('\"', '\"\"')}\"`).all())
+ .map((row) => JSON.stringify(row)).join('\\n');
+ for (const secret of secrets) {
+ const digest = createHash('sha256').update(JSON.stringify([sessionKey, secret])).digest('hex');
+ assert.equal(stored.includes(digest), false, 'session bindings never enter shared board data');
+ }
+ } finally { db.close(); }
+ const local = resolve(cwd, box.git(cwd, 'rev-parse', '--git-dir'), 'pullboard-checkout-session.json');
+ const bindingText = readFileSync(local, 'utf8');
+ for (const secret of secrets) assert.equal(bindingText.includes(secret), false);
+ const binding = JSON.parse(bindingText);
+ assert.equal(binding.agent, cwd === box.repo ? 'coordinator' : 'web-1');
+ assert.equal(binding.digest, createHash('sha256').update(JSON.stringify([sessionKey, secrets.at(-1)])).digest('hex'));
+ assert.ok(Number.isFinite(Date.parse(binding.at)));
+}
+
+test('a second session cannot write in the main checkout until takeover [B3,B7]', () => {
+ const box = project();
+ const first = 'claude-session-secret-first-273';
+ const second = 'claude-session-secret-second-273';
+ const initial = box.run(box.repo, ['shout', 'web', 'first session owns main', '--json'], { session: first });
+ assert.equal(initial.status, 0, `${initial.stdout}${initial.stderr}`);
+ const before = boardSnapshot(box.boardFile);
+ const refused = box.run(box.repo, ['shout', 'web', 'must not land', '--json'], { session: second });
+ assert.notEqual(refused.status, 0);
+ const error = JSON.parse(refused.stdout).error;
+ assert.equal(error.code, 'NOT_YOUR_CHECKOUT');
+ assert.match(error.message, /coordinator/u);
+ assert.match(error.next, /pullboard worktree/u);
+ assert.match(error.message, /pullboard takeover/u);
+ assert.deepEqual(boardSnapshot(box.boardFile), before, 'refusal leaves all board counts unchanged');
+ const worktrees = box.git(box.repo, 'worktree', 'list', '--porcelain');
+ for (const args of [['init'], ['worktree', 'web'], ['hooks'], ['spec', 'apply'], ['hook', 'pre-commit'], ['submit', '1']]) {
+ const blocked = box.run(box.repo, [...args, '--json'], { session: second });
+ assert.equal(blocked.status, 1, `${args.join(' ')} must refuse another session before side effects`);
+ assert.equal(JSON.parse(blocked.stdout).error.code, 'NOT_YOUR_CHECKOUT');
+ assert.deepEqual(boardSnapshot(box.boardFile), before, `${args.join(' ')} leaves every board row intact`);
+ assert.equal(box.git(box.repo, 'worktree', 'list', '--porcelain'), worktrees, 'the wrong session cannot create a worktree first');
+ }
+
+ const takeover = box.run(box.repo, ['takeover', '--json'], { session: second });
+ assert.equal(takeover.status, 0, `${takeover.stdout}${takeover.stderr}`);
+ const rows = boardSnapshot(box.boardFile);
+ assert.ok(rows.event.slice(before.event.length).some(row => row.event_kind === 'shout' && row.event_by === 'coordinator'), 'takeover is recorded through an existing ordered shout event');
+ assert.match(rows.shout.at(-1).shout_text, /coordinator took over/);
+ assert.equal(rows.shout.at(-1).shout_to, 'person');
+ assert.equal(rows.shout.length, before.shout.length + 1, 'main-checkout takeover records the person notice');
+ const after = box.run(box.repo, ['shout', 'web', 'second session owns main', '--json'], { session: second });
+ assert.equal(after.status, 0, `${after.stdout}${after.stderr}`);
+ assertNoRawSession(box, box.repo, [first, second]);
+ const beforeSelf = boardSnapshot(box.boardFile);
+ const self = box.run(box.repo, ['shout', 'coordinator', 'cannot address myself', '--json'], { agent: false });
+ assert.notEqual(self.status, 0);
+ assert.deepEqual(boardSnapshot(box.boardFile), beforeSelf, 'self-addressed shout is refused without changing the board');
+});
+
+test('lane ownership is session-scoped and takeover preserves the joined agent [B3,B7]', () => {
+ const box = project();
+ const first = 'codex-thread-secret-first-273';
+ const second = 'codex-thread-secret-second-273';
+ const claim = box.run(box.web, ['claim', '1', '--json'], { session: first, sessionKey: 'CODEX_THREAD_ID' });
+ assert.equal(claim.status, 0, `${claim.stdout}${claim.stderr}`);
+ const sameSession = box.run(box.web, ['claim', '1', '--json'], { session: first, sessionKey: 'CODEX_THREAD_ID' });
+ assert.equal(sameSession.status, 0, `${sameSession.stdout}${sameSession.stderr}`);
+ const before = boardSnapshot(box.boardFile);
+ const refused = box.run(box.web, ['claim', '1', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });
+ assert.notEqual(refused.status, 0);
+ assert.equal(JSON.parse(refused.stdout).error.code, 'NOT_YOUR_CHECKOUT');
+ assert.match(JSON.parse(refused.stdout).error.message, /web-1/u);
+ assert.match(JSON.parse(refused.stdout).error.next, /pullboard worktree/u);
+ assert.deepEqual(boardSnapshot(box.boardFile), before, 'refused lane write leaves event and item counts unchanged');
+
+ const takeover = box.run(box.web, ['takeover', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });
+ assert.equal(takeover.status, 0, `${takeover.stdout}${takeover.stderr}`);
+ assert.equal(boardSnapshot(box.boardFile).event.length, before.event.length + 1, 'lane takeover records one event');
+ assert.equal(boardSnapshot(box.boardFile).shout.at(-1).shout_to, 'coordinator');
+ const after = box.run(box.web, ['claim', '1', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });
+ assert.equal(after.status, 0, `${after.stdout}${after.stderr}`);
+ assertNoRawSession(box, box.web, [first, second], 'CODEX_THREAD_ID');
+});
+
+test('no-session shells are one session and markerless terminals retain their writes [B3,B7]', () => {
+ const box = project();
+ const sentinel = box.run(box.web, ['claim', '1', '--json'], { session: undefined });
+ assert.equal(sentinel.status, 0, `${sentinel.stdout}${sentinel.stderr}`);
+ const noSessionAgain = box.run(box.web, ['claim', '1', '--json'], { session: undefined });
+ assert.equal(noSessionAgain.status, 0, `${noSessionAgain.stdout}${noSessionAgain.stderr}`);
+ const terminalRead = box.run(box.web, ['show', '1', '--json'], { agent: false });
+ assert.equal(terminalRead.status, 0, `${terminalRead.stdout}${terminalRead.stderr}`);
+ assert.equal(JSON.parse(terminalRead.stdout).item_status, 'claimed');
+ const beforeIdentified = boardSnapshot(box.boardFile);
+ const identified = box.run(box.web, ['release', '1', '--json'], { session: 'identified-after-sentinel-273', sessionKey: 'CODEX_SESSION_ID' });
+ assert.equal(identified.status, 1);
+ assert.equal(JSON.parse(identified.stdout).error.code, 'NOT_YOUR_CHECKOUT');
+ assert.deepEqual(boardSnapshot(box.boardFile), beforeIdentified);
+ const terminalWrite = box.run(box.web, ['shout', 'coordinator', 'the markerless terminal still works', '--json'], { agent: false });
+ assert.equal(terminalWrite.status, 0, terminalWrite.stdout + terminalWrite.stderr);
+ const secondSessionRead = box.run(box.web, ['show', '1', '--json'], { session: 'read-from-another-session-273' });
+ assert.equal(secondSessionRead.status, 0, secondSessionRead.stdout + secondSessionRead.stderr);
+
+ // Existing relay-person-request coverage should be retained: this private CLI fixture does not
+ // establish a linked relay or inject io.personRequest, so an ordinary shout is not a substitute.
+ // A decision addressed to its own sender must be refused rather than self-answered.
+ const beforeSelf = boardSnapshot(box.boardFile);
+ const self = box.run(box.repo, ['shout', 'coordinator', 'self decision', '--decision', '--json'], { agent: false });
+ assert.notEqual(self.status, 0);
+ assert.deepEqual(boardSnapshot(box.boardFile), beforeSelf, 'self-addressed decision is refused without a write');
+});
+
+test('the actual view adapter writes without taking over an agent session [B3,B7]', () => {
+ const box = project();
+ const owner = box.run(box.repo, ['shout', 'web', 'agent owns this checkout', '--json'], { session: 'view-owner-session-273' });
+ assert.equal(owner.status, 0, owner.stdout + owner.stderr);
+ const file = resolve(box.repo, box.git(box.repo, 'rev-parse', '--git-dir'), 'pullboard-checkout-session.json');
+ const before = readFileSync(file);
+ const apiModule = pathToFileURL(resolve(import.meta.dirname, '../src/api.js')).href;
+ const cliModule = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;
+ const source = `
+ const { executeMove } = await import(${JSON.stringify(apiModule)});
+ const { main } = await import(${JSON.stringify(cliModule)});
+ const response = await executeMove(process.cwd(), { verb: 'shout', args: { to: 'web', text: 'actual view action' } }, main);
+ process.stdout.write(JSON.stringify(response));
+ `;
+ const response = spawnSync(process.execPath, ['--input-type=module', '-e', source], {
+ cwd: box.repo, env: { ...box.base, CODEX_THREAD_ID: 'other-process-view-session-273' }, encoding: 'utf8', timeout: 15_000,
+ });
+ assert.equal(response.status, 0, response.stderr);
+ const document = JSON.parse(response.stdout);
+ assert.equal(document.status, 200, response.stdout);
+ assert.equal(document.body.event.event_kind, 'shout');
+ assert.equal(document.body.event.event_by, 'coordinator');
+ assert.equal(boardSnapshot(box.boardFile).shout.at(-1).shout_text, 'actual view action');
+ assert.deepEqual(readFileSync(file), before, 'the authenticated view does not alter the local agent-session binding');
+});
+
+test('takeover waits for an active write and then refuses the old session [B3,B7]', { timeout: 45_000 }, async () => {
+ const box = project();
+ const started = join(box.dir, 'gate-started');
+ const release = join(box.dir, 'gate-release');
+ const gateFile = join(box.dir, 'holding-gate.cjs');
+ writeFileSync(gateFile, `const fs = require('node:fs');
+ fs.writeFileSync(${JSON.stringify(started)}, 'started');
+ const timer = setInterval(() => { if (fs.existsSync(${JSON.stringify(release)})) { clearInterval(timer); process.exit(0); } }, 10);
+ setTimeout(() => process.exit(19), 20000).unref();
+ `);
+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: `node '${gateFile.replaceAll("'", "'\\''")}'` }));
+ box.git(box.repo, 'add', 'pullboard.json');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: configure holding gate');
+ box.git(box.web, 'merge', '--quiet', 'main');
+ const claim = box.run(box.web, ['claim', '1', '--json'], { session: 'active-write-273', sessionKey: 'CODEX_SESSION_ID' });
+ assert.equal(claim.status, 0, claim.stdout + claim.stderr);
+ writeFileSync(join(box.web, 'web/page.txt'), 'changed for the claimed item\n');
+ box.git(box.web, 'add', 'web/page.txt');
+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): change the page [G1]');
+ /** Start a real CLI write with a durable closed-process observation. */
+ function launch(session, ...args) {
+ const child = spawn(process.execPath, [BIN, ...args, '--json'], { cwd: box.web, env: { ...box.base, CODEX_SESSION_ID: session }, stdio: ['ignore', 'pipe', 'pipe'] });
+ let output = '';
+ child.stdout.setEncoding('utf8').on('data', (part) => { output += part; });
+ child.stderr.resume();
+ child.closed = new Promise((resolveClose) => child.once('close', (code) => resolveClose({ code, output })));
+ return child;
+ }
+ /** Wait on an actual private fixture observation, with an assertion if it never becomes true. */
+ async function observed(predicate, label) {
+ const deadline = Date.now() + 10_000;
+ while (!predicate() && Date.now() < deadline) await new Promise((done) => setTimeout(done, 10));
+ assert.ok(predicate(), label);
+ }
+ /** Observe the takeover waiting on this checkout's resource rather than depending on a sleep. */
+ function queued() {
+ const db = new DatabaseSync(join(box.repo, '.git', 'pullboard', 'resources.sqlite'), { readOnly: true });
+ try { return db.prepare("SELECT COUNT(*) AS count FROM waiter WHERE name LIKE 'checkout-session:%'").get().count > 0; }
+ finally { db.close(); }
+ }
+ const submission = launch('active-write-273', 'submit', '1');
+ let takeover;
+ try {
+ await observed(() => existsSync(started) || submission.exitCode !== null, 'the actual submission reaches its configured gate');
+ assert.equal(submission.exitCode, null, 'the submission is still writing while the gate waits');
+ takeover = launch('next-write-273', 'takeover');
+ await observed(() => queued() || takeover.exitCode !== null, 'the takeover reaches the same checkout guard');
+ assert.equal(takeover.exitCode, null, 'takeover waits until the old session finishes its active write');
+ assert.equal(boardSnapshot(box.boardFile).shout.length, 0, 'takeover has not recorded a receipt before acquiring the checkout');
+ writeFileSync(release, 'release');
+ const submitted = await submission.closed;
+ assert.equal(submitted.code, 0, submitted.output);
+ const taken = await takeover.closed;
+ assert.equal(taken.code, 0, taken.output);
+ assert.equal(boardSnapshot(box.boardFile).item[0].item_status, 'submitted');
+ const beforeRefusal = boardSnapshot(box.boardFile);
+ const old = box.run(box.web, ['shout', 'coordinator', 'old session cannot write', '--json'], { session: 'active-write-273', sessionKey: 'CODEX_SESSION_ID' });
+ assert.equal(old.status, 1);
+ assert.equal(JSON.parse(old.stdout).error.code, 'NOT_YOUR_CHECKOUT');
+ assert.deepEqual(boardSnapshot(box.boardFile), beforeRefusal);
+ } finally {
+ writeFileSync(release, 'release');
+ if (submission.exitCode === null) submission.kill('SIGTERM');
+ if (takeover?.exitCode === null) takeover.kill('SIGTERM');
+ await submission.closed;
+ if (takeover) await takeover.closed;
+ }
+});
diff --git a/test/api.test.js b/test/api.test.js
index 3a8da405..b08e7147 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -370,7 +370,7 @@ test('[A1,B21,B27] decisions shows an agent its direct and lane asks only', () =
const app1Ask = json(box, box.repo, 'shout', ['app-1', 'App one decision?', '--decision']).id;
const app2Ask = json(box, box.repo, 'shout', ['app-2', 'App two decision?', '--decision']).id;
const reviewAsk = json(box, box.repo, 'shout', ['review', 'Review decision?', '--decision']).id;
- const coordinatorAsk = json(box, box.repo, 'shout', ['coordinator', 'Coordinator decision?', '--decision']).id;
+ const coordinatorAsk = json(box, app1, 'shout', ['coordinator', 'Coordinator decision?', '--decision']).id;
const app1Queue = json(box, app1, 'decisions').decisions.map(({ shout_id }) => shout_id);
assert.deepEqual(app1Queue, [laneAsk, app1Ask]);
@@ -586,6 +586,9 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>
json(source, source.repo, 'spec', ['approve', 'G1'], 'approve');
json(source, source.repo, 'spec', ['decline', 'G1', '--reason', 'Catalog decline'], 'decline');
json(source, source.repo, 'spec', ['apply'], 'apply');
+ /** Exercise the agent-only takeover with a private explicit session, leaving later terminal calls markerless. */
+ const sessionSource = { ...source, run: (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env: { ...source.env, CODEX_SESSION_ID: 'api-catalog-session' }, encoding: 'utf8' }) };
+ json(sessionSource, source.repo, 'takeover');
const missing = Object.keys(JSON_SHAPES.commands).filter((key) => !covered.has(key));
assert.deepEqual(missing, [], `add real-repo invocations for undocumented coverage gaps: ${missing.join(', ')}`);
assert.deepEqual([...coveredRoots].sort(), resultCommands(), 'every actual root/factory command has an invocation');