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
Merge branch 'main' into HEAD
Corey Olson08912976c03f
diff --cc docs/api.mdindex fb260524,ee6fccbe..21762536--- a/docs/api.md+++ b/docs/api.md@@@ -202,8 -204,6 +205,8 @@@ For example: `flow: review wait averagEach 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. On a linked board one main checkout holds the coordinator at a time: another linked main checkout acting as coordinator gets `COORDINATOR_HELD`, naming the holder as `computer` and the end of its relay machine id, and `pullboard takeover` there, from an agent session or a person's terminal, takes the coordinator; its result adds `coordinator` (the new holder) and `previous`. 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`.- `heartbeat` records the registered seat’s machine-local session activity without adding a shared board move. It returns `{seat, presence, heartbeatAt}`; an unknown seat returns `null` for its identity and timestamp. SessionStart, Stop and SessionEnd hooks call it. A seat is live for ten minutes after its last observation, idle until thirty minutes, then gone; its permanent identity remains. Ordinary reads do not refresh presence. `status` shows live and idle seats, while `status --all` also lists gone seats. Observations are private to the machine and board identity and do not travel through export or relay.++`heartbeat` records the registered seat’s machine-local session activity without adding a shared board move. It returns `{seat, presence, heartbeatAt}`; an unknown seat returns `null` for its identity and timestamp. Native SessionStart and Stop hooks observe activity before reading context; Claude Code also installs a SessionEnd observation. A seat is live for ten minutes after its last observation, idle until thirty minutes, then gone; its permanent identity remains. Ordinary reads do not refresh presence. `status` shows live and idle seats, while `status --all` also lists gone seats. Observations are private to the machine and board identity and do not travel through export or relay.+`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`. Among unreserved submissions, `awaitingFirstReview` counts items with no release since their latest submission; `releasedWithoutVerdict` counts those released without a verdict. `releasedItems` lists `{item, releases, reason}` with the cumulative release count and latest reason for that submission. Historical releases without a reason show `reason not recorded`.With `submitGate: "landing"`, `status.submitInvariantProposals` lists files that failed outside a recorded submit selection. Each proposal carries `file`, `escapes` (distinct tested merge commits), `runtimeMs`, `budgetMs: 60000`, `withinBudget`, `commits` and the participating `submissions`. Repeated escapes below budget come first. Unmeasured whole-file runtime is `null`, not a sum of test-case durations. A later whole-file diagnostic or full gate passing at the identical commit suppresses that escape; another commit or merely an equal Git tree does not. Submission events record versioned `submissionProof: { version: 1, files, full, deferred, reason }`, including the actual full-fallback reason, plus `deferredFiles` when `submitDeferAbove` moved the affected selection to landing. A deferred full fallback records only invariants actually selected to run, rather than its possible full selection. Historical submissions without this receipt remain unknown. Landing batches append versioned `invariantEvidence` with actual tested commits, participants and whole-file diagnostics; earlier evidence cannot be replaced. Status reads those canonical events and changes no configuration. Edit `submitInvariants` on main to accept a proposal. Outside the landing submit policy the proposal list is empty.diff --cc src/agent-hook-work.jsindex 00000000,333d80b4..a0302c0fmode 000000,100644..100644--- a/src/agent-hook-work.js+++ b/src/agent-hook-work.js@@@ -1,0 -1,32 +1,36 @@@+ /** Read ordinary local work for a native nudge; the parent bounds this whole worker [I6]. */+ import { fileURLToPath } from 'node:url';+-/** Session start uses normal resume; Stop only reads committed, unsubmitted work. */++/** Native hook activity refreshes only the private sidecar before ordinary read-only context. */+ async function work(event) {++ const { heartbeatCommand } = await import('./cli-presence.js');++ try { heartbeatCommand({ cwd: process.cwd(), err: text => process.stderr.write(text + '\n') }); }++ catch { /* A failed private observation must not suppress the ordinary native context. */ }++ if (event === 'SessionEnd') return;+ if (event === 'SessionStart') {+ const { main } = await import('./cli.js');+ process.exitCode = await main(['resume'], { cwd: process.cwd(),+ stdout: process.stdout, stderr: process.stderr, stdin: process.stdin });+ return;+ }+ const { repoInfo, headCommit, tryGit } = await import('./git.js');+ const { join } = await import('node:path');+ const store = await import('./board.js');+ const info = repoInfo(process.cwd());+ const board = store.openBoardForRead(join(info.commonDir, 'pullboard', 'board.sqlite'));+ if (!board) return;+ try {+ const agent = store.agentAt(board, info.root), head = headCommit(info.root);+ if (!agent || !head) return;+ const items = store.listItems(board, { all: true }).filter(item => item.item_status === 'claimed'+ && item.item_owner === agent.agent_id && item.item_claim_head && item.item_claim_head !== head+ && tryGit(info.root, ['merge-base', '--is-ancestor', item.item_claim_head, head]).status === 0+ && tryGit(info.root, ['diff', '--quiet', item.item_claim_head, head, '--']).status === 1);+ if (items.length) process.stdout.write(`Committed work on ${items.map(item => '#' + item.item_id).join(', ')} is not submitted. Run pullboard submit <id> when it is ready.\n`);+ } finally { store.closeBoard(board); }+ }++ if (process.argv[1] === fileURLToPath(import.meta.url)) {+ try { await work(process.argv[2]); }+ catch { process.exitCode = 1; }+ }diff --cc src/agent-hook.jsindex 00000000,dabd6253..a9699cf0mode 000000,100644..100644--- a/src/agent-hook.js+++ b/src/agent-hook.js@@@ -1,0 -1,43 +1,43 @@@+ /** Native hooks provide bounded context and warnings, never a blocking decision [I6]. */+ import { spawn } from 'node:child_process';+ import { fileURLToPath } from 'node:url';+ import { AGENT_HOOK_EVENTS } from './agent-hooks.js';++ /** Run a single owned worker group; no inherited vendor payload can choose executable arguments. */+ export async function runAgentHook(io, event) {- if (!AGENT_HOOK_EVENTS.includes(event)) return 0;++ if (!AGENT_HOOK_EVENTS.includes(event) && event !== 'SessionEnd') return 0;+ let response;+ try {+ const result = await new Promise(resolveResult => {+ const child = spawn(process.execPath, [fileURLToPath(new URL('./agent-hook-work.js', import.meta.url)), event], {+ cwd: io.cwd, env: process.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let text = '', timedOut = false, finished = false;+ /** Retain bounded public board context, excluding diagnostic stderr and vendor transcripts. */+ const capture = chunk => { if (text.length < 8192) text += chunk.toString('utf8').slice(0, 8192 - text.length); };+ child.stdout.on('data', capture);+ child.stderr.resume();+ /** Finish once even when a spawn error precedes the close notification. */+ const finish = status => {+ if (finished) return;+ finished = true; clearTimeout(timer);+ resolveResult({ status, text, timedOut });+ };+ const timer = setTimeout(() => {+ timedOut = true;+ // This process group was created for this one worker, never selected by executable name.+ if (child.exitCode === null && child.signalCode === null) {+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* A worker that already closed needs no signal. */ }+ }+ finish(null);+ }, 2000);+ child.once('error', () => finish(null));+ child.once('close', finish);+ });+ if (result.timedOut || result.status !== 0) response = { systemMessage: `Pullboard hook warning: ${result.timedOut ? 'the local nudge timed out' : 'the local nudge could not finish'}; continuing. Run pullboard resume manually.` };+ else if (event === 'SessionStart') response = { hookSpecificOutput: { hookEventName: event, additionalContext: result.text.trim() } };+ else response = result.text.trim() ? { systemMessage: result.text.trim() } : {};+ } catch { response = { systemMessage: 'Pullboard hook warning: the local nudge could not start; continuing. Run pullboard resume manually.' }; }+ io.stdout.write(JSON.stringify(response) + '\n');+ return 0;+ }diff --cc src/agent-hooks.jsindex 00000000,dcd1e05d..76e198bemode 000000,100644..100644--- a/src/agent-hooks.js+++ b/src/agent-hooks.js@@@ -1,0 -1,109 +1,115 @@@+ /** Project-local agent nudges never grant trust or replace another tool's hooks [I6]. */+ import {+ existsSync,+ lstatSync,+ mkdirSync,+ readFileSync,+ realpathSync,+ renameSync,+ writeFileSync,+ } from 'node:fs';+ import {+ dirname,+ isAbsolute,+ join,+ relative,+ } from 'node:path';++ export const AGENT_HOOK_EVENTS = ['SessionStart', 'Stop'];++const CLAUDE_HOOK_EVENTS = [...AGENT_HOOK_EVENTS, 'SessionEnd'];+ export const LEGACY_RESUME_HOOK =+ 'm=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)/..; for p in node_modules/.bin/pullboard "$m/node_modules/.bin/pullboard"; do [ -x "$p" ] && exec "$p" resume; done; command -v pullboard >/dev/null && exec pullboard resume; true';+ const SOURCES = [['Claude Code', '.claude/settings.json'], ['Codex', '.codex/hooks.json']];++ /** Resolve the same local/main/PATH installations as I6; a missing executable is a silent no-op. */+ export function agentHookCommand(event) {- if (!AGENT_HOOK_EVENTS.includes(event)) throw new Error('unsupported agent hook event');++ if (!CLAUDE_HOOK_EVENTS.includes(event)) throw new Error('unsupported agent hook event');+ return 'm=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)/..; '+ + `for p in node_modules/.bin/pullboard "$m/node_modules/.bin/pullboard"; do [ -x "$p" ] && exec "$p" hook ${event}; done; `+ + `command -v pullboard >/dev/null || exit 0; exec pullboard hook ${event}`;+ }++ /** Recognize only the exact command this installer owns. */+ function owned(handler) {- return handler?.type === 'command' && AGENT_HOOK_EVENTS.some(event => handler.command === agentHookCommand(event)++ return handler?.type === 'command' && CLAUDE_HOOK_EVENTS.some(event => handler.command === agentHookCommand(event)+ || handler.command === `pullboard hook ${event}`);+ }++ /** Never follow project configuration through a symlink into a user's home. */+ function regularProjectPath(root, name) {+ const file = join(root, name), parent = dirname(file);+ for (const path of [parent, file]) {+ let stat;+ try { stat = lstatSync(path); } catch (error) { if (error.code === 'ENOENT') continue; throw error; }+ if (stat.isSymbolicLink()) return false;+ const inside = relative(realpathSync(root), realpathSync(path));+ if (inside === '..' || inside.startsWith('../') || isAbsolute(inside)) return false;+ }+ return !existsSync(file) || lstatSync(file).isFile();+ }++ /** Read an existing object without replacing malformed settings or hook arrays. */+ function settingsAt(root, name) {+ if (!regularProjectPath(root, name)) throw new Error('configuration is not a regular project file');+ const value = existsSync(join(root, name)) ? JSON.parse(readFileSync(join(root, name), 'utf8')) : {};+ if (!value || typeof value !== 'object' || Array.isArray(value)+ || value.hooks !== undefined && (!value.hooks || typeof value.hooks !== 'object' || Array.isArray(value.hooks))) throw new Error('configuration is not an object');- for (const event of AGENT_HOOK_EVENTS) if (value.hooks?.[event] !== undefined++ for (const event of CLAUDE_HOOK_EVENTS) if (value.hooks?.[event] !== undefined+ && (!Array.isArray(value.hooks[event]) || value.hooks[event].some(group => !group || typeof group !== 'object' || !Array.isArray(group.hooks)))) throw new Error('hook groups are not arrays');+ return value;+ }++ /** Merge or remove only Pullboard's exact handlers, preserving unrelated settings and groups. */+ export function configureAgentHooks(root, { remove = false, legacyResume = LEGACY_RESUME_HOOK, onWrite = () => {} } = {}) {+ return SOURCES.map(([vendor, name]) => {+ try {+ if (remove && !existsSync(join(root, name))) return `${vendor} agent hooks are not installed`;+ const value = settingsAt(root, name), before = JSON.stringify(value);+ value.hooks ??= {};- for (const event of AGENT_HOOK_EVENTS) {++ for (const event of vendor === 'Claude Code' ? CLAUDE_HOOK_EVENTS : AGENT_HOOK_EVENTS) {+ const groups = value.hooks[event] ?? [];+ const kept = groups.flatMap(group => {+ const hooks = group.hooks.filter(handler => !owned(handler)+ && !(vendor === 'Claude Code' && legacyResume && event === 'SessionStart' && handler?.command === legacyResume));+ return hooks.length || Object.keys(group).some(key => key !== 'hooks') ? [{ ...group, hooks }] : [];+ });- if (!remove) kept.push({ hooks: [{ type: 'command', command: agentHookCommand(event), timeout: 5 }] });++ if (!remove) {++ const nudge = { hooks: [{ type: 'command', command: agentHookCommand(event), timeout: 5 }] };++ // Observe activity before an existing custom Claude resume without rewriting the user's command.++ if (vendor === 'Claude Code' && event === 'SessionStart' && JSON.stringify(kept).includes('pullboard resume')) kept.unshift(nudge);++ else kept.push(nudge);++ }+ if (kept.length) value.hooks[event] = kept;+ else delete value.hooks[event];+ }+ if (!Object.keys(value.hooks).length) delete value.hooks;+ const changed = JSON.stringify(value) !== before;+ if (changed) {+ mkdirSync(dirname(join(root, name)), { recursive: true });+ const temporary = join(root, name) + `.${process.pid}.tmp`;+ writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });+ renameSync(temporary, join(root, name));+ onWrite(name);+ }+ if (remove) return `removed Pullboard's ${vendor} agent nudges from ${name}`;+ return vendor === 'Claude Code'+ ? `${changed ? 'added a' : 'kept the'} Claude Code session hook and Stop reminder in ${name}`+ : `${changed ? 'installed' : 'kept'} Codex agent nudges in ${name}; review and trust them with /hooks`;+ } catch {+ return `${vendor} agent hook warning: kept ${name} unchanged; repair its project-local JSON and run pullboard hooks`;+ }+ });+ }++ /** File presence is installation evidence, never proof that a vendor trusted a definition. */+ export function agentHookStatus(root) {+ return SOURCES.map(([vendor, name]) => {+ let events = [];+ try {+ const value = settingsAt(root, name);- events = AGENT_HOOK_EVENTS.filter(event => value.hooks?.[event]?.some(group => group.hooks.some(handler => owned(handler)++ events = (vendor === 'Claude Code' ? CLAUDE_HOOK_EVENTS : AGENT_HOOK_EVENTS).filter(event => value.hooks?.[event]?.some(group => group.hooks.some(handler => owned(handler)+ && [agentHookCommand(event), `pullboard hook ${event}`].includes(handler.command))));+ } catch { /* Invalid configuration remains visibly inactive. */ }+ return { vendor, configured: existsSync(join(root, name)), events, trust: vendor === 'Codex' ? 'unverified' : null };+ });+ }diff --cc src/board.jsindex bbd81639,3b68d872..44a0200e--- a/src/board.js+++ b/src/board.js@@@ -1,4 -1,4 +1,5 @@@+import { heartbeatSeat } from './seat-presence.js';+ import * as activityDeliveryStore from './activity-delivery-store.js';import { requireFactKind } from './item-notes.js';import { activityNewsFlag } from './activity-news.js';import { migrateEventLogVersion } from './board-event-log-migrate.js';diff --cc src/commands/status.jsindex 6caf07c8,7a4e0db8..6979588f--- a/src/commands/status.js+++ b/src/commands/status.js@@@ -37,13 -38,11 +38,14 @@@ export async function run(io, { valuesconst me = identifyCaller(ctx, board, { environmentAgent: environment?.environmentAgent ?? (() => null),relayLinked: relay?.relayLinked ?? (() => false) }, readers);const mine = store.itemsInStatus(board, 'claimed', me.id);- const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });- return { me, mine, ruleCounts: ruleProofCounts(ctx.info.root, board, approvalState.spec), needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),+ const agents = store.listAgents(board);+ const presenceCounts = { live: 0, idle: 0, gone: 0 };+ for (const seat of agents) presenceCounts[seat.presence] += 1;+ const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config, agents });+ return { me, mine, agents, presenceCounts, ruleCounts: ruleProofCounts(ctx.info.root, board, approvalState.spec), needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),submitInvariantProposals: submitInvariantProposals(store.submitInvariantEvents(board, ctx.config), ctx.config) };});+ summary.memoryHeld = memoryHeldRuns();if (values.json) {io.result(summary);return 0;@@@ -56,8 -55,8 +58,10 @@@if (summary.specApprovalBaseline?.pending) io.say('approval baseline pending: the next coordinator or person command in the main checkout records the existing approved rows; lane work may continue and none are flagged until then');if (summary.specApprovalBaseline?.invalid) io.say('approval baseline unreadable: existing rows need approval evidence; restore a known-good board export to recover the original baseline');io.say(reviewQueueLine(ctx, summary.reviewQueue, span));+ io.say(`seats: ${summary.presenceCounts.live} live, ${summary.presenceCounts.idle} idle, ${summary.presenceCounts.gone} gone`);+ for (const seat of summary.agents.filter(seat => values.all || seat.presence !== 'gone')) io.say(`${seat.agent_id}: ${seat.presence}${seat.heartbeatAt ? ` (heartbeat ${seat.heartbeatAt})` : ' (no local heartbeat)'}`);+ if (summary.memoryHeld === null) io.say('local memory hold status unavailable; pullboard resources shows the queue');+ else for (const run of summary.memoryHeld) io.say(`local memory holds ${run.agent}${run.item ? ` #${run.item}` : ''}${run.kind ? ` (${run.kind})` : ''}${run.repo ? ` in ${run.repo}` : ''}`);for (const proposal of summary.submitInvariantProposals) io.say(submitInvariantLine(proposal));for (const need of summary.needs.filter(need => need.kind === 'agent-approved')) io.say(`${need.text}; ${need.what}`);if (!summary.relay.linked && !originRepository(ctx.info.root, { optional: true })) {diff --cc src/help.jsindex 83da1e6e,695a5c71..20d06b6a--- a/src/help.js+++ b/src/help.js@@@ -350,9 -361,9 +362,9 @@@ const HELP_ALIASES =lanes: { usage: 'pullboard lanes', source: 'whoami' },agents: { usage: 'pullboard agents', source: 'whoami' },lane: { usage: 'pullboard lane add <name> --owns <path>[,<path>]', source: 'lane add' },- status: { usage: 'pullboard status', source: 'whoami' },+ status: { usage: 'pullboard status [--all]', source: 'whoami' },done: { usage: 'pullboard done <id>', source: 'submit <id>' },- inbox: { usage: 'pullboard inbox', source: null },+ inbox: { usage: 'pullboard inbox', source: null, extraFlags: ['--acted-on <interrupt-ids>'] },'check accept': { usage: 'pullboard check accept <id>', source: 'check accept' },relay: { source: 'relay', every: true },lifecycle: { usage: 'pullboard lifecycle', source: null },diff --cc test/e2e-cli.test.jsindex 8e329e8a,3bf3c80b..8443e663--- a/test/e2e-cli.test.js+++ b/test/e2e-cli.test.js@@@ -51,9 -51,9 +51,9 @@@ test('init adds a Claude Code session hassert.deepEqual(settings.permissions, { allow: [...mine.permissions.allow, ...claudeLoopRules({ gate: '' })] });assert.deepEqual(settings.sandbox, { filesystem: { allowWrite: [box.env.PULLBOARD_MACHINE_HOME] } });assert.deepEqual(Object.keys(settings).sort(), ['hooks', 'permissions', 'sandbox'], 'init adds no other top-level setting');- assert.deepEqual(Object.keys(settings.hooks).sort(), ['SessionEnd', 'SessionStart', 'Stop'], 'init installs only the three activity hook events');- assert.deepEqual(settings.hooks.Stop.slice(0, mine.hooks.Stop.length), mine.hooks.Stop, 'custom Stop hooks remain unchanged');- assert.ok(settings.hooks.Stop.at(-1).hooks[0].command.includes('pullboard heartbeat'));- assert.deepEqual(Object.keys(settings.hooks).sort(), ['SessionStart', 'Stop'], 'init adds no other hook event');++ assert.deepEqual(Object.keys(settings.hooks).sort(), ['SessionEnd', 'SessionStart', 'Stop'], 'init installs the three supported Claude activity hook events');+ assert.deepEqual(settings.hooks.Stop.slice(0, mine.hooks.Stop.length), mine.hooks.Stop);+ assert.equal(settings.hooks.Stop.length, mine.hooks.Stop.length + 1, 'only the new nonblocking Stop nudge is appended');assert.equal(settings.hooks.SessionStart.length, 1);const { command } = settings.hooks.SessionStart[0].hooks[0];const card = spawnSync('sh', ['-c', command], { cwd: repo, env: box.env, encoding: 'utf8' });diff --cc test/hooks.test.jsindex db4457fb,2a2616a8..c5fd3eef--- a/test/hooks.test.js+++ b/test/hooks.test.js@@@ -20,6 -21,98 +21,100 @@@ after(e2e.cleanup)const SPEC = { ...parseSpec('## G\n- G1 [approved, must] One. | gate: t\n- G2 [retired] Gone.\n'), name: 'SPEC.md' };const RULES = defaults().commits;+ test("a hook nudges and never blocks, fails open on error or timeout, and init merges with the user's hooks [I6]", () => {+ const box = e2e.project('true');+ const result = runFixtureChild(process.execPath, [e2e.BIN, 'hook', 'SessionStart'], {+ cwd: box.web, env: box.env, input: JSON.stringify({ hook_event_name: 'SessionStart', cwd: box.web }),+ encoding: 'utf8',+ });+ assert.equal(result.status, 0, `a native session-start hook must nudge without refusing: ${result.stdout}${result.stderr}`);+ const response = JSON.parse(result.stdout);+ assert.equal(response.continue === false || response.decision === 'block', false);+ assert.equal(response.hookSpecificOutput.hookEventName, 'SessionStart');+ assert.match(response.hookSpecificOutput.additionalContext, /pullboard|work|claim/i);+ const claude = join(box.repo, '.claude/settings.json'), codex = join(box.repo, '.codex/hooks.json');+ const mine = { permissions: { allow: ['Bash(my-check)'] }, hooks: { Stop: [{ hooks: [{ type: 'command', command: 'echo my-stop' }] }] } };+ const codexMine = { description: 'My existing hooks', hooks: { SessionStart: [{ matcher: 'startup', hooks: [{ type: 'command', command: 'echo my-start' }] }] } };+ writeFileSync(claude, JSON.stringify(mine));+ writeFileSync(codex, JSON.stringify(codexMine));+ assert.equal(box.run(box.repo, 'init', '--no-permissions').code, 0,+ 'the actual init entrypoint merges existing agent hooks');+ const configured = [claude, codex].map(file => JSON.parse(readFileSync(file, 'utf8')));++ assert.ok(configured[0].hooks.SessionEnd.some(group => group.hooks.some(handler => handler.command.includes('hook SessionEnd'))));++ assert.equal(Object.hasOwn(configured[1].hooks, 'SessionEnd'), false, 'Codex keeps its supported SessionStart and Stop definitions');+ assert.deepEqual(configured[0].permissions, mine.permissions);+ assert.deepEqual(configured[0].hooks.Stop[0], mine.hooks.Stop[0]);+ assert.deepEqual(configured[1].hooks.SessionStart[0], codexMine.hooks.SessionStart[0]);+ assert.equal(configured[1].description, codexMine.description);+ for (const settings of configured) for (const event of ['SessionStart', 'Stop']) {+ const handlers = settings.hooks[event].flatMap(group => group.hooks);+ assert.equal(handlers.filter(handler => handler.command.includes(`hook ${event}`)).length, 1);+ const handler = handlers.find(handler => handler.command.includes(`hook ${event}`));+ assert.equal(handler.type, 'command');+ assert.ok(handler.timeout > 0);+ assert.equal(handler.command.includes('\n'), false, 'the installation is one thin resolver line');+ const missing = runFixtureChild('/bin/sh', ['-c', handler.command], { cwd: box.dir,+ env: { ...box.env, PATH: '/usr/bin:/bin' }, encoding: 'utf8' });+ assert.equal(missing.status, 0, 'missing executable cannot break the vendor session');+ assert.equal(missing.stdout, '');+ }+ const once = [readFileSync(claude, 'utf8'), readFileSync(codex, 'utf8')];+ assert.equal(box.run(box.repo, 'hooks').code, 0);+ assert.deepEqual([readFileSync(claude, 'utf8'), readFileSync(codex, 'utf8')], once, 'merging twice is idempotent');++ const added = box.run(box.repo, 'add', 'web', 'Native stop reminder', '--criterion', 'committed work is named', '--json');+ assert.equal(added.code, 0, added.err);+ const id = JSON.parse(added.out).item.item_id;+ assert.equal(box.run(box.web, 'claim', String(id)).code, 0);+ assert.equal(e2e.commitFile(box, box.web, 'web/nudge.txt', 'committed work\n', 'feat(web): nudge work [G1]').status, 0);+ // Contract probes use current documented vendor envelopes, never an actual user's transcript.+ // https://learn.chatgpt.com/docs/hooks and https://code.claude.com/docs/en/hooks+ for (const vendor of ['codex', 'claude']) {+ const payload = { session_id: `private-${vendor}-fixture`, cwd: box.web, hook_event_name: 'Stop', stop_hook_active: false,+ ...(vendor === 'codex' ? { turn_id: 'private-turn', last_assistant_message: null } : { transcript_path: join(box.dir, 'private-unused.jsonl') }) };+ const stop = runFixtureChild(process.execPath, [e2e.BIN, 'hook', 'Stop'], { cwd: box.web, env: box.env, input: JSON.stringify(payload), encoding: 'utf8' });+ assert.equal(stop.status, 0, stop.stderr);+ const notice = JSON.parse(stop.stdout);+ assert.equal(notice.continue === false || notice.decision === 'block', false);+ assert.match(notice.systemMessage, new RegExp(`#${id}\\b`));+ }+ const broken = runFixtureChild(process.execPath, [e2e.BIN, 'hook', 'SessionStart'], { cwd: box.dir, env: box.env, encoding: 'utf8' });+ assert.equal(broken.status, 0);+ assert.match(JSON.parse(broken.stdout).systemMessage, /warning.*continuing/i);+ const unknown = runFixtureChild(process.execPath, [e2e.BIN, 'hook', 'FutureVendorEvent'], { cwd: box.dir, env: box.env, encoding: 'utf8' });+ assert.equal(unknown.status, 0);+ assert.equal(unknown.stdout, '');+ const slow = join(box.dir, 'slow-git');+ mkdirSync(slow);+ writeFileSync(join(slow, 'git'), '#!/bin/sh\nexec /bin/sleep 10\n');+ chmodSync(join(slow, 'git'), 0o755);+ const timeout = runFixtureChild(process.execPath, [e2e.BIN, 'hook', 'SessionStart'], {+ cwd: box.web, env: { ...box.env, PATH: `${slow}:${box.env.PATH}` }, encoding: 'utf8',+ });+ assert.equal(timeout.status, 0);+ assert.match(JSON.parse(timeout.stdout).systemMessage, /timed out.*continuing/i);+ const doctor = box.run(box.repo, 'doctor', '--json');+ const status = JSON.parse(doctor.out).agentHooks.find(hook => hook.vendor === 'Codex');+ assert.deepEqual(status.events, ['SessionStart', 'Stop']);+ assert.equal(status.trust, 'unverified', 'installation never fabricates vendor trust');+ const validCodex = readFileSync(codex, 'utf8');+ writeFileSync(codex, '{ malformed user JSON');+ const malformed = box.run(box.repo, 'hooks');+ assert.equal(malformed.code, 0);+ assert.match(malformed.out, /warning.*kept.*unchanged/i);+ assert.equal(readFileSync(codex, 'utf8'), '{ malformed user JSON');+ writeFileSync(codex, validCodex);+ assert.equal(box.run(box.repo, 'hooks', 'uninstall').code, 0);+ assert.deepEqual(JSON.parse(readFileSync(claude, 'utf8')), mine);+ assert.deepEqual(JSON.parse(readFileSync(codex, 'utf8')), codexMine);+ const disabled = join(box.dir, 'disabled');+ mkdirSync(disabled);+ box.git(disabled, 'init', '-q', '-b', 'main');+ assert.equal(box.run(disabled, 'init', '--no-hooks', '--no-permissions').code, 0);+ assert.equal(existsSync(join(disabled, '.codex/hooks.json')), false);+ assert.equal(existsSync(join(disabled, '.claude/settings.json')), false);+ });+/** Make a private real repository for staged-diff hook tests, with cleanup tied to the test. */function stagedRepo(t) {const root = mkdtempSync(join(tmpdir(), 'pullboard-staged-diff-'));diff --cc test/presence.test.jsindex 631832db,00000000..366be7b0mode 100644,000000..100644--- a/test/presence.test.js+++ b/test/presence.test.js@@@ -1,272 -1,0 +1,281 @@@+/** Seat identity survives heartbeat-based presence changes on a real SQLite board [B3]. */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import * as store from '../src/board.js';++test('a seat presence moves live to idle to gone from its heartbeat [B3]', (t) => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-presence-'));+ let at = Date.parse('2026-10-24T12:00:00Z');+ const board = store.openBoard(join(root, 'board.sqlite'), { now: () => new Date(at) });+ t.after(() => { store.closeBoard(board); rmSync(root, { recursive: true, force: true }); });+ const id = store.register(board, { lane: 'core', path: join(root, 'seat') });+ const identity = store.agentById(board, id);+ assert.equal(store.listAgents(board).find(seat => seat.agent_id === id).presence, 'live');+ at += 10 * 60_000 - 1;+ assert.equal(store.listAgents(board).find(seat => seat.agent_id === id).presence, 'live');+ at += 1;+ assert.equal(store.listAgents(board).find(seat => seat.agent_id === id).presence, 'idle');+ at += 20 * 60_000;+ assert.equal(store.listAgents(board).find(seat => seat.agent_id === id).presence, 'gone');+ assert.equal(store.agentById(board, id).agent_id, identity.agent_id);+ assert.equal(store.agentById(board, id).agent_path, identity.agent_path);+});++test('local heartbeats revive a seat without changing exported history or a remote copy [B3,A7]', async (t) => {+ const { heartbeatSeat } = await import('../src/seat-presence.js');+ const { exportBoard, importBoard } = await import('../src/exchange.js');+ const root = mkdtempSync(join(tmpdir(), 'pullboard-presence-local-'));+ let at = Date.parse('2026-10-24T12:00:00Z');+ const clock = { now: () => new Date(at) };+ const board = store.openBoard(join(root, 'board.sqlite'), clock);+ const remote = store.openBoard(join(root, 'remote.sqlite'), clock);+ t.after(() => { store.closeBoard(board); store.closeBoard(remote); rmSync(root, { recursive: true, force: true }); });+ const id = store.register(board, { lane: 'core', path: join(root, 'seat') });+ const before = exportBoard(board);+ at += 30 * 60_000;+ assert.equal(store.agentById(board, id).presence, 'gone');+ assert.equal(heartbeatSeat(board, id), true);+ assert.equal(store.agentById(board, id).presence, 'live');+ assert.equal(store.agentById(board, id).heartbeatAt, clock.now().toISOString());+ assert.deepEqual(exportBoard(board), before, 'heartbeat is not native history or exported state');+ importBoard(remote, before);+ assert.equal(store.agentById(remote, id).presence, 'gone', 'a foreign registration is not a local heartbeat');+ assert.equal(store.agentById(remote, id).heartbeatAt, null);+ assert.equal(heartbeatSeat(board, 'missing-seat'), false);+});++test('status reads and explicit hooks heartbeat without a shared board write [B3,I6]', async (t) => {+ const { createE2eHelpers } = await import('./e2e-helpers.js');+ const { readFileSync } = await import('node:fs');+ const { DatabaseSync } = await import('node:sqlite');+ const { projectState } = await import('../src/serve.js');+ const helpers = createE2eHelpers();+ t.after(helpers.cleanup);+ const box = helpers.project('true');+ const file = join(box.repo, '.git', 'pullboard', 'board.sqlite');+ const local = new DatabaseSync(`${file}.presence.sqlite`);+ t.after(() => local.close());+ const boardId = local.prepare("ATTACH DATABASE ? AS native");+ boardId.run(file);+ const identity = local.prepare("SELECT meta_value FROM native.board_meta WHERE meta_key='board_id'").get().meta_value;+ local.exec('DETACH DATABASE native');+ local.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run('2000-01-01T00:00:00.000Z', JSON.stringify([identity, 'web-1']));+ local.exec('CREATE TABLE writes(n INTEGER NOT NULL); INSERT INTO writes VALUES(0); CREATE TRIGGER count_heartbeat AFTER UPDATE ON heartbeat BEGIN UPDATE writes SET n=n+1; END');+ const board = store.openBoard(file);+ const events = board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n;+ board.db.exec('BEGIN IMMEDIATE');+ const status = box.run(box.web, 'status', '--json');+ const explicit = box.run(box.web, 'heartbeat', '--json');+ board.db.exec('ROLLBACK');+ assert.equal(status.code, 0, status.err + status.out);+ const summary = JSON.parse(status.out);+ assert.equal(summary.agents.find(seat => seat.agent_id === 'web-1').presence, 'gone', 'status reads the stale observation');+ assert.equal(explicit.code, 0, explicit.err + explicit.out);+ assert.equal(JSON.parse(explicit.out).presence, 'live');+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, 'the explicit hook alone refreshes while the shared board is write-locked');+ assert.equal(board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n, events);+ const state = projectState(box.repo, { board });+ assert.equal(state.agents.find(seat => seat.agent_id === 'web-1').presence, 'live');+ store.closeBoard(board);+ const settings = JSON.parse(readFileSync(join(box.repo, '.claude', 'settings.json'), 'utf8'));+ for (const event of ['SessionStart', 'Stop', 'SessionEnd']) {+ const commands = settings.hooks[event].flatMap(entry => entry.hooks.map(hook => hook.command));- assert.ok(commands.some(command => command.includes(event === 'SessionStart' ? 'pullboard resume' : 'pullboard heartbeat')), event);++ assert.ok(commands.some(command => command.includes(`hook ${event}`)), event);+ }+ const heartbeat = box.run(box.web, 'heartbeat', '--json');+ assert.equal(heartbeat.code, 0, heartbeat.err + heartbeat.out);+ assert.equal(JSON.parse(heartbeat.out).presence, 'live');+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, 'a separate CLI process in the same minute performs no additional heartbeat write');+});+++test('an imported board never inherits a same-path coordinator heartbeat [B3,A7]', async (t) => {+ const { exportBoard, importBoard } = await import('../src/exchange.js');+ const root = mkdtempSync(join(tmpdir(), 'pullboard-presence-identity-'));+ const clock = { now: () => new Date('2026-10-24T12:00:00Z') };+ const local = store.openBoard(join(root, 'local.sqlite'), clock);+ const foreign = store.openBoard(join(root, 'foreign.sqlite'), clock);+ t.after(() => { store.closeBoard(local); store.closeBoard(foreign); rmSync(root, { recursive: true, force: true }); });+ store.register(local, { lane: 'coordinator', path: join(root, 'old-coordinator') });+ store.register(foreign, { lane: 'coordinator', path: join(root, 'foreign-coordinator') });+ /** Read the native board identity to prove this is a real replacement. */+ const identity = board => board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value;+ assert.notEqual(identity(local), identity(foreign));+ assert.equal(store.agentById(local, 'coordinator').presence, 'live');+ importBoard(local, exportBoard(foreign));+ assert.equal(identity(local), identity(foreign), 'the accepted import really replaced board identity');+ assert.equal(store.agentById(local, 'coordinator').agent_path, join(root, 'foreign-coordinator'));+ assert.equal(store.agentById(local, 'coordinator').presence, 'gone');+ assert.equal(store.agentById(local, 'coordinator').heartbeatAt, null);+});++test('plain status counts large seat history and hides gone seats behind --all [B3,C7]', async (t) => {+ const { createE2eHelpers } = await import('./e2e-helpers.js');+ const { heartbeatSeat } = await import('../src/seat-presence.js');+ const { JSON_SHAPES } = await import('../src/json.js');+ const helpers = createE2eHelpers();+ t.after(helpers.cleanup);+ const box = helpers.project('true');+ let at = Date.now() - 40 * 60_000;+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'), { now: () => new Date(at) });+ const gone = [];+ for (let index = 0; index < 100; index += 1) gone.push(store.register(board, { lane: 'api', path: join(box.dir, `history-${index}`) }));+ at = Date.now() - 11 * 60_000;+ const idle = store.register(board, { lane: 'api', path: join(box.dir, 'idle-seat') });+ at = Date.now();+ heartbeatSeat(board, 'coordinator');+ heartbeatSeat(board, 'web-1');+ assert.equal(store.listAgents(board).filter(seat => seat.presence === 'gone').length, 100);+ store.closeBoard(board);+ const plain = box.run(box.web, 'status');+ assert.equal(plain.code, 0, plain.err + plain.out);+ assert.match(plain.out, /seats: 2 live, 1 idle, 100 gone/u);+ assert.ok(plain.out.includes(`${idle}: idle`));+ assert.ok(gone.every(id => !plain.out.includes(`${id}: gone`)), 'plain status never prints historical gone rows');+ const all = box.run(box.web, 'status', '--all');+ assert.equal(all.code, 0, all.err + all.out);+ assert.ok(gone.every(id => all.out.includes(`${id}: gone`)), 'the explicit flag retains access to every identity');+ const structured = box.run(box.web, 'status', '--json');+ assert.equal(structured.code, 0, structured.err + structured.out);+ const summary = JSON.parse(structured.out);+ assert.deepEqual(summary.presenceCounts, { live: 2, idle: 1, gone: 100 });+ assert.equal(summary.agents.length, 103, 'JSON may retain full history per outside1705');+ assert.equal(JSON_SHAPES.commands.heartbeat.required.seat, 'string|null');+ assert.equal(JSON_SHAPES.commands.heartbeat.required.heartbeatAt, 'string|null');+});+++test('a local heartbeat persists once per minute and refreshes after clock rollback [B3,C7]', async (t) => {+ const { heartbeatSeat } = await import('../src/seat-presence.js');+ const { DatabaseSync } = await import('node:sqlite');+ const root = mkdtempSync(join(tmpdir(), 'pullboard-presence-throttle-'));+ let at = Date.parse('2026-10-24T12:00:00.000Z');+ const file = join(root, 'board.sqlite');+ const board = store.openBoard(file, { now: () => new Date(at) });+ const id = store.register(board, { lane: 'core', path: join(root, 'seat') });+ const local = new DatabaseSync(`${file}.presence.sqlite`);+ t.after(() => { local.close(); store.closeBoard(board); rmSync(root, { recursive: true, force: true }); });+ local.exec('CREATE TABLE writes(n INTEGER NOT NULL); INSERT INTO writes VALUES(0); CREATE TRIGGER count_update AFTER UPDATE ON heartbeat BEGIN UPDATE writes SET n=n+1; END');+ const first = store.agentById(board, id).heartbeatAt;+ at += 59_999;+ assert.equal(heartbeatSeat(board, id), true);+ assert.equal(store.agentById(board, id).heartbeatAt, first);+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 0, 'fresh activity needs no SQLite update');+ at += 1;+ assert.equal(heartbeatSeat(board, id), true);+ assert.equal(store.agentById(board, id).heartbeatAt, new Date(at).toISOString());+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, 'the exact one-minute boundary refreshes once');+ at -= 120_000;+ assert.equal(heartbeatSeat(board, id), true);+ assert.equal(store.agentById(board, id).heartbeatAt, new Date(at).toISOString(), 'a future persisted value cannot suppress observations after rollback');+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 2);+ assert.equal(heartbeatSeat(board, id), true);+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 2, 'the rollback replacement is itself throttled');+});+++test('read commands never refresh presence while committed writes and hooks do [B3,C7]', async (t) => {+ const { createE2eHelpers } = await import('./e2e-helpers.js');+ const { DatabaseSync } = await import('node:sqlite');+ const helpers = createE2eHelpers();+ t.after(helpers.cleanup);+ const box = helpers.project('true');+ const added = box.run(box.repo, 'add', 'web', 'Read-only presence control', '--criterion', 'Keep the same item', '--check', 'true', '--json');+ assert.equal(added.code, 0, added.err + added.out);+ const id = JSON.parse(added.out).item.item_id;+ const withdrawn = box.run(box.repo, 'withdraw', String(id), 'Private read-only presence control', '--json');+ assert.equal(withdrawn.code, 0, withdrawn.err + withdrawn.out);+ const file = join(box.repo, '.git', 'pullboard', 'board.sqlite');+ const board = store.openBoard(file);+ const local = new DatabaseSync(`${file}.presence.sqlite`);+ t.after(() => { local.close(); store.closeBoard(board); });+ assert.equal(store.getItem(board, id).item_status, 'withdrawn', 'the real native move leaves no claimable item');+ const identity = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value;+ const key = JSON.stringify([identity, 'web-1']);+ const stale = '2000-01-01T00:00:00.000Z';+ local.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run(stale, key);+ local.exec('CREATE TABLE writes(n INTEGER NOT NULL); INSERT INTO writes VALUES(0); CREATE TRIGGER count_update AFTER UPDATE ON heartbeat BEGIN UPDATE writes SET n=n+1; END');+ board.db.exec('BEGIN IMMEDIATE');+ try {+ const status = box.run(box.web, 'status', '--json');+ assert.equal(status.code, 0, status.err + status.out);+ const summary = JSON.parse(status.out);+ assert.equal(summary.agents.find(seat => seat.agent_id === 'web-1').presence, 'gone', 'status projects the stored observation without reviving it');+ assert.equal(local.prepare('SELECT at FROM heartbeat WHERE seat=?').get(key).at, stale);+ for (const args of [['show', String(id), '--json'], ['list', '--json']]) {+ const result = box.run(box.web, ...args);+ assert.equal(result.code, 0, result.err + result.out);+ assert.equal(JSON.parse(result.out).version, 1);+ }+ const next = box.run(box.web, 'next', '--json');+ assert.ok([0, 1].includes(next.code), next.err + next.out);+ assert.equal(board.db.prepare("SELECT COUNT(*) AS n FROM item WHERE item_status='claimed'").get().n, 0, 'the next control really makes no claim');+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 0, 'none of the read commands writes the private sidecar');+ } finally { board.db.exec('ROLLBACK'); }+ const shouted = box.run(box.web, 'shout', 'coordinator', 'Committed write refreshes this seat', '--json');+ assert.equal(shouted.code, 0, shouted.err + shouted.out);+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1);+ const shout = board.db.prepare('SELECT shout_at FROM shout WHERE shout_from=? ORDER BY shout_id DESC LIMIT 1').get('web-1');+ const observed = local.prepare('SELECT at FROM heartbeat WHERE seat=?').get(key).at;+ assert.ok(Date.parse(observed) >= Date.parse(shout.shout_at), 'the local refresh follows the committed native shout');+ local.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run(stale, key);+ local.exec('UPDATE writes SET n=0');+ const refused = box.run(box.web, 'shout', 'missing-reader', 'This write must refuse', '--json');+ assert.equal(refused.code, 1, refused.err + refused.out);+ assert.equal(JSON.parse(refused.out).error.code, 'NO_READER');+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 0, 'a refused native write cannot refresh presence');+ const events = board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n;+ const hook = box.run(box.web, 'heartbeat', '--json');+ assert.equal(hook.code, 0, hook.err + hook.out);+ assert.equal(JSON.parse(hook.out).presence, 'live');+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, 'an explicit agent hook still refreshes the stale private observation');+ assert.equal(board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n, events, 'the hook remains local, not an ordered move');+ local.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run(stale, key);+ local.exec('UPDATE writes SET n=0');+ const resumed = box.run(box.web, 'resume', '--json');+ assert.equal(resumed.code, 0, resumed.err + resumed.out);+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 0, 'public resume is not an activity hook');+ const { readFileSync } = await import('node:fs');+ const { runFixtureChild } = await import('./fixture-child.js');+ const settings = JSON.parse(readFileSync(join(box.web, '.claude', 'settings.json'), 'utf8'));+ const command = settings.hooks.SessionStart[0].hooks[0].command;- assert.ok(command.includes('pullboard heartbeat') && command.includes('pullboard resume'));++ assert.ok(command.includes('hook SessionStart'));+ const session = runFixtureChild('sh', ['-c', command], { cwd: box.web, env: box.env, encoding: 'utf8' });+ assert.equal(session.status, 0, session.failure || session.stderr || session.stdout);+ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, 'SessionStart explicitly observes activity before its read-only resume');++ for (const event of ['Stop', 'SessionEnd']) {++ local.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run(stale, key);++ local.exec('UPDATE writes SET n=0');++ const command = settings.hooks[event].at(-1).hooks[0].command;++ const observed = runFixtureChild('sh', ['-c', command], { cwd: box.web, env: box.env, encoding: 'utf8' });++ assert.equal(observed.status, 0, observed.failure || observed.stderr || observed.stdout);++ assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, `${event} records actual local activity`);++ assert.equal(board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n, events, `${event} never writes shared history`);++ }+});+++test('explicit SessionStart observation upgrades an existing resume hook without rewriting it [B3,I6]', async (t) => {+ const { createE2eHelpers } = await import('./e2e-helpers.js');+ const { readFileSync, writeFileSync } = await import('node:fs');+ const helpers = createE2eHelpers();+ t.after(helpers.cleanup);+ const box = helpers.project('true');+ const file = join(box.repo, '.claude', 'settings.json');+ const settings = JSON.parse(readFileSync(file, 'utf8'));+ const custom = { matcher: 'startup', hooks: [{ type: 'command', command: 'echo custom; pullboard resume', timeout: 17 }] };+ settings.hooks.SessionStart = [custom];+ writeFileSync(file, JSON.stringify(settings));+ const upgraded = box.run(box.repo, 'init', '--verbose');+ assert.equal(upgraded.code, 0, upgraded.err + upgraded.out);+ const after = JSON.parse(readFileSync(file, 'utf8'));+ assert.equal(after.hooks.SessionStart.length, 2);- assert.ok(after.hooks.SessionStart[0].hooks[0].command.includes('pullboard heartbeat'));++ assert.ok(after.hooks.SessionStart[0].hooks[0].command.includes('hook SessionStart'));+ assert.deepEqual(after.hooks.SessionStart[1], custom, 'the existing user hook bytes remain its own command');+ const again = box.run(box.repo, 'init', '--verbose');+ assert.equal(again.code, 0, again.err + again.out);+ assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), after, 'repeated init never duplicates the observation hook');+});