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): the board state sends item summaries [A2,N26]

Corey Olson1d52b953584d
diff --git a/docs/api.md b/docs/api.md
index dc73067c..1354fa94 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -12,7 +12,7 @@ A successful command returns the fields listed below. `version` is always the nu
When `add` or `edit` supplies a new nonempty check, it records the item before measuring that check in a background temporary checkout of the captured `main` commit. Use `--wait` to wait for the measurement before returning, or `args.wait: true` for an HTTP add/edit move. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, request?, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `pending`, `green`, `red`, or `unavailable`. A background request carries an opaque `request` identity; an older completion cannot overwrite a newly edited or cleared check.
-The board-state API's item projection includes `check` and, when recorded, `checkBaseline` with the same observation fields. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.
+An item's HTTP detail, and each item in the full board state, include `check` and, when recorded, `checkBaseline` with the same observation fields. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.
`pullboard stats [--since <date>] --json` returns `{version: 1, stats: {...}}` from the append-only event log. `submissions` and `rejections` count moves, including repeated attempts; `rejectionShare` is rejections divided by submissions (zero when the window has no submissions). `merged` counts distinct items with a merge move; `mergedWithoutAccept` counts those whose merge lacks an earlier acceptance of the latest submitted commit. That audit uses earlier history even when the acceptance falls before the selected window. Current item and verdict rows do not replace event evidence.
@@ -144,7 +144,7 @@ Use `--ref src/file.js:12-30@<full-40-character-sha>` to bind a fact to a commit
A correction is a new fact with `--supersedes <fact-id>`. It requires the live holder or coordinator even when its kind is an observation. The earlier fact remains visible; supersession must name a fact on the same item. A missing or cross-item identity is refused with `NO_FACT`. Unsupported kinds receive `BAD_FACT_KIND`, empty text receives `EMPTY_FACT`, and unauthorized judgements or corrections receive `FACT_JUDGEMENT`.
-`show --json` retains its existing item fields and verdicts and adds `thread`. The HTTP state item's additive `thread` field has the same array. Entries are oldest first, ordered by the append-only event sequence. A fact entry is `{type: "fact", ...fact}`. A move entry is `{type: "move", eventId, kind, by, at, detail}`, with `detail` holding the original move's structured event detail. Text `show` prints these moves and facts as one timeline, including full references and both sides of a correction. Ordinary verdict summaries and `--history` remain available.
+`show --json` retains its existing item fields and verdicts and adds `thread`. The HTTP item detail's `thread` field, also on each item in the full board state, has the same array. Entries are oldest first, ordered by the append-only event sequence. A fact entry is `{type: "fact", ...fact}`. A move entry is `{type: "move", eventId, kind, by, at, detail}`, with `detail` holding the original move's structured event detail. Text `show` prints these moves and facts as one timeline, including full references and both sides of a correction. Ordinary verdict summaries and `--history` remain available.
The HTTP move is `{verb: "fact", item: 12, agent: "web-1", args: {kind: "measurement", text: "The check takes 8 seconds", ref: "src/file.js:12-30@<full-sha>"}}`. Omit `agent` to act as the coordinator; `args.supersedes` supplies a correction's earlier fact identity. The response carries the committed `fact` event and the CLI result. The event-log format stays at version 1 because facts use its existing immutable event rows; exports and imports preserve those rows. The sealed move engine advances to version 3 for this release so older engines refuse the new operation before replay.
@@ -197,7 +197,10 @@ The server checks any Origin against its own address and grants no CORS permissi
| Method and path | Result |
| --- | --- |
| `GET /api/v1/boards` | Registered boards with their project details and ids |
-| `GET /api/v1/boards/:board/state?seen=N` | The view's board state, including open coordinator requests and the unseen shout count since N |
+| `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/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 |
| `GET /api/v1/boards/:board/code?ref=path:lines@commit&before=...` | A bounded preview of committed file lines from that registered board |
| `GET /api/v1/boards/:board/events?after=N` | Events after sequence N, in order, and their event-log format version |
@@ -206,6 +209,10 @@ The server checks any Origin against its own address and grants no CORS permissi
The boards response keeps `boards` and may include `warnings` for registered entries that could not be opened. State `seen` must be a nonnegative safe integer; omitting it retains the `unseen: null` result. State continues to include only the newest 40 shouts. Use `GET /api/v1/boards/:board/shouts/:id` to resolve an older address; its `{ shout }` result contains the complete stored shout row, including sender, recipient, text, timestamp, decision flag and reply relationship. Decision shouts also include `decision_state` (`open` or `answered`) and `decision_answer` (the reply row or `null`); other shouts use `null` for both fields. A missing id returns `NO_SHOUT` with HTTP 404; malformed ids are refused with HTTP 400. Code previews read only a registered repo's committed tree, use a plain commit SHA and at most 60 lines, and never read the working tree. The shared router lets adapters omit the optional code capability; such adapters return the versioned `CODE_NOT_AVAILABLE` refusal.
+The state from `pullboard serve` lists every item as a summary of what the lists and the roadmap read: `id`, `title`, `lane`, `status`, `route`, `milestone`, `specs`, `claim`, `builtBy`, `blockedBy`, `updatedAt`, `stage`, `since`, `counts` and `verdict`. `milestone` names the first roadmap milestone that lists the item, or is `null`. `claim` is the live lease on the item, `{by, until}`: its builder's while it is claimed, or its reviewer's while a submitted item is reserved for review; otherwise it is `null`. `stage` is the item's status, except `accepted` for a verified item and `merged` once a merge is recorded. `since` is when the item entered that stage: edits, review reservations and renewals do not restart it, and a lapsed claim's stage starts at its recorded lease deadline. `counts` has the item's number of `verdicts` and `facts`. `verdict` keeps only the latest verdict's `decision` and `reason`, or is `null`. The state also has `moveCounts`, the board's lifecycle moves keyed `from>to:verb`, as the view's lifecycle drawing counts them.
+
+`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`.
+
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.
@@ -218,6 +225,8 @@ The coordinator maintains the roadmap with `milestone add <name> [--note ...] [-
| `boards` | `version:number`, `boards:array` |
| `state` | `version:number`, `state:object` |
| `shout` | `version:number`, `shout:object` |
+| `item` | `version:number`, `item:object` |
+| `items` | `version:number`, `ids:array` |
| `events` | `version:number`, `events:array` |
| `move` | `version:number`, `event:object`, `result:object` |
| `request` | `version:number`, `event:object`, `result:object` |
diff --git a/docs/api.test.js b/docs/api.test.js
index dd4c7c3d..32654801 100644
--- a/docs/api.test.js
+++ b/docs/api.test.js
@@ -45,6 +45,10 @@ test('[A2] API guide documents the local HTTP response catalog', () => {
assert.deepEqual(documented, source);
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\/items\/:id`/);
+ assert.match(guide, /`GET \/api\/v1\/boards\/:board\/items\?q=text`/);
+ assert.match(guide, /`ITEM_NOT_AVAILABLE`/);
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/code\?ref=path:lines@commit&before=\.\.\.`/);
assert.match(guide, /`CODE_NOT_AVAILABLE` refusal/);
});
diff --git a/src/api-http.js b/src/api-http.js
index 19c3d63e..2553affe 100644
--- a/src/api-http.js
+++ b/src/api-http.js
@@ -53,6 +53,13 @@ function seenCursor(value) {
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;
+ if (value === 'full' || value === 'summary') return value;
+ throw new Refused('BAD_REQUEST', 'state detail is full or summary; use detail=full for every item in full, or detail=summary for item summaries');
+}
+
/** Create the common API router; an adapter controls authorization and board storage. */
export function createApiHandler(adapter, { pollMs = 200 } = {}) {
if (!Number.isInteger(pollMs) || pollMs < 10 || pollMs > 60_000) throw new Refused('API_POLL', 'use a poll interval from 10 to 60000 milliseconds');
@@ -119,16 +126,30 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
try {
let url;
try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); } catch { throw new Refused('BAD_REQUEST', 'use a valid path under /api/v1/boards'); }
- const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests|code|tokens)$/.exec(url.pathname);
+ const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests|code|tokens|items)$/.exec(url.pathname);
const shoutRoute = /^\/api\/v1\/boards\/([^/]+)\/shouts\/([^/]+)$/.exec(url.pathname);
- const boardId = route?.[1] ?? shoutRoute?.[1] ?? null;
+ const itemRoute = /^\/api\/v1\/boards\/([^/]+)\/items\/([^/]+)$/.exec(url.pathname);
+ const boardId = route?.[1] ?? shoutRoute?.[1] ?? itemRoute?.[1] ?? null;
const who = await adapter.authenticate(req, { board: boardId, write: req.method === 'POST' });
if (req.method === 'GET' && url.pathname === '/api/v1/boards') {
const listing = await adapter.boards(who);
return json(res, 200, Array.isArray(listing) ? { boards: listing } : listing);
}
- if (!route && !shoutRoute) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, shout, code, events, moves or requests path')));
+ if (!route && !shoutRoute && !itemRoute) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, item, shout, code, events, moves or requests path')));
const board = await adapter.board(boardId, who);
+ if (itemRoute) {
+ if (req.method !== 'GET') throw new Refused('BAD_REQUEST', 'read an item with GET; use a board move to change it');
+ const rawId = itemRoute[2];
+ if (!/^[1-9]\d*$/.test(rawId) || !Number.isSafeInteger(Number(rawId))) throw new Refused('BAD_REQUEST', 'item needs a positive integer id; use an id from the board state');
+ if (typeof adapter.item !== 'function') throw new Refused('ITEM_NOT_AVAILABLE', "this API adapter does not provide item detail reads; use its board state, which carries each item's full detail");
+ const item = await adapter.item(board, Number(rawId), who);
+ if (!item) return json(res, 404, refusal(new Refused('NO_ITEM', `no item #${rawId} on this board; use an id from the board state`)));
+ return json(res, 200, { item });
+ }
+ if (req.method === 'GET' && route?.[2] === 'items') {
+ if (typeof adapter.search !== 'function') throw new Refused('ITEM_NOT_AVAILABLE', "this API adapter does not provide item search; use its board state, which carries each item's full detail");
+ return json(res, 200, { ids: await adapter.search(board, url.searchParams.get('q') ?? '', who) });
+ }
if (req.method === 'GET' && shoutRoute) {
const rawId = shoutRoute[2];
if (!/^[1-9]\d*$/.test(rawId) || !Number.isSafeInteger(Number(rawId))) throw new Refused('BAD_REQUEST', 'shout needs a positive integer id; use the id from the event or recent state');
@@ -151,13 +172,14 @@ 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 (typeof adapter.stateJson === 'function') {
- const state = await adapter.stateJson(board, who, seen);
+ 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 eventLogVersion = await adapter.eventLogVersion?.(board, who);
return jsonState(res, 200, state, eventLogVersion);
}
- const state = await adapter.state(board, who, seen);
+ const state = await adapter.state(board, who, seen, options);
const eventLogVersion = await adapter.eventLogVersion?.(board, who);
return json(res, 200, { state, ...(eventLogVersion === undefined ? {} : { eventLogVersion }) });
}
diff --git a/src/api.js b/src/api.js
index 5f97ec57..1a311490 100644
--- a/src/api.js
+++ b/src/api.js
@@ -10,6 +10,7 @@ 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 { MACHINE } from './machine.js';
import { listApiProjects } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
import { proofStats } from './stats.js';
@@ -88,6 +89,7 @@ function buildLocalBoardState(board, codeIsMain, milestones) {
}])),
proofStats: proofStats(db),
threads: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, store.itemThread(db, item.item_id)])),
+ leases: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, item.item_lease_until ?? null])),
}), codeIsMain);
state.proofStats = projectData.proofStats;
state.requests = projectData.requests;
@@ -96,7 +98,117 @@ function buildLocalBoardState(board, codeIsMain, 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;
+ return withListFields(state, projectData.leases);
+}
+
+/** What a board-state item summary keeps: what the lists and the roadmap read (A2, N26). */
+const SUMMARY_FIELDS = Object.freeze(['id', 'title', 'lane', 'status', 'route', 'milestone', 'specs', 'claim', 'builtBy',
+ 'blockedBy', 'updatedAt', 'stage', 'since', 'counts', 'verdict']);
+const SUMMARY_KEYS = new Set(SUMMARY_FIELDS);
+const CLOCK_MOVES = MACHINE.moves.filter((move) => move.by.includes('clock'));
+
+/**
+ * Replay an item's recorded events through the declared lifecycle, as the view's timeline does
+ * (M1). The board logs a claim on a claimed item as renew, and never the clock's lapse, so a move
+ * that cannot start where the replay stands, or a status the history does not reach, puts the
+ * lapse in first.
+ *
+ * @param {{ kind: string, at: string }[]} history
+ * @param {string} status
+ * @returns {{ from: string, move: object | null, at: string | null }[]}
+ */
+function lifecycleSteps(history, status) {
+ const steps = [];
+ let at = MACHINE.initial;
+ /** Record where the replay stands and the move it makes, if any, then follow that move. */
+ const step = (move, event) => {
+ steps.push({ from: at, move, at: event ? event.at : null });
+ if (move) at = move.to;
+ };
+ for (const event of history) {
+ const verb = event.kind === 'renew' ? 'claim' : event.kind;
+ /** The declared move this event makes from a state; a renew is the claim that stays claimed. */
+ const fits = (state) => MACHINE.moves.find((move) => move.verb === verb && move.from.includes(state)
+ && (verb !== 'claim' || (event.kind === 'renew') === (move.to === state)));
+ const lapse = fits(at) ? null : CLOCK_MOVES.find((move) => move.from.includes(at) && fits(move.to));
+ if (lapse) step(lapse, null);
+ step(fits(at) || null, event);
+ }
+ const lapse = at === status ? null : CLOCK_MOVES.find((move) => move.from.includes(at) && move.to === status);
+ if (lapse) step(lapse, null);
+ return steps;
+}
+
+/** When an item arrived in its list stage; edits, review reservations and renewals do not restart it. */
+function stageSince(item, steps) {
+ if (item.merged) return item.history.findLast((event) => event.kind === 'merged')?.at || item.updatedAt;
+ const arrival = steps.findLast((step) => step.move && step.from !== step.move.to);
+ // A lapse is inferred, but the claim's own receipt records the deadline that caused it.
+ if (arrival?.move?.verb === 'lapse') {
+ const claim = item.thread.findLast((entry) => entry.type === 'move' && ['claim', 'renew'].includes(entry.kind));
+ if (claim?.detail?.leaseUntil) return claim.detail.leaseUntil;
+ }
+ return arrival ? arrival.at || item.updatedAt : item.history.find((event) => event.kind === 'add')?.at || item.updatedAt;
+}
+
+/**
+ * Give every item what its list rows read without its history: its list stage and when it entered
+ * it, its roadmap milestone, the live lease on it, and its verdict and fact counts. A recorded merge,
+ * not an accept, ends the pipeline. The board's moves are tallied once, keyed from>to:verb as the
+ * lifecycle drawing sums them.
+ *
+ * @param {any} state
+ * @param {Map<number, string | null>} leases Each item's recorded claim deadline.
+ * @returns {any}
+ */
+function withListFields(state, leases) {
+ const milestones = new Map();
+ for (const milestone of state.milestones ?? []) {
+ for (const entry of milestone.items) if (typeof entry.id === 'number' && !milestones.has(entry.id)) milestones.set(entry.id, milestone.name);
+ }
+ const moveCounts = {};
+ const items = state.items.map((item) => {
+ const steps = lifecycleSteps(item.history, item.status);
+ for (const step of steps) {
+ const key = step.move && step.from + '>' + step.move.to + ':' + step.move.verb;
+ if (key) moveCounts[key] = (moveCounts[key] ?? 0) + 1;
+ }
+ // Who holds the item under a live lease: its builder while claimed, its reviewer while reserved.
+ const claim = item.status === 'claimed' && item.owner ? { by: item.owner, until: leases.get(item.id) ?? null }
+ : item.status === 'submitted' && item.reviewer ? { by: item.reviewer, until: item.reviewUntil } : null;
+ return { ...item,
+ milestone: milestones.get(item.id) ?? null,
+ claim,
+ stage: item.merged ? 'merged' : item.status === 'verified' ? 'accepted' : item.status,
+ since: stageSince(item, steps),
+ counts: { verdicts: item.verdicts.length, facts: item.thread.filter((entry) => entry.type === 'fact').length },
+ };
+ });
+ return { ...state, items, moveCounts };
+}
+
+/** Keep the summary fields; the latest verdict keeps only its decision and reason. */
+function itemSummary(item) {
+ const summary = Object.fromEntries(SUMMARY_FIELDS.map((key) => [key, item[key]]));
+ summary.verdict = item.verdict && { decision: item.verdict.decision, reason: item.verdict.reason };
+ return summary;
+}
+
+/** Everything a summary leaves out, with the latest verdict whole: laid over its summary, it is the full item. */
+function itemDetail(item) {
+ return Object.fromEntries(Object.entries(item).filter(([key]) => key === 'id' || key === 'verdict' || !SUMMARY_KEYS.has(key)));
+}
+
+/** The text the view's search matches for an item, lowercased: its #id, title, lane, spec ids and criterion. */
+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. */
+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 };
}
/** Add the request-specific unread count without mutating the reusable snapshot. */
@@ -265,42 +377,69 @@ 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 = [], onStateBuild } = {}) {
+export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, isMain, allowedOrigins = [], onStateBuild, stateDetail = 'full' } = {}) {
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');
+ // A page that still reads each item's detail from the state keeps full items until it opts in.
+ if (!['full', 'summary'].includes(stateDetail)) throw new TypeError('createLocalApiHandler stateDetail is full or summary');
const codeIsMain = codeIsFromMain() && isMain !== false;
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) {
+ /**
+ * 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.
+ */
+ function withSnapshot(board, read) {
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 result = read(cached, true);
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) };
+ return result;
}
}
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 entry = snapshotEntry(before.revision, state, 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 read(entry, false);
+ }
+ /** 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 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) };
+ });
+ }
+ /** 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) => {
+ const item = entry.items.get(id);
+ return item ? itemDetail(item) : null;
+ });
+ }
+ /** The ids of the items the view's search would show for this text, in board-state order. */
+ function localSearch(board, text) {
+ const words = String(text).trim().toLowerCase();
+ return withSnapshot(board, (entry) => {
+ entry.searchTexts ??= entry.state.items.map((item) => [item.id, searchText(item)]);
+ return entry.searchTexts.filter(([, searched]) => !words || searched.includes(words)).map(([id]) => id);
+ });
}
return createApiHandler({
authenticate: (req) => {
@@ -315,8 +454,10 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
},
boards: () => apiBoardListing(projects, codeIsMain),
board: (id) => findBoard(id, projects, codeIsMain),
- state: (board, who, seen) => localState(board, seen).state,
- stateJson: (board, who, seen) => localState(board, seen).json,
+ state: (board, who, seen, options) => localState(board, seen, options).state,
+ stateJson: (board, who, seen, options) => localState(board, seen, options).json,
+ item: (board, id) => localItem(board, id),
+ search: (board, text) => localSearch(board, text),
shout: (board, id) => relayLinked(board.root)
? relayPresentationShout(board.root, id)
: withBoard(board.root, (db) => store.shoutDetails(db, id), codeIsMain),
@@ -330,11 +471,14 @@ 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, onStateBuild } = {}) {
+/**
+ * Serve the RFC 0002 API only on loopback, behind the same session-secret boundary as the view. Its
+ * state sends item summaries unless asked for detail=full; each item's detail has its own path (A2).
+ */
+export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects, isMain, onStateBuild, stateDetail = 'summary' } = {}) {
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, onStateBuild });
+ const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects, isMain, onStateBuild, stateDetail });
const server = createServer(handler);
server.requestTimeout = 15_000;
return new Promise((ready, fail) => {
diff --git a/src/json.js b/src/json.js
index 82120b5b..fa713ba8 100644
--- a/src/json.js
+++ b/src/json.js
@@ -90,6 +90,8 @@ export const JSON_SHAPES = {
boards: shape({ boards: 'array' }),
state: shape({ state: 'object' }),
shout: shape({ shout: 'object' }),
+ item: shape({ item: 'object' }),
+ items: shape({ ids: 'array' }),
events: shape({ events: 'array' }),
move: shape({ event: 'object', result: 'object' }),
request: shape({ event: 'object', result: 'object' }),
diff --git a/test/api-http.test.js b/test/api-http.test.js
index ee9df79f..861473d7 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -4,10 +4,11 @@ import { randomUUID } from 'node:crypto';
import { runFixtureChild, runFixtureGit } from './fixture-child.js';
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
+import { spawn } from 'node:child_process';
import { createServer, request as httpRequest } from 'node:http';
import { join, resolve } from 'node:path';
import { test } from 'node:test';
-import { serveApi } from '../src/api.js';
+import { createLocalApiHandler, serveApi } from '../src/api.js';
import { main } from '../src/cli.js';
import { createApiHandler } from '../src/api-http.js';
import { registryFile, registerProject } from '../src/projects.js';
@@ -205,13 +206,158 @@ async function cachedHttpStateTest(t) {
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.items.find((item) => item.id === itemId).claim, null);
+ assert.equal((await box.call(box.path + '/items/' + itemId)).document.item.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, N26] the board state sends summaries and an item's detail comes from its own path", async (t) => {
+ const box = await httpBox(t);
+ 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 accepted = (await move({ verb: 'add', args: {
+ lane: 'app', title: 'Accepted summary item', criterion: 'Every list reads the Zebra marker', brief: 'A brief only the detail carries',
+ specs: 'G1', check: 'true', wait: true,
+ } })).item.item_id;
+ await move({ verb: 'claim', item: accepted, agent: builder.agent });
+ await move({ verb: 'fact', item: accepted, agent: builder.agent, args: { kind: 'note', text: 'a fact only the thread carries' } });
+ await move({ verb: 'submit', item: accepted, agent: builder.agent });
+ await move({ verb: 'next', agent: verifier.agent, args: { verify: true } });
+ await move({ verb: 'verify', item: accepted, agent: verifier.agent, args: { decision: 'accept', reason: 'CRITERION_MET', note: 'ran the check and read the summary' } });
+ const claimed = (await move({ verb: 'add', args: { lane: 'app', title: 'Claimed summary item', criterion: 'stays claimed', specs: 'G1' } })).item.item_id;
+ await move({ verb: 'claim', item: claimed, agent: builder.agent });
+ const open = (await move({ verb: 'add', args: { lane: 'app', title: 'Open summary item', criterion: 'waits for a builder', specs: 'G1' } })).item.item_id;
+ box.cli(box.root, 'milestone', 'add', 'Delivery', '--items', String(accepted));
+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
+ let leaseUntil;
+ try { leaseUntil = board.db.prepare('SELECT item_lease_until FROM item WHERE item_id = ?').get(claimed).item_lease_until; } finally { store.closeBoard(board); }
+
+ const summaryFields = ['id', 'title', 'lane', 'status', 'route', 'milestone', 'specs', 'claim', 'builtBy', 'blockedBy', 'updatedAt', 'stage', 'since', 'counts', 'verdict'];
+ const summaryState = await box.call(box.path + '/state');
+ assert.equal(summaryState.status, 200);
+ const fullState = await box.call(box.path + '/state?detail=full');
+ assert.equal(fullState.status, 200);
+ const summaries = new Map(summaryState.document.state.items.map((item) => [item.id, item]));
+ const fulls = new Map(fullState.document.state.items.map((item) => [item.id, item]));
+ assert.deepEqual([...summaries.keys()], [open, claimed, accepted], 'the state still lists every item, in board order');
+ assert.deepEqual([...fulls.keys()], [...summaries.keys()]);
+ for (const summary of summaries.values()) {
+ assert.deepEqual(Object.keys(summary), summaryFields, `#${summary.id} carries only the summary fields`);
+ }
+ for (const full of fulls.values()) {
+ for (const field of ['thread', 'verdicts', 'history', 'brief', 'criterion', 'check', ...summaryFields]) assert.ok(Object.hasOwn(full, field), `detail=full keeps #${full.id}'s ${field}`);
+ }
+ assert.ok(Buffer.byteLength(JSON.stringify(summaryState.document)) < Buffer.byteLength(JSON.stringify(fullState.document)));
+ assert.equal(JSON.stringify(summaryState.document).includes('A brief only the detail carries'), false, 'no brief text in the summaries');
+ assert.equal(JSON.stringify(summaryState.document).includes('Zebra'), false, 'no criterion text in the summaries');
+
+ const acceptedFull = fulls.get(accepted);
+ assert.deepEqual(summaries.get(accepted), {
+ id: accepted, title: 'Accepted summary item', lane: 'app', status: 'verified', route: acceptedFull.route, milestone: 'Delivery',
+ specs: ['G1'], claim: null, builtBy: builder.agent, blockedBy: [], updatedAt: acceptedFull.updatedAt, stage: 'accepted',
+ since: acceptedFull.history.findLast((event) => event.kind === 'accept').at, counts: { verdicts: 1, facts: 1 },
+ verdict: { decision: 'ACCEPT', reason: 'CRITERION_MET' },
+ });
+ const claimedFull = fulls.get(claimed);
+ assert.deepEqual(summaries.get(claimed).claim, { by: builder.agent, until: leaseUntil });
+ assert.equal(summaries.get(claimed).stage, 'claimed');
+ assert.equal(summaries.get(claimed).since, claimedFull.history.findLast((event) => event.kind === 'claim').at);
+ assert.deepEqual(summaries.get(open), {
+ id: open, title: 'Open summary item', lane: 'app', status: 'open', route: fulls.get(open).route, milestone: null,
+ specs: ['G1'], claim: null, builtBy: null, blockedBy: [], updatedAt: fulls.get(open).updatedAt, stage: 'open',
+ since: fulls.get(open).history.find((event) => event.kind === 'add').at, counts: { verdicts: 0, facts: 0 }, verdict: null,
+ });
+ assert.deepEqual(summaryState.document.state.moveCounts, {
+ 'open>claimed:claim': 2, 'claimed>submitted:submit': 1, 'submitted>submitted:reserve': 1, 'submitted>verified:accept': 1,
+ }, 'the lifecycle drawing tallies the moves without any history');
+ assert.deepEqual(fullState.document.state.moveCounts, summaryState.document.state.moveCounts);
+
+ for (const [id, full] of fulls) {
+ const detail = await box.call(box.path + '/items/' + id);
+ assert.equal(detail.status, 200);
+ assert.deepEqual({ ...summaries.get(id), ...detail.document.item }, full, `#${id}'s summary and detail make its full item`);
+ const carried = Object.keys(detail.document.item).filter((field) => summaryFields.includes(field));
+ assert.deepEqual(carried, ['id', 'verdict'], 'the detail repeats only the id and the whole latest verdict');
+ for (const field of ['thread', 'verdicts', 'history', 'brief', 'criterion', 'check', 'owner', 'reviewer', 'reviewUntil', 'verifiedBy', 'commit', 'merged']) {
+ assert.ok(Object.hasOwn(detail.document.item, field), `#${id}'s detail carries ${field}`);
+ }
+ }
+ const acceptedDetail = (await box.call(box.path + '/items/' + accepted)).document.item;
+ assert.equal(acceptedDetail.brief, 'A brief only the detail carries');
+ assert.equal(acceptedDetail.criterion, 'Every list reads the Zebra marker');
+ assert.equal(acceptedDetail.check, 'true');
+ assert.equal(acceptedDetail.checkBaseline.result, 'green');
+ assert.equal(acceptedDetail.verdict.note, 'ran the check and read the summary');
+ assert.deepEqual(acceptedDetail.thread.filter((entry) => entry.type === 'fact').map((entry) => entry.text), ['a fact only the thread carries']);
+
+ /** Search through HTTP and return the matching ids in board order. */
+ const search = async (text) => {
+ const found = await box.call(box.path + '/items?q=' + encodeURIComponent(text));
+ assert.equal(found.status, 200);
+ return found.document.ids;
+ };
+ assert.deepEqual(await search('zebra'), [accepted], 'the criterion is searched without being in the state');
+ assert.deepEqual(await search(' CLAIMED summary '), [claimed], 'trimmed text matches a title, ignoring case');
+ assert.deepEqual(await search('#' + open), [open], 'an #id matches its item');
+ assert.deepEqual(await search('g1'), [open, claimed, accepted], 'spec ids match');
+ assert.deepEqual(await search('APP'), [open, claimed, accepted], 'the lane matches');
+ assert.deepEqual(await search(''), [open, claimed, accepted], 'no text matches every item, as the view shows them all');
+ assert.deepEqual(await search('no item says this'), []);
+
+ const missing = await box.call(box.path + '/items/9999');
+ assert.equal(missing.status, 404);
+ assert.equal(missing.document.error.code, 'NO_ITEM');
+ for (const rawId of ['0', 'abc', '1.5']) {
+ const malformed = await box.call(box.path + '/items/' + rawId);
+ assert.equal(malformed.status, 400);
+ assert.equal(malformed.document.error.code, 'BAD_REQUEST');
+ }
+ const posted = await box.call(box.path + '/items/' + accepted, {});
+ assert.equal(posted.status, 400);
+ const badDetail = await box.call(box.path + '/state?detail=everything');
+ assert.equal(badDetail.status, 400);
+ assert.equal(badDetail.document.error.code, 'BAD_REQUEST');
+ assert.deepEqual((await box.call(box.path + '/state?detail=summary')).document.state.items, summaryState.document.state.items);
+
+ // pullboard serve itself sends summaries; a page's own server, built as the view builds it, keeps full items until it opts in.
+ const served = spawn(process.execPath, [BIN, 'serve', '--port', '0', '--json'], { cwd: box.root, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ const exited = new Promise((done) => served.once('close', done));
+ t.after(async () => { served.kill('SIGTERM'); await exited; });
+ const servedUrl = await new Promise((found, fail) => {
+ let out = '';
+ const timer = setTimeout(() => fail(new Error('pullboard serve printed no address: ' + out)), 30_000);
+ served.stdout.setEncoding('utf8');
+ served.stdout.on('data', (chunk) => {
+ out += chunk;
+ const match = /"url":\s*"([^"]+)"/.exec(out);
+ if (match) { clearTimeout(timer); found(new URL(match[1])); }
+ });
+ served.once('close', (code) => { clearTimeout(timer); fail(new Error('pullboard serve exited ' + code + ': ' + out)); });
+ });
+ const servedState = await fetchFresh(servedUrl.origin + box.path + '/state', { headers: { 'x-pullboard-key': servedUrl.searchParams.get('k') } });
+ assert.equal(servedState.status, 200);
+ assert.deepEqual((await servedState.json()).state.items, summaryState.document.state.items, 'pullboard serve sends the same summaries');
+ let pagePort;
+ const pageHandler = createLocalApiHandler({ secret: 'page-fixture-secret', getPort: () => pagePort, runCommand: main, projects: () => [{ root: box.root, name: 'HTTP fixture' }] });
+ const page = createServer(pageHandler);
+ await new Promise((done) => page.listen(0, '127.0.0.1', done));
+ pagePort = page.address().port;
+ t.after(() => new Promise((done) => { pageHandler.close(); page.close(done); page.closeIdleConnections(); }));
+ const pageState = await fetchFresh('http://127.0.0.1:' + pagePort + box.path + '/state', { headers: { 'x-pullboard-key': 'page-fixture-secret' } });
+ assert.deepEqual((await pageState.json()).state.items, fullState.document.state.items, 'a page server that has not opted in keeps every item in full');
+ const pageSummary = await fetchFresh('http://127.0.0.1:' + pagePort + box.path + '/state?detail=summary', { headers: { 'x-pullboard-key': 'page-fixture-secret' } });
+ assert.deepEqual((await pageSummary.json()).state.items, summaryState.document.state.items, 'and sends summaries when asked');
+});
+
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; } });
@@ -389,7 +535,8 @@ test('[A2] real HTTP state, moves and refusals use the CLI and exact committed e
assert.deepEqual(refused.document.error, JSON.parse(terminal.stdout).error, 'the original CLI refusal keeps its message and next step');
const state = await box.call(box.path + '/state');
assert.equal(state.document.state.board, box.id);
- assert.equal(state.document.state.items.find((item) => item.id === id).owner, one.agent);
+ assert.equal(state.document.state.items.find((item) => item.id === id).claim.by, one.agent);
+ assert.equal((await box.call(box.path + '/items/' + id)).document.item.owner, one.agent);
const events = await box.call(box.path + '/events?after=' + added.document.event.event_id);
assert.deepEqual(events.document.events, [claimed.document.event]);
const badAgent = await box.call(box.path + '/moves', { verb: 'release', item: id, agent: 'absent-agent' });
@@ -417,22 +564,22 @@ test('[A2,V2,H16] board-state JSON retains pending and red baselines and removes
id = store.addItem(board, { by: 'coordinator', lane: 'app', title: 'Captured API observation',
check: pending.command, checkBaseline: pending });
} finally { store.closeBoard(board); }
- const initial = await box.call(box.path + '/state');
- assert.deepEqual(initial.document.state.items.find((item) => item.id === id).checkBaseline, pending,
+ const initial = await box.call(box.path + '/items/' + id);
+ assert.deepEqual(initial.document.item.checkBaseline, pending,
'a pending captured request reaches the public state endpoint before completion');
const completed = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
try {
store.completeCheckBaseline(completed, id, { agentId: 'coordinator', expected: pending,
baseline: { command: pending.command, main: pending.main, result: 'red', seconds: 1 } });
} finally { store.closeBoard(completed); }
- const redState = await box.call(box.path + '/state');
- const red = redState.document.state.items.find((item) => item.id === id).checkBaseline;
+ const redState = await box.call(box.path + '/items/' + id);
+ const red = redState.document.item.checkBaseline;
assert.deepEqual(red, { command: pending.command, main: pending.main, result: 'red', seconds: 1, request: pending.request });
assert.equal(Object.hasOwn(red, 'warning'), false, 'a failing baseline has no proves-nothing warning');
const cleared = await box.call(box.path + '/moves', { verb: 'edit', item: id, args: { check: '' } });
assert.equal(cleared.status, 200, JSON.stringify(cleared.document));
- const clearedState = await box.call(box.path + '/state');
- const clearedItem = clearedState.document.state.items.find((item) => item.id === id);
+ const clearedState = await box.call(box.path + '/items/' + id);
+ const clearedItem = clearedState.document.item;
assert.equal(clearedItem.check, '');
assert.equal(Object.hasOwn(clearedItem, 'checkBaseline'), false, 'clearing the check removes its old observation from API state');
});
@@ -454,8 +601,8 @@ test('[A2,V2] HTTP add and edit preserve explicit blocking baseline requests', a
assert.equal(item.item_check_baseline.result, 'green', '--wait returns a terminal observation in the add response');
assert.equal(item.item_check_baseline.warning, 'CRITERION_PROVES_NOTHING');
assert.equal(readFileSync(firstMarker, 'utf8'), 'finished');
- const addedState = await box.call(box.path + '/state');
- const projected = addedState.document.state.items.find((row) => row.id === item.item_id);
+ const addedState = await box.call(box.path + '/items/' + item.item_id);
+ const projected = addedState.document.item;
assert.equal(projected.check, check);
assert.deepEqual(projected.checkBaseline, item.item_check_baseline, 'board-state item JSON carries the same complete observation and warning');
const secondMarker = join(box.dir, 'edit-finished');
@@ -467,9 +614,9 @@ test('[A2,V2] HTTP add and edit preserve explicit blocking baseline requests', a
assert.equal(edited.document.result.item.item_check_baseline.command, editedCheck);
assert.equal(edited.document.result.item.item_check_baseline.result, 'green', '--wait also blocks edit until its new check finishes');
assert.equal(readFileSync(secondMarker, 'utf8'), 'finished');
- const editedState = await box.call(box.path + '/state');
+ const editedState = await box.call(box.path + '/items/' + item.item_id);
const editedItem = edited.document.result.item;
- assert.deepEqual(editedState.document.state.items.find((row) => row.id === item.item_id).checkBaseline,
+ assert.deepEqual(editedState.document.item.checkBaseline,
editedItem.item_check_baseline, 'board-state JSON replaces the observation when the check changes');
});
@@ -653,6 +800,11 @@ 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/);
+ 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);
+ assert.equal((await unavailable.json()).error.code, 'ITEM_NOT_AVAILABLE', 'an adapter whose state carries full items offers no item reads');
+ }
});
test('[A2, N26] state JSON fragments preserve the API envelope and legacy adapter fallback', async (t) => {
diff --git a/test/thread.test.js b/test/thread.test.js
index f4b9d047..a29990de 100644
--- a/test/thread.test.js
+++ b/test/thread.test.js
@@ -306,16 +306,17 @@ test('[B29,B30,B31,B32,A2] CLI and HTTP facts share stamped threads, guard judge
});
const observationId = observation.document.result.fact.id;
- const beforeRefusal = await box.call(box.path + '/state');
- const existingThread = beforeRefusal.document.state.items.find((entry) => entry.id === id).thread;
+ const beforeRefusal = await box.call(box.path + '/items/' + id);
+ const existingThread = beforeRefusal.document.item.thread;
+ assert.ok(existingThread.some((entry) => entry.id === observationId), 'the item detail carries the thread');
const refused = await box.call(box.path + '/moves', {
verb: 'fact', item: id, agent: observer.agent,
args: { kind: 'decision', text: 'observer cannot decide' },
});
assert.equal(refused.status, 409);
assert.equal(refused.document.error.code, 'FACT_JUDGEMENT');
- const afterRefusal = await box.call(box.path + '/state');
- assert.deepEqual(afterRefusal.document.state.items.find((entry) => entry.id === id).thread, existingThread, 'a refused judgement appends no event');
+ const afterRefusal = await box.call(box.path + '/items/' + id);
+ assert.deepEqual(afterRefusal.document.item.thread, existingThread, 'a refused judgement appends no event');
const correctionRun = box.run(holder.path, 'fact', String(id), 'supersession', '--supersedes', observationId, '--json', '--', 'corrected evidence');
assert.equal(correctionRun.status, 0, correctionRun.stderr);
@@ -338,8 +339,8 @@ test('[B29,B30,B31,B32,A2] CLI and HTTP facts share stamped threads, guard judge
assert.ok(terminalShow.stdout.includes(`ref: thread-fixture.txt:1@${box.commit}`), 'show keeps the full commit reference');
const terminalJson = JSON.parse(box.run(box.root, 'show', String(id), '--json').stdout);
- const apiState = await box.call(box.path + '/state');
- const apiItem = apiState.document.state.items.find((entry) => entry.id === id);
+ const apiState = await box.call(box.path + '/items/' + id);
+ const apiItem = apiState.document.item;
assert.deepEqual(terminalJson.thread, apiItem.thread, 'CLI JSON and API state expose the same stamped thread');
assert.deepEqual(relayPresentation(box.root).state.items.find((entry) => entry.id === id).thread, apiItem.thread, 'sealed presentation carries the same facts');
assert.deepEqual(apiItem.thread.filter((entry) => entry.type === 'fact').map(({ id: factId, text, supersedes }) => ({ id: factId, text, supersedes })), [