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): a delta brings a held snapshot up to date [A2,N26]

Corey Olson2ac7502e2ea4
diff --git a/docs/api.md b/docs/api.md
index 63c96eba..b541db90 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -199,6 +199,7 @@ The server checks any Origin against its own address and grants no CORS permissi
| `GET /api/v1/boards` | Registered boards with their project details and ids |
| `GET /api/v1/boards/:board/state?seen=N` | The board state, listing item summaries, including open coordinator requests and the unseen shout count since N |
| `GET /api/v1/boards/:board/state?detail=full` | The same state with every item in full, which static view exports read |
+| `GET /api/v1/boards/:board/state?since=N` | What changed in the summary state since the snapshot this server sent at event N, and the new latest sequence |
| `GET /api/v1/boards/:board/items/:id` | One item's full detail: the fields its summary leaves out |
| `GET /api/v1/boards/:board/items?q=text` | The ids of the items whose id, title, lane, spec ids or criterion contain the text, ignoring case |
| `GET /api/v1/boards/:board/shouts/:id` | One shout from any point in the board's history, including its decision and answer fields |
@@ -213,6 +214,10 @@ The state from `pullboard serve` lists every item as a summary of what the lists
`GET /api/v1/boards/:board/items/:id` returns `{item}`: the item's `id` and every field its summary leaves out, which are `owner`, `reviewer`, `reviewUntil`, `verifiedBy`, `criterion`, `brief`, `commit`, `merged`, `history`, `check`, `checkBaseline` when recorded, `verdicts`, `thread`, and the latest `verdict` in full. Laid over its summary, the detail is the item exactly as the full state carries it. An unknown id returns `NO_ITEM` with HTTP 404; a malformed id is refused with HTTP 400. `state?detail=full` returns every item in full, summary fields included, and `detail=summary` returns summaries; any other value is refused with `BAD_REQUEST`. Without `detail`, a server answers with its own default, `stateDetail: "summary"` or `"full"`: `serveApi`, which `pullboard serve` runs, defaults to summaries, and `createLocalApiHandler`, which a page's own server builds, defaults to full items until that page reads summaries. `GET /api/v1/boards/:board/items?q=text` returns `{ids}`, in state order, for the items whose `#id`, title, lane, spec ids or criterion contain the trimmed text, ignoring case, as the view's search matches; empty text matches every item. An adapter without these reads, such as the relay, whose state carries every item in full, returns `ITEM_NOT_AVAILABLE`.
+Every 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`.
+
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.
The local board state and events responses include `eventLogVersion`, which identifies the persisted event-record format separately from the HTTP envelope's `version`. Static view exports keep this field in both state.json and events.json so a reader can refuse a format newer than it understands. Sealed relay events do not use this local board format marker.
@@ -224,6 +229,7 @@ The coordinator maintains the roadmap with `milestone add <name> [--note ...] [-
| --- | --- |
| `boards` | `version:number`, `boards:array` |
| `state` | `version:number`, `state:object` |
+| `delta` | `version:number`, `since:number`, `sequence:number`, `delta:object\|null` |
| `shout` | `version:number`, `shout:object` |
| `item` | `version:number`, `item:object` |
| `items` | `version:number`, `ids:array` |
diff --git a/docs/api.test.js b/docs/api.test.js
index 4a018925..1eafde75 100644
--- a/docs/api.test.js
+++ b/docs/api.test.js
@@ -46,6 +46,8 @@ test('[A2] API guide documents the local HTTP response catalog', () => {
assert.match(guide, /`warnings` with its registry display fields and a versioned refusal/);
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/state\?seen=N`/);
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/state\?detail=full`/);
+ assert.match(guide, /`GET \/api\/v1\/boards\/:board\/state\?since=N`/);
+ assert.match(guide, /`BASE_NOT_KEPT`/);
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/items\/:id`/);
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/items\?q=text`/);
assert.match(guide, /`ITEM_NOT_AVAILABLE`/);
diff --git a/src/api-http.js b/src/api-http.js
index bbe3c3d7..6f65fd7f 100644
--- a/src/api-http.js
+++ b/src/api-http.js
@@ -53,6 +53,12 @@ function seenCursor(value) {
return eventCursor(value);
}
+/** A delta's base is the sequence of a state the client holds; unlike an omitted events cursor, blank is invalid. */
+function sinceCursor(value) {
+ if (value === '') throw new Refused('BAD_CURSOR', "since needs a nonnegative integer; use the sequence of the state you hold");
+ return eventCursor(value);
+}
+
/** Read a state request's detail choice: item summaries, every item in full, or null for the server's default (A2). */
function stateDetail(value) {
if (value === null) return null;
@@ -182,6 +188,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;
const options = { detail: stateDetail(url.searchParams.get('detail')) };
+ if (url.searchParams.has('since')) {
+ const since = sinceCursor(url.searchParams.get('since'));
+ if (options.detail === 'full') throw new Refused('BAD_REQUEST', 'a delta brings item summaries up to date; use since=N without detail=full');
+ if (typeof adapter.delta !== 'function') throw new Refused('DELTA_NOT_AVAILABLE', 'this API adapter does not answer since=N; use its board state');
+ return json(res, 200, await adapter.delta(board, who, seen, { since, eventLogVersion: url.searchParams.get('eventLogVersion') }));
+ }
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');
@@ -235,6 +247,26 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
}
+/**
+ * Apply a state delta (GET .../state?since=N) to the state it extends, giving the state a fresh
+ * snapshot would. It recomputes nothing: whole fields replace, and keyed lists take their changed
+ * entries and, when given, their new key order (A2).
+ *
+ * @param {any} state
+ * @param {{ replace: object, merge: Record<string, { key: string, set: object[], ids?: (string|number)[] }>, remove?: string[] }} delta
+ * @returns {any}
+ */
+export function applyStateDelta(state, delta) {
+ const next = { ...state, ...delta.replace };
+ for (const field of delta.remove ?? []) delete next[field];
+ for (const [field, { key, set, ids }] of Object.entries(delta.merge)) {
+ const entries = new Map((state[field] ?? []).map((entry) => [entry[key], entry]));
+ for (const entry of set) entries.set(entry[key], entry);
+ next[field] = (ids ?? (state[field] ?? []).map((entry) => entry[key])).map((id) => entries.get(id));
+ }
+ return next;
+}
+
/** Choose the same HTTP refusal class for local and sealed relay adapters. */
export function apiStatus(error) {
return { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, BASELINE_EXISTS: 412, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);
diff --git a/src/api.js b/src/api.js
index a838cc7b..f0fe4805 100644
--- a/src/api.js
+++ b/src/api.js
@@ -94,7 +94,7 @@ function boardStateRevision(root, id, isMain) {
externalRoadmap: local.externalMilestones,
eventLogVersion: store.EVENT_LOG_VERSION,
});
- return { cacheId: info.commonDir + '\0' + id, revision, milestones: local.externalMilestones, cacheable: true };
+ return { cacheId: info.commonDir + '\0' + id, revision, event: local.event, milestones: local.externalMilestones, cacheable: true };
}
/** Cheap file identity for an event-stream poll; content is read only after this marker changes. */
@@ -487,11 +487,75 @@ function searchText(item) {
return ('#' + item.id + ' ' + item.title + ' ' + item.lane + ' ' + item.specs.join(' ') + ' ' + (item.criterion || '')).toLowerCase();
}
-/** One cached board build: the full state, its item summaries and the lookups that serve them. */
+/** One cached board build: the full state, its item summaries, its delta fingerprint and the lookups that serve them. */
function snapshotEntry(revision, state, preparedFlow) {
const summary = { ...state, items: state.items.map(itemSummary) };
- return { revision, state, summary, preparedFlow, summaryFields: prepareStateJson(summary), stateJsonFields: null,
- items: new Map(state.items.map((item) => [item.id, item])), searchTexts: null };
+ return { revision, sequence: state.sequence, state, summary, preparedFlow, summaryFields: prepareStateJson(summary), stateJsonFields: null,
+ print: fingerprint(summary), items: new Map(state.items.map((item) => [item.id, item])), searchTexts: null };
+}
+
+/** State fields every delta carries whole: this request's unread count and flow, and the small Needs-you lists. */
+const DELTA_WHOLE = new Set(['unseen', 'proofStats', 'decisions', 'holds', 'requests', 'personRequests']);
+/** The state lists a delta merges entry by entry, and the field that names each entry. */
+const DELTA_KEYS = Object.freeze({ items: 'id', shouts: 'shout_id', asked: 'shout_id', events: 'event_id', agents: 'agent_id', spec: 'id', practice: 'id', milestones: 'name' });
+/** How many recent builds of each board a server keeps as possible delta bases. */
+const DELTA_BASES = 24;
+
+/** A digest of one value's JSON, which is what a client holds of it. */
+function jsonDigest(value) {
+ return createHash('sha256').update(JSON.stringify(value) ?? 'undefined').digest('base64');
+}
+
+/**
+ * Fingerprint a summary build without keeping it: a digest of each field, and for each keyed list
+ * its entry order and each entry's digest. A list whose keys repeat or are missing is a whole field.
+ */
+function fingerprint(state) {
+ const fields = new Map();
+ const lists = new Map();
+ for (const [field, value] of Object.entries(state)) {
+ if (DELTA_WHOLE.has(field)) continue;
+ const key = Object.hasOwn(DELTA_KEYS, field) ? DELTA_KEYS[field] : null;
+ const ids = key && Array.isArray(value) ? value.map((entry) => entry?.[key]) : null;
+ if (ids && ids.every((id) => typeof id === 'number' || typeof id === 'string') && new Set(ids).size === ids.length) {
+ lists.set(field, { key, ids, digests: new Map(value.map((entry) => [entry[key], jsonDigest(entry)])) });
+ } else fields.set(field, jsonDigest(value));
+ }
+ return { fields, lists };
+}
+
+/** Whether two key lists name the same entries in the same order. */
+function sameIds(left, right) {
+ return left.length === right.length && left.every((id, at) => id === right[at]);
+}
+
+/**
+ * What changed from each of these bases to the current build. Changed values travel whole, so the
+ * delta applied to any one of the bases gives the current state; the request's own fields and the
+ * Needs-you lists always come whole. A keyed list sends only its changed entries, and its full key
+ * order when entries were added, removed or moved.
+ *
+ * @param {{ fields: Map<string, string>, lists: Map<string, any> }[]} bases
+ * @param {{ fields: Map<string, string>, lists: Map<string, any> }} current
+ * @param {any} state The current summary state, projected for this request.
+ * @returns {{ replace: object, merge: object, remove?: string[] }}
+ */
+function stateDelta(bases, current, state) {
+ const replace = {};
+ const merge = {};
+ for (const [field, value] of Object.entries(state)) {
+ if (DELTA_WHOLE.has(field)) { replace[field] = value; continue; }
+ const list = current.lists.get(field);
+ if (list && bases.every((base) => base.lists.get(field)?.key === list.key)) {
+ const set = value.filter((entry) => bases.some((base) => base.lists.get(field).digests.get(entry[list.key]) !== list.digests.get(entry[list.key])));
+ const moved = bases.some((base) => !sameIds(base.lists.get(field).ids, list.ids));
+ if (set.length || moved) merge[field] = { key: list.key, set, ...(moved ? { ids: list.ids } : {}) };
+ } else if (list || bases.some((base) => base.fields.get(field) !== current.fields.get(field))) {
+ replace[field] = value;
+ }
+ }
+ const remove = [...new Set(bases.flatMap((base) => [...base.fields.keys(), ...base.lists.keys()]))].filter((field) => !Object.hasOwn(state, field));
+ return { replace, merge, ...(remove.length ? { remove } : {}) };
}
/** Add the request-specific unread count without mutating the reusable snapshot. */
@@ -669,6 +733,15 @@ 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.
+ 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 };
+ 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);
+ }
/**
* Read the current board build through `read(entry, cached)`, reusing the cached build while every
* input revision holds before and after the read, and building it again when one moved.
@@ -687,9 +760,12 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
}
onStateBuild?.({ board: board.id });
- const state = buildLocalBoardState(board, codeIsMain, before.milestones);
+ // The build names the event it was read at, so a client can ask for what changed after it.
+ const state = { ...buildLocalBoardState(board, codeIsMain, before.milestones), sequence: before.event };
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);
@@ -709,6 +785,29 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
return { state, json: serializeState(state, fields) };
});
}
+ /**
+ * 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.
+ */
+ function localDelta(board, seen, { since, eventLogVersion = null }) {
+ return withSnapshot(board, (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';
+ /** Tell the client to load a fresh snapshot, and why. */
+ const reset = (code, message) => ({ ...answer, delta: null, reset: refusalDocument(new Refused(code, message)).error });
+ if (eventLogVersion !== null && eventLogVersion !== String(store.EVENT_LOG_VERSION)) {
+ return reset('FORMAT_CHANGED', `this server writes event-log format ${store.EVENT_LOG_VERSION}, not ${eventLogVersion}; use GET ${path} for a fresh snapshot`);
+ }
+ 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);
+ 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) };
+ });
+ }
/** One item's detail from the current build, or null when the board has no such item. */
function localItem(board, id) {
return withSnapshot(board, (entry) => {
@@ -740,6 +839,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
state: (board, who, seen, options) => localState(board, seen, options).state,
stateJson: (board, who, seen, options) => localState(board, seen, options).json,
watchRevision: (board) => watchLocalStateRevision(board),
+ delta: (board, who, seen, options) => localDelta(board, seen, options),
item: (board, id) => localItem(board, id),
search: (board, text) => localSearch(board, text),
shout: (board, id) => relayLinked(board.root)
diff --git a/src/json.js b/src/json.js
index fa713ba8..cb556f2c 100644
--- a/src/json.js
+++ b/src/json.js
@@ -89,6 +89,7 @@ export const JSON_SHAPES = {
http: {
boards: shape({ boards: 'array' }),
state: shape({ state: 'object' }),
+ delta: shape({ since: 'number', sequence: 'number', delta: 'object|null' }),
shout: shape({ shout: 'object' }),
item: shape({ item: 'object' }),
items: shape({ ids: 'array' }),
diff --git a/test/api-http.test.js b/test/api-http.test.js
index 803f8d2e..9696cb72 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -11,7 +11,7 @@ import { test } from 'node:test';
import { createLocalApiHandler, serveApi } from '../src/api.js';
import { serveView } from '../src/serve.js';
import { main } from '../src/cli.js';
-import { createApiHandler } from '../src/api-http.js';
+import { applyStateDelta, createApiHandler } from '../src/api-http.js';
import { registryFile, registerProject } from '../src/projects.js';
import { Refused } from '../src/refused.js';
import * as store from '../src/board.js';
@@ -395,6 +395,112 @@ test("[A2, N26] a sent-back item's summary carries its reject note's first line"
assert.deepEqual({ ...reworked, ...(await box.call(box.path + '/items/' + rejected)).document.item }, full, 'the detail still completes the summary');
});
+test('[A2, N26] a delta brings a snapshot up to date', async (t) => {
+ const box = await httpBox(t);
+ writeFileSync(join(box.root, 'SPEC.md'), '# HTTP fixture\n\n## Goals\n- G1 [approved, must] Keep the board. | gate: true\n- G2 [pending, must] Keep each delta small. | gate: true\n');
+ runFixtureGit(['commit', '-qam', 'docs: ask whether deltas stay small'], { cwd: box.root, env: box.env, stdio: 'pipe' });
+ const builder = box.cli(box.root, 'worktree', 'app', '--model', 'fixture-builder');
+ const verifier = box.cli(box.root, 'worktree', 'app', '--model', 'fixture-verifier');
+ /** Make one real board move through HTTP and return its result. */
+ async function move(body) {
+ const moved = await box.call(box.path + '/moves', body);
+ assert.equal(moved.status, 200, JSON.stringify(moved.document));
+ return moved.document.result;
+ }
+ const item = (await move({ verb: 'add', args: { lane: 'app', title: 'Delta item', criterion: 'moves through review', specs: 'G1' } })).item.item_id;
+ const waiting = (await move({ verb: 'add', args: { lane: 'app', title: 'Waiting item', criterion: 'stays open', specs: 'G1', after: String(item) } })).item.item_id;
+
+ const first = (await box.call(box.path + '/state')).document.state;
+ assert.ok(Number.isSafeInteger(first.sequence), 'a snapshot names the event it reflects');
+ let held = first;
+ /**
+ * Ask for what changed since the held snapshot, apply it, and compare it with a fresh snapshot
+ * read at the same instant, so the flow observation in both is the same.
+ */
+ async function catchUp(label) {
+ t.mock.timers.enable({ apis: ['Date'], now: Date.now() });
+ try {
+ const answer = await box.call(box.path + '/state?since=' + held.sequence);
+ const fresh = await box.call(box.path + '/state');
+ assert.equal(answer.status, 200, label);
+ assert.ok(answer.document.delta, `${label}: ${JSON.stringify(answer.document.reset)}`);
+ assert.equal(answer.document.since, held.sequence, label);
+ assert.equal(answer.document.sequence, fresh.document.state.sequence, `${label}: the delta names the new latest sequence`);
+ assert.equal(answer.document.eventLogVersion, fresh.document.eventLogVersion, label);
+ const updated = applyStateDelta(held, answer.document.delta);
+ assert.deepEqual(updated, fresh.document.state, `${label}: the delta brings the snapshot up to date`);
+ assert.ok(JSON.stringify(answer.document).length < JSON.stringify(fresh.document).length, `${label}: the delta is smaller than a snapshot`);
+ held = updated;
+ return answer.document.delta;
+ } finally {
+ t.mock.timers.reset();
+ }
+ }
+ const changed = (delta, field) => (delta.merge[field]?.set ?? []).map((entry) => entry[delta.merge[field].key]);
+
+ await move({ verb: 'claim', item, agent: builder.agent });
+ const claimed = await catchUp('claim');
+ assert.deepEqual(changed(claimed, 'items'), [item], 'only the claimed item travels');
+ assert.equal(claimed.merge.items.set[0].claim.by, builder.agent);
+ assert.equal(Object.hasOwn(claimed.merge.items, 'ids'), false, 'no item came or went, so the order is not sent');
+ const still = await catchUp('nothing changed');
+ assert.deepEqual(still.merge, {}, 'an unchanged board merges nothing');
+ assert.deepEqual(Object.keys(still.replace).sort(), ['decisions', 'holds', 'personRequests', 'proofStats', 'requests', 'unseen'],
+ 'only the always-whole fields come');
+
+ await move({ verb: 'submit', item, agent: builder.agent });
+ assert.equal((await catchUp('submit')).merge.items.set[0].status, 'submitted');
+
+ await move({ verb: 'next', agent: verifier.agent, args: { verify: true } });
+ await move({ verb: 'verify', item, agent: verifier.agent, args: { decision: 'accept', reason: 'CRITERION_MET', note: 'read every delta' } });
+ const verdict = await catchUp('verdict');
+ assert.deepEqual(changed(verdict, 'items').sort((a, b) => a - b), [item, waiting], 'the accept also unblocks the item waiting on it');
+
+ const asked = await move({ verb: 'shout', agent: builder.agent, args: { to: 'coordinator', text: 'May the delta skip the order?', decision: true } });
+ const shouted = await catchUp('shout');
+ assert.ok(changed(shouted, 'shouts').includes(asked.id), 'the new shout travels');
+ assert.ok(changed(shouted, 'asked').includes(asked.id), 'and so does the open question');
+ const answered = await move({ verb: 'answer', item: asked.id, args: { text: 'Only when nothing moved.' } });
+ const answer = await catchUp('answer');
+ assert.ok(changed(answer, 'shouts').includes(answered.id), 'the answer travels');
+ assert.ok(answer.merge.asked.ids.every((id) => id !== asked.id), 'the answered question leaves the open list');
+
+ box.cli(box.root, 'spec', 'approve', 'G2');
+ const decided = await catchUp('spec decision');
+ assert.deepEqual(changed(decided, 'spec'), ['G2'], 'only the decided spec row travels');
+
+ writeFileSync(join(box.root, 'DOCTRINE.md'), '# Local rules\n\n## Team Rules\n\n- LOCAL1 [approved, must] Keep each delta exact. | gate: true\n');
+ const unmoved = held.sequence;
+ const edited = await catchUp('a doctrine edit without a move');
+ assert.equal(held.sequence, unmoved, 'no event, so the sequence holds');
+ assert.ok(changed(edited, 'practice').includes('LOCAL1'), 'the doctrine row travels anyway');
+ await catchUp('again at the same sequence, which may repeat the edit but still applies exactly');
+
+ held = first;
+ await catchUp('every move at once, from the first snapshot');
+
+ const ahead = await box.call(box.path + '/state?since=' + (held.sequence + 1000));
+ assert.equal(ahead.status, 200);
+ assert.equal(ahead.document.delta, null);
+ assert.equal(ahead.document.reset.code, 'BASE_AHEAD');
+ assert.match(ahead.document.reset.next, /\/state/);
+ 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');
+ 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);
+ assert.equal(unknownDocument.reset.code, 'BASE_NOT_KEPT', 'a server that never sent that snapshot says so instead of guessing');
+ 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);
+ assert.equal(refused.document.error.code, code, query);
+ }
+});
+
test('[A2, N26] local milestone item status refreshes after an item event', async (t) => {
let builds = 0;
const box = await httpBox(t, { onStateBuild: () => { builds += 1; } });
@@ -989,6 +1095,9 @@ test('[A2] adapters without a committed-code capability return a versioned refus
assert.equal(document.version, 1);
assert.equal(document.error.code, 'CODE_NOT_AVAILABLE');
assert.match(document.error.next, /local view|local API/);
+ const noDelta = await fetchFresh('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/state?since=1');
+ assert.equal(noDelta.status, 400);
+ assert.equal((await noDelta.json()).error.code, 'DELTA_NOT_AVAILABLE', 'an adapter whose state carries full items offers no deltas');
for (const path of ['/items/1', '/items?q=anything']) {
const unavailable = await fetchFresh('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + path);
assert.equal(unavailable.status, 400);