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.

perf(api): project cached flow history per request [A2]

Corey Olson886e7a0a8d1b
diff --git a/src/api.js b/src/api.js
index d3c9e77d..8760f796 100644
--- a/src/api.js
+++ b/src/api.js
@@ -13,7 +13,7 @@ import { laneNames } from './lanes.js';
import { listApiProjects } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
import { proofStats } from './stats.js';
-import { flowStats } from './stats-flow.js';
+import { prepareFlowHistory, projectFlowStats } from './stats-flow.js';
import { projectRowDecisions } from './row-decisions.js';
import { Refused } from './refused.js';
import { codeAt, projectState } from './serve.js';
@@ -98,14 +98,14 @@ function buildLocalBoardState(board, codeIsMain, milestones) {
}
/** Add the request-specific unread count without mutating the reusable snapshot. */
-function stateForRequest(state, root, seen, history, refreshFlow, isMain) {
+function stateForRequest(state, root, seen, preparedFlow, refreshFlow, isMain) {
const projection = seen === null ? { unseen: null } : withBoard(root, (board) => ({
unseen: { since: seen, count: board.db.prepare('SELECT COUNT(*) AS n FROM shout WHERE shout_id > ?').get(seen).n },
}), isMain);
- if (refreshFlow && history) {
+ if (refreshFlow && preparedFlow) {
projection.proofStats = {
...state.proofStats,
- flow: flowStats(history, null, Date.now(), state.proofStats),
+ flow: projectFlowStats(preparedFlow, null, Date.now(), state.proofStats),
};
}
return { ...state, ...projection };
@@ -252,7 +252,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
const before = boardStateRevision(board.root, board.id, codeIsMain);
const cached = stateCache.get(before.cacheId);
if (before.cacheable && cached?.revision === before.revision) {
- const afterProjection = stateForRequest(cached.state, board.root, seen, cached.history, true, codeIsMain);
+ const afterProjection = stateForRequest(cached.state, board.root, seen, cached.preparedFlow, true, codeIsMain);
const after = boardStateRevision(board.root, board.id, codeIsMain);
if (after.cacheable && after.revision === before.revision) {
stateCache.delete(before.cacheId);
@@ -264,9 +264,10 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
onStateBuild?.({ board: board.id });
const state = buildLocalBoardState(board, codeIsMain, before.milestones);
const history = withBoard(board.root, (db) => store.events(db), codeIsMain);
+ const preparedFlow = prepareFlowHistory(history);
const after = boardStateRevision(board.root, board.id, codeIsMain);
if (before.cacheable && after.cacheable && before.revision === after.revision) {
- stateCache.set(before.cacheId, { revision: before.revision, state, history });
+ stateCache.set(before.cacheId, { revision: before.revision, state, preparedFlow });
while (stateCache.size > 32) stateCache.delete(stateCache.keys().next().value);
} else {
stateCache.delete(before.cacheId);
diff --git a/src/git.js b/src/git.js
index 0c5d0a3b..61f06b8e 100644
--- a/src/git.js
+++ b/src/git.js
@@ -271,21 +271,23 @@ function readRepoInfo(cwd, env) {
* @returns {boolean}
*/
export function codeIsFromMain(root = CODE_ROOT) {
- const env = gitChildEnv(root);
- const top = tryGit(root, ['rev-parse', '--show-toplevel'], { env });
- if (top.status === 0) return repoInfo(root, { env }).isMain;
- let folder = resolve(root);
- while (true) {
- try {
- lstatSync(join(folder, '.git'));
- throw new Refused('UNMERGED_SCHEMA', 'the running code has Git metadata that cannot be read; restore its Git link before retrying, or install a released pullboard outside this checkout');
- } catch (error) {
- if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
+ return fact(`codeIsFromMain:${resolve(root)}`, () => {
+ const env = gitChildEnv(root);
+ const top = tryGit(root, ['rev-parse', '--show-toplevel'], { env });
+ if (top.status === 0) return repoInfo(root, { env }).isMain;
+ let folder = resolve(root);
+ while (true) {
+ try {
+ lstatSync(join(folder, '.git'));
+ throw new Refused('UNMERGED_SCHEMA', 'the running code has Git metadata that cannot be read; restore its Git link before retrying, or install a released pullboard outside this checkout');
+ } catch (error) {
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
+ }
+ const parent = dirname(folder);
+ if (parent === folder) return true;
+ folder = parent;
}
- const parent = dirname(folder);
- if (parent === folder) return true;
- folder = parent;
- }
+ });
}
/**
diff --git a/src/stats-flow.js b/src/stats-flow.js
index b42fcfcc..db498f1f 100644
--- a/src/stats-flow.js
+++ b/src/stats-flow.js
@@ -90,30 +90,32 @@ function queuesFrom(items, now) {
const openByLane = new Map();
const accepted = [];
for (const item of items) {
- expireClaim(item, now);
- const queue = queues[item.state];
+ const current = item.state === 'claimed' && Number.isFinite(item.leaseUntil) && item.leaseUntil <= now
+ ? { ...item, state: 'open', openAt: item.leaseUntil }
+ : item;
+ const queue = queues[current.state];
if (!queue) continue;
queue.size += 1;
- const start = { open: item.openAt, claimed: item.claimAt, submitted: item.submitAt, accepted: item.acceptAt }[item.state];
+ const start = { open: current.openAt, claimed: current.claimAt, submitted: current.submitAt, accepted: current.acceptAt }[current.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, since: new Date(start).toISOString(), ageMinutes };
- if (item.state === 'submitted' && (!item.reserve || Number.isFinite(item.reserve.until) && item.reserve.until <= now)) {
+ ageMinutes === queue.oldest.ageMinutes && current.id < queue.oldest.id)) queue.oldest = { id: current.id, since: new Date(start).toISOString(), ageMinutes };
+ if (current.state === 'submitted' && (!current.reserve || Number.isFinite(current.reserve.until) && current.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 };
+ ageMinutes === unreviewed.oldest.ageMinutes && current.id < unreviewed.oldest.id)) {
+ unreviewed.oldest = { id: current.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);
+ if (current.state === 'open') openByLane.set(current.lane, (openByLane.get(current.lane) ?? 0) + 1);
+ if (current.state === 'accepted') accepted.push(current.id);
}
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. */
function activeFrom(actors, now) {
- const agents = [...actors.values()].filter(actor => actor.lastAt >= now - 60 * MINUTE && actor.lastAt <= now)
+ const agents = [...actors].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();
@@ -142,19 +144,11 @@ function recommendation(stage, { activeAgents, queues, openByLane, accepted, cou
return accepted.length ? `land the accepted items: ${named}${more}` : '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) {
+/** Compile immutable lifecycle facts once so API cache hits only need a time-specific projection. */
+export function prepareFlowHistory(history) {
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);
- }
+ const dailyEvents = [];
for (const event of history) {
const detail = JSON.parse(event.event_detail);
const at = Date.parse(event.event_at);
@@ -169,16 +163,35 @@ export function flowStats(history, boundary, now, counts) {
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;
+ if (event.event_kind === 'add') dailyEvents.push({ at, kind: 'added' });
+ if (event.event_kind === 'merged' && item.mergeAt === undefined) dailyEvents.push({ at, kind: 'merged' });
move(item, event, detail, at);
}
+ const frozenItems = [...items.values()].map((item) => Object.freeze({
+ ...item,
+ ...(item.reserve ? { reserve: Object.freeze({ ...item.reserve }) } : {}),
+ }));
+ const frozenActors = [...actors.values()].map((actor) => Object.freeze({ ...actor }));
+ const frozenDailyEvents = dailyEvents.map((event) => Object.freeze(event));
+ return Object.freeze({ items: Object.freeze(frozenItems), actors: Object.freeze(frozenActors), dailyEvents: Object.freeze(frozenDailyEvents) });
+}
+
+/** Project current queues and time windows from compiled facts without mutating the cached snapshot. */
+export function projectFlowStats(prepared, boundary, now, counts) {
+ const selected = at => !boundary || at >= Date.parse(boundary);
+ const daily = new Map();
+ for (const event of prepared.dailyEvents) {
+ if (!selected(event.at)) continue;
+ const date = new Date(event.at).toISOString().slice(0, 10);
+ if (!daily.has(date)) daily.set(date, { date, added: 0, merged: 0 });
+ daily.get(date)[event.kind] += 1;
+ }
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()) {
+ for (const item of prepared.items) {
const measured = itemStages(item, now);
for (const stage of STAGES) {
const sample = measured[stage];
@@ -192,8 +205,8 @@ export function flowStats(history, boundary, now, counts) {
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 queueData = queuesFrom(prepared.items, now);
+ const activeAgents = activeFrom(prepared.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 ? {
@@ -208,6 +221,11 @@ export function flowStats(history, boundary, now, counts) {
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);
+}
+
/** Format elapsed minutes in rounded human units while JSON retains its original numeric precision. */
function duration(value) {
if (value === null) return 'unmeasured';
diff --git a/test/git-provenance.test.js b/test/git-provenance.test.js
index 66ed31fa..bade34f6 100644
--- a/test/git-provenance.test.js
+++ b/test/git-provenance.test.js
@@ -1,11 +1,12 @@
/** Running source provenance ignores inherited Git hook repository overrides [A5,A6]. */
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
+import { codeIsFromMain, withGitFacts } from '../src/git.js';
/** Run Git in a disposable fixture without depending on user or system config. */
function git(cwd, args, env) {
@@ -64,3 +65,40 @@ test('[A5,A6] code provenance strips inherited GIT_DIR in both worktree-to-main
});
assert.equal(mainAsWorktree, true, 'main source can upgrade in a hook that inherits linked-worktree variables');
});
+
+test('[A2,N26,A5,A6] code provenance is cached per request and refreshes for the next request', async (t) => {
+ const fixture = mkdtempSync(join(tmpdir(), 'pullboard-git-provenance-scope-'));
+ t.after(() => rmSync(fixture, { recursive: true, force: true }));
+ const main = join(fixture, 'main');
+ const linked = join(fixture, 'linked');
+ const alias = join(fixture, 'active');
+ mkdirSync(main);
+ const baseEnv = {
+ ...process.env,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Provenance test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Provenance test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ const init = git(main, ['init', '-q', '-b', 'main'], baseEnv);
+ assert.equal(init.status, 0, init.stderr);
+ writeFileSync(join(main, 'README.md'), 'fixture\n');
+ for (const args of [['add', 'README.md'], ['commit', '-q', '-m', 'fixture']]) {
+ const result = git(main, args, baseEnv);
+ assert.equal(result.status, 0, result.stderr);
+ }
+ const worktree = git(main, ['worktree', 'add', '-q', '-b', 'feature', linked], baseEnv);
+ assert.equal(worktree.status, 0, worktree.stderr);
+ symlinkSync(main, alias);
+
+ await withGitFacts(async () => {
+ assert.equal(codeIsFromMain(alias), true, 'the primary checkout has main-checkout provenance');
+ unlinkSync(alias);
+ symlinkSync(linked, alias);
+ assert.equal(codeIsFromMain(alias), true, 'one request keeps a consistent provenance fact');
+ });
+
+ assert.equal(codeIsFromMain(alias), false, 'the next request recomputes linked-worktree provenance');
+});
diff --git a/test/stats-flow.test.js b/test/stats-flow.test.js
index a241e1f9..89d688ed 100644
--- a/test/stats-flow.test.js
+++ b/test/stats-flow.test.js
@@ -7,7 +7,7 @@ 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 { flowLines, flowStats, prepareFlowHistory, projectFlowStats } from '../src/stats-flow.js';
import { runFixtureGit } from './fixture-child.js';
const BASE = Date.parse('2026-10-10T00:00:00Z');
@@ -259,6 +259,43 @@ test('a recommendation names at most three items [R1,R2]', t => {
assert.equal(flow.bottleneck.recommendation, 'land the accepted items: #1, #2, #3 +2 more');
});
+test('a prepared flow projection matches fresh expiry and activity windows without mutation [R1,R2]', t => {
+ const commit = 'a'.repeat(40);
+ const entries = [
+ [-30, 'activity-only', 'shout', null],
+ [0, 'coordinator', 'add', 1, { lane: 'core' }], [10, 'core-1', 'claim', 1, { leaseUntil: at(30) }],
+ [0, 'coordinator', 'add', 2, { lane: 'core' }], [10, 'core-2', 'claim', 2, { leaseUntil: at(1000) }],
+ [20, 'core-2', 'submit', 2, { commit }], [21, 'review-1', 'reserve', 2, { until: at(30) }],
+ ];
+ const { board } = fixture(t, entries);
+ const history = store.events(board);
+ const counts = { submissions: 1, rejections: 0, rejectionShare: 0 };
+ const prepared = prepareFlowHistory(history);
+ const observe = minute => projectFlowStats(prepared, null, BASE + minute * 60_000, counts);
+ const reference = minute => flowStats(history, null, BASE + minute * 60_000, counts);
+
+ const beforeExpiry = observe(29);
+ assert.deepEqual(beforeExpiry, reference(29));
+ assert.equal(beforeExpiry.queues.claimed.size, 1);
+ assert.equal(beforeExpiry.unreviewed.size, 0);
+ assert.ok(beforeExpiry.activeAgents.agents.some(agent => agent.id === 'activity-only'));
+
+ const atExpiry = observe(30);
+ assert.deepEqual(atExpiry, reference(30));
+ assert.equal(atExpiry.queues.claimed.size, 0, 'a claim expires at its exact lease deadline');
+ assert.equal(atExpiry.queues.open.size, 1);
+ assert.equal(atExpiry.unreviewed.size, 1, 'a reservation expires at its exact deadline');
+ assert.ok(atExpiry.activeAgents.agents.some(agent => agent.id === 'activity-only'), 'the last-hour boundary is inclusive');
+
+ const afterExpiry = observe(31);
+ assert.deepEqual(afterExpiry, reference(31));
+ assert.equal(afterExpiry.stages.reviewWait.count, 0, 'an expired reservation no longer closes the wait stage');
+ assert.ok(!afterExpiry.activeAgents.agents.some(agent => agent.id === 'activity-only'), 'activity ages out after 60 minutes');
+ assert.deepEqual(observe(30), atExpiry, 'a later projection cannot mutate the prepared snapshot');
+ assert.deepEqual(observe(31), afterExpiry, 'repeating a projection yields the same time-specific result');
+ assert.ok(Object.isFrozen(prepared) && Object.isFrozen(prepared.items) && Object.isFrozen(prepared.items[0]));
+});
+
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);