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
perf: cache serialized API state fragments
Corey Olsonc4bc642725ae
diff --git a/src/api-http.js b/src/api-http.jsindex fc6cb3ff..19c3d63e 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -16,6 +16,13 @@ function json(res, status, value) {res.end(JSON.stringify({ version: 1, ...value }));}+/** Emit a local adapter's pre-serialized state inside the unchanged API v1 envelope. */+function jsonState(res, status, state, eventLogVersion) {+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });+ const version = eventLogVersion === undefined ? '' : ',"eventLogVersion":' + JSON.stringify(eventLogVersion);+ res.end('{"version":1,"state":' + state + version + '}');+}+/** Read a bounded JSON object, draining oversize requests so a refusal reaches the caller. */async function readBody(req, { maxBytes = BODY_BYTES } = {}) {if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 20_000_000) throw new TypeError('API body limit needs a positive safe integer no larger than twenty million');@@ -144,6 +151,12 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {}if (req.method === 'GET' && route[2] === 'state') {const seen = url.searchParams.has('seen') ? seenCursor(url.searchParams.get('seen')) : null;+ if (typeof adapter.stateJson === 'function') {+ const state = await adapter.stateJson(board, who, seen);+ if (typeof state !== 'string') throw new TypeError('the local state serializer must return JSON text');+ const eventLogVersion = await adapter.eventLogVersion?.(board, who);+ return jsonState(res, 200, state, eventLogVersion);+ }const state = await adapter.state(board, who, seen);const eventLogVersion = await adapter.eventLogVersion?.(board, who);return json(res, 200, { state, ...(eventLogVersion === undefined ? {} : { eventLogVersion }) });diff --git a/src/api.js b/src/api.jsindex 8760f796..866b2f42 100644--- a/src/api.js+++ b/src/api.js@@ -111,6 +111,41 @@ function stateForRequest(state, root, seen, preparedFlow, refreshFlow, isMain) {return { ...state, ...projection };}+/** Cache JSON fragments for state fields whose values stay fixed across a cache hit. */+function prepareStateJson(state) {+ const fields = Object.entries(state).map(([key, value]) => {+ if (key === 'unseen') return { dynamic: key };+ if (key === 'proofStats') {+ const stats = Object.entries(value).filter(([name]) => name !== 'flow').map(([name, entry]) => jsonField(name, entry)).filter(Boolean);+ return { dynamic: key, stats };+ }+ return { static: jsonField(key, value) };+ });+ if (!fields.some((field) => field.dynamic === 'unseen')) fields.push({ dynamic: 'unseen' });+ return fields;+}++/** Serialize a state field through JSON.stringify, omitting values JSON would omit. */+function jsonField(key, value) {+ const encoded = JSON.stringify(value);+ return encoded === undefined ? '' : JSON.stringify(key) + ':' + encoded;+}++/** Reuse static state fragments while encoding request-specific unread and flow data. */+function serializeState(state, fields) {+ 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);+ return '"proofStats":{' + [...field.stats, flow].filter(Boolean).join(',') + '}';+ }+ return '';+ }).filter(Boolean);+ return '{' + encoded.join(',') + '}';+}+const ADDRESS = '127.0.0.1';const VERSION = 1;@@ -235,6 +270,36 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const key = Buffer.from(secret);const permittedOrigins = new Set(allowedOrigins);const stateCache = new Map();+ /** Return the current state and its cached-static JSON representation under revision checks. */+ function localState(board, seen) {+ const before = boardStateRevision(board.root, board.id, codeIsMain);+ const cached = stateCache.get(before.cacheId);+ if (before.cacheable && cached?.revision === before.revision) {+ const state = 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);+ stateCache.set(before.cacheId, cached);+ return { state, json: serializeState(state, cached.stateJsonFields) };+ }+ }++ 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);+ const stateJsonFields = prepareStateJson(state);+ if (before.cacheable && after.cacheable && before.revision === after.revision) {+ const entry = { revision: before.revision, state, preparedFlow, stateJsonFields };+ stateCache.set(before.cacheId, entry);+ while (stateCache.size > 32) stateCache.delete(stateCache.keys().next().value);+ } else {+ stateCache.delete(before.cacheId);+ }+ const projected = stateForRequest(state, board.root, seen, null, false, codeIsMain);+ return { state: projected, json: serializeState(projected, stateJsonFields) };+ }return createApiHandler({authenticate: (req) => {const url = new URL(req.url ?? '/', 'http://' + ADDRESS);@@ -248,32 +313,8 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =},boards: () => apiBoardListing(projects, codeIsMain),board: (id) => findBoard(id, projects, codeIsMain),- state: (board, who, seen) => {- 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.preparedFlow, 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 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, preparedFlow });- while (stateCache.size > 32) stateCache.delete(stateCache.keys().next().value);- } else {- stateCache.delete(before.cacheId);- }- return stateForRequest(state, board.root, seen, null, false, codeIsMain);- },+ state: (board, who, seen) => localState(board, seen).state,+ stateJson: (board, who, seen) => localState(board, seen).json,shout: (board, id) => relayLinked(board.root)? relayPresentationShout(board.root, id): withBoard(board.root, (db) => store.shoutDetails(db, id), codeIsMain),diff --git a/src/git.js b/src/git.jsindex 61f06b8e..7b375425 100644--- a/src/git.js+++ b/src/git.js@@ -273,8 +273,12 @@ function readRepoInfo(cwd, env) {export function codeIsFromMain(root = CODE_ROOT) {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;+ const info = tryGit(root, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'], { env });+ const fields = info.stdout.split('\n');+ if (info.status === 0 && fields.length === 3 && fields.every(Boolean)) {+ return realpathSync.native(fields[2]) === realpathSync.native(fields[1]);+ }+ if (info.status === 0) return repoInfo(root, { env }).isMain;let folder = resolve(root);while (true) {try {diff --git a/test/api-http.test.js b/test/api-http.test.jsindex 22f10e02..0c0946cb 100644--- a/test/api-http.test.js+++ b/test/api-http.test.js@@ -116,14 +116,17 @@ 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 hostileShout = 'cache baseline "quoted" \\ path\nline\n", "proofStats": {"flow":"forged"}';+ box.cli(box.root, 'shout', 'app', hostileShout);const first = await box.call(box.path + '/state');assert.equal(first.status, 200);assert.equal(builds, 1);+ assert.ok(first.document.state.shouts.some((shout) => shout.shout_text === hostileShout));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.ok(unchanged.document.state.shouts.some((shout) => shout.shout_text === hostileShout));assert.notEqual(unchanged.document.state.proofStats.flow.asOf, first.document.state.proofStats.flow.asOf);const latestShout = first.document.state.shouts.at(-1).shout_id;@@ -593,3 +596,38 @@ test('[A2] adapters without a committed-code capability return a versioned refusassert.equal(document.error.code, 'CODE_NOT_AVAILABLE');assert.match(document.error.next, /local view|local API/);});++test('[A2, N26] state JSON fragments preserve the API envelope and legacy adapter fallback', async (t) => {+ const state = { board: 'fixture', label: 'a ",\\"injected\\":true', unseen: null };+ const handler = createApiHandler({+ authenticate: () => ({ user: 'fixture-user' }),+ board: (id) => ({ id }),+ stateJson: (_board, _who, seen) => seen === 1 ? state : JSON.stringify(state),+ eventLogVersion: () => 'v1',+ });+ const server = createServer(handler);+ await new Promise((done) => server.listen(0, '127.0.0.1', done));+ t.after(() => new Promise((done) => { handler.close(); server.close(done); server.closeIdleConnections(); }));+ const response = await fetchFresh('http://127.0.0.1:' + server.address().port + '/api/v1/boards/fixture/state');+ const text = await response.text();+ assert.equal(response.status, 200);+ assert.deepEqual(JSON.parse(text), { version: 1, state, eventLogVersion: 'v1' });+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.equal(response.headers.get('etag'), null);+ const invalidSerializer = await fetchFresh('http://127.0.0.1:' + server.address().port + '/api/v1/boards/fixture/state?seen=1');+ assert.equal(invalidSerializer.status, 500);+ assert.equal((await invalidSerializer.json()).error.code, 'SERVICE_ERROR');++ const legacy = createApiHandler({+ authenticate: () => ({ user: 'fixture-user' }),+ board: (id) => ({ id }),+ state: () => state,+ });+ const legacyServer = createServer(legacy);+ await new Promise((done) => legacyServer.listen(0, '127.0.0.1', done));+ t.after(() => new Promise((done) => { legacy.close(); legacyServer.close(done); legacyServer.closeIdleConnections(); }));+ const legacyResponse = await fetchFresh('http://127.0.0.1:' + legacyServer.address().port + '/api/v1/boards/fixture/state');+ assert.deepEqual(await legacyResponse.json(), { version: 1, state });+ assert.equal(legacyResponse.headers.get('cache-control'), 'no-store');+ assert.equal(legacyResponse.headers.get('etag'), null);+});diff --git a/test/git-provenance.test.js b/test/git-provenance.test.jsindex bade34f6..40fc5478 100644--- a/test/git-provenance.test.js+++ b/test/git-provenance.test.js@@ -101,4 +101,5 @@ test('[A2,N26,A5,A6] code provenance is cached per request and refreshes for the});assert.equal(codeIsFromMain(alias), false, 'the next request recomputes linked-worktree provenance');+ assert.equal(codeIsFromMain(fixture), true, 'a source path outside Git retains released-source provenance');});