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(stats): report landed flow windows and stage tails [R1,R2]
Corey Olsonb2ab035aea58
diff --git a/src/cli.js b/src/cli.jsindex dc579b0e..0bbf19fd 100644--- a/src/cli.js+++ b/src/cli.js@@ -567,6 +567,7 @@ const OPTIONS = {history: { type: 'boolean' },verbose: { type: 'boolean' },since: { type: 'string' },+ window: { type: 'string' },decision: { type: 'boolean' },evidence: { type: 'string' },outcome: { type: 'string' },diff --git a/src/commands/stats.js b/src/commands/stats.jsindex 131d3116..201804fb 100644--- a/src/commands/stats.js+++ b/src/commands/stats.js@@ -7,7 +7,15 @@ import { caughtLines } from '../caught.js';import * as gateReceipt from '../gate-receipt.js';import {flowLines,+ flowStats,} from '../stats-flow.js';+import {+ flowWindowLines,+ flowWindowMinutes,+} from '../stats-flow-window.js';+import {+ Refused,+} from '../refused.js';import {proofStats,} from '../stats.js';@@ -20,9 +28,19 @@ import {/** Run `pullboard stats` and return its exit code. */export function run(io, { values }) {const ctx = context(io);- const { stats, agents } = withBoard(ctx, (board) => ({ stats: proofStats(board, { since: values.since }), agents: store.listAgents(board) }));+ if (values.since !== undefined && values.window !== undefined) {+ throw new Refused('USAGE', 'choose either --since <date> or --window <duration>, for example pullboard stats --window 6h');+ }+ const windowMinutes = values.window === undefined ? undefined : flowWindowMinutes(values.window);+ const now = ctx.clock.now().getTime();+ const { stats, agents, window } = withBoard(ctx, (board) => {+ const stats = proofStats(board, { since: values.since, now });+ return { stats, agents: store.listAgents(board), ...(windowMinutes === undefined ? {} : {+ window: flowStats(store.events(board), null, now, stats, { windowMinutes }).window,+ }) };+ });const waits = gateReceipt.gateWaitStats(ctx.info.root);- io.result?.({ stats, gateWaits: waits.stats });+ io.result?.({ stats, gateWaits: waits.stats, ...(window ? { window } : {}) });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'}`);@@ -30,7 +48,7 @@ export function run(io, { values }) {io.say(`events: ${stats.firstEventAt ?? 'none'} to ${stats.lastEventAt ?? 'none'}${stats.since ? ` (since ${stats.since})` : ''}`);for (const line of barStatsLines(stats.bars)) io.say(line);for (const line of caughtLines(stats.caught)) io.say(line);- for (const line of flowLines(stats.flow)) io.say(line);+ for (const line of window ? flowWindowLines(window) : flowLines(stats.flow)) io.say(line);for (const line of waits.lines) io.say(line);return 0;}diff --git a/src/help.js b/src/help.jsindex 53b79e78..dcff3eae 100644--- a/src/help.js+++ b/src/help.js@@ -166,7 +166,9 @@ Coordinatorpullboard hold <lane|id> --off lift a lane or item holdReceipts- pullboard stats [--since <date>] proof numbers from the event log; --json for sites and tools+ pullboard stats [--since <date> | --window <duration>] proof numbers from the event log; --json for sites and tools+ --window 6h (also 30m or 1d): landed-item stage quartiles, tails and excess over targets;+ includes all attempts and sent-back idle; missing intervals stay unmeasured;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;diff --git a/src/stats-flow-window.js b/src/stats-flow-window.jsnew file mode 100644index 00000000..cac25323--- /dev/null+++ b/src/stats-flow-window.js@@ -0,0 +1,148 @@+/** Window projections of the canonical lifecycle observer; absent evidence is never a zero [R1,R2]. */+import { Refused } from './refused.js';++const MINUTE = 60_000;+export const WINDOW_STAGES = ['build', 'reviewWait', 'review', 'sendBackIdle', 'mergeWait'];+const TARGETS = { build: 240, reviewWait: 30, review: 60, sendBackIdle: 30, mergeWait: 60 };+const LABELS = { build: 'building', reviewWait: 'waiting for a reviewer', review: 'in review',+ sendBackIdle: 'sent back, idle', mergeWait: 'waiting to land' };++/** Enable interval observations only for an explicitly requested window, not persistent proof counters. */+export function newWindowTrace() {+ return { cursor: null, entries: [], intervals: [], missing: [], submissions: 0, rejections: 0 };+}++/** Observe a transition already accepted by moveFlowItem, without replaying another state machine. */+export function observeFlowStage(item, stage, at, by) {+ const trace = item.windowTrace;+ if (!trace || item.mergeAt !== undefined) return;+ const prior = trace.cursor;+ if (prior?.stage === stage) return;+ if (prior && Number.isFinite(at) && at >= prior.start) {+ trace.intervals.push({ ...prior, end: at, completedBy: by });+ } else if (prior && !trace.missing.includes(prior.stage)) trace.missing.push(prior.stage);+ trace.cursor = stage ? { stage, start: at, by } : null;+ if (trace.cursor) trace.entries.push({ ...trace.cursor });+}++/** A verdict without a recorded reservation cannot divide waiting from review work. */+export function observeFlowVerdict(item, by) {+ const trace = item.windowTrace;+ if (!trace || trace.cursor?.stage === 'review' && trace.cursor.by === by) return;+ for (const stage of ['reviewWait', 'review']) if (!trace.missing.includes(stage)) trace.missing.push(stage);+ trace.cursor = null;+}++/** Freeze nested observations along with the existing immutable prepared lifecycle. */+export function frozenWindowTrace(trace) {+ return Object.freeze({ ...trace, cursor: trace.cursor ? Object.freeze({ ...trace.cursor }) : null,+ entries: Object.freeze(trace.entries.map(row => Object.freeze({ ...row }))),+ intervals: Object.freeze(trace.intervals.map(row => Object.freeze({ ...row }))),+ missing: Object.freeze([...trace.missing]) });+}++/** Accept positive durations with an explicit unit; timestamps continue to use the separate --since option. */+export function flowWindowMinutes(value) {+ const match = /^(\d+(?:\.\d+)?)(m|h|d)$/u.exec(String(value));+ const minutes = match ? Number(match[1]) * { m: 1, h: 60, d: 1440 }[match[2]] : NaN;+ if (!(minutes > 0) || !Number.isFinite(minutes)) {+ throw new Refused('USAGE', 'use pullboard stats --window with a positive duration, for example --window 6h, --window 30m or --window 1d');+ }+ return minutes;+}++/** The reference uses discrete quarter indices and the arithmetic median, including even sample counts. */+function quartiles(values) {+ const sorted = [...values].sort((a, b) => a - b);+ const count = sorted.length;+ const middle = Math.floor(count / 2);+ return { fastQuarterMinutes: count ? sorted[Math.min(count - 1, Math.floor(count / 4))] : null,+ medianMinutes: count ? count % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2 : null,+ slowQuarterMinutes: count ? sorted[Math.min(count - 1, Math.floor(count * 3 / 4))] : null,+ worstMinutes: count ? sorted.at(-1) : null };+}++/** Classify an observed tail; reviewer eligibility stays explicitly unknown without a recorded observation. */+function tailItem(item, stage, minutes) {+ const trace = item.windowTrace;+ const cause = stage === 'build' ? trace.submissions >= 3 ? 'rework' : 'long-build'+ : { reviewWait: 'reviewer-wait', review: 'slow-review', sendBackIdle: 'send-back-idle', mergeWait: 'landing-queue' }[stage];+ return { id: item.id, minutes, cause, submissions: trace.submissions, rejections: trace.rejections,+ ...(stage === 'reviewWait' ? { eligibility: 'unmeasured' } : {}) };+}++/** Sum only closed intervals; an omitted or incomplete stage is not a measured zero-minute visit. */+function stageMinutes(item, stage) {+ const trace = item.windowTrace;+ if (!trace || trace.missing.includes(stage)) return null;+ const rows = trace.intervals.filter(row => row.stage === stage && row.end <= item.mergeAt);+ return rows.length ? rows.reduce((sum, row) => sum + (row.end - row.start) / MINUTE, 0) : null;+}++/** Close a still-held cursor at its recorded expiry for observation-only traffic counts. */+function trafficTrace(item, now) {+ const trace = item.windowTrace;+ if (!trace?.cursor) return trace;+ const { stage } = trace.cursor;+ const until = stage === 'build' ? item.leaseUntil : stage === 'review' ? item.reserve?.until : NaN;+ if (!Number.isFinite(until) || until > now || until < trace.cursor.start) return trace;+ const entries = stage === 'review' ? [...trace.entries, { stage: 'reviewWait', start: until, by: 'clock' }] : trace.entries;+ return { ...trace, entries, intervals: [...trace.intervals, { ...trace.cursor, end: until, completedBy: 'clock' }] };+}++/** Count visits in the window, including unfinished work, and only name seats observed doing that work. */+function stageTraffic(items, stage, since, now) {+ let arrivals = 0, completions = 0;+ const seats = new Set();+ for (const item of items) {+ const trace = trafficTrace(item, now);+ for (const row of trace?.entries ?? []) {+ if (row.stage !== stage || row.start < since || row.start > now) continue;+ arrivals += 1;+ if (['build', 'review'].includes(stage) && row.by && !['clock', 'board', 'person'].includes(row.by)) seats.add(row.by);+ }+ for (const row of trace?.intervals ?? []) {+ if (row.stage !== stage || row.end < since || row.end > now) continue;+ completions += 1;+ if (row.completedBy && !['clock', 'board', 'person'].includes(row.completedBy)) seats.add(row.completedBy);+ }+ }+ return { arrivals, completions, seats: [...seats].sort() };+}++/** Project landed item totals and stage traffic from the same prepared canonical lifecycle facts. */+export function projectFlowWindow(prepared, minutes, now) {+ if (!(minutes > 0) || !Number.isFinite(minutes) || !Number.isFinite(new Date(now - minutes * MINUTE).getTime())) {+ throw new Refused('USAGE', 'use pullboard stats --window with a positive finite duration, for example --window 6h');+ }+ const since = now - minutes * MINUTE;+ const landed = prepared.items.filter(item => item.mergeAt >= since && item.mergeAt <= now);+ const stages = Object.fromEntries(WINDOW_STAGES.map(stage => {+ const measured = landed.map(item => ({ item, minutes: stageMinutes(item, stage) })).filter(row => row.minutes !== null);+ const values = measured.map(row => row.minutes);+ return [stage, { count: values.length, ...quartiles(values), totalMinutes: values.reduce((sum, value) => sum + value, 0),+ unmeasuredCompleted: landed.length - values.length, targetMinutes: TARGETS[stage],+ overTargetMinutes: values.reduce((sum, value) => sum + Math.max(0, value - TARGETS[stage]), 0),+ ...stageTraffic(prepared.items, stage, since, now),+ tail: measured.sort((a, b) => b.minutes - a.minutes || a.item.id - b.item.id).slice(0, 3)+ .map(row => tailItem(row.item, stage, row.minutes)) }];+ }));+ const constraint = WINDOW_STAGES.reduce((largest, stage) => stages[stage].overTargetMinutes > (largest ? stages[largest].overTargetMinutes : 0) ? stage : largest, null);+ return { since: new Date(since).toISOString(), until: new Date(now).toISOString(), durationMinutes: minutes,+ landedItems: landed.length,+ arrivals: { added: prepared.dailyEvents.filter(event => event.kind === 'added' && event.at >= since && event.at <= now).length, landed: landed.length },+ stages, constraint: { stage: constraint, overTargetMinutes: constraint ? stages[constraint].overTargetMinutes : 0 } };+}++/** Render the measured window without substituting zero for absent quartiles or undocumented eligibility. */+export function flowWindowLines(window) {+ const time = value => value === null ? 'unmeasured' : `${Number(value.toFixed(2))} min`;+ return [`flow window: ${window.since} to ${window.until} · ${window.arrivals.added} added · ${window.landedItems} landed`,+ ...WINDOW_STAGES.flatMap(stage => {+ const row = window.stages[stage];+ return [`${LABELS[stage]}: ${row.count} measured · fast quarter ${time(row.fastQuarterMinutes)} · median ${time(row.medianMinutes)} · slow quarter ${time(row.slowQuarterMinutes)} · worst ${time(row.worstMinutes)} · ${row.unmeasuredCompleted} unmeasured`,+ ` ${row.arrivals} arrivals · ${row.completions} completions · seats ${row.seats.join(', ') || 'none observed'} · ${time(row.overTargetMinutes)} over ${time(row.targetMinutes)} target`,+ ...row.tail.map(item => ` #${item.id}: ${time(item.minutes)} · ${item.cause}${item.eligibility ? ' (eligibility unmeasured; check eligible reviewers)' : ''}`)];+ }),+ `constraint: ${window.constraint.stage ? LABELS[window.constraint.stage] : 'none measured over target'} · ${time(window.constraint.overTargetMinutes)} over target`];+}diff --git a/src/stats-flow.js b/src/stats-flow.jsindex 8bde4bbe..b6d4d1c5 100644--- a/src/stats-flow.js+++ b/src/stats-flow.js@@ -1,4 +1,11 @@import { proofEventDetail } from './proof-event-detail.js';+import {+ newWindowTrace,+ observeFlowStage,+ observeFlowVerdict,+ frozenWindowTrace,+ projectFlowWindow,+} from './stats-flow-window.js';/** Flow times, queues and recommendations from recorded lifecycle evidence [R1,R2]. */const MINUTE = 60_000;const STAGES = ['build', 'reviewWait', 'review', 'mergeWait'];@@ -29,6 +36,7 @@ export function roleOf(kind, detail) {/** 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) {+ observeFlowStage(item, null, item.leaseUntil, 'clock');item.state = 'open';item.openAt = item.leaseUntil;}@@ -37,24 +45,39 @@ function expireClaim(item, at) {/** Replay one lifecycle move; its first claim and first merge survive rework and repeated receipts. */export function moveFlowItem(item, event, detail, at) {expireClaim(item, at);+ if (item.windowTrace?.cursor?.stage === 'review' && Number.isFinite(item.reserve?.until) && (item.reserve.until < at || item.reserve.until === at && !['accept', 'reject'].includes(event.event_kind))) {+ observeFlowStage(item, 'reviewWait', item.reserve.until, 'clock');+ }switch (event.event_kind) {case 'add':item.lane = detail.lane ?? 'unknown'; item.state = 'open'; item.openAt = at; break;case 'claim':+ observeFlowStage(item, 'build', at, event.event_by);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':+ if (item.windowTrace && item.mergeAt === undefined) {+ item.windowTrace.submissions += 1;+ if (item.windowTrace.cursor?.stage !== 'build' && !item.windowTrace.missing.includes('build')) item.windowTrace.missing.push('build');+ }+ observeFlowStage(item, 'reviewWait', at, event.event_by);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 'reserve':+ observeFlowStage(item, 'review', at, event.event_by);+ item.reserve = { at, by: event.event_by, until: Date.parse(detail.until) }; break;case 'release':+ observeFlowStage(item, detail.review || item.state === 'submitted' ? 'reviewWait' : null, at, event.event_by);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;+ if (item.state === 'submitted') observeFlowVerdict(item, event.event_by);+ observeFlowStage(item, event.event_kind === 'accept' ? 'mergeWait' : 'sendBackIdle', at, event.event_by);+ if (event.event_kind === 'reject' && item.windowTrace && item.mergeAt === undefined) item.windowTrace.rejections += 1;item.verdictAt = at;item.finalReserveAt = item.reserve?.by === event.event_by &&(!Number.isFinite(item.reserve.until) || item.reserve.until >= at) ? item.reserve.at : null;@@ -63,12 +86,16 @@ export function moveFlowItem(item, event, detail, at) {else { item.state = 'open'; item.openAt = at; }break;}- case 'merged': item.mergeAt ??= at; item.state = 'merged'; break;+ case 'merged':+ observeFlowStage(item, null, at, event.event_by);+ 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;+ case 'lapse':+ observeFlowStage(item, null, at, event.event_by);+ item.state = 'open'; item.openAt = at; item.reserve = null; break;+ case 'withdraw': observeFlowStage(item, null, at, event.event_by); item.state = 'withdrawn'; break;}}@@ -146,7 +173,7 @@ function recommendation(stage, { activeAgents, queues, openByLane, accepted, cou}/** Compile immutable lifecycle facts once so API cache hits only need a time-specific projection. */-export function prepareFlowHistory(history) {+export function prepareFlowHistory(history, { window = false } = {}) {const items = new Map();const actors = new Map();const dailyEvents = [];@@ -162,7 +189,7 @@ export function prepareFlowHistory(history) {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' });+ if (!items.has(event.item_id)) items.set(event.item_id, { id: event.item_id, lane: 'unknown', ...(window ? { windowTrace: newWindowTrace() } : {}) });const item = items.get(event.item_id);if (event.event_kind === 'add') dailyEvents.push({ at, kind: 'added' });if (event.event_kind === 'merged' && item.mergeAt === undefined) dailyEvents.push({ at, kind: 'merged' });@@ -170,6 +197,7 @@ export function prepareFlowHistory(history) {}const frozenItems = [...items.values()].map((item) => Object.freeze({...item,+ ...(item.windowTrace ? { windowTrace: frozenWindowTrace(item.windowTrace) } : {}),...(item.reserve ? { reserve: Object.freeze({ ...item.reserve }) } : {}),}));const frozenActors = [...actors.values()].map((actor) => Object.freeze({ ...actor }));@@ -178,7 +206,7 @@ export function prepareFlowHistory(history) {}/** Project current queues and time windows from compiled facts without mutating the cached snapshot. */-export function projectFlowStats(prepared, boundary, now, counts) {+export function projectFlowStats(prepared, boundary, now, counts, { windowMinutes } = {}) {const selected = at => !boundary || at >= Date.parse(boundary);const daily = new Map();for (const event of prepared.dailyEvents) {@@ -218,13 +246,13 @@ export function projectFlowStats(prepared, 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, unreviewed: queueData.unreviewed, daily: [...daily.values()].sort((a, b) => a.date.localeCompare(b.date)),+ return { ...(windowMinutes === undefined ? {} : { window: projectFlowWindow(prepared, windowMinutes, now) }), 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 };}/** Derive flow from an immutable history with an injectable observation time for fixtures. */-export function flowStats(history, boundary, now, counts) {- return projectFlowStats(prepareFlowHistory(history), boundary, now, counts);+export function flowStats(history, boundary, now, counts, options = {}) {+ return projectFlowStats(prepareFlowHistory(history, { window: options.windowMinutes !== undefined }), boundary, now, counts, options);}/** Format elapsed minutes in rounded human units while JSON retains its original numeric precision. */diff --git a/test/stats-cli.test.js b/test/stats-cli.test.jsindex 5959ce27..67216e37 100644--- a/test/stats-cli.test.js+++ b/test/stats-cli.test.js@@ -13,10 +13,10 @@ import { serveApi } from '../src/api.js';import { fetchFresh } from './http-fixture.js';/** Capture the real CLI without spawning a second model or changing the machine's registry. */-async function run(root, args) {+async function run(root, args, clock) {let stdout = '';let stderr = '';- const code = await main(args, { cwd: root,+ const code = await main(args, { cwd: root, ...(clock ? { clock } : {}),stdout: { isTTY: false, write: (text) => { stdout += text; } },stderr: { write: (text) => { stderr += text; } } });return { code, stdout, stderr, data: args.includes('--json') ? JSON.parse(stdout) : null };@@ -208,3 +208,36 @@ test('[N26,D1] the caught list never interrupts', async (t) => {assert.deepEqual(store.events(board), before, 'asking for the list records nothing');assert.equal(board.db.prepare('SELECT count(*) AS n FROM shout').get().n, shouts, 'a catch pushes no shout, banner or notification');});+++test('[R1,R2,A1] stats window exposes measured tails in text and JSON without recording moves', async t => {+ const { root, board } = fixture(t);+ const clock = { now: () => new Date('2026-10-08T13:00:00Z') };+ const before = store.events(board);+ const json = await run(root, ['stats', '--window', '6h', '--json'], clock);+ assert.equal(json.code, 0, json.stderr);+ assert.equal(json.data.version, 1);+ assert.equal(json.data.window.durationMinutes, 360);+ assert.equal(json.data.window.landedItems, 1);+ assert.equal(json.data.window.stages.build.count, 1);+ assert.equal(json.data.window.stages.build.medianMinutes, 0, 'recorded instantaneous work is a measured zero');+ assert.equal(json.data.window.stages.review.medianMinutes, null, 'the fixture has no reservation evidence');+ assert.deepEqual(json.data.stats, proofStats(board, { now: clock.now().getTime() }));+ const text = await run(root, ['stats', '--window', '6h'], clock);+ assert.equal(text.code, 0, text.stderr);+ assert.match(text.stdout, /flow window:.*1 landed/u);+ assert.match(text.stdout, /in review: 0 measured.*median unmeasured/u);+ assert.match(text.stdout, /#1: 0 min/u);+ const help = await run(root, ['stats', '--help']);+ assert.match(help.stdout, /--window <duration>/u);+ for (const duration of ['0h', '-1h', '6', 'forever', '999999999999999999999d']) {+ const bad = await run(root, ['stats', '--window', duration, '--json'], clock);+ assert.equal(bad.code, 1);+ assert.equal(bad.data.error.code, 'USAGE');+ assert.match(bad.data.error.next, /--window 6h/u);+ }+ const ambiguous = await run(root, ['stats', '--window', '6h', '--since', '2026-10-08', '--json'], clock);+ assert.equal(ambiguous.code, 1);+ assert.equal(ambiguous.data.error.code, 'USAGE');+ assert.deepEqual(store.events(board), before);+});diff --git a/test/stats-flow.test.js b/test/stats-flow.test.jsindex 0d7fb141..55a40039 100644--- a/test/stats-flow.test.js+++ b/test/stats-flow.test.js@@ -114,6 +114,70 @@ test('a flow window reports stage quartiles and the slowest items with their cauassert.deepEqual(store.events(board), history, 'statistics append no synthetic measurement moves');});+test('flow windows retain released reviews, lease boundaries and repeated accept evidence [R1,R2]', t => {+ const commit = 'a'.repeat(40);+ const { board, stats } = fixture(t, [+ [0, 'coordinator', 'add', 1, { lane: 'core' }],+ [10, 'core-1', 'claim', 1, { leaseUntil: at(1000) }],+ [20, 'core-1', 'submit', 1, { commit }],+ [30, 'review-1', 'reserve', 1, { until: at(35) }],+ [40, 'review-2', 'reserve', 1, { until: at(50) }],+ [50, 'review-2', 'release', 1, { review: true }],+ [60, 'review-1', 'reserve', 1, { until: at(70) }],+ [70, 'review-1', 'accept', 1, { commit }],+ [80, 'review-1', 'accept', 1, { commit }],+ [90, 'coordinator', 'merged', 1],+ [0, 'coordinator', 'add', 2, { lane: 'core' }],+ [10, 'core-2', 'claim', 2, { leaseUntil: at(25) }],+ [0, 'coordinator', 'add', 3, { lane: 'core' }],+ [10, 'core-3', 'claim', 3, { leaseUntil: at(1000) }],+ [20, 'core-3', 'submit', 3, { commit }],+ [30, 'review-2', 'reserve', 3, { until: at(40) }],+ ], 100);+ const history = store.events(board);+ const prepared = prepareFlowHistory(history, { window: true });+ const before = JSON.stringify(prepared);+ const window = projectFlowStats(prepared, null, BASE + 100 * 60_000, stats(), { windowMinutes: 100 }).window;+ assert.equal(window.landedItems, 1);+ assert.equal(window.stages.build.medianMinutes, 10);+ assert.equal(window.stages.reviewWait.medianMinutes, 25, 'wait is 20-30 plus 35-40 plus 50-60');+ assert.equal(window.stages.review.medianMinutes, 25, 'review ends at recorded expiry or release; a verdict at expiry remains valid');+ assert.equal(window.stages.mergeWait.medianMinutes, 20, 'repeated acceptance cannot erase the first acceptance');+ assert.deepEqual(window.stages.review.seats, ['review-1', 'review-2']);+ assert.equal(window.stages.review.completions, 4, 'includes the still-submitted item reservation expiry');+ assert.equal(window.stages.build.completions, 3, 'includes a claim expiring without another move');+ assert.equal(window.stages.reviewWait.arrivals, 5, 'includes observed waiting after expiry');+ assert.equal(JSON.stringify(prepared), before, 'time-specific expiry observation does not mutate reusable history');+ assert.deepEqual(store.events(board), history);+});++test('flow windows leave missing starts and empty distributions unmeasured [R1,R2]', t => {+ const commit = 'a'.repeat(40);+ const { board, stats } = fixture(t, [+ [0, 'coordinator', 'add', 1, { lane: 'core' }],+ [10, 'core-1', 'submit', 1, { commit }],+ [20, 'review-1', 'reject', 1, { commit }],+ [30, 'core-1', 'claim', 1, { leaseUntil: at(1000) }],+ [40, 'core-1', 'submit', 1, { commit: 'b'.repeat(40) }],+ [50, 'review-1', 'reserve', 1, { until: at(1000) }],+ [60, 'review-1', 'accept', 1, { commit: 'b'.repeat(40) }],+ [70, 'coordinator', 'merged', 1],+ ], 100);+ const history = store.events(board);+ const window = flowStats(history, null, BASE + 100 * 60_000, stats(), { windowMinutes: 100 }).window;+ assert.equal(window.stages.build.count, 0, 'one measured rework cannot fill a missing original start');+ assert.equal(window.stages.build.medianMinutes, null);+ assert.equal(window.stages.reviewWait.count, 0, 'an unreserved original verdict leaves the whole item total incomplete');+ assert.equal(window.stages.reviewWait.arrivals, 2, 'a missing close cannot erase a known arrival');+ assert.equal(window.stages.sendBackIdle.medianMinutes, 10);+ const empty = flowStats(history, null, BASE + 100 * 60_000, stats(), { windowMinutes: 10 }).window;+ assert.equal(empty.landedItems, 0);+ assert.equal(empty.stages.build.count, 0);+ assert.equal(empty.stages.build.worstMinutes, null);+ assert.deepEqual(empty.stages.build.tail, []);+ assert.deepEqual(empty.constraint, { stage: null, overTargetMinutes: 0 });+});+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 = [