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
fix(api): stabilize flow observation validators [A2,R1,R2]
Corey Olsona4cbdd7fe4cb
diff --git a/src/api-http.js b/src/api-http.jsindex a89ea835..8983ecc9 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -36,10 +36,10 @@ function stateText(state, eventLogVersion) {* no-store: the browser never answers a poll from its cache, so a page that wants the newest clock* readings still gets them by not asking If-None-Match.*/-function sendState(req, res, text, tagged) {+function sendState(req, res, text, tagged, validator = text) {const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' };if (tagged) {- const board = text.replace(/"(asOf|ageMinutes)":(?:"[^"]*"|[-+.0-9eE]+|null)/gu, '"$1":null');+ const board = validator.replace(/"(asOf|ageMinutes)":(?:"[^"]*"|[-+.0-9eE]+|null)/gu, '"$1":null');Object.assign(headers, { etag: '"' + createHash('sha256').update(board).digest('base64url').slice(0, 32) + '"' });const held = String(req.headers['if-none-match'] ?? '').split(',').map((tag) => tag.trim().replace(/^W\//u, ''));if (held.includes(headers.etag)) {@@ -324,10 +324,12 @@ export function createApiHandler(adapter, { pollMs = 200, tagState = false } = {return sendState(req, res, JSON.stringify({ version: 1, ...delta }), tagState);}if (typeof adapter.stateJson === 'function') {- const state = await adapter.stateJson(board, who, seen, options);- if (typeof state !== 'string') throw new TypeError('the local state serializer must return JSON text');+ const encoded = await adapter.stateJson(board, who, seen, options);+ const state = typeof encoded === 'string' ? encoded : encoded?.json;+ if (typeof state !== 'string' || encoded?.validator !== undefined && typeof encoded.validator !== 'string') throw new TypeError('the local state serializer must return JSON text and optional internal validator text');const eventLogVersion = await adapter.eventLogVersion?.(board, who);- return sendState(req, res, stateText(state, eventLogVersion), tagState);+ return sendState(req, res, stateText(state, eventLogVersion), tagState,+ typeof encoded?.validator === 'string' ? stateText(encoded.validator, eventLogVersion) : undefined);}const state = await adapter.state(board, who, seen, options);const eventLogVersion = await adapter.eventLogVersion?.(board, who);diff --git a/src/api.js b/src/api.jsindex 029f1990..0a7e4947 100644--- a/src/api.js+++ b/src/api.js@@ -551,7 +551,9 @@ function searchText(item) {/** One cached board build: the full state, its item summaries, its delta fingerprint and the lookups that serve them. */function snapshotEntry(revision, state, preparedFlow, { inputs = null, itemMeta = new Map(), itemMoveCounts = new Map() } = {}) {const summary = { ...state, items: state.items.map(itemSummary) };- return { revision, sequence: state.sequence, state, summary, preparedFlow, summaryFields: prepareStateJson(summary), stateJsonFields: null,+ const reportValidator = { json: JSON.stringify(state.proofStats?.flow?.report), expiries: [...new Set(preparedFlow.items.flatMap(item =>+ item.state === 'claimed' ? [item.leaseUntil] : item.state === 'submitted' ? [item.reserve?.until] : []).filter(Number.isFinite))].sort((a, b) => a - b) };+ return { revision, sequence: state.sequence, state, summary, preparedFlow, reportValidator, summaryFields: prepareStateJson(summary), stateJsonFields: null,print: fingerprint(summary), items: new Map(state.items.map((item) => [item.id, item])), itemMeta, itemMoveCounts, inputs, searchTexts: null };}@@ -656,13 +658,16 @@ function jsonField(key, value) {}/** Reuse static state fragments while encoding request-specific unread and flow data. */-function serializeState(state, fields) {+function serializeState(state, fields, reportJson) {if (!fields) return JSON.stringify(state);const encoded = fields.map((field) => {if (field.static !== undefined) return field.static;if (field.dynamic === 'unseen') return jsonField('unseen', state.unseen);if (field.dynamic === 'proofStats') {- const flow = jsonField('flow', state.proofStats?.flow);+ const value = state.proofStats?.flow;+ const flow = reportJson === undefined || !value ? jsonField('flow', value)+ : '"flow":{' + Object.entries(value).map(([key, entry]) => key === 'report'+ ? '"report":' + reportJson : jsonField(key, entry)).filter(Boolean).join(',') + '}';return '"proofStats":{' + [...field.stats, flow].filter(Boolean).join(',') + '}';}return '';@@ -991,7 +996,13 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const state = stateForRequest(full ? entry.state : entry.summary, board.root, seen, entry.preparedFlow, cached, codeIsMain);// Full fragments wait for the first full request, so a server sending summaries never builds them.const fields = full ? (entry.stateJsonFields ??= prepareStateJson(entry.state)) : entry.summaryFields;- return { state, json: serializeState(state, fields), entry };+ const expiries = entry.reportValidator.expiries;+ let low = 0, high = expiries.length;+ const now = Date.now();+ while (low < high) { const middle = (low + high) >>> 1; if (expiries[middle] <= now) low = middle + 1; else high = middle; }+ // A snapshot's recorded report stays validator-stable; real lease boundaries remain observable.+ const validator = serializeState(state, fields, entry.reportValidator.json) + '\0report-expiry:' + low;+ return { state, json: serializeState(state, fields), validator, entry };});// Only the build actually returned is sent; a delta extends summaries, never a full state.if (!full) keepSentBase(sent.entry);@@ -1138,7 +1149,10 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =boards: () => withGitReadFacts(() => apiBoardListing(apiProjects, codeIsMain)),board: (id) => withGitReadFacts(() => findBoard(id, apiProjects, codeIsMain)),state: (board, who, seen, options) => withGitReadFacts(() => localState(board, seen, options).state),- stateJson: (board, who, seen, options) => withGitReadFacts(() => localState(board, seen, options).json),+ stateJson: (board, who, seen, options) => withGitReadFacts(() => {+ const sent = localState(board, seen, options);+ return { json: sent.json, validator: sent.validator };+ }),watchRevision: (board) => {const watcher = withGitReadFacts(() => watchLocalStateRevision(board, { scopeCommonDir }));return { ...watcher, revision: () => withGitReadFacts(() => watcher.revision()) };diff --git a/test/flow-report-api.test.js b/test/flow-report-api.test.jsnew file mode 100644index 00000000..22b97b36--- /dev/null+++ b/test/flow-report-api.test.js@@ -0,0 +1,83 @@+/** Stable API validation retains recorded flow facts and native clock boundaries [A2,R1,R2]. */+import assert from 'node:assert/strict';+import { randomUUID } from 'node:crypto';+import { createServer } from 'node:http';+import { join } from 'node:path';+import { after, test } from 'node:test';+import { setTimeout as delay } from 'node:timers/promises';+import { createLocalApiHandler } from '../src/api.js';+import * as store from '../src/board.js';+import { logEvent } from '../src/board-event-log.js';+import { main } from '../src/cli.js';+import { apiFetch } from './api-fixture.js';+import { createE2eHelpers } from './e2e-helpers.js';++const fixtures = createE2eHelpers();+after(fixtures.cleanup);++/** Serve an isolated real Git/SQLite board through the production local adapter. */+async function apiFixture(t) {+ const box = fixtures.project('true');+ const secret = randomUUID();+ let port = 0;+ const handler = createLocalApiHandler({ secret, getPort: () => port, runCommand: main,+ projects: () => [{ root: box.repo, name: 'Flow validator', project: '', added: '2026-01-01T00:00:00Z' }], stateDetail: 'summary' });+ const server = createServer(handler);+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ port = server.address().port;+ t.after(async () => { handler.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });+ const api = { secret, origin: `http://127.0.0.1:${port}` };+ const listing = await (await apiFetch(api, '/api/v1/boards')).json();+ const path = `/api/v1/boards/${listing.boards[0].id}/state`;+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'), undefined, { isMain: true });+ t.after(() => store.closeBoard(board));+ return { api, path, board };+}++/** Append controlled lifecycle evidence through the native counter-maintaining writer. */+function event(board, id, kind, detail, at = Date.now()) {+ logEvent(board, kind === 'reserve' || kind === 'accept' ? 'review-1' : 'web-1', kind, id, detail, new Date(at));+}++test('flow report polls ignore only observation increments and retain claim and reservation expiry [A2,R1,R2]', async t => {+ const { api, path, board } = await apiFixture(t);+ const claim = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Claim clock' });+ const review = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Review clock' });+ const now = Date.now(), until = now + 2500, commit = 'a'.repeat(40);+ event(board, claim, 'claim', { leaseUntil: new Date(until).toISOString() }, now);+ event(board, review, 'claim', { leaseUntil: new Date(now + 60_000).toISOString() }, now - 1000);+ event(board, review, 'submit', { commit }, now - 500);+ event(board, review, 'reserve', { until: new Date(until + 2500).toISOString() }, now);+ const first = await apiFetch(api, path), initial = await first.json();+ const tag = first.headers.get('etag');+ await delay(30);+ const current = await (await apiFetch(api, path)).json();+ assert.notDeepEqual(current.state.proofStats.flow.report, initial.state.proofStats.flow.report, 'public durations continue advancing');+ assert.equal((await apiFetch(api, path, { headers: { 'if-none-match': tag } })).status, 304);+ await delay(Math.max(0, until - Date.now() + 30));+ const expiredClaim = await apiFetch(api, path, { headers: { 'if-none-match': tag } });+ assert.equal(expiredClaim.status, 200, 'a real claim boundary invalidates the report validator');+ const claimTag = expiredClaim.headers.get('etag');+ await expiredClaim.json();+ await delay(Math.max(0, until + 2500 - Date.now() + 30));+ assert.equal((await apiFetch(api, path, { headers: { 'if-none-match': claimTag } })).status, 200, 'a real reservation boundary invalidates it again');+});++test('completed flow durations and captured submission sizes remain validator material [A2,R1,R2]', async t => {+ const { api, path, board } = await apiFixture(t);+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Recorded duration and size' });+ const now = Date.now(), commit = 'b'.repeat(40);+ event(board, id, 'claim', { leaseUntil: new Date(now + 120_000).toISOString() }, now);+ const before = await apiFetch(api, path);+ const oldTag = before.headers.get('etag');+ await before.json();+ event(board, id, 'submit', { commit, submissionSize: { base: 'c'.repeat(40), head: commit, lines: 150, method: 'added-plus-deleted-no-renames' } }, now + 60_000);+ event(board, id, 'reserve', { until: new Date(now + 120_000).toISOString() }, now + 60_000);+ event(board, id, 'accept', { commit }, now + 60_001);+ const changed = await apiFetch(api, path, { headers: { 'if-none-match': oldTag } });+ assert.equal(changed.status, 200);+ const report = (await changed.json()).state.proofStats.flow.report;+ assert.equal(report.overall.sizeBuckets['100to300'].accepted, 1);+ assert.equal(report.items.find(item => item.id === id).stages.build.minutes, 1);+ assert.equal((await apiFetch(api, path, { headers: { 'if-none-match': changed.headers.get('etag') } })).status, 304, 'completed facts stay stable between new events');+});