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
fix(presence): observe writes and explicit hooks only [B3,C7,I6]
Corey Olson2ab59f04f5be
diff --git a/src/cli-main.js b/src/cli-main.jsindex 89887172..152c47a5 100644--- a/src/cli-main.js+++ b/src/cli-main.js@@ -308,7 +308,6 @@ async function runMain(argv, streams) {}try {if (needsRepo) {- (await import('./cli-presence.js')).heartbeatCommand(io);await rememberTrunk(io, git);}traceServeStartup('cli-command-preamble-start');@@ -320,7 +319,6 @@ async function runMain(argv, streams) {const code = await runCommand(argv, io);if (code === 0) {await checkoutSession?.finish?.();- if (needsRepo) (await import('./cli-presence.js')).heartbeatCommand(io);}if (code === 0) await (await syncWork())?.retrySync(io);const status = io.exitCode(code);diff --git a/src/cli-presence.js b/src/cli-presence.jsindex d35e1045..672c661e 100644--- a/src/cli-presence.js+++ b/src/cli-presence.js@@ -1,4 +1,4 @@-/** One authenticated, machine-local heartbeat per command, independent of shared-board write locks [B3]. */+/** Authenticated machine-local activity only at explicit hooks or successful native writes [B3]. */import { context } from './cli-read-context.js';import {closeBoard,@@ -9,17 +9,17 @@ import { heartbeatSeat } from './seat-presence.js';const recorded = new WeakSet();/** Observe only the registered local checkout after normal session binding; unknown callers gain no identity. */-export function heartbeatCommand(io) {+export function heartbeatCommand(io, { ctx: suppliedContext, board: suppliedBoard } = {}) {if (recorded.has(io)) return;let board;try {- const ctx = context(io);- board = openBoardForRead(ctx.file, ctx.clock);+ const ctx = suppliedContext ?? context(io);+ board = suppliedBoard ?? openBoardForRead(ctx.file, ctx.clock);if (!board) return;// Only the registered id is needed: projecting model/presence would reopen this same sidecar.const seat = board.db.prepare('SELECT agent_id FROM agent WHERE agent_path=?').get(ctx.info.root);if (seat && heartbeatSeat(board, seat.agent_id)) recorded.add(io);} catch (error) {if (!['NO_CONFIG', 'NOT_A_REPO'].includes(error.code)) io.err(`presence heartbeat unavailable: ${error.message}`);- } finally { if (board) closeBoard(board); }+ } finally { if (board && !suppliedBoard) closeBoard(board); }}diff --git a/src/cli.js b/src/cli.jsindex d83617d7..51a988c0 100644--- a/src/cli.js+++ b/src/cli.js@@ -614,6 +614,7 @@ export async function ordered(ctx, board, operation, args) {? relayOperation(ctx.info.root, operation, args, ctx.io, command, applyRequested,requested ? () => { ctx.io.recordedMove = true; } : undefined) : applyRequested());if (requested && gitSyncLinked(ctx.info.root)) ctx.io.recordedMove = true;+ if (requested && ctx.io.recordedMove) (await import('./cli-presence.js')).heartbeatCommand(ctx.io, { ctx, board });return result;};const digest = agentSessionDigest();diff --git a/src/commands/heartbeat.js b/src/commands/heartbeat.jsindex 53f3f628..20809e8d 100644--- a/src/commands/heartbeat.js+++ b/src/commands/heartbeat.js@@ -1,12 +1,16 @@+import { heartbeatCommand } from '../cli-presence.js';/** Agent session hooks observe activity without adding any shared board move [B3]. */import { context } from '../cli-read-context.js';import { withBoardRead } from '../cli-board-read.js';import { agentAt } from '../board-query.js';-/** Report the heartbeat already recorded by the ordinary command entry point. */+/** An explicit agent hook records local activity without turning ordinary reads into writers. */export async function run(io) {const ctx = context(io);- const seat = await withBoardRead(ctx, board => agentAt(board, ctx.info.root));+ const seat = await withBoardRead(ctx, board => {+ heartbeatCommand(io, { ctx, board });+ return agentAt(board, ctx.info.root);+ });io.result?.({ seat: seat?.agent_id ?? null, presence: seat?.presence ?? 'gone', heartbeatAt: seat?.heartbeatAt ?? null });return 0;}diff --git a/src/init.js b/src/init.jsindex 4236cfcb..2175715d 100644--- a/src/init.js+++ b/src/init.js@@ -414,8 +414,12 @@ function writeAgentDocs(root, onWrite) {* The session hook's command: pullboard from this checkout's install, else the main checkout's,* else the PATH, and silence when there is none, so a session never fails to start over it.*/-export const RESUME_HOOK =+const RESUME_ONLY_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 HEARTBEAT_HOOK = RESUME_ONLY_HOOK.replaceAll(' resume', ' heartbeat');+export const RESUME_HOOK = RESUME_ONLY_HOOK+ .replace('[ -x "$p" ] && exec "$p" resume', 'if [ -x "$p" ]; then "$p" heartbeat >/dev/null 2>&1; exec "$p" resume; fi')+ .replace('command -v pullboard >/dev/null && exec pullboard resume', 'if command -v pullboard >/dev/null; then pullboard heartbeat >/dev/null 2>&1; exec pullboard resume; fi');/*** The MCP server command: pullboard from this checkout's install, else the main checkout's, else the PATH (#961).@@ -713,9 +717,14 @@ function writeSessionHook(root, onWrite) {}settings.hooks = { ...settings.hooks };let changed = false;- for (const [event, command] of [['SessionStart', RESUME_HOOK], ['Stop', RESUME_HOOK.replaceAll(' resume', ' heartbeat')], ['SessionEnd', RESUME_HOOK.replaceAll(' resume', ' heartbeat')]]) {+ for (const [event, command] of [['SessionStart', RESUME_HOOK], ['Stop', HEARTBEAT_HOOK], ['SessionEnd', HEARTBEAT_HOOK]]) {const hooks = settings.hooks[event] ?? [];if (!Array.isArray(hooks)) continue;+ if (event === 'SessionStart' && JSON.stringify(hooks).includes('pullboard resume') && !JSON.stringify(hooks).includes('pullboard heartbeat')) {+ // Preserve every existing command, including custom resume hooks; add an explicit local observation first.+ settings.hooks[event] = [{ hooks: [{ type: 'command', command: `(${HEARTBEAT_HOOK}) >/dev/null 2>&1 || true`, timeout: 30 }] }, ...hooks];+ changed = true;+ }if (!JSON.stringify(hooks).includes(event === 'SessionStart' ? 'pullboard resume' : 'pullboard heartbeat')) {settings.hooks[event] = [...hooks, { hooks: [{ type: 'command', command, timeout: 30 }] }];changed = true;diff --git a/test/e2e-cli.test.js b/test/e2e-cli.test.jsindex 65562f9c..3f74f4ff 100644--- a/test/e2e-cli.test.js+++ b/test/e2e-cli.test.js@@ -51,8 +51,9 @@ test('init adds a Claude Code session hook that runs resume, and keeps every othassert.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(), ['SessionStart', 'Stop'], 'init adds no other hook event');- assert.deepEqual(settings.hooks.Stop, mine.hooks.Stop);+ 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.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 --git a/test/presence.test.js b/test/presence.test.jsindex 05ca3c1e..631832db 100644--- a/test/presence.test.js+++ b/test/presence.test.js@@ -47,7 +47,7 @@ test('local heartbeats revive a seat without changing exported history or a remoassert.equal(heartbeatSeat(board, 'missing-seat'), false);});-test('status and session hooks heartbeat the local seat without a shared board write [B3,I6]', async (t) => {+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');@@ -68,11 +68,14 @@ test('status and session hooks heartbeat the local seat without a shared board wconst 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, 'live');- assert.equal(local.prepare('SELECT n FROM writes').get().n, 1, 'one stale observation refresh while the shared board is write-locked');+ 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');@@ -230,4 +233,40 @@ test('read commands never refresh presence while committed writes and hooks do [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'));+ 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');+});+++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.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');});