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
feat(core): keep typed item threads [B29,B30,B31,B32]
Corey Olson0e378c3bb526
diff --git a/docs/api.md b/docs/api.mdindex d003ce8f..a3e04408 100644--- a/docs/api.md+++ b/docs/api.md@@ -34,7 +34,7 @@ When `add` or `edit` supplies a new nonempty check, Pullboard measures it once i| `milestone move` | `version:number`, `milestone:object` || `milestone edit` | `version:number`, `milestone:object` || `milestone remove` | `version:number`, `milestone:object` |-| `show` | `version:number`, `item_id:number`, `item_title:string`, `item_lane:string`, `item_status:string`, `verdicts:array` |+| `show` | `version:number`, `item_id:number`, `item_title:string`, `item_lane:string`, `item_status:string`, `verdicts:array`, `thread:array` || `status` | `version:number`, `me:object`, `mine:array`, `stats:object`, `reviewQueue:object`, `unread:number` || `doctor` | `version:number`, `problems:array` || `inbox` | `version:number`, `shouts:array` |@@ -43,6 +43,7 @@ When `add` or `edit` supplies a new nonempty check, Pullboard measures it once i| `log` | `version:number`, `events:array` || `add` | `version:number`, `item:object` || `edit` | `version:number`, `item:object` |+| `fact` | `version:number`, `item:number`, `fact:object` || `escalate` | `version:number`, `id:number`, `from:string`, `to:string` || `run` | `version:number`, `messages:array` || `sweep` | `version:number`, `messages:array` |@@ -93,6 +94,20 @@ When outstanding reviews reach `verify.reviewRatio` times the active reviewers (For HTTP `next`, a review offer returns success with `event: null`, `offer` and the ordinary CLI `result`. Send `args.build: true` to claim as before and receive the actual claim event. The unattended `run` command always supplies explicit build intent, records it on fresh claims, and prints the review backlog each iteration.+## Item threads++`pullboard fact <id> <kind> "<text>"` appends a fact to an existing item. The observation kinds are `capture`, `measurement`, `note` and `diff`; any registered agent may append them. The judgement kinds are `decision`, `rejection`, `supersession` and `root-cause`; only the item's live lease holder or the coordinator may append them. An expired lease gives no judgement permission. Facts do not change the item's status or its claim.++The result is `{version: 1, item: <item-id>, fact: {...}}`. A fact has `id` (stable string identity), `eventId` (board-local event sequence), `kind`, exact `text`, `by` (registered author), `at` (UTC timestamp), `ref` and `supersedes`. The board supplies identity, author and time. `ref` and `supersedes` are `null` when omitted.++Use `--ref src/file.js:12-30@<full-40-character-sha>` to bind a fact to a committed code range. A single line is `:12@...`. The reference becomes `{path, start, end, commit}`; paths are relative to the repo, line numbers are positive and ascending, and the commit is lowercase hexadecimal. Short hashes are refused with `BAD_FACT_REF`. Replicas validate this binding without fetching source code.++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.++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.+## RefusalsA refusal keeps the command's existing exit status and prints exactly one versioned document to stdout. In JSON mode stderr stays empty except for sign-in instructions and check consent notices. The command-specific `code` identifies the rule; `message` explains what happened; `next` gives the next step.diff --git a/docs/formats.md b/docs/formats.mdindex c5424d75..84945900 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -70,7 +70,7 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. || `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. || `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |-| `move engine` | `2` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |+| `move engine` | `3` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |<!-- format-versions:end -->Pullboard 0.6.1 released engine 1. The first change to released move semantics raises the engine once for the next release; later changes developed before that release keep the same version. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Older clients refuse engine-2 moves before changing rows or replay cursors; engine 2 still accepts engine-1 moves.@@ -235,6 +235,7 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `edit` | editor | `brief`, `route`, `criterion`, `check`, `unfrozen` || `escalate` | builder | `from`, `to`, `note`, `attempt` || `attempt` | reporting agent | `n`, `seconds`, `result` |+| `fact` | author | `id`, `kind`, `text`, `ref`, `supersedes` || `claim` | builder | `leaseUntil`, `digest` || `renew` | builder | `leaseUntil`, `digest` || `release` | builder | — |@@ -255,6 +256,14 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `row_apply` | coordinator | `events` |<!-- events:end -->+Item facts use the existing append-only `event` table and event-log version 1. A `fact` event's actor and timestamp stamp its author and time; its detail carries a stable string `id`, typed `kind`, exact `text`, optional `ref` binding or `null`, and superseded fact id or `null`. Allowed kinds are `capture`, `measurement`, `note`, `diff`, `decision`, `rejection`, `supersession` and `root-cause`. Judgement kinds and any correction using `supersedes` require the item's live holder or the coordinator. A correction must refer to a fact on the same item; it adds a new event and preserves every earlier fact.++A binding is `{path, start, end, commit}`: a relative repository path, a positive ascending inclusive line range and a full 40-character hexadecimal commit id. It identifies code without storing source or requiring Git on a replica. Fact ids are generated UUIDs locally. A sealed `appendFact` operation uses its executable move id as its fact id, so replicas keep corrections bound to the same fact even when local event sequence ids differ. Native export/import retains these event rows without a separate fact table or schema upgrade.++The derived `thread` in CLI `show` JSON and API v1 item state is an array in ascending event order. Move entries are `{type: "move", eventId, kind, by, at, detail}`. Fact entries are `{type: "fact", id, eventId, kind, text, by, at, ref, supersedes}`. `eventId` is the board's numeric event sequence; `id` is the stable fact identity used by corrections. `by` and `at` come from the immutable event author and UTC timestamp. `detail` retains a move's original structured payload. Nullable `ref` and `supersedes` preserve omitted fields as `null`. Superseded facts remain in the array beside their corrections.++Engine version 3 adds the sealed `appendFact` operation. It is the single engine increment reserved for the release after 0.7.0; other changes in that release reuse version 3. Older supported operations remain replayable; an older client refuses a version-3 move before applying it. The sealed envelope, CLI/API envelope, schema and event-log layout versions are unchanged.+New CLI claims include a `policy` object (`version: 1`, `commit`) in the frozen criterion. It pins the coordinator checkout’s committed configuration on its attached main branch. A temporary detached review checkout refuses new policy-dependent claims or project gates with `NO_POLICY`; the coordinator returns to its main branch. Existing frozen submissions remain verifiable. Legacy claims use their recorded claim-base commit. A CLI `submit` records the pre-merge coordinator HEAD as optional `policyCommit`; historical doctor and acceptance checks use this snapshot when allowing unchanged foreign files brought in from MAIN. Verified dependencies may also contribute unchanged files in their own lanes before a MAIN merge; foreign deletion or replacement is not authorized by an unrelated dependency’s tree. The complete candidate diff against both claim base and frozen MAIN is checked with rename detection disabled, preserving deleted paths and whitespace in names. Frozen item checks run against the exact submitted commit in an isolated checkout when accepting and auditing; repairing a reviewer’s checkout cannot make a red submission green.Person answer events additionally record their `channel`, either `terminal` or `view`, including the forwarded answer to the original asker. Agent answers omit that field.diff --git a/docs/formats.test.js b/docs/formats.test.jsindex a411d45f..4997f44d 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -12,6 +12,7 @@ import {ACCEPT_REASON,answerDecision,addItem,+ appendFact,claim,closeBoard,editItem,@@ -158,6 +159,8 @@ function recordEventContract() {applyRowDecisions(board, { agentId: coordinator, events: decisions.map((record) => record.event) });const freeze = (digest) => () => ({ text: `criterion-${digest}`, digest });const first = addItem(board, { by: coordinator, lane: 'docs', title: 'Accepted example', criterion: 'Initial', specIds: ['A1'], route: 'strong' });+ const fact = appendFact(board, first, { agentId: builder, kind: 'note', text: 'Captured evidence', ref: 'docs/formats.md:1-3@' + 'a'.repeat(40) });+ appendFact(board, first, { agentId: coordinator, kind: 'measurement', text: 'Corrected evidence', supersedes: fact.id });editItem(board, first, { agentId: coordinator, brief: 'Files: docs/formats.md\nTest: docs/formats.test.js', route: 'mid', criterion: 'Changed', check: 'node test' });recordAttempt(board, first, { agentId: builder, n: 1, seconds: 2, result: 'failed' });claim(board, first, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('first') });@@ -350,6 +353,7 @@ test('[A5] schema, versions, event kinds and event detail fields match live behaadd: 'item creator',edit: 'editor',attempt: 'reporting agent',+ fact: 'author',guards: 'board',shout: 'sender',pass: 'coordinator',diff --git a/src/api.js b/src/api.jsindex 582c9aca..29dbbd9b 100644--- a/src/api.js+++ b/src/api.js@@ -86,6 +86,7 @@ const MOVES = {'spec-decline': { prefix: ['spec', 'decline'], positions: ['ids'], flags: ['reason'] },add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'] },edit: { item: true, flags: ['criterion', 'brief', 'route', 'check'] },+ fact: { item: true, positions: ['kind', 'text'], flags: ['supersedes', 'ref'] },claim: { item: true },release: { item: true },submit: { item: true },@@ -205,10 +206,12 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =requests: store.openRequests(db),milestones: milestoneRoadmap(board.root, db),rowDecisions: store.rowDecisions(db),+ threads: new Map(store.listItems(db, { all: true }).map((item) => [item.item_id, store.itemThread(db, item.item_id)])),}));state.requests = projectData.requests;state.milestones = projectData.milestones;state = projectRowDecisions(projectData.rowDecisions, state);+ state.items = state.items.map((item) => ({ ...item, thread: projectData.threads.get(item.id) ?? [] }));return state;},code: (board, ref) => codeAt(board.root, ref),diff --git a/src/board.js b/src/board.jsindex 60db3e95..21f97f25 100644--- a/src/board.js+++ b/src/board.js@@ -6,7 +6,7 @@* every move lands in an append-only event log (R2). The caller supplies what only git and the* spec know: the commit, the verifier's checkout, the frozen criterion.*/-import { randomBytes } from 'node:crypto';+import { randomBytes, randomUUID } from 'node:crypto';import { mkdirSync } from 'node:fs';import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';@@ -1564,6 +1564,67 @@ export function events(board, { itemId } = {}) {.all(itemId ?? null, itemId ?? null);}+/** Fact labels distinguish observations from judgements reserved to an item's live holder [B29,B30]. */+export const FACT_KINDS = Object.freeze(['capture', 'measurement', 'note', 'diff', 'decision', 'rejection', 'supersession', 'root-cause']);+const FACT_JUDGEMENTS = new Set(['decision', 'rejection', 'supersession', 'root-cause']);++/** Validate a portable code binding without reading source on replicas that hold only board data [B32,H7]. */+export function factReference(ref) {+ if (ref === null || ref === undefined) return null;+ const parts = typeof ref === 'string' && /^([^\r\n\0]+):(\d+)(?:-(\d+))?@([0-9a-f]{40})$/iu.exec(ref);+ if (!parts) throw new Refused('BAD_FACT_REF', 'a fact reference needs path:line[-line]@full-sha with all 40 hexadecimal characters; use the full git commit id');+ const [, path, first, last, commit] = parts;+ const start = Number(first), end = Number(last ?? first);+ if (path.startsWith('/') || path.includes('\\') || /^[A-Za-z]:/u.test(path) || path.split('/').some((part) => !part || part === '.' || part === '..') || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start) {+ throw new Refused('BAD_FACT_REF', 'a fact reference needs a relative repo path and a positive ascending line range; use path:line[-line]@full-sha');+ }+ return { path, start, end, commit: commit.toLowerCase() };+}++/** Give facts the same stamped identity on CLI, API, export and replica reads [B29,B31]. */+function factFromEvent(event) {+ const detail = JSON.parse(event.event_detail);+ return { id: detail.id, eventId: event.event_id, kind: detail.kind, text: detail.text,+ by: event.event_by, at: event.event_at, ref: detail.ref ?? null, supersedes: detail.supersedes ?? null };+}++/** Read every move and fact in append order, including superseded facts and full original text [B31,B32]. */+export function itemThread(board, id) {+ itemById(board, id);+ return events(board, { itemId: id }).map((event) => event.event_kind === 'fact'+ ? { type: 'fact', ...factFromEvent(event) }+ : { type: 'move', eventId: event.event_id, kind: event.event_kind, by: event.event_by,+ at: event.event_at, detail: JSON.parse(event.event_detail) });+}++/** Add threads to public item projections without changing their existing fields [A1,A2,B32]. */+export function projectItemThreads(board, state) {+ return { ...state, items: state.items.map((item) => ({ ...item, thread: itemThread(board, item.id) })) };+}++/** Append a typed fact atomically; a correction never edits the original event [B29,B30,B31,B32].+ * The internal factId is set from a sealed move's identity during replay, rather than replica-local sequence ids.+ */+export function appendFact(board, id, { agentId, kind, text, ref = null, supersedes = null, factId = randomUUID() }) {+ return atomic(board, () => {+ const item = current(board, itemById(board, id));+ if (!board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(agentId)) throw new Refused('NO_AGENT', `no registered agent ${agentId}; join a worktree before appending a fact`);+ if (!FACT_KINDS.includes(kind)) throw new Refused('BAD_FACT_KIND', `unknown fact kind ${String(kind)}; use ${FACT_KINDS.join(', ')}`);+ if (typeof text !== 'string' || !text.trim()) throw new Refused('EMPTY_FACT', 'a fact needs nonempty text; supply the observation or judgement');+ if ((FACT_JUDGEMENTS.has(kind) || supersedes !== null) && agentId !== COORDINATOR && (!isHeld(board, item) || item.item_owner !== agentId)) {+ throw new Refused('FACT_JUDGEMENT', `only the item's live holder${isHeld(board, item) ? ' (' + item.item_owner + ')' : ''} or the coordinator may append a judgement or supersede a fact; append an observation or ask the coordinator`);+ }+ if (typeof factId !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(factId)) throw new Refused('BAD_FACT_ID', 'a fact identity is invalid; retry with the current Pullboard engine');+ if (board.db.prepare("SELECT 1 FROM event WHERE event_kind = 'fact' AND json_extract(event_detail, '$.id') = ?").get(factId)) throw new Refused('BAD_FACT_ID', 'this fact identity is already recorded; retry the original sealed move instead of appending it again');+ if (supersedes !== null && (typeof supersedes !== 'string' || !itemThread(board, id).some((entry) => entry.type === 'fact' && entry.id === supersedes))) {+ throw new Refused('NO_FACT', `no fact ${String(supersedes)} on item #${id}; use a fact id from pullboard show ${id} --json`);+ }+ const binding = factReference(ref);+ logEvent(board, agentId, 'fact', id, { id: factId, kind, text, ref: binding, supersedes });+ return factFromEvent(board.lastEvent);+ });+}+/*** The next item an agent can take (N2): for a builder, the oldest open item in its lane whose* dependencies are verified; for a verifier, the oldest submitted item it did not build. An agentdiff --git a/src/cli.js b/src/cli.jsindex ac2e81c4..53a3d1d7 100644--- a/src/cli.js+++ b/src/cli.js@@ -112,6 +112,8 @@ Workpullboard doctor check board integrity without changing itpullboard show <id> [--history] an item, the criterion frozen at claim, its verdicts: the latest in full,earlier ones as one line; --history prints every note in full+ pullboard fact <id> <kind> <text> [--supersedes <fact-id>] [--ref path:lines@full-sha]+ append an observation or a holder/coordinator judgement to its threadpullboard next [--wait <minutes>] offer an eligible review when reviews pile up, otherwise claim workpullboard next --build claim a build explicitly, recording a skipped review offerpullboard next --verify reserve the next submitted item you can check;@@ -176,7 +178,7 @@ Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HEconst HELP_NAMES = ['tour', 'init', 'worktree', 'join', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export','serve', 'relay', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'show', 'next',- 'check', 'claim', 'release', 'submit', 'done', 'verify', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import',+ 'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import','sweep', 'merged', 'withdraw', 'refreeze', 'hold', 'ledger', 'log', 'spec', 'spec check', 'spec view','spec show', 'spec unmet', 'spec signoff', 'spec signers', 'spec signers add', 'forget', 'prompt', 'gate', 'hook','hook pre-commit', 'hook commit-msg', 'hook pre-push', 'view export', 'version', 'lifecycle', 'help',@@ -194,6 +196,7 @@ const HELP_EXAMPLES = {tour: 'pullboard tour', init: 'pullboard init', worktree: 'pullboard worktree web', resume: 'pullboard resume',add: 'pullboard add web "Upload page" --specs G1', list: 'pullboard list web', show: 'pullboard show 12',claim: 'pullboard claim 12', submit: 'pullboard submit 12', 'next --verify': 'pullboard next --verify',+ fact: 'pullboard fact 12 measurement "The check passes in 8 seconds"',verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',status: 'pullboard status', view: 'pullboard view', log: 'pullboard log 12', ledger: 'pullboard ledger',@@ -428,6 +431,8 @@ const OPTIONS = {outcome: { type: 'string' },item: { type: 'string' },commit: { type: 'string' },+ ref: { type: 'string' },+ supersedes: { type: 'string' },help: { type: 'boolean', short: 'h' },version: { type: 'boolean', short: 'v' },};@@ -1230,15 +1235,16 @@ function readCommands(io, { first, second, rest, values }) {show: () => {const ctx = context(io);const id = idArg(first);- const { item, verdicts, moves, related, reviewer } = withBoard(ctx, (board) => ({+ const { item, verdicts, moves, thread, related, reviewer } = withBoard(ctx, (board) => ({item: store.getItem(board, id),verdicts: store.verdictsFor(board, id),moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),+ thread: store.itemThread(board, id),related: store.relatedItems(board, store.getItem(board, id)),reviewer: store.reviewHolder(board, store.getItem(board, id)),}));if (values.json) {- io.result({ ...item, verdicts });+ io.result({ ...item, verdicts, thread });return 0;}io.say(itemLine(item));@@ -1270,6 +1276,17 @@ function readCommands(io, { first, second, rest, values }) {if (notes.some((note, index) => note !== verdicts[index].verdict_note)) io.say(`(earlier verdicts shortened; every note in full: pullboard show ${id} --history)`);if (item.item_merged_commit) io.say(`merged as ${item.item_merged_commit}`);if (item.item_withdrawn_reason) io.say(`withdrawn: ${item.item_withdrawn_reason}`);+ io.say('thread:');+ for (const entry of thread) {+ const stamp = ` ${entry.at} ${entry.by} `;+ if (entry.type === 'fact') {+ io.say(`${stamp}fact ${entry.kind} ${entry.id}${entry.supersedes ? ' (supersedes ' + entry.supersedes + ')' : ''}: ${entry.text}`);+ if (entry.ref) io.say(` ref: ${entry.ref.path}:${entry.ref.start}${entry.ref.end === entry.ref.start ? '' : '-' + entry.ref.end}@${entry.ref.commit}`);+ } else {+ const detail = entry.detail;+ io.say(`${stamp}${entry.kind}${detail.commit ? ' at ' + detail.commit : ''}${detail.reason ? ': ' + detail.reason : ''}`);+ }+ }return 0;},status: () => {@@ -1678,6 +1695,15 @@ function workCommands(io, args) {return withBoard(ctx, (board) => work(ctx, board, whoAmI(ctx, board)));};return {+ fact: () => act(async (ctx, board, me) => {+ if (!first || !second || rest.length !== 1) throw new Refused('USAGE', 'pullboard fact <id> <kind> <text> [--supersedes <fact-id>] [--ref path:lines@full-sha]');+ const id = idArg(first);+ const fact = await ordered(ctx, board, 'appendFact', [id, { agentId: me.id, kind: second,+ text: rest[0], supersedes: values.supersedes ?? null, ref: values.ref ?? null }]);+ io.result?.({ item: id, fact });+ io.say(`fact ${fact.id} appended to #${id} as ${fact.kind}`);+ return 0;+ }),milestone: () => act(async (ctx, board, me) => {const ids = (text) => (text ?? '').split(',').map((value) => value.trim()).filter(Boolean);let name;diff --git a/src/engine.js b/src/engine.jsindex 7829cc77..2b852bc8 100644--- a/src/engine.js+++ b/src/engine.js@@ -11,7 +11,7 @@ export const ENGINE_OPERATIONS = Object.freeze(['claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'merged','withdraw', 'refreeze', 'shout', 'passDecision', 'answerDecision', 'holdLane', 'releaseLane','addMilestone', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone',- 'recordRowDecisions', 'applyRowDecisions',+ 'recordRowDecisions', 'applyRowDecisions', 'appendFact',]);/** Read a replica's committed prefix without trusting an independently saved transport cursor. */@@ -81,6 +81,10 @@ function validateMove(move) {/** Restore only the frozen criterion callback; no receiver runs another machine's Git or shell. */function executableArgs(move) {const args = structuredClone(move.args);+ if (move.operation === 'appendFact') {+ if (!args[1] || typeof args[1] !== 'object' || Array.isArray(args[1])) throw new Refused('RELAY_MOVE', 'a fact needs its typed arguments; use the current Pullboard engine');+ args[1].factId = move.id;+ }if (['claim', 'refreeze'].includes(move.operation)) {const options = args[1];if (!options || !Object.hasOwn(options, 'frozen')) throw new Refused('RELAY_MOVE', 'the claim has no frozen criterion; send it with the current pullboard engine');diff --git a/src/json.js b/src/json.jsindex a61589e7..b736f561 100644--- a/src/json.js+++ b/src/json.js@@ -28,7 +28,7 @@ export const JSON_SHAPES = {'milestone move': shape({ milestone: 'object' }),'milestone edit': shape({ milestone: 'object' }),'milestone remove': shape({ milestone: 'object' }),- show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array' }),+ show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array', thread: 'array' }),status: shape({ me: 'object', mine: 'array', stats: 'object', reviewQueue: 'object', unread: 'number' }),doctor: shape({ problems: 'array' }),inbox: shape({ shouts: 'array' }),@@ -37,6 +37,7 @@ export const JSON_SHAPES = {log: shape({ events: 'array' }),add: shape({ item: 'object' }),edit: shape({ item: 'object' }),+ fact: shape({ item: 'number', fact: 'object' }),escalate: shape({ id: 'number', from: 'string', to: 'string' }),run: shape({ messages: 'array' }),sweep: shape({ messages: 'array' }),diff --git a/src/machine.js b/src/machine.jsindex d93cce97..f3933b9b 100644--- a/src/machine.js+++ b/src/machine.js@@ -10,7 +10,7 @@*//** Executable move semantics; bump once per release after a released move's meaning changes [H16]. */-export const ENGINE_VERSION = 2;+export const ENGINE_VERSION = 3;/** @typedef {'agent' | 'coordinator' | 'clock'} Role */diff --git a/src/relay-presentation.js b/src/relay-presentation.jsindex 276fbe8e..9b98342c 100644--- a/src/relay-presentation.js+++ b/src/relay-presentation.js@@ -10,7 +10,11 @@ import { projectState } from './serve.js';/** Capture spec, doctrine, config and board presentation without sending plaintext to a relay. */export function relayPresentation(root) {- return { version: 1, state: projectState(root), config: loadConfig(root) };+ const state = projectState(root);+ const info = repoInfo(root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));+ try { return { version: 1, state: store.projectItemThreads(board, state), config: loadConfig(root) }; }+ finally { store.closeBoard(board); }}/** Notice presentation-only changes, including a spec or doctrine edit without a board move. */diff --git a/test/api.test.js b/test/api.test.jsindex a1a9cb49..23158643 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -283,6 +283,7 @@ test('[A1] command results match the catalog across roots and subcommands', () =const added = json(box, repo, 'add', ['coordinator', 'API item', '--specs', 'G1', '--criterion', 'the API item is verified', '--check', 'true']);assert.equal(added.item.item_id, 1);+ json(box, repo, 'fact', ['1', 'note', 'API fact']);json(box, repo, 'edit', ['1', '--criterion', 'the edited API item is verified', '--check', 'true']);json(box, repo, 'show', ['1']);json(box, repo, 'list', ['--all']);diff --git a/test/thread.test.js b/test/thread.test.jsnew file mode 100644index 00000000..540b9d1d--- /dev/null+++ b/test/thread.test.js@@ -0,0 +1,348 @@+/** Exercise typed item threads and deterministic replication on isolated SQLite boards [B29,B30,B31,B32]. */+import assert from 'node:assert/strict';+import { execFileSync, spawnSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { serveApi } from '../src/api.js';+import { main } from '../src/cli.js';+import { relayPresentation } from '../src/relay-presentation.js';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { exportBoard, importBoard } from '../src/exchange.js';++const HOUR = 3_600_000;+const SHA = 'a'.repeat(40);+const KINDS = ['capture', 'measurement', 'note', 'diff', 'decision', 'rejection', 'supersession', 'root-cause'];++/** Open an isolated board with stable time and registered actors; close it with the test. */+function fixture(t) {+ let at = Date.parse('2026-10-08T00:00:00.000Z');+ const clock = { now: () => new Date(at), advance: (ms) => { at += ms; } };+ const board = store.openBoard(':memory:', clock);+ t.after(() => store.closeBoard(board));+ store.register(board, { lane: 'coordinator', path: '/repo' });+ store.register(board, { lane: 'web', path: '/repo-web-1' });+ store.register(board, { lane: 'web', path: '/repo-web-2' });+ store.register(board, { lane: 'api', path: '/repo-api-1' });+ return { board, clock };+}++/** Add a web item and optionally hold it under a deterministic two-hour lease. */+function item(board, title = 'Threaded item', holder = null) {+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title });+ if (holder) store.claim(board, id, {+ agentId: holder, lane: 'web', leaseMs: 2 * HOUR,+ freeze: (found) => ({ text: found.item_title, digest: `digest:${found.item_title}` }),+ });+ return id;+}++test('[B29] every fact kind is stamped, and nonholders can append observations', (t) => {+ const { board } = fixture(t);+ const id = item(board, 'All fact kinds', 'web-1');+ const observations = ['capture', 'measurement', 'note', 'diff'];+ for (const kind of observations) {+ const fact = store.appendFact(board, id, { agentId: 'web-2', kind, text: `evidence: ${kind}`, factId: `observation-${kind}` });+ assert.deepEqual({ id: fact.id, kind: fact.kind, text: fact.text, by: fact.by, at: fact.at, ref: fact.ref, supersedes: fact.supersedes }, {+ id: `observation-${kind}`, kind, text: `evidence: ${kind}`, by: 'web-2', at: '2026-10-08T00:00:00.000Z', ref: null, supersedes: null,+ });+ }+ for (const kind of ['decision', 'rejection', 'supersession', 'root-cause']) {+ assert.equal(store.appendFact(board, id, { agentId: 'web-1', kind, text: `judgement: ${kind}`, factId: `judgement-${kind}` }).kind, kind);+ }+ assert.deepEqual(store.itemThread(board, id).filter((entry) => entry.type === 'fact').map(({ kind }) => kind), KINDS);+ const before = store.events(board).length;+ assert.throws(() => store.appendFact(board, id, { agentId: 'absent-agent', kind: 'note', text: 'unknown author' }), { code: 'NO_AGENT' });+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-2', kind: 'guess', text: 'unsupported label' }), { code: 'BAD_FACT_KIND' });+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-2', kind: 'note', text: ' ' }), { code: 'EMPTY_FACT' });+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-2', kind: 'note', text: 'duplicate identity', factId: 'observation-note' }), { code: 'BAD_FACT_ID' });+ assert.equal(store.events(board).length, before, 'invalid facts create no partial events');+ const closed = item(board, 'Closed item');+ store.withdraw(board, closed, { agentId: 'coordinator', reason: 'kept for historical evidence' });+ assert.equal(store.appendFact(board, closed, { agentId: 'api-1', kind: 'note', text: 'history can still receive evidence' }).by, 'api-1');+ assert.equal(store.getItem(board, closed).item_status, 'withdrawn', 'a fact can be appended to a closed item without reopening it');+});++test('[B30] judgements and corrections require the live holder or coordinator, including after lease expiry', (t) => {+ const { board, clock } = fixture(t);+ const id = item(board, 'Guarded item', 'web-1');+ const observation = store.appendFact(board, id, { agentId: 'web-2', kind: 'note', text: 'shared evidence', factId: 'guard-evidence' });+ for (const kind of ['decision', 'rejection', 'supersession', 'root-cause']) {+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-2', kind, text: 'unauthorized judgement', factId: `denied-${kind}` }), { code: 'FACT_JUDGEMENT' });+ }+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-2', kind: 'note', text: 'unauthorized correction', supersedes: observation.id, factId: 'denied-correction' }), { code: 'FACT_JUDGEMENT' });+ assert.equal(store.appendFact(board, id, { agentId: 'coordinator', kind: 'decision', text: 'coordinator judgement', factId: 'coordinator-decision' }).by, 'coordinator');+ clock.advance(2 * HOUR + 1);+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-1', kind: 'decision', text: 'expired-holder judgement', factId: 'expired-decision' }), { code: 'FACT_JUDGEMENT' });+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-1', kind: 'note', text: 'expired-holder correction', supersedes: observation.id, factId: 'expired-correction' }), { code: 'FACT_JUDGEMENT' });+});++test('[B31] fact events are append-only, corrections retain both facts, and supersession stays on its item', (t) => {+ const { board } = fixture(t);+ const id = item(board, 'Correction chain', 'web-1');+ const otherId = item(board, 'Other item');+ const original = store.appendFact(board, id, { agentId: 'web-2', kind: 'measurement', text: 'first value', factId: 'correction-original' });+ const first = store.appendFact(board, id, { agentId: 'web-1', kind: 'supersession', text: 'corrected once', supersedes: original.id, factId: 'correction-one' });+ const second = store.appendFact(board, id, { agentId: 'web-1', kind: 'supersession', text: 'corrected twice', supersedes: first.id, factId: 'correction-two' });+ assert.deepEqual(store.itemThread(board, id).filter((entry) => entry.type === 'fact').map(({ id: factId, text, supersedes }) => ({ id: factId, text, supersedes })), [+ { id: original.id, text: 'first value', supersedes: null },+ { id: first.id, text: 'corrected once', supersedes: original.id },+ { id: second.id, text: 'corrected twice', supersedes: first.id },+ ]);+ assert.throws(() => store.appendFact(board, otherId, { agentId: 'coordinator', kind: 'supersession', text: 'cross-item correction', supersedes: original.id, factId: 'cross-item' }), { code: 'NO_FACT' });+ assert.throws(() => board.db.prepare("UPDATE event SET event_detail = '{}' WHERE event_kind = 'fact'").run(), /append-only|immutable|event/i);+ assert.throws(() => board.db.prepare("DELETE FROM event WHERE event_kind = 'fact'").run(), /append-only|immutable|event/i);+ assert.equal(store.itemThread(board, id).filter((entry) => entry.type === 'fact').length, 3);+});++test('[B32] fact references require a full SHA and a safe positive ascending line range', (t) => {+ const { board } = fixture(t);+ const id = item(board, 'Bound evidence');+ const fact = store.appendFact(board, id, {+ agentId: 'web-1', kind: 'diff', text: 'lines changed', ref: `src/board.js:12-30@${SHA.toUpperCase()}`, factId: 'full-ref',+ });+ assert.deepEqual(fact.ref, { path: 'src/board.js', start: 12, end: 30, commit: SHA });+ for (const ref of [`src/board.js:12@${SHA.slice(0, 7)}`, `src/board.js:0@${SHA}`, `src/board.js:9-4@${SHA}`, `../board.js:1@${SHA}`, `/tmp/board.js:1@${SHA}`]) {+ assert.throws(() => store.appendFact(board, id, { agentId: 'web-1', kind: 'note', text: 'bad ref', ref, factId: `bad-${ref.replaceAll(/[^A-Za-z0-9]/gu, '-')}` }), { code: 'BAD_FACT_REF' }, ref);+ }+});++test('[B29,B31,B32] itemThread merges moves and facts in append order with exact ids, stamps and text', (t) => {+ const { board, clock } = fixture(t);+ const id = item(board, 'Ordered thread');+ const beforeClaim = store.events(board, { itemId: id }).at(-1);+ clock.advance(1_000);+ store.claim(board, id, {+ agentId: 'web-1', lane: 'web', leaseMs: 2 * HOUR,+ freeze: (found) => ({ text: found.item_title, digest: `digest:${found.item_title}` }),+ });+ const claimEvent = store.events(board, { itemId: id }).at(-1);+ clock.advance(1_000);+ const fact = store.appendFact(board, id, { agentId: 'web-2', kind: 'capture', text: 'first line\nsecond line stays', factId: 'ordered-fact' });+ clock.advance(1_000);+ store.release(board, id, 'web-1');+ const releaseEvent = store.events(board, { itemId: id }).at(-1);+ const thread = store.itemThread(board, id);+ assert.deepEqual(thread.map((entry) => entry.type === 'fact' ? `fact:${entry.id}` : `move:${entry.kind}`), [+ `move:${beforeClaim.event_kind}`, `move:${claimEvent.event_kind}`, `fact:${fact.id}`, 'move:release',+ ]);+ assert.deepEqual(thread[2], {+ type: 'fact', id: 'ordered-fact', eventId: fact.eventId, kind: 'capture', text: 'first line\nsecond line stays',+ by: 'web-2', at: '2026-10-08T00:00:02.000Z', ref: null, supersedes: null,+ });+ assert.equal(thread[0].eventId, beforeClaim.event_id);+ assert.equal(thread[1].eventId, claimEvent.event_id);+ assert.equal(thread[3].eventId, releaseEvent.event_id);+ assert.ok(thread.every((entry, index) => index === 0 || thread[index - 1].eventId < entry.eventId));+});++test('[B31,B32] native export and import preserve every fact in the item thread', (t) => {+ const { board } = fixture(t);+ const id = item(board, 'Portable thread', 'web-1');+ const first = store.appendFact(board, id, { agentId: 'web-2', kind: 'note', text: 'original', factId: 'portable-original' });+ store.appendFact(board, id, { agentId: 'web-1', kind: 'supersession', text: 'corrected', supersedes: first.id, factId: 'portable-correction' });+ const restored = store.openBoard(':memory:');+ t.after(() => store.closeBoard(restored));+ importBoard(restored, exportBoard(board));+ assert.deepEqual(store.itemThread(restored, id), store.itemThread(board, id));+ assert.deepEqual(exportBoard(restored), exportBoard(board));+});++test('[B29,B31,H16] engine fact replay uses move ids, retries once, and keeps corrections identical across replicas', (t) => {+ const clock = { now: () => new Date('2026-10-08T00:00:00.000Z') };+ const left = store.openBoard(':memory:', clock);+ const right = store.openBoard(':memory:', clock);+ t.after(() => { store.closeBoard(left); store.closeBoard(right); });+ for (const replica of [left, right]) {+ store.register(replica, { lane: 'coordinator', path: '/replicated-repo' });+ store.register(replica, { lane: 'web', path: '/replicated-repo-web-1' });+ const id = store.addItem(replica, { by: 'coordinator', lane: 'web', title: 'Replicated thread' });+ assert.equal(id, 1);+ replica.db.prepare('UPDATE board_meta SET meta_value = ? WHERE meta_key = ?').run('b'.repeat(32), 'board_id');+ }+ const id = 1;+ const baselineEvents = store.events(left).length;+ const first = prepareEngineMove(left, 'appendFact', [id, { agentId: 'web-1', kind: 'note', text: 'replicated original' }], { id: 'fact-envelope-one' });+ assert.equal(first.engine, ENGINE_VERSION);+ const firstOptions = { sequence: 1, at: '2026-10-08T00:00:10.000Z' };+ const firstLeft = applyEngineMove(left, first, firstOptions);+ assert.deepEqual(applyEngineMove(right, first, firstOptions), firstLeft);+ assert.equal(firstLeft.result.id, first.id);+ assert.equal(store.events(left).length, baselineEvents + 1);+ assert.deepEqual(applyEngineMove(left, first, firstOptions), firstLeft, 'retry returns its receipt');+ assert.equal(store.events(left).length, baselineEvents + 1, 'retry creates no duplicate event');+ const correction = prepareEngineMove(left, 'appendFact', [id, {+ agentId: 'coordinator', kind: 'supersession', text: 'replicated correction', supersedes: first.id,+ }], { id: 'fact-envelope-two' });+ assert.equal(correction.engine, ENGINE_VERSION);+ const secondOptions = { sequence: 2, at: '2026-10-08T00:00:11.000Z' };+ const correctedLeft = applyEngineMove(left, correction, secondOptions);+ assert.deepEqual(applyEngineMove(right, correction, secondOptions), correctedLeft);+ const facts = store.itemThread(left, id).filter((entry) => entry.type === 'fact');+ assert.deepEqual(facts.map(({ id: factId, text, supersedes }) => ({ id: factId, text, supersedes })), [+ { id: first.id, text: 'replicated original', supersedes: null },+ { id: correction.id, text: 'replicated correction', supersedes: first.id },+ ]);+ assert.deepEqual(store.itemThread(right, id), store.itemThread(left, id));+ assert.equal(store.events(left).length, baselineEvents + 2);+ assert.deepEqual(exportBoard(right), exportBoard(left));+});++/** Exercise facts through the private CLI and local HTTP API against one real isolated repo [B29,B30,B31,B32,A2]. */++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');++/** Quote one path literally for the private worktree's pullboard shim. */+function shellWordHttp(value) {+ return "'" + value.replace(/'/g, "'\\''") + "'";+}++/** Build a committed project in a private HOME, with CLI calls isolated from personal Git state. */+function threadHttpFixture(t) {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-thread-http-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const root = join(dir, 'repo');+ const bin = join(dir, 'bin');+ mkdirSync(root);+ mkdirSync(bin);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWordHttp(process.execPath)} ${shellWordHttp(BIN)} "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const env = {+ ...process.env,+ HOME: join(dir, 'home'),+ PULLBOARD_HOME: join(dir, 'home'),+ PATH: bin + ':' + process.env.PATH,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Thread HTTP Fixture',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Thread HTTP Fixture',+ GIT_COMMITTER_EMAIL: '[email protected]',+ };+ mkdirSync(env.HOME);+ /** Run Git only in this disposable repository and return trimmed output. */+ const git = (...args) => execFileSync('git', args, { cwd: root, env, stdio: 'pipe', encoding: 'utf8' }).trim();+ /** Invoke the actual CLI with the private environment. */+ const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });+ /** Decode one successful JSON command. */+ function cli(cwd, ...args) {+ const result = run(cwd, ...args, '--json');+ assert.equal(result.status, 0, `${args.join(' ')}: ${result.stderr}${result.stdout}`);+ return JSON.parse(result.stdout);+ }+ git('init', '-q', '-b', 'main');+ cli(root, 'init');+ const configFile = join(root, 'pullboard.json');+ const config = JSON.parse(readFileSync(configFile, 'utf8'));+ writeFileSync(configFile, JSON.stringify({ ...config, gate: 'true', lanes: { app: { owns: ['app/'] } } }));+ writeFileSync(join(root, 'SPEC.md'), '# Thread fixture\n\n## Goals\n- G1 [approved, must] Keep item evidence. | gate: true\n');+ writeFileSync(join(root, 'thread-fixture.txt'), 'committed reference target\n');+ git('add', '-A');+ git('commit', '-q', '-m', 'chore: create private thread fixture');+ return { dir, root, env, git, cli, run, commit: git('rev-parse', 'HEAD') };+}++/** Start a real authenticated API for only this test's fixture board. */+async function threadHttpBox(t) {+ const box = threadHttpFixture(t);+ const api = await serveApi({ runCommand: main, projects: () => [{ root: box.root, name: 'Thread HTTP fixture' }] });+ t.after(() => api.close());+ const url = new URL(api.url);+ const key = url.searchParams.get('k');+ const catalogResponse = await fetch(url.origin + '/api/v1/boards', { headers: { 'x-pullboard-key': key } });+ assert.equal(catalogResponse.status, 200);+ const catalog = await catalogResponse.json();+ const id = catalog.boards[0].id;+ /** Send an authenticated JSON request and return its HTTP status and decoded body. */+ async function call(path, value) {+ const response = await fetch(url.origin + path, {+ method: value === undefined ? 'GET' : 'POST',+ headers: { 'x-pullboard-key': key, ...(value === undefined ? {} : { 'content-type': 'application/json' }) },+ ...(value === undefined ? {} : { body: JSON.stringify(value) }),+ });+ return { status: response.status, document: await response.json() };+ }+ return { ...box, api, url, key, boardId: id, path: `/api/v1/boards/${id}`, call };+}++test('[B29,B30,B31,B32,A2] CLI and HTTP facts share stamped threads, guard judgements, and preserve full refs and literal text', async (t) => {+ const box = await threadHttpBox(t);+ const holder = box.cli(box.root, 'worktree', 'app');+ const observer = box.cli(box.root, 'worktree', 'app');+ const added = await box.call(box.path + '/moves', { verb: 'add', args: { lane: 'app', title: 'Evidence item', criterion: 'thread stays readable', specs: 'G1' } });+ assert.equal(added.status, 200);+ const id = added.document.result.item.item_id;+ const claim = await box.call(box.path + '/moves', { verb: 'claim', item: id, agent: holder.agent });+ assert.equal(claim.status, 200);+ assert.equal(claim.document.event.event_kind, 'claim');++ const rawRef = `thread-fixture.txt:1@${box.commit}`;+ const shortRef = await box.call(box.path + '/moves', {+ verb: 'fact', item: id, agent: observer.agent,+ args: { kind: 'note', text: 'short reference refused', ref: `thread-fixture.txt:1@${box.commit.slice(0, 7)}` },+ });+ assert.equal(shortRef.status, 409);+ assert.equal(shortRef.document.error.code, 'BAD_FACT_REF');+ const observation = await box.call(box.path + '/moves', {+ verb: 'fact', item: id, agent: observer.agent,+ args: { kind: 'note', text: '--literal evidence', ref: rawRef },+ });+ assert.equal(observation.status, 200);+ assert.equal(observation.document.event.event_kind, 'fact');+ assert.equal(observation.document.event.event_by, observer.agent);+ assert.equal(observation.document.result.fact.text, '--literal evidence');+ assert.equal(observation.document.version, 1);+ assert.equal(observation.document.result.version, 1);+ assert.equal(observation.document.result.fact.by, observer.agent);+ assert.equal(observation.document.result.fact.at, observation.document.event.event_at);+ assert.equal(observation.document.result.fact.eventId, observation.document.event.event_id);+ assert.match(observation.document.result.fact.id, /^[A-Za-z0-9_-]+$/u);+ assert.deepEqual(observation.document.result.fact.ref, {+ path: 'thread-fixture.txt', start: 1, end: 1, commit: box.commit,+ });+ 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 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 correctionRun = box.run(holder.path, 'fact', String(id), 'supersession', '--supersedes', observationId, '--json', '--', 'corrected evidence');+ assert.equal(correctionRun.status, 0, correctionRun.stderr);+ const correction = JSON.parse(correctionRun.stdout);+ assert.equal(correction.item, id, 'the holder CLI command returns its versioned result');+ assert.equal(correction.fact.text, 'corrected evidence');+ const holderCorrection = correction.fact;+ assert.equal(holderCorrection.kind, 'supersession');+ assert.equal(holderCorrection.by, holder.agent);++ const terminalShow = box.run(box.root, 'show', String(id));+ assert.equal(terminalShow.status, 0, terminalShow.stderr);+ const oldText = `fact note ${observationId}: --literal evidence`;+ const newText = `fact supersession ${holderCorrection.id} (supersedes ${observationId}): corrected evidence`;+ const timeline = terminalShow.stdout.slice(terminalShow.stdout.indexOf('thread:'));+ assert.ok(timeline.indexOf(' add') >= 0 && timeline.indexOf(' claim') > timeline.indexOf(' add'), 'show includes moves in order');+ assert.ok(timeline.indexOf(oldText) > timeline.indexOf(' claim'), 'facts follow their earlier moves in one timeline');+ assert.ok(terminalShow.stdout.indexOf(oldText) >= 0, 'show prints the original literal-dash fact');+ assert.ok(terminalShow.stdout.indexOf(newText) > terminalShow.stdout.indexOf(oldText), 'show prints both corrections in append order');+ 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);+ 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 })), [+ { id: observationId, text: '--literal evidence', supersedes: null },+ { id: holderCorrection.id, text: 'corrected evidence', supersedes: observationId },+ ]);+});