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): measure flow and name the bottleneck [R1,R2]

Corey Olson871771174fed
diff --git a/docs/api.md b/docs/api.md
index fcc77d14..27200b38 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -16,6 +16,16 @@ The board-state API's item projection includes `check` and, when recorded, `chec
`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.
+`stats.flow` adds the flow through the board:
+
+- `stages.build`, `reviewWait`, `review` and `mergeWait` each contain `count`, `totalMinutes`, `averageMinutes`, `medianMinutes` and `unmeasuredCompleted`. Build runs from first claim to the final submission, including rework. Review wait ends at the reservation whose verdict closes that submission; released or expired reservations remain waiting time. Review runs from that reservation to verdict, and merge wait from accept to the first merge receipt. Each stage enters its averages when its end is inside the inclusive `--since` window. Unfinished or missing intervals are omitted; averages and medians with no samples are `null`. Legacy verdicts without reservations leave review wait and review unmeasured, never zero.
+- `queues.open`, `claimed`, `submitted` and `accepted` contain `size` and `oldest` (`{id, ageMinutes}`, or `null`). These are current queues, including work added before the window; accepted means accepted but not merged. Open age starts at the latest add, reopen, reject, build release or claim lapse. Claimed age starts at claim, unaffected by renewal; submitted age starts at final submit, and accepted age at accept. Equal ages choose the lower item id. Expired claims become open at their recorded lease expiry.
+- `daily` contains UTC `{date, added, merged}` counts for dates with those moves in the window. An item's first merge completes its cycle; repeated receipts never create another completion, even in a later window. `submitsPerMerged` divides window submission attempts by first completions in the window, or is zero without completions. `stats.rejectionShare` remains the share of window submissions sent back.
+- `activeAgents` contains `total`, an `agents` list (`id`, `lane`, `role`), and counts in `roles` and `lanes`. Activity means any move in the inclusive last 60 minutes, independent of `--since`. Builder roles come from claim, submit or build release; verifier roles from reserve, verdict or review release. A roleless move retains the latest recorded role, including earlier history; without one the role is `unknown`. The coordinator's role is `coordinator`. Lanes come from recorded joins, not a guess from the id.
+- `bottleneck` contains `stage`, `share`, `completedItems`, `fullyMeasuredCycles`, `totalCycleMinutes`, `lowConfidence`, `message` and `recommendation`. Only completed cycles with all four measured stages contribute stage shares; the line states how many fully measured cycles support it. Fewer than half the completed cycles fully measured sets low confidence. The largest summed share wins, with ties in build, review wait, review, merge wait order. No completed cycles, or none fully measured, means no named stage or action (`null`).
+
+The single recommended action uses the first matching rule: review wait with fewer than one active verifier per four active builders says **add a verifier**; otherwise **review the oldest submission first (#N)**. Build with more than 30% of window submissions sent back says **tighten criteria or briefs: N of M submissions were sent back**; otherwise **add a builder in &lt;lane with the most open items&gt;**, with lane-name ties sorted alphabetically. Review says **reviews are slow (median X min): check how long the frozen checks take**. Merge wait says **land the accepted items: #A, #B**, with ids ascending. If the relevant queue is empty, its action explicitly says none waiting, or **add a builder when open work is available**. JSON retains numeric precision; CLI minutes round to two decimal places. Statistics are read-only.
+
`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`.
diff --git a/src/cli.js b/src/cli.js
index c9ed2f68..cb6b6664 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -67,6 +67,7 @@ import { doctorProblems, doctrineProblems } from './doctor.js';
import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';
import { proofStats } from './stats.js';
+import { flowLines } from './stats-flow.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
import { loadMachineSettings, setGateSlots } from './settings.js';
@@ -1427,6 +1428,7 @@ function readCommands(io, { first, second, rest, values }) {
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})` : ''}`);
+ for (const line of flowLines(stats.flow)) io.say(line);
return 0;
},
ledger: () => {
diff --git a/src/help.js b/src/help.js
index 90df3fe9..da8a79cc 100644
--- a/src/help.js
+++ b/src/help.js
@@ -101,6 +101,32 @@ Coordinator
Receipts
pullboard stats [--since <date>] proof numbers from the event log; --json for sites and tools
+ stage averages/medians count ends inside the inclusive UTC window;
+ build: first claim to final submit (including rework);
+ review wait: final submit to the closing review reservation;
+ released/expired reservations remain wait, not review;
+ review: closing reservation to verdict; merge wait: accept to first merge
+ unfinished stages are omitted; missing legacy reservations are unmeasured
+ queues include all current work, even added before --since;
+ open age restarts on add, reopen, reject, release or claim lapse;
+ claimed age starts at claim (not renewal), submitted at final submit,
+ accepted-not-merged at accept; oldest ties use the lower item id
+ daily additions and first merges use UTC dates; repeated merge receipts count once
+ active agents moved in the last 60 minutes (inclusive), by role and lane;
+ role is latest role-bearing move, falling back to earlier history or unknown:
+ claim/submit/build release = builder; reserve/verdict/review release = verifier;
+ the coordinator is coordinator; shouts and joins never imply a role
+ bottleneck: largest summed stage share over fully measured first-merge cycles;
+ ties: build, review wait, review, merge wait; print fully measured/total cycles;
+ fewer than half fully measured means low confidence; no measured cycles means no action
+ one action, first matching rule:
+ review wait + fewer than 1 verifier per 4 active builders: add a verifier
+ review wait otherwise: review the oldest submission first (#N)
+ build + more than 30% sent back: tighten criteria or briefs: N of M submissions were sent back
+ build otherwise: add a builder in the lane with most open items (lane-name tie)
+ review: reviews are slow (median X min): check how long the frozen checks take
+ merge wait: land the accepted items: #A, #B
+ when that queue is empty, the action says none waiting or waits for open work
pullboard ledger markdown: what was built, by whom, verified by whom
pullboard log [id] every move, in order
diff --git a/src/stats-flow.js b/src/stats-flow.js
new file mode 100644
index 00000000..d73f7dce
--- /dev/null
+++ b/src/stats-flow.js
@@ -0,0 +1,220 @@
+/** Flow times, queues and recommendations from recorded lifecycle evidence [R1,R2]. */
+const MINUTE = 60_000;
+const STAGES = ['build', 'reviewWait', 'review', 'mergeWait'];
+const LABELS = { build: 'build', reviewWait: 'review wait', review: 'review', mergeWait: 'merge wait' };
+
+/** Summarize measured minutes; an absent interval is never an invented zero. */
+function summarize(values) {
+ const sorted = [...values].sort((a, b) => a - b);
+ const count = sorted.length;
+ const totalMinutes = sorted.reduce((sum, value) => sum + value, 0);
+ const middle = Math.floor(count / 2);
+ return { count, totalMinutes, averageMinutes: count ? totalMinutes / count : null,
+ medianMinutes: count ? count % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2 : null };
+}
+
+/** Keep only nonnegative, recorded start/end intervals. */
+function interval(start, end) {
+ return Number.isFinite(start) && Number.isFinite(end) && end >= start ? (end - start) / MINUTE : null;
+}
+
+/** Identify role-bearing moves without guessing a role from an agent's lane. */
+function roleOf(kind, detail) {
+ if (['reserve', 'accept', 'reject', 'verify'].includes(kind) || kind === 'release' && detail.review) return 'verifier';
+ if (['claim', 'submit'].includes(kind) || kind === 'release' && !detail.review) return 'builder';
+ return null;
+}
+
+/** Return an expired claim to its open queue at the recorded lease boundary. */
+function expireClaim(item, at) {
+ if (item.state === 'claimed' && Number.isFinite(item.leaseUntil) && item.leaseUntil <= at) {
+ item.state = 'open';
+ item.openAt = item.leaseUntil;
+ }
+}
+
+/** Replay one lifecycle move; its first claim and first merge survive rework and repeated receipts. */
+function move(item, event, detail, at) {
+ expireClaim(item, at);
+ switch (event.event_kind) {
+ case 'add':
+ item.lane = detail.lane ?? 'unknown'; item.state = 'open'; item.openAt = at; break;
+ case 'claim':
+ item.firstClaim ??= at; item.claimAt = at; item.state = 'claimed';
+ item.leaseUntil = Date.parse(detail.leaseUntil); break;
+ case 'renew': item.leaseUntil = Date.parse(detail.leaseUntil); break;
+ case 'submit':
+ item.submitAt = at; item.commit = detail.commit; item.verdictAt = null; item.acceptAt = null;
+ item.reserve = null; item.finalReserveAt = null; item.state = 'submitted'; break;
+ case 'reserve': item.reserve = { at, by: event.event_by, until: Date.parse(detail.until) }; break;
+ case 'release':
+ if (detail.review || item.state === 'submitted') item.reserve = null;
+ else { item.state = 'open'; item.openAt = at; }
+ break;
+ case 'accept':
+ case 'reject': {
+ if (!item.commit || detail.commit !== item.commit) break;
+ item.verdictAt = at;
+ item.finalReserveAt = item.reserve?.by === event.event_by &&
+ (!Number.isFinite(item.reserve.until) || item.reserve.until >= at) ? item.reserve.at : null;
+ item.reserve = null;
+ if (event.event_kind === 'accept') { item.state = 'accepted'; item.acceptAt = at; }
+ else { item.state = 'open'; item.openAt = at; }
+ break;
+ }
+ case 'merged': item.mergeAt ??= at; item.state = 'merged'; break;
+ case 'reopen':
+ case 'refreeze':
+ case 'escalate':
+ case 'lapse': item.state = 'open'; item.openAt = at; item.reserve = null; break;
+ case 'withdraw': item.state = 'withdrawn'; break;
+ }
+}
+
+/** Select the current final attempt's measured stages without charging released reviews as review work. */
+function itemStages(item, now) {
+ const reserveAt = item.verdictAt !== null && item.verdictAt !== undefined ? item.finalReserveAt :
+ item.reserve && (!Number.isFinite(item.reserve.until) || item.reserve.until >= now) ? item.reserve.at : null;
+ return {
+ build: { end: item.submitAt, minutes: interval(item.firstClaim, item.submitAt) },
+ reviewWait: { end: reserveAt, minutes: interval(item.submitAt, reserveAt) },
+ review: { end: item.verdictAt, minutes: interval(reserveAt, item.verdictAt) },
+ mergeWait: { end: item.mergeAt, minutes: interval(item.acceptAt, item.mergeAt) },
+ };
+}
+
+/** Count current queues and name the longest wait, with item id as the deterministic tie breaker. */
+function queuesFrom(items, now) {
+ const queues = Object.fromEntries(['open', 'claimed', 'submitted', 'accepted'].map(state => [state, { size: 0, oldest: null }]));
+ const openByLane = new Map();
+ const accepted = [];
+ for (const item of items) {
+ expireClaim(item, now);
+ const queue = queues[item.state];
+ if (!queue) continue;
+ queue.size += 1;
+ const start = { open: item.openAt, claimed: item.claimAt, submitted: item.submitAt, accepted: item.acceptAt }[item.state];
+ const ageMinutes = interval(start, now);
+ if (ageMinutes !== null && (!queue.oldest || ageMinutes > queue.oldest.ageMinutes ||
+ ageMinutes === queue.oldest.ageMinutes && item.id < queue.oldest.id)) queue.oldest = { id: item.id, ageMinutes };
+ if (item.state === 'open') openByLane.set(item.lane, (openByLane.get(item.lane) ?? 0) + 1);
+ if (item.state === 'accepted') accepted.push(item.id);
+ }
+ return { queues, openByLane, accepted: accepted.sort((a, b) => a - b) };
+}
+
+/** Attribute last-hour activity using the latest recorded role, including a prior role when only shouts are recent. */
+function activeFrom(actors, now) {
+ const agents = [...actors.values()].filter(actor => actor.lastAt >= now - 60 * MINUTE && actor.lastAt <= now)
+ .map(({ id, lane, role }) => ({ id, lane, role })).sort((a, b) => a.id.localeCompare(b.id));
+ const roles = { builder: 0, verifier: 0, coordinator: 0, unknown: 0 };
+ const lanes = new Map();
+ for (const actor of agents) {
+ roles[actor.role] += 1;
+ lanes.set(actor.lane, (lanes.get(actor.lane) ?? 0) + 1);
+ }
+ return { total: agents.length, agents, roles, lanes: Object.fromEntries([...lanes].sort(([a], [b]) => a.localeCompare(b))) };
+}
+
+/** Recommend exactly one documented action for the largest measured completed-cycle stage. */
+function recommendation(stage, { activeAgents, queues, openByLane, accepted, counts, stages }) {
+ if (stage === 'reviewWait') {
+ if (activeAgents.roles.verifier < activeAgents.roles.builder / 4) return 'add a verifier';
+ return queues.submitted.oldest ? `review the oldest submission first (#${queues.submitted.oldest.id})` :
+ 'review the oldest submission first (none waiting)';
+ }
+ if (stage === 'build') {
+ if (counts.rejectionShare > 0.3) return `tighten criteria or briefs: ${counts.rejections} of ${counts.submissions} submissions were sent back`;
+ const lane = [...openByLane].sort(([a, first], [b, second]) => second - first || a.localeCompare(b))[0]?.[0];
+ return lane ? `add a builder in ${lane}` : 'add a builder when open work is available';
+ }
+ if (stage === 'review') return `reviews are slow (median ${stages.review.medianMinutes ?? 'unmeasured'} min): check how long the frozen checks take`;
+ return accepted.length ? `land the accepted items: ${accepted.map(id => `#${id}`).join(', ')}` : 'land the accepted items (none waiting)';
+}
+
+/** Derive flow from the same immutable history used for counts, with an injectable observation time for fixtures. */
+export function flowStats(history, boundary, now, counts) {
+ const items = new Map();
+ const actors = new Map();
+ const daily = new Map();
+ /** Include a stage or first completion at the exact lower boundary. */
+ const selected = at => !boundary || at >= Date.parse(boundary);
+ /** Count each day's additions and first completed merges without filling gaps with invented moves. */
+ function day(at) {
+ const date = new Date(at).toISOString().slice(0, 10);
+ if (!daily.has(date)) daily.set(date, { date, added: 0, merged: 0 });
+ return daily.get(date);
+ }
+ for (const event of history) {
+ const detail = JSON.parse(event.event_detail);
+ const at = Date.parse(event.event_at);
+ const id = event.event_by;
+ if (!['board', 'person', 'clock'].includes(id)) {
+ if (!actors.has(id)) actors.set(id, { id, lane: 'unknown', role: 'unknown', lastAt: at });
+ const actor = actors.get(id);
+ if (event.event_kind === 'join' && detail.lane) actor.lane = detail.lane;
+ actor.role = id === 'coordinator' ? 'coordinator' : roleOf(event.event_kind, detail) ?? actor.role;
+ actor.lastAt = at;
+ }
+ if (event.item_id === null || event.item_id === undefined) continue;
+ if (!items.has(event.item_id)) items.set(event.item_id, { id: event.item_id, lane: 'unknown' });
+ const item = items.get(event.item_id);
+ if (event.event_kind === 'add' && selected(at)) day(at).added += 1;
+ if (event.event_kind === 'merged' && item.mergeAt === undefined && selected(at)) day(at).merged += 1;
+ move(item, event, detail, at);
+ }
+ const samples = Object.fromEntries(STAGES.map(stage => [stage, []]));
+ const cycleTotals = Object.fromEntries(STAGES.map(stage => [stage, 0]));
+ let completedItems = 0;
+ let fullyMeasuredCycles = 0;
+ const unmeasured = Object.fromEntries(STAGES.map(stage => [stage, 0]));
+ for (const item of items.values()) {
+ const measured = itemStages(item, now);
+ for (const stage of STAGES) {
+ const sample = measured[stage];
+ if (sample.minutes !== null && selected(sample.end)) samples[stage].push(sample.minutes);
+ }
+ if (!Number.isFinite(item.mergeAt) || !selected(item.mergeAt)) continue;
+ completedItems += 1;
+ for (const stage of STAGES) if (measured[stage].minutes === null) unmeasured[stage] += 1;
+ if (STAGES.some(stage => measured[stage].minutes === null)) continue;
+ fullyMeasuredCycles += 1;
+ for (const stage of STAGES) cycleTotals[stage] += measured[stage].minutes ?? 0;
+ }
+ const stages = Object.fromEntries(STAGES.map(stage => [stage, { ...summarize(samples[stage]), unmeasuredCompleted: unmeasured[stage] }]));
+ const queueData = queuesFrom(items.values(), now);
+ const activeAgents = activeFrom(actors, now);
+ const stage = STAGES.reduce((largest, next) => cycleTotals[next] > cycleTotals[largest] ? next : largest);
+ const totalCycleMinutes = Object.values(cycleTotals).reduce((sum, value) => sum + value, 0);
+ const bottleneck = fullyMeasuredCycles ? {
+ stage, share: totalCycleMinutes ? cycleTotals[stage] / totalCycleMinutes : 0,
+ completedItems, fullyMeasuredCycles, totalCycleMinutes, lowConfidence: fullyMeasuredCycles < completedItems / 2,
+ message: `${LABELS[stage]} has the largest share of cycle time; bottleneck from ${fullyMeasuredCycles} fully measured cycles of ${completedItems}`,
+ recommendation: recommendation(stage, { ...queueData, activeAgents, counts, stages }),
+ } : { stage: null, share: null, completedItems, fullyMeasuredCycles: 0, totalCycleMinutes: 0, lowConfidence: completedItems > 0,
+ message: completedItems ? `not enough measured flow to name a bottleneck (${completedItems} items completed since ${boundary ?? 'the beginning'}, none with every stage measured)` :
+ `not enough flow to name a bottleneck (0 items completed since ${boundary ?? 'the beginning'})`, recommendation: null };
+ return { stages, queues: queueData.queues, daily: [...daily.values()].sort((a, b) => a.date.localeCompare(b.date)),
+ submitsPerMerged: completedItems ? counts.submissions / completedItems : 0, activeAgents, bottleneck };
+}
+
+/** Format measured minutes for people while JSON retains the original numeric precision. */
+function minutes(value) { return value === null ? 'unmeasured' : String(Number(value.toFixed(2))); }
+
+/** Render all flow dimensions and the evidence behind the single recommended action. */
+export function flowLines(flow) {
+ const lines = STAGES.map(stage => {
+ const row = flow.stages[stage];
+ return `${LABELS[stage]}: average ${minutes(row.averageMinutes)} min · median ${minutes(row.medianMinutes)} min · ${row.count} measured; ${row.unmeasuredCompleted} of ${flow.bottleneck.completedItems} completed items unmeasured`;
+ });
+ for (const [state, queue] of Object.entries(flow.queues)) {
+ lines.push(`${state} queue: ${queue.size} · oldest ${queue.oldest ? `#${queue.oldest.id} (${minutes(queue.oldest.ageMinutes)} min)` : 'none'}`);
+ }
+ lines.push(`per day: ${flow.daily.map(row => `${row.date}: ${row.added} added, ${row.merged} merged`).join('; ') || 'none'}`);
+ lines.push(`${minutes(flow.submitsPerMerged)} submissions per merged item`);
+ lines.push(`active in the last hour: ${flow.activeAgents.total} agents · roles ${Object.entries(flow.activeAgents.roles).map(([role, count]) => `${role} ${count}`).join(', ')} · lanes ${Object.entries(flow.activeAgents.lanes).map(([lane, count]) => `${lane} ${count}`).join(', ') || 'none'}`);
+ const bottleneck = flow.bottleneck;
+ lines.push(`bottleneck: ${bottleneck.message}${bottleneck.share === null ? '' : ` (${minutes(bottleneck.share * 100)}%)`}${bottleneck.lowConfidence ? ' · low confidence' : ''}`);
+ if (bottleneck.recommendation) lines.push(`next: ${bottleneck.recommendation}`);
+ return lines;
+}
diff --git a/src/stats.js b/src/stats.js
index 9a90ff3f..1f6fd7da 100644
--- a/src/stats.js
+++ b/src/stats.js
@@ -1,6 +1,7 @@
/** Public proof numbers derived from the append-only event log [R1,R2]. */
import { events } from './board.js';
import { Refused } from './refused.js';
+import { flowStats } from './stats-flow.js';
/** Parse an inclusive UTC date boundary, refusing malformed or impossible dates. */
export function sinceDate(value) {
@@ -93,8 +94,9 @@ 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 } = {}) {
+export function proofStats(board, { since, now = Date.now() } = {}) {
const boundary = sinceDate(since);
const history = events(board);
- return { ...countsFrom(history, boundary), ...actorsFrom(history, boundary) };
+ const counts = countsFrom(history, boundary);
+ return { ...counts, ...actorsFrom(history, boundary), flow: flowStats(history, boundary, now, counts) };
}
diff --git a/test/stats-actors.test.js b/test/stats-actors.test.js
index 05113441..5af3ee73 100644
--- a/test/stats-actors.test.js
+++ b/test/stats-actors.test.js
@@ -172,7 +172,8 @@ test('[R1,R2] explicit snapshots override prior state, null clears it, and syste
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), {
+ const { flow, ...historical } = proofStats(board);
+ assert.deepEqual(historical, {
since: null,
submissions: 0,
rejections: 0,
diff --git a/test/stats-cli.test.js b/test/stats-cli.test.js
index 9fc45160..0a6f0f85 100644
--- a/test/stats-cli.test.js
+++ b/test/stats-cli.test.js
@@ -65,6 +65,9 @@ test('[R1,R2,A1] stats JSON is versioned, text states the same proof numbers and
assert.match(text.stdout, /agents: coordinator \(unknown; \d+ moves\), review-1 \(unknown; \d+ moves\), web-1 \(unknown; \d+ moves\)/u);
assert.ok(text.stdout.includes(expected.firstEventAt));
assert.ok(text.stdout.includes(expected.lastEventAt));
+ assert.match(text.stdout, /build: average 0 min · median 0 min · 1 measured/u);
+ assert.match(text.stdout, /review: average unmeasured min · median unmeasured min · 0 measured; 1 of 1 completed items unmeasured/u);
+ assert.match(text.stdout, /not enough measured flow to name a bottleneck \(1 items completed since the beginning, none with every stage measured\)/u);
assert.deepEqual(store.events(board), before, 'reading statistics appends no move');
});
diff --git a/test/stats-flow.test.js b/test/stats-flow.test.js
new file mode 100644
index 00000000..ba40bd00
--- /dev/null
+++ b/test/stats-flow.test.js
@@ -0,0 +1,263 @@
+/** Hand-computed synthetic histories exercise real Git/SQLite statistics and each recommendation [R1,R2]. */
+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';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { proofStats } from '../src/stats.js';
+import { flowLines } from '../src/stats-flow.js';
+import { runFixtureGit } from './fixture-child.js';
+
+const BASE = Date.parse('2026-10-10T00:00:00Z');
+
+/** Convert hand-written minute offsets to exact UTC timestamps. */
+function at(minutes) { return new Date(BASE + minutes * 60_000).toISOString(); }
+
+/** Import a synthetic native event log into a private on-disk SQLite board in a real Git repository.
+ * Current item rows deliberately remain open: statistics must follow events, not those stale rows.
+ */
+function fixture(t, entries, now = 200) {
+ const root = mkdtempSync(join(tmpdir(), 'pullboard-flow-'));
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, stdio: 'pipe' });
+ const seed = store.openBoard(join(root, '.git', 'seed.sqlite'));
+ store.register(seed, { lane: 'coordinator', path: root });
+ for (let n = 1; n <= 8; n += 1) store.register(seed, { lane: 'core', path: join(root, `builder-${n}`) });
+ for (let n = 1; n <= 2; n += 1) store.register(seed, { lane: 'review', path: join(root, `reviewer-${n}`) });
+ const maxId = Math.max(0, ...entries.map(entry => entry[3] ?? 0));
+ for (let id = 1; id <= maxId; id += 1) store.addItem(seed, { by: 'coordinator', lane: 'core', title: `Flow ${id}` });
+ const document = exportBoard(seed);
+ store.closeBoard(seed);
+ const joins = document.tables.agent.map(agent => [0, agent.agent_id, 'join', null, { lane: agent.agent_lane }]);
+ document.tables.event = [...joins, ...entries].map((entry, order) => ({ entry, order }))
+ .sort((a, b) => a.entry[0] - b.entry[0] || a.order - b.order)
+ .map(({ entry: [minutes, by, kind, item, detail = {}] }, index) => ({
+ event_id: index + 1, event_at: at(minutes), event_by: by, event_kind: kind, item_id: item, event_detail: JSON.stringify(detail),
+ }));
+ document.tables.sqlite_sequence.find(row => row.name === 'event').seq = document.tables.event.length;
+ const board = store.openBoard(join(root, '.git', 'flow.sqlite'));
+ importBoard(board, document);
+ t.after(() => { store.closeBoard(board); rmSync(root, { recursive: true, force: true }); });
+ /** Read the real board at its deterministic observation time. */
+ function stats(options = {}) { return proofStats(board, { now: BASE + now * 60_000, ...options }); }
+ return { board, stats };
+}
+
+/** Produce a valid single-attempt measured cycle with independently chosen four stage lengths. */
+function cycle(id, durations, start = 1, { legacy = false } = {}) {
+ const [build, wait, review, merge] = durations;
+ const submitted = start + build, reserved = submitted + wait, accepted = reserved + review;
+ const commit = String(id).repeat(40);
+ return [
+ [0, 'coordinator', 'add', id, { lane: 'core' }],
+ [start, `core-${id}`, 'claim', id, { leaseUntil: at(1000) }],
+ [submitted, `core-${id}`, 'submit', id, { commit }],
+ ...(legacy ? [] : [[reserved, 'review-1', 'reserve', id, { until: at(1000) }]]),
+ [accepted, 'review-1', 'accept', id, { commit }],
+ [accepted + merge, 'coordinator', 'merged', id, { commit: 'a'.repeat(40) }],
+ ];
+}
+
+/** Return the exact summary expected from hand-computed samples. */
+function summary(count, totalMinutes, averageMinutes, medianMinutes, unmeasuredCompleted = 0) {
+ return { count, totalMinutes, averageMinutes, medianMinutes, unmeasuredCompleted };
+}
+
+test('flow numbers match a hand computation through rework, released reviews and every live queue [R1,R2]', t => {
+ const a = 'a'.repeat(40), b = 'b'.repeat(40), c = 'c'.repeat(40);
+ const entries = [
+ [0, 'coordinator', 'add', 1, { lane: 'core' }], [10, 'core-1', 'claim', 1, { leaseUntil: at(1000) }],
+ [30, 'core-1', 'submit', 1, { commit: a }], [40, 'review-1', 'reserve', 1, { until: at(1000) }],
+ [50, 'review-1', 'reject', 1, { commit: a }], [60, 'core-1', 'claim', 1, { leaseUntil: at(1000) }],
+ [90, 'core-1', 'submit', 1, { commit: b }], [95, 'review-1', 'reserve', 1, { until: at(1000) }],
+ [100, 'review-1', 'release', 1, { review: true }], [120, 'review-2', 'reserve', 1, { until: at(1000) }],
+ [130, 'review-2', 'accept', 1, { commit: b }], [150, 'coordinator', 'merged', 1, { commit: c }],
+ [170, 'coordinator', 'merged', 1, { commit: c }],
+ [5, 'coordinator', 'add', 2, { lane: 'core' }], [20, 'core-2', 'claim', 2, { leaseUntil: at(1000) }],
+ [60, 'core-2', 'submit', 2, { commit: a }], [70, 'review-1', 'reserve', 2, { until: at(1000) }],
+ [100, 'review-1', 'accept', 2, { commit: a }], [160, 'coordinator', 'merged', 2, { commit: c }],
+ [40, 'coordinator', 'add', 3, { lane: 'core' }],
+ [100, 'coordinator', 'add', 4, { lane: 'core' }], [180, 'core-4', 'claim', 4, { leaseUntil: at(1000) }],
+ [190, 'core-4', 'release', 4],
+ [80, 'coordinator', 'add', 5, { lane: 'web' }], [100, 'core-5', 'claim', 5, { leaseUntil: at(180) }],
+ [120, 'coordinator', 'add', 6, { lane: 'core' }], [175, 'core-6', 'claim', 6, { leaseUntil: at(220) }],
+ [195, 'core-6', 'renew', 6, { leaseUntil: at(260) }],
+ [150, 'coordinator', 'add', 7, { lane: 'core' }], [180, 'core-7', 'claim', 7, { leaseUntil: at(1000) }],
+ [190, 'core-7', 'submit', 7, { commit: a }],
+ [150, 'coordinator', 'add', 8, { lane: 'core' }], [180, 'core-8', 'claim', 8, { leaseUntil: at(1000) }],
+ [185, 'core-8', 'submit', 8, { commit: a }], [190, 'review-1', 'reserve', 8, { until: at(1000) }],
+ [195, 'review-1', 'accept', 8, { commit: a }], [199, 'core-7', 'shout', null],
+ ];
+ const { board, stats } = fixture(t, entries);
+ const result = stats();
+ assert.ok(result.flow, 'stats JSON carries event-derived flow');
+ assert.equal(store.getItem(board, 1).item_status, 'open', 'fixture rows cannot substitute for the event history');
+ assert.deepEqual(result.flow.stages, {
+ build: summary(4, 135, 33.75, 25),
+ reviewWait: summary(3, 45, 15, 10),
+ review: summary(3, 45, 15, 10),
+ mergeWait: summary(2, 80, 40, 40),
+ }, 'build samples80,40,10,5; wait30,10,5; review10,30,5; merge20,60');
+ assert.deepEqual(result.flow.queues, {
+ open: { size: 3, oldest: { id: 3, ageMinutes: 160 } }, claimed: { size: 1, oldest: { id: 6, ageMinutes: 25 } },
+ submitted: { size: 1, oldest: { id: 7, ageMinutes: 10 } }, accepted: { size: 1, oldest: { id: 8, ageMinutes: 5 } },
+ });
+ assert.deepEqual(result.flow.daily, [{ date: '2026-10-10', added: 8, merged: 2 }]);
+ assert.equal(result.flow.submitsPerMerged, 2.5, 'five submissions divided by two first merges');
+ assert.equal(result.rejectionShare, 1 / 5);
+ assert.deepEqual(result.flow.activeAgents, {
+ total: 6, roles: { builder: 4, verifier: 1, coordinator: 1, unknown: 0 }, lanes: { coordinator: 1, core: 4, review: 1 },
+ agents: ['coordinator', 'core-4', 'core-6', 'core-7', 'core-8', 'review-1'].map(id => ({
+ id, lane: id === 'coordinator' ? 'coordinator' : id.startsWith('core') ? 'core' : 'review',
+ role: id === 'coordinator' ? 'coordinator' : id.startsWith('core') ? 'builder' : 'verifier',
+ })),
+ });
+ assert.equal(result.flow.bottleneck.stage, 'build');
+ assert.equal(result.flow.bottleneck.share, 120 / 280);
+ assert.equal(result.flow.bottleneck.totalCycleMinutes, 280);
+ assert.equal(result.flow.bottleneck.recommendation, 'add a builder in core');
+ assert.deepEqual(result.flow.bottleneck.completedItems, 2);
+ assert.deepEqual(flowLines(result.flow), [
+ 'build: average 33.75 min · median 25 min · 4 measured; 0 of 2 completed items unmeasured',
+ 'review wait: average 15 min · median 10 min · 3 measured; 0 of 2 completed items unmeasured',
+ 'review: average 15 min · median 10 min · 3 measured; 0 of 2 completed items unmeasured',
+ 'merge wait: average 40 min · median 40 min · 2 measured; 0 of 2 completed items unmeasured',
+ 'open queue: 3 · oldest #3 (160 min)', 'claimed queue: 1 · oldest #6 (25 min)',
+ 'submitted queue: 1 · oldest #7 (10 min)', 'accepted queue: 1 · oldest #8 (5 min)',
+ 'per day: 2026-10-10: 8 added, 2 merged', '2.5 submissions per merged item',
+ 'active in the last hour: 6 agents · roles builder 4, verifier 1, coordinator 1, unknown 0 · lanes coordinator 1, core 4, review 1',
+ 'bottleneck: build has the largest share of cycle time; bottleneck from 2 fully measured cycles of 2 (42.86%)',
+ 'next: add a builder in core',
+ ]);
+ const before = store.events(board);
+ stats();
+ assert.deepEqual(store.events(board), before, 'reading flow never records a move');
+
+ const window = stats({ since: at(150) });
+ assert.deepEqual(window.flow.stages.build, summary(2, 15, 7.5, 7.5));
+ assert.deepEqual(window.flow.stages.mergeWait, summary(2, 80, 40, 40));
+ assert.equal(window.flow.bottleneck.share, 120 / 280, 'completed cycles retain their pre-window stages');
+ assert.deepEqual(window.flow.daily, [{ date: '2026-10-10', added: 2, merged: 2 }]);
+ assert.equal(stats({ since: at(170) }).flow.bottleneck.completedItems, 0, 'a repeated receipt is not another completed cycle');
+ assert.deepEqual(stats({ since: at(170) }).flow.daily, [], 'repeated receipts cannot inflate a later day or window');
+});
+
+test('flow charges an expired reservation to waiting and counts UTC days at their exact boundary [R1,R2]', t => {
+ const commit = '1'.repeat(40);
+ const entries = [
+ [1430, 'coordinator', 'add', 1, { lane: 'core' }], [1431, 'core-1', 'claim', 1, { leaseUntil: at(2000) }],
+ [1435, 'core-1', 'submit', 1, { commit }], [1436, 'review-1', 'reserve', 1, { until: at(1438) }],
+ [1440, 'review-2', 'reserve', 1, { until: at(2000) }], [1443, 'review-2', 'accept', 1, { commit }],
+ [1445, 'coordinator', 'merged', 1, { commit: 'a'.repeat(40) }],
+ [1440, 'coordinator', 'add', 2, { lane: 'core' }], [1446, 'coordinator', 'merged', 1, { commit: 'b'.repeat(40) }],
+ ];
+ const { stats } = fixture(t, entries, 1450);
+ assert.deepEqual(stats().flow.daily, [
+ { date: '2026-10-10', added: 1, merged: 0 }, { date: '2026-10-11', added: 1, merged: 1 },
+ ]);
+ const flow = stats({ since: '2026-10-11' }).flow;
+ assert.deepEqual(flow.stages.build, summary(0, 0, null, null));
+ assert.deepEqual(flow.stages.reviewWait, summary(1, 5, 5, 5));
+ assert.deepEqual(flow.stages.review, summary(1, 3, 3, 3));
+ assert.deepEqual(flow.stages.mergeWait, summary(1, 2, 2, 2));
+ assert.equal(flow.bottleneck.totalCycleMinutes, 14, 'the full cycle retains the four pre-window build minutes');
+ assert.equal(flow.bottleneck.share, 5 / 14);
+ assert.deepEqual(flow.daily, [{ date: '2026-10-11', added: 1, merged: 1 }]);
+});
+
+test('flow distinguishes expired and released reviews, open resets, legacy gaps and exact boundaries [R1,R2]', t => {
+ const commit = '1'.repeat(40);
+ const entries = [
+ ...cycle(1, [10, 20, 5, 10]), ...cycle(2, [10, 90, 20, 10], 1, { legacy: true }),
+ ...cycle(3, [10, 90, 20, 10], 1, { legacy: true }),
+ [20, 'coordinator', 'add', 4, { lane: 'core' }], [30, 'core-4', 'claim', 4, { leaseUntil: at(1000) }],
+ [40, 'core-4', 'submit', 4, { commit }], [45, 'review-1', 'reserve', 4, { until: at(50) }],
+ [180, 'review-2', 'reserve', 4, { until: at(1000) }],
+ [190, 'coordinator', 'reopen', 4, { commit }],
+ [10, 'coordinator', 'add', 5, { lane: 'core' }], [110, 'core-5', 'claim', 5, { leaseUntil: at(1000) }],
+ [120, 'core-5', 'submit', 5, { commit }], [140, 'review-2', 'reserve', 5, { until: at(1000) }],
+ [150, 'review-2', 'reject', 5, { commit }],
+ [139, 'core-1', 'shout', null], [140, 'core-2', 'shout', null], [200, 'core-3', 'shout', null],
+ [150, 'core-6', 'shout', null], [199, 'core-4', 'shout', null], [150, 'core-5', 'shout', null],
+ ];
+ const { stats } = fixture(t, entries);
+ const flow = stats().flow;
+ assert.deepEqual(flow.queues.open, { size: 2, oldest: { id: 5, ageMinutes: 50 } });
+ assert.deepEqual(flow.stages.reviewWait, summary(2, 40, 20, 20, 2), 'legacy review intervals are omitted; reopen has no closing reservation');
+ assert.deepEqual(flow.stages.review, summary(2, 15, 7.5, 7.5, 2));
+ assert.equal(flow.bottleneck.completedItems, 3);
+ assert.equal(flow.bottleneck.fullyMeasuredCycles, 1);
+ assert.equal(flow.bottleneck.lowConfidence, true);
+ assert.equal(flow.bottleneck.stage, 'reviewWait', 'long legacy waits cannot manufacture a measured bottleneck');
+ assert.equal(flow.bottleneck.share, 20 / 45);
+ assert.match(flow.bottleneck.message, /1 fully measured cycles of 3/u);
+ assert.deepEqual(flow.activeAgents.agents.filter(agent => agent.id.startsWith('core')), [
+ { id: 'core-2', lane: 'core', role: 'builder' }, { id: 'core-3', lane: 'core', role: 'builder' },
+ { id: 'core-4', lane: 'core', role: 'builder' }, { id: 'core-5', lane: 'core', role: 'builder' },
+ { id: 'core-6', lane: 'core', role: 'unknown' },
+ ], 'inclusive last-hour boundary, prior role fallback, roleless unknown and stale actor exclusion');
+});
+
+test('every bottleneck recommendation follows its documented rule and ties choose the earlier stage [R1,R2]', t => {
+ for (const [durations, extras, expected] of [
+ [[1, 20, 1, 1], [[190, 'core-1', 'shout', null]], 'add a verifier'],
+ [[1, 20, 1, 1], [[190, 'review-1', 'shout', null]], 'review the oldest submission first (#2)'],
+ [[1, 20, 1, 1], [[190, 'review-1', 'shout', null],
+ [185, 'core-4', 'claim', 4, { leaseUntil: at(1000) }],
+ [180, 'coordinator', 'add', 5, { lane: 'core' }], [185, 'core-5', 'claim', 5, { leaseUntil: at(1000) }],
+ [180, 'coordinator', 'add', 6, { lane: 'core' }], [185, 'core-6', 'claim', 6, { leaseUntil: at(1000) }]], 'review the oldest submission first (#2)'],
+ [[20, 1, 1, 1], [[185, 'review-1', 'reserve', 2, { until: at(1000) }], [190, 'review-1', 'reject', 2, { commit: '2'.repeat(40) }]], 'tighten criteria or briefs: 1 of 3 submissions were sent back'],
+ [[20, 1, 1, 1], [], 'add a builder in core'],
+ [[1, 1, 20, 1], [], 'reviews are slow (median 12.5 min): check how long the frozen checks take'],
+ [[1, 1, 1, 20], [], 'land the accepted items: #3'],
+ [[20, 20, 20, 20], [], 'add a builder in core'],
+ ]) {
+ const entries = [...cycle(1, durations),
+ [100, 'coordinator', 'add', 2, { lane: 'core' }], [110, 'core-2', 'claim', 2, { leaseUntil: at(1000) }],
+ [180, 'core-2', 'submit', 2, { commit: '2'.repeat(40) }],
+ [110, 'coordinator', 'add', 3, { lane: 'core' }], [115, 'core-3', 'claim', 3, { leaseUntil: at(1000) }],
+ [120, 'core-3', 'submit', 3, { commit: '3'.repeat(40) }],
+ [125, 'review-2', 'reserve', 3, { until: at(1000) }], [130, 'review-2', 'accept', 3, { commit: '3'.repeat(40) }],
+ [150, 'coordinator', 'add', 4, { lane: 'core' }], ...extras];
+ const result = fixture(t, entries).stats();
+ assert.equal(result.flow.bottleneck.recommendation, expected, durations.join(','));
+ }
+});
+
+test('flow reports no evidence instead of inventing a bottleneck or missing review time [R1,R2]', t => {
+ const empty = fixture(t, []).stats().flow;
+ assert.equal(empty.bottleneck.stage, null);
+ assert.equal(empty.bottleneck.recommendation, null);
+ assert.equal(empty.submitsPerMerged, 0);
+ assert.deepEqual(empty.stages.build, summary(0, 0, null, null));
+ const legacy = fixture(t, cycle(1, [10, 20, 30, 40], 1, { legacy: true })).stats().flow;
+ assert.equal(legacy.bottleneck.stage, null);
+ assert.equal(legacy.bottleneck.recommendation, null);
+ assert.match(legacy.bottleneck.message, /1 items completed.*none with every stage measured/u);
+ assert.deepEqual(legacy.stages.review, summary(0, 0, null, null, 1));
+ assert.deepEqual(legacy.stages.build, summary(1, 10, 10, 10));
+ const half = fixture(t, [...cycle(1, [10, 20, 30, 40]), ...cycle(2, [10, 20, 30, 40], 1, { legacy: true })]).stats().flow;
+ assert.equal(half.bottleneck.lowConfidence, false, 'exactly half fully measured is not below half');
+});
+
+test('open age restarts on each return and equal queue ages choose the lower id [R1,R2]', t => {
+ const entries = [
+ [0, 'coordinator', 'add', 1, { lane: 'core' }], [10, 'core-1', 'claim', 1, { leaseUntil: at(1000) }],
+ [190, 'core-1', 'release', 1],
+ [0, 'coordinator', 'add', 2, { lane: 'core' }], [10, 'core-2', 'claim', 2, { leaseUntil: at(1000) }],
+ [180, 'core-2', 'submit', 2, { commit: '2'.repeat(40) }], [185, 'coordinator', 'reopen', 2],
+ [0, 'coordinator', 'add', 3, { lane: 'core' }], [10, 'core-3', 'claim', 3, { leaseUntil: at(190) }],
+ ];
+ assert.deepEqual(fixture(t, entries).stats().flow.queues.open, { size: 3, oldest: { id: 2, ageMinutes: 15 } });
+ assert.deepEqual(fixture(t, entries.filter(entry => entry[2] !== 'reopen'), 200).stats().flow.queues.open,
+ { size: 2, oldest: { id: 1, ageMinutes: 10 } });
+});
+
+test('active lane counts preserve recorded names that also exist on Object.prototype [R1,R2]', t => {
+ const entries = [[150, 'core-1', 'join', null, { lane: 'constructor' }], [160, 'core-1', 'shout', null]];
+ assert.deepEqual(fixture(t, entries).stats().flow.activeAgents, {
+ total: 1, agents: [{ id: 'core-1', lane: 'constructor', role: 'unknown' }],
+ roles: { builder: 0, verifier: 0, coordinator: 0, unknown: 1 }, lanes: { constructor: 1 },
+ });
+});