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(stats): publish event-derived proof numbers [R1,R2]

Corey Olsonfe4bd44b6d3b
diff --git a/docs/api.md b/docs/api.md
index d003ce8f..9a79c4e5 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -12,6 +12,12 @@ A successful command returns the fields listed below. `version` is always the nu
When `add` or `edit` supplies a new nonempty check, Pullboard measures it once in a temporary checkout of the current `main` commit. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `green`, `red`, or `unavailable`. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when filing, showing, or reserving the item for review. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. The captured observation travels with the board move, so replicas store the result without executing the command.
+`pullboard stats [--since <date>] --json` returns `{version: 1, stats: {...}}` from the append-only event log. `submissions` and `rejections` count moves, including repeated attempts; `rejectionShare` is rejections divided by submissions (zero when the window has no submissions). `merged` counts distinct items with a merge move; `mergedWithoutAccept` counts those whose merge lacks an earlier acceptance of the latest submitted commit. That audit uses earlier history even when the acceptance falls before the selected window. Current item and verdict rows do not replace event evidence.
+
+`firstEventAt` and `lastEventAt` are the first and latest dates in the selected window, or `null` when it is empty. `since` is the inclusive boundary as an ISO UTC timestamp, or `null` for the full history. Dates accept `YYYY-MM-DD` or an ISO UTC timestamp ending in `Z`; invalid dates return `BAD_SINCE` with repair guidance.
+
+`agentCount` counts distinct event actors other than `board` and `person`; the coordinator and join moves are included. `agents` lists `{id, moves, families}` for each actor. `families` lists `{name, agents, moves}` by recorded family label, and `familyCount` counts these buckets, including `unknown`. Labels are not inferred from a model name or current agent, item, or verdict rows. A family's first recorded event snapshot applies to that move and following moves, until another snapshot changes or clears it; earlier unattributed moves remain `unknown`. Date windows preserve earlier recorded declarations but count only selected moves. Arrays are sorted by identifier or label. Local HTTP board state carries the same full-history object as `state.proofStats`.
+
<!-- api-command-shapes:start -->
| Command | Required top-level fields |
| --- | --- |
@@ -35,6 +41,7 @@ When `add` or `edit` supplies a new nonempty check, Pullboard measures it once i
| `milestone edit` | `version:number`, `milestone:object` |
| `milestone remove` | `version:number`, `milestone:object` |
| `show` | `version:number`, `item_id:number`, `item_title:string`, `item_lane:string`, `item_status:string`, `verdicts:array` |
+| `stats` | `version:number`, `stats:object` |
| `status` | `version:number`, `me:object`, `mine:array`, `stats:object`, `reviewQueue:object`, `unread:number` |
| `doctor` | `version:number`, `problems:array` |
| `inbox` | `version:number`, `shouts:array` |
diff --git a/src/api.js b/src/api.js
index 582c9aca..3489bfdd 100644
--- a/src/api.js
+++ b/src/api.js
@@ -10,6 +10,7 @@ import { relayLinked, relayOperation } from './relay.js';
import { laneNames } from './lanes.js';
import { listApiProjects } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
+import { proofStats } from './stats.js';
import { projectRowDecisions } from './row-decisions.js';
import { Refused } from './refused.js';
import { codeAt, projectState } from './serve.js';
@@ -205,7 +206,9 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
requests: store.openRequests(db),
milestones: milestoneRoadmap(board.root, db),
rowDecisions: store.rowDecisions(db),
+ proofStats: proofStats(db),
}));
+ state.proofStats = projectData.proofStats;
state.requests = projectData.requests;
state.milestones = projectData.milestones;
state = projectRowDecisions(projectData.rowDecisions, state);
diff --git a/src/cli.js b/src/cli.js
index ac2e81c4..ded59ebf 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -56,6 +56,7 @@ import { exportView, serveView } from './serve.js';
import { serveApi } from './api.js';
import { doctorProblems } from './doctor.js';
import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
+import { proofStats } from './stats.js';
import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots } from './trusted-policy.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
@@ -145,6 +146,7 @@ Coordinator
pullboard hold <lane> --off release it
Receipts
+ pullboard stats [--since <date>] proof numbers from the event log; --json for sites and tools
pullboard ledger markdown: what was built, by whom, verified by whom
pullboard log [id] every move, in order
@@ -177,7 +179,7 @@ const HELP_NAMES = [
'tour', 'init', 'worktree', 'join', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',
'serve', 'relay', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'show', 'next',
'check', 'claim', 'release', 'submit', 'done', 'verify', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import',
- 'sweep', 'merged', 'withdraw', 'refreeze', 'hold', 'ledger', 'log', 'spec', 'spec check', 'spec view',
+ 'sweep', 'merged', 'withdraw', 'refreeze', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view',
'spec show', 'spec unmet', 'spec signoff', 'spec signers', 'spec signers add', 'forget', 'prompt', 'gate', 'hook',
'hook pre-commit', 'hook commit-msg', 'hook pre-push', 'view export', 'version', 'lifecycle', 'help',
'roadmap', 'milestone',
@@ -196,7 +198,7 @@ const HELP_EXAMPLES = {
claim: 'pullboard claim 12', submit: 'pullboard submit 12', 'next --verify': 'pullboard next --verify',
verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',
answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',
- status: 'pullboard status', view: 'pullboard view', log: 'pullboard log 12', ledger: 'pullboard ledger',
+ status: 'pullboard status', view: 'pullboard view', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',
roadmap: 'pullboard roadmap', milestone: 'pullboard milestone add "0.7.0" --items 12,13',
edit: 'pullboard edit 12 --brief "Add the upload page"', release: 'pullboard release 12',
escalate: 'pullboard escalate 12 --note "needs a manual step"', next: 'pullboard next',
@@ -423,6 +425,7 @@ const OPTIONS = {
must: { type: 'boolean' },
json: { type: 'boolean' },
history: { type: 'boolean' },
+ since: { type: 'string' },
decision: { type: 'boolean' },
evidence: { type: 'string' },
outcome: { type: 'string' },
@@ -1338,6 +1341,17 @@ function readCommands(io, { first, second, rest, values }) {
for (const ask of asks) io.say(`#${ask.shout_id} ${ask.shout_from} -> ${ask.shout_to}, ${span(ctx, ask.shout_at)} ago: ${firstLine(ask.shout_text)}`);
return 0;
},
+ stats: () => {
+ const ctx = context(io);
+ const stats = withBoard(ctx, (board) => proofStats(board, { since: values.since }));
+ io.result?.({ stats });
+ io.say(`${stats.submissions} submissions · ${stats.rejections} rejections · ${(stats.rejectionShare * 100).toFixed(1)}% sent back`);
+ io.say(`${stats.merged} items merged · ${stats.mergedWithoutAccept} merged without an accept`);
+ io.say(`${stats.agentCount} agents · ${stats.familyCount} family buckets: ${stats.families.map((family) => `${family.name} (${family.agents} agents, ${family.moves} moves)`).join('; ') || 'none'}`);
+ io.say(`agents: ${stats.agents.map((agent) => `${agent.id} (${agent.families.join('/')}; ${agent.moves} moves)`).join(', ') || 'none'}`);
+ io.say(`events: ${stats.firstEventAt ?? 'none'} to ${stats.lastEventAt ?? 'none'}${stats.since ? ` (since ${stats.since})` : ''}`);
+ return 0;
+ },
ledger: () => {
const ctx = context(io);
const { items, stats } = withBoard(ctx, (board) => ({
diff --git a/src/json.js b/src/json.js
index a61589e7..615e28ff 100644
--- a/src/json.js
+++ b/src/json.js
@@ -29,6 +29,7 @@ export const JSON_SHAPES = {
'milestone edit': shape({ milestone: 'object' }),
'milestone remove': shape({ milestone: 'object' }),
show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array' }),
+ stats: shape({ stats: 'object' }),
status: shape({ me: 'object', mine: 'array', stats: 'object', reviewQueue: 'object', unread: 'number' }),
doctor: shape({ problems: 'array' }),
inbox: shape({ shouts: 'array' }),
diff --git a/src/stats.js b/src/stats.js
new file mode 100644
index 00000000..9a90ff3f
--- /dev/null
+++ b/src/stats.js
@@ -0,0 +1,100 @@
+/** Public proof numbers derived from the append-only event log [R1,R2]. */
+import { events } from './board.js';
+import { Refused } from './refused.js';
+
+/** Parse an inclusive UTC date boundary, refusing malformed or impossible dates. */
+export function sinceDate(value) {
+ if (value === undefined || value === null) return null;
+ const text = String(value);
+ const match = /^(\d{4}-\d{2}-\d{2})(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z)?$/u.exec(text);
+ const milliseconds = match ? Date.parse(text) : NaN;
+ if (!Number.isFinite(milliseconds) || new Date(milliseconds).toISOString().slice(0, 10) !== match?.[1]) {
+ throw new Refused('BAD_SINCE', 'the since date is invalid; use --since YYYY-MM-DD or an ISO UTC timestamp, for example --since 2026-10-08');
+ }
+ return new Date(milliseconds).toISOString();
+}
+
+/** Count moves in a window while auditing merges against their complete earlier history. */
+function countsFrom(history, boundary) {
+ const selected = history.filter((event) => !boundary || Date.parse(event.event_at) >= Date.parse(boundary));
+ const selectedIds = new Set(selected.map((event) => event.event_id));
+ let submissions = 0;
+ let rejections = 0;
+ const merged = new Set();
+ const withoutAccept = new Set();
+ const submitted = new Map();
+ const accepted = new Map();
+ for (const event of history) {
+ const detail = JSON.parse(event.event_detail);
+ if (event.event_kind === 'submit') {
+ submitted.set(event.item_id, detail.commit);
+ accepted.delete(event.item_id);
+ if (selectedIds.has(event.event_id)) submissions += 1;
+ } else if (event.event_kind === 'accept') {
+ if (detail.commit && detail.commit === submitted.get(event.item_id)) accepted.set(event.item_id, detail.commit);
+ } else if (event.event_kind === 'reject') {
+ accepted.delete(event.item_id);
+ if (selectedIds.has(event.event_id)) rejections += 1;
+ } else if (event.event_kind === 'merged' && selectedIds.has(event.event_id)) {
+ merged.add(event.item_id);
+ if (!accepted.has(event.item_id)) withoutAccept.add(event.item_id);
+ }
+ }
+ const dates = selected.map((event) => event.event_at).sort((a, b) => Date.parse(a) - Date.parse(b));
+ return {
+ since: boundary,
+ submissions,
+ rejections,
+ rejectionShare: submissions ? rejections / submissions : 0,
+ merged: merged.size,
+ mergedWithoutAccept: withoutAccept.size,
+ firstEventAt: dates[0] ?? null,
+ lastEventAt: dates.at(-1) ?? null,
+ };
+}
+
+/** Count lifecycle moves from one immutable read of the event history. */
+export function eventCounts(board, { since } = {}) {
+ return countsFrom(events(board), sinceDate(since));
+}
+
+/** Attribute only recorded actor families, retaining earlier declarations across date windows. */
+function actorsFrom(history, boundary) {
+ const declared = new Map();
+ const actors = new Map();
+ const families = new Map();
+ for (const event of history) {
+ const id = event.event_by;
+ if (id === 'board' || id === 'person') continue;
+ const detail = JSON.parse(event.event_detail);
+ if (Object.hasOwn(detail, 'family')) {
+ declared.set(id, typeof detail.family === 'string' && detail.family.trim() ? detail.family : 'unknown');
+ }
+ if (boundary && Date.parse(event.event_at) < Date.parse(boundary)) continue;
+ const name = declared.get(id) ?? 'unknown';
+ if (!actors.has(id)) actors.set(id, { id, moves: 0, families: new Set() });
+ const actor = actors.get(id);
+ actor.moves += 1;
+ actor.families.add(name);
+ if (!families.has(name)) families.set(name, { name, agents: new Set(), moves: 0 });
+ const family = families.get(name);
+ family.moves += 1;
+ family.agents.add(id);
+ }
+ const agents = [...actors.keys()].sort().map((id) => {
+ const actor = actors.get(id);
+ return { ...actor, families: [...actor.families].sort() };
+ });
+ const groups = [...families.keys()].sort().map((name) => {
+ const family = families.get(name);
+ return { ...family, agents: family.agents.size };
+ });
+ return { agentCount: agents.length, familyCount: groups.length, agents, families: groups };
+}
+
+/** Assemble the public statistics shared by the CLI and local board state from one event snapshot. */
+export function proofStats(board, { since } = {}) {
+ const boundary = sinceDate(since);
+ const history = events(board);
+ return { ...countsFrom(history, boundary), ...actorsFrom(history, boundary) };
+}
diff --git a/test/api.test.js b/test/api.test.js
index a1a9cb49..22a2bdf4 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -237,6 +237,7 @@ test('[A1] command results match the catalog across roots and subcommands', () =
assert.equal(existsSync(join(box.env.PULLBOARD_HOME, 'config.json')), false, 'machine settings use the separate settings.json file');
json(box, repo, 'resume');
json(box, repo, 'status');
+ json(box, repo, 'stats');
json(box, repo, 'doctor');
const plainStatus = box.run(repo, 'status');
assert.equal(plainStatus.status, 0, plainStatus.stderr);
diff --git a/test/stats-actors.test.js b/test/stats-actors.test.js
new file mode 100644
index 00000000..05113441
--- /dev/null
+++ b/test/stats-actors.test.js
@@ -0,0 +1,189 @@
+/** Event statistics attribute only recorded actor-family evidence, never current declarations [R1,R2]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { addItem, claim, closeBoard, events, openBoard, register, release } from '../src/board.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { eventCounts, proofStats } from '../src/stats.js';
+
+/** Create a private in-memory board with a controllable clock and its two real actors. */
+function fixture(t) {
+ let at = new Date('2026-02-01T00:00:00.000Z');
+ const board = openBoard(':memory:', { now: () => new Date(at) });
+ t.after(() => closeBoard(board));
+ /** Advance the deterministic event clock. */
+ const setTime = (value) => { at = new Date(value); };
+ setTime('2026-02-01T00:00:00.000Z');
+ register(board, { lane: 'coordinator', path: '/actors/coordinator' });
+ setTime('2026-02-01T00:01:00.000Z');
+ register(board, { lane: 'web', path: '/actors/web-builder', family: 'legacy-family' });
+ return { board, setTime };
+}
+
+/** Add one open web item using the coordinator's public board operation. */
+function addWebItem(f, title, at) {
+ f.setTime(at);
+ return addItem(f.board, { by: 'coordinator', lane: 'web', title, criterion: 'actor events are counted' });
+}
+
+/** Claim and return an item to open so a later action can exercise another event snapshot. */
+function claimAndRelease(f, id, claimAt, releaseAt) {
+ f.setTime(claimAt);
+ claim(f.board, id, {
+ agentId: 'web-1', lane: 'web', leaseMs: 86_400_000,
+ freeze: () => ({ text: 'A stable actor fixture criterion.', digest: 'actor-fixture-digest' }),
+ });
+ f.setTime(releaseAt);
+ release(f.board, id, 'web-1');
+}
+
+/** Build a legacy history before a family change and ordinary moves after that declaration. */
+function familyHistory(t) {
+ const f = fixture(t);
+ const first = addWebItem(f, 'Before family event', '2026-02-02T10:00:00.000Z');
+ claimAndRelease(f, first, '2026-02-02T11:00:00.000Z', '2026-02-02T12:00:00.000Z');
+ f.setTime('2026-02-03T10:00:00.000Z');
+ register(f.board, { lane: 'web', path: '/actors/web-builder', family: 'new-family' });
+ const second = addWebItem(f, 'After family event one', '2026-02-04T10:00:00.000Z');
+ claimAndRelease(f, second, '2026-02-04T11:00:00.000Z', '2026-02-04T12:00:00.000Z');
+ const third = addWebItem(f, 'After family event two', '2026-02-05T10:00:00.000Z');
+ claimAndRelease(f, third, '2026-02-05T11:00:00.000Z', '2026-02-05T12:00:00.000Z');
+ // Emulate the legacy event format even if future joins begin capturing family snapshots.
+ const document = exportBoard(f.board);
+ for (const event of document.tables.event) {
+ if (event.event_kind === 'family') continue;
+ const detail = JSON.parse(event.event_detail);
+ delete detail.family;
+ event.event_detail = JSON.stringify(detail);
+ }
+ return { ...f, board: importedBoard(t, document) };
+}
+
+/** Read an event detail from an exported private document. */
+function detailOf(event) {
+ return JSON.parse(event.event_detail);
+}
+
+/** Set a recorded family snapshot on one copied event without changing the live board. */
+function setSnapshot(event, family) {
+ event.event_detail = JSON.stringify({ ...detailOf(event), family });
+}
+
+/** Import a modified native document into a separate private in-memory board. */
+function importedBoard(t, document) {
+ const board = openBoard(':memory:');
+ t.after(() => closeBoard(board));
+ importBoard(board, document);
+ return board;
+}
+
+/** Add one historical system-actor event to an exported document and its sequence counter. */
+function appendSystemEvent(document, event) {
+ const eventId = Math.max(0, ...document.tables.event.map((row) => row.event_id)) + 1;
+ document.tables.event.push({ event_id: eventId, item_id: null, ...event });
+ const counter = document.tables.sqlite_sequence.find((row) => row.name === 'event');
+ if (counter) counter.seq = eventId;
+}
+
+/** Keep the pre-existing event counts identical when actor dimensions are added. */
+function assertCountsUnchanged(board, stats, options) {
+ const counts = eventCounts(board, options);
+ for (const key of ['since', 'submissions', 'rejections', 'rejectionShare', 'merged', 'mergedWithoutAccept', 'firstEventAt', 'lastEventAt']) {
+ assert.deepEqual(stats[key], counts[key], `${key} stays the same as eventCounts`);
+ }
+}
+
+test('[R1,R2] legacy family declarations are unknown until a family event and do not backfill', (t) => {
+ const { board } = familyHistory(t);
+ const stats = proofStats(board);
+ assert.equal(board.db.prepare('SELECT agent_family FROM agent WHERE agent_id=?').get('web-1').agent_family, 'new-family',
+ 'the current declaration is newer than the initial events');
+ assert.deepEqual(stats.agents, [
+ { id: 'coordinator', moves: 4, families: ['unknown'] },
+ { id: 'web-1', moves: 8, families: ['new-family', 'unknown'] },
+ ]);
+ assert.deepEqual(stats.families, [
+ { name: 'new-family', agents: 1, moves: 5 },
+ { name: 'unknown', agents: 2, moves: 7 },
+ ]);
+ assert.equal(stats.agentCount, 2);
+ assert.equal(stats.familyCount, 2);
+ assertCountsUnchanged(board, stats);
+});
+
+test('[R1,R2] a window keeps earlier family evidence but excludes earlier unknown-family moves', (t) => {
+ const { board } = familyHistory(t);
+ const since = '2026-02-04';
+ const stats = proofStats(board, { since });
+ assert.equal(stats.since, '2026-02-04T00:00:00.000Z');
+ assert.equal(stats.agentCount, 2);
+ assert.deepEqual(stats.agents, [
+ { id: 'coordinator', moves: 2, families: ['unknown'] },
+ { id: 'web-1', moves: 4, families: ['new-family'] },
+ ], 'the pre-window family event classifies selected legacy-format moves');
+ assert.deepEqual(stats.families, [
+ { name: 'new-family', agents: 1, moves: 4 },
+ { name: 'unknown', agents: 1, moves: 2 },
+ ]);
+ assert.equal(stats.familyCount, 2);
+ assertCountsUnchanged(board, stats, { since });
+});
+
+test('[R1,R2] explicit snapshots override prior state, null clears it, and system actors stay excluded', (t) => {
+ const { board } = familyHistory(t);
+ const document = exportBoard(board);
+ const history = document.tables.event;
+ const actorEvents = history.filter((event) => event.event_by === 'web-1');
+ const join = actorEvents.find((event) => event.event_kind === 'join');
+ const firstRelease = actorEvents.filter((event) => event.event_kind === 'release')[0];
+ const familyUpdate = actorEvents.find((event) => event.event_kind === 'family');
+ const laterClaims = actorEvents.filter((event) => event.event_kind === 'claim').slice(1);
+ const laterReleases = actorEvents.filter((event) => event.event_kind === 'release').slice(1);
+ setSnapshot(join, 'join-snapshot');
+ setSnapshot(firstRelease, 'move-snapshot');
+ setSnapshot(laterClaims[0], null);
+ setSnapshot(laterClaims[1], 'third-snapshot');
+ assert.equal(detailOf(familyUpdate).family, 'new-family', 'a family-change event is itself explicit evidence');
+ appendSystemEvent(document, {
+ event_at: '2026-02-06T00:00:00.000Z', event_by: 'board', event_kind: 'guards', event_detail: JSON.stringify({ family: 'ignored-board' }),
+ });
+ appendSystemEvent(document, {
+ event_at: '2026-02-06T00:01:00.000Z', event_by: 'person', event_kind: 'row_decision', event_detail: JSON.stringify({ family: 'ignored-person' }),
+ });
+ const imported = importedBoard(t, document);
+ const stats = proofStats(imported);
+ assert.deepEqual(stats.agents, [
+ { id: 'coordinator', moves: 4, families: ['unknown'] },
+ { id: 'web-1', moves: 8, families: ['join-snapshot', 'move-snapshot', 'new-family', 'third-snapshot', 'unknown'] },
+ ]);
+ assert.deepEqual(stats.families, [
+ { name: 'join-snapshot', agents: 1, moves: 2 },
+ { name: 'move-snapshot', agents: 1, moves: 1 },
+ { name: 'new-family', agents: 1, moves: 1 },
+ { name: 'third-snapshot', agents: 1, moves: 2 },
+ { name: 'unknown', agents: 2, moves: 6 },
+ ]);
+ assert.equal(stats.agentCount, 2, 'board and person are system actors, not agents');
+ assert.equal(stats.familyCount, 5);
+ assertCountsUnchanged(imported, stats);
+ assert.ok(laterReleases.length === 2, 'both later missing-snapshot moves inherit the previous explicit evidence');
+ assert.equal(events(imported).filter((event) => ['board', 'person'].includes(event.event_by)).length, 2);
+});
+
+test('[R1,R2] an empty board reports no agents or family buckets', (t) => {
+ const board = openBoard(':memory:');
+ t.after(() => closeBoard(board));
+ assert.deepEqual(proofStats(board), {
+ since: null,
+ submissions: 0,
+ rejections: 0,
+ rejectionShare: 0,
+ merged: 0,
+ mergedWithoutAccept: 0,
+ firstEventAt: null,
+ lastEventAt: null,
+ agentCount: 0,
+ familyCount: 0,
+ agents: [],
+ families: [],
+ });
+});
diff --git a/test/stats-cli.test.js b/test/stats-cli.test.js
new file mode 100644
index 00000000..e8327f71
--- /dev/null
+++ b/test/stats-cli.test.js
@@ -0,0 +1,99 @@
+/** Event-derived proof numbers have the same data in text and versioned JSON [R1,R2,A1]. */
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, realpathSync, rmSync, writeFileSync } 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';
+import { main } from '../src/cli.js';
+import { proofStats } from '../src/stats.js';
+import { serveApi } from '../src/api.js';
+
+/** Capture the real CLI without spawning a second model or changing the machine's registry. */
+async function run(root, args) {
+ let stdout = '';
+ let stderr = '';
+ const code = await main(args, { cwd: root,
+ stdout: { isTTY: false, write: (text) => { stdout += text; } },
+ stderr: { write: (text) => { stderr += text; } } });
+ return { code, stdout, stderr, data: args.includes('--json') ? JSON.parse(stdout) : null };
+}
+
+/** Create an isolated Git board with one rejected submission and accepted rework. */
+function fixture(t) {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-stats-cli-')));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: root, stdio: 'pipe' });
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ lanes: { web: { owns: ['web/'] } } }));
+ writeFileSync(join(root, 'PRACTICE.md'), '');
+ const clock = { now: () => new Date('2026-10-08T12:00:00.000Z') };
+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'), clock);
+ t.after(() => store.closeBoard(board));
+ store.register(board, { lane: 'coordinator', path: root });
+ const builder = store.register(board, { lane: 'web', path: join(root, 'web') });
+ const reviewer = store.register(board, { lane: 'review', path: join(root, 'review') });
+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Proof fixture' });
+ const freeze = () => ({ text: 'Proof fixture', digest: 'frozen' });
+ const submit = (commit) => {
+ store.claim(board, id, { agentId: builder, lane: 'web', leaseMs: 3_600_000, freeze });
+ store.submit(board, id, { agentId: builder, commit, tree: 'b'.repeat(40) });
+ };
+ submit('a'.repeat(40));
+ store.verify(board, id, { agentId: reviewer, decision: 'REJECT', reason: 'TEST_FAILURE', note: 'Fixture rejects the first attempt.', head: 'a'.repeat(40), digest: 'frozen', policy: 'any' });
+ submit('c'.repeat(40));
+ store.verify(board, id, { agentId: reviewer, decision: 'ACCEPT', note: 'Fixture rework meets its bar.', head: 'c'.repeat(40), digest: 'frozen', policy: 'any' });
+ store.merged(board, id, { agentId: 'coordinator', commit: 'd'.repeat(40) });
+ return { root, board };
+}
+
+test('[R1,R2,A1] stats JSON is versioned, text states the same proof numbers and neither records a move', async (t) => {
+ const { root, board } = fixture(t);
+ const before = store.events(board);
+ const expected = proofStats(board);
+ const json = await run(root, ['stats', '--json']);
+ assert.equal(json.code, 0, json.stderr);
+ assert.equal(json.stderr, '');
+ assert.deepEqual(json.data, { version: 1, stats: expected });
+ assert.deepEqual([expected.submissions, expected.rejections, expected.rejectionShare, expected.merged, expected.mergedWithoutAccept], [2, 1, 0.5, 1, 0]);
+ const text = await run(root, ['stats']);
+ assert.equal(text.code, 0, text.stderr);
+ assert.match(text.stdout, /2 submissions · 1 rejections · 50\.0% sent back/u);
+ assert.match(text.stdout, /1 items merged · 0 merged without an accept/u);
+ assert.ok(text.stdout.includes(expected.firstEventAt));
+ assert.ok(text.stdout.includes(expected.lastEventAt));
+ assert.deepEqual(store.events(board), before, 'reading statistics appends no move');
+});
+
+test('[R2,A1] stats forwards the inclusive date window and returns an actionable invalid-date refusal', async (t) => {
+ const { root, board } = fixture(t);
+ const json = await run(root, ['stats', '--since', '2026-10-09', '--json']);
+ assert.equal(json.code, 0, json.stderr);
+ assert.deepEqual(json.data.stats, proofStats(board, { since: '2026-10-09' }));
+ assert.equal(json.data.stats.submissions, 0);
+ assert.equal(json.data.stats.firstEventAt, null);
+ const bad = await run(root, ['stats', '--since', '2026-02-30', '--json']);
+ assert.equal(bad.code, 1);
+ assert.equal(bad.data.version, 1);
+ assert.equal(bad.data.error.code, 'BAD_SINCE');
+ assert.match(bad.data.error.next, /--since 2026-10-08/u);
+ const help = await run(root, ['stats', '--help']);
+ assert.equal(help.code, 0);
+ assert.match(help.stdout, /--since <date>/u);
+});
+
+/** Exercise authenticated state from the same private board used by the command checks. */
+test('[R1,R2,A2] local HTTP state exposes exactly the command statistics', async (t) => {
+ const { root, board } = fixture(t);
+ const api = await serveApi({ runCommand: main, projects: () => [{ root, name: 'Statistics fixture' }] });
+ t.after(() => api.close());
+ const url = new URL(api.url);
+ const headers = { 'x-pullboard-key': url.searchParams.get('k') };
+ const response = await fetch(`${url.origin}/api/v1/boards/${store.boardId(board)}/state`, { headers });
+ assert.equal(response.status, 200);
+ const document = await response.json();
+ const command = await run(root, ['stats', '--json']);
+ assert.equal(command.code, 0, command.stderr);
+ assert.equal(document.version, 1);
+ assert.deepEqual(document.state.proofStats, command.data.stats);
+});
diff --git a/test/stats-counts.test.js b/test/stats-counts.test.js
new file mode 100644
index 00000000..beb7dd6e
--- /dev/null
+++ b/test/stats-counts.test.js
@@ -0,0 +1,188 @@
+/** Event-derived submission, rejection and merge counts preserve historical acceptance proof [R1,R2]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { addItem, claim, closeBoard, getItem, merged, openBoard, register, submit, verify } from '../src/board.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { eventCounts } from '../src/stats.js';
+
+const COMMIT_ONE = '1'.repeat(40);
+const COMMIT_TWO = '2'.repeat(40);
+const MAIN_MERGE = 'a'.repeat(40);
+const TREE_ONE = 'tree-one';
+const TREE_TWO = 'tree-two';
+
+/** Create a real SQLite board with a mutable deterministic clock and close it after the test. */
+function fixture(t) {
+ let at = new Date('2026-01-01T00:00:00.000Z');
+ const board = openBoard(':memory:', { now: () => new Date(at) });
+ t.after(() => closeBoard(board));
+ /** Advance the deterministic board clock for the next public lifecycle move. */
+ const setTime = (value) => { at = new Date(value); };
+ setTime('2026-01-01T00:00:00.000Z');
+ register(board, { lane: 'coordinator', path: '/fixture/coordinator' });
+ setTime('2026-01-01T00:01:00.000Z');
+ register(board, { lane: 'web', path: '/fixture/web-builder', family: 'builder-family' });
+ setTime('2026-01-01T00:02:00.000Z');
+ register(board, { lane: 'web', path: '/fixture/web-reviewer', family: 'review-family' });
+ return { board, setTime };
+}
+
+/** Freeze a stable criterion for every claim and rework in these lifecycle fixtures. */
+function freezeCriterion() {
+ return { text: 'The fixture lifecycle remains auditable.', digest: 'fixture-criterion-digest' };
+}
+
+/** Add and claim one item as its builder at the requested deterministic time. */
+function addAndClaim(f, title) {
+ f.setTime('2026-01-02T00:00:00.000Z');
+ const id = addItem(f.board, { by: 'coordinator', lane: 'web', title, criterion: 'the history is counted' });
+ f.setTime('2026-01-02T01:00:00.000Z');
+ claim(f.board, id, { agentId: 'web-1', lane: 'web', leaseMs: 86_400_000, freeze: freezeCriterion });
+ return id;
+}
+
+/** Submit one immutable commit after the builder holds its claim. */
+function submitAt(f, id, commit, tree, at) {
+ f.setTime(at);
+ submit(f.board, id, { agentId: 'web-1', commit, tree });
+}
+
+/** Record an accept or reject from a different registered reviewer. */
+function verdictAt(f, id, decision, commit, at) {
+ f.setTime(at);
+ return verify(f.board, id, {
+ agentId: 'web-2', decision,
+ ...(decision === 'REJECT' ? { reason: 'TEST_FAILURE' } : {}),
+ note: decision === 'REJECT' ? 'the first result fails; rework is needed' : 'rework is verified against the frozen criterion',
+ head: commit,
+ digest: 'fixture-criterion-digest',
+ policy: 'any',
+ });
+}
+
+/** Build a valid reject, rework, accept, and repeated-merge history on a private board. */
+function rejectedThenMerged(t) {
+ const f = fixture(t);
+ const id = addAndClaim(f, 'Rejected then merged');
+ submitAt(f, id, COMMIT_ONE, TREE_ONE, '2026-01-03T10:00:00.000Z');
+ verdictAt(f, id, 'REJECT', COMMIT_ONE, '2026-01-04T10:00:00.000Z');
+ f.setTime('2026-01-04T11:00:00.000Z');
+ claim(f.board, id, { agentId: 'web-1', lane: 'web', leaseMs: 86_400_000, freeze: freezeCriterion });
+ submitAt(f, id, COMMIT_TWO, TREE_TWO, '2026-01-05T10:00:00.000Z');
+ verdictAt(f, id, 'ACCEPT', COMMIT_TWO, '2026-01-06T10:00:00.000Z');
+ f.setTime('2026-01-07T10:00:00.000Z');
+ merged(f.board, id, { agentId: 'coordinator', commit: MAIN_MERGE });
+ f.setTime('2026-01-08T10:00:00.000Z');
+ merged(f.board, id, { agentId: 'coordinator', commit: 'b'.repeat(40) });
+ return { ...f, id };
+}
+
+/** Import a copied native board document into a fresh private in-memory SQLite board. */
+function importedBoard(t, document) {
+ const board = openBoard(':memory:');
+ t.after(() => closeBoard(board));
+ importBoard(board, document);
+ return board;
+}
+
+/** Re-number an edited private event history and its SQLite AUTOINCREMENT counter. */
+function resequenceEvents(document, history) {
+ document.tables.event = history
+ .sort((first, second) => Date.parse(first.event_at) - Date.parse(second.event_at))
+ .map((event, index) => ({ ...event, event_id: index + 1 }));
+ const counter = document.tables.sqlite_sequence.find((row) => row.name === 'event');
+ if (counter) counter.seq = document.tables.event.length;
+}
+
+test('[R1,R2] repeated submissions and rejections count attempts while merges count distinct items', (t) => {
+ const { board } = rejectedThenMerged(t);
+ const counts = eventCounts(board);
+ assert.deepEqual(counts, {
+ since: null,
+ submissions: 2,
+ rejections: 1,
+ rejectionShare: 0.5,
+ merged: 1,
+ mergedWithoutAccept: 0,
+ firstEventAt: '2026-01-01T00:00:00.000Z',
+ lastEventAt: '2026-01-08T10:00:00.000Z',
+ });
+ assert.equal(getItem(board, 1).item_status, 'verified');
+});
+
+test('[R1,R2] date and timestamp windows are inclusive and earlier acceptance still proves a merge', (t) => {
+ const { board } = rejectedThenMerged(t);
+ assert.deepEqual(eventCounts(board, { since: '2026-01-05' }), {
+ since: '2026-01-05T00:00:00.000Z',
+ submissions: 1,
+ rejections: 0,
+ rejectionShare: 0,
+ merged: 1,
+ mergedWithoutAccept: 0,
+ firstEventAt: '2026-01-05T10:00:00.000Z',
+ lastEventAt: '2026-01-08T10:00:00.000Z',
+ });
+ assert.deepEqual(eventCounts(board, { since: '2026-01-07T10:00:00Z' }), {
+ since: '2026-01-07T10:00:00.000Z',
+ submissions: 0,
+ rejections: 0,
+ rejectionShare: 0,
+ merged: 1,
+ mergedWithoutAccept: 0,
+ firstEventAt: '2026-01-07T10:00:00.000Z',
+ lastEventAt: '2026-01-08T10:00:00.000Z',
+ }, 'the acceptance before the selected window remains proof for the later merge');
+});
+
+test('[R1,R2] empty windows normalize cleanly and invalid dates refuse', (t) => {
+ const { board } = rejectedThenMerged(t);
+ assert.deepEqual(eventCounts(board, { since: '2026-02-01' }), {
+ since: '2026-02-01T00:00:00.000Z',
+ submissions: 0,
+ rejections: 0,
+ rejectionShare: 0,
+ merged: 0,
+ mergedWithoutAccept: 0,
+ firstEventAt: null,
+ lastEventAt: null,
+ });
+ assert.throws(() => eventCounts(board, { since: '2026-02-30' }), { code: 'BAD_SINCE' });
+ assert.throws(() => eventCounts(board, { since: '2026-01-07T10:00:00+00:00' }), { code: 'BAD_SINCE' });
+});
+
+test('[R1,R2] imported historical merges without a matching current acceptance remain anomalies', (t) => {
+ const { board, id } = rejectedThenMerged(t);
+ const original = exportBoard(board);
+ const accepts = original.tables.event.filter((event) => event.item_id === id && event.event_kind === 'accept');
+ assert.equal(accepts.length, 1);
+
+ const missingAccept = structuredClone(original);
+ missingAccept.tables.event = missingAccept.tables.event.filter((event) => !(event.item_id === id && event.event_kind === 'accept'));
+ const missingBoard = importedBoard(t, missingAccept);
+ assert.equal(getItem(missingBoard, id).item_status, 'verified', 'the historical item row still says verified');
+ assert.equal(eventCounts(missingBoard).mergedWithoutAccept, 1, 'the merge is anomalous when its accept event is absent');
+
+ const wrongAccept = structuredClone(original);
+ const wrongEvent = wrongAccept.tables.event.find((event) => event.item_id === id && event.event_kind === 'accept');
+ wrongEvent.event_detail = JSON.stringify({ ...JSON.parse(wrongEvent.event_detail), commit: 'f'.repeat(40) });
+ const wrongBoard = importedBoard(t, wrongAccept);
+ assert.equal(getItem(wrongBoard, id).item_status, 'verified');
+ assert.equal(eventCounts(wrongBoard).mergedWithoutAccept, 1, 'a different accepted commit does not prove the merged submission');
+
+ const staleAccept = structuredClone(original);
+ const itemHistory = staleAccept.tables.event.filter((event) => event.item_id === id);
+ const firstSubmit = itemHistory.find((event) => event.event_kind === 'submit' && JSON.parse(event.event_detail).commit === COMMIT_ONE);
+ const secondSubmit = itemHistory.find((event) => event.event_kind === 'submit' && JSON.parse(event.event_detail).commit === COMMIT_TWO);
+ const mergedEvent = itemHistory.find((event) => event.event_kind === 'merged');
+ const oldAccept = {
+ ...accepts[0],
+ event_at: '2026-01-03T11:00:00.000Z',
+ event_detail: JSON.stringify({ reason: 'CRITERION_MET', commit: COMMIT_ONE }),
+ };
+ const oldHistory = staleAccept.tables.event.filter((event) => event.item_id !== id || event.event_kind === 'add');
+ resequenceEvents(staleAccept, [...oldHistory, firstSubmit, oldAccept, secondSubmit, mergedEvent]);
+ const staleBoard = importedBoard(t, staleAccept);
+ assert.equal(getItem(staleBoard, id).item_status, 'verified');
+ assert.equal(eventCounts(staleBoard).mergedWithoutAccept, 1,
+ 'a new submit invalidates a previously accepted commit even when the current row remains verified');
+});