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(presence): observe local seat heartbeats [B3,I6,A7]

Corey Olson77e41bc2c691
diff --git a/src/board-query.js b/src/board-query.js
index 60202e5c..a3e2837f 100644
--- a/src/board-query.js
+++ b/src/board-query.js
@@ -1,3 +1,4 @@
+import { withSeatPresence } from './seat-presence.js';
import { itemById } from './board-item-read.js';
export { itemById };
import { outsideSource } from './outside-source.js';
@@ -277,7 +278,7 @@ export function agentModel(board, id) {
/** Attach an agent's model to a row from the legacy stable agent table. */
export function withModel(board, agent) {
- return agent ? { ...agent, agent_model: agentModel(board, agent.agent_id), agent_parent_session: agentParent(board, agent.agent_id) } : agent;
+ return agent ? withSeatPresence(board, [{ ...agent, agent_model: agentModel(board, agent.agent_id), agent_parent_session: agentParent(board, agent.agent_id) }])[0] : agent;
}
/**
@@ -287,9 +288,9 @@ export function withModel(board, agent) {
* @returns {any[]}
*/
export function listAgents(board) {
- return board.db.prepare(`SELECT agent.*, model.meta_value AS agent_model, parent.meta_value AS agent_parent_session FROM agent
+ return withSeatPresence(board, board.db.prepare(`SELECT agent.*, model.meta_value AS agent_model, parent.meta_value AS agent_parent_session FROM agent
LEFT JOIN board_meta model ON model.meta_key='agent_model:' || agent.agent_id
- LEFT JOIN board_meta parent ON parent.meta_key='agent_parent_session:' || agent.agent_id ORDER BY agent.rowid`).all();
+ LEFT JOIN board_meta parent ON parent.meta_key='agent_parent_session:' || agent.agent_id ORDER BY agent.rowid`).all());
}
/** The optional engine-20 fields of a fact, present only when its event set them. */
diff --git a/src/board.js b/src/board.js
index 79f49d64..d3746cb2 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1,3 +1,4 @@
+import { heartbeatSeat } from './seat-presence.js';
import { ensureProofCounters } from './proof-counters.js';
import { correctedNoVerdictReopen } from './reopen-history.js';
import {
@@ -593,6 +594,7 @@ export function register(board, who) {
if (lineage) board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_lineage:${id}`, lineage);
}
logEvent(board, id, 'join', null, route === 'strong' ? { lane } : { lane, route });
+ if (board.executionEngineVersion === undefined) heartbeatSeat(board, id);
return id;
});
}
diff --git a/src/cli-main.js b/src/cli-main.js
index 0bad3f05..0dfd4133 100644
--- a/src/cli-main.js
+++ b/src/cli-main.js
@@ -303,7 +303,10 @@ async function runMain(argv, streams) {
}
}
try {
- if (needsRepo) await rememberTrunk(io, git);
+ if (needsRepo) {
+ (await import('./cli-presence.js')).heartbeatCommand(io);
+ await rememberTrunk(io, git);
+ }
traceServeStartup('cli-command-preamble-start');
// The relay and baseline work loads only where a relay token, relay state, a link or a pending result exists.
/** Load the work around the command when any of it could act here, or null. */
@@ -311,7 +314,10 @@ async function runMain(argv, streams) {
await (await syncWork())?.syncBefore(io, main);
traceServeStartup('cli-command-preamble-ready');
const code = await runCommand(argv, io);
- if (code === 0) await checkoutSession?.finish?.();
+ 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);
if (status === 0 && needsRepo && !parsed?.values['dry-run']) (await import('./blocks.js')).clearCompletedBlocks(io);
diff --git a/src/cli-presence.js b/src/cli-presence.js
new file mode 100644
index 00000000..127a44ba
--- /dev/null
+++ b/src/cli-presence.js
@@ -0,0 +1,21 @@
+/** One authenticated, machine-local heartbeat per command, independent of shared-board write locks [B3]. */
+import { context } from './cli-read-context.js';
+import { agentAt, closeBoard, openBoardForRead } from './board-query.js';
+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) {
+ if (recorded.has(io)) return;
+ let board;
+ try {
+ const ctx = context(io);
+ board = openBoardForRead(ctx.file, ctx.clock);
+ if (!board) return;
+ const seat = agentAt(board, ctx.info.root);
+ if (seat && heartbeatSeat(board, seat.agent_id)) recorded.add(io);
+ } catch (error) {
+ if (error.code !== 'NO_CONFIG') io.err(`presence heartbeat unavailable: ${error.message}`);
+ } finally { if (board) closeBoard(board); }
+}
diff --git a/src/commands/heartbeat.js b/src/commands/heartbeat.js
new file mode 100644
index 00000000..53f3f628
--- /dev/null
+++ b/src/commands/heartbeat.js
@@ -0,0 +1,12 @@
+/** 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. */
+export async function run(io) {
+ const ctx = context(io);
+ const seat = await withBoardRead(ctx, board => 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/commands/status.js b/src/commands/status.js
index 9e5bb7e9..412f63e8 100644
--- a/src/commands/status.js
+++ b/src/commands/status.js
@@ -38,7 +38,7 @@ export async function run(io, { values }) {
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(),
+ return { me, mine, agents: store.listAgents(board), 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) };
});
if (values.json) {
@@ -53,6 +53,7 @@ export async function run(io, { values }) {
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));
+ for (const seat of summary.agents) io.say(`${seat.agent_id}: ${seat.presence}${seat.heartbeatAt ? ` (heartbeat ${seat.heartbeatAt})` : ' (no local heartbeat)'}`);
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 --git a/src/help.js b/src/help.js
index 0bf71342..40f52217 100644
--- a/src/help.js
+++ b/src/help.js
@@ -66,6 +66,7 @@ Set up
pullboard relay revoke <token-id> revoke one token from that list; other agents keep working
pullboard relay recover --skip <sequence> person-only recovery of one blocked next relay position
pullboard handoff [--take <id>] write or take an agent hand-off; keep questions on its item
+ pullboard heartbeat record this seat's local session activity; no board move
pullboard resume [--diagnostics] where you are: your claim, branch, what came back,
unread shouts, what to do next; run it to start any session
pullboard badge write board-derived Shields endpoint JSON to docs/badges/
diff --git a/src/init.js b/src/init.js
index f30c9a79..e462bedc 100644
--- a/src/init.js
+++ b/src/init.js
@@ -711,9 +711,17 @@ function writeSessionHook(root, onWrite) {
return 'kept .claude/settings.json, which is not a JSON object; add a SessionStart hook that runs pullboard resume';
}
}
- const starts = settings.hooks?.SessionStart ?? [];
- if (JSON.stringify(starts).includes('pullboard resume')) return 'kept the Claude Code session hook';
- settings.hooks = { ...settings.hooks, SessionStart: [...starts, { hooks: [{ type: 'command', command: RESUME_HOOK, timeout: 30 }] }] };
+ settings.hooks = { ...settings.hooks };
+ let changed = false;
+ for (const [event, command] of [['SessionStart', RESUME_HOOK], ['Stop', 'pullboard heartbeat'], ['SessionEnd', 'pullboard heartbeat']]) {
+ const hooks = settings.hooks[event] ?? [];
+ if (!Array.isArray(hooks)) continue;
+ if (!JSON.stringify(hooks).includes(command)) {
+ settings.hooks[event] = [...hooks, { hooks: [{ type: 'command', command, timeout: 30 }] }];
+ changed = true;
+ }
+ }
+ if (!changed) return 'kept the Claude Code session hook';
mkdirSync(join(root, '.claude'), { recursive: true });
writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
onWrite('.claude/settings.json');
diff --git a/src/json.js b/src/json.js
index a2ca0c7a..b213b691 100644
--- a/src/json.js
+++ b/src/json.js
@@ -45,6 +45,7 @@ export const JSON_SHAPES = {
badge: shape({ items: 'number', checked: 'number', percent: 'number|null', changed: 'array' }),
status: shape({ me: 'object', mine: 'array', ruleCounts: 'object', stats: 'object', reviewQueue: 'object', unread: 'number', relay: 'object' }),
doctor: shape({ problems: 'array' }),
+ heartbeat: shape({ seat: 'string', presence: 'string', heartbeatAt: 'string' }),
health: shape({ asOf: 'string', thresholds: 'object', stuck: 'array', waiting: 'array' }),
'sentinel propose': shape({ sentinel: 'object' }),
'sentinel approve': shape({ sentinel: 'object' }),
diff --git a/src/seat-presence.js b/src/seat-presence.js
new file mode 100644
index 00000000..211cbd88
--- /dev/null
+++ b/src/seat-presence.js
@@ -0,0 +1,51 @@
+/** Machine-local heartbeat observations never enter board events, export or relay [B3]. */
+import { existsSync } from 'node:fs';
+import { DatabaseSync } from 'node:sqlite';
+
+const memory = new WeakMap();
+
+/** Locate a board's private observation sidecar without changing the shared board schema. */
+function observationFile(board) {
+ const file = board.db.prepare('PRAGMA database_list').all().find(row => row.name === 'main')?.file;
+ return file ? `${file}.presence.sqlite` : null;
+}
+
+/** Update exactly one local seat row; registration and command activity are observations, not moves. */
+export function heartbeatSeat(board, id) {
+ if (!board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(id)) return false;
+ const at = board.clock.now().toISOString();
+ const file = observationFile(board);
+ if (!file) {
+ const rows = memory.get(board.db) ?? new Map();
+ rows.set(id, at);
+ memory.set(board.db, rows);
+ return true;
+ }
+ const db = new DatabaseSync(file);
+ try {
+ db.exec('PRAGMA busy_timeout=250; CREATE TABLE IF NOT EXISTS heartbeat(seat TEXT PRIMARY KEY, at TEXT NOT NULL)');
+ db.prepare('INSERT INTO heartbeat(seat,at) VALUES (?,?) ON CONFLICT(seat) DO UPDATE SET at=excluded.at').run(id, at);
+ return true;
+ } finally { db.close(); }
+}
+
+/** Read all local observations once; an unseen seat is gone, never inferred alive from shared history. */
+function heartbeatRows(board) {
+ const file = observationFile(board);
+ if (!file) return memory.get(board.db) ?? new Map();
+ if (!existsSync(file)) return new Map();
+ const db = new DatabaseSync(file, { readOnly: true });
+ try { return new Map(db.prepare('SELECT seat,at FROM heartbeat').all().map(row => [row.seat, row.at])); }
+ finally { db.close(); }
+}
+
+/** Project exact ten/thirty-minute boundaries while retaining the seat's permanent identity. */
+export function withSeatPresence(board, seats) {
+ const rows = heartbeatRows(board);
+ const now = board.clock.now().getTime();
+ return seats.map(seat => {
+ const heartbeatAt = rows.get(seat.agent_id) ?? null;
+ const elapsed = heartbeatAt === null ? Infinity : Math.max(0, now - Date.parse(heartbeatAt));
+ return { ...seat, heartbeatAt, presence: elapsed < 600_000 ? 'live' : elapsed < 1_800_000 ? 'idle' : 'gone' };
+ });
+}
diff --git a/test/presence.test.js b/test/presence.test.js
index 4eec2cee..79404f93 100644
--- a/test/presence.test.js
+++ b/test/presence.test.js
@@ -23,3 +23,62 @@ test('a seat presence moves live to idle to gone from its heartbeat [B3]', (t) =
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 and session hooks heartbeat the local seat 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());
+ local.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run('2000-01-01T00:00:00.000Z', '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');
+ 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 presence row update per read command');
+ 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);
+ }
+ 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');
+});