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.

fix(stats): warm counters and disclose cold reads [R1,R2,C7]

Corey Olson4ad7261c76a6
diff --git a/docs/api.md b/docs/api.md
index 5211f519..014bd14c 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -57,7 +57,7 @@ The single recommended action uses the first matching rule: review wait with few
`stats.flow.unreviewed` is a current `{size, oldest}` queue using the same `{id, since, ageMinutes}` shape and observation as the other queues. It contains submitted items with no verdict since their final submit and no live reviewer reservation; released or expired reservations count as unreserved, and their age still starts at the final submit.
-The coordinator's `resume` ends with one `flow:` line if the measured review-wait average is strictly greater than **60 minutes**, or the oldest currently unreviewed submission is strictly older than **180 minutes**. Exact boundaries do not trip. Both thresholds share one line if both trip. The line gives the tripped threshold's numbers, the measured bottleneck stage, its share and total cycle minutes, and the same recommended action as `stats`. It does not replace a measured build, review or merge bottleneck with review wait. Without a fully measured cycle, a trip still names its threshold and waiting item, followed by **bottleneck: not measured yet**, with no invented stage or action. A healthy or unmeasured board with no trip adds no line. Agent resumes do not add this line. Coordinator resume JSON includes the same `flow` observation as stats.
+The coordinator's `resume` ends with one `flow:` line if the measured review-wait average is strictly greater than **60 minutes**, or the oldest currently unreviewed submission is strictly older than **180 minutes**. Exact boundaries do not trip. Both thresholds share one line if both trip. The line gives the tripped threshold's numbers, the measured bottleneck stage, its share and total cycle minutes, and the same recommended action as `stats`. It does not replace a measured build, review or merge bottleneck with review wait. Without a fully measured cycle, a trip still names its threshold and waiting item, followed by **bottleneck: not measured yet**, with no invented stage or action. A healthy or unmeasured board with no trip adds no line. Agent resumes do not add this line. Coordinator resume JSON includes the same `flow` observation as stats. If its local proof counters are unavailable, resume computes the complete legacy result and explains that fallback in text and the optional `proofStatsFallback` JSON field. A read never builds counters; the next writable command builds or catches them up. The field is absent when current counters serve the result.
The coordinator's `resume` opens, after its header line, with its inbox: `inbox: <n> unread shouts, <n> open decisions for you`, then the newest three unread shouts by id, sender, age and first line, then `<n> more; read them all with pullboard inbox` when there are more. Only shouts to the coordinator, its lane or all count. While shouts are unread its `next:` reads `read your <n> unread shouts first: pullboard inbox; then ...`. Resume marks nothing read; `inbox` does. Coordinator resume JSON carries the same as `inbox: {unread, decisions, newest: [{id, from, at, text}], more, read}`.
diff --git a/src/board.js b/src/board.js
index b1272a9f..f57f106d 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1,3 +1,4 @@
+import { ensureProofCounters } from './proof-counters.js';
import {
lineOrderEnabled,
lineBuildOrder,
@@ -316,6 +317,7 @@ export function openBoard(file, clock = systemClock, { isMain, onDiagnostic } =
db.exec(`PRAGMA busy_timeout = ${BOARD_BUSY_TIMEOUT_MS}`);
if (file !== ':memory:' && isMain !== false) db.exec('PRAGMA journal_mode = WAL');
const board = { db, clock };
+ let warmCounters = true;
if (isMain !== false || file === ':memory:') {
// Migrate and audit only a board whose version is behind; a drifted shape is reported and left alone (#1047).
const standing = boardStanding(db, SCHEMA_DIGEST, SCHEMA_VERSION, readEventLogVersion(db) < EVENT_LOG_VERSION);
@@ -327,13 +329,16 @@ export function openBoard(file, clock = systemClock, { isMain, onDiagnostic } =
guardStore(board);
}
if (standing === 'behind' || standing === 'unstamped') recordSchemaStamp(db, SCHEMA_DIGEST);
- if (standing === 'drifted') reportDrift(file, onDiagnostic);
+ if (standing === 'drifted') { warmCounters = false; reportDrift(file, onDiagnostic); }
} else {
// Read compatibility before any local effect; persistent schema belongs to trunk alone.
readEventLogVersion(db);
reportSharedSchema(file, sharedSchemaDiagnostic(db, expectedBoardSchema(SCHEMA, migrate, storeTriggers)), onDiagnostic);
}
guardMoves(board);
+ // Writable commands catch up old writers or missing local projections once. Read-only open
+ // never calls this path; drifted stores remain untouched, and invalid history stays invalid.
+ if (warmCounters) atomic(board, () => ensureProofCounters(board));
return board;
} catch (error) {
try { db?.close(); } catch {}
diff --git a/src/commands/resume.js b/src/commands/resume.js
index 0888bd6a..83c1eaf2 100644
--- a/src/commands/resume.js
+++ b/src/commands/resume.js
@@ -175,6 +175,13 @@ export async function resumeHere(io, view, diagnostics = false, { json = false }
const decisionSections = isMain ? coordinatorDecisionSections(board, ctx) : null;
const { shouts = [], ...decisions } = decisionSections ?? {};
const needsState = resumeNeeds(root, { board, config: ctx.config, includeRigorUndrafted: me.id === COORDINATOR });
+ let proofStatsFallback;
+ const flow = decisionSections ? proofStats(board, { now: ctx.clock.now().getTime(),
+ /** Keep the cold-path notice in text and JSON without changing the statistics object. */
+ onFallback: () => {
+ proofStatsFallback = 'Proof statistics: counters are unavailable; reading the complete event history for this resume. The next writable command will build the counters.';
+ },
+ }).flow : null;
return {
me,
health: recordedHealthFindings(board),
@@ -182,7 +189,7 @@ export async function resumeHere(io, view, diagnostics = false, { json = false }
needsYou: personNeeds(needsState),
...(me.id === COORDINATOR ? { rigor: { undrafted: needsState.rigorUndrafted } } : {}),
...(decisionSections ? { ...decisions, ...(diagnostics ? verifiedMergeGroups(root, pendingMerges, shouts, ctx.clock.now().getTime()) : {}),
- flow: proofStats(board, { now: ctx.clock.now().getTime() }).flow } : {}),
+ flow, ...(proofStatsFallback ? { proofStatsFallback } : {}) } : {}),
requests: me.id === COORDINATOR ? store.openRequests(board) : [],
holding: all.filter((item) => item.item_status === 'claimed' && item.item_owner === me.id),
held: all.filter((item) => item.item_status === 'claimed' && item.item_owner === me.id)
@@ -234,6 +241,7 @@ export async function resumeHere(io, view, diagnostics = false, { json = false }
for (const problem of card.hookProblems ?? []) say(`${problem.message}; ${problem.next}`);
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
say(`resume: ${me.displayName}${me.family ? ` [family ${me.family}]` : ''}, ${me.lane} lane${isMain ? ', the main checkout' : ''}, at ${root}`);
+ if (card.proofStatsFallback) say(card.proofStatsFallback);
if (card.health.recordedAt) {
say(`Health recorded ${card.health.recordedAt}: ${card.health.findings.length} finding${card.health.findings.length === 1 ? '' : 's'}; refresh with pullboard sentinel run.`);
for (const finding of card.health.findings) say(` ${finding.subject}: ${finding.why}; next: ${finding.next}`);
diff --git a/src/stats.js b/src/stats.js
index 52a91f0c..8cf5bc09 100644
--- a/src/stats.js
+++ b/src/stats.js
@@ -98,19 +98,20 @@ function actorsFrom(history, boundary) {
}
/** Assemble the public statistics shared by the CLI and local board state from one event snapshot. */
-export function proofStats(board, { since, now = Date.now() } = {}) {
+export function proofStats(board, { since, now = Date.now(), onFallback } = {}) {
const boundary = sinceDate(since);
// A SAVEPOINT is read-only until a write occurs, and nests inside callers' transactions.
// Hold one snapshot across the cursor, projection shards, and verdicts while other seats append.
board.db.exec('SAVEPOINT proof_stats_read');
- try { return proofStatsSnapshot(board, boundary, now); }
+ try { return proofStatsSnapshot(board, boundary, now, onFallback); }
finally { board.db.exec('RELEASE proof_stats_read'); }
}
/** Assemble cached or legacy statistics within the caller's already established read snapshot. */
-function proofStatsSnapshot(board, boundary, now) {
+function proofStatsSnapshot(board, boundary, now, onFallback) {
const counted = counterProofStats(board, boundary, now);
if (counted) return counted;
+ onFallback?.();
const history = events(board);
const counts = countsFrom(history, boundary);
const verdicts = board.db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all();
diff --git a/test/stats-cold.test.js b/test/stats-cold.test.js
new file mode 100644
index 00000000..6b9577d5
--- /dev/null
+++ b/test/stats-cold.test.js
@@ -0,0 +1,128 @@
+/** Counter availability selects the real proof-statistics path without changing historical results [R1,R2,C7]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { test } from 'node:test';
+import { DatabaseSync } from 'node:sqlite';
+import { runFixtureChild, runFixtureGit } from './fixture-child.js';
+import { addItem, closeBoard, openBoard, openBoardForRead, register } from '../src/board.js';
+import { clearProofCounters, currentProofCounters, proofCounter } from '../src/proof-counters.js';
+import { proofStats } from '../src/stats.js';
+import { proofStats as legacyProofStats } from './fixtures/proof-stats-legacy.js';
+
+/** Record actual prepared statements while preserving native SQLite receiver bindings. */
+function recordingBoard(board, statements) {
+ const db = new Proxy(board.db, {
+ /** Observe SQL without changing its result, admission, or transaction behavior. */
+ get(target, key) {
+ if (key === 'prepare') return (sql) => { statements.push(sql); return target.prepare(sql); };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ return { ...board, db };
+}
+
+/** Make a private on-disk board using native moves, then emulate an older writer or a missing local cache. */
+function fixture(t, state) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-stats-cold-'));
+ const file = join(directory, 'board.sqlite');
+ const clock = { now: () => new Date('2026-10-01T00:00:00.000Z') };
+ const board = openBoard(file, clock);
+ try {
+ register(board, { lane: 'coordinator', path: '/fixture/coordinator' });
+ const id = addItem(board, { by: 'coordinator', lane: 'web', title: 'Historical proof', criterion: 'all events remain counted' });
+ assert.ok(currentProofCounters(board), 'native moves built current counters');
+ if (state === 'stale') {
+ board.db.prepare('INSERT INTO event(event_at,event_by,event_kind,item_id,event_detail) VALUES (?,?,?,?,?)')
+ .run('2026-10-02T00:00:00.000Z', 'coordinator', 'submit', id, JSON.stringify({ commit: 'a'.repeat(40) }));
+ assert.ok(proofCounter(board, 'summary'), 'stale is present, not absent');
+ assert.equal(currentProofCounters(board), null, 'the real older-writer event makes the cursor stale');
+ }
+ if (state === 'absent') {
+ clearProofCounters(board);
+ assert.equal(proofCounter(board, 'summary'), null);
+ }
+ } finally { closeBoard(board); }
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ return { file, clock };
+}
+
+for (const state of ['current', 'stale', 'absent']) {
+ test(`proof stats ${state} counters preserve legacy results; writable open repairs cold state [R1,R2,C7]`, (t) => {
+ const { file, clock } = fixture(t, state);
+ const options = { now: Date.parse('2026-10-03T00:00:00.000Z') };
+ let expected;
+ const reader = openBoardForRead(file, clock);
+ try {
+ const statements = [];
+ const notices = [];
+ const changes = reader.db.prepare('SELECT total_changes() AS n').get().n;
+ expected = legacyProofStats(reader, options);
+ assert.deepEqual(proofStats(recordingBoard(reader, statements), { ...options, onFallback: () => notices.push('legacy') }), expected);
+ assert.equal(notices.length, state === 'current' ? 0 : 1, 'only an actual legacy read announces fallback');
+ assert.equal(statements.some(sql => /^SELECT \* FROM event ORDER BY event_id$/u.test(sql)), state !== 'current');
+ assert.equal(reader.db.prepare('SELECT total_changes() AS n').get().n, changes, 'readonly statistics never warm the counters');
+ assert.equal(currentProofCounters(reader) !== null, state === 'current', 'reading leaves the cache availability unchanged');
+ } finally { closeBoard(reader); }
+
+ // This is the real writable opener used by ordinary commands, not a manual cache repair.
+ closeBoard(openBoard(file, clock));
+ const warmed = openBoardForRead(file, clock);
+ try {
+ assert.ok(currentProofCounters(warmed), 'the next writable open automatically builds or catches up counters');
+ const statements = [];
+ let notices = 0;
+ assert.deepEqual(proofStats(recordingBoard(warmed, statements), { ...options, onFallback: () => { notices += 1; } }), expected);
+ assert.equal(notices, 0);
+ assert.equal(statements.some(sql => /^SELECT \* FROM event ORDER BY event_id$/u.test(sql)), false, 'the repaired hot path never replays the whole event table');
+ } finally { closeBoard(warmed); }
+ });
+}
+
+/** Exercise the user-visible cold notice through the actual CLI in an isolated real Git repository. */
+test('resume announces complete proof fallback in text and JSON until a native write repairs counters [N19,R1,R2,C7]', (t) => {
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-resume-cold-')));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const repo = join(directory, 'repo');
+ mkdirSync(repo);
+ const shims = join(directory, 'bin');
+ mkdirSync(shims);
+ const bin = resolve(import.meta.dirname, '../bin/pullboard.js');
+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "${bin}" "$@"\n`, { mode: 0o755 });
+ const env = { ...process.env, PATH: `${shims}:${process.env.PATH}`, PULLBOARD_VIEW_BACKGROUND: '0',
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Test Agent', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test Agent', GIT_COMMITTER_EMAIL: '[email protected]',
+ PULLBOARD_HOME: join(directory, 'home'), PULLBOARD_MACHINE_HOME: join(directory, 'machine-home'),
+ };
+ delete env.PULLBOARD_RELAY_TOKEN;
+ /** Run real Git using only the fixture identity and checkout. */
+ const git = (...args) => runFixtureGit(args, { cwd: repo, env });
+ /** Run the production CLI and preserve any actual setup failure. */
+ const run = (...args) => {
+ const result = runFixtureChild(process.execPath, [bin, ...args], { cwd: repo, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.failure || result.stderr || result.stdout);
+ return result.stdout;
+ };
+ git('init', '-q', '-b', 'main');
+ run('init');
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true', spec: 'SPEC.md', verify: 'any', lease: '2h', lanes: { web: { owns: ['web/'], specs: ['G1'] } } }));
+ writeFileSync(join(repo, 'SPEC.md'), '# Proof fixture\n\n## G · Goals\n- G1 [approved, must] Proof history stays complete. | gate: test\n');
+ git('add', '-A');
+ git('commit', '-q', '-m', 'chore: create cold resume fixture');
+ run('resume', '--json'); // Finish any first-resume native bookkeeping before making the cache cold.
+ const file = join(git('rev-parse', '--path-format=absolute', '--git-common-dir').trim(), 'pullboard', 'board.sqlite');
+ const db = new DatabaseSync(file);
+ try { clearProofCounters({ db }); } finally { db.close(); }
+ const cold = JSON.parse(run('resume', '--json'));
+ assert.match(cold.proofStatsFallback, /counters are unavailable.*complete event history.*next writable command/iu);
+ assert.ok(cold.flow, 'cold resume still returns its complete flow result');
+ const text = run('resume');
+ assert.equal(text.split('\n').filter(line => line === cold.proofStatsFallback).length, 1, 'plain resume announces the actual fallback once');
+ run('shout', 'all', 'A normal native write builds the local counters.');
+ const hot = JSON.parse(run('resume', '--json'));
+ assert.equal(Object.hasOwn(hot, 'proofStatsFallback'), false, 'the next native write ends the cold state');
+ assert.ok(hot.flow);
+});