Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(cli): name flow bottlenecks in coordinator resume [N32]
Corey Olson0b551a7e8bc0
diff --git a/docs/api.md b/docs/api.mdindex 87ba7463..7fb4f4a9 100644--- a/docs/api.md+++ b/docs/api.md@@ -27,6 +27,12 @@ The board-state API's item projection includes `check` and, when recorded, `checThe 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 <lane with the most open items>**, 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.+`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.++For example: `flow: review wait average 61 min (1 measured; > 60 min); bottleneck: build (66.67% of 300 measured cycle min); next: add a builder when open work is available`. An unmeasured trip reads `flow: unreviewed #1 waiting 181 min (> 180 min); bottleneck: not measured yet`.+`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.jsindex 8ce11c31..7c9a99ae 100644--- a/src/cli.js+++ b/src/cli.js@@ -67,7 +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 { flowLines, flowAlertLine } from './stats-flow.js';import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';@@ -872,7 +872,8 @@ function resumeHere(io) {return {me,all,- ...(decisionSections ? { ...decisions, ...verifiedMergeGroups(root, toMerge, shouts, ctx.clock.now().getTime()) } : {}),+ ...(decisionSections ? { ...decisions, ...verifiedMergeGroups(root, toMerge, shouts, ctx.clock.now().getTime()),+ flow: proofStats(board, { now: ctx.clock.now().getTime() }).flow } : {}),requests: me.id === COORDINATOR ? store.openRequests(board) : [],holding: all.filter((item) => item.item_status === 'claimed' && item.item_owner === me.id),sentBack: all@@ -968,6 +969,8 @@ function resumeHere(io) {else next = 'nothing open in your lane; pullboard next --verify names work you can check';io.result?.({ ...card, root, dirty, next });say(`next: ${next}`);+ const flowAlert = isMain ? flowAlertLine(card.flow) : null;+ if (flowAlert) say(flowAlert);return 0;}diff --git a/src/stats-flow.js b/src/stats-flow.jsindex dbe830c0..9509dab7 100644--- a/src/stats-flow.js+++ b/src/stats-flow.js@@ -86,6 +86,7 @@ function itemStages(item, now) {/** 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 unreviewed = { size: 0, oldest: null };const openByLane = new Map();const accepted = [];for (const item of items) {@@ -97,10 +98,17 @@ function queuesFrom(items, now) {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, since: new Date(start).toISOString(), ageMinutes };+ if (item.state === 'submitted' && (!item.reserve || Number.isFinite(item.reserve.until) && item.reserve.until <= now)) {+ unreviewed.size += 1;+ if (ageMinutes !== null && (!unreviewed.oldest || ageMinutes > unreviewed.oldest.ageMinutes ||+ ageMinutes === unreviewed.oldest.ageMinutes && item.id < unreviewed.oldest.id)) {+ unreviewed.oldest = { id: item.id, since: new Date(start).toISOString(), 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) };+ return { queues, unreviewed, 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. */@@ -194,7 +202,7 @@ export function flowStats(history, boundary, now, counts) {} : { 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 { asOf: new Date(now).toISOString(), stages, queues: queueData.queues, daily: [...daily.values()].sort((a, b) => a.date.localeCompare(b.date)),+ return { asOf: new Date(now).toISOString(), stages, queues: queueData.queues, unreviewed: queueData.unreviewed, daily: [...daily.values()].sort((a, b) => a.date.localeCompare(b.date)),submitsPerMerged: completedItems ? counts.submissions / completedItems : 0, activeAgents, bottleneck };}@@ -218,3 +226,17 @@ export function flowLines(flow) {if (bottleneck.recommendation) lines.push(`next: ${bottleneck.recommendation}`);return lines;}++/** Name a tripped documented threshold using the same measured flow and action as stats [N32]. */+export function flowAlertLine(flow) {+ const average = flow.stages.reviewWait.averageMinutes;+ const oldest = flow.unreviewed.oldest;+ const thresholds = [];+ if (average > 60) thresholds.push(`review wait average ${minutes(average)} min (${flow.stages.reviewWait.count} measured; > 60 min)`);+ if (oldest?.ageMinutes > 180) thresholds.push(`unreviewed #${oldest.id} waiting ${minutes(oldest.ageMinutes)} min (> 180 min)`);+ if (!thresholds.length) return null;+ const bottleneck = flow.bottleneck;+ const measured = bottleneck.stage === null ? 'bottleneck: not measured yet' :+ `bottleneck: ${LABELS[bottleneck.stage]} (${minutes(bottleneck.share * 100)}% of ${minutes(bottleneck.totalCycleMinutes)} measured cycle min); next: ${bottleneck.recommendation}`;+ return `flow: ${thresholds.join('; ')}; ${measured}`;+}diff --git a/test/resume-flow.test.js b/test/resume-flow.test.jsnew file mode 100644index 00000000..5155b837--- /dev/null+++ b/test/resume-flow.test.js@@ -0,0 +1,161 @@+/** Coordinator flow alerts reuse the real Git/SQLite statistics and documented thresholds [N32,R1,R2]. */+import assert from 'node:assert/strict';+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 { runFixtureGit } from './fixture-child.js';++const BASE = Date.parse('2026-10-10T00:00:00Z');+const MINUTE = 60_000;++/** Build native lifecycle moves on a private real board with a deterministic observation clock. */+function fixture(t, { wait = null, age = null, reservation = null, otherAge = null } = {}) {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-resume-flow-')));+ /** Run Git with a private fixture identity and no user configuration. */+ const git = (...args) => runFixtureGit(args, { cwd: root, stdio: 'pipe', env: {+ ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ } });+ git('init', '-q', '-b', 'main');+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', verify: 'any', lanes: { web: { owns: ['web/'] } } }));+ writeFileSync(join(root, 'SPEC.md'), '# Flow fixture\n\n## G · Goals\n- G1 [approved, must] The fixture works. | gate: test\n');+ writeFileSync(join(root, 'DOCTRINE.md'), '# Doctrine\n');+ git('add', '-A');+ git('commit', '-q', '-m', 'chore: create flow fixture');+ const web = join(root, 'builder');+ git('worktree', 'add', '-q', '-b', 'web/one', web);+ let at = 0;+ const clock = { now: () => new Date(BASE + at * MINUTE) };+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'), clock);+ t.after(() => { store.closeBoard(board); rmSync(root, { recursive: true, force: true }); });+ store.register(board, { lane: 'coordinator', path: root });+ const builder = store.register(board, { lane: 'web', path: web });+ const reviewer = store.register(board, { lane: 'review', path: join(root, 'reviewer') });+ const freeze = () => ({ text: JSON.stringify({ rows: [] }), digest: 'frozen' });+ /** Add and submit an item at exact recorded minute offsets. */+ function submit(start, submitted) {+ at = start;+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Flow fixture' });+ store.claim(board, id, { agentId: builder, lane: 'web', leaseMs: 1000 * MINUTE, freeze });+ at = submitted;+ store.submit(board, id, { agentId: builder, commit: 'a'.repeat(40), tree: 'b'.repeat(40) });+ return id;+ }+ if (wait !== null) {+ const id = submit(0, 200);+ at = 200 + wait;+ store.reserveReview(board, id, { agentId: reviewer, leaseMs: 1000 * MINUTE, policy: 'any' });+ at += 20;+ store.verify(board, id, { agentId: reviewer, decision: 'ACCEPT', note: 'Fixture meets its bar.', head: 'a'.repeat(40), digest: 'frozen', policy: 'any' });+ at = 300;+ store.merged(board, id, { agentId: 'coordinator', commit: 'c'.repeat(40) });+ }+ let waiting = null;+ if (age !== null) {+ waiting = submit(301, 500 - age);+ if (otherAge !== null) submit(311, 500 - otherAge);+ if (reservation !== null) {+ at = 350;+ store.reserveReview(board, waiting, { agentId: reviewer, leaseMs: (reservation === 'live' ? 151 : 150) * MINUTE, policy: 'any' });+ if (reservation === 'released') {+ at = 450;+ store.release(board, waiting, reviewer, 'Fixture releases its review.');+ } else if (reservation === 'verdict') {+ at = 450;+ store.verify(board, waiting, { agentId: reviewer, decision: 'REJECT', reason: 'TEST_FAILURE', note: 'Fixture rejection.', head: 'a'.repeat(40), digest: 'frozen', policy: 'any' });+ }+ }+ }+ at = 500;+ /** Run the real command against its native board and capture exact text or JSON. */+ async function run(args, cwd = root) {+ let stdout = '', stderr = '';+ const code = await main(args, { cwd, clock,+ stdout: { isTTY: false, write: text => { stdout += text; } },+ stderr: { write: text => { stderr += text; } } });+ assert.equal(code, 0, stderr || stdout);+ return args.includes('--json') ? JSON.parse(stdout) : stdout.trimEnd();+ }+ return { root, web, waiting, run, stats: () => proofStats(board, { now: clock.now().getTime() }) };+}++/** Require exactly one final line while preserving the ordinary next-step line immediately before it. */+function alert(text, expected) {+ const lines = text.split('\n');+ assert.deepEqual(lines.filter(line => line.startsWith('flow:')), [expected]);+ assert.equal(lines.at(-1), expected);+ assert.match(lines.at(-2), /^next: /u);+}++test('coordinator resume ends with the exact measured-average flow alert [N32,R1,R2]', async t => {+ const box = fixture(t, { wait: 61 });+ alert(await box.run(['resume']), 'flow: review wait average 61 min (1 measured; > 60 min); bottleneck: build (66.67% of 300 measured cycle min); next: add a builder when open work is available');+ const json = await box.run(['resume', '--json']);+ assert.deepEqual(json.flow, box.stats().flow, 'resume uses precisely the stats observation, stage and action');+ const stats = await box.run(['stats', '--json']);+ assert.deepEqual(json.flow.stages, stats.stats.flow.stages);+ assert.deepEqual(json.flow.bottleneck, stats.stats.flow.bottleneck);+});++test('coordinator resume alerts for the oldest unreviewed submission alone [N32,R1,R2]', async t => {+ const box = fixture(t, { wait: 10, age: 181 });+ alert(await box.run(['resume']), 'flow: unreviewed #2 waiting 181 min (> 180 min); bottleneck: build (66.67% of 300 measured cycle min); next: add a builder when open work is available');+ assert.deepEqual(box.stats().flow.unreviewed, { size: 1, oldest: { id: 2, since: '2026-10-10T05:19:00.000Z', ageMinutes: 181 } });+});++test('coordinator resume keeps both threshold trips in one final flow line [N32,R1,R2]', async t => {+ const box = fixture(t, { wait: 61, age: 181 });+ alert(await box.run(['resume']), 'flow: review wait average 61 min (1 measured; > 60 min); unreviewed #2 waiting 181 min (> 180 min); bottleneck: build (66.67% of 300 measured cycle min); next: add a builder when open work is available');+});++test('coordinator resume adds no alert at exact healthy threshold boundaries [N32,R1,R2]', async t => {+ const box = fixture(t, { wait: 60, age: 180 });+ const text = await box.run(['resume']);+ assert.doesNotMatch(text, /^flow:/mu);+ assert.match(text.split('\n').at(-1), /^next: /u);+});++test('coordinator resume adds no alert to an unmeasured healthy board [N32,R1,R2]', async t => {+ const box = fixture(t);+ assert.equal(box.stats().flow.bottleneck.stage, null);+ assert.doesNotMatch(await box.run(['resume']), /^flow:/mu);+});++test('coordinator resume names an old waiting item without inventing a measured bottleneck [N32,R1,R2]', async t => {+ const box = fixture(t, { age: 181 });+ alert(await box.run(['resume']), 'flow: unreviewed #1 waiting 181 min (> 180 min); bottleneck: not measured yet');+});++for (const reservation of ['expired', 'released']) {+ test(`coordinator resume counts an ${reservation} review as unreserved from final submit [N32,R1,R2]`, async t => {+ const box = fixture(t, { age: 181, reservation });+ alert(await box.run(['resume']), 'flow: unreviewed #1 waiting 181 min (> 180 min); bottleneck: not measured yet');+ });+}++for (const reservation of ['live', 'verdict']) {+ test(`coordinator resume excludes a ${reservation} review from the unreviewed alert [N32,R1,R2]`, async t => {+ const box = fixture(t, { age: 181, reservation });+ assert.deepEqual(box.stats().flow.unreviewed, { size: 0, oldest: null });+ assert.doesNotMatch(await box.run(['resume']), /^flow:/mu);+ });+}++test('agent resume keeps its next step without a coordinator flow alert [N32,R1,R2]', async t => {+ const box = fixture(t, { wait: 61, age: 181 });+ const text = await box.run(['resume'], box.web);+ assert.doesNotMatch(text, /^flow:/mu);+ assert.match(text.split('\n').at(-1), /^next: /u);+ assert.equal(Object.hasOwn(await box.run(['resume', '--json'], box.web), 'flow'), false);+});++test('coordinator resume finds the oldest unreserved item behind an older live review [N32,R1,R2]', async t => {+ const box = fixture(t, { age: 190, otherAge: 181, reservation: 'live' });+ alert(await box.run(['resume']), 'flow: unreviewed #2 waiting 181 min (> 180 min); bottleneck: not measured yet');+ assert.deepEqual(box.stats().flow.unreviewed, { size: 1, oldest: { id: 2, since: '2026-10-10T05:19:00.000Z', ageMinutes: 181 } });+});