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): only a sent summary state is a delta base [A2,N26]
Corey Olsonc3dadcf13b03
diff --git a/docs/api.md b/docs/api.mdindex b541db90..1ba6f257 100644--- a/docs/api.md+++ b/docs/api.md@@ -216,7 +216,7 @@ The state from `pullboard serve` lists every item as a summary of what the listsEvery state names the event it reflects as `sequence`, the latest event id when it was read. `GET /api/v1/boards/:board/state?since=N` answers `{since, sequence, eventLogVersion, delta}`, where `sequence` is the new latest and `delta` brings the summary state this server sent at event N up to date: `delta.replace` holds whole fields that changed, `delta.merge` holds keyed lists by field, as `{key, set, ids?}`, with only their changed entries and, when entries came, went or moved, the full key order, and `delta.remove` names fields that went away. Items merge by `id`, `shouts` and `asked` by `shout_id`, `events` by `event_id`, `agents` by `agent_id`, `spec` and `practice` rows by `id`, and `milestones` by `name`. `unseen`, `proofStats` and the Needs-you lists, `decisions`, `holds`, `requests` and `personRequests`, always come whole. Apply a delta without recomputing anything: copy `replace` over the state, delete each `remove` field, and for each `merge` field, overlay `set` on the entries by `key` and order them by `ids`, or keep their order. `applyStateDelta(state, delta)` in `src/api-http.js` does exactly this, and the result equals a fresh snapshot at `sequence`. A delta also carries changes that wrote no event, such as a spec or doctrine edit, so its `sequence` may equal N. N alone cannot say which of the snapshots sent at N a client holds, so after such a change a later delta from the same N may repeat it; it still applies exactly.-A server keeps the fingerprints of its last 24 builds of each board, in memory only. When it cannot extend the client's snapshot, `delta` is `null` and `reset` says why, with `{code, message, next}`: `BASE_NOT_KEPT` when it never sent a snapshot at N or has forgotten it, as after a restart; `BASE_AHEAD` when N is past the board's latest event; and `FORMAT_CHANGED` when the request's optional `eventLogVersion` differs from the server's. The client then loads a fresh snapshot. `since` must be a nonnegative integer (`BAD_CURSOR` otherwise), works with `seen`, and is refused with `detail=full`; an adapter without deltas, such as the relay, returns `DELTA_NOT_AVAILABLE`.+A server keeps, in memory only, the fingerprints of the last 24 summary states it sent for each board, as snapshots or as a delta's result; a read of one item or a search sends no snapshot, so it never makes a base. When it cannot extend the client's snapshot, `delta` is `null` and `reset` says why, with `{code, message, next}`: `BASE_NOT_KEPT` when it never sent a snapshot at N or has forgotten it, as after a restart; `BASE_AHEAD` when N is past the board's latest event; and `FORMAT_CHANGED` when the request's optional `eventLogVersion` differs from the server's. The client then loads a fresh snapshot. `since` must be a nonnegative integer (`BAD_CURSOR` otherwise), works with `seen`, and is refused with `detail=full`; an adapter without deltas, such as the relay, returns `DELTA_NOT_AVAILABLE`.Core readers can call `allShouts(board)` for every stored shout, oldest first, without advancing any agent's unread cursor. Static exports can use that read to retain text for old shout addresses. Relay snapshots carry the same history only inside their authenticated, encrypted presentation; the relay service receives no plaintext shout history. Older presentations without complete history return `SHOUT_NOT_AVAILABLE`; refresh them with a current CLI.diff --git a/src/api.js b/src/api.jsindex c9ce9fd0..15d8dd01 100644--- a/src/api.js+++ b/src/api.js@@ -733,14 +733,17 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const key = Buffer.from(secret);const permittedOrigins = new Set(allowedOrigins);const stateCache = new Map();- // Each board's recent build fingerprints, oldest first, and the latest sequence a forgotten build had.+ // The fingerprints of the summary states each board's clients were sent, least recently sent+ // first, and the latest sequence a forgotten one had. A build only read for an item, a search or+ // a reset was never sent, so no client holds it and it is never a base.const deltaBases = new Map();- /** Keep a new build as a possible delta base, forgetting the oldest beyond the limit. */- function keepBase(cacheId, entry) {- const kept = deltaBases.get(cacheId) ?? { builds: [], forgottenThrough: -1 };+ /** Keep a summary state just sent, as a snapshot or as a delta's result, forgetting the oldest beyond the limit. */+ function keepSentBase(entry) {+ const kept = deltaBases.get(entry.cacheId) ?? { builds: [], forgottenThrough: -1 };+ kept.builds = kept.builds.filter((build) => build.print !== entry.print);kept.builds.push({ sequence: entry.sequence, print: entry.print });while (kept.builds.length > DELTA_BASES) kept.forgottenThrough = Math.max(kept.forgottenThrough, kept.builds.shift().sequence);- deltaBases.set(cacheId, kept);+ deltaBases.set(entry.cacheId, kept);}/*** Read the current board build through `read(entry, cached)`, reusing the cached build while every@@ -765,7 +768,6 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const history = withBoard(board.root, (db) => store.events(db), codeIsMain);const entry = snapshotEntry(before.revision, state, prepareFlowHistory(history));entry.cacheId = before.cacheId;- keepBase(before.cacheId, entry);const after = boardStateRevision(board.root, board.id, codeIsMain);if (before.cacheable && after.cacheable && before.revision === after.revision) {stateCache.set(before.cacheId, entry);@@ -777,21 +779,25 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =}/** Return item summaries or every item in full, as asked or by this server's default, and the JSON for either. */function localState(board, seen, { detail = null } = {}) {- return withSnapshot(board, (entry, cached) => {- const full = (detail ?? stateDetail) === 'full';+ const full = (detail ?? stateDetail) === 'full';+ const sent = withSnapshot(board, (entry, cached) => {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) };+ return { state, json: serializeState(state, fields), entry };});+ // Only the build actually returned is sent; a delta extends summaries, never a full state.+ if (!full) keepSentBase(sent.entry);+ return sent;}/**- * What changed in the item summaries' state since the build this server sent at event `since`.- * Builds made by this request are not bases: a server that never sent a snapshot at `since`, or- * has forgotten one, answers with a reset that names why instead of guessing.+ * What changed in the item summaries' state since the summary state this server sent at event+ * `since`. A server that never sent one at `since`, or has forgotten it, answers with a reset that+ * names why instead of guessing; a delta's result is what the client then holds, so it is kept.*/function localDelta(board, seen, { since, eventLogVersion = null }) {- return withSnapshot(board, (entry, cached) => {+ /** One build's answer: its delta from the summary states sent at `since`, or a reset naming why there is none. */+ const answerFor = (entry, cached) => {const state = stateForRequest(entry.summary, board.root, seen, entry.preparedFlow, cached, codeIsMain);const answer = { since, sequence: entry.sequence, eventLogVersion: store.EVENT_LOG_VERSION };const path = '/api/v1/boards/' + board.id + '/state';@@ -802,11 +808,13 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =}if (since > entry.sequence) return reset('BASE_AHEAD', `this board's latest event is ${entry.sequence}, before ${since}; use GET ${path} for a fresh snapshot`);const kept = deltaBases.get(entry.cacheId) ?? { builds: [], forgottenThrough: -1 };- const bases = since <= kept.forgottenThrough ? []- : kept.builds.filter((build) => build.sequence === since && (cached || build.print !== entry.print)).map((build) => build.print);+ const bases = since <= kept.forgottenThrough ? [] : kept.builds.filter((build) => build.sequence === since).map((build) => build.print);if (!bases.length) return reset('BASE_NOT_KEPT', `this server keeps no snapshot it sent at event ${since}; use GET ${path} for a fresh snapshot`);return { ...answer, delta: stateDelta(bases, entry.print, state) };- });+ };+ const sent = withSnapshot(board, (entry, cached) => ({ entry, answer: answerFor(entry, cached) }));+ if (sent.answer.delta) keepSentBase(sent.entry);+ return sent.answer;}/** One item's detail from the current build, or null when the board has no such item. */function localItem(board, id) {diff --git a/test/api-http.test.js b/test/api-http.test.jsindex 9696cb72..14619c81 100644--- a/test/api-http.test.js+++ b/test/api-http.test.js@@ -487,13 +487,30 @@ test('[A2, N26] a delta brings a snapshot up to date', async (t) => {const format = await box.call(box.path + '/state?since=' + held.sequence + '&eventLogVersion=0');assert.equal(format.document.delta, null);assert.equal(format.document.reset.code, 'FORMAT_CHANGED', 'a snapshot in another event-log format is never extended');+ // A restarted server that has only read an item, or searched, never sent a snapshot: it cannot+ // extend the held one, even when a change with no event leaves the sequence where it was.+ writeFileSync(join(box.root, 'DOCTRINE.md'), '# Local rules\n\n## Team Rules\n\n- LOCAL1 [approved, must] A restarted server knows only what it sent. | gate: true\n');const restarted = await serveApi({ runCommand: main, projects: () => [{ root: box.root, name: 'HTTP fixture' }] });t.after(() => restarted.close());const restartedUrl = new URL(restarted.url);- const unknown = await fetchFresh(restartedUrl.origin + box.path + '/state?since=' + held.sequence, { headers: { 'x-pullboard-key': restartedUrl.searchParams.get('k') } });- const unknownDocument = await unknown.json();- assert.equal(unknownDocument.delta, null);+ /** Read through the restarted server with its own key. */+ const restartedRead = async (path) => (await fetchFresh(restartedUrl.origin + box.path + path, { headers: { 'x-pullboard-key': restartedUrl.searchParams.get('k') } })).json();+ assert.equal((await restartedRead('/items/' + item)).item.id, item);+ assert.deepEqual((await restartedRead('/items?q=delta')).ids, [item]);+ const unknownDocument = await restartedRead('/state?since=' + held.sequence);+ assert.equal(unknownDocument.delta, null, JSON.stringify(unknownDocument.delta));assert.equal(unknownDocument.reset.code, 'BASE_NOT_KEPT', 'a server that never sent that snapshot says so instead of guessing');+ const resent = (await restartedRead('/state')).state;+ assert.equal(resent.sequence, held.sequence, 'the doctrine edit wrote no event');+ assert.notDeepEqual(resent.practice, held.practice, 'so the held snapshot really is stale');+ assert.equal((await restartedRead('/state?since=' + held.sequence)).delta === null, false, 'once it sends a snapshot at that sequence, it can extend it');+ t.mock.timers.enable({ apis: ['Date'], now: Date.now() });+ try {+ const extended = applyStateDelta(resent, (await restartedRead('/state?since=' + resent.sequence)).delta);+ assert.deepEqual(extended, (await restartedRead('/state')).state, 'and its delta still brings that snapshot up to date');+ } finally {+ t.mock.timers.reset();+ }for (const [query, code] of [['since=', 'BAD_CURSOR'], ['since=-1', 'BAD_CURSOR'], ['since=1.5', 'BAD_CURSOR'], ['since=1&detail=full', 'BAD_REQUEST']]) {const refused = await box.call(box.path + '/state?' + query);assert.equal(refused.status, 400, query);