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(api): reuse unchanged board state [A2,N26]

Corey Olson228e1b099bb7
diff --git a/src/api.js b/src/api.js
index 4be3e21e..d3c9e77d 100644
--- a/src/api.js
+++ b/src/api.js
@@ -1,17 +1,19 @@
/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */
-import { randomBytes, timingSafeEqual } from 'node:crypto';
+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
import { join } from 'node:path';
+import { existsSync, readFileSync } from 'node:fs';
import { displayAgentName } from './agent-names.js';
import * as store from './board.js';
-import { COORDINATOR, loadConfig } from './config.js';
-import { codeIsFromMain, repoInfo } from './git.js';
+import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
+import { codeIsFromMain, repoInfo, resolveCommit } from './git.js';
import { refusalDocument } from './json.js';
import { relayLinked, relayOperation, relayRevoke, relayTokens } from './relay.js';
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 { projectRowDecisions } from './row-decisions.js';
import { Refused } from './refused.js';
import { codeAt, projectState } from './serve.js';
@@ -21,6 +23,94 @@ import { moveArgs } from './api-moves.js';
import { personRequestStatuses } from './relay-requests.js';
export { moveArgs } from './api-moves.js';
+/** Hash the exact bytes of one state input, preserving a missing-file marker. */
+function fileRevision(root, file) {
+ const path = join(root, file);
+ if (!existsSync(path)) return [file, null];
+ return [file, createHash('sha256').update(readFileSync(path)).digest('hex')];
+}
+
+/** Capture the inexpensive inputs that can invalidate a complete board-state snapshot. */
+function boardStateRevision(root, id, isMain) {
+ const info = repoInfo(root);
+ const config = loadConfig(info.root);
+ const files = [
+ fileRevision(info.root, CONFIG_FILE),
+ fileRevision(info.root, config.spec),
+ fileRevision(info.root, config.practice),
+ ['standard-doctrine.md', createHash('sha256').update(readFileSync(new URL('./standard-doctrine.md', import.meta.url))).digest('hex')],
+ ];
+ const local = withBoard(info.root, (board) => {
+ const now = board.clock.now().toISOString();
+ const agents = store.listAgents(board);
+ const leases = board.db.prepare('SELECT item_id, item_status, item_owner, item_lease_until, item_review_by, item_review_until FROM item ORDER BY item_id').all()
+ .map((item) => [
+ item.item_id, item.item_status, item.item_owner, item.item_lease_until, item.item_review_by, item.item_review_until,
+ item.item_status === 'claimed' && (item.item_lease_until ?? '') > now,
+ item.item_status === 'submitted' && Boolean(item.item_review_by) && (item.item_review_until ?? '') > now,
+ ]);
+ const milestones = store.milestones(board);
+ const hasExternalMilestones = milestones.some((milestone) => milestone.items.some((item) => typeof item !== 'number'));
+ return {
+ event: board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id,
+ agents,
+ leases,
+ milestones: hasExternalMilestones ? milestoneRoadmap(info.root, board) : store.roadmap(board),
+ };
+ }, isMain);
+ const revision = JSON.stringify([
+ info.commonDir, id, resolveCommit(info.root, 'HEAD'), files,
+ local.event, local.agents, local.leases, local.milestones, store.EVENT_LOG_VERSION,
+ ]);
+ return { cacheId: info.commonDir + '\0' + id, revision, milestones: local.milestones, cacheable: true };
+}
+
+/** Build the complete local API state, including fields that the shared project snapshot omits. */
+function buildLocalBoardState(board, codeIsMain, milestones) {
+ let state = projectState(board.root, { seen: null, isMain: codeIsMain });
+ const config = loadConfig(board.root);
+ state.agents = state.agents.map((agent) => ({
+ ...agent,
+ model: agent.agent_model ?? 'unknown',
+ displayName: displayAgentName(agent, config.agents.names),
+ }));
+ state.board = board.id;
+ const projectData = withBoard(board.root, (db) => ({
+ requests: store.openRequests(db),
+ personRequests: personRequestStatuses(db),
+ milestones,
+ rowDecisions: store.rowDecisions(db),
+ checks: new Map(store.listItems(db, { all: true }).map((item) => store.getItem(db, item.item_id)).map((item) => [item.item_id, {
+ check: item.item_check,
+ ...(item.item_check_baseline ? { checkBaseline: item.item_check_baseline } : {}),
+ }])),
+ proofStats: proofStats(db),
+ threads: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, store.itemThread(db, item.item_id)])),
+ }), codeIsMain);
+ state.proofStats = projectData.proofStats;
+ state.requests = projectData.requests;
+ state.personRequests = projectData.personRequests;
+ state.milestones = projectData.milestones;
+ state.items = state.items.map((item) => ({ ...item, ...projectData.checks.get(item.id) }));
+ state = projectRowDecisions(projectData.rowDecisions, state);
+ state.items = state.items.map((item) => ({ ...item, thread: projectData.threads.get(item.id) ?? [] }));
+ return state;
+}
+
+/** Add the request-specific unread count without mutating the reusable snapshot. */
+function stateForRequest(state, root, seen, history, 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) {
+ projection.proofStats = {
+ ...state.proofStats,
+ flow: flowStats(history, null, Date.now(), state.proofStats),
+ };
+ }
+ return { ...state, ...projection };
+}
+
const ADDRESS = '127.0.0.1';
const VERSION = 1;
@@ -138,12 +228,13 @@ async function createRequest(root, body, isMain) {
}
/** Create the authenticated local adapter used by the HTTP server and other local transports. */
-export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, isMain, allowedOrigins = [] } = {}) {
+export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, isMain, allowedOrigins = [], onStateBuild } = {}) {
if (typeof getPort !== 'function') throw new TypeError('createLocalApiHandler needs a bound-port getter');
if (typeof runCommand !== 'function') throw new TypeError('createLocalApiHandler needs the actual CLI entry point as runCommand');
const codeIsMain = codeIsFromMain() && isMain !== false;
const key = Buffer.from(secret);
const permittedOrigins = new Set(allowedOrigins);
+ const stateCache = new Map();
return createApiHandler({
authenticate: (req) => {
const url = new URL(req.url ?? '/', 'http://' + ADDRESS);
@@ -158,34 +249,29 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
boards: () => apiBoardListing(projects, codeIsMain),
board: (id) => findBoard(id, projects, codeIsMain),
state: (board, who, seen) => {
- let state = projectState(board.root, { seen, isMain: codeIsMain });
- const config = loadConfig(board.root);
- state.agents = state.agents.map((agent) => ({
- ...agent,
- model: agent.agent_model ?? 'unknown',
- displayName: displayAgentName(agent, config.agents.names),
- }));
- state.board = board.id;
- const projectData = withBoard(board.root, (db) => ({
- requests: store.openRequests(db),
- personRequests: personRequestStatuses(db),
- milestones: milestoneRoadmap(board.root, db),
- rowDecisions: store.rowDecisions(db),
- checks: new Map(store.listItems(db, { all: true }).map((item) => store.getItem(db, item.item_id)).map((item) => [item.item_id, {
- check: item.item_check,
- ...(item.item_check_baseline ? { checkBaseline: item.item_check_baseline } : {}),
- }])),
- proofStats: proofStats(db),
- threads: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, store.itemThread(db, item.item_id)])),
- }), codeIsMain);
- state.proofStats = projectData.proofStats;
- state.requests = projectData.requests;
- state.personRequests = projectData.personRequests;
- state.milestones = projectData.milestones;
- state.items = state.items.map((item) => ({ ...item, ...projectData.checks.get(item.id) }));
- state = projectRowDecisions(projectData.rowDecisions, state);
- state.items = state.items.map((item) => ({ ...item, thread: projectData.threads.get(item.id) ?? [] }));
- return state;
+ 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 after = boardStateRevision(board.root, board.id, codeIsMain);
+ if (after.cacheable && after.revision === before.revision) {
+ stateCache.delete(before.cacheId);
+ stateCache.set(before.cacheId, cached);
+ return afterProjection;
+ }
+ }
+
+ onStateBuild?.({ board: board.id });
+ const state = buildLocalBoardState(board, codeIsMain, before.milestones);
+ const history = withBoard(board.root, (db) => store.events(db), codeIsMain);
+ 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 });
+ while (stateCache.size > 32) stateCache.delete(stateCache.keys().next().value);
+ } else {
+ stateCache.delete(before.cacheId);
+ }
+ return stateForRequest(state, board.root, seen, null, false, codeIsMain);
},
shout: (board, id) => relayLinked(board.root)
? relayPresentationShout(board.root, id)
@@ -201,10 +287,10 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
}
/** Serve the RFC 0002 API only on loopback, behind the same session-secret boundary as the view. */
-export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects, isMain } = {}) {
+export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects, isMain, onStateBuild } = {}) {
if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');
let bound;
- const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects, isMain });
+ const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects, isMain, onStateBuild });
const server = createServer(handler);
server.requestTimeout = 15_000;
return new Promise((ready, fail) => {
diff --git a/test/api-http.test.js b/test/api-http.test.js
index 8feac635..22f10e02 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -46,7 +46,17 @@ function fixture(t) {
/** Decode one successful versioned CLI invocation without printing session links. */
function cli(cwd, ...args) {
const result = run(cwd, ...args, '--json');
- assert.equal(result.status, 0, result.stderr);
+ let reason = result.stderr;
+ if (result.status !== 0 && result.stdout) {
+ try {
+ const response = JSON.parse(result.stdout);
+ const error = response?.error;
+ if (error && typeof error === 'object') {
+ reason = [result.stderr, error.code, error.message].filter(Boolean).join('\n');
+ }
+ } catch { /* Keep the existing stderr-only diagnostic for non-JSON failures. */ }
+ }
+ assert.equal(result.status, 0, reason);
return JSON.parse(result.stdout);
}
git('init', '-q', '-b', 'main');
@@ -61,9 +71,9 @@ function fixture(t) {
}
/** Serve this fixture's explicit project, avoiding any registry outside its private home. */
-async function httpBox(t, { includeMissing = false } = {}) {
+async function httpBox(t, { includeMissing = false, onStateBuild } = {}) {
const box = fixture(t);
- const api = await serveApi({ runCommand: main, projects: () => [...(includeMissing ? [{ root: join(box.dir, 'gone'), name: 'Missing fixture' }] : []), { root: box.root, name: 'HTTP fixture' }] });
+ const api = await serveApi({ runCommand: main, onStateBuild, projects: () => [...(includeMissing ? [{ root: join(box.dir, 'gone'), name: 'Missing fixture' }] : []), { root: box.root, name: 'HTTP fixture' }] });
t.after(() => api.close());
const url = new URL(api.url);
const key = url.searchParams.get('k');
@@ -101,6 +111,102 @@ test('[A2] a stale registered folder does not hide another readable board', asyn
assert.equal(state.document.state.board, box.id);
});
+/** Prove the authenticated HTTP state reuses a complete snapshot until one of its inputs changes. */
+async function cachedHttpStateTest(t) {
+ let builds = 0;
+ const box = await httpBox(t, { onStateBuild: () => { builds += 1; } });
+ const agent = box.cli(box.root, 'worktree', 'app', '--model', 'fixture-agent');
+ box.cli(box.root, 'shout', 'app', 'cache baseline');
+
+ const first = await box.call(box.path + '/state');
+ assert.equal(first.status, 200);
+ assert.equal(builds, 1);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ const unchanged = await box.call(box.path + '/state');
+ assert.equal(builds, 1, 'an identical refresh reuses the complete board state');
+ assert.notEqual(unchanged.document.state.proofStats.flow.asOf, first.document.state.proofStats.flow.asOf);
+
+ const latestShout = first.document.state.shouts.at(-1).shout_id;
+ const unread = await box.call(box.path + '/state?seen=0');
+ assert.equal(unread.document.state.unseen.since, 0);
+ assert.ok(unread.document.state.unseen.count > 0);
+ const read = await box.call(box.path + '/state?seen=' + latestShout);
+ assert.deepEqual(read.document.state.unseen, { since: latestShout, count: 0 });
+ assert.equal(builds, 1, 'the request-specific seen cursor does not rebuild or mutate the shared state');
+
+ box.cli(box.root, 'add', 'app', 'cache invalidation item', '--criterion', 'visible after the next refresh', '--specs', 'G1');
+ const moved = await box.call(box.path + '/state');
+ assert.equal(builds, 2);
+ assert.ok(moved.document.state.items.some((item) => item.title === 'cache invalidation item'));
+
+ writeFileSync(join(box.root, 'SPEC.md'), '# HTTP fixture\n\n## Goals\n- G1 [approved, must] Keep the board. | gate: true\n- G2 [approved, must] Keep the cache fresh. | gate: true\n');
+ const spec = await box.call(box.path + '/state');
+ assert.equal(builds, 3);
+ assert.ok(spec.document.state.spec.some((row) => row.id === 'G2'));
+
+ const configFile = join(box.root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
+ writeFileSync(configFile, JSON.stringify({ ...config, lease: '1m', lanes: { ...config.lanes, ops: { owns: [] } } }));
+ const configured = await box.call(box.path + '/state');
+ assert.equal(builds, 4);
+ assert.ok(configured.document.state.lanes.includes('ops'));
+
+ writeFileSync(join(box.root, 'DOCTRINE.md'), '# Local rules\n\n## Team Rules\n\n- LOCAL1 [approved, must] Keep the local board readable. | gate: true\n');
+ const doctrine = await box.call(box.path + '/state');
+ assert.equal(builds, 5);
+ assert.ok(doctrine.document.state.practice.some((row) => row.id === 'LOCAL1'));
+
+ writeFileSync(join(box.root, 'cache-head.txt'), 'advance HEAD without a board event\n');
+ runFixtureGit(['add', 'cache-head.txt'], { cwd: box.root, env: box.env, stdio: 'pipe' });
+ runFixtureGit(['commit', '-q', '-m', 'chore: advance fixture head'], { cwd: box.root, env: box.env, stdio: 'pipe' });
+ const headed = await box.call(box.path + '/state');
+ assert.equal(builds, 6);
+ const head = runFixtureGit(['rev-parse', 'HEAD'], { cwd: box.root, env: box.env, stdio: 'pipe' });
+ assert.equal(headed.document.state.rowAgesAt['SPEC.md'], head);
+
+ box.cli(box.root, 'shout', 'app', 'agent inbox cursor');
+ const beforeInbox = await box.call(box.path + '/state');
+ const agentBeforeInbox = beforeInbox.document.state.agents.find((entry) => entry.agent_id === agent.agent);
+ const boardBeforeInbox = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
+ try {
+ store.inbox(boardBeforeInbox, agent.agent);
+ } finally {
+ store.closeBoard(boardBeforeInbox);
+ }
+ const afterInbox = await box.call(box.path + '/state');
+ const agentAfterInbox = afterInbox.document.state.agents.find((entry) => entry.agent_id === agent.agent);
+ assert.equal(agentAfterInbox.agent_last_shout_id, Math.max(...beforeInbox.document.state.shouts.map((shout) => shout.shout_id)));
+ assert.notEqual(agentAfterInbox.agent_last_shout_id, agentBeforeInbox.agent_last_shout_id);
+ assert.equal(builds, 8, 'an inbox cursor change without an event invalidates the agent projection');
+
+ const added = await box.call(box.path + '/moves', { verb: 'add', args: { lane: 'app', title: 'Lease cache item', criterion: 'remain current', specs: 'G1' } });
+ assert.equal(added.status, 200);
+ const itemId = added.document.result.item.item_id;
+ const claimed = await box.call(box.path + '/moves', { verb: 'claim', item: itemId, agent: agent.agent });
+ assert.equal(claimed.status, 200);
+ const active = await box.call(box.path + '/state');
+ assert.equal(active.document.state.items.find((item) => item.id === itemId).status, 'claimed');
+ const lastEvent = active.document.state.events[0].event_id;
+ const leaseBoard = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
+ let leaseUntil;
+ try {
+ leaseUntil = leaseBoard.db.prepare('SELECT item_lease_until FROM item WHERE item_id = ?').get(itemId).item_lease_until;
+ } finally {
+ store.closeBoard(leaseBoard);
+ }
+ assert.ok(Number.isFinite(Date.parse(leaseUntil)));
+ const now = Date.now();
+ t.mock.timers.enable({ apis: ['Date'], now });
+ t.mock.timers.tick(Math.max(1, Date.parse(leaseUntil) - now + 1));
+ const expired = await box.call(box.path + '/state');
+ assert.equal(expired.document.state.items.find((item) => item.id === itemId).status, 'open');
+ assert.equal(expired.document.state.items.find((item) => item.id === itemId).owner, null);
+ assert.equal(expired.document.state.events[0].event_id, lastEvent, 'lease expiry changed no board event');
+ assert.equal(builds, 10, 'clock-only lease expiry invalidates the cached state');
+}
+
+test('[A2, N26] an unchanged board state is reused and a move rebuilds it', cachedHttpStateTest);
+
test('[A2] local HTTP state accepts a safe seen cursor and committed code previews', async (t) => {
const box = await httpBox(t);
box.cli(box.root, 'shout', 'app', 'state cursor baseline');