Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: a truth layer you can correct and time-travel (v1.77.0) (#242)

Serg Eroshe3afb94a5753f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 5d7ef4ce..a68be85c 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.76.0",
+ "version": "1.77.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 062e7ba9..4610d18f 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.76.0",
+ "version": "1.77.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1ebc2cf1..60592619 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,7 +46,9 @@ jobs:
validate:
name: validate
runs-on: ubuntu-26.04
- timeout-minutes: 20
+ # The full suite outgrew twenty minutes on a slow runner; the bound is
+ # there so a hung run cannot hold a runner for GitHub's six-hour default.
+ timeout-minutes: 30
steps:
- name: Check out repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 97220ec5..a8d89b11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,38 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.77.0] - 2026-10-08
+
+Open Second Brain now keeps its claim ledger in time and correctable: a claim can carry a validity window frozen from its source at ingest, the events recall reads the ledger over an assertion-time slice, an agent's stated claims commit only when they anchor in their assertion text, and two same-slot claims with disjoint windows stand in a succession channel instead of a conflict. One correct verb discovers a correction's blast radius and retires what it touches, and every serving surface serves a retired-but-serveable record only beside its resolved, readable chain-tip correction, fail-closed. The deep relational recall arm runs under width budgets with hub skipping, walks entity co-occurrence bridges, reports per-node path provenance gated at the caller's reach, and never lets a traversal-only row outrank what the lanes matched.
+
+### Added
+
+- **Validity windows on the claim ledger.** A claim event can carry optional `valid_from` / `valid_until` (half-open `[valid_from, valid_until)`, a bare ISO date or a canonical UTC timestamp; bare dates day-snap, relative phrases never parse, and a windowless line serializes byte-identically to before, so an old binary reads new lines on the assertion-time axis it knows). `o2b brain truth ingest` and the `brain_truth` `ingest` operation accept the window (`--valid-from`/`--valid-until`; a malformed or inverted bound is refused by name, as `INVALID_PARAMS` on MCP and exit 2 on the CLI), and with the flags absent each open bound is resolved from the source record's frontmatter `valid_from` / `valid_until` and frozen verbatim onto the event at ingest - explicit input wins outright, resolution is per bound, an unreadable or windowless source stores a windowless event, a malformed source bound resolves as absent so it can never refuse an ingest, and mtime is never consulted (an assertion-time proxy is not validity).
+- **Windowed truth events recall.** The `brain_truth` `events` operation and `o2b brain truth events` recall a slice of the ledger through one shared report, so shape, ascending-`ts` ordering, gating and paging cannot drift between the surfaces. `entity` filters by canonical name (display spellings accepted), `since` / `until` bound the assertion time through the shared time-range grammar (a claim's validity window is a different axis and rides on the rows verbatim; `since` floors into its second so tail-following pagination re-sees a boundary event but never skips one), and paging defaults to 200 rows under a hard 1,000-row cap. Every row passes the same owner/reach gate `brain_claims` asks.
+- **Grounded agent-stated claims.** The `brain_truth` `state` operation and `o2b brain truth state` commit an agent's stated claims - `subject` / `relation` / `object` plus the assertion `text` they came from - into the ledger. The payload boundary refuses a whole call (unknown relation, missing text or source, malformed ts, empty agent) before anything is written, and the anchoring verdict is per claim: subject and object must both anchor in the text through the quality-gated match-form kernel, so a grounded claim commits as an `agent_stated` ledger event while an ungrounded one is reported back with machine reason codes. The extractor tag is annotation only - conflict detection reads the ledger exactly as before.
+- **A succession channel beside conflicts.** Two same-slot claims with present, non-intersecting validity windows classify as successions (the predecessor is the representative claim whose window closes first) and never as conflicts; intersecting windows or any windowless claim keeps the assertion-time contest rule verbatim, and an expired window never suppresses contestation on its own. The channel is a separate, presence-gated field on the truth state - never a conflict kind - so `ask_user` semantics, hygiene findings and conflict priority are structurally unreachable from it, and windowless output stays byte-identical.
+- **One correct verb.** `brain_lifecycle` gains the `correct` action and `o2b brain lifecycle correct <target>` the matching subcommand. The dry run - the default - discovers the blast radius within the caller's reach and writes nothing: the claim-graph closure over replaced and contesting records, a wikilink mention scan, and the same-entity/aspect ledger claims, each row reach-gated by its source record. `--apply` retires each target through the end-state policy - validity closes at the explicit `--window-end` when the correction is time-scoped, else at the correction instant, while `--flatly-wrong` tombstones instead, for a claim that was never true - appends ledger correction events under the corrected record's own source (a same-source value change reads as self-correction in the fold, never a conflict), retargets mentions with per-write failures carried (the log and the receipt lines are testimony and never rewritten), and issues bundle-correlated receipts (`correction_bundle:<id>` in `evidence_triggers`, the existing `supersede` / `tombstone` reason codes). Replay converges: an already-applied correction is a no-op with `appended: false`. A target the caller may not read is refused as missing before anything is written.
+- **Width budgets for deep relational recall.** The relational arm's traversal runs under width budgets - 8 seeds, 4 expansions per node, 16 nodes in total, and a node whose walked-edge degree exceeds 12 is reached but not expanded - and abandons the frontier deterministically once the composite recall deadline fires, keeping every node already reached. Each budget is a named constant overridable through an `OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_*` environment variable or its `search_traversal_*` config key, and an invalid value is refused naming the key in force.
+- **Entity co-occurrence bridges.** Two documents that mention the same normalized entity gain one bridge edge over the index's `chunk_entities`, so the walk follows co-occurrence beside the declared typed edges (labelled `entity`, machine-derived, never part of the query edge-type vocabulary). On by default, off through `OPEN_SECOND_BRAIN_SEARCH_ENTITY_BRIDGES` or `search_entity_bridges_enabled`; the budgets, the transport reach and the bridges are wired through to the production search call site, byte-identical with the arm disabled.
+- **Per-node path provenance in the retrieval trail.** A relational row's trail entry carries the ordered path of documents that reached it, each node gated at the caller's reach and owner scope, so the trail names only pages the caller can read and the reason string renders the walk shape alone.
+- **Relational-only rows stay below the organic tail.** A row the traversal found and no lane matched is admitted below the organic tail in the fused order, and a structural rung makes it impossible for a relational-only row to outrank a deep keyword direct hit: the traversal widens the pool, it never outranks what the lanes matched. With the arm off, the rung never fires.
+
+### Changed
+
+- **A retired record is served only beside its correction.** A validity-closed predecessor stays serveable inside its window and a superseded non-tip stays readable; only a tombstoned record drops out of recall everywhere. Every surface that serves memory - the search pool after ranking, recall by topic, context packs, the `Brain/active.md` digest and the dream scan - applies one rule to a serveable retired row: it is served only beside its chain-tip correction, resolved and readable at the caller's reach, and dropped otherwise. The drop is fail-closed: a chain walk that dangles, cycles, stops at the depth cap or answers the row itself is unresolved, and a correction pulled in beside its predecessor re-runs the caller's full filter set - status, visibility scope, agent scope, reach, and the property, degree and composite filters - because a successor the caller could not read on its own must not enter through the correction door. A pulled-in correction enters as a link-type row carrying a share of its predecessor's score, provenance-stamped `correction_for:`. Records with no pointer, and pools with neither pull-in nor retired row, are byte-identical to before.
+- **Docs:** the README gains the claim-ledger and corrections capability bullets and the deep-relational-recall note with the budget keys and defaults, and `docs/architecture.md` states the serve-with-correction rule and the agent-scope matrix's new recipe row (234 recipes over 101 tools). The plugin mirrors follow.
+
+### Fixed
+
+- **Withheld rows no longer surface as counts.** The events account covers only the rows that passed the gate (`total` is the gated count and no withheld key exists beside it), the relational path provenance carries the readable document ids alone, and its reason string renders the walk shape only, so a filtered answer is byte-identical to the answer over a vault that never held the withheld rows.
+- **A source page the caller cannot read answers exactly like an absent one.** The truth `ingest` and `state` window resolution now runs through the caller's readable predicate: an unreadable source stores a windowless claim with no validity keys and a byte-identical response. The CLI verb runs at operator reach and resolves ungated.
+- **Extensionless page references resolve only to files that exist.** The .md-twin resolution no longer answers with the twin when neither candidate exists and no longer accepts a directory as a page, so a slug convention in a log payload no longer drops the rows carrying it and the `Brain/inbox` directory no longer resolves as a page; in the events gate, a slash-bearing extensionless spelling resolves through the same first-existing rule, so both spellings of one page answer as one.
+- **Slot claims gate on the extension-bearing source path.** The correct verb's claims gate was asked over a fenced or extensionless path spelling it could never answer readable, so in-reach claims dropped from a remote caller's blast radius; the gate now hears the same path shape as the sibling callers, and a source naming no page under its literal spelling stays withheld.
+- **The correct verb validates its window end before writing.** A malformed `--window-end` is refused with the same check the ledger append boundary applies - a bare ISO date or a canonical UTC instant - before anything is written, including the frontmatter-only correction that appends no ledger event.
+- **The coupling tip is probed through the caller's full filter set.** With the opt-in property, degree or composite-scope filters active, a correction could pass the coupling verdict and then fall to the pool's re-filter, leaving its predecessor served bare; the tip candidate is now probed through the same pipeline the re-filter runs, and a tip the probe drops counts as unresolved, so the predecessor drops with it.
+- **A self-pointing chain walk is unresolved.** A blocked or stale `superseded_by` index edge left the post-rank walk no first hop and answered the start page as its own chain tip, the one corner where the serve-with-correction coupling failed open; a walk tip that is not distinct from the start page now classifies as unresolved and the retired row drops.
+- **Malformed validity windows answer as invalid params.** A malformed or inverted `valid_from` / `valid_until` answers `INVALID_PARAMS` on MCP and exit 2 on the CLI like every sibling mistyped input, and a stated-claims payload with a malformed ts or an empty agent is refused whole before the first write.
+
## [1.76.0] - 2026-10-08
Open Second Brain now keeps its search index current without a scheduler: a search or a session start that finds the index more than a minute old answers from it as it is and starts one low-priority background incremental run, so the next read sees the current vault. Nothing stays resident and nothing runs while no agent works. Two indexer changes make those frequent runs cheap: a run that changed no document writes almost nothing, and a changed document rewrites only the chunks that changed, so an edit to a 1 MB daily log costs about 0.2 MB of writes instead of about 9 MB.
@@ -8309,6 +8341,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.77.0]: https://github.com/itechmeat/open-second-brain/compare/v1.76.0...v1.77.0
[1.76.0]: https://github.com/itechmeat/open-second-brain/compare/v1.75.0...v1.76.0
[1.75.0]: https://github.com/itechmeat/open-second-brain/compare/v1.74.1...v1.75.0
[1.74.1]: https://github.com/itechmeat/open-second-brain/compare/v1.74.0...v1.74.1
diff --git a/README.md b/README.md
index b57a6ca8..056be799 100644
--- a/README.md
+++ b/README.md
@@ -101,6 +101,8 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
- **Search.** Keyword search with an optional semantic lane, result explanations, recall profiles and compact cards: [search CLI](docs/cli-reference.md#search), [ranking](docs/how-it-works.md#full-text-search).
- **Session recall.** Import agent transcripts already on disk and search them: [session logs](docs/cli-reference.md#session-logs-this-machine-already-has-since-v1500).
- **Hygiene.** `o2b brain hygiene scan` finds contested, duplicate, stale and unused memories; `apply` runs only the findings you pick: [maintenance](docs/cli-reference.md#maintenance-and-operator-surfaces).
+- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes: [entity truth CLI](docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).
+- **Corrections.** `o2b brain lifecycle correct <target>` reports a correction's blast radius and retires the affected records - validity-closed by default, tombstoned with `--flatly-wrong`, dry run by default and `--apply` to write. A retired record that recall can still serve is served only beside its correction, never alone: [belief lifecycle CLI](docs/cli-reference.md#belief-lifecycle-and-decision-memory-since-v1330).
- **Sharing and backup.** Knowledge packs export a chosen subset; `o2b brain bank-export` writes a one-file backup bundle: [knowledge packs](docs/cli-reference.md#knowledge-packs).
- **Today view and note markers.** `o2b brain today`, `@osb loop` and `@osb set` markers: [Brain CLI](docs/cli-reference.md#brain-observing-memory).
- **Self-inspection.** `o2b version`, `o2b install --friction` and `o2b state status` report what is installed and where state lives: [CLI reference](docs/cli-reference.md#core).
@@ -110,10 +112,11 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
- **Semantic search:** an embedding provider plus `sqlite-vec`; the `embeddings-setup` skill walks through it: [`skills/embeddings-setup/SKILL.md`](skills/embeddings-setup/SKILL.md).
- **Decision models:** a typed judgment model that can rerank search and filter candidates, off by default per use: [`docs/decision-models.md`](docs/decision-models.md).
+- **Deep relational recall:** a fourth search arm over typed links, off by default. Its traversal runs under width budgets - 8 seeds, 4 edges per node, 16 nodes in total, and a hub above 12 walked edges is reached but not expanded - each overridable through an `OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_*` environment variable or a `search_traversal_*` config key; entity co-occurrence bridges join the walk by default and switch off separately (`OPEN_SECOND_BRAIN_SEARCH_ENTITY_BRIDGES`): [retrieval quality](docs/cli-reference.md#retrieval-quality-and-context-delivery-since-v1370).
## What is new
-1.76.0 keeps the search index current without a scheduler. A search or a session start that finds the index more than a minute old answers from it as it is and starts one low-priority background run, so the next read sees the current vault; nothing stays resident, and nothing runs while no agent works. A changed note now rewrites only the parts of the index that changed, so appending to a large daily log costs a fraction of what it did, and `o2b search status` shows how fresh the index is. Every release is described in the [CHANGELOG](CHANGELOG.md).
+1.77.0 makes the claim ledger time-aware and correctable. A claim can carry a validity window (`o2b brain truth ingest --valid-from`/`--valid-until`, frozen from the source record when the flags are absent), `o2b brain truth events` recalls the ledger over an assertion-time slice, `o2b brain truth state` grounds an agent's stated claims with a per-claim anchoring verdict, and `o2b brain lifecycle correct` retires what a correction touches - dry run by default, with a retired record that recall can still serve answered only beside its resolved, readable correction, never alone. The deep relational recall arm now runs under width budgets with hub skipping and entity co-occurrence bridges. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/architecture.md b/docs/architecture.md
index a31befef..caca5ad1 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -417,14 +417,29 @@ implemented: reporting how many rows `fail` would withhold is itself the
disclosure, so `warn`'s observability here is the `owner:` stamp appearing on
new files, not a count in any response.
+A retirement does not always hide a record. A validity-closed predecessor
+stays serveable inside its window and a superseded non-tip stays readable;
+only a tombstoned record drops out of recall everywhere. Every surface that
+serves memory - the search pool after ranking, recall by topic, context
+packs, the `Brain/active.md` digest and the dream scan - applies one rule to
+a serveable retired row: it is served only beside its chain-tip correction,
+resolved and readable at the caller's reach, and dropped otherwise. The drop
+is fail-closed, so a row whose correction is missing or out of reach is
+indistinguishable from an absent one, and a correction pulled in beside its
+predecessor passes the full filter set - status, visibility scope, agent
+scope, reach - because a successor the caller could not read on its own must
+not enter through the correction door. The predicate in
+`src/core/search/correction-coupling.ts` is the rule's only spelling; the
+surfaces differ in what they serve, never in what the rule says.
+
The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape
is the point rather than its size. One hundred and one classified tools carry
-233 call recipes - one per mode, view or operation, because one executed view
+234 call recipes - one per mode, view or operation, because one executed view
is not an executed classification. Every recipe runs TWICE against the same
two-owner fixture, once with the gate closed and once with it open, and the
classification decides what the open run must show: the 32 recipes classified
as reaching owner-taggable content must surface the marker with the gate off,
-which is what stops the closed run from passing vacuously. The other 201 carry
+which is what stops the closed run from passing vacuously. The other 202 carry
a claim of unreachability, and that claim is executed directly - the marker
must be absent even where nothing is hidden. The first version of this probe
asserted only the closed half, and 81 of its entries were driven against
diff --git a/docs/brainstorm/truth-correctable-time-aware/cli-output/consultant.md b/docs/brainstorm/truth-correctable-time-aware/cli-output/consultant.md
new file mode 100644
index 00000000..95eebd9d
--- /dev/null
+++ b/docs/brainstorm/truth-correctable-time-aware/cli-output/consultant.md
@@ -0,0 +1,59 @@
+### Variant 1: Five Narrow Independent Cards
+- **Approach**: Each card lands as the smallest correct version of itself with no shared new module and no cross-card sequencing: the ledger gains optional validity fields read only by a new succession channel; the windowed recall surface gains one additive response field; the correction sweep orchestrates existing primitives under today's retire-in-place semantics; agent-stated claims ground into the intake relation layer without touching the ledger; multi-hop recall deepens the existing relational arm over document typed edges only. Every cross-card decision is taken locally in the most conservative direction, so nothing shared changes and the cards can be built fully in parallel.
+ - Succession channel versus conflict kind: a separate successions channel beside the conflicts array in the policy layer, keyed only when both claims of a pair carry present non-overlapping windows; mixed or windowless pairs keep today's assertion-time behavior byte-identically; never a new conflict kind, so ask_user semantics, hygiene findings and priority ranking stay untouched. Precedence rule: validity governs only validity-versus-validity pairs; contestation stays assertion-keyed even for windowed pairs, an expired window never suppresses contestation on its own, and the assertion-time sibling consumers (collision, grounding score) stay assertion-keyed.
+ - Window defaults: explicit input only (CLI flags and declared optional ingest fields); no automatic resolution from source records, keeping ledger ingest self-contained.
+ - Correction record state and sweep atomicity: supersede/tombstone as today; the sweep is a deterministic fail-recorded sequence β€” dry-run discovery, per-record supersede, mention retargeting with apply:false then apply, per-record receipts correlated by a bundle id carried in evidence_triggers β€” with no record-state change and no write-batch extension.
+ - Agent-stated claims: they land in the intake relation layer, extending the declared-payload boundary with anchorEntities occurrence grounding and report-back verdicts; no extractor tag on ledger events this wave, so provenance-based conflict detection reduces to additive annotation over the claim-graph fields that already exist.
+ - Claim-chain recall: deferred. The arm deepens over document typed relations plus chunk_entities now; claim-edge composition is explicitly deferred until grounded object-entity linking exists.
+ - Windowed-slots response shape: an additive claim_events field beside the count-preserving events; slots and the global count untouched (superset reading); rows in stable ascending ts order with a named default limit; the SearchError-to-INVALID_PARAMS boundary lifted out of recall-tools into a shared wrapper; the schema description states that since/until filters assertion ts only.
+ - Multi-hop width caps: 8 seeds, 4 expansions per node, 16 total nodes as named constants with config override; a hub is a node whose walked-edge degree exceeds a threshold; traversal stays deadline-bounded; direct-hit precedence is not addressed this wave.
+ - Serve-with-correction invariant: stays search-pipeline-only and best-effort; relation polarity is hardened so a resolvable, readable successor is always pulled in beside a demoted predecessor; recall by topic, context-pack, active.md and dream keep the hide-or-annotate split.
+- **Trade-offs**:
+ - Pro: smallest blast radius per card; the byte-identical and ask_user invariants hold by construction because no shared code changes.
+ - Pro: full parallelism, no ordering constraints; each card reviews as one unit and can ship or slip alone.
+ - Con: the assertion-versus-validity axis is decided twice (windows card and windowing card) with real drift risk, and the precedence rule ends up implicit in two places instead of stated once.
+ - Con: the wave's two genuinely novel ideas are not delivered β€” the coupling guarantee remains best-effort and search-only, and recall still cannot answer transitive claim questions.
+ - Con: agent-stated claims never reach the ledger, so that card's headline (provenance-based conflict detection over ledger events) degrades to annotation, and the extractor column the claims view lacks stays missing.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Shared Temporal Kernel, Fully Coupled Wave
+- **Approach**: Build one shared time-axis kernel first β€” a single module owning window parsing (the existing strict grammars lifted together), the half-open interval test, and one explicit precedence rule β€” then land all five cards as consumers in the same release, including claim-edge traversal over the grounded linking the same wave introduces and a guaranteed cross-surface coupling predicate. Every cross-card decision is made exactly once, in the kernel or in one named consumer.
+ - Succession channel versus conflict kind: a separate successions channel; the precedence rule is a kernel property β€” classification keys on validity only when both claims of a pair carry present windows (non-overlapping present windows succeed; overlapping windows fall through to today's assertion-time contest rule); assertion time keeps governing contestation even for windowed pairs, an expired window never suppresses contestation on its own, and the sibling assertion-time consumers stay assertion-keyed and documented as such.
+ - Window defaults: explicit input wins; absent input, ingest resolves the window from the source record's event time using the existing rung order and stores the resolved value frozen, so scan time never reads the vault.
+ - Correction record state and sweep atomicity: validity-close is the default (the predecessor stays serveable inside its window, the only regime where serve-with-correction is non-trivial); tombstone only for flatly-wrong claims; chosen per target by whether the correction is time-scoped, and recorded in the receipt. A new write-batch op type lets discovery, retirement and mention retargeting commit as one validate-all-then-commit batch; the bundle id joins the receipts.
+ - Agent-stated claims: they land in both stores with a defined bridge β€” ledger events (subject as entity, relation-derived aspect, object as value) carrying the agent_stated extractor tag, plus intake relations for synchronous entity linking; grounding is per claim (grounded commits, ungrounded reported back β€” the first partial-commit lane in the subsystem); provenance changes priority, ordering and resolution hints only, never which pairs contest.
+ - Claim-chain recall: now. The arm walks the new claim/entity edges after the linking lands within the wave, under the same boundedness rules.
+ - Windowed-slots response shape: an additive claim_events field carrying validity fields verbatim beside the count-preserving events; the schema text pins ts-only filtering so the two temporal vocabularies stay unambiguous inside one response.
+ - Multi-hop width caps: one traversal-budget object (seeds, per-node, total, depth) shared with the existing traversal-lane precedent; hub by typed-edge degree; deadline-bounded; direct-hit precedence made structural (sub-neutral lane weight or admission below the last organic row) with a pinning test reconciled against the promote-never-sink rerank pin.
+ - Serve-with-correction invariant: one shared predicate applied at every serving surface (search pool and post-rank, topic recall, context-pack, active.md, dream); a retired claim is served only beside its correction; an unresolved or out-of-reach successor drops the retired row (fail-closed, so a withheld page stays indistinguishable from an absent one); appended correction content re-runs the full visibility, agent-scope and reach filter set, closing the recorded pulled-in-successor gap.
+- **Trade-offs**:
+ - Pro: every cross-card decision exists exactly once with one test seam; the wave delivers all five capabilities including the two novel invariants.
+ - Pro: the precedence rule, the grammars and the coupling invariant each have one home, so byte-identical gating is enforced in one place per concern.
+ - Con: largest blast radius β€” ledger schema, the write path, a new batch op type and five serving surfaces change in one release; a kernel bug touches every card at once.
+ - Con: strict internal ordering (kernel first, then linking, then claim-edge traversal) removes parallelism and makes the release hard to split if review finds problems.
+ - Con: first-of-kind mechanics concentrate here: the first partial-commit write lane, the first retirement op type in the write batch, and the first guaranteed serving predicate, all introduced together.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Two Sub-Suites over a Pinned Contract
+- **Approach**: Split the wave into two sequenced sub-suites joined by a small, test-pinned contract: sub-suite A (temporal truth) delivers the ledger validity fields, the windowed events surface, and grounded agent-stated claims as ledger events; sub-suite B (correction and recall) delivers the correct verb, the deepened traversal with direct-hit precedence, and the coupling invariant, consuming A only through the contract. The contract pins exactly the three genuinely cross-card decisions β€” the axis precedence rule with the windowed event shape, the correction record-state policy, and the coupling-invariant statement β€” and nothing else.
+ - Succession channel versus conflict kind: a separate successions channel; the precedence rule is contract item 1 (both-claims-windowed pairs classify on validity; everything else keeps today's assertion behavior verbatim; an expired window never suppresses contestation), so A and B cannot drift on which time wins.
+ - Window defaults: explicit input overrides; otherwise ingest resolves from the source record's event time when that source is readable at ingest, storing the frozen resolved window; the freeze (never a live reference) is contract text.
+ - Correction record state and sweep atomicity: per target β€” a time-scoped correction closes validity (predecessor serveable in its window, coupling meaningful), a flatly-wrong claim tombstones; the choice is recorded in the bundle receipt and the policy is contract item 3, which succession logic and path-provenance annotation both read. The sweep runs validate-all dry-run first (blast-radius report), then a fail-recorded applied sequence reusing retargetWikilinks' per-write failure carry; no write-batch op type this wave; idempotent replay converges; the bundle id joins the receipts.
+ - Agent-stated claims: they land as ledger events with the agent_stated extractor tag in A, with per-claim verdicts (grounded commits, ungrounded reported back); the intake-relation bridge is contract-specified and materialized in A only where object-entity linking is needed; provenance affects priority, ordering and hints only, never which pairs contest.
+ - Claim-chain recall: document typed relations plus chunk_entities now in B, with full width caps and direct-hit precedence; claim-edge composition is deferred to the next wave behind the linking A delivers, with the contract naming the future edge source and its enablement gate β€” the one honest deferral, since those edges have no live data until A's grounded claims accumulate.
+ - Windowed-slots response shape: a dedicated events operation on brain_truth (plus a CLI subcommand, matching the existing CLI-over-MCP op asymmetry), leaving today's slots response untouched entirely so existing consumers stay byte-identical by construction; stable ascending order, named default limit, inclusive day-edge semantics inherited from the shared grammar; rows reach-gated per row like every row-returning surface.
+ - Multi-hop width caps: 8 seeds, 4 per node, 16 total as named constants with config override; hub defined by typed-edge degree, never prose; deadline-bounded; direct-hit precedence structural with a pinning test; ordered-path provenance carries only nodes readable at the caller's reach (per-node gating like the derived-fact premise gate), with contested or superseded claims annotated through the contract's record-state policy.
+ - Serve-with-correction invariant: one shared predicate module in B consumed by every serving surface; a retired row is served only beside its chain-tip correction when that successor is resolved and readable at the caller's reach, and is dropped otherwise; appended correction content re-runs the full filter set; the guarantee is pinned by a cross-suite test named in the contract.
+- **Trade-offs**:
+ - Pro: the three genuinely cross-card decisions become first-class, test-pinned artifacts instead of implicit coupling; each sub-suite has a bounded blast radius and reviews as one unit.
+ - Pro: delivers the novel invariants (guaranteed cross-surface coupling, provenance-bearing ledger claims, structural direct-hit precedence) while deferring exactly the one item with a data-maturity dependency.
+ - Pro: the dedicated events operation keeps every existing consumer byte-identical by construction, the cheapest possible off state.
+ - Con: the contract is new surface to maintain; a weak or stale contract would let the sub-suites drift exactly where they must not.
+ - Con: claim-edge composition slips a wave, and the correction sweep reports partial application rather than committing as one batch.
+- **Complexity**: large
+- **Risk**: medium
+
+### Recommended: Variant 3
+**Rationale**: The recons show exactly three hard couplings β€” the assertion-versus-validity axis shared by the windows and windowing cards, the correction record-state policy shared by the correct verb, the succession logic and path provenance, and the data dependency of claim-edge traversal on grounded linking β€” and Variant 3 makes exactly those three the pinned contract while leaving everything else independent, which is the DRY without the blast radius. It delivers the wave's novel invariants that Variant 1 defers (guaranteed serve-with-correction, provenance-bearing ledger claims, direct-hit precedence), and unlike Variant 2 it does not concentrate ledger schema, write-path and five-surface serving risk in one coupled release, nor introduce a first-of-kind partial-commit lane and batch op type in the same wave that introduces the underlying data. Deferring claim-edge composition behind the enablement A ships is the one honest sequencing choice, since traversal over edges with no live data cannot earn its budget.
diff --git a/docs/brainstorm/truth-correctable-time-aware/cli-output/prompt.md b/docs/brainstorm/truth-correctable-time-aware/cli-output/prompt.md
new file mode 100644
index 00000000..b5046171
--- /dev/null
+++ b/docs/brainstorm/truth-correctable-time-aware/cli-output/prompt.md
@@ -0,0 +1,72 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Implement the "Truth, Correctable & Time-Aware" release wave for Open Second Brain: five kanban cards of one truth/claim subsystem, shipped together on branch feat/truth-correctable-time-aware (v1.76.0 plus this wave, nothing else).
+
+1. (t_edba0c15, p3) Per-claim temporal validity windows. Carry optional valid_from/valid_until on truth-ledger claim events and their append input, defaulted from the source record's event time; extend the conflict policy layer so two claims about the same entity#aspect slot with non-overlapping windows classify as succession (predecessor/successor over validity time) instead of contradiction, ending the ingest-order dependence where a 2024-dated fact ingested today reads as a fresh contest. Windowless behavior stays byte-identical (test-pinned); succession must never enter ask_user semantics. The upstream card's claims-table-view half is already at parity and is out of scope.
+2. (t_cb7ff437, p2) Windowed entity-fact recall. Add since/until to the truth-ledger recall surface (MCP brain_truth, CLI o2b brain truth) reusing the one strict time-range grammar (unparseable or inverted bounds error INVALID_PARAMS, never silently widening), returning the claim events for an entity within the window. Today slots returns the fold plus an event count; the field name events is taken and test-pinned, so this is a response-shape addition (new field or new operation), not a data-model change. The filter is on assertion ingest time (ts) and stays visibly distinct from fact-validity windows.
+3. (t_c37af4e9, p2) Multi-hop recall across claim/entity chains. Extend the existing fourth RRF arm (default-off, rrf-only, depth 2, document typed edges only) with deeper bounded traversal, width caps (seed, per-node expansion, total), hub-entity skip defined without prose inspection, ordered-path provenance with per-node reach gating, and a structural direct-hit precedence guarantee (today a relational-only row can outrank a direct hit under neutral RRF weight). Edge types come only from the schema vocabulary; the arm never reads prose.
+4. (t_cabe84aa, p3) Single correct-this-fact verb with served-only-with-correction coupling. One deterministic verb that, given a correction, discovers every affected record (claim-graph whatReplaced/whatContests plus search plus wikilink mentions), retires each in place, rewrites or annotates inline mentions, and emits one receipt bundle with a correlation id. Plus the serving invariant: a retired claim is never served bare β€” whenever it reaches a caller, its correction reaches with it, on every serving surface. Today only a best-effort, search-pipeline-only demote-and-pull-in exists for non-tombstoned predecessors, and supersede hides records outright, which makes the coupling vacuous for its own outputs unless the record state or the serving path changes.
+5. (t_3e87656b, p2) Agent-stated claims with mechanical grounding. The writing agent declares subject/relation/object claims; the engine grounds each mechanically (subject and object must occur in the note text; relation names pass the single relation-vocabulary boundary), commits grounded claims with an agent_stated extractor tag plus provenance, reports ungrounded ones back per claim, and conflict detection reasons over claim provenance β€” annotation, priority and ordering only; conflicts stay resolution ask_user. Self-mined relation-template learning is split out of this wave by validator decision (auto-application to plain writes would collide with apply-gate discipline).
+
+# Project context
+
+Open Second Brain: a memory layer for AI agents that lives in an Obsidian-compatible Markdown vault (Brain/). TypeScript on Bun, strict tsc, oxlint/oxfmt, bun test. Surfaces: MCP servers, lifecycle hooks, the o2b CLI. Deterministic-first core: no model runs in the core paths; the decision model, where present, is probabilities-only and never writes.
+
+Recent commits:
+646a49df feat: freshen the search index on read, rewriting only changed chunks (v1.76.0) (#239)
+78f924b9 feat: deliver context to subagent turns, hygiene digest at turn end and tiered context shrink (v1.75.0) (#238)
+542d214b fix(opencode): support both plugin APIs (v1.74.1) (#190)
+0cbb60b8 feat: near-duplicate defense across the fact lifecycle (v1.74.0) (#237)
+0f0c9a76 feat: honest query embeds and drift-checked upgrades (v1.73.0) (#235)
+2b424d9a feat: honest embedding spend and a semantic belief order (v1.72.0) (#234)
+
+Related substrate (verified against the live tree by premise-verification recons; all anchors live at HEAD 646a49df):
+- Truth ledger (append-only device-sharded JSONL plus a derived, recomputable state cache): src/core/brain/truth/types.ts (ClaimEvent has v/ts/agent/entity/aspect/value/valueKind/quantity/source and no validity fields; TruthState.events is a count), fold.ts (deterministic total order, history cap), conflicts.ts (CONFLICT_WINDOW_DAYS 30, assertion-time contestation, kind value_conflict, resolution ask_user pinned; the base fold is returned unchanged when nothing contests β€” test-pinned), store.ts (fail-closed coercion at TRUTH_SCHEMA_VERSION 1, conditional-spread serialization, 10k-event cap), ingest.ts (deterministic structurers only).
+- Claim-graph projection (rebuildable view over frontmatter; 5000-node cap; six subdirs only): src/core/brain/claim-graph.ts (valid_from/valid_until, provenance, superseded_by, contradicts; truthAt half-open; whatReplaced/whatContests).
+- Lifecycle: src/core/brain/lifecycle/tombstone.ts (in-place supersede/tombstone with superseded_by, receipts), lifecycle/temporal-replace.ts (half-open [valid_from, valid_until) close-and-open at one shared instant β€” the non-tombstoning correction primitive).
+- Correction substrate: src/core/brain/page-dedup.ts (retargetWikilinks with apply:false dry-run and neverRewrite for Brain/log), heal-enrich.ts (linkExactMentions), write-batch.ts (validate-all-then-commit batch ops; no retirement op type), decisions/receipts.ts (closed receipt schema, per-record idempotency).
+- Cooperative write paths: src/core/brain/intake/extract-intake.ts (declared entities and relations, refuse-before-write, mandatory provenance, quarantine lane), derived-fact.ts (grounding by reference to premises), atomic-facts.ts (anchorEntities literal-occurrence kernel), src/core/graph/relation-vocab.ts (single six-token relation boundary), src/core/brain/provenance/ (stated over deduced over inferred).
+- Recall: src/core/search/relational-fanout.ts and pipeline/relational-arm.ts (fourth RRF arm; default-off and rrf-only; depth 2; no width caps; type-list provenance, no ordered path), fusion.ts (neutral lane weight, so no direct-hit precedence today), relation-polarity.ts (default-on demote 0.6 and successor pull-in 0.9; unresolved successor inert), result-filters.ts (tombstoned rows dropped first; fail-closed reach filter), enrich.ts (note-level trust, opt-in replacement pointer), pipeline/post-rank.ts (recorded gap: pulled-in successors bypass visibility and agent-scope), time-range.ts plus recall-tools.ts resolveSessionGrepBounds (the one strict grammar and the SearchError-to-INVALID_PARAMS boundary, module-private today), validity.ts and pipeline/event-time.ts (search-side validity windows, a distinct layer), retrieval-trail.ts (typed provenance vocabulary; per-row reasons are strings).
+- Surfaces: src/mcp/brain/knowledge-tools.ts (brain_truth ops ingest|slots|conflicts|aggregate|collisions with closed schemas; brain_claims read-only), src/mcp/brain/lifecycle-tools.ts (tombstone|supersede|temporal-replace|tip|curator, reach-gated), src/cli/brain/verbs/truth.ts, claims.ts, lifecycle.ts (CLI truth ingest already accepts --ts; CLI ops are a superset of MCP ops).
+- Pinned tests: tests/core/brain/truth/conflicts.test.ts (windowless byte-identical, silent succession), tests/mcp/brain-truth.test.ts (events is a count), tests/core/search/relational-fanout.test.ts (depth-2 pins), tests/core/architecture/visibility-surface-census.test.ts (exported /brain/truth/ and claim-graph surfaces), tests/mcp/agent-scope-matrix.test.ts (tools and recipes as equalities).
+
+Conventions:
+- Deterministic, provider-free core paths; append-only events with derived folds; fail-closed parsing with schema-version discipline; optional fields serialize by conditional spread so unset means byte-identical.
+- Refuse-before-write on cooperative paths; receipts and Brain/log are testimony, read and reported but never rewritten; every write answers at the caller's reach (an unreadable target is refused as missing); every ranked output carries reasons; new config flags follow parseBool(envOrConfig(...)) with named defaults; one merged feature PR per CHANGELOG version.
+
+Hard constraints:
+- Byte-identical behavior when the new features are off; windowless truth-ledger behavior is test-pinned.
+- Conflicts keep resolution ask_user and are never auto-resolved; succession stays silent, non-ask_user evolution.
+- Visibility and reach rules apply to every new read or write path; any new MCP tool or operation joins the agent-scope-matrix equality in docs/architecture.md, and new exports join the visibility-surface census.
+- No new external dependencies; no hardcoded natural-language phrases; English everywhere; SOLID, KISS, DRY.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. Each variant must answer, explicitly, the load-bearing design questions the premise-verification recons surfaced:
+
+1. Where succession surfaces: a separate state channel or a new conflict kind.
+2. Which time governs a claim pair: the validity-versus-assertion precedence rule, and whether an expired window suppresses contestation.
+3. What defaults a claim's window: explicit input, source-record resolution, and whether a resolved window is frozen or a live reference.
+4. What state a corrected record ends in: tombstone (hidden) or validity-close (serveable in its window), and by what rule.
+5. Where agent-stated claims land: truth-ledger events, intake relations, or both with a bridge.
+6. Claim-chain recall now or deferred, and against which edges.
+7. The windowed-slots response shape: an additive field beside the count-preserving events or a dedicated operation, and what the windowed response carries.
+8. Multi-hop width caps: seed, per-node and total budgets, hub definition without prose inspection, and how direct-hit precedence is made real.
+9. Where the serve-with-correction invariant lives and what happens when the correction is unresolved or out of reach.
+
+For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-4 sentences describing the variant, followed by short labeled answers to the load-bearing questions.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-4 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/truth-correctable-time-aware/design.md b/docs/brainstorm/truth-correctable-time-aware/design.md
new file mode 100644
index 00000000..7e394e29
--- /dev/null
+++ b/docs/brainstorm/truth-correctable-time-aware/design.md
@@ -0,0 +1,126 @@
+# Truth-correctable, time-aware claims - validity windows, windowed recall, grounded agent-stated claims, a correct verb, and guaranteed serve-with-correction
+
+**Status:** draft
+**Author:** feature-release orchestrator (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+The Open Second Brain truth ledger keys every comparison on assertion time: a 2024-dated claim ingested today still reads as a fresh contest against a 2026 claim, because `ClaimEvent` carries no validity window and the conflict scanner measures pure assertion-time distance. Recall cannot window claim events at all, agent-stated claims cannot ground into the ledger with per-claim verdicts, no correction verb exists anywhere, and no serving surface guarantees that a retired claim is served together with its correction. The multi-hop recall arm has no width bounds, no hub handling, no ordered path provenance, and nothing pins direct-hit precedence.
+
+## Scope
+
+- Optional per-claim validity fields (`validFrom`/`validUntil`) on `ClaimEvent`, `AppendClaimInput` and `ClaimVersion`, presence-gated under `TRUTH_SCHEMA_VERSION = 1`, with parsing reused from the existing validity discipline.
+- A succession channel beside the conflicts array: a separate, optional `TruthState.successions` field, never a new conflict kind; ask_user semantics, hygiene findings and priority ranking untouched.
+- Ingest window defaults: explicit input wins; otherwise ingest resolves the window from the source record's frontmatter validity when that source is readable at ingest, storing the frozen resolved value.
+- A dedicated `events` operation on `brain_truth` (plus a CLI subcommand) with `since`/`until`/`entity`/`limit`, leaving today's `slots` response untouched entirely; rows carry validity fields verbatim and are reach-gated per row.
+- Grounded agent-stated claims as ledger events with the `agent_stated` extractor tag and per-claim verdicts: grounded claims commit, ungrounded claims are reported back with reasons.
+- A single `correct` verb (MCP action on `brain_lifecycle`, CLI subcommand on `brain lifecycle`) sweeping discovery, per-target retirement, mention retargeting and receipt bundling, with per-target end-state policy and a fail-recorded, idempotent, bundle-correlated receipt sequence.
+- Deepened relational traversal with width caps (8 seeds, 4 per node, 16 total nodes), hub skipping by typed-edge degree, deadline bounding, entity-bridge edges over `chunk_entities`, and ordered per-node reach-gated path provenance.
+- Structural direct-hit precedence with a pinning test reconciled against the promote-never-sink rerank pin.
+- A shared serve-with-correction coupling predicate consumed by every serving surface (search pool and post-rank, recall by topic, context-pack, active.md, dream), fail-closed on unresolved or out-of-reach successors.
+- Documentation updates (README, docs/architecture.md agent-scope-matrix equality, plugin mirrors via `bun run sync-plugin-mirrors`).
+
+## Out of scope
+
+- Claim-edge composition over grounded object-entity linking: deferred to the next wave. The contract names the future edge source (claim/entity edges derived from sub-suite A's grounded `agent_stated` events joined through the entity registry) and its enablement gate (grounded claims accumulated in live data, object-entity linking landed). Traversal over edges with no live data cannot earn its budget.
+- Self-mined relation templates: the accept-gate design is its own card; no data exists until grounded claims accumulate.
+- A tombstone/supersede op type in the write batch: the sweep runs as a fail-recorded sequence this wave, not as one Kernel 2 batch.
+- A `--since-last-run` polling cursor on the truth ledger: tail-following stays consumer-side; ascending order plus `limit` gives a resumable slice.
+- Provenance re-weighting of conflict priority: this wave the `agent_stated` tag is annotation only; it never changes which pairs contest and never re-ranks conflict priority.
+- The assertion-time sibling consumers `collision.ts` (14-day convergence) and `grounding.ts` (30-day contest balance) stay assertion-keyed, documented at their constants.
+- Turning the relational arm default-on: enablement stays `relationalArmEnabled` plus rrf fusion; byte-identical off behavior is preserved by construction.
+
+## Chosen approach
+
+Variant 3, Two Sub-Suites over a Pinned Contract, is accepted as recommended by the consultant with no orchestrator override. The wave splits into two sequenced sub-suites joined by a small, test-pinned contract. Sub-suite A (temporal truth) delivers the ledger validity fields with the succession channel, the windowed events surface, and grounded agent-stated claims as ledger events. Sub-suite B (correction and recall) delivers the correct verb, the deepened traversal with direct-hit precedence, and the coupling invariant, consuming A only through the contract. The contract pins exactly the three genuinely cross-card decisions - the axis precedence rule with the windowed event shape, the correction record-state policy, and the coupling-invariant statement - and nothing else. This keeps each sub-suite's blast radius bounded and reviewable as one unit while still delivering the wave's novel invariants that a five-narrow-cards reading would defer, and unlike a fully coupled kernel-first wave it does not concentrate ledger schema, write-path and five-surface serving risk in one release.
+
+## Design decisions
+
+1. **The assertion-versus-validity axis is contract item 1, stated once.** A same-slot pair (same canonical `entity` and `aspect`) classifies as succession, not contest, if and only if both claims carry present validity windows and the windows do not intersect. Everything else - either claim windowless, or windows intersecting - keeps today's assertion-time behavior verbatim: 30-day `CONFLICT_WINDOW_DAYS` distance, different-source requirement, `kind: "value_conflict"`, `resolution: "ask_user"`. An expired window never suppresses contestation on its own: a windowed claim whose window has passed still contests under the fall-through. Rationale: this preserves the pinned byte-identical windowless path (`conflicts.ts:83` returns the base fold unchanged; `tests/core/brain/truth/conflicts.test.ts` pins "without conflicts the state matches the base fold exactly" and the bit-identical neutral default), answers the validator's pinned semantic decision explicitly, and keeps succession outside ask_user semantics so hygiene findings and priority ranking stay untouched.
+
+2. **Succession surfaces as a separate channel, not a conflict kind.** `TruthState` gains `readonly successions?: ReadonlyArray<ClaimSuccession>` - optional and presence-gated, set only when non-empty, serialized with the conditional-spread pattern from `store.ts:128-138` so every windowless line, fold, state file and conflict result stays byte-identical. `fold.ts` is untouched; the succession pass lives in the policy layer (`conflicts.ts` plus a new `succession.ts` sibling), matching the existing policy-over-fold shape. `TruthConflictKind` gains no member, so `ask_user` semantics, the hygiene detector and conflict priority are structurally unreachable from succession code. Rationale: a new conflict kind would drag succession into dispute machinery built for ask_user; an optional channel adds read-side tolerance for an absent field instead.
+
+3. **Window defaults are explicit-input-first, frozen-at-ingest.** CLI flags `--valid-from`/`--valid-until` and declared optional MCP ingest fields win outright. Absent input, ingest resolves the window from the source record's frontmatter `valid_from`/`valid_until` when the source is readable at ingest (the first rung of the EventTimeResolver order; no mtime fallback - an mtime is an assertion-time proxy, not validity). The resolved value is stored frozen on the event; never a live reference. If the source is unreadable or windowless, the event is stored windowless and behaves byte-identically to today. Rationale: scan time never reads the vault, the ledger stays self-contained, and the freeze is contract text so A and B cannot reinterpret it.
+
+4. **One interval convention inside the truth layer: half-open.** Ledger windows use `[validFrom, validUntil)` with `isValidAt` semantics from `lifecycle/temporal-replace.ts`, reusing `ValidityBounds`. Values parse with the `search/validity.ts` discipline (bare dates day-snapped, datetimes, never relative phrases) - no second grammar. The events operation's `since`/`until` are a different vocabulary: they filter assertion `ts` only, through the shared `time-range.ts` grammar with its inclusive day-edge semantics. Both schema descriptions state their convention explicitly so the two temporal vocabularies stay unambiguous inside one response.
+
+5. **Windowed recall is a dedicated `events` operation, not a slots filter.** `brain_truth` gains `operation: "events"` with `entity` (optional, normalized, composing), `since`, `until`, `limit`; the CLI gains `o2b brain truth events` with the same arguments, matching the existing CLI-over-MCP op asymmetry (`sweep` precedent). Today's `slots` response is untouched entirely, so every existing consumer stays byte-identical by construction - `events` in the slots/conflicts responses remains the count pinned by `tests/mcp/brain-truth.test.ts:96`. The events response is `{ ok: true, operation: "events", entity: string | null, events: ClaimEventRow[], total: number, withheld: number, truncated: boolean }` where `ClaimEventRow` is the stored event with validity fields verbatim. Ordering is stable ascending assertion `ts` (the `readClaimEvents` order), which makes tail-follow pagination an advancing `since`. Default limit `DEFAULT_EVENT_LIST_LIMIT = 200`, hard cap `CLAIM_EVENT_MAX_LIST_LIMIT = 1000`, `truncated` set when more rows matched. Bounds are resolved through the shared grammar and floored/ceiled to the second (`eventsWindowBounds` in the new `events-window.ts`), exact against second-precision stamps via string compare. Every row passes the same per-row visibility/reach gate `brain_claims` uses; rows dropped by the gate are counted in `withheld` so a remote caller sees deterministic output and a withheld page stays indistinguishable from an absent one. Rationale: this is the corrected mechanics from the premise verification - `events` as a name is taken by the count, and the card's "filter the returned events" reading was false because no events were ever returned.
+
+6. **Agent-stated claims land as ledger events with per-claim verdicts.** A stated claim is `{ subject, relation, object }` plus assertion `text`, `source` and optional `agent`. It commits as one `ClaimEvent` with `entity` = normalized subject, `aspect` = the relation token (validated against the single relation vocabulary boundary, `isKnownRelation`), `value` = object display form, and `extractor: "agent_stated"` (new optional field on `ClaimEvent`/`AppendClaimInput`, tolerated by `coerceClaim` under schema v1). Grounding uses the one existing occurrence kernel: a pure `anchorEntityForms` export lifted from `atomic-facts.ts` (quality-gated normalized match forms, minimum length 3); subject and object must be anchored in `text` or the claim is reported back, not committed. Naming deliberately avoids "grounding", which is taken by the source-diversity score in `truth/grounding.ts`; the new module and verdicts speak of anchoring. Refuse-before-write still governs the payload boundary: an unknown relation, missing text or missing source refuses the whole call with nothing written; per-claim partial commit applies only to the anchoring verdict, which is safe because each event is an independent append in an append-only ledger and the response reports exactly what landed - the first partial-commit lane in this subsystem, justified by the verdict contract. Rationale: this is the store mapping that makes provenance visible to conflict detection without touching `contestingValues`; the tag is additive annotation on conflict rows this wave.
+
+7. **The correction end-state policy is contract item 2, one pure function.** `src/core/brain/truth/correction-policy.ts` pins: `correctionEndState(input: { flatlyWrong: boolean; windowEnd?: string }, correctionTs: string): { endState: "validity_close" | "tombstone"; validUntil: string | null }`. A flatly-wrong claim tombstones (hidden; the coupling invariant is vacuous for it, which is correct - nothing surfaces, correction included). Every other correction closes validity at `windowEnd` when time-scoped, else at the correction instant: the predecessor stays serveable inside its historical window, which is the only regime where serve-with-correction is non-trivial. The choice is recorded per target in the bundle receipt using the existing receipt reason codes (`supersede` for validity_close, `tombstone` for tombstone - name-aligned CLI verb, MCP action, receipt code). Succession logic consumes the policy's outcome through the ledger data (a validity-closed predecessor against its successor has non-overlapping present windows and classifies as succession under contract item 1); path-provenance annotation reads the same frontmatter outcome. Rationale: the recon showed `supersede()`-only sweeps make coupling vacuous for their own outputs because tombstoned means hidden; per-target choice keeps both regimes honest and answers the fork the card never surfaced.
+
+8. **The sweep is validate-all dry-run, then fail-recorded, no batch op.** `brain_lifecycle correct` (MCP action) and `o2b brain lifecycle correct` (CLI verb) gather the affected set within the caller's reach: the claim-graph closure (`whatReplaced` chain tip plus `whatContests`), a full-vault match-only wikilink mention scan via `retargetWikilinks` with `apply: false` (the counting pass asserts no vault identity), and same-entity/aspect truth-ledger claims. Dry-run returns the blast-radius report and writes nothing. Applied runs a fail-recorded sequence reusing `retargetWikilinks`' per-write failure carry: per-target retirement through the end-state policy, mention retargeting, per-record receipts via `appendDecisionChangeReceipt` with the bundle id carried in `evidence_triggers` as `correction_bundle:<bundleId>` (the receipt schema stays closed). For ledger claims, the correction appends a new event asserting the corrected value from the successor's source - same-source value change reads as self-correction in the fold (`conflicts.ts:36-44`), never a conflict. Replay converges: tombstone is a byte-identical no-op on replay, receipts return `appended: false`, an already-closed window stays closed. Brain/log and receipt lines are never rewritten (testimony). Rationale: fail-recorded matches the `retargetWikilinks` precedent and avoids a first-of-kind batch op type in the same wave that introduces the underlying data.
+
+9. **The coupling invariant is contract item 3, one predicate, every surface.** `src/core/search/correction-coupling.ts` pins `couplingVerdict(input: { predecessorPath: string; successorPath: string | null; successorReadable: boolean }): CouplingVerdict` with `CouplingVerdict = { action: "serve_coupled"; correctionPath: string } | { action: "drop" }`. A retired-but-serveable row (validity-closed predecessor inside its window, or superseded non-tip still serveable) is served only when its chain-tip correction is resolved and readable at the caller's reach; otherwise the row is dropped fail-closed, so a withheld page stays indistinguishable from an absent one. Content pulled in as a correction re-runs the full filter set - status, visibility scope, agent scope, reach - closing the recorded gap at `post-rank.ts:142-168` where polarity-pulled successors bypass visibility and agent scope. The predicate replaces the search pipeline's best-effort polarity branch for retired rows and is consumed by recall by topic, context-pack, active.md and dream scan, replacing today's hide-or-annotate split with one rule. Tombstoned rows stay dropped by the status filter everywhere; the predicate governs the serveable-retired regime only. Rationale: the recon verified the partial coupling exists in search only, is best-effort, and is void for tombstoned predecessors - the genuinely missing property is the guarantee across surfaces, which needs exactly one predicate to be testable.
+
+10. **Traversal budgets are named constants with config override; hub is degree, never prose.** `relationalFanout` gains `TRAVERSAL_MAX_SEEDS = 8`, `TRAVERSAL_MAX_EXPANSION_PER_NODE = 4`, `TRAVERSAL_MAX_TOTAL_NODES = 16`, and hub detection: a node whose walked-edge degree (typed edges plus entity bridges) exceeds `TRAVERSAL_HUB_DEGREE_THRESHOLD = 12` is reached but not expanded. All four are overridable through `OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_*` config following the `parseBool(envOrConfig(...))` pattern. The walk stays deadline-bounded by accepting a deadline parameter; on a fired clock the frontier is abandoned deterministically and already-reached nodes are kept. Depth stays 2 by default. Rationale: the arm today has no width bound at all - every query wikilink is a seed and every typed edge of every frontier document is followed; upstream's 8/4/16 budgets are the copied precedent, and deadline bounding is required because recall phases run under a composite deadline.
+
+11. **Entity bridges from chunk_entities, behind their own flag.** A new store reader `entityBridgesForDocuments` (new file `src/core/search/store/entity-bridges.ts`) joins the `chunk_entities` table so two documents mentioning one normalized entity get a bridge edge labeled `entity`. Bridges are walked by the deepened arm when enabled (`OPEN_SECOND_BRAIN_SEARCH_ENTITY_BRIDGES`, default true, read only when the arm itself is enabled); they are machine-derived, not part of the query edge-type vocabulary, so `parseRelationalQuery` validation is unaffected and attribution renders them as `via entity`. Rationale: this is the chunk_entities half of the corrected scope - document typed relations plus entity co-occurrence now, while claim-edge composition over grounded linking waits for live data.
+
+12. **Direct-hit precedence is structural admission plus a tightened rerank pin.** Relational-only rows (absent from the organic candidate set) are admitted after the last organic row in the pre-rerank fused order, and the rerank pin for relational-origin rows is tightened: a relational-origin row may move within the relational block and may never sink below its pre-rerank position relative to other relational rows, and may never cross above an organic direct hit. The two pins coexist and are both test-pinned. Rationale: the recon showed nothing pins precedence today - neutral RRF weight 1 lets a relational-only rank-1 row outrank a keyword-rank-20 direct hit - and a sub-neutral lane weight would perturb all fusion globally, while admission is local to the arm's rows and reconciles cleanly with promote-never-sink.
+
+13. **Ordered path provenance is per-node reach-gated and frontmatter-annotated.** `RelationalReach` gains an ordered path of `{ documentId, relation }` steps; only nodes readable at the caller's reach appear (per-node gating, the `brain_derive_fact` premise-gate precedent), and the attribution reason renders withheld hops as a count (`relational: via <types> (<n> hops, <k> nodes withheld)`). The machine-readable ordered path lands in the typed retrieval-trail vocabulary as a new stable code carrying readable document ids plus the withheld count - additive reason strings stay human provenance, the trail stays typed. When a readable path node is a non-tip superseded predecessor whose window has closed, the row is annotated `superseded_by: <tip>` through the record-state policy's frontmatter outcome - search reads frontmatter only, never the ledger, keeping the search-to-ledger coupling at zero.
+
+14. **The arm's enablement story does not change.** The deepened traversal rides the existing `relationalArmEnabled` (default false) plus rrf-fusion gates. Byte-identical off behavior holds by construction: with the arm off, fusion, ranking, attribution and the coupling predicate's search wiring see unchanged inputs. Rationale: flipping a default-on in the same wave as the coupling change would silently re-rank every stock deployment; enablement is an explicit operator choice documented by the docs lane.
+
+15. **Schema-version discipline: optional fields stay under version 1.** `validFrom`, `validUntil` and `extractor` are optional, presence-gated fields tolerated by `coerceClaim` and serialized by conditional spread. The read/write matrix: a new binary reads old lines (fields absent) and new lines (fields present, validated when present); an old binary reads new lines, ignores unknown keys, and behaves on the assertion-time axis exactly as today - state files carry `successions` only when non-empty, and old binaries' strict state validators treat the derived cache as recomputable (`readTruthState` reads null on structural mismatch and the caller refolds from events). No version bump, no migration.
+
+16. **One operator concept `correct`, no new MCP tool.** The verb extends `brain_lifecycle` with a `correct` action and the CLI lifecycle verb with a `correct` subcommand. The agent-scope-matrix equality keeps its tool count and gains the recipe rows for the new action; the test equality and docs/architecture.md classification move together (implementation lane updates the test, docs lane updates the document and regenerates mirrors). Rationale: a new `brain_correct` tool would grow the matrix tool count for a concept that is lifecycle retirement plus provenance, which `brain_lifecycle` already owns.
+
+## File changes
+
+New files:
+
+- `src/core/brain/truth/validity.ts` - window parsing, intersection test, `claimWindow`, `eventsWindowBounds` helpers (lane 1).
+- `src/core/brain/truth/succession.ts` - succession classification over slot versions (lane 1).
+- `src/core/brain/truth/stated-claims.ts` - stated-claim validation and anchoring verdicts (lane 1).
+- `src/core/brain/truth/correction-policy.ts` - contract item 2, the end-state policy (lane 1).
+- `src/core/brain/truth/events-window.ts` - pure windowed event selection and second-precision bounds (lane 2).
+- `src/mcp/brain/time-bounds.ts` - shared SearchError-to-INVALID_PARAMS wrapper over `resolveTimeRange` (lane 2).
+- `src/core/brain/lifecycle/correction.ts` - correct-verb discovery, retirement and receipt bundling (lane 3).
+- `src/core/search/correction-coupling.ts` - contract item 3, the coupling predicate (lane 3).
+- `src/core/search/store/entity-bridges.ts` - chunk_entities bridge-edge reader (lane 4).
+- Tests: `tests/core/brain/truth/validity.test.ts`, `tests/core/brain/truth/succession.test.ts`, `tests/core/brain/truth/stated-claims.test.ts`, `tests/core/brain/truth/correction-policy.test.ts` (lane 1); `tests/core/brain/truth/events-window.test.ts`, `tests/mcp/time-bounds.test.ts` (lane 2); `tests/core/brain/lifecycle/correction.test.ts`, `tests/core/search/correction-coupling.test.ts`, `tests/core/search/post-rank-coupling.test.ts`, `tests/core/brain/coupling-surfaces.test.ts`, `tests/mcp/brain-lifecycle-correct.test.ts` (lane 3); `tests/core/search/relational-path.test.ts` (lane 4); `tests/contract/serve-with-correction.test.ts` (integrator).
+
+Modified files:
+
+- `src/core/brain/truth/types.ts`, `src/core/brain/truth/store.ts`, `src/core/brain/truth/conflicts.ts`, `src/core/brain/truth/ingest.ts`, `src/core/brain/atomic-facts.ts` (export the anchoring kernel), `tests/core/brain/truth/store.test.ts`, `tests/core/brain/truth/conflicts.test.ts`, `tests/core/architecture/visibility-surface-census.test.ts` (lane 1).
+- `src/mcp/brain/knowledge-tools.ts`, `src/mcp/brain/recall-tools.ts`, `src/cli/brain/verbs/truth.ts`, `tests/mcp/brain-truth.test.ts`, `tests/cli/brain-truth.test.ts` (lane 2).
+- `src/mcp/brain/lifecycle-tools.ts`, `src/cli/brain/verbs/lifecycle.ts`, `src/core/search/pipeline/post-rank.ts`, `src/core/brain/query.ts`, `src/core/brain/context-pack.ts`, `src/core/brain/active.ts`, `src/core/brain/dream-scan.ts`, `tests/mcp/agent-scope-matrix.test.ts` (lane 3).
+- `src/core/search/relational-fanout.ts`, `src/core/search/pipeline/relational-arm.ts`, `src/core/search/fusion.ts`, `src/core/search/ranker.ts`, `src/core/search/pipeline/attribution.ts`, `src/core/search/retrieval-trail.ts`, `src/core/search/index.ts`, `tests/core/search/relational-fanout.test.ts`, `tests/core/search/relational-arm.test.ts`, `tests/core/search/fusion.test.ts` (lane 4).
+- `README.md`, `docs/architecture.md`, regenerated plugin mirrors under `plugins/codex/` (docs lane).
+
+## Risks and open questions
+
+- **Contract drift.** The contract is new surface; a weak or stale contract would let the sub-suites drift exactly where they must not. Mitigation: all three items are pure modules with named test files committed by lane 1 and lane 3 first, and the integrator owns the cross-suite pinning test `tests/contract/serve-with-correction.test.ts`.
+- **Partial-commit precedent.** Per-claim commit for stated claims is the first partial-commit write lane in the subsystem. The verdict contract keeps it honest: the payload boundary still refuses whole calls, only anchoring verdicts are per-claim, and the response reports exactly what landed.
+- **Entity-bridge noise.** chunk_entities bridges can connect popular entities across unrelated documents. Mitigation: hub skipping by degree, width caps, and a dedicated flag to disable bridges independent of the arm.
+- **Forward/backward compatibility.** Old binaries reading new lines ignore unknown keys and stay on the assertion-time axis; a mixed-device vault therefore shows axis behavior per device until all devices upgrade. Acceptable for a derived, recomputable cache and append-only events; noted here so it is a documented property, not a surprise.
+- **Sweep blast radius.** A wrong target selection could retire many records. Mitigation: dry-run-first is the default UX, retarget is match-only and never rewrites code spans or Brain/log, receipts are per-record and idempotent, and the counting pass asserts no vault identity.
+- **Open during implementation.** The exact hub threshold value (12) and the entity-bridge default may need tuning against a real corpus; both are named constants with config override so tuning does not change code shape. The retrieval-trail code name for the ordered path is finalized in review against the existing stable-code vocabulary.
+
+## Premise verification
+
+Verdicts below come from the premise-verification recon reports, which are authoritative over the card bodies. The recons confirmed two cards as stated and corrected three; each corrected card's scope in this design follows the corrected scope, not the card text.
+
+### t_edba0c15 - Per-claim temporal validity windows feeding conflict-vs-succession: CORRECTED
+
+The gap is real but narrower and differently seated than the card implies: the conflict scanner genuinely has no validity axis and keys purely on assertion time (ingest-order dependence confirmed reproducible), but per-claim windows, a point-in-time query and a succession-aware claims view already exist on the sibling claim-graph layer, and the card's claims-table-view half is already at parity (`brain_claims` / `o2b brain claims` already render windows, provenance, supersession and tombstone status). Corrected scope adopted: (a) optional `validFrom`/`validUntil` on `ClaimEvent`/`AppendClaimInput`/`ClaimVersion` with presence-gated serialization under schema v1; (b) window defaults resolved from the source record's event time, frozen at ingest; (c) the conflict policy layer extended so two same-slot claims with non-overlapping present windows classify as succession while the windowless path stays byte-identical and succession stays outside ask_user semantics; (d) the precedence rule stated explicitly as contract item 1. The claims-table half is dropped as present parity; the one missing extractor column belongs to t_3e87656b's `agent_stated` tag.
+
+### t_cb7ff437 - Windowed entity-fact recall: since/until on brain_truth slots: CORRECTED
+
+The gap is real (no since/until anywhere on the truth-ledger recall surface; the strict grammar is reusable), but the card's central reading was false: the slots response has never carried claim-event rows - `events` in that response is a count, pinned by test - so the feature necessarily extends the response shape or adds an operation, and the validator's either/or ("filter the events fed to the fold" versus "filter the returned events") is moot. Corrected scope adopted: a dedicated `operation: "events"` on `brain_truth` plus a CLI subcommand, leaving today's slots response untouched entirely so existing consumers stay byte-identical by construction; stable ascending order, named default limit, inclusive day-edge semantics inherited from the shared grammar, rows reach-gated per row, validity fields passed through verbatim, and the schema description stating that since/until filter assertion `ts` only. The fold stays whole: conflicts and current truth keep being computed over the full event set.
+
+### t_c37af4e9 - Multi-hop recall across claim/entity chains with bounded fan-out and path provenance: CORRECTED
+
+The validator's resolution is confirmed - a bounded multi-hop lane exists and the card is a present_weaker extension of it - with two parity fixes the design respects: the relational arm is doubly opt-in (default-off and rrf-only, so unconditionally extending it ships to no one), and direct-hit precedence is NOT an existing guardrail (neutral RRF weight 1 lets a relational-only row outrank a direct hit; no test pins precedence). Corrected scope adopted: width caps (8 seeds, 4 per node, 16 total) and hub skipping by typed-edge degree as new work with named constants and config override; direct-hit precedence as a new structural mechanism (admission below the last organic row plus a tightened rerank pin) with a pinning test; ordered-path provenance with per-node reach gating; traversal over document typed relations plus chunk_entities entity bridges now; claim-edge composition over grounded object-entity linking deferred to the next wave behind the enablement sub-suite A ships, with the contract naming the future edge source and its gate; the arm's default-off enablement unchanged.
+
+### t_cabe84aa - Single correct-this-fact verb with served-only-with-correction coupling: CONFIRMED
+
+Confirmed: the preservation half is at parity as claimed, no single correction verb exists anywhere in src/ or tests/, and no serving surface guarantees a retired claim is served coupled with its correction. Two refinements verified and folded in: a partial best-effort coupling already exists in the search pipeline only (relation polarity demotes a non-tombstoned predecessor and pulls in a resolved successor; unresolved leaves the predecessor served bare; topic recall, context-pack, active.md and dream have no analogue), and the `trust.replacement` pointer is opt-in, not unconditional. The design's novelty is the guaranteed cross-surface coupling (contract item 3) and the per-target end-state policy (contract item 2) the card never surfaced: supersede-only sweeps make coupling vacuous for their own outputs because tombstoned means hidden.
+
+### t_3e87656b - Agent-stated claims with mechanical grounding, provenance-based conflict detection, self-mined relation templates: CONFIRMED
+
+Confirmed: all three gaps are real (no occurrence-grounded declared-claim path, no provenance-aware conflict detection, no relation-template learning). One inventory correction adopted: the closer existing path is the typed extraction intake (`extract-intake.ts`), not only `derived-fact.ts`, and the one existing occurrence-in-text kernel is `anchorEntities` in `atomic-facts.ts` - both are the extension points this design uses. Scope within this wave: agent-stated claims land as ledger events with the `agent_stated` extractor tag and per-claim anchoring verdicts; provenance is annotation only and never changes which pairs contest (the `ask_user` resolution stays pinned); the intake-relation bridge is contract-named and deferred with object-entity linking; relation-template learning is out of scope as its own future accept-gated card. The naming hazard is respected: "grounding" is taken by the source-diversity score in `truth/grounding.ts`, so the new verdicts speak of anchoring.
diff --git a/docs/brainstorm/truth-correctable-time-aware/plan.md b/docs/brainstorm/truth-correctable-time-aware/plan.md
new file mode 100644
index 00000000..956a913f
--- /dev/null
+++ b/docs/brainstorm/truth-correctable-time-aware/plan.md
@@ -0,0 +1,207 @@
+# Truth-correctable, time-aware claims - implementation plan
+
+Four parallel implementation lanes plus one integrator, structured over Variant 3's two sub-suites. Sub-suite A (tasks 1-10, lanes 1 and 2) delivers temporal truth: ledger validity fields with the succession channel, the windowed events operation, and grounded agent-stated ledger claims. Sub-suite B (tasks 11-19, lanes 3 and 4) delivers correction and recall: the correct verb with per-target end-state policy and fail-recorded sweep receipts, deepened traversal with width caps and direct-hit precedence, and the shared serve-with-correction coupling predicate across surfaces. Sub-suite B tasks start only after the contract modules they consume have landed (see Cross-lane contract and the dependency rule).
+
+Lane ownership is disjoint: no two lanes edit the same file. Shared new modules exist only as contract items and are named in the Cross-lane contract. Every task is test-first: the named test files are written first, run, and must fail with the expected error before implementation.
+
+| Lane | Name | Owns |
+|------|------|------|
+| 1 | ledger-core | `src/core/brain/truth/**` (except `events-window.ts`), `src/core/brain/atomic-facts.ts`, truth and census tests |
+| 2 | recall-surfaces | `src/mcp/brain/knowledge-tools.ts`, `src/mcp/brain/recall-tools.ts`, `src/mcp/brain/time-bounds.ts`, `src/core/brain/truth/events-window.ts`, `src/cli/brain/verbs/truth.ts`, truth MCP/CLI tests |
+| 3 | correction-coupling | `src/core/brain/lifecycle/correction.ts`, `src/core/search/correction-coupling.ts`, `src/mcp/brain/lifecycle-tools.ts`, `src/cli/brain/verbs/lifecycle.ts`, `src/core/search/pipeline/post-rank.ts`, `src/core/brain/{query,context-pack,active,dream-scan}.ts`, lifecycle/coupling/matrix tests |
+| 4 | deep-traversal | `src/core/search/{relational-fanout,fusion,ranker,retrieval-trail,index}.ts`, `src/core/search/pipeline/{relational-arm,attribution}.ts`, `src/core/search/store/entity-bridges.ts`, relational search tests |
+| D | docs | `README.md`, `docs/architecture.md`, regenerated `plugins/codex/` mirrors |
+| I | integrator | `tests/contract/serve-with-correction.test.ts`, full gates |
+
+## Cross-lane contract
+
+The contract pins exactly the three genuinely cross-card decisions. Each item names its owning lane, its module, and the exact signatures every consumer implements against. A consumer lane codes against these signatures before the owning lane's commit lands; the poll rule in the dependency section covers the wait.
+
+### Contract item 1: the assertion-versus-validity axis rule (owner: lane 1, module `src/core/brain/truth/validity.ts` + `src/core/brain/truth/succession.ts`)
+
+- `ClaimEvent`, `AppendClaimInput` and `ClaimVersion` gain optional presence-gated `validFrom?: string` and `validUntil?: string` (canonical ISO-8601 UTC, half-open `[validFrom, validUntil)`), serialized by conditional spread under `TRUTH_SCHEMA_VERSION = 1`.
+- `export interface ClaimWindow { readonly fromMs: number | null; readonly untilMs: number | null }` and `export function claimWindow(event: ClaimEvent): ClaimWindow | null` - null when the event carries no window; a missing bound is unbounded on that side.
+- `export function windowsIntersect(a: ClaimWindow, b: ClaimWindow): boolean` - half-open intersection, `a.fromMs < b.untilMs && b.fromMs < a.untilMs` with null as plus/minus infinity.
+- Classification rule: a same-slot pair is succession if and only if both claims carry present windows and `windowsIntersect` is false; every other pair keeps today's assertion-time contest behavior verbatim; an expired window never suppresses contestation on its own.
+- Windowed event shape: `ClaimEventRow` is the stored `ClaimEvent` with validity fields verbatim; the events operation's `since`/`until` filter assertion `ts` only and are stated as such in the schema description.
+- Sibling consumers stay assertion-keyed: `collision.ts` and `grounding.ts` constants gain a comment stating the axis choice; their code does not change.
+
+### Contract item 2: the correction end-state policy (owner: lane 1, module `src/core/brain/truth/correction-policy.ts`)
+
+```ts
+export type CorrectionEndState = "validity_close" | "tombstone";
+
+export interface CorrectionEndStateInput {
+ /** The caller declares the prior claim was never true, not merely superseded. */
+ readonly flatlyWrong: boolean;
+ /** Explicit window end for a time-scoped correction (canonical ISO-8601 UTC). */
+ readonly windowEnd?: string;
+}
+
+export function correctionEndState(
+ input: CorrectionEndStateInput,
+ correctionTs: string,
+): { endState: CorrectionEndState; validUntil: string | null };
+// flatlyWrong -> { endState: "tombstone", validUntil: null }
+// otherwise -> { endState: "validity_close", validUntil: windowEnd ?? correctionTs }
+```
+
+Consumers: lane 3's correct verb chooses per target through this function and records the choice in the bundle receipt with the existing reason codes (`supersede` for validity_close, `tombstone` for tombstone); lane 1's succession logic and lane 4's path-provenance annotation read the outcome through the ledger/frontmatter data (a validity-closed predecessor against its successor has non-overlapping present windows and classifies as succession under item 1).
+
+### Contract item 3: the serve-with-correction coupling predicate (owner: lane 3, module `src/core/search/correction-coupling.ts`)
+
+```ts
+export type CouplingVerdict =
+ | { readonly action: "serve_coupled"; readonly correctionPath: string }
+ | { readonly action: "drop" };
+
+export interface CouplingInput {
+ /** Path of the retired-but-serveable row's page. */
+ readonly predecessorPath: string;
+ /** Chain-tip successor path from resolveChainTip/buildChainLookup, null when unresolved. */
+ readonly successorPath: string | null;
+ /** True when the successor page is readable at the caller's reach. */
+ readonly successorReadable: boolean;
+}
+
+export function couplingVerdict(input: CouplingInput): CouplingVerdict;
+// resolved AND readable -> { action: "serve_coupled", correctionPath: successorPath }
+// otherwise -> { action: "drop" }
+```
+
+Rule: a retired-but-serveable row is served only beside its chain-tip correction; otherwise it is dropped fail-closed (a withheld page stays indistinguishable from an absent one). Any correction content pulled in re-runs the full filter set: status, visibility scope, agent scope, reach. Every serving surface consumes this predicate: search post-rank, recall by topic, context-pack, active.md, dream scan. Tombstoned rows stay dropped by the status filter everywhere; the predicate governs the serveable-retired regime only. The guarantee is pinned by the integrator's cross-suite test `tests/contract/serve-with-correction.test.ts`, named here as part of the contract.
+
+### Dependency rule
+
+- Lanes commit their pure modules first: lane 1 commits `validity.ts`, `succession.ts`, `correction-policy.ts` (and their tests) before its store/surface wiring tasks; lane 3 commits `correction-coupling.ts` before its wiring tasks; lane 4 commits the `relational-fanout.ts` budget changes before arm wiring.
+- A lane that consumes an upstream lane's module may poll `git log -- <file>` for the upstream lane's commit at a 30 s interval, with a 12-minute cap; when the cap expires the consumer proceeds against the contract signatures above (they are exact and test-pinned, so drift surfaces as the consumer's failing test, which the integrator then reconciles).
+- Sub-suite B tasks (11-19) must not land before the contract item they consume has landed: lane 3's task 16 needs item 2, lane 4's tasks need no lane-1 module (they depend on item 1's annotation rule only through frontmatter data, so lane 4 may run fully in parallel), lane 3's tasks 18-19 need item 3 (their own module).
+- Format and lint before every commit; each task is its own conventional commit on the feature branch.
+
+## Tasks
+
+### Task 1: Ledger validity fields and window parsing
+- **Lane**: 1 (ledger-core)
+- **Files**: `src/core/brain/truth/validity.ts` (new), `src/core/brain/truth/types.ts`, `src/core/brain/truth/store.ts`, `tests/core/brain/truth/validity.test.ts` (new, written first), `tests/core/brain/truth/store.test.ts`, `tests/core/architecture/visibility-surface-census.test.ts`
+- **Acceptance**: `validity.test.ts` passes: window parsing reuses the `search/validity.ts` discipline (bare dates day-snapped, datetimes, relative phrases rejected), `claimWindow` returns null for windowless events, `windowsIntersect` implements the half-open rule with infinity for missing bounds; `store.test.ts` passes: presence-gated serialization leaves windowless lines byte-identical, `coerceClaim` tolerates and validates the new optional fields under schema v1, the read/write matrix (old binary reads new lines, new binary reads old lines) is pinned; census rows exist for the new exported surfaces.
+- **Depends on**: none.
+
+### Task 2: Succession channel in the conflict policy layer
+- **Lane**: 1 (ledger-core)
+- **Files**: `src/core/brain/truth/succession.ts` (new), `src/core/brain/truth/conflicts.ts`, `src/core/brain/truth/types.ts`, `tests/core/brain/truth/succession.test.ts` (new, written first), `tests/core/brain/truth/conflicts.test.ts`
+- **Acceptance**: `succession.test.ts` passes: two same-slot claims with present non-overlapping windows classify as `ClaimSuccession` entries and never as conflicts; intersecting windows or any windowless claim falls through to the assertion-time contest rule verbatim; an expired window never suppresses contestation. `conflicts.test.ts` passes unchanged on its existing pins (base fold equality, bit-identical neutral default) and `TruthState.successions` is absent (undefined, not `[]`) whenever empty; `TruthConflictKind` is unchanged; state file serialization spreads `successions` only when present.
+- **Depends on**: Task 1.
+
+### Task 3: Ingest window defaults, frozen at ingest
+- **Lane**: 1 (ledger-core)
+- **Files**: `src/core/brain/truth/store.ts`, `src/core/brain/truth/validity.ts`, `tests/core/brain/truth/validity.test.ts`
+- **Acceptance**: `validity.test.ts` window-default cases pass: explicit `validFrom`/`validUntil` input wins outright; absent input, the resolver reads the source record's frontmatter `valid_from`/`valid_until` when the source is readable at ingest and stores the frozen resolved value; an unreadable or windowless source stores a windowless event that is byte-identical to today's output; mtime is never used as a window source.
+- **Depends on**: Task 1.
+
+### Task 4: Grounded agent-stated claim core
+- **Lane**: 1 (ledger-core)
+- **Files**: `src/core/brain/truth/stated-claims.ts` (new), `src/core/brain/truth/ingest.ts`, `src/core/brain/truth/types.ts` (optional `extractor?: "agent_stated"`), `src/core/brain/truth/store.ts`, `src/core/brain/atomic-facts.ts` (export the occurrence-anchoring kernel as a pure `anchorEntityForms`), `tests/core/brain/truth/stated-claims.test.ts` (new, written first)
+- **Acceptance**: `stated-claims.test.ts` passes: a stated claim `{ subject, relation, object }` with `text` maps to a ledger event (entity = normalized subject, aspect = relation token, value = object) with `extractor: "agent_stated"`; an unknown relation, missing text or missing source refuses the whole payload with nothing written (refuse-before-write at the boundary); anchoring verdicts are per claim - subject and object anchored via the quality-gated match forms commit, ungrounded claims are reported back with reasons; conflict detection is untouched (`contestingValues` unchanged, conflict rows may annotate the tag but never re-rank or resolve).
+- **Depends on**: Task 1.
+
+### Task 5: Correction end-state policy (contract item 2)
+- **Lane**: 1 (ledger-core)
+- **Files**: `src/core/brain/truth/correction-policy.ts` (new), `tests/core/brain/truth/correction-policy.test.ts` (new, written first)
+- **Acceptance**: `correction-policy.test.ts` passes the exact signature and rule table: `flatlyWrong` yields tombstone with null `validUntil`; any other input yields validity_close with `windowEnd` when time-scoped, else the correction instant; results are pure and deterministic.
+- **Depends on**: none. Must land before lane 3's Task 16 (sub-suite A before B).
+
+### Task 6: Events-window selection (pure)
+- **Lane**: 2 (recall-surfaces)
+- **Files**: `src/core/brain/truth/events-window.ts` (new), `tests/core/brain/truth/events-window.test.ts` (new, written first)
+- **Acceptance**: `events-window.test.ts` passes: `selectClaimEvents(events, { entity, sinceMs, untilMs, limit })` slices the already-`ts`-sorted event array with second-precision string compare (since floored, until ceiled to the second, matching the grammar's inclusive day-edge semantics), composes with the normalized-entity filter, applies `DEFAULT_EVENT_LIST_LIMIT = 200` with hard cap `CLAIM_EVENT_MAX_LIST_LIMIT = 1000`, and returns stable ascending rows with `total` and `truncated`.
+- **Depends on**: none (codes against the `ClaimEvent` shape of contract item 1).
+
+### Task 7: Shared time-bounds wrapper
+- **Lane**: 2 (recall-surfaces)
+- **Files**: `src/mcp/brain/time-bounds.ts` (new), `src/mcp/brain/recall-tools.ts`, `tests/mcp/time-bounds.test.ts` (new, written first)
+- **Acceptance**: `time-bounds.test.ts` passes: the lifted `resolveTimeBounds(since, before)` resolves through `resolveTimeRange` and maps `SearchError` to `MCPError(INVALID_PARAMS)`; `recall-tools.ts` consumes the shared wrapper for session-grep bounds with behavior unchanged (its existing tests stay green).
+- **Depends on**: none.
+
+### Task 8: brain_truth events operation and agent-stated claims operation
+- **Lane**: 2 (recall-surfaces)
+- **Files**: `src/mcp/brain/knowledge-tools.ts`, `tests/mcp/brain-truth.test.ts`
+- **Acceptance**: `brain-truth.test.ts` additions pass: `operation: "events"` accepts `entity`/`since`/`until`/`limit` (declared in the closed schema, `additionalProperties: false`), returns `{ ok, operation, entity, events: ClaimEventRow[], total, withheld, truncated }` with rows in stable ascending assertion-`ts` order and validity fields verbatim; every row passes the same per-row visibility/reach gate as `brain_claims`, dropped rows counted in `withheld`; the slots and conflicts responses are byte-identical to before (the `events` count pin stays); `operation: "state"` accepts `{ claims, text, source, agent? }`, refuses unknown relations before any write, commits grounded claims with `extractor: "agent_stated"`, and reports ungrounded claims back per claim with reasons. Schema descriptions state the ts-only filter and the half-open validity convention.
+- **Depends on**: Tasks 1, 2, 4, 6, 7 (polls lane 1 commits per the dependency rule).
+
+### Task 9: CLI truth surface
+- **Lane**: 2 (recall-surfaces)
+- **Files**: `src/cli/brain/verbs/truth.ts`, `tests/cli/brain-truth.test.ts`
+- **Acceptance**: `brain-truth.test.ts` CLI additions pass: `o2b brain truth events [--entity E] [--since X] [--until Y] [--limit N]` prints the same shape as the MCP events op; `o2b brain truth ingest` accepts `--valid-from`/`--valid-until`; `o2b brain truth state --subject S --relation R --object O --text T --source S [--agent N]` prints the anchoring verdict (committed event or reported-back reasons); unparseable bounds fail with the INVALID_PARAMS-equivalent CLI error through the shared wrapper; the CLI/MCP op asymmetry is preserved (all ops present on both, `sweep` CLI-only).
+- **Depends on**: Tasks 3, 4, 6, 8.
+
+### Task 10: Sub-suite A integration checkpoint
+- **Lane**: 2 (recall-surfaces)
+- **Files**: none new (verification only)
+- **Acceptance**: full truth-suite test files green together (`tests/core/brain/truth/`, `tests/mcp/brain-truth.test.ts`, `tests/cli/brain-truth.test.ts`, census test); a windowed events call over events ingested with resolved windows returns rows carrying the frozen windows; the succession channel and the events surface agree on the axis rule from contract item 1.
+- **Depends on**: Tasks 1-9.
+
+### Task 11: Traversal budgets, hub skipping, deadline
+- **Lane**: 4 (deep-traversal)
+- **Files**: `src/core/search/relational-fanout.ts`, `src/core/search/index.ts`, `tests/core/search/relational-fanout.test.ts`
+- **Acceptance**: `relational-fanout.test.ts` additions pass: seed cap `TRAVERSAL_MAX_SEEDS = 8`, per-node cap `TRAVERSAL_MAX_EXPANSION_PER_NODE = 4`, total-node cap `TRAVERSAL_MAX_TOTAL_NODES = 16`, all overridable via `OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_*` with the `parseBool(envOrConfig(...))` pattern; a node whose walked-edge degree exceeds `TRAVERSAL_HUB_DEGREE_THRESHOLD = 12` is reached but not expanded; a fired deadline abandons the frontier deterministically keeping already-reached nodes; the existing hop-dominance and determinism pins stay green; off state unchanged.
+- **Depends on**: none.
+
+### Task 12: Entity bridges from chunk_entities
+- **Lane**: 4 (deep-traversal)
+- **Files**: `src/core/search/store/entity-bridges.ts` (new), `src/core/search/relational-fanout.ts`, `tests/core/search/relational-fanout.test.ts`
+- **Acceptance**: `relational-fanout.test.ts` bridge cases pass: `entityBridgesForDocuments` joins `chunk_entities` into deduplicated bridge edges labeled `entity`; bridges are walked only when `OPEN_SECOND_BRAIN_SEARCH_ENTITY_BRIDGES` is true and the arm is enabled; with bridges off, fanout output equals the Task 11 output exactly; bridge edges count toward hub degree and node caps.
+- **Depends on**: Task 11.
+
+### Task 13: Ordered path provenance with per-node reach gating
+- **Lane**: 4 (deep-traversal)
+- **Files**: `src/core/search/pipeline/relational-arm.ts`, `src/core/search/pipeline/attribution.ts`, `src/core/search/retrieval-trail.ts`, `tests/core/search/relational-path.test.ts` (new, written first), `tests/core/search/relational-arm.test.ts`
+- **Acceptance**: `relational-path.test.ts` passes: `RelationalReach` carries the ordered path of `{ documentId, relation }` steps; path nodes unreadable at the caller's reach are omitted and counted, and the attribution reason renders `relational: via <types> (<n> hops, <k> nodes withheld)`; a readable path node that is a non-tip superseded predecessor with a closed validity window is annotated `superseded_by: <tip>` from frontmatter only; the ordered path lands in the retrieval trail as a new stable typed code carrying readable document ids plus the withheld count; existing attribution tests stay green.
+- **Depends on**: Task 12.
+
+### Task 14: Structural direct-hit precedence
+- **Lane**: 4 (deep-traversal)
+- **Files**: `src/core/search/fusion.ts`, `src/core/search/ranker.ts`, `src/core/search/pipeline/relational-arm.ts`, `tests/core/search/fusion.test.ts`
+- **Acceptance**: `fusion.test.ts` precedence pins pass: relational-only rows are admitted after the last organic row in the pre-rerank fused order; a relational-only row at relational-rank 1 never outranks a keyword direct hit; the tightened rerank pin holds (a relational-origin row may move within the relational block, never sinks below its pre-rerank position relative to other relational rows, and never crosses above an organic direct hit); with the arm disabled, fusion output is byte-identical.
+- **Depends on**: Task 11.
+
+### Task 15: Coupling predicate module (contract item 3)
+- **Lane**: 3 (correction-coupling)
+- **Files**: `src/core/search/correction-coupling.ts` (new), `tests/core/search/correction-coupling.test.ts` (new, written first)
+- **Acceptance**: `correction-coupling.test.ts` passes the exact signature and rule table: resolved and readable successor yields `serve_coupled` with the correction path; unresolved, unreadable, or absent successor yields `drop`; pure, deterministic, no I/O.
+- **Depends on**: none.
+
+### Task 16: Correct-verb sweep core
+- **Lane**: 3 (correction-coupling)
+- **Files**: `src/core/brain/lifecycle/correction.ts` (new), `tests/core/brain/lifecycle/correction.test.ts` (new, written first)
+- **Acceptance**: `correction.test.ts` passes: discovery gathers the affected set within the caller's reach (claim-graph closure via `whatReplaced`/`whatContests`, match-only wikilink mention scan via `retargetWikilinks` with `apply: false`, same-entity/aspect ledger claims); dry-run writes nothing and returns the blast-radius report; the applied run retires each target through `correctionEndState` (contract item 2), retargets mentions with per-write failure carry, appends ledger correction events from the successor's source (self-correction semantics, never a conflict), and emits per-record receipts with `correction_bundle:<bundleId>` in `evidence_triggers`; replay converges (no double tombstone, receipts report `appended: false`, closed windows stay closed); Brain/log and receipt lines are never rewritten; every write passes the vault-identity guard.
+- **Depends on**: Task 5 (contract item 2; sub-suite A before B).
+
+### Task 17: brain_lifecycle correct action, CLI verb, matrix equality
+- **Lane**: 3 (correction-coupling)
+- **Files**: `src/mcp/brain/lifecycle-tools.ts`, `src/cli/brain/verbs/lifecycle.ts`, `tests/mcp/brain-lifecycle-correct.test.ts` (new, written first), `tests/mcp/agent-scope-matrix.test.ts`
+- **Acceptance**: `brain-lifecycle-correct.test.ts` passes: `brain_lifecycle` action `correct` and CLI `o2b brain lifecycle correct` expose the sweep with `dry_run` default true, a `flatly_wrong` flag, an optional `window_end`, and reach-gated targets (a target the caller may not read is refused as missing before anything is written); the agent-scope-matrix equality is updated for the new action's recipes and stays an equality (tool count unchanged); receipt reason codes stay `supersede`/`tombstone`, name-aligned with the verb and action.
+- **Depends on**: Task 16.
+
+### Task 18: Search-pipeline coupling wiring
+- **Lane**: 3 (correction-coupling)
+- **Files**: `src/core/search/pipeline/post-rank.ts`, `tests/core/search/post-rank-coupling.test.ts` (new, written first)
+- **Acceptance**: `post-rank-coupling.test.ts` passes: the retired-row branch consumes `couplingVerdict` - a retired-but-serveable row is served only beside its resolved, readable chain-tip correction and is dropped otherwise; correction content pulled in re-runs the full filter set (status, visibility scope, agent scope, reach), closing the recorded gap where pulled successors bypassed visibility and agent scope; with no retired rows the pool is unchanged (byte-identical neutral path pinned); tombstoned rows remain dropped by the status filter before the predicate runs.
+- **Depends on**: Task 15.
+
+### Task 19: Cross-surface coupling
+- **Lane**: 3 (correction-coupling)
+- **Files**: `src/core/brain/query.ts`, `src/core/brain/context-pack.ts`, `src/core/brain/active.ts`, `src/core/brain/dream-scan.ts`, `tests/core/brain/coupling-surfaces.test.ts` (new, written first)
+- **Acceptance**: `coupling-surfaces.test.ts` passes: recall by topic, context-pack injection, the active.md digest and the dream scan all decide through `couplingVerdict` - a serveable retired row appears only with its correction, is dropped otherwise, and today's exclusion wiring keeps tombstoned rows hidden; each surface's non-retired output is unchanged.
+- **Depends on**: Task 15.
+
+### Task 20: Docs, matrix documentation, and plugin mirrors
+- **Lane**: D (docs)
+- **Files**: `README.md`, `docs/architecture.md`, regenerated mirrors under `plugins/codex/`
+- **Acceptance**: docs/architecture.md agent-scope-matrix section matches the implementation lane's test equality (same recipe rows for the `correct` action); README documents the `events` and `state` truth operations, the `correct` verb, the traversal budget flags and their defaults; `bun run sync-plugin-mirrors` has been run and the generated mirror is committed in this lane's FIRST commit; `bun run sync-plugin-mirrors:check` is clean afterwards.
+- **Depends on**: Tasks 10 and 17 (final shapes and matrix numbers; may be written against the contract in parallel and committed after they land).
+
+### Task 21: Integrator - contract pin and full gates
+- **Lane**: I (integrator)
+- **Files**: `tests/contract/serve-with-correction.test.ts` (new, written first)
+- **Acceptance**: the cross-suite contract test passes: with sub-suite A's windows and sub-suite B's coupling wired together, a retired-but-serveable row served by any surface is always accompanied by its chain-tip correction, and is dropped when the successor is unresolved or out of reach - the guarantee named in contract item 3. Then the full gates in CI order: formatter, linter, full test suite, `bun run sync-plugin-mirrors:check`, the architecture census and agent-scope-matrix equalities; any cross-lane drift against the contract is reconciled here.
+- **Depends on**: Tasks 10, 14, 19, 20.
diff --git a/docs/brainstorm/truth-correctable-time-aware/variants.md b/docs/brainstorm/truth-correctable-time-aware/variants.md
new file mode 100644
index 00000000..702f9cc2
--- /dev/null
+++ b/docs/brainstorm/truth-correctable-time-aware/variants.md
@@ -0,0 +1,68 @@
+# Variants - truth-correctable, time-aware claims (audit trail)
+
+Source: cli-output/consultant.md. The orchestrator accepted the consultant recommendation (Variant 3, Two Sub-Suites over a Pinned Contract) with no override. The three variants and the recommendation follow verbatim.
+
+## Consultant variants (verbatim)
+
+### Variant 1: Five Narrow Independent Cards
+- **Approach**: Each card lands as the smallest correct version of itself with no shared new module and no cross-card sequencing: the ledger gains optional validity fields read only by a new succession channel; the windowed recall surface gains one additive response field; the correction sweep orchestrates existing primitives under today's retire-in-place semantics; agent-stated claims ground into the intake relation layer without touching the ledger; multi-hop recall deepens the existing relational arm over document typed edges only. Every cross-card decision is taken locally in the most conservative direction, so nothing shared changes and the cards can be built fully in parallel.
+ - Succession channel versus conflict kind: a separate successions channel beside the conflicts array in the policy layer, keyed only when both claims of a pair carry present non-overlapping windows; mixed or windowless pairs keep today's assertion-time behavior byte-identically; never a new conflict kind, so ask_user semantics, hygiene findings and priority ranking stay untouched. Precedence rule: validity governs only validity-versus-validity pairs; contestation stays assertion-keyed even for windowed pairs, an expired window never suppresses contestation on its own, and the assertion-time sibling consumers (collision, grounding score) stay assertion-keyed.
+ - Window defaults: explicit input only (CLI flags and declared optional ingest fields); no automatic resolution from source records, keeping ledger ingest self-contained.
+ - Correction record state and sweep atomicity: supersede/tombstone as today; the sweep is a deterministic fail-recorded sequence β€” dry-run discovery, per-record supersede, mention retargeting with apply:false then apply, per-record receipts correlated by a bundle id carried in evidence_triggers β€” with no record-state change and no write-batch extension.
+ - Agent-stated claims: they land in the intake relation layer, extending the declared-payload boundary with anchorEntities occurrence grounding and report-back verdicts; no extractor tag on ledger events this wave, so provenance-based conflict detection reduces to additive annotation over the claim-graph fields that already exist.
+ - Claim-chain recall: deferred. The arm deepens over document typed relations plus chunk_entities now; claim-edge composition is explicitly deferred until grounded object-entity linking exists.
+ - Windowed-slots response shape: an additive claim_events field beside the count-preserving events; slots and the global count untouched (superset reading); rows in stable ascending ts order with a named default limit; the SearchError-to-INVALID_PARAMS boundary lifted out of recall-tools into a shared wrapper; the schema description states that since/until filters assertion ts only.
+ - Multi-hop width caps: 8 seeds, 4 expansions per node, 16 total nodes as named constants with config override; a hub is a node whose walked-edge degree exceeds a threshold; traversal stays deadline-bounded; direct-hit precedence is not addressed this wave.
+ - Serve-with-correction invariant: stays search-pipeline-only and best-effort; relation polarity is hardened so a resolvable, readable successor is always pulled in beside a demoted predecessor; recall by topic, context-pack, active.md and dream keep the hide-or-annotate split.
+- **Trade-offs**:
+ - Pro: smallest blast radius per card; the byte-identical and ask_user invariants hold by construction because no shared code changes.
+ - Pro: full parallelism, no ordering constraints; each card reviews as one unit and can ship or slip alone.
+ - Con: the assertion-versus-validity axis is decided twice (windows card and windowing card) with real drift risk, and the precedence rule ends up implicit in two places instead of stated once.
+ - Con: the wave's two genuinely novel ideas are not delivered β€” the coupling guarantee remains best-effort and search-only, and recall still cannot answer transitive claim questions.
+ - Con: agent-stated claims never reach the ledger, so that card's headline (provenance-based conflict detection over ledger events) degrades to annotation, and the extractor column the claims view lacks stays missing.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Shared Temporal Kernel, Fully Coupled Wave
+- **Approach**: Build one shared time-axis kernel first β€” a single module owning window parsing (the existing strict grammars lifted together), the half-open interval test, and one explicit precedence rule β€” then land all five cards as consumers in the same release, including claim-edge traversal over the grounded linking the same wave introduces and a guaranteed cross-surface coupling predicate. Every cross-card decision is made exactly once, in the kernel or in one named consumer.
+ - Succession channel versus conflict kind: a separate successions channel; the precedence rule is a kernel property β€” classification keys on validity only when both claims of a pair carry present windows (non-overlapping present windows succeed; overlapping windows fall through to today's assertion-time contest rule); assertion time keeps governing contestation even for windowed pairs, an expired window never suppresses contestation on its own, and the sibling assertion-time consumers stay assertion-keyed and documented as such.
+ - Window defaults: explicit input wins; absent input, ingest resolves the window from the source record's event time using the existing rung order and stores the resolved value frozen, so scan time never reads the vault.
+ - Correction record state and sweep atomicity: validity-close is the default (the predecessor stays serveable inside its window, the only regime where serve-with-correction is non-trivial); tombstone only for flatly-wrong claims; chosen per target by whether the correction is time-scoped, and recorded in the receipt. A new write-batch op type lets discovery, retirement and mention retargeting commit as one validate-all-then-commit batch; the bundle id joins the receipts.
+ - Agent-stated claims: they land in both stores with a defined bridge β€” ledger events (subject as entity, relation-derived aspect, object as value) carrying the agent_stated extractor tag, plus intake relations for synchronous entity linking; grounding is per claim (grounded commits, ungrounded reported back β€” the first partial-commit lane in the subsystem); provenance changes priority, ordering and resolution hints only, never which pairs contest.
+ - Claim-chain recall: now. The arm walks the new claim/entity edges after the linking lands within the wave, under the same boundedness rules.
+ - Windowed-slots response shape: an additive claim_events field carrying validity fields verbatim beside the count-preserving events; the schema text pins ts-only filtering so the two temporal vocabularies stay unambiguous inside one response.
+ - Multi-hop width caps: one traversal-budget object (seeds, per-node, total, depth) shared with the existing traversal-lane precedent; hub by typed-edge degree; deadline-bounded; direct-hit precedence made structural (sub-neutral lane weight or admission below the last organic row) with a pinning test reconciled against the promote-never-sink rerank pin.
+ - Serve-with-correction invariant: one shared predicate applied at every serving surface (search pool and post-rank, topic recall, context-pack, active.md, dream); a retired claim is served only beside its correction; an unresolved or out-of-reach successor drops the retired row (fail-closed, so a withheld page stays indistinguishable from an absent one); appended correction content re-runs the full visibility, agent-scope and reach filter set, closing the recorded pulled-in-successor gap.
+- **Trade-offs**:
+ - Pro: every cross-card decision exists exactly once with one test seam; the wave delivers all five capabilities including the two novel invariants.
+ - Pro: the precedence rule, the grammars and the coupling invariant each have one home, so byte-identical gating is enforced in one place per concern.
+ - Con: largest blast radius β€” ledger schema, the write path, a new batch op type and five serving surfaces change in one release; a kernel bug touches every card at once.
+ - Con: strict internal ordering (kernel first, then linking, then claim-edge traversal) removes parallelism and makes the release hard to split if review finds problems.
+ - Con: first-of-kind mechanics concentrate here: the first partial-commit write lane, the first retirement op type in the write batch, and the first guaranteed serving predicate, all introduced together.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Two Sub-Suites over a Pinned Contract
+- **Approach**: Split the wave into two sequenced sub-suites joined by a small, test-pinned contract: sub-suite A (temporal truth) delivers the ledger validity fields, the windowed events surface, and grounded agent-stated claims as ledger events; sub-suite B (correction and recall) delivers the correct verb, the deepened traversal with direct-hit precedence, and the coupling invariant, consuming A only through the contract. The contract pins exactly the three genuinely cross-card decisions β€” the axis precedence rule with the windowed event shape, the correction record-state policy, and the coupling-invariant statement β€” and nothing else.
+ - Succession channel versus conflict kind: a separate successions channel; the precedence rule is contract item 1 (both-claims-windowed pairs classify on validity; everything else keeps today's assertion behavior verbatim; an expired window never suppresses contestation), so A and B cannot drift on which time wins.
+ - Window defaults: explicit input overrides; otherwise ingest resolves from the source record's event time when that source is readable at ingest, storing the frozen resolved window; the freeze (never a live reference) is contract text.
+ - Correction record state and sweep atomicity: per target β€” a time-scoped correction closes validity (predecessor serveable in its window, coupling meaningful), a flatly-wrong claim tombstones; the choice is recorded in the bundle receipt and the policy is contract item 3, which succession logic and path-provenance annotation both read. The sweep runs validate-all dry-run first (blast-radius report), then a fail-recorded applied sequence reusing retargetWikilinks' per-write failure carry; no write-batch op type this wave; idempotent replay converges; the bundle id joins the receipts.
+ - Agent-stated claims: they land as ledger events with the agent_stated extractor tag in A, with per-claim verdicts (grounded commits, ungrounded reported back); the intake-relation bridge is contract-specified and materialized in A only where object-entity linking is needed; provenance affects priority, ordering and hints only, never which pairs contest.
+ - Claim-chain recall: document typed relations plus chunk_entities now in B, with full width caps and direct-hit precedence; claim-edge composition is deferred to the next wave behind the linking A delivers, with the contract naming the future edge source and its enablement gate β€” the one honest deferral, since those edges have no live data until A's grounded claims accumulate.
+ - Windowed-slots response shape: a dedicated events operation on brain_truth (plus a CLI subcommand, matching the existing CLI-over-MCP op asymmetry), leaving today's slots response untouched entirely so existing consumers stay byte-identical by construction; stable ascending order, named default limit, inclusive day-edge semantics inherited from the shared grammar; rows reach-gated per row like every row-returning surface.
+ - Multi-hop width caps: 8 seeds, 4 per node, 16 total as named constants with config override; hub defined by typed-edge degree, never prose; deadline-bounded; direct-hit precedence structural with a pinning test; ordered-path provenance carries only nodes readable at the caller's reach (per-node gating like the derived-fact premise gate), with contested or superseded claims annotated through the contract's record-state policy.
+ - Serve-with-correction invariant: one shared predicate module in B consumed by every serving surface; a retired row is served only beside its chain-tip correction when that successor is resolved and readable at the caller's reach, and is dropped otherwise; appended correction content re-runs the full filter set; the guarantee is pinned by a cross-suite test named in the contract.
+- **Trade-offs**:
+ - Pro: the three genuinely cross-card decisions become first-class, test-pinned artifacts instead of implicit coupling; each sub-suite has a bounded blast radius and reviews as one unit.
+ - Pro: delivers the novel invariants (guaranteed cross-surface coupling, provenance-bearing ledger claims, structural direct-hit precedence) while deferring exactly the one item with a data-maturity dependency.
+ - Pro: the dedicated events operation keeps every existing consumer byte-identical by construction, the cheapest possible off state.
+ - Con: the contract is new surface to maintain; a weak or stale contract would let the sub-suites drift exactly where they must not.
+ - Con: claim-edge composition slips a wave, and the correction sweep reports partial application rather than committing as one batch.
+- **Complexity**: large
+- **Risk**: medium
+
+## Final rationale
+
+### Recommended: Variant 3
+**Rationale**: The recons show exactly three hard couplings β€” the assertion-versus-validity axis shared by the windows and windowing cards, the correction record-state policy shared by the correct verb, the succession logic and path provenance, and the data dependency of claim-edge traversal on grounded linking β€” and Variant 3 makes exactly those three the pinned contract while leaving everything else independent, which is the DRY without the blast radius. It delivers the wave's novel invariants that Variant 1 defers (guaranteed serve-with-correction, provenance-bearing ledger claims, direct-hit precedence), and unlike Variant 2 it does not concentrate ledger schema, write-path and five-surface serving risk in one coupled release, nor introduce a first-of-kind partial-commit lane and batch op type in the same wave that introduces the underlying data. Deferring claim-edge composition behind the enablement A ships is the one honest sequencing choice, since traversal over edges with no live data cannot earn its budget.
+
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index fcb8a5fc..932f28d1 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.76.0",
+ "version": "1.77.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 3be6572f..5c18c803 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.76.0",
+ "version": "1.77.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index cd8f1d6a..76e53d68 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.76.0"
+version: "1.77.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 42e7b65c..6c36d364 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.76.0",
+ "version": "1.77.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/codex/README.md b/plugins/codex/README.md
index 4e3b51fd..4094271c 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -101,6 +101,8 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
- **Search.** Keyword search with an optional semantic lane, result explanations, recall profiles and compact cards: [search CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#search), [ranking](https://github.com/itechmeat/open-second-brain/blob/main/docs/how-it-works.md#full-text-search).
- **Session recall.** Import agent transcripts already on disk and search them: [session logs](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#session-logs-this-machine-already-has-since-v1500).
- **Hygiene.** `o2b brain hygiene scan` finds contested, duplicate, stale and unused memories; `apply` runs only the findings you pick: [maintenance](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#maintenance-and-operator-surfaces).
+- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes: [entity truth CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).
+- **Corrections.** `o2b brain lifecycle correct <target>` reports a correction's blast radius and retires the affected records - validity-closed by default, tombstoned with `--flatly-wrong`, dry run by default and `--apply` to write. A retired record that recall can still serve is served only beside its correction, never alone: [belief lifecycle CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#belief-lifecycle-and-decision-memory-since-v1330).
- **Sharing and backup.** Knowledge packs export a chosen subset; `o2b brain bank-export` writes a one-file backup bundle: [knowledge packs](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#knowledge-packs).
- **Today view and note markers.** `o2b brain today`, `@osb loop` and `@osb set` markers: [Brain CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#brain-observing-memory).
- **Self-inspection.** `o2b version`, `o2b install --friction` and `o2b state status` report what is installed and where state lives: [CLI reference](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#core).
@@ -110,10 +112,11 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
- **Semantic search:** an embedding provider plus `sqlite-vec`; the `embeddings-setup` skill walks through it: [`skills/embeddings-setup/SKILL.md`](https://github.com/itechmeat/open-second-brain/blob/main/skills/embeddings-setup/SKILL.md).
- **Decision models:** a typed judgment model that can rerank search and filter candidates, off by default per use: [`docs/decision-models.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/decision-models.md).
+- **Deep relational recall:** a fourth search arm over typed links, off by default. Its traversal runs under width budgets - 8 seeds, 4 edges per node, 16 nodes in total, and a hub above 12 walked edges is reached but not expanded - each overridable through an `OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_*` environment variable or a `search_traversal_*` config key; entity co-occurrence bridges join the walk by default and switch off separately (`OPEN_SECOND_BRAIN_SEARCH_ENTITY_BRIDGES`): [retrieval quality](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#retrieval-quality-and-context-delivery-since-v1370).
## What is new
-1.76.0 keeps the search index current without a scheduler. A search or a session start that finds the index more than a minute old answers from it as it is and starts one low-priority background run, so the next read sees the current vault; nothing stays resident, and nothing runs while no agent works. A changed note now rewrites only the parts of the index that changed, so appending to a large daily log costs a fraction of what it did, and `o2b search status` shows how fresh the index is. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+1.77.0 makes the claim ledger time-aware and correctable. A claim can carry a validity window (`o2b brain truth ingest --valid-from`/`--valid-until`, frozen from the source record when the flags are absent), `o2b brain truth events` recalls the ledger over an assertion-time slice, `o2b brain truth state` grounds an agent's stated claims with a per-claim anchoring verdict, and `o2b brain lifecycle correct` retires what a correction touches - dry run by default, with a retired record that recall can still serve answered only beside its resolved, readable correction, never alone. The deep relational recall arm now runs under width budgets with hub skipping and entity co-occurrence bridges. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index cd8f1d6a..76e53d68 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.76.0"
+version: "1.77.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index a4818511..e01288b0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.76.0"
+version = "1.77.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index b9c450ac..b88ab1fe 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -47,7 +47,7 @@ Brain verbs (observing memory):
dream Deterministic dreaming pass; stage/validate/apply/retriage bundles
apply-evidence Log a real-work application of a preference
note Append a one-line narrative milestone to Brain/log/today
- lifecycle Tombstone/supersede a memory, resolve chain tips, curator slices
+ lifecycle Tombstone/supersede a memory, correct one record, resolve chain tips, curator slices
expire Set, change or clear a signal's or preference's expiration date
note-lifecycle Note FILES: rename/move/archive/delete one, rewriting inbound links
scaffold-stub Unresolved wikilink targets: list them, or materialise a stub
@@ -94,7 +94,7 @@ Brain verbs (observing memory):
health-baseline Acknowledge-before watermark for advisories (set <date>|now / get / clear)
history Render a preference's edit-history timeline
activation Activation event store: status and sweep
- truth Claim ledger: ingest, slots, conflicts, aggregate, collisions, sweep
+ truth Claim ledger: ingest, slots, conflicts, aggregate, collisions, events, state, sweep
facts Decompose text into atomic assertions (--ingest to ledger)
dead-end Negative-knowledge registry: record and list failed approaches
foresight Forward projection: routines coming due, open commitments and questions
@@ -235,16 +235,20 @@ export const VERB_HELP: Record<string, string> = {
"event kind. CLI mirror of the MCP `brain_note` tool β€” same on-disk contract.\n" +
"Use from cron jobs and shell scripts. Multi-line text collapses to one line.\n",
lifecycle:
- "usage: o2b brain lifecycle <tombstone|supersede|temporal-replace|tip|curator> [...] [--vault <path>] [--json]\n" +
- "Cross-type tombstone + supersede lifecycle. tombstone <path> --reason <r>\n" +
+ "usage: o2b brain lifecycle <tombstone|supersede|temporal-replace|tip|curator|correct> [...] [--vault <path>] [--json]\n" +
+ "Cross-type tombstone + supersede + correct lifecycle. tombstone <path> --reason <r>\n" +
"[--superseded-by <id>] marks a memory _status: tombstoned in place (no delete);\n" +
"supersede <predecessor> <successor> tombstones the predecessor and records the\n" +
"replacement pointer; temporal-replace <predecessor> <successor> --at <T> closes the\n" +
"predecessor (valid_until = T) and opens the successor (valid_from = T) at one shared\n" +
"instant; tip <id> walks a supersede chain to its live tip; curator\n" +
"[--high-use-min <n>] lists injected-never-used, contradicted, and high-used\n" +
- "memories from observed-use verdicts. Tombstoned entries stay on disk for audit\n" +
- "but are excluded from recall, inject, and active.md.\n",
+ "memories from observed-use verdicts; correct <target> [--value <v>]\n" +
+ "[--successor <id>] [--flatly-wrong] [--window-end <T>] [--reason <r>] sweeps one\n" +
+ "record's correction - blast-radius report by default, --apply retires the target\n" +
+ "(validity close, or tombstone when --flatly-wrong), retargets mentions, appends\n" +
+ "ledger correction events and bundle-correlated receipts. Tombstoned entries stay\n" +
+ "on disk for audit but are excluded from recall, inject, and active.md.\n",
expire:
"usage: o2b brain expire <id> --expires <YYYY-MM-DD|ISO-8601|none>\n" +
" [--agent <name>] [--vault <path>] [--json]\n" +
@@ -500,13 +504,17 @@ export const VERB_HELP: Record<string, string> = {
"events outside the retention window or beyond the newest-N cap and refolds\n" +
"(--max-events 0 clears every retained event).\n",
truth:
- "usage: o2b brain truth <ingest|slots|conflicts|aggregate|collisions|sweep> [--vault <path>] [--json]\n" +
+ "usage: o2b brain truth <ingest|slots|conflicts|aggregate|collisions|events|state|sweep> [--vault <path>] [--json]\n" +
"Operator surface over the entity claim ledger (Brain/truth/). ingest appends one\n" +
"claim (--entity --aspect --value --source, optional --quantity-value/--quantity-unit/\n" +
- "--quantity-action); slots renders current values with superseded history; conflicts\n" +
- "lists contested slots (two values within the window from independent sources,\n" +
- "resolution always ask_user); aggregate sums exact (entity, action, unit) quantity\n" +
- "matches; collisions reports cross-agent convergence; sweep keeps the newest N events.\n",
+ "--quantity-action, optional --valid-from/--valid-until validity window); slots\n" +
+ "renders current values with superseded history; conflicts lists contested slots\n" +
+ "(two values within the window from independent sources, resolution always ask_user);\n" +
+ "aggregate sums exact (entity, action, unit) quantity matches; collisions reports\n" +
+ "cross-agent convergence; events recalls a windowed slice of the ledger (--entity,\n" +
+ "--since, --until, --limit); state grounds one agent-stated claim with an anchoring\n" +
+ "verdict (--subject --relation --object --text --source); sweep keeps the newest N\n" +
+ "events.\n",
facts:
"usage: o2b brain facts decompose (--file <path> | --text <text>) [--ingest --entity E] [--vault <path>] [--json]\n" +
"Deterministically decompose text into atomic assertions via markdown structure\n" +
diff --git a/src/cli/brain/verbs/lifecycle.ts b/src/cli/brain/verbs/lifecycle.ts
index 6cb26b5c..566fb048 100644
--- a/src/cli/brain/verbs/lifecycle.ts
+++ b/src/cli/brain/verbs/lifecycle.ts
@@ -1,6 +1,7 @@
/**
- * `o2b brain lifecycle <action>` - cross-type tombstone + supersede
- * lifecycle CLI (Belief lifecycle suite, Track A anchor, t_7d5a3589).
+ * `o2b brain lifecycle <action>` - cross-type tombstone + supersede +
+ * correct lifecycle CLI (Belief lifecycle suite, Track A anchor,
+ * t_7d5a3589; correct verb from truth-correctable-time-aware).
*
* Actions:
* - `tombstone <path> --reason <r> [--superseded-by <id>]`
@@ -8,12 +9,15 @@
* - `temporal-replace <predecessor> <successor> --at <T>`
* - `tip <id>` resolve a supersede chain to its live tip
* - `curator [--high-use-min <n>]` read slices over observed-use verdicts
+ * - `correct <target> [--value <v>] [--successor <id>] [--flatly-wrong]
+ * [--window-end <T>] [--reason <r>] [--apply]`
*
* CLI mirror of the `brain_lifecycle` MCP tool; both delegate to the
* core lifecycle module so the on-disk shape cannot drift.
*/
import { defaultConfigPath } from "../../../core/config.ts";
+import { correct } from "../../../core/brain/lifecycle/correction.ts";
import { curatorSlices } from "../../../core/brain/lifecycle/curator.ts";
import { temporalReplace } from "../../../core/brain/lifecycle/temporal-replace.ts";
import {
@@ -54,13 +58,18 @@ export async function cmdBrainLifecycle(argv: string[]): Promise<number> {
"superseded-by": { type: "string" },
"high-use-min": { type: "string" },
at: { type: "string" },
+ value: { type: "string" },
+ successor: { type: "string" },
+ "window-end": { type: "string" },
+ "flatly-wrong": { type: "boolean" },
+ apply: { type: "boolean" },
json: { type: "boolean" },
});
const action = positional[0];
if (action === undefined) {
return usageError(
- "brain lifecycle requires an action: tombstone | supersede | temporal-replace | tip | curator",
+ "brain lifecycle requires an action: tombstone | supersede | temporal-replace | tip | curator | correct",
);
}
@@ -163,6 +172,62 @@ export async function cmdBrainLifecycle(argv: string[]): Promise<number> {
}
return 0;
}
+ case "correct": {
+ const target = positional[1];
+ if (target === undefined) {
+ return usageError("brain lifecycle correct requires a target path");
+ }
+ const value = normalizeFlagString(flags["value"]) ?? undefined;
+ const successor = normalizeFlagString(flags["successor"]) ?? undefined;
+ const windowEnd = normalizeFlagString(flags["window-end"]) ?? undefined;
+ const reason = normalizeFlagString(flags["reason"]) ?? undefined;
+ const flatlyWrong = flags["flatly-wrong"] === true;
+ // Dry run is the DEFAULT; --apply runs the sweep for real.
+ const dryRun = flags["apply"] !== true;
+ const res = correct({
+ vault,
+ target,
+ ...(value !== undefined ? { value } : {}),
+ ...(successor !== undefined ? { successor } : {}),
+ ...(windowEnd !== undefined ? { windowEnd } : {}),
+ ...(reason !== undefined ? { reason } : {}),
+ flatlyWrong,
+ dryRun,
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ const payload = {
+ bundle_id: res.bundleId,
+ dry_run: res.dryRun,
+ blast_radius: {
+ target: res.blastRadius.target,
+ replaced_by: res.blastRadius.replacedBy,
+ contests: res.blastRadius.contests,
+ mentions: res.blastRadius.mentions,
+ claims: res.blastRadius.claims,
+ },
+ retirements: res.retirements.map((r) => ({
+ path: r.path,
+ end_state: r.endState,
+ valid_until: r.validUntil,
+ reason_code: r.reasonCode,
+ changed: r.changed,
+ })),
+ retarget: res.retarget,
+ ledger: res.ledger,
+ receipts: res.receipts,
+ };
+ if (wantsJson) {
+ okJson(payload);
+ } else {
+ ok(
+ `${res.dryRun ? "dry run" : "applied"} correction bundle ${res.bundleId}: ` +
+ `${res.retirements.length} retirement(s), ${res.retarget.rewritten.length} mention file(s) rewritten, ` +
+ `${res.ledger.length} ledger event(s), ${res.receipts.length} receipt(s)`,
+ );
+ }
+ return 0;
+ }
case "tip": {
const id = positional[1];
if (id === undefined) {
diff --git a/src/cli/brain/verbs/truth.ts b/src/cli/brain/verbs/truth.ts
index a805248a..b6af68bf 100644
--- a/src/cli/brain/verbs/truth.ts
+++ b/src/cli/brain/verbs/truth.ts
@@ -1,9 +1,12 @@
/**
* `o2b brain truth <op>` (Entity Truth & Self-Improving Dream Suite):
- * operator surface over the claim ledger - `ingest` appends one claim,
- * `slots` and `conflicts` render the fold (with conflict detection),
- * `aggregate` sums exact-match quantities, `collisions` reports
- * cross-agent convergence, `sweep` bounds the ledger.
+ * operator surface over the claim ledger - `ingest` appends one claim
+ * (optionally validity-windowed), `slots` and `conflicts` render the
+ * fold (with conflict detection), `aggregate` sums exact-match
+ * quantities, `collisions` reports cross-agent convergence, `events`
+ * recalls a windowed slice of the ledger, `state` grounds one
+ * agent-stated claim with an anchoring verdict, `sweep` bounds the
+ * ledger.
*
* Exit codes: 0 on success, 1 on an operational failure, 2 on usage
* errors.
@@ -12,27 +15,51 @@
import { aggregateQuantities } from "../../../core/brain/truth/aggregate.ts";
import { detectAgentCollisions } from "../../../core/brain/truth/collision.ts";
import { computeTruthStateWithConflicts } from "../../../core/brain/truth/conflicts.ts";
+import { claimEventLimit } from "../../../core/brain/truth/events-window.ts";
import {
appendClaimEvent,
CLAIM_EVENT_MAX_COUNT,
+ ClaimWindowRefusal,
readClaimEvents,
sweepClaimEvents,
} from "../../../core/brain/truth/store.ts";
+import {
+ appendStatedClaims,
+ StatedClaimsRefusal,
+} from "../../../core/brain/truth/stated-claims.ts";
import { normalizeEntityName } from "../../../core/brain/entities/canonical.ts";
import { isoSecond } from "../../../core/brain/time.ts";
+import { SearchError } from "../../../core/search/types.ts";
+import { TRANSPORT_REACH } from "../../../core/graph/transport-reach.ts";
+import { resolveAgentName } from "../../../core/config.ts";
+import { claimEventsReport, statedClaimEntities } from "../../../mcp/brain/knowledge-tools.ts";
+import { parseTimeBounds } from "../../../mcp/brain/time-bounds.ts";
import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
-const OPS = ["ingest", "slots", "conflicts", "aggregate", "collisions", "sweep"] as const;
+const OPS = [
+ "ingest",
+ "slots",
+ "conflicts",
+ "aggregate",
+ "collisions",
+ "events",
+ "state",
+ "sweep",
+] as const;
type TruthOp = (typeof OPS)[number];
const USAGE =
- "usage: o2b brain truth <ingest|slots|conflicts|aggregate|collisions|sweep>\n" +
+ "usage: o2b brain truth <ingest|slots|conflicts|aggregate|collisions|events|state|sweep>\n" +
" ingest --entity E --aspect A --value V --source S [--agent N] [--ts ISO]\n" +
+ " [--valid-from X --valid-until Y]\n" +
" [--quantity-value N --quantity-unit U --quantity-action W]\n" +
" slots [--entity E]\n" +
" conflicts [--window-days N]\n" +
" aggregate --action W [--unit U] [--entity E]\n" +
" collisions [--window-days N]\n" +
+ " events [--entity E] [--since X] [--until Y] [--limit N]\n" +
+ " state --subject S --relation R --object O --text T --source S\n" +
+ " [--agent N]\n" +
" sweep [--max-events N]\n" +
" common [--vault <path>] [--json]";
@@ -55,6 +82,15 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {
source: { type: "string" },
agent: { type: "string" },
ts: { type: "string" },
+ "valid-from": { type: "string" },
+ "valid-until": { type: "string" },
+ subject: { type: "string" },
+ relation: { type: "string" },
+ object: { type: "string" },
+ text: { type: "string" },
+ since: { type: "string" },
+ until: { type: "string" },
+ limit: { type: "string" },
"quantity-value": { type: "string" },
"quantity-unit": { type: "string" },
"quantity-action": { type: "string" },
@@ -97,22 +133,40 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {
action: (flags["quantity-action"] as string | undefined) ?? null,
};
}
- const result = appendClaimEvent(vault, {
- ts: (flags["ts"] as string | undefined) ?? isoSecond(new Date()),
- agent: resolveBrainAgent(flags, config),
- entity: requireString(flags, "entity"),
- aspect: requireString(flags, "aspect"),
- value: requireString(flags, "value"),
- valueKind,
- ...(quantity !== undefined ? { quantity } : {}),
- source: requireString(flags, "source"),
- });
+ const validFrom = flags["valid-from"] as string | undefined;
+ const validUntil = flags["valid-until"] as string | undefined;
+ // Validity windows (contract item 1): presence-gated passthrough;
+ // the store refuses an unparseable or inverted window by name,
+ // mapped to the usage failure class - a mistyped window is the
+ // same kind of mistake as --since garbage or --limit 0.
+ let result;
+ try {
+ result = appendClaimEvent(vault, {
+ ts: (flags["ts"] as string | undefined) ?? isoSecond(new Date()),
+ agent: resolveBrainAgent(flags, config),
+ entity: requireString(flags, "entity"),
+ aspect: requireString(flags, "aspect"),
+ value: requireString(flags, "value"),
+ valueKind,
+ ...(quantity !== undefined ? { quantity } : {}),
+ ...(validFrom !== undefined ? { validFrom } : {}),
+ ...(validUntil !== undefined ? { validUntil } : {}),
+ source: requireString(flags, "source"),
+ });
+ } catch (exc) {
+ if (exc instanceof ClaimWindowRefusal) throw new UsageError((exc as Error).message);
+ throw exc;
+ }
const body = {
ok: true,
entity: result.event.entity,
aspect: result.event.aspect,
value: result.event.value,
path: result.path,
+ ...(result.event.validFrom !== undefined ? { valid_from: result.event.validFrom } : {}),
+ ...(result.event.validUntil !== undefined
+ ? { valid_until: result.event.validUntil }
+ : {}),
};
if (asJson) okJson(body);
else ok(`claim recorded: ${body.entity} / ${body.aspect} = ${body.value}`);
@@ -199,6 +253,135 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {
}
return 0;
}
+ case "events": {
+ // Bounds parse through the shared time-bounds wrapper - the same
+ // parser the MCP events operation refuses with - mapped to the
+ // INVALID_PARAMS-equivalent exit-2 usage error.
+ let sinceMs: number | null;
+ let untilMs: number | null;
+ try {
+ const bounds = parseTimeBounds(
+ flags["since"] as string | undefined,
+ flags["until"] as string | undefined,
+ );
+ sinceMs = bounds.sinceMs;
+ untilMs = bounds.untilMs;
+ } catch (exc) {
+ if (exc instanceof SearchError) throw new UsageError(exc.message);
+ throw exc;
+ }
+ const limitRaw = flags["limit"] as string | undefined;
+ // A non-numeric --limit reaches the shared limit guard as NaN,
+ // and that guard's refusal would stringify the NaN as "null" -
+ // naming nothing the operator typed. Validate the flag is finite
+ // here, before that message is composed, and name the raw value.
+ if (limitRaw !== undefined && !Number.isFinite(Number(limitRaw))) {
+ throw new UsageError(
+ `--limit must be a positive integer, got ${JSON.stringify(limitRaw)}`,
+ );
+ }
+ let limit: number;
+ try {
+ limit = claimEventLimit(limitRaw === undefined ? undefined : Number(limitRaw));
+ } catch (exc) {
+ throw new UsageError((exc as Error).message);
+ }
+ // The CLI runs at local reach (stdio child of the caller); the
+ // owner-scope gate still binds the server-resolved identity. The
+ // body is the shared claimEventsReport, so this surface answers
+ // byte-identically to the MCP operation at the same query.
+ const body = claimEventsReport(vault, resolveAgentName(config), TRANSPORT_REACH.local, {
+ entity: flags["entity"] as string | undefined,
+ sinceMs,
+ untilMs,
+ limit,
+ });
+ if (asJson) {
+ okJson(body);
+ } else {
+ const rows = body.events as ReadonlyArray<{
+ ts: string;
+ entity: string;
+ aspect: string;
+ value: string;
+ source: string;
+ }>;
+ ok(
+ `events: ${body.total} matched, ${rows.length} shown` +
+ `${body.truncated ? ", truncated" : ""}`,
+ );
+ for (const e of rows) {
+ ok(` ${e.ts} ${e.entity} / ${e.aspect} = ${e.value} ${e.source}`);
+ }
+ }
+ return 0;
+ }
+ case "state": {
+ // One agent-stated claim per invocation, through the same
+ // grounded-claim core the MCP state operation calls: the payload
+ // boundary refuses whole (unknown relation, missing text or
+ // source) as the INVALID_PARAMS-equivalent usage error, and the
+ // anchoring verdict - committed event or reported-back reasons -
+ // is the answer.
+ const body = (() => {
+ try {
+ const outcome = appendStatedClaims(
+ vault,
+ {
+ claims: [
+ {
+ subject: requireString(flags, "subject"),
+ relation: requireString(flags, "relation"),
+ object: requireString(flags, "object"),
+ },
+ ],
+ text: requireString(flags, "text"),
+ agent: resolveBrainAgent(flags, config),
+ ts: isoSecond(new Date()),
+ source: requireString(flags, "source"),
+ },
+ { entities: statedClaimEntities(vault), configPath: config },
+ );
+ return {
+ ok: true,
+ operation: "state" as const,
+ committed: outcome.committed.map((result) => ({ ...result.event })),
+ ungrounded: outcome.ungrounded.map(({ claim, reasons }) => ({
+ subject: claim.subject,
+ relation: claim.relation,
+ object: claim.object,
+ reasons,
+ })),
+ };
+ } catch (exc) {
+ // Both refusal channels are mistyped-input refusals, so both
+ // answer as the usage failure class - the same mapping the
+ // ingest case applies, so the state verb never answers a
+ // window the SOURCE record carries as an operational failure.
+ if (exc instanceof StatedClaimsRefusal || exc instanceof ClaimWindowRefusal) {
+ throw new UsageError((exc as Error).message);
+ }
+ throw exc;
+ }
+ })();
+ if (asJson) {
+ okJson(body);
+ } else {
+ if (body.committed.length > 0) {
+ for (const row of body.committed) {
+ const r = row as { entity: string; aspect: string; value: string };
+ ok(`anchored claim recorded: ${r.entity} / ${r.aspect} = ${r.value}`);
+ }
+ }
+ for (const u of body.ungrounded) {
+ ok(
+ `ungrounded claim reported back: ${u.subject} / ${u.relation} / ${u.object}` +
+ ` (${u.reasons.join(", ")})`,
+ );
+ }
+ }
+ return 0;
+ }
case "sweep": {
const maxRaw = flags["max-events"] as string | undefined;
const maxEvents = maxRaw !== undefined ? Number(maxRaw) : CLAIM_EVENT_MAX_COUNT;
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index 223d6872..33fafa76 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -46,6 +46,13 @@ import {
import { isPreferenceVisible } from "./owner-scoped-facts.ts";
import { parseRetired } from "./preference.ts";
import { collectPreferences, resolveOwnerScopeDelivery } from "./preferences-collect.ts";
+import {
+ SUPERSEDED_BY_KEY,
+ buildChainLookup,
+ resolveChainTip,
+ type ChainLookup,
+} from "./lifecycle/tombstone.ts";
+import { chainVerdict } from "../search/correction-coupling.ts";
import { BRAIN_TOMBSTONE_STATUS } from "./types.ts";
import { BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "./path-constants.ts";
import { brainActivePath, brainDirsForWrite } from "./paths.ts";
@@ -384,6 +391,10 @@ function readRecentlyRetired(
if (!existsSync(dirs.retired)) return [];
const scope = resolveOwnerScopeDelivery(vault, agentScope).enforcedScope;
const out: BrainRetired[] = [];
+ // The serve-with-correction chain index, built on the first
+ // pointer-bearing record and reused for the rest of the walk: a vault
+ // whose retired records carry no pointer never pays for it.
+ let chainLookup: ChainLookup | null = null;
for (const name of readdirSync(dirs.retired)) {
// Filtered BEFORE the newest-first cut, so a withheld record never
// pushes a visible one out of the list either.
@@ -392,6 +403,21 @@ function readRecentlyRetired(
try {
const retired = parseRetired(full);
if (scope !== null && !isPreferenceVisible(retired, scope)) continue;
+ // Serve-with-correction coupling (truth-correctable-time-aware,
+ // contract item 3): a retired record whose frontmatter declares a
+ // successor - the serveable-retired regime - is digested only
+ // beside its resolved, readable chain-tip correction and is
+ // omitted fail-closed otherwise. A record with no pointer is not
+ // in the predicate's regime and keeps today's rendering.
+ const pointer = retired[SUPERSEDED_BY_KEY];
+ if (typeof pointer === "string" && pointer.trim() !== "") {
+ chainLookup ??= buildChainLookup(vault, readable);
+ const verdict = chainVerdict(
+ posix.join(BRAIN_RETIRED_REL, name),
+ resolveChainTip(pointer, chainLookup),
+ );
+ if (verdict.action === "drop") continue;
+ }
out.push(retired);
} catch {
// Same rationale as readActivePreferences.
diff --git a/src/core/brain/artifact-ref-view.ts b/src/core/brain/artifact-ref-view.ts
index 66de1a51..025cbc3e 100644
--- a/src/core/brain/artifact-ref-view.ts
+++ b/src/core/brain/artifact-ref-view.ts
@@ -30,7 +30,7 @@
*/
import { join } from "node:path";
-import { existsSync } from "node:fs";
+import { existsSync, statSync } from "node:fs";
import { pathIsInside, vaultRelative } from "../path-safety.ts";
import type { FrontmatterCache } from "../search/result-filters.ts";
@@ -42,9 +42,11 @@ const MARKDOWN_EXT = ".md";
/**
* A reference a report row carries: either a vault-relative path
- * (`Brain/preferences/pref-x.md`, `notes/y.md`) or a bare Brain artifact
- * id (`pref-x`, `ret-y`, `sig-2026-05-01-z`), optionally spelled as a
- * wikilink (`[[pref-x]]`, `[[notes/y.md]]`).
+ * (`Brain/preferences/pref-x.md`, `notes/y.md`), an extensionless
+ * vault-page spelling of one (`Brain/notes/private`, the conventional
+ * Obsidian wikilink body), or a bare Brain artifact id (`pref-x`,
+ * `ret-y`, `sig-2026-05-01-z`), optionally spelled as a wikilink
+ * (`[[pref-x]]`, `[[notes/y.md]]`).
*
* `null` / `undefined` / empty are accepted and read as "this row names
* nothing here", which is visible: a row with no subject cannot disclose
@@ -175,6 +177,35 @@ function artifactPath(vault: string, id: string): string | null {
return null;
}
+/**
+ * The candidate an extensionless vault-page reference denotes: the bare
+ * spelling when that file exists, else its `.md` twin when the twin
+ * exists - the same first-existing rule the claim ledger's write side
+ * applies to an extensionless source, so the read-side gate cannot drift
+ * from the spelling the writer used. When neither file exists the
+ * reference names nothing here (`null` reads as visible): a convention
+ * like `Notes/<slug>-applied` in a log payload is not a page, and
+ * judging it as a missing `.md` page would drop every row carrying it.
+ * Both candidates are probed only inside the vault, so a
+ * traversal-shaped reference never reaches the filesystem outside it.
+ */
+function pageCandidate(vault: string, bare: string): string | null {
+ if (isVaultFile(vault, bare)) return bare;
+ const twin = bare + MARKDOWN_EXT;
+ if (isVaultFile(vault, twin)) return twin;
+ return null;
+}
+
+/** The vault-relative path names a regular file, so it can name a page. */
+function isVaultFile(vault: string, rel: string): boolean {
+ if (!pathIsInside(join(vault, rel), vault)) return false;
+ try {
+ return statSync(join(vault, rel)).isFile();
+ } catch {
+ return false;
+ }
+}
+
/**
* Bind one per-path rule to one vault, as a reference-shaped view.
*
@@ -198,13 +229,22 @@ export function artifactRefView(
if (ref === null || ref === undefined || ref.length === 0) return true;
const memo = verdicts.get(ref);
if (memo !== undefined) return memo;
- // A reference that names a path is resolved as one; anything else is
- // a Brain artifact id, and an id with no artifact on disk names
- // nothing that could be hidden - see {@link artifactPath} for why
- // that reading is only true while its directory list is complete.
+ // A reference that names a path is resolved as one - including its
+ // extensionless spelling, whose .md twin is the page an Obsidian
+ // writer named (a gate that resolved only the .md form failed OPEN
+ // for exactly that spelling). A bare id is a Brain artifact id, and
+ // an id with no artifact on disk names nothing that could be hidden
+ // - see {@link artifactPath} for why that reading is only true while
+ // its directory list is complete.
const bare = unbracket(ref);
const rel =
- bare.length === 0 ? null : bare.endsWith(MARKDOWN_EXT) ? bare : artifactPath(vault, bare);
+ bare.length === 0
+ ? null
+ : bare.endsWith(MARKDOWN_EXT)
+ ? bare
+ : bare.includes("/")
+ ? pageCandidate(vault, bare)
+ : artifactPath(vault, bare);
// A reference that resolves outside the vault names no page anyone
// could be shown, and is hidden before the rule reads anything: log
// bodies carry strings an earlier caller wrote.
diff --git a/src/core/brain/atomic-facts.ts b/src/core/brain/atomic-facts.ts
index 3615496e..e5641eb1 100644
--- a/src/core/brain/atomic-facts.ts
+++ b/src/core/brain/atomic-facts.ts
@@ -114,6 +114,29 @@ export function splitSentences(text: string): string[] {
/** Minimum normalised form length that participates in substring matching. */
const MIN_ANCHOR_FORM_LENGTH = 3;
+/**
+ * The occurrence-anchoring kernel (truth-correctable-time-aware,
+ * task 4): the quality-gated normalized match forms that literally
+ * occur in `text`. Candidate labels pass through the quality gate
+ * (sanitize decoration, then normalize, drop structurally-invalid
+ * forms) before matching, and forms shorter than
+ * {@link MIN_ANCHOR_FORM_LENGTH} never participate. Pure: no I/O, no
+ * registry. The one kernel every occurrence-anchoring caller shares -
+ * the assertion decomposer and the agent-stated claim verdicts both
+ * anchor through it, so the two can never drift.
+ */
+export function anchorEntityForms(
+ text: string,
+ forms: ReadonlyArray<string>,
+): ReadonlyArray<string> {
+ const haystack = normalizeEntityName(text);
+ return Object.freeze(
+ entityMatchForms(forms).filter(
+ (f) => f.length >= MIN_ANCHOR_FORM_LENGTH && haystack.includes(f),
+ ),
+ );
+}
+
/**
* Anchor an assertion against active registry entities, sorted ids. Labels
* pass through the quality gate (sanitise decoration, then normalise, drop
@@ -123,14 +146,12 @@ const MIN_ANCHOR_FORM_LENGTH = 3;
*/
function anchorEntities(text: string, entities: ReadonlyArray<AtomicEntityLike>): string[] {
if (entities.length === 0) return [];
- const haystack = normalizeEntityName(text);
const ids: string[] = [];
for (const entity of entities) {
if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;
- const forms = entityMatchForms([entity.name, ...entity.aliases]).filter(
- (f) => f.length >= MIN_ANCHOR_FORM_LENGTH,
- );
- if (forms.some((f) => haystack.includes(f))) ids.push(entity.id);
+ if (anchorEntityForms(text, [entity.name, ...entity.aliases]).length > 0) {
+ ids.push(entity.id);
+ }
}
return ids.toSorted();
}
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index 6cc4b1b5..ee7bf930 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -32,7 +32,8 @@ import {
resolveOwnerScopeDelivery,
type OwnerScopeDelivery,
} from "./preferences-collect.ts";
-import { isTombstoned } from "./lifecycle/tombstone.ts";
+import { buildChainLookup, isTombstoned, resolveChainTip } from "./lifecycle/tombstone.ts";
+import { chainVerdict } from "../search/correction-coupling.ts";
import { preferChainTips } from "./inject-governor.ts";
import { tensionWarningsForContextItems } from "./tensions.ts";
import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
@@ -409,6 +410,36 @@ function withOptionalLanes(
};
}
+/**
+ * Serve-with-correction coupling over the collected candidates
+ * (truth-correctable-time-aware, contract item 3). A candidate whose
+ * frontmatter declares a successor - the serveable-retired regime the
+ * correct verb's validity-close writes - is kept only beside its
+ * resolved, readable chain-tip correction and is dropped fail-closed
+ * when a hop dangles; a candidate with no pointer is not in the
+ * predicate's regime and passes through unchanged. `visible` is the
+ * caller's per-page verdict over ABSOLUTE paths; it becomes the chain
+ * lookup's readability, so a tip the caller may not read resolves as
+ * little as nothing at all.
+ */
+function applyCouplingToCandidates(
+ vault: string,
+ candidates: ReadonlyArray<Candidate>,
+ visible: ((absPath: string) => boolean) | undefined,
+): ReadonlyArray<Candidate> {
+ if (candidates.every((c) => c.supersededBy === null)) return candidates;
+ const readable = visible === undefined ? undefined : (rel: string) => visible(join(vault, rel));
+ const chainLookup = buildChainLookup(vault, readable);
+ return candidates.filter((c) => {
+ if (c.supersededBy === null) return true;
+ const verdict = chainVerdict(
+ relative(vault, c.path),
+ resolveChainTip(c.supersededBy, chainLookup),
+ );
+ return verdict.action === "serve_coupled";
+ });
+}
+
function collectCandidates(
vault: string,
delimitUntrusted: boolean,
@@ -540,9 +571,22 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
// supersession chains passes through byte-identically.
const ownerScope = resolveOwnerScopeDelivery(vault, opts.agentScope);
const collected = collectCandidates(vault, delimitUntrusted, ownerScope);
+ // Serve-with-correction coupling (truth-correctable-time-aware,
+ // contract item 3): a candidate the chain-tip preference would keep -
+ // under `includeHistorical`, a superseded ancestor - is injected only
+ // beside its resolved, readable chain-tip correction and is dropped
+ // fail-closed when a hop dangles, so a historical injection cannot
+ // resurrect a predecessor whose correction is not there. The caller's
+ // visibility is the chain lookup's readability, so a withheld tip
+ // resolves exactly as little as the caller may read. Non-historical
+ // injection keeps only tips and is unchanged.
+ const coupled =
+ opts.includeHistorical === true
+ ? applyCouplingToCandidates(vault, collected.candidates, opts.visible)
+ : collected.candidates;
// Reach filtering happens after the chain-tip preference: a withheld
// tip must not resurrect the superseded ancestor it replaced.
- const tips = preferChainTips(collected.candidates, {
+ const tips = preferChainTips(coupled, {
historical: opts.includeHistorical === true,
}).kept;
const withheldIds = new Set<string>();
diff --git a/src/core/brain/dream-scan.ts b/src/core/brain/dream-scan.ts
index 6070a716..328b143d 100644
--- a/src/core/brain/dream-scan.ts
+++ b/src/core/brain/dream-scan.ts
@@ -23,7 +23,13 @@ import type {
ScanResult,
SignalRecord,
} from "./dream-plan.ts";
-import { isTombstoned } from "./lifecycle/tombstone.ts";
+import {
+ isTombstoned,
+ SUPERSEDED_BY_KEY,
+ buildChainLookup,
+ resolveChainTip,
+} from "./lifecycle/tombstone.ts";
+import { chainVerdict } from "../search/correction-coupling.ts";
import { brainDirs } from "./paths.ts";
import { parsePreference } from "./preference.ts";
import { parseSignal } from "./signal.ts";
@@ -170,11 +176,19 @@ function collectPreferences(
}
function collectRetired(
+ vault: string,
files: ReadonlyArray<string>,
retired: RetiredRecord[],
corrupted: CorruptedEntry[],
walk: DirectoryWalk,
): void {
+ // The serve-with-correction chain index, built on the first
+ // pointer-bearing record and reused for the rest of the walk: a vault
+ // whose retired records carry no pointer never pays for it. The scan
+ // runs at the operator's own reach, so every on-disk page is indexed -
+ // resolution here asks only whether the chain terminates, not who may
+ // read it.
+ let chainLookup: ReturnType<typeof buildChainLookup> | null = null;
for (const full of files) {
walk.step();
// Retired files we only need for topic + id (for supersede
@@ -193,6 +207,19 @@ function collectRetired(
? (meta["user_rejected_reason"] as string).trim()
: "";
if (topic && id) {
+ // Serve-with-correction coupling (truth-correctable-time-aware,
+ // contract item 3): a retired record whose frontmatter declares
+ // a successor - the serveable-retired regime - is scanned only
+ // when that chain resolves to a tip, and is dropped fail-closed
+ // when a hop dangles, so the pass never plans over a correction
+ // that is not there. A record with no pointer is not in the
+ // predicate's regime and is scanned as before.
+ const pointer = meta[SUPERSEDED_BY_KEY];
+ if (typeof pointer === "string" && pointer.trim() !== "") {
+ chainLookup ??= buildChainLookup(vault);
+ const verdict = chainVerdict(id, resolveChainTip(pointer, chainLookup));
+ if (verdict.action === "drop") continue;
+ }
retired.push({
path: full,
topic,
@@ -274,7 +301,7 @@ function scanBrainRun(
() => collectSignals(processed, false, signals, corrupted, walk),
() => collectSignals(archived, false, signals, corrupted, walk, true),
() => collectPreferences(preferenceFiles, preferences, corrupted, walk),
- () => collectRetired(retiredFiles, retired, corrupted, walk),
+ () => collectRetired(vault, retiredFiles, retired, corrupted, walk),
];
for (const collect of collectors) {
opts.safeguard?.checkpoint();
diff --git a/src/core/brain/lifecycle/correction.ts b/src/core/brain/lifecycle/correction.ts
new file mode 100644
index 00000000..c1f0ec99
--- /dev/null
+++ b/src/core/brain/lifecycle/correction.ts
@@ -0,0 +1,674 @@
+/**
+ * The correct-verb sweep core (truth-correctable-time-aware, Task 16).
+ *
+ * One entry, {@link correct}, sweeps one record's correction end to end:
+ * discovery gathers the affected set within the caller's reach (the
+ * claim-graph closure over `whatReplaced`/`whatContests`, a match-only
+ * wikilink mention scan via `retargetWikilinks` with `apply: false`, and
+ * the same-entity/aspect truth-ledger claims), the dry run - the DEFAULT
+ * - writes nothing and returns that blast-radius report, and the applied
+ * run executes a fail-recorded sequence:
+ *
+ * 1. per-target retirement through the correction end-state policy
+ * (contract item 2): `flatlyWrong` tombstones via the shared
+ * tombstone writer, every other correction closes validity at the
+ * window end or at the correction instant, leaving the record
+ * serveable inside its historical window;
+ * 2. ledger correction events asserting the corrected value under the
+ * corrected record's own source - a same-source value change reads
+ * as self-correction in the fold, never a conflict - each opening
+ * its validity window at the correction instant;
+ * 3. mention retargeting with `retargetWikilinks`' per-write failure
+ * carry, never rewriting Brain/log or the receipt lines;
+ * 4. bundle-correlated receipts with `correction_bundle:<bundleId>`
+ * in `evidence_triggers`, the existing reason codes carried
+ * name-aligned (`supersede` for validity_close, `tombstone` for
+ * tombstone).
+ *
+ * Replay converges: an already-applied retirement is a no-op, a closed
+ * window is never re-closed, the ledger is not re-appended, and the
+ * receipts report `appended: false`. Every write passes the
+ * vault-identity guard, and a target the caller may not read is refused
+ * as a missing one before anything is written.
+ */
+
+import { join } from "node:path";
+
+import { normalizeAgentArgument } from "../../agent-identity.ts";
+import { resolveAgentName } from "../../config.ts";
+import { sanitiseTextField } from "../../redactor.ts";
+import type { FrontmatterMap } from "../../types.ts";
+import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
+import { appendDecisionChangeReceipt } from "../decisions/receipts.ts";
+import {
+ LIFECYCLE_STATUS_KEY,
+ LIFECYCLE_STATUS_KEY_NORMALIZED,
+ normalizeChainLink,
+ readLifecycleState,
+ SUPERSEDED_BY_KEY,
+ SUPERSEDE_DEFAULT_REASON,
+ tombstone,
+} from "./tombstone.ts";
+import { appendLogEvent } from "../log.ts";
+import { resolveNotePath } from "../note-path.ts";
+import { BRAIN_DECISIONS_REL, BRAIN_LOG_REL } from "../path-constants.ts";
+import { isoSecond } from "../time.ts";
+import { vaultRelative } from "../paths.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { retargetWikilinks } from "../page-dedup.ts";
+import {
+ buildClaimGraph,
+ whatContests,
+ whatReplaced,
+ type ClaimGraph,
+ type ClaimNode,
+} from "../claim-graph.ts";
+import { stripWikilinkDecoration } from "../wikilink.ts";
+import { correctionEndState, type CorrectionEndState } from "../truth/correction-policy.ts";
+import { appendClaimEvent, ClaimWindowRefusal, readClaimEvents } from "../truth/store.ts";
+import { isValidityPoint } from "../truth/validity.ts";
+import type { ClaimEvent } from "../truth/types.ts";
+
+/** The receipt reason code a validity-close retirement is recorded under. */
+const REASON_CODE_SUPERSEDE = "supersede" as const;
+/** The receipt reason code a tombstone retirement is recorded under. */
+const REASON_CODE_TOMBSTONE = "tombstone" as const;
+
+/** Frontmatter key of a validity window end (the temporal-replace convention). */
+const VALID_UNTIL_KEY = "valid_until";
+
+/** The `evidence_triggers` prefix every bundle-correlated receipt carries. */
+export const CORRECTION_BUNDLE_TRIGGER_PREFIX = "correction_bundle:";
+
+/**
+ * Cap on the rationale the tombstone-path receipt carries, mirroring the
+ * shared tombstone writer's own reason cap (`REASON_MAX_LEN` in
+ * tombstone.ts): the receipt this sweep mints must be writable under the
+ * same limits the writer it stands in for would have met.
+ */
+const TOMBSTONE_RATIONALE_MAX_LEN = 512;
+
+/** Raised when a correction target or input is refused. */
+export class CorrectionError extends Error {
+ constructor(message: string, options?: { readonly cause?: unknown }) {
+ super(message, options);
+ this.name = "CorrectionError";
+ }
+}
+
+export interface CorrectInput {
+ readonly vault: string;
+ /** Vault-relative POSIX path of the record being corrected. */
+ readonly target: string;
+ /**
+ * The corrected value the ledger events assert. Absent: the sweep
+ * retires and retargets but appends nothing to the ledger.
+ */
+ readonly value?: string;
+ /**
+ * Successor id or wikilink stored as the target's `superseded_by`
+ * pointer and used as the mention-retarget destination. Absent: no
+ * pointer is written and mentions are only reported.
+ */
+ readonly successor?: string;
+ /** The caller declares the prior claim was never true, not merely superseded. */
+ readonly flatlyWrong?: boolean;
+ /** Explicit window end for a time-scoped correction (canonical ISO-8601 UTC). */
+ readonly windowEnd?: string;
+ /** Operator-facing reason for the retirement. */
+ readonly reason?: string;
+ /**
+ * False runs the applied sequence. Absent or true - the default - the
+ * sweep only reports the blast radius and writes nothing.
+ */
+ readonly dryRun?: boolean;
+ /** Identity override; resolver default used when omitted or blank. */
+ readonly agent?: string;
+ /** Wall clock for the correction instant. Defaults to `new Date()`. */
+ readonly now?: Date;
+ readonly configPath?: string;
+ /**
+ * The vault-relative paths the caller may read. A target it may not
+ * read is refused as a missing one, before anything is written, and
+ * every discovered row stays inside the same reach. Absent, every
+ * path may be read.
+ */
+ readonly readable?: (rel: string) => boolean;
+}
+
+/** What one discovery found inside the caller's reach. */
+export interface CorrectionBlastRadius {
+ /** Vault-relative path of the target. */
+ readonly target: string;
+ /** Claim-graph chain tip that replaced the target, null when unresolved. */
+ readonly replacedBy: string | null;
+ /** Claim-graph ids contesting the target, sorted. */
+ readonly contests: ReadonlyArray<string>;
+ /** Files holding at least one mention of the target, sorted, reach-gated. */
+ readonly mentions: ReadonlyArray<string>;
+ /** Reach-gated ledger events in the target's slots, including the target's own. */
+ readonly claims: ReadonlyArray<ClaimEvent>;
+}
+
+/** How one target retired. */
+export interface CorrectionRetirement {
+ readonly path: string;
+ readonly endState: CorrectionEndState;
+ readonly validUntil: string | null;
+ /** The existing receipt reason code the choice is recorded under. */
+ readonly reasonCode: typeof REASON_CODE_SUPERSEDE | typeof REASON_CODE_TOMBSTONE;
+ /** False when the retirement was already in place (replay). */
+ readonly changed: boolean;
+}
+
+/** One bundle-correlated receipt the sweep asked for. */
+export interface CorrectionReceiptRecord {
+ readonly subject: string;
+ readonly appended: boolean;
+}
+
+/** The outcome of one sweep, dry or applied. */
+export interface CorrectResult {
+ readonly bundleId: string;
+ readonly dryRun: boolean;
+ readonly blastRadius: CorrectionBlastRadius;
+ /** Empty on a dry run. */
+ readonly retirements: ReadonlyArray<CorrectionRetirement>;
+ readonly retarget: {
+ readonly matched: ReadonlyArray<string>;
+ readonly rewritten: ReadonlyArray<string>;
+ readonly failed: ReadonlyArray<Readonly<{ path: string; reason: string }>>;
+ };
+ /** Empty on a dry run. */
+ readonly ledger: ReadonlyArray<{
+ readonly entity: string;
+ readonly aspect: string;
+ readonly value: string;
+ readonly source: string;
+ }>;
+ /** Empty on a dry run. */
+ readonly receipts: ReadonlyArray<CorrectionReceiptRecord>;
+}
+
+/** Resolve the target to a vault-relative path, refusing it as missing. */
+function resolveTarget(
+ vault: string,
+ target: string,
+ readable: ((rel: string) => boolean) | undefined,
+): string {
+ let abs: string;
+ try {
+ abs = resolveNotePath(vault, target, {
+ mustExist: true,
+ ...(readable !== undefined ? { readable } : {}),
+ });
+ } catch (err) {
+ throw new CorrectionError(
+ `correct: target does not resolve inside the vault: ${(err as Error).message}`,
+ { cause: err },
+ );
+ }
+ return vaultRelative(abs, vault);
+}
+
+/** The id a record is mentioned and chained under: basename, no extension. */
+function idOfRel(rel: string): string {
+ return normalizeChainLink(rel);
+}
+
+/**
+ * The pre-retirement status exactly as the shared tombstone writer reads
+ * it before its write (the `scalar()` chain in tombstone.ts): a
+ * non-string or empty value reads as "unknown". The sweep's retirement
+ * receipt must be spelled with the writer's own key material so the
+ * writer's ask dedupes against it - a divergent edge-case spelling here
+ * would silently turn one retirement into two receipts.
+ */
+function priorStatusOf(meta: Readonly<Record<string, unknown>>): string {
+ for (const key of [LIFECYCLE_STATUS_KEY, LIFECYCLE_STATUS_KEY_NORMALIZED]) {
+ const value = meta[key];
+ if (typeof value === "string" && value !== "") return value;
+ }
+ return "unknown";
+}
+
+/**
+ * The vault-relative path a claim's source spelling names, or null when
+ * it names nothing - a source that names no page is provenance text and
+ * cannot be reach-gated, so it reads as within reach.
+ *
+ * The fence comes off (unlike {@link stripWikilinkDecoration}, which
+ * keeps it) and the extension stays on, so the gate is asked over the
+ * same extension-bearing vault-relative path every other caller hands
+ * the readable predicate: claim-graph node paths and mention-scan paths.
+ * The previous spelling failed on both ends - a fenced source gated on
+ * its `[[...]]` wrapper, an unfenced one on the stripped extension - and
+ * an existing, readable source page answered unreadable at remote reach,
+ * dropping its claim out of the blast radius. A source that names no
+ * page under its literal spelling gates on that spelling - withheld,
+ * which is the safe direction.
+ */
+function sourceRel(source: string): string | null {
+ const stripped = stripWikilinkDecoration(source);
+ const fenced = /^\[\[([^\]]+)\]\]$/.exec(stripped);
+ const body = fenced !== null ? fenced[1]!.trim() : stripped;
+ if (body === "") return null;
+ return body;
+}
+
+/** True when the caller may read the record a claim's source names. */
+function claimWithinReach(
+ event: ClaimEvent,
+ readable: ((rel: string) => boolean) | undefined,
+): boolean {
+ if (readable === undefined) return true;
+ const rel = sourceRel(event.source);
+ if (rel === null) return true;
+ return readable(rel);
+}
+
+function nodeWithinReach(
+ node: ClaimNode,
+ readable: ((rel: string) => boolean) | undefined,
+): boolean {
+ return readable === undefined ? true : readable(node.path);
+}
+
+/** True when a vault-relative path sits inside the caller's readable set. */
+function withinReach(rel: string, readable: ((rel: string) => boolean) | undefined): boolean {
+ return readable === undefined || readable(rel);
+}
+
+/**
+ * Run the correct-verb sweep for one record. Dry by default: the applied
+ * sequence runs only under `dryRun: false`.
+ */
+export function correct(input: CorrectInput): CorrectResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // counting passes below write nothing and assert nothing themselves;
+ // this guard refuses a foreign vault before any of the work runs.
+ assertVaultIdentityForWrite(input.vault);
+ const target = input.target.trim();
+ if (target === "") throw new CorrectionError("correct: target is required");
+ const value = input.value?.trim();
+ if (input.value !== undefined && value === "") {
+ throw new CorrectionError("correct: value must not be empty when given");
+ }
+ // Same input shape as the value refusal: a successor that normalizes
+ // to empty - `|||`, a fence carrying only an alias - would otherwise
+ // flow into the `superseded_by` pointer and the mention retarget as a
+ // malformed `[[]]`. Refused before anything is written, dry or applied.
+ const successorId = input.successor === undefined ? undefined : idOfRel(input.successor);
+ if (input.successor !== undefined && successorId === "") {
+ throw new CorrectionError("correct: successor must not be empty when given");
+ }
+ // The window end lands in frontmatter as `valid_until` even when no
+ // ledger append runs (no corrected value supplied), so it is validated
+ // here with the SAME check the ledger append boundary applies, before
+ // anything is written - otherwise a malformed bound would sit in the
+ // record unread until a window parse found it.
+ if (input.windowEnd !== undefined && !isValidityPoint(input.windowEnd)) {
+ throw new CorrectionError(
+ `correct: window_end must be a bare ISO date or canonical ISO-8601 UTC instant: ` +
+ `${JSON.stringify(input.windowEnd)}`,
+ );
+ }
+ const dryRun = input.dryRun !== false;
+ const now = input.now ?? new Date();
+ const correctionTs = isoSecond(now);
+ const agent = normalizeAgentArgument(input.agent ?? null) ?? resolveAgentName(input.configPath);
+
+ const targetRel = resolveTarget(input.vault, target, input.readable);
+ const targetId = idOfRel(targetRel);
+
+ // ----- Discovery (within the caller's reach) -----------------------------
+ const graph: ClaimGraph = buildClaimGraph(input.vault, { now });
+ const replacedNode = whatReplaced(graph, targetId);
+ // A record with no successor pointer is its own chain tip; only a
+ // genuine successor counts as what replaced the target.
+ const replacedBy =
+ replacedNode !== null &&
+ replacedNode.id !== targetId &&
+ nodeWithinReach(replacedNode, input.readable)
+ ? replacedNode.id
+ : null;
+ const contests = whatContests(graph, targetId)
+ .filter((n) => nodeWithinReach(n, input.readable))
+ .map((n) => n.id)
+ .toSorted();
+
+ // The counting pass of the mention scan: it writes nothing and asserts
+ // no vault identity, so the blast radius stays available to a caller
+ // that is only deciding whether to write at all. The readable
+ // predicate is threaded in so a file outside the caller's reach is
+ // never opened, matched or named - the scan's report is filtered
+ // through reach again below, as a second gate on the response shape.
+ const mentionScan = retargetWikilinks(
+ input.vault,
+ [{ from: targetId, ...(successorId !== undefined ? { to: successorId } : {}) }],
+ {
+ apply: false,
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
+ },
+ );
+ const mentions = mentionScan.matched.filter((rel) => withinReach(rel, input.readable));
+
+ const allEvents = readClaimEvents(input.vault).events;
+ // The target's own events name the resolved target path - the full
+ // vault-relative spelling or its extensionless form - never a bare
+ // basename: a basename fold also matched a same-named page in another
+ // folder, letting its claims bypass the reach gate below and its
+ // source spelling stand in for the target's on an applied correction.
+ const namesTarget = (e: ClaimEvent): boolean => {
+ const rel = sourceRel(e.source);
+ return rel !== null && (rel === targetRel || rel === targetRel.replace(/\.md$/i, ""));
+ };
+ const targetEvents = allEvents.filter(namesTarget);
+ const slots = new Set(targetEvents.map((e) => `${e.entity}\u0000${e.aspect}`));
+ const claims = allEvents.filter(
+ (e) =>
+ slots.has(`${e.entity}\u0000${e.aspect}`) &&
+ (namesTarget(e) || claimWithinReach(e, input.readable)),
+ );
+
+ const blastRadius: CorrectionBlastRadius = Object.freeze({
+ target: targetRel,
+ replacedBy,
+ contests: Object.freeze(contests),
+ mentions: Object.freeze(mentions),
+ claims: Object.freeze(claims),
+ });
+
+ const stem = targetId.replace(/[^A-Za-z0-9._-]/g, "-");
+ const bundleId = `correct-${stem}-${correctionTs.replace(/[-:]/g, "")}`;
+ const trigger = `${CORRECTION_BUNDLE_TRIGGER_PREFIX}${bundleId}`;
+
+ if (dryRun) {
+ return {
+ bundleId,
+ dryRun: true,
+ blastRadius,
+ retirements: Object.freeze([]),
+ retarget: {
+ // Reach-filtered: the raw scan names every file on disk that
+ // matches, which beside the gated blast_radius.mentions would be
+ // a one-field disclosure of exactly the withheld paths.
+ matched: mentionScan.matched.filter((rel) => withinReach(rel, input.readable)),
+ rewritten: Object.freeze([]),
+ failed: mentionScan.failed.filter((f) => withinReach(f.path, input.readable)),
+ },
+ ledger: Object.freeze([]),
+ receipts: Object.freeze([]),
+ };
+ }
+
+ // ----- Applied: ledger, retirement, retargeting, receipts ---------------
+ const policy = correctionEndState(
+ {
+ flatlyWrong: input.flatlyWrong === true,
+ ...(input.windowEnd !== undefined ? { windowEnd: input.windowEnd } : {}),
+ },
+ correctionTs,
+ );
+ const reasonCode =
+ policy.endState === "tombstone" ? REASON_CODE_TOMBSTONE : REASON_CODE_SUPERSEDE;
+ const reason = input.reason?.trim() || SUPERSEDE_DEFAULT_REASON;
+
+ // Replay detection FIRST, off the target's frontmatter as it stands:
+ // an already-applied retirement makes the sequence a recorded no-op -
+ // no double tombstone, no re-closed window, no re-appended event.
+ const [rawMeta, body] = parseFrontmatter(join(input.vault, targetRel));
+ const meta = rawMeta as FrontmatterMap;
+ const storedUntil = meta[VALID_UNTIL_KEY];
+ const alreadyRetired =
+ policy.endState === "tombstone"
+ ? readLifecycleState(meta).tombstoned
+ : typeof storedUntil === "string" && storedUntil !== "";
+
+ // Ledger correction events, appended BEFORE the retirement write so the
+ // append's open-bound resolution never reads the window this sweep is
+ // about to close, and skipped entirely on a replay. Each event keeps
+ // the corrected record's own source spelling, so the fold reads the
+ // change as self-correction, never a conflict, and opens its validity
+ // window at the correction instant - where the predecessor's closed
+ // window ends.
+ const ledger: Array<CorrectResult["ledger"][number]> = [];
+ if (value !== undefined && !alreadyRetired) {
+ const sourceBySlot = new Map<string, string>();
+ for (const e of targetEvents) {
+ const key = `${e.entity}\u0000${e.aspect}`;
+ if (!sourceBySlot.has(key)) sourceBySlot.set(key, e.source);
+ }
+ for (const [key, source] of sourceBySlot) {
+ const [entity, aspect] = key.split("\u0000");
+ // A record already validity-closed carries a stored window end
+ // BEFORE this correction instant, and the append below resolves
+ // its open until-bound from that very frontmatter - the close a
+ // previous sweep wrote - so the store refuses the inverted window.
+ // That is the replay having CONVERGED, not an internal fault: it
+ // surfaces as the verb's named refusal class, strict (nothing was
+ // written), naming the record and the close that blocks it.
+ try {
+ appendClaimEvent(
+ input.vault,
+ {
+ ts: correctionTs,
+ agent,
+ entity: entity!,
+ aspect: aspect!,
+ value,
+ source,
+ validFrom: correctionTs,
+ },
+ input.configPath !== undefined ? { configPath: input.configPath } : undefined,
+ );
+ } catch (err) {
+ if (err instanceof ClaimWindowRefusal) {
+ throw new CorrectionError(
+ `correct: ${targetRel} is already validity-closed` +
+ (typeof storedUntil === "string" && storedUntil !== "" ? ` at ${storedUntil}` : "") +
+ `, before this correction; the replay has converged, so the ledger ` +
+ `correction is refused rather than written with an inverted window`,
+ { cause: err },
+ );
+ }
+ throw err;
+ }
+ ledger.push(Object.freeze({ entity: entity!, aspect: aspect!, value, source }));
+ }
+ }
+
+ const retirements: CorrectionRetirement[] = [];
+ // Bundle-correlated receipts: one for the retirement decision and one
+ // per corrected slot. Asking is idempotent, so a replay reports
+ // appended: false instead of doubling the record.
+ const receipts: CorrectionReceiptRecord[] = [];
+ const askReceipt = (subject: string, before: string, after: string): void => {
+ // Fail-soft, the same discipline the tombstone pre-receipt below
+ // applies: an accountability-log hiccup must never abort an applied
+ // sweep whose writes have already landed. A failed ask is reported
+ // (it reads as not appended), never fatal.
+ let appended = false;
+ try {
+ const res = appendDecisionChangeReceipt(input.vault, {
+ subject,
+ before,
+ after,
+ actor: agent,
+ reasonCode,
+ rationale: reason,
+ evidenceTriggers: [trigger],
+ ts: correctionTs,
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+ appended = res.appended;
+ } catch {
+ // The retirement and the ledger events are already on disk; the
+ // missing receipt surfaces through the response's appended: false.
+ }
+ receipts.push(Object.freeze({ subject, appended }));
+ };
+ if (alreadyRetired) {
+ retirements.push(
+ Object.freeze({
+ path: targetRel,
+ endState: policy.endState,
+ validUntil: policy.endState === "tombstone" ? null : (storedUntil as string),
+ reasonCode,
+ changed: false,
+ }),
+ );
+ if (policy.endState === "tombstone") {
+ // Replay of a tombstone retirement: the first run's pre-retirement
+ // status is gone from the frontmatter THIS run re-read (the first
+ // run stamped `_status: tombstoned` over it), so the sweep cannot
+ // re-derive the idempotency key its first receipt was written
+ // under - asking again would mint a fresh no-change receipt under
+ // a mutated key. The receipt already stands on disk; report it as
+ // not appended.
+ receipts.push(Object.freeze({ subject: targetRel, appended: false }));
+ } else {
+ // The receipt describes the state on disk, so a replay names the
+ // SAME close instant the first run recorded and its idempotency
+ // key matches.
+ askReceipt(
+ targetRel,
+ `status:${priorStatusOf(meta)}`,
+ `validity_close until ${storedUntil as string}`,
+ );
+ }
+ } else if (policy.endState === "tombstone") {
+ // Bundle-trigger carry. The shared tombstone writer appends its OWN
+ // decision-change receipt after the write, keyed on
+ // (subject, before, after) with no evidence triggers. This sweep's
+ // ask goes FIRST, spelled with the writer's exact key material and
+ // carrying correction_bundle:<bundleId>, so the writer's own ask
+ // dedupes against it and exactly ONE receipt records the retirement
+ // - the sweep's, naming the bundle. The spelling mirrors
+ // tombstone.ts's receipt block; the tombstone-receipt tests in
+ // correction.test.ts pin the coupling. Fail-soft, mirroring the
+ // writer's own receipt discipline: an accountability-log hiccup must
+ // never fail the retirement itself.
+ const pointer = successorId ? `[[${successorId}]]` : null;
+ let receiptAppended = false;
+ try {
+ const pre = appendDecisionChangeReceipt(input.vault, {
+ subject: targetRel,
+ before: `status:${priorStatusOf(meta)}`,
+ after:
+ pointer !== null ? `status:tombstoned superseded_by:${pointer}` : "status:tombstoned",
+ actor: agent,
+ reasonCode: REASON_CODE_TOMBSTONE,
+ rationale: sanitiseTextField(reason, {
+ maxLen: TOMBSTONE_RATIONALE_MAX_LEN,
+ singleLine: true,
+ }).trim(),
+ evidenceTriggers: [trigger],
+ ts: correctionTs,
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+ receiptAppended = pre.appended;
+ } catch {
+ // The writer's own receipt below still records the retirement,
+ // without the bundle trigger.
+ }
+ receipts.push(Object.freeze({ subject: targetRel, appended: receiptAppended }));
+ const res = tombstone({
+ vault: input.vault,
+ path: targetRel,
+ reason,
+ ...(successorId !== undefined ? { supersededBy: successorId } : {}),
+ ...(input.agent !== undefined ? { agent: input.agent } : {}),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
+ });
+ retirements.push(
+ Object.freeze({
+ path: res.path,
+ endState: "tombstone",
+ validUntil: null,
+ reasonCode: REASON_CODE_TOMBSTONE,
+ changed: res.changed,
+ }),
+ );
+ } else {
+ // Validity close (the temporal-replace frontmatter convention): the
+ // record stays on disk and serveable inside its historical window,
+ // pointing at its successor when one is named.
+ const nextMeta: FrontmatterMap = { ...meta };
+ nextMeta[VALID_UNTIL_KEY] = policy.validUntil ?? correctionTs;
+ if (successorId !== undefined) {
+ nextMeta[SUPERSEDED_BY_KEY] = `[[${successorId}]]`;
+ }
+ try {
+ writeFrontmatterAtomic(join(input.vault, targetRel), nextMeta, body, { overwrite: true });
+ } catch (err) {
+ throw new CorrectionError(
+ `correct: failed to close validity on ${targetRel}: ${(err as Error).message}`,
+ { cause: err },
+ );
+ }
+ appendLogEvent(input.vault, {
+ timestamp: correctionTs,
+ eventType: BRAIN_LOG_EVENT_KIND.temporalReplace,
+ body: {
+ predecessor: targetRel,
+ ...(successorId !== undefined ? { successor: successorId } : {}),
+ at: policy.validUntil ?? correctionTs,
+ agent,
+ },
+ });
+ retirements.push(
+ Object.freeze({
+ path: targetRel,
+ endState: "validity_close",
+ validUntil: policy.validUntil ?? correctionTs,
+ reasonCode: REASON_CODE_SUPERSEDE,
+ changed: true,
+ }),
+ );
+ askReceipt(
+ targetRel,
+ `status:${priorStatusOf(meta)}`,
+ `validity_close until ${policy.validUntil ?? correctionTs}`,
+ );
+ }
+
+ // Mention retargeting reuses the counting scan's own matcher with
+ // writes on; the applied pass is idempotent (a rewritten spelling no
+ // longer matches), and Brain/log and the receipt lines are testimony
+ // that is never rewritten. Failures are carried, not thrown. The
+ // caller's readable predicate is threaded in: a page outside the
+ // caller's reach is never opened, never rewritten, never named - the
+ // applied pass may not write into files its caller cannot read.
+ const appliedRetarget = retargetWikilinks(
+ input.vault,
+ [{ from: targetId, ...(successorId !== undefined ? { to: successorId } : {}) }],
+ {
+ neverRewrite: [BRAIN_LOG_REL, BRAIN_DECISIONS_REL],
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
+ },
+ );
+
+ // Bundle-correlated receipts for the corrected slots: one per slot the
+ // ledger appended to, under the same bundle trigger as the retirement.
+ for (const entry of ledger) {
+ askReceipt(`${entry.entity}/${entry.aspect}`, `value:${entry.source}`, `value:${entry.value}`);
+ }
+
+ return {
+ bundleId,
+ dryRun: false,
+ blastRadius,
+ retirements: Object.freeze(retirements),
+ retarget: {
+ // Reach-filtered, like the dry run: only in-reach paths are disclosed.
+ matched: appliedRetarget.matched.filter((rel) => withinReach(rel, input.readable)),
+ rewritten: appliedRetarget.rewritten.filter((rel) => withinReach(rel, input.readable)),
+ failed: appliedRetarget.failed.filter((f) => withinReach(f.path, input.readable)),
+ },
+ ledger: Object.freeze(ledger),
+ receipts: Object.freeze(receipts),
+ };
+}
diff --git a/src/core/brain/page-dedup.ts b/src/core/brain/page-dedup.ts
index 07f7c27f..cf968380 100644
--- a/src/core/brain/page-dedup.ts
+++ b/src/core/brain/page-dedup.ts
@@ -227,6 +227,17 @@ export interface WikilinkRetargetReport {
* Always empty when `apply` is false.
*/
readonly failed: ReadonlyArray<WikilinkRewriteFailure>;
+ /**
+ * How many files the `readable` predicate refused. Zero when no
+ * predicate was given.
+ *
+ * A count, never paths: this pass's reports cross tool boundaries, and
+ * the filenames a caller may not read are exactly what the predicate
+ * was supplied to withhold - naming them, or even counting them out
+ * per directory, would hand the caller the existence leak the
+ * predicate exists to prevent.
+ */
+ readonly withheld: number;
}
export interface RetargetWikilinksOptions {
@@ -259,6 +270,17 @@ export interface RetargetWikilinksOptions {
* under a new name rather than a different subject.
*/
readonly neverRewrite?: ReadonlyArray<string>;
+ /**
+ * The vault-relative paths the caller may read. A file the predicate
+ * refuses is never opened, never matched, never rewritten and never
+ * NAMED in the report - it is counted in
+ * {@link WikilinkRetargetReport.withheld} and nothing else. This is
+ * the caller-reach gate for restricted sweeps: without it the walk
+ * reads every matching page's bytes and would rewrite them, so a
+ * restricted caller could both read the disclosure and write into
+ * pages it cannot see. Absent, every walked file may be read.
+ */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -492,18 +514,27 @@ export function retargetWikilinks(
matched: Object.freeze([]),
rewritten: Object.freeze([]),
failed: Object.freeze([]),
+ withheld: 0,
});
if (!existsSync(abs)) return empty;
const rules = resolveVaultScope(vault).rules;
const neverRewrite = opts.neverRewrite ?? [];
+ const readable = opts.readable;
const ordered = [...retargets].toSorted((a, b) => b.from.length - a.from.length);
const files: string[] = [];
const matched: string[] = [];
const rewritten: string[] = [];
const failed: WikilinkRewriteFailure[] = [];
+ let withheld = 0;
for (const file of markdownFilesUnder(vault, abs, rules)) {
+ // Asked BEFORE the read, so a file the caller may not read contributes
+ // nothing - not its bytes, not a match, not a rewrite, not its name.
+ if (readable !== undefined && !readable(file.rel)) {
+ withheld += 1;
+ continue;
+ }
let raw: string;
try {
raw = readFileSync(file.abs, "utf8");
@@ -537,6 +568,7 @@ export function retargetWikilinks(
failed: Object.freeze(
failed.toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)),
),
+ withheld,
});
}
diff --git a/src/core/brain/query.ts b/src/core/brain/query.ts
index 35d16d47..2306fb2d 100644
--- a/src/core/brain/query.ts
+++ b/src/core/brain/query.ts
@@ -39,7 +39,15 @@ import { everyArtifactRefView, type ArtifactRefView } from "./artifact-ref-view.
import { reachView } from "./reach-view.ts";
import { resolvedTransportReach, type TransportReach } from "../graph/transport-reach.ts";
import { parseSignal } from "./signal.ts";
-import { isTombstoned } from "./lifecycle/tombstone.ts";
+import {
+ SUPERSEDED_BY_KEY,
+ buildChainLookup,
+ isTombstoned,
+ resolveChainTip,
+ type ChainLookup,
+} from "./lifecycle/tombstone.ts";
+import { chainVerdict } from "../search/correction-coupling.ts";
+import { vaultRelative } from "../path-safety.ts";
import { parseFrontmatter } from "../vault.ts";
import { normaliseWikilinkTarget } from "./wikilink.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
@@ -273,9 +281,9 @@ export function queryByTopic(
reachView(vault, resolvedTransportReach(options.transportReach)),
);
let preference: BrainPreference | BrainRetired | null = null;
- preference = findPreferenceForTopic(dirs.preferences, want, "preference", view);
+ preference = findPreferenceForTopic(vault, dirs.preferences, want, "preference", view);
if (!preference) {
- preference = findPreferenceForTopic(dirs.retired, want, "retired", view);
+ preference = findPreferenceForTopic(vault, dirs.retired, want, "retired", view);
}
// Expiration filter (C5): an active preference past its expiration_date
// is dropped from the default result (surfaced only under showExpired).
@@ -391,6 +399,7 @@ function collectSignals(dir: string, topic: string, out: BrainSignal[]): void {
* `topic-key-collision` for preferences whose topics fold together.
*/
function findPreferenceForTopic(
+ vault: string,
dir: string,
topic: string,
kind: "preference" | "retired",
@@ -406,6 +415,10 @@ function findPreferenceForTopic(
const entries = readdirSync(dir, { withFileTypes: true })
.slice()
.toSorted((a, b) => a.name.localeCompare(b.name));
+ // The serve-with-correction chain index, built on the first
+ // pointer-bearing record and reused for the rest of the walk: a vault
+ // whose records carry no pointer never pays for it.
+ let chainLookup: ChainLookup | null = null;
for (const entry of entries) {
if (!entry.isFile()) continue;
if (!entry.name.startsWith(prefix) || !entry.name.endsWith(".md")) {
@@ -414,12 +427,32 @@ function findPreferenceForTopic(
const path = join(dir, entry.name);
// Belief lifecycle suite (t_7d5a3589): a tombstoned entry is excluded
// from recall while remaining on disk for audit.
- if (isTombstoned(parseFrontmatter(path)[0])) continue;
+ const [meta] = parseFrontmatter(path);
+ if (isTombstoned(meta)) continue;
try {
const parsed = kind === "preference" ? parsePreference(path) : parseRetired(path);
// Skipped, not returned-then-dropped: see `ownerScope` on
// {@link QueryByTopicOptions}.
- if (parsed.topic === topic && view.visible(parsed.id)) return parsed;
+ if (parsed.topic === topic && view.visible(parsed.id)) {
+ // Serve-with-correction coupling (truth-correctable-time-aware,
+ // contract item 3): a record whose frontmatter declares a
+ // successor but which survived the tombstone filter - the
+ // serveable-retired regime the correct verb's validity-close
+ // writes - is recallable by topic only beside its resolved,
+ // readable chain-tip correction, and is skipped fail-closed
+ // otherwise. A record with no pointer is not in the predicate's
+ // regime and keeps today's behavior.
+ const pointer = meta[SUPERSEDED_BY_KEY];
+ if (typeof pointer === "string" && pointer.trim() !== "") {
+ chainLookup ??= buildChainLookup(vault, (rel) => view.visible(rel));
+ const verdict = chainVerdict(
+ vaultRelative(path, vault),
+ resolveChainTip(pointer, chainLookup),
+ );
+ if (verdict.action === "drop") continue;
+ }
+ return parsed;
+ }
} catch {
// Unit F, deliberately NOT converted - same reasoning as
// collectSignals above: `parsePreference` / `parseRetired` throw on
diff --git a/src/core/brain/truth/collision.ts b/src/core/brain/truth/collision.ts
index 1fdbefc2..96d22d86 100644
--- a/src/core/brain/truth/collision.ts
+++ b/src/core/brain/truth/collision.ts
@@ -13,6 +13,10 @@ import type { InsightCandidate } from "../triggers/types.ts";
import type { ClaimEvent } from "./types.ts";
/** Claims older than this many days never participate. */
+// Assertion-keyed by contract (truth-correctable-time-aware, item 1):
+// collision detection measures assertion time only and never reads a
+// claim's validity window, so a windowed claim collides exactly like a
+// windowless one.
export const COLLISION_WINDOW_DAYS = 14;
/** Cap on findings per detection pass. */
export const COLLISION_FINDINGS_CAP = 20;
diff --git a/src/core/brain/truth/conflicts.ts b/src/core/brain/truth/conflicts.ts
index 9c8186a1..59342d3b 100644
--- a/src/core/brain/truth/conflicts.ts
+++ b/src/core/brain/truth/conflicts.ts
@@ -6,9 +6,19 @@
* `resolution: ask_user`, never auto-resolved); a later value outside
* the window supersedes silently because that is normal fact
* evolution, not contradiction.
+ *
+ * Since the validity axis (truth-correctable-time-aware, contract
+ * item 1) the contest rule carries one exclusion: a version pair whose
+ * claims are fully succession-separated (present, non-intersecting
+ * windows on every cross-pair - see `succession.ts`) never contests.
+ * Every other pair keeps the assertion-time rule verbatim, and an
+ * expired window never suppresses contestation on its own. Successions
+ * surface on the state's own presence-gated channel, never as
+ * conflicts.
*/
-import { computeTruthState } from "./fold.ts";
+import { computeTruthState, slotKey } from "./fold.ts";
+import { classifyClaimSuccessions, valuesSuccessionSeparated } from "./succession.ts";
import type { ClaimEvent, ClaimSlot, ClaimVersion, TruthConflict, TruthState } from "./types.ts";
/** Two values asserted within this many days of each other contest. */
@@ -29,24 +39,33 @@ function withinWindow(aTs: string, bTs: string, windowDays: number): boolean {
/**
* Contesting versions for one slot: every history value whose latest
* assertion is within the window of the current value AND whose source
- * differs (same source changing its value is self-correction). Returns
+ * differs (same source changing its value is self-correction) AND that
+ * is not succession-separated from the current value. Returns
* chronological order ending with the current value, or null when
* nothing contests.
*/
-function contestingValues(slot: ClaimSlot, windowDays: number): ClaimVersion[] | null {
+function contestingValues(
+ slot: ClaimSlot,
+ slotEvents: ReadonlyArray<ClaimEvent>,
+ windowDays: number,
+): ClaimVersion[] | null {
const contesting = slot.history
- .filter(
- (v) => withinWindow(v.ts, slot.current.ts, windowDays) && v.source !== slot.current.source,
- )
+ .filter((v) => {
+ if (!withinWindow(v.ts, slot.current.ts, windowDays)) return false;
+ if (v.source === slot.current.source) return false;
+ if (valuesSuccessionSeparated(slotEvents, v.value, slot.current.value)) return false;
+ return true;
+ })
.toReversed(); // history is newest-first; conflicts read chronologically
if (contesting.length === 0) return null;
return [...contesting, slot.current];
}
/**
- * The full fold with conflicts materialized and `contested` flags set.
- * With no conflicting events the output is deeply equal to
- * {@link computeTruthState} - the neutral default stays bit-identical.
+ * The full fold with conflicts and successions materialized and
+ * `contested` flags set. With no conflicting or succession-separated
+ * events the output is deeply equal to {@link computeTruthState} - the
+ * neutral default stays bit-identical.
*/
export function computeTruthStateWithConflicts(
events: ReadonlyArray<ClaimEvent>,
@@ -54,13 +73,29 @@ export function computeTruthStateWithConflicts(
): TruthState {
const windowDays = opts.windowDays ?? CONFLICT_WINDOW_DAYS;
const base = computeTruthState(events);
+ const successions = classifyClaimSuccessions(events);
+
+ // Events grouped per slot so the contest scan can apply the
+ // succession exclusion at claim granularity (fold versions aggregate
+ // events and carry no windows themselves).
+ const eventsBySlot = new Map<string, ClaimEvent[]>();
+ for (const e of events) {
+ const key = slotKey(e.entity, e.aspect);
+ const list = eventsBySlot.get(key);
+ if (list === undefined) eventsBySlot.set(key, [e]);
+ else list.push(e);
+ }
const conflicts: TruthConflict[] = [];
const slots: ClaimSlot[] = [];
- let changed = false;
+ let changed = successions.length > 0;
for (const slot of base.slots) {
- const values = contestingValues(slot, windowDays);
+ const values = contestingValues(
+ slot,
+ eventsBySlot.get(slotKey(slot.entity, slot.aspect)) ?? [],
+ windowDays,
+ );
if (values === null) {
slots.push(slot);
continue;
@@ -83,9 +118,13 @@ export function computeTruthStateWithConflicts(
if (!changed) return base;
// Slots are already sorted by (entity, aspect) in the base fold, so
// conflicts built in slot order inherit the same deterministic sort.
+ // Successions spread conditionally: an empty channel stays absent
+ // (undefined, never []), keeping windowless state files
+ // byte-identical.
return Object.freeze({
...base,
slots: Object.freeze(slots),
conflicts: Object.freeze(conflicts),
+ ...(successions.length > 0 ? { successions: Object.freeze(successions) } : {}),
});
}
diff --git a/src/core/brain/truth/correction-policy.ts b/src/core/brain/truth/correction-policy.ts
new file mode 100644
index 00000000..d72151e4
--- /dev/null
+++ b/src/core/brain/truth/correction-policy.ts
@@ -0,0 +1,60 @@
+/**
+ * Correction end-state policy (truth-correctable-time-aware, contract
+ * item 2): the one pure decision of HOW a corrected predecessor
+ * retires. A flatly-wrong claim was never true, so it tombstones -
+ * hidden everywhere, which makes the serve-with-correction invariant
+ * vacuous for it by design (nothing surfaces, correction included).
+ * Every other correction merely supersedes: validity closes at the
+ * explicit window end when the correction is time-scoped, else at the
+ * correction instant, leaving the predecessor serveable inside its
+ * historical window - the only regime where serve-with-correction is
+ * non-trivial.
+ *
+ * The choice is recorded per target by the correct verb using the
+ * existing receipt reason codes (`supersede` for validity_close,
+ * `tombstone` for tombstone). Succession and path-provenance consume
+ * the outcome through the ledger/frontmatter data, never through this
+ * module: a validity-closed predecessor against its successor carries
+ * non-overlapping present windows and classifies as succession under
+ * contract item 1.
+ *
+ * `validUntil` passes through verbatim - this decision stays pure. The
+ * correct sweep validates `windowEnd` at its own boundary with the same
+ * check the ledger append boundary applies (a bare ISO date or a
+ * canonical UTC timestamp), and refuses a malformed bound with a
+ * CorrectionError before anything is written; the ledger append keeps
+ * naming a malformed bound it is handed directly. Pure, deterministic,
+ * no I/O, no clock.
+ */
+
+/** How a corrected predecessor retires. */
+export type CorrectionEndState = "validity_close" | "tombstone";
+
+export interface CorrectionEndStateInput {
+ /** The caller declares the prior claim was never true, not merely superseded. */
+ readonly flatlyWrong: boolean;
+ /** Explicit window end for a time-scoped correction (canonical ISO-8601 UTC). */
+ readonly windowEnd?: string;
+}
+
+export interface CorrectionEndStateOutcome {
+ readonly endState: CorrectionEndState;
+ readonly validUntil: string | null;
+}
+
+/**
+ * Decide the end state of one corrected target. `flatlyWrong` yields
+ * `{ endState: "tombstone", validUntil: null }` outright; any other
+ * input yields `{ endState: "validity_close", validUntil: windowEnd ??
+ * correctionTs }`.
+ */
+export function correctionEndState(
+ input: CorrectionEndStateInput,
+ correctionTs: string,
+): CorrectionEndStateOutcome {
+ if (input.flatlyWrong) return Object.freeze({ endState: "tombstone", validUntil: null });
+ return Object.freeze({
+ endState: "validity_close",
+ validUntil: input.windowEnd ?? correctionTs,
+ });
+}
diff --git a/src/core/brain/truth/events-window.ts b/src/core/brain/truth/events-window.ts
new file mode 100644
index 00000000..8a121dcc
--- /dev/null
+++ b/src/core/brain/truth/events-window.ts
@@ -0,0 +1,160 @@
+/**
+ * Pure windowed selection over claim events (truth-correctable-time-aware,
+ * Task 6): the selection half of the brain_truth `events` operation.
+ *
+ * The module is pure and vault-free: it takes the already-`ts`-ascending
+ * event array `readClaimEvents` returns and slices it against an optional
+ * normalized-entity filter and an optional assertion-time window. The
+ * window is ASSERTION time only - `since`/`until` filter the events' `ts`
+ * and say nothing about the claims' validity windows (contract item 1
+ * keeps those two temporal vocabularies separate; the per-claim
+ * `[validFrom, validUntil)` convention rides on the rows verbatim).
+ *
+ * Bounds arrive as unix-ms (resolved by the caller through the shared
+ * time-range grammar) and are compared at SECOND precision, because
+ * ledger stamps are whole-second ISO-8601 UTC (`isoSecond`). `since`
+ * floors into its second, so a bound mid-second still admits the events
+ * of that second - the safe direction for tail-following pagination,
+ * where an advancing `since` may re-see a boundary event but must never
+ * skip one. `until` also resolves to the stamp of the second containing
+ * it and compares inclusively, which is what the grammar's inclusive
+ * upper edge means at second precision: the grammar's day-end edge
+ * (`23:59:59.999`) keeps the whole final second of the day and excludes
+ * the next day's midnight second. Sub-second detail on an event stamp is
+ * truncated before the compare, so a hand-written fractional row behaves
+ * as the whole second it was asserted in.
+ */
+
+import { normalizeEntityName } from "../entities/canonical.ts";
+import { isoSecond } from "../time.ts";
+import type { ClaimEvent } from "./types.ts";
+
+/** Default page size for the events operation. */
+export const DEFAULT_EVENT_LIST_LIMIT = 200;
+
+/** Hard cap on the events operation's page size; larger asks are capped. */
+export const CLAIM_EVENT_MAX_LIST_LIMIT = 1000;
+
+/** Selection knobs for one events query. Absent bounds stay open. */
+export interface ClaimEventSelection {
+ /** Canonical entity name or its display-form spelling; empty filters nothing. */
+ readonly entity?: string;
+ /** Inclusive lower assertion-time bound (unix-ms), floored to the second. */
+ readonly sinceMs?: number | null;
+ /** Inclusive upper assertion-time bound (unix-ms), resolved to its whole second. */
+ readonly untilMs?: number | null;
+ /** Page size; defaults to {@link DEFAULT_EVENT_LIST_LIMIT}, capped at the hard cap. */
+ readonly limit?: number;
+}
+
+/** One events query's outcome: the page, the full match count, the cut flag. */
+export interface ClaimEventSelectionResult {
+ /** Matched events, ascending assertion `ts`, within the page limit. */
+ readonly rows: ReadonlyArray<ClaimEvent>;
+ /** Every event the filters matched, the page included. */
+ readonly total: number;
+ /** True when more events matched than the page returned. */
+ readonly truncated: boolean;
+}
+
+/**
+ * Validate and cap one events page size coming from an untyped surface
+ * (MCP arguments, CLI flags). Absent asks for the default; anything that
+ * is not a positive integer is refused with a named error rather than
+ * silently coerced; anything above the hard cap is capped, which is the
+ * operation's specified bound.
+ */
+export function claimEventLimit(raw: unknown): number {
+ if (raw === undefined || raw === null) return DEFAULT_EVENT_LIST_LIMIT;
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1) {
+ throw new RangeError(
+ `claim events limit must be a positive integer, got ${JSON.stringify(raw)}`,
+ );
+ }
+ return Math.min(raw, CLAIM_EVENT_MAX_LIST_LIMIT);
+}
+
+/**
+ * Resolve unix-ms window bounds into whole-second ISO-8601 UTC stamps,
+ * the form the second-precision string compare below consumes. Null
+ * stays null: that side of the window is open. A non-finite bound is
+ * refused by name - it would otherwise reach `new Date(NaN)` below and
+ * die inside `toISOString()` as an unnamed "Invalid time value" error -
+ * in the same style the limit validation uses, naming the offending
+ * argument (spelled with String rather than JSON.stringify, which
+ * renders a NaN as "null").
+ */
+export function eventsWindowBounds(
+ sinceMs: number | null,
+ untilMs: number | null,
+): { since: string | null; until: string | null } {
+ if (sinceMs !== null && !Number.isFinite(sinceMs)) {
+ throw new RangeError(
+ `claim events since bound must be a finite number, got ${String(sinceMs)}`,
+ );
+ }
+ if (untilMs !== null && !Number.isFinite(untilMs)) {
+ throw new RangeError(
+ `claim events until bound must be a finite number, got ${String(untilMs)}`,
+ );
+ }
+ return {
+ since: sinceMs === null ? null : isoSecond(new Date(floorToSecond(sinceMs))),
+ until: untilMs === null ? null : isoSecond(new Date(floorToSecond(untilMs))),
+ };
+}
+
+function floorToSecond(ms: number): number {
+ return Math.floor(ms / 1000) * 1000;
+}
+
+/**
+ * The event stamp at second precision. Ledger stamps are written by
+ * `isoSecond`, for which this is the identity; a hand-written fractional
+ * stamp is judged as the whole second it was asserted in.
+ */
+function eventSecond(ts: string): string {
+ return `${ts.slice(0, 19)}Z`;
+}
+
+/**
+ * Every event the selection's filters match, in the input's ascending
+ * `(ts, shard, line)` order - the page WITHOUT the page size, so a
+ * caller that gates rows per row (visibility, reach) can count what the
+ * gate withheld and page the survivors itself.
+ */
+export function matchClaimEvents(
+ events: ReadonlyArray<ClaimEvent>,
+ selection: ClaimEventSelection,
+): ReadonlyArray<ClaimEvent> {
+ const bounds = eventsWindowBounds(selection.sinceMs ?? null, selection.untilMs ?? null);
+ const entity = selection.entity === undefined ? "" : normalizeEntityName(selection.entity);
+ return events.filter(
+ (event) =>
+ (entity === "" || event.entity === entity) &&
+ (bounds.since === null || eventSecond(event.ts) >= bounds.since) &&
+ (bounds.until === null || eventSecond(event.ts) <= bounds.until),
+ );
+}
+
+/**
+ * Slice a `ts`-ascending event array against the selection. Order is
+ * preserved from the input (the store returns ascending `(ts, shard,
+ * line)`), so the rows are stable across calls over an unchanged ledger.
+ * A `limit` below 1 or fractional is refused rather than silently
+ * coerced; a `limit` above the hard cap is capped, which is the
+ * operation's specified bound.
+ */
+export function selectClaimEvents(
+ events: ReadonlyArray<ClaimEvent>,
+ selection: ClaimEventSelection,
+): ClaimEventSelectionResult {
+ const limit = claimEventLimit(selection.limit ?? DEFAULT_EVENT_LIST_LIMIT);
+
+ const matched = matchClaimEvents(events, selection);
+ return {
+ rows: matched.slice(0, limit),
+ total: matched.length,
+ truncated: matched.length > limit,
+ };
+}
diff --git a/src/core/brain/truth/grounding.ts b/src/core/brain/truth/grounding.ts
index f7c82c64..6960d4ba 100644
--- a/src/core/brain/truth/grounding.ts
+++ b/src/core/brain/truth/grounding.ts
@@ -135,6 +135,10 @@ export function computeGroundingScore(
events: ReadonlyArray<ClaimEvent>,
opts: GroundingOptions = {},
): GroundingScore {
+ // Assertion-keyed by contract (truth-correctable-time-aware, item 1):
+ // the grounding balance measures assertion time only and never reads
+ // a claim's validity window, so windowed and windowless claims weigh
+ // identically here.
const windowDays = opts.windowDays ?? CONFLICT_WINDOW_DAYS;
const key = slotKey(slot.entity, slot.aspect);
const currentNorm = normalizeClaimValue(slot.current.value);
diff --git a/src/core/brain/truth/stated-claims.ts b/src/core/brain/truth/stated-claims.ts
new file mode 100644
index 00000000..f167879f
--- /dev/null
+++ b/src/core/brain/truth/stated-claims.ts
@@ -0,0 +1,209 @@
+/**
+ * Grounded agent-stated claim core (truth-correctable-time-aware,
+ * task 4): the bridge from an agent's stated claims
+ * (`{ subject, relation, object }` plus the assertion `text` they came
+ * from) into claim-ledger events.
+ *
+ * Two boundaries govern the path, with different strictness:
+ *
+ * - The payload boundary refuses WHOLE calls: an unknown relation
+ * (validated against the single relation vocabulary), missing text,
+ * missing source, an empty agent or a malformed ts throws
+ * {@link StatedClaimsRefusal} before anything is written.
+ * - The anchoring verdict is PER CLAIM, using the one occurrence
+ * kernel {@link anchorEntityForms} (quality-gated normalized match
+ * forms, minimum length 3): a claim whose subject and object both
+ * anchor in the text commits with `extractor: "agent_stated"`; an
+ * ungrounded claim is reported back with machine reason codes.
+ * Per-claim partial commit is safe here because each event is an
+ * independent append in an append-only ledger and the outcome
+ * reports exactly what landed.
+ *
+ * The extractor tag is annotation only: conflict detection reads the
+ * ledger exactly as before and the tag never re-ranks or resolves a
+ * conflict. Naming deliberately avoids "grounding", which is taken by
+ * the source-diversity score in `truth/grounding.ts` - verdicts here
+ * speak of anchoring.
+ */
+
+import { isKnownRelation, normalizeRelation } from "../../graph/relation-vocab.ts";
+import { anchorEntityForms, type AtomicEntityLike } from "../atomic-facts.ts";
+import { normalizeEntityName } from "../entities/canonical.ts";
+import type { AppendClaimInput, AppendClaimResult } from "./store.ts";
+import { appendClaimEvent, ISO_UTC_TS_RE } from "./store.ts";
+import type { ClaimExtractor } from "./types.ts";
+
+/** How this release tags agent-stated claims. */
+const AGENT_STATED: ClaimExtractor = "agent_stated";
+
+/** One stated claim: subject, typed relation, object. */
+export interface StatedClaim {
+ readonly subject: string;
+ readonly relation: string;
+ readonly object: string;
+}
+
+/** The payload the agent states, anchored by one shared assertion text. */
+export interface StatedClaimsPayload {
+ readonly claims: ReadonlyArray<StatedClaim>;
+ /** The assertion text every claim must anchor in. */
+ readonly text: string;
+ readonly agent: string;
+ /** Canonical ISO-8601 UTC timestamp for the committed events. */
+ readonly ts: string;
+ /** Provenance wikilink or vault-relative path. */
+ readonly source: string;
+}
+
+export interface StatedClaimsOptions {
+ /**
+ * Registry entities whose aliases extend the anchoring forms: an
+ * entity whose canonical name normalizes equal to a claim's subject
+ * or object contributes its full alias pool to that side.
+ */
+ readonly entities?: ReadonlyArray<AtomicEntityLike>;
+ readonly configPath?: string;
+ /**
+ * The caller's reach gate over the payload's source page (see
+ * `AppendClaimOptions.readableSource`): a source the caller cannot
+ * read resolves no frontmatter window, exactly like an absent one.
+ * Absent at operator reach.
+ */
+ readonly readableSource?: (rel: string) => boolean;
+}
+
+/** Machine-readable reason codes for an ungrounded claim. */
+export type StatedClaimRefusalReason =
+ | "missing_subject"
+ | "missing_object"
+ | "subject_unanchored"
+ | "object_unanchored";
+
+/** A claim that was reported back instead of committed. */
+export interface UngroundedStatedClaim {
+ readonly claim: StatedClaim;
+ readonly reasons: ReadonlyArray<StatedClaimRefusalReason>;
+}
+
+export interface StatedClaimsOutcome {
+ /** What landed, in payload order. */
+ readonly committed: ReadonlyArray<AppendClaimResult>;
+ /** What was reported back, in payload order. */
+ readonly ungrounded: ReadonlyArray<UngroundedStatedClaim>;
+}
+
+/** The payload boundary's typed refusal. Nothing has been written. */
+export class StatedClaimsRefusal extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "StatedClaimsRefusal";
+ }
+}
+
+/**
+ * The anchoring forms for one claimed side: the stated value itself,
+ * plus the alias pool of a registry entity whose canonical name
+ * normalizes equal to it.
+ */
+function statedAnchorForms(
+ value: string,
+ entities: ReadonlyArray<AtomicEntityLike>,
+): ReadonlyArray<string> {
+ const normalized = normalizeEntityName(value);
+ for (const entity of entities) {
+ if (normalizeEntityName(entity.name) === normalized) {
+ return [value, ...entity.aliases];
+ }
+ }
+ return [value];
+}
+
+/** Per-claim anchoring verdict: why the claim cannot commit, if it cannot. */
+function ungroundedReasons(
+ claim: StatedClaim,
+ text: string,
+ entities: ReadonlyArray<AtomicEntityLike>,
+): ReadonlyArray<StatedClaimRefusalReason> {
+ const reasons: StatedClaimRefusalReason[] = [];
+ if (normalizeEntityName(claim.subject) === "") {
+ reasons.push("missing_subject");
+ } else if (anchorEntityForms(text, statedAnchorForms(claim.subject, entities)).length === 0) {
+ reasons.push("subject_unanchored");
+ }
+ if (claim.object.trim() === "") {
+ reasons.push("missing_object");
+ } else if (anchorEntityForms(text, statedAnchorForms(claim.object, entities)).length === 0) {
+ reasons.push("object_unanchored");
+ }
+ return reasons;
+}
+
+/**
+ * Validate the payload boundary, commit the grounded claims as ledger
+ * events, and report the ungrounded ones back. Refused payloads write
+ * nothing; anchoring verdicts are per claim. The outcome reports
+ * exactly what landed, in payload order on both sides.
+ */
+export function appendStatedClaims(
+ vault: string,
+ payload: StatedClaimsPayload,
+ opts: StatedClaimsOptions = {},
+): StatedClaimsOutcome {
+ const source = payload.source.trim();
+ if (source === "") {
+ throw new StatedClaimsRefusal("stated claims: source is required");
+ }
+ if (payload.text.trim() === "") {
+ throw new StatedClaimsRefusal("stated claims: text is required");
+ }
+ for (const claim of payload.claims) {
+ if (!isKnownRelation(claim.relation)) {
+ throw new StatedClaimsRefusal(
+ `stated claims: unknown relation: ${JSON.stringify(claim.relation)}`,
+ );
+ }
+ }
+ // The whole-call promise covers every field the committed events
+ // carry: an empty agent or a malformed ts must refuse HERE, through
+ // the typed refusal channel, before the first write - not surface
+ // mid-loop as the store's plain error outside the documented refusal
+ // channel.
+ if (payload.agent.trim() === "") {
+ throw new StatedClaimsRefusal("stated claims: agent is required");
+ }
+ if (!ISO_UTC_TS_RE.test(payload.ts)) {
+ throw new StatedClaimsRefusal(
+ `stated claims: ts must be canonical ISO-8601 UTC: ${JSON.stringify(payload.ts)}`,
+ );
+ }
+
+ const entities = opts.entities ?? [];
+ const committed: AppendClaimResult[] = [];
+ const ungrounded: UngroundedStatedClaim[] = [];
+ for (const claim of payload.claims) {
+ const reasons = ungroundedReasons(claim, payload.text, entities);
+ if (reasons.length > 0) {
+ ungrounded.push(Object.freeze({ claim, reasons: Object.freeze(reasons) }));
+ continue;
+ }
+ const input: AppendClaimInput = {
+ ts: payload.ts,
+ agent: payload.agent,
+ entity: normalizeEntityName(claim.subject),
+ aspect: normalizeRelation(claim.relation),
+ value: claim.object.trim(),
+ extractor: AGENT_STATED,
+ source,
+ };
+ committed.push(
+ appendClaimEvent(vault, input, {
+ configPath: opts.configPath,
+ ...(opts.readableSource !== undefined ? { readableSource: opts.readableSource } : {}),
+ }),
+ );
+ }
+ return Object.freeze({
+ committed: Object.freeze(committed),
+ ungrounded: Object.freeze(ungrounded),
+ });
+}
diff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.ts
index 93713a2f..95d2c54a 100644
--- a/src/core/brain/truth/store.ts
+++ b/src/core/brain/truth/store.ts
@@ -20,11 +20,15 @@ import {
readdirSync,
readFileSync,
rmSync,
+ statSync,
writeFileSync,
} from "node:fs";
import { join } from "node:path";
import { resolveDeviceId } from "../../config.ts";
+import { parseFrontmatter } from "../../vault.ts";
+import type { FrontmatterMap } from "../../types.ts";
+import { vaultRelative } from "../../path-safety.ts";
import {
JSONL_LEDGER_EXT,
jsonlLedgerGrammar,
@@ -32,12 +36,23 @@ import {
shardedFileName,
} from "../ledger-shards.ts";
import { normalizeEntityName } from "../entities/canonical.ts";
+import { VALID_FROM_KEY, VALID_UNTIL_KEY } from "../lifecycle/temporal-replace.ts";
+import { resolveNotePath } from "../note-path.ts";
+import { ANCHORED_WIKILINK_RE, stripWikilinkDecoration } from "../wikilink.ts";
import { computeTruthState } from "./fold.ts";
+import {
+ isValidityPoint,
+ resolveIngestWindow,
+ validityWindowMs,
+ type SourceValidityWindow,
+} from "./validity.ts";
import type {
ClaimEvent,
+ ClaimExtractor,
ClaimParseWarning,
ClaimQuantity,
ClaimSlot,
+ ClaimSuccession,
ClaimSweepOutcome,
ClaimVersion,
ReadClaimEventsResult,
@@ -52,7 +67,22 @@ export const CLAIM_EVENT_MAX_COUNT = 10000;
// Same canonical UTC shape the log writer emits; see ISO_UTC_TS_RE in
// log-jsonl.ts for why this stays strict.
-const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
+export const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
+
+/**
+ * A validity window the append boundary refuses: an unparseable bound,
+ * or an empty or inverted window. Typed so a tool surface can map it to
+ * its invalid-params failure class (MCP INVALID_PARAMS, CLI exit 2)
+ * instead of letting it answer as an internal error - the same
+ * mistyped-input discipline the since/until and limit guards follow.
+ * The refusal itself stays strict: nothing is written.
+ */
+export class ClaimWindowRefusal extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "ClaimWindowRefusal";
+ }
+}
// `claims.jsonl` or `claims.<deviceId>.jsonl`; device ids are lowercase
// slugs, and Syncthing conflict copies are never shards (the shared
@@ -60,6 +90,79 @@ const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
const CLAIMS_STEM = "claims";
const CLAIMS_GRAMMAR = jsonlLedgerGrammar(CLAIMS_STEM);
+/** Extension appended when a source target names no file as given. */
+const NOTE_EXTENSION = ".md";
+
+/**
+ * The source record's frontmatter validity window, or null when the
+ * source is unreadable or carries no validity frontmatter (the ingest
+ * default rule, truth-correctable-time-aware task 3). The source is a
+ * provenance wikilink or vault-relative path: the wikilink decoration
+ * is stripped, the target resolves inside the vault only (a traversal
+ * or symlink escape reads as unreadable), and the target is tried as
+ * given, then with a `.md` suffix (the Obsidian extensionless-link
+ * shape). Only `valid_from` / `valid_until` participate; an mtime is
+ * never consulted, because an mtime is an assertion-time proxy, not
+ * validity.
+ *
+ * `readable` is the caller's reach gate, when the append answers at a
+ * caller reach (the MCP tools; the CLI verb runs at operator reach and
+ * passes none). A candidate the gate withholds is treated EXACTLY like
+ * an absent one - skipped like a missing file, so a source the caller
+ * cannot read resolves no window and leaves no signal distinguishing
+ * withheld from absent anywhere in the event or the response.
+ */
+function sourceFrontmatterWindow(
+ vault: string,
+ source: string,
+ readable?: (rel: string) => boolean,
+): SourceValidityWindow | null {
+ // The vault path a source names: the anchored wikilink body when the
+ // source is a wikilink, else the source verbatim - then alias/anchor
+ // decoration off, folder segments and `.md` kept (the same body
+ // discipline every vault-path resolver applies).
+ const anchored = ANCHORED_WIKILINK_RE.exec(source.trim());
+ const target = stripWikilinkDecoration(anchored !== null ? anchored[1]! : source.trim());
+ if (target === "") return null;
+ const candidates = target.endsWith(NOTE_EXTENSION) ? [target] : [target, target + NOTE_EXTENSION];
+ for (const candidate of candidates) {
+ let path: string;
+ try {
+ path = resolveNotePath(vault, candidate, { mustExist: false });
+ } catch {
+ return null; // lexical traversal or symlink escape: unreadable.
+ }
+ // Only a REGULAR file names a page: a directory at the bare
+ // spelling is not the record and must not shadow its `.md` twin -
+ // the same regular-file rule the artifact-ref view's isVaultFile
+ // applies on the read side. An unreadable candidate is skipped like
+ // a missing one.
+ try {
+ if (!statSync(path).isFile()) continue;
+ } catch {
+ continue;
+ }
+ // A page the caller may not read does not exist for them: skip it
+ // like a missing file rather than refusing, so the extensionless
+ // spelling's .md twin resolves exactly as it would had the bare
+ // candidate never existed.
+ if (readable !== undefined && !readable(vaultRelative(path, vault))) continue;
+ // parseFrontmatter never raises on an unreadable file; it yields an
+ // empty map, which reads as a windowless source.
+ const [meta] = parseFrontmatter(path);
+ const validFrom = frontmatterWindowBound(meta, VALID_FROM_KEY);
+ const validUntil = frontmatterWindowBound(meta, VALID_UNTIL_KEY);
+ if (validFrom === undefined && validUntil === undefined) return null;
+ return { validFrom, validUntil };
+ }
+ return null;
+}
+
+function frontmatterWindowBound(meta: FrontmatterMap, key: string): string | undefined {
+ const value = meta[key];
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
+}
+
export function truthDir(vault: string): string {
return join(vault, "Brain", "truth");
}
@@ -94,9 +197,42 @@ export interface AppendClaimInput {
readonly value: string;
readonly valueKind?: ClaimEvent["valueKind"];
readonly quantity?: ClaimQuantity;
+ /**
+ * Validity window start; absent keys mean windowless (contract item
+ * 1). An absent bound resolves from the source record's frontmatter
+ * `valid_from` when the source is readable at the caller's reach
+ * (`AppendClaimOptions.readableSource`), and the resolved value is
+ * frozen on the event; an unreadable, withheld or windowless source
+ * leaves the event windowless.
+ */
+ readonly validFrom?: string;
+ /** Validity window end, exclusive; resolved per bound like `validFrom`. */
+ readonly validUntil?: string;
+ /**
+ * Presence-gated provenance tag (schema v1). This binary writes only
+ * `agent_stated`; reads tolerate any non-empty string for forward
+ * compatibility.
+ */
+ readonly extractor?: ClaimExtractor;
readonly source: string;
}
+export interface AppendClaimOptions {
+ readonly configPath?: string;
+ /**
+ * The caller's reach gate over the source page, asked with the
+ * vault-relative path of every candidate the source resolves to.
+ * Absent at operator reach (the CLI verb): every source is
+ * resolvable, today's behavior. Present on the MCP tools: a source
+ * the caller cannot read is treated exactly like an absent one - no
+ * window resolves from it, so the frozen event and the response
+ * shape carry no signal distinguishing a withheld source from a
+ * missing one (the window read must not become a frontmatter oracle
+ * over pages the caller may not see).
+ */
+ readonly readableSource?: (rel: string) => boolean;
+}
+
export interface AppendClaimResult {
readonly path: string;
readonly event: ClaimEvent;
@@ -109,7 +245,7 @@ export interface AppendClaimResult {
export function appendClaimEvent(
vault: string,
input: AppendClaimInput,
- opts: { readonly configPath?: string } = {},
+ opts: AppendClaimOptions = {},
): AppendClaimResult {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
@@ -124,6 +260,51 @@ export function appendClaimEvent(
if (!ISO_UTC_TS_RE.test(input.ts)) {
throw new Error(`claim ts must be canonical ISO-8601 UTC: ${JSON.stringify(input.ts)}`);
}
+ // Ingest window defaults (truth-correctable-time-aware, task 3):
+ // explicit input wins outright; a bound the caller left open resolves
+ // from the source record's frontmatter `valid_from` / `valid_until`
+ // when the source is readable at the caller's reach, and the resolved
+ // value is frozen on the event. An unreadable, withheld (see
+ // `AppendClaimOptions.readableSource`) or windowless source stores a
+ // windowless event - byte-identical to the pre-window ledger. The
+ // source is read only when a bound is actually missing, so the fully
+ // explicit path performs no extra I/O; mtime is never consulted.
+ const needsSourceWindow = input.validFrom === undefined || input.validUntil === undefined;
+ const resolved = resolveIngestWindow(
+ input,
+ needsSourceWindow ? sourceFrontmatterWindow(vault, input.source, opts.readableSource) : null,
+ );
+ // Validity windows (contract item 1): presence-gated, strictly
+ // validated, and never guessed. An unparsable bound or an empty or
+ // inverted window refuses the append by name - typed, so the tool
+ // surfaces answer it as invalid params rather than an internal error.
+ if (resolved.validFrom !== undefined && !isValidityPoint(resolved.validFrom)) {
+ throw new ClaimWindowRefusal(
+ `claim validFrom must be a bare ISO date or canonical UTC timestamp: ${JSON.stringify(resolved.validFrom)}`,
+ );
+ }
+ if (resolved.validUntil !== undefined && !isValidityPoint(resolved.validUntil)) {
+ throw new ClaimWindowRefusal(
+ `claim validUntil must be a bare ISO date or canonical UTC timestamp: ${JSON.stringify(resolved.validUntil)}`,
+ );
+ }
+ const window = validityWindowMs(resolved.validFrom, resolved.validUntil);
+ if (
+ window !== null &&
+ window.fromMs !== null &&
+ window.untilMs !== null &&
+ window.fromMs >= window.untilMs
+ ) {
+ throw new ClaimWindowRefusal(
+ `claim validity window is empty or inverted: validFrom ${JSON.stringify(resolved.validFrom)} does not parse before validUntil ${JSON.stringify(resolved.validUntil)}`,
+ );
+ }
+ // Extractor (truth-correctable-time-aware, task 4): presence-gated,
+ // strict on write (this binary emits exactly one tag), tolerant on
+ // read. Annotation only - the tag never touches conflict semantics.
+ if (input.extractor !== undefined && input.extractor !== "agent_stated") {
+ throw new Error(`claim extractor must be agent_stated: ${JSON.stringify(input.extractor)}`);
+ }
const event: ClaimEvent = Object.freeze({
v: TRUTH_SCHEMA_VERSION,
@@ -134,7 +315,10 @@ export function appendClaimEvent(
value,
valueKind: input.valueKind ?? "text",
...(input.quantity !== undefined ? { quantity: input.quantity } : {}),
+ ...(resolved.validFrom !== undefined ? { validFrom: resolved.validFrom } : {}),
+ ...(resolved.validUntil !== undefined ? { validUntil: resolved.validUntil } : {}),
source: input.source.trim(),
+ ...(input.extractor !== undefined ? { extractor: input.extractor } : {}),
});
mkdirSync(truthDir(vault), { recursive: true });
@@ -271,6 +455,66 @@ function coerceClaim(
action: action as string | null,
});
}
+ // Validity fields (contract item 1): tolerated when absent (old
+ // lines), validated when present (new lines, schema v1). Unknown
+ // keys stay ignored, so an older binary reading these lines degrades
+ // to the assertion-time axis by construction.
+ const rawValidFrom = obj["validFrom"];
+ const rawValidUntil = obj["validUntil"];
+ if (
+ rawValidFrom !== undefined &&
+ (typeof rawValidFrom !== "string" || !isValidityPoint(rawValidFrom))
+ ) {
+ warnings.push({
+ path,
+ lineNumber,
+ message: `invalid claim validFrom: ${String(rawValidFrom)}`,
+ });
+ return null;
+ }
+ if (
+ rawValidUntil !== undefined &&
+ (typeof rawValidUntil !== "string" || !isValidityPoint(rawValidUntil))
+ ) {
+ warnings.push({
+ path,
+ lineNumber,
+ message: `invalid claim validUntil: ${String(rawValidUntil)}`,
+ });
+ return null;
+ }
+ const validFrom = rawValidFrom as string | undefined;
+ const validUntil = rawValidUntil as string | undefined;
+ const window = validityWindowMs(validFrom, validUntil);
+ if (
+ window !== null &&
+ window.fromMs !== null &&
+ window.untilMs !== null &&
+ window.fromMs >= window.untilMs
+ ) {
+ warnings.push({
+ path,
+ lineNumber,
+ message: "invalid claim validity window: validFrom must parse before validUntil",
+ });
+ return null;
+ }
+ // Extractor (task 4): tolerated when absent, validated as a
+ // non-empty string when present, passed through verbatim so a future
+ // extractor value survives an upgrade cycle. Annotation only.
+ const rawExtractor = obj["extractor"];
+ if (
+ rawExtractor !== undefined &&
+ (typeof rawExtractor !== "string" || rawExtractor.trim() === "")
+ ) {
+ warnings.push({
+ path,
+ lineNumber,
+ message: `invalid claim extractor: ${String(rawExtractor)}`,
+ });
+ return null;
+ }
+ const extractor = rawExtractor as ClaimExtractor | undefined;
return Object.freeze({
v: TRUTH_SCHEMA_VERSION,
ts,
@@ -280,6 +524,9 @@ function coerceClaim(
value: obj["value"] as string,
valueKind,
...(quantity !== undefined ? { quantity } : {}),
+ ...(validFrom !== undefined ? { validFrom } : {}),
+ ...(validUntil !== undefined ? { validUntil } : {}),
+ ...(extractor !== undefined ? { extractor } : {}),
source: obj["source"] as string,
});
}
@@ -335,6 +582,32 @@ function isTruthConflict(v: unknown): v is TruthConflict {
);
}
+function isClaimEventLike(v: unknown): v is ClaimEvent {
+ if (v === null || typeof v !== "object") return false;
+ const row = v as Record<string, unknown>;
+ return (
+ row["v"] === TRUTH_SCHEMA_VERSION &&
+ typeof row["ts"] === "string" &&
+ ISO_UTC_TS_RE.test(row["ts"]) &&
+ (["agent", "entity", "aspect", "value", "source"] as const).every(
+ (key) => typeof row[key] === "string" && (row[key] as string).trim() !== "",
+ ) &&
+ (row["valueKind"] === "text" || row["valueKind"] === "quantity")
+ );
+}
+
+function isClaimSuccession(v: unknown): v is ClaimSuccession {
+ if (v === null || typeof v !== "object") return false;
+ const row = v as Record<string, unknown>;
+ return (
+ typeof row["entity"] === "string" &&
+ typeof row["aspect"] === "string" &&
+ isClaimEventLike(row["predecessor"]) &&
+ isClaimEventLike(row["successor"]) &&
+ typeof row["detectedAt"] === "string"
+ );
+}
+
/**
* Read the derived state cache; structurally invalid content (including
* corrupt nested rows) reads as null and the caller refolds from events.
@@ -353,6 +626,15 @@ export function readTruthState(vault: string): TruthState | null {
for (const conflict of parsed.conflicts as ReadonlyArray<unknown>) {
if (!isTruthConflict(conflict)) return null;
}
+ // Successions are presence-gated (contract item 1): absent is the
+ // normal windowless shape, present must validate, and a corrupt
+ // channel reads as null so the caller refolds from events.
+ if (parsed.successions !== undefined) {
+ if (!Array.isArray(parsed.successions)) return null;
+ for (const succession of parsed.successions as ReadonlyArray<unknown>) {
+ if (!isClaimSuccession(succession)) return null;
+ }
+ }
return parsed;
} catch {
return null;
diff --git a/src/core/brain/truth/succession.ts b/src/core/brain/truth/succession.ts
new file mode 100644
index 00000000..b8231d94
--- /dev/null
+++ b/src/core/brain/truth/succession.ts
@@ -0,0 +1,117 @@
+/**
+ * Succession classification (truth-correctable-time-aware, contract
+ * item 1): the policy-layer sibling of `conflicts.ts`. A same-slot
+ * claim pair is succession if and only if BOTH claims carry present
+ * validity windows and the windows do not intersect; every other pair
+ * keeps the assertion-time contest rule verbatim, and an expired
+ * window never suppresses contestation on its own.
+ *
+ * Succession stays outside the conflict vocabulary on purpose: it is a
+ * separate, presence-gated channel on {@link TruthState}, never a
+ * `TruthConflictKind`, so `ask_user` semantics, hygiene findings and
+ * conflict priority are structurally unreachable from here. Pure
+ * functions; no I/O, no clock.
+ */
+
+import { normalizeClaimValue, slotKey } from "./fold.ts";
+import type { ClaimEvent, ClaimSuccession } from "./types.ts";
+import { claimWindow, windowsIntersect } from "./validity.ts";
+
+/**
+ * Whether one same-slot claim pair classifies as succession: distinct
+ * values, both claims carrying present windows, windows
+ * non-intersecting. Re-assertions of one value are never succession -
+ * they are the same fact restated, and they can never contest either.
+ */
+export function isSuccessionPair(a: ClaimEvent, b: ClaimEvent): boolean {
+ if (normalizeClaimValue(a.value) === normalizeClaimValue(b.value)) return false;
+ const wa = claimWindow(a);
+ const wb = claimWindow(b);
+ if (wa === null || wb === null) return false;
+ return !windowsIntersect(wa, wb);
+}
+
+/**
+ * Whether two values inside one slot are fully separated by the
+ * succession rule: every cross-pair of their claims satisfies
+ * {@link isSuccessionPair}. Any windowless or intersecting cross-pair
+ * keeps today's contest behavior verbatim, so the conflict policy may
+ * exclude a version pair from contestation only under this predicate.
+ * Value comparison uses the fold's normalized identity.
+ */
+export function valuesSuccessionSeparated(
+ slotEvents: ReadonlyArray<ClaimEvent>,
+ valueA: string,
+ valueB: string,
+): boolean {
+ const normA = normalizeClaimValue(valueA);
+ const normB = normalizeClaimValue(valueB);
+ if (normA === normB) return false;
+ const groupA = slotEvents.filter((e) => normalizeClaimValue(e.value) === normA);
+ const groupB = slotEvents.filter((e) => normalizeClaimValue(e.value) === normB);
+ if (groupA.length === 0 || groupB.length === 0) return false;
+ return groupA.every((a) => groupB.every((b) => isSuccessionPair(a, b)));
+}
+
+/** Stable total order over events: (ts, agent, source, value) - the fold's order. */
+function compareEvents(a: ClaimEvent, b: ClaimEvent): number {
+ if (a.ts !== b.ts) return a.ts < b.ts ? -1 : 1;
+ if (a.agent !== b.agent) return a.agent < b.agent ? -1 : 1;
+ if (a.source !== b.source) return a.source < b.source ? -1 : 1;
+ if (a.value !== b.value) return a.value < b.value ? -1 : 1;
+ return 0;
+}
+
+/** The latest-asserted claim of one normalized value inside a slot. */
+function latestClaimForValue(slotEvents: ReadonlyArray<ClaimEvent>, normValue: string): ClaimEvent {
+ const group = slotEvents.filter((e) => normalizeClaimValue(e.value) === normValue);
+ return group.reduce((latest, e) => (compareEvents(e, latest) > 0 ? e : latest));
+}
+
+/**
+ * Classify successions over all claim events, one {@link ClaimSuccession}
+ * per slot value-pair that is fully succession-separated. The
+ * predecessor is the representative claim (latest assertion) whose
+ * window closes first - non-intersection guarantees a finite earlier
+ * end, so the ordering is total. Output sorts by slot key for
+ * determinism; the result is independent of input order.
+ */
+export function classifyClaimSuccessions(
+ events: ReadonlyArray<ClaimEvent>,
+): ReadonlyArray<ClaimSuccession> {
+ const bySlot = new Map<string, ClaimEvent[]>();
+ for (const e of events) {
+ const key = slotKey(e.entity, e.aspect);
+ const list = bySlot.get(key);
+ if (list === undefined) bySlot.set(key, [e]);
+ else list.push(e);
+ }
+
+ const out: ClaimSuccession[] = [];
+ for (const key of [...bySlot.keys()].toSorted()) {
+ const slotEvents = bySlot.get(key)!;
+ const [entity, aspect] = key.split("\n") as [string, string];
+ const values = [...new Set(slotEvents.map((e) => normalizeClaimValue(e.value)))].toSorted();
+ for (let i = 0; i < values.length; i++) {
+ for (let j = i + 1; j < values.length; j++) {
+ if (!valuesSuccessionSeparated(slotEvents, values[i]!, values[j]!)) continue;
+ const first = latestClaimForValue(slotEvents, values[i]!);
+ const second = latestClaimForValue(slotEvents, values[j]!);
+ const firstUntil = claimWindow(first)!.untilMs ?? Number.POSITIVE_INFINITY;
+ const secondUntil = claimWindow(second)!.untilMs ?? Number.POSITIVE_INFINITY;
+ const [predecessor, successor] =
+ firstUntil <= secondUntil ? [first, second] : [second, first];
+ out.push(
+ Object.freeze({
+ entity,
+ aspect,
+ predecessor: Object.freeze(predecessor),
+ successor: Object.freeze(successor),
+ detectedAt: successor.ts,
+ }),
+ );
+ }
+ }
+ }
+ return Object.freeze(out);
+}
diff --git a/src/core/brain/truth/types.ts b/src/core/brain/truth/types.ts
index aff17d6a..a8cc336a 100644
--- a/src/core/brain/truth/types.ts
+++ b/src/core/brain/truth/types.ts
@@ -12,6 +12,15 @@ export const TRUTH_SCHEMA_VERSION = 1;
export type ClaimValueKind = "text" | "quantity";
+/**
+ * How a claim entered the ledger. The only writer-side value this
+ * release emits is `agent_stated` (a grounded agent-stated claim,
+ * truth-correctable-time-aware task 4); reads tolerate any non-empty
+ * string under schema v1 so a future extractor survives an upgrade
+ * cycle untouched.
+ */
+export type ClaimExtractor = "agent_stated";
+
/** Structured payload for the quantitative fact family (t_220c313e). */
export interface ClaimQuantity {
readonly value: number;
@@ -27,6 +36,16 @@ export interface ClaimQuantity {
* (NFC, lowercase, collapsed whitespace) so slot addressing compares
* like with like; `value` keeps its display casing and is normalized
* only for identity comparison inside the fold.
+ *
+ * The optional validity fields carry the claim's real-world validity
+ * window, half-open `[validFrom, validUntil)` (see `validity.ts`).
+ * They are presence-gated under `TRUTH_SCHEMA_VERSION = 1`: absent
+ * keys mean windowless, and every windowless line serializes
+ * byte-identically to the pre-window ledger. Stored values are bare
+ * ISO dates or canonical UTC timestamps; comparisons run on the
+ * validity axis only when BOTH claims of a pair carry present windows
+ * (contract item 1) - a windowless or expired claim never suppresses
+ * assertion-time contestation on its own.
*/
export interface ClaimEvent {
readonly v: typeof TRUTH_SCHEMA_VERSION;
@@ -38,6 +57,16 @@ export interface ClaimEvent {
readonly value: string;
readonly valueKind: ClaimValueKind;
readonly quantity?: ClaimQuantity;
+ /** Validity window start (bare ISO date or canonical UTC timestamp). */
+ readonly validFrom?: string;
+ /** Validity window end, exclusive (bare ISO date or canonical UTC timestamp). */
+ readonly validUntil?: string;
+ /**
+ * Presence-gated provenance tag (schema v1): how this claim entered
+ * the ledger. Annotation only - the tag never changes which pairs
+ * contest, never re-ranks conflict priority, and never resolves one.
+ */
+ readonly extractor?: ClaimExtractor;
/** Provenance wikilink or vault-relative path. */
readonly source: string;
}
@@ -53,6 +82,14 @@ export interface ClaimVersion {
readonly source: string;
/** How many events asserted this value. */
readonly assertCount: number;
+ /**
+ * Validity fields tolerated on state-file versions for schema
+ * forward-compatibility. The fold does not populate them (succession
+ * reads windows from the events themselves), so they stay absent in
+ * every state this binary writes.
+ */
+ readonly validFrom?: string;
+ readonly validUntil?: string;
}
/**
@@ -87,13 +124,38 @@ export interface TruthConflict {
readonly detectedAt: string;
}
-/** The derived fold over all retained claim events. */
+/**
+ * A superseded-by-windows transition (contract item 1): two distinct
+ * values for one slot whose claims all carry present, non-intersecting
+ * validity windows. Succession lives OUTSIDE the conflict vocabulary -
+ * it is never a {@link TruthConflict}, never `ask_user`, and never
+ * reaches hygiene findings or conflict priority. The predecessor is
+ * the claim whose window closes first; `detectedAt` is the successor's
+ * assertion timestamp.
+ */
+export interface ClaimSuccession {
+ readonly entity: string;
+ readonly aspect: string;
+ readonly predecessor: ClaimEvent;
+ readonly successor: ClaimEvent;
+ readonly detectedAt: string;
+}
+
+/**
+ * The derived fold over all retained claim events.
+ *
+ * `successions` is presence-gated: undefined (never an empty array)
+ * whenever no succession classifies, and serialized by conditional
+ * spread so windowless states stay byte-identical to the pre-window
+ * ledger.
+ */
export interface TruthState {
readonly version: typeof TRUTH_SCHEMA_VERSION;
readonly events: number;
readonly updatedAt: string | null;
readonly slots: ReadonlyArray<ClaimSlot>;
readonly conflicts: ReadonlyArray<TruthConflict>;
+ readonly successions?: ReadonlyArray<ClaimSuccession>;
}
export interface ClaimParseWarning {
diff --git a/src/core/brain/truth/validity.ts b/src/core/brain/truth/validity.ts
new file mode 100644
index 00000000..08814a4e
--- /dev/null
+++ b/src/core/brain/truth/validity.ts
@@ -0,0 +1,203 @@
+/**
+ * Ledger validity windows (truth-correctable-time-aware, contract
+ * item 1): the assertion-versus-validity axis for the claim ledger.
+ *
+ * A claim may carry an optional presence-gated validity window
+ * (`validFrom` / `validUntil`, half-open `[validFrom, validUntil)`),
+ * stored as a bare ISO date or a canonical UTC timestamp. Window
+ * parsing shares the `src/core/search/validity.ts` grammar - the same
+ * shapes parse, datetimes with a missing offset read as UTC, and
+ * relative phrases never parse, because a stored window must not be
+ * clock-dependent - with one ledger-specific difference pinned by this
+ * module's own tests: a bare date resolves to its `T00:00:00Z` start on
+ * BOTH edges, so the exclusive until bound keeps adjacent bare-date
+ * windows (`until: 2026-09-01` then `from: 2026-09-01`) disjoint, the
+ * half-open convention `lifecycle/temporal-replace.ts` evaluates
+ * frontmatter windows by. This module mirrors that grammar locally
+ * rather than importing it, so the Brain layer keeps no dependency on
+ * the search layer.
+ *
+ * Pure functions; no I/O, no clock.
+ */
+
+import type { ClaimEvent } from "./types.ts";
+
+const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
+
+/**
+ * Parse one validity point to unix ms, mirroring the
+ * `src/core/search/validity.ts` grammar. A bare date resolves to its
+ * day start on BOTH edges - the until bound stays exclusive, so a
+ * bare-date window is half-open and adjacent bare-date windows never
+ * intersect. Returns null for relative phrases, garbage, and impossible
+ * calendar dates - never a guess.
+ */
+function validityPointMs(raw: string): number | null {
+ const text = raw.trim();
+ if (text === "") return null;
+ const date = ISO_DATE_RE.exec(text);
+ if (date) {
+ const ms = Date.UTC(Number(date[1]), Number(date[2]) - 1, Number(date[3]));
+ const check = new Date(ms);
+ if (
+ check.getUTCFullYear() !== Number(date[1]) ||
+ check.getUTCMonth() !== Number(date[2]) - 1 ||
+ check.getUTCDate() !== Number(date[3])
+ ) {
+ return null;
+ }
+ return ms;
+ }
+ if (text.includes("T") || text.includes("t")) {
+ const hasOffset = /(?:z|[+-]\d{2}:?\d{2})$/i.test(text);
+ const parsed = Date.parse(hasOffset ? text : `${text}Z`);
+ if (Number.isFinite(parsed)) return parsed;
+ }
+ return null;
+}
+
+/**
+ * Whether `raw` is a storable ledger validity point: a bare ISO date
+ * (day-snapped at parse time) or a canonical UTC timestamp. Everything
+ * else - relative phrases, offset-bearing datetimes, empty strings,
+ * garbage - is rejected by the write boundary with a named error.
+ */
+export function isValidityPoint(raw: string): boolean {
+ const text = raw.trim();
+ if (text === "") return false;
+ if (ISO_DATE_RE.test(text)) return validityPointMs(text) !== null;
+ // Canonical UTC only: a timestamp must end in Z (offsets are not
+ // canonical and are rejected rather than normalized).
+ return /(?:z)$/i.test(text) && validityPointMs(text) !== null;
+}
+
+/** The validity window of one claim, in unix ms. */
+export interface ClaimWindow {
+ /** Window start, or null when open on the from side. */
+ readonly fromMs: number | null;
+ /** Window end (exclusive), or null when open on the until side. */
+ readonly untilMs: number | null;
+}
+
+/**
+ * The validity window an event carries, or null when the event carries
+ * no window at all. A missing bound is unbounded on that side; a
+ * present-but-unparseable bound reads as unbounded too (the write
+ * boundary rejects unparseable values with a named error, so this
+ * branch only tolerates hand-built events).
+ */
+export function claimWindow(event: ClaimEvent): ClaimWindow | null {
+ const hasFrom = typeof event.validFrom === "string" && event.validFrom.trim() !== "";
+ const hasUntil = typeof event.validUntil === "string" && event.validUntil.trim() !== "";
+ if (!hasFrom && !hasUntil) return null;
+ return Object.freeze({
+ fromMs: hasFrom ? validityPointMs(event.validFrom!) : null,
+ untilMs: hasUntil ? validityPointMs(event.validUntil!) : null,
+ });
+}
+
+/**
+ * Half-open intersection: `[a.validFrom, a.validUntil)` overlaps
+ * `[b.validFrom, b.validUntil)` iff `a.fromMs < b.untilMs` and
+ * `b.fromMs < a.untilMs`, with a missing bound acting as minus
+ * infinity on the from side and plus infinity on the until side.
+ */
+export function windowsIntersect(a: ClaimWindow, b: ClaimWindow): boolean {
+ const aFrom = a.fromMs ?? Number.NEGATIVE_INFINITY;
+ const aUntil = a.untilMs ?? Number.POSITIVE_INFINITY;
+ const bFrom = b.fromMs ?? Number.NEGATIVE_INFINITY;
+ const bUntil = b.untilMs ?? Number.POSITIVE_INFINITY;
+ return aFrom < bUntil && bFrom < aUntil;
+}
+
+/** Strictly parsed present bounds of a candidate window. */
+export interface ParsedValidityWindow {
+ readonly fromMs: number | null;
+ readonly untilMs: number | null;
+}
+
+/**
+ * Parse a candidate window's bounds under the storable grammar
+ * ({@link isValidityPoint}) for the append and read boundaries.
+ * Returns null when any PRESENT bound fails the grammar - the caller
+ * names the failure; absent bounds simply parse to null on their side.
+ */
+export function validityWindowMs(
+ validFrom: string | undefined,
+ validUntil: string | undefined,
+): ParsedValidityWindow | null {
+ const hasFrom = validFrom !== undefined && validFrom.trim() !== "";
+ const hasUntil = validUntil !== undefined && validUntil.trim() !== "";
+ if (hasFrom && !isValidityPoint(validFrom!)) return null;
+ if (hasUntil && !isValidityPoint(validUntil!)) return null;
+ return Object.freeze({
+ fromMs: hasFrom ? validityPointMs(validFrom!) : null,
+ untilMs: hasUntil ? validityPointMs(validUntil!) : null,
+ });
+}
+
+/**
+ * A validity window candidate as carried by a caller's input or by a
+ * source record's frontmatter (`valid_from` / `valid_until`).
+ */
+export interface SourceValidityWindow {
+ readonly validFrom?: string;
+ readonly validUntil?: string;
+}
+
+/** The resolved ingest window: only the bounds that survive resolution. */
+export interface ResolvedIngestWindow {
+ readonly validFrom?: string;
+ readonly validUntil?: string;
+}
+
+/**
+ * A source-side bound participates only when it is present and parses
+ * under the storable grammar. A malformed frontmatter window must
+ * never refuse an otherwise-valid ingest nor leak garbage into the
+ * ledger, so it resolves as absent; explicit input bypasses this gate
+ * verbatim, because the append boundary validates it and names the
+ * failure.
+ */
+function sourceBound(value: string | undefined): string | undefined {
+ if (value === undefined) return undefined;
+ const text = value.trim();
+ if (text === "" || !isValidityPoint(text)) return undefined;
+ return text;
+}
+
+/**
+ * Ingest window defaults, frozen at ingest (truth-correctable-time-aware,
+ * task 3): each explicit input bound wins outright; a bound the caller
+ * left open resolves from the source record's frontmatter window, and
+ * the adopted string is stored verbatim (frozen - never a live
+ * reference back to the record). A null source window (unreadable or
+ * windowless source) resolves nothing, so the event stays windowless
+ * and byte-identical to the pre-window ledger. mtime is not an input
+ * here by construction: an mtime is an assertion-time proxy, not
+ * validity. Resolution is per bound, so an explicit from pairs with a
+ * source until.
+ *
+ * Pure; the caller owns reading the source record.
+ */
+export function resolveIngestWindow(
+ input: SourceValidityWindow,
+ sourceWindow: SourceValidityWindow | null,
+): ResolvedIngestWindow {
+ const fromExplicit = input.validFrom !== undefined;
+ const untilExplicit = input.validUntil !== undefined;
+ const validFrom = fromExplicit
+ ? input.validFrom
+ : sourceWindow === null
+ ? undefined
+ : sourceBound(sourceWindow.validFrom);
+ const validUntil = untilExplicit
+ ? input.validUntil
+ : sourceWindow === null
+ ? undefined
+ : sourceBound(sourceWindow.validUntil);
+ return Object.freeze({
+ ...(validFrom !== undefined ? { validFrom } : {}),
+ ...(validUntil !== undefined ? { validUntil } : {}),
+ });
+}
diff --git a/src/core/graph/relation-vocab.ts b/src/core/graph/relation-vocab.ts
index aa21c3be..0a4b1b74 100644
--- a/src/core/graph/relation-vocab.ts
+++ b/src/core/graph/relation-vocab.ts
@@ -20,6 +20,14 @@
* natural-language phrase.
*/
+/**
+ * The supersession edge relation: the token whose typed edge declares a
+ * page's successor. Exported once here - the vocabulary's single
+ * boundary - so consumers read the relation from this module instead of
+ * hardcoding the string at their own call sites.
+ */
+export const SUPERSEDED_BY_RELATION = "superseded_by";
+
/**
* The default semantic relation types. A frontmatter relation field
* name is identical to the relation it produces (`contradicts:` β†’
@@ -32,7 +40,7 @@ export const DEFAULT_RELATION_TYPES = Object.freeze([
"depends_on",
"refines",
"contradicts",
- "superseded_by",
+ SUPERSEDED_BY_RELATION,
] as const);
export type DefaultRelationType = (typeof DEFAULT_RELATION_TYPES)[number];
diff --git a/src/core/search/correction-coupling.ts b/src/core/search/correction-coupling.ts
new file mode 100644
index 00000000..fb270c14
--- /dev/null
+++ b/src/core/search/correction-coupling.ts
@@ -0,0 +1,93 @@
+/**
+ * Serve-with-correction coupling predicate (truth-correctable-time-aware,
+ * contract item 3, Task 15).
+ *
+ * A retired-but-serveable row - a validity-closed predecessor inside its
+ * window, or a superseded non-tip that is still serveable - is served only
+ * beside its chain-tip correction. When the chain-tip successor is
+ * unresolved or unreadable at the caller's reach, the row is dropped
+ * FAIL-CLOSED: a withheld page stays indistinguishable from an absent one.
+ *
+ * The predicate is pure: callers resolve the chain tip (via
+ * `resolveChainTip`/`buildChainLookup`) and the successor's readability at
+ * the caller's reach, then ask for the verdict. It performs no I/O and
+ * never inspects the vault, so every serving surface - search post-rank,
+ * recall by topic, context-pack, active.md, dream scan - consumes the one
+ * spelling of the rule from this module.
+ *
+ * Tombstoned rows are NOT this predicate's concern: they stay dropped by
+ * the status filter everywhere, before any coupling question arises. The
+ * predicate governs the serveable-retired regime only.
+ */
+
+/** The verdict a serving surface acts on for one retired-but-serveable row. */
+export type CouplingVerdict =
+ | { readonly action: "serve_coupled"; readonly correctionPath: string }
+ | { readonly action: "drop" };
+
+export interface CouplingInput {
+ /**
+ * Path of the retired-but-serveable row's page. Caller context, not a
+ * verdict input: the predicate never reads it - the verdict turns on
+ * the successor fields alone - while callers carry the path into the
+ * receipts and records they write once the verdict is in. It stays on
+ * the input so every surface hands one shape and the pairing of
+ * predecessor to verdict is visible at the call site.
+ */
+ readonly predecessorPath: string;
+ /** Chain-tip successor path from resolveChainTip/buildChainLookup, null when unresolved. */
+ readonly successorPath: string | null;
+ /** True when the successor page is readable at the caller's reach. */
+ readonly successorReadable: boolean;
+}
+
+/** Action values, spelled once so the fail-closed default is visible here. */
+const SERVE_COUPLED = "serve_coupled" as const;
+const DROP = "drop" as const;
+
+/**
+ * Decide whether a retired-but-serveable row may be served. Resolved AND
+ * readable successor yields `serve_coupled` carrying the correction path;
+ * every other combination drops the row. Pure and deterministic.
+ */
+export function couplingVerdict(input: CouplingInput): CouplingVerdict {
+ if (input.successorPath === null || !input.successorReadable) {
+ return { action: DROP };
+ }
+ return { action: SERVE_COUPLED, correctionPath: input.successorPath };
+}
+
+/**
+ * The slice of `resolveChainTip`'s result a verdict needs - structural,
+ * so the Brain serving surfaces can hand one over without this module
+ * importing the lifecycle's types.
+ */
+export interface ChainResolution {
+ /** False when the walk stopped at an id the lookup could not resolve. */
+ readonly resolvedAll: boolean;
+ /** True when a cycle or the depth cap short-circuited the walk. */
+ readonly cycle: boolean;
+ /** Normalized identifier of the chain tip the walk stopped on. */
+ readonly tip: string;
+}
+
+/**
+ * The one mapping from a resolved chain to the verdict, shared by every
+ * Brain serving surface: a chain that resolved on every hop to its tip
+ * serves the row beside that tip; a dangling hop, a cycle or a depth-cap
+ * stop is an unresolved correction and drops the row fail-closed. The
+ * caller's readability composition is folded into the chain lookup it
+ * built (a page the caller may not read is not indexed), so a fully
+ * resolved chain is by construction readable at the caller's reach.
+ */
+export function chainVerdict(
+ predecessorPath: string,
+ resolution: ChainResolution,
+): CouplingVerdict {
+ const resolved = resolution.resolvedAll && !resolution.cycle;
+ return couplingVerdict({
+ predecessorPath,
+ successorPath: resolved ? resolution.tip : null,
+ successorReadable: resolved,
+ });
+}
diff --git a/src/core/search/index.ts b/src/core/search/index.ts
index 4405bdfd..297c2a29 100644
--- a/src/core/search/index.ts
+++ b/src/core/search/index.ts
@@ -93,6 +93,22 @@ export {
SearchError,
SEARCH_ERROR_CODES,
} from "./types.ts";
+export {
+ resolveTraversalBudgets,
+ TRAVERSAL_MAX_SEEDS,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE,
+ TRAVERSAL_MAX_TOTAL_NODES,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD,
+ TRAVERSAL_MAX_SEEDS_ENV,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE_ENV,
+ TRAVERSAL_MAX_TOTAL_NODES_ENV,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD_ENV,
+ TRAVERSAL_MAX_SEEDS_CONFIG,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE_CONFIG,
+ TRAVERSAL_MAX_TOTAL_NODES_CONFIG,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD_CONFIG,
+ type TraversalBudgets,
+} from "./relational-fanout.ts";
export {
parseStructuredRecallQueryDocument,
structuredRecallQueryText,
@@ -1407,6 +1423,7 @@ export function resolveSearchConfig(opts: {
const base: ResolvedSearchConfig = Object.freeze({
vault: opts.vault,
dbPath,
+ configPath: opts.configPath ?? null,
scopeRules,
chunkSize,
chunkOverlap,
diff --git a/src/core/search/pipeline/attribution.ts b/src/core/search/pipeline/attribution.ts
index 5a79eed7..1c512782 100644
--- a/src/core/search/pipeline/attribution.ts
+++ b/src/core/search/pipeline/attribution.ts
@@ -90,14 +90,27 @@ export function decorateFinalResults(input: DecorationInput): ReadonlyArray<Brai
: "second_pass: or-broadened retry";
return Object.freeze({ ...r, reasons: Object.freeze([...r.reasons, reason]) });
});
- // Relational-arm attribution (t_09b7ccea): a node surfaced by the
- // typed-edge fan-out carries a reason naming the link types and hop
- // distance it was reached by. An empty reach map (arm off) is a no-op.
+ // Relational-arm attribution (t_09b7ccea; ordered path provenance,
+ // truth-correctable-time-aware): a node surfaced by the typed-edge
+ // fan-out carries a reason naming the link types and hop distance it was
+ // reached by. Per-node gating omits unreadable or out-of-scope path
+ // nodes from the ordered path; the reason never states how many were
+ // dropped, because a count would tell the caller that a node it may not
+ // see exists (the views' identical-to-absent convention). A readable
+ // path node that is a non-tip superseded predecessor with a closed
+ // validity window annotates the row with the frontmatter pointer's tip.
+ // An empty reach map (arm off) is a no-op.
if (input.relationalReach.size === 0) return withSecondPassReasons;
return withSecondPassReasons.map((r) => {
const reach = input.relationalReach.get(r.chunkId);
if (reach === undefined) return r;
- const reason = `relational: via ${reach.via.join(", ")} (${reach.hops} hop${reach.hops === 1 ? "" : "s"})`;
- return Object.freeze({ ...r, reasons: Object.freeze([...r.reasons, reason]) });
+ const reason =
+ `relational: via ${reach.via.join(", ")} ` +
+ `(${reach.hops} hop${reach.hops === 1 ? "" : "s"})`;
+ const reasons =
+ reach.supersededBy !== undefined
+ ? [...r.reasons, reason, `superseded_by: ${reach.supersededBy}`]
+ : [...r.reasons, reason];
+ return Object.freeze({ ...r, reasons: Object.freeze(reasons) });
});
}
diff --git a/src/core/search/pipeline/outcome.ts b/src/core/search/pipeline/outcome.ts
index d47c832a..516dc3b0 100644
--- a/src/core/search/pipeline/outcome.ts
+++ b/src/core/search/pipeline/outcome.ts
@@ -24,6 +24,8 @@ import {
corpusStatementFor,
INDEX_STALE_SECONDS,
RETRIEVAL_DEGRADATION,
+ RETRIEVAL_RELATIONAL_PATH_CODE,
+ type RelationalPathTrailEntry,
} from "../retrieval-trail.ts";
import { buildEvidenceVerification, coverageOverResults } from "../evidence-verification.ts";
import { fnv1aHex } from "../feedback.ts";
@@ -33,6 +35,7 @@ import {
isPathReadableAtReach,
type FrontmatterCache,
} from "../result-filters.ts";
+import type { RelationalReach } from "./relational-arm.ts";
import type {
CoverageIndexSnapshot,
CoverageScope,
@@ -51,6 +54,30 @@ import type {
const NO_RESULTS: ReadonlyArray<BrainSearchResult> = Object.freeze([]);
+/**
+ * The relational arm's reach-gated ordered paths for the surfaced rows,
+ * one entry per surfaced relational row in ranked order - the projection
+ * the trail renders as `relational-path` entries. Undefined when the arm
+ * contributed nothing or none of its rows survived to this window, so an
+ * arm-off answer is byte-identical to the pre-change one.
+ */
+function relationalPathEntries(
+ reach: ReadonlyMap<number, RelationalReach> | undefined,
+ results: ReadonlyArray<BrainSearchResult>,
+): ReadonlyArray<RelationalPathTrailEntry> | undefined {
+ if (reach === undefined || reach.size === 0) return undefined;
+ const entries: RelationalPathTrailEntry[] = [];
+ for (const r of results) {
+ const node = reach.get(r.chunkId);
+ if (node === undefined) continue;
+ entries.push({
+ code: RETRIEVAL_RELATIONAL_PATH_CODE,
+ path: node.path.map((step) => step.documentId),
+ });
+ }
+ return entries.length > 0 ? entries : undefined;
+}
+
export interface EmptyOutcomeInput {
readonly store: Store;
readonly opts: SearchOptions;
@@ -148,6 +175,15 @@ export interface OutcomeInput {
* keeps that path free of the index reads the probe performs.
*/
readonly corpus: RetrievalCorpusStatement | null;
+ /**
+ * The relational arm's reach map (deepened traversal,
+ * truth-correctable-time-aware), handed over so the trail renders the
+ * ordered provenance of the rows this outcome actually surfaces.
+ * Absent or empty - the arm off, or none of its rows surviving to the
+ * surfaced window - projects to no trail entry, keeping those answers
+ * byte-identical to the pre-change shape.
+ */
+ readonly relationalReach?: ReadonlyMap<number, RelationalReach>;
}
export function buildSearchOutcome(input: OutcomeInput): SearchOutcome {
@@ -212,11 +248,13 @@ export function buildSearchOutcome(input: OutcomeInput): SearchOutcome {
? attachTrustMetadata(config.vault, finalResults, input.frontmatterCache)
: finalResults;
+ const relationalPaths = relationalPathEntries(input.relationalReach, resultsOut);
const retrievalTrail = buildRetrievalTrail({
retrieved: resultsOut.length,
pool: input.poolSize,
degraded: input.degraded,
empty: input.corpus ?? undefined,
+ ...(relationalPaths !== undefined ? { relationalPaths } : {}),
});
const tail = {
@@ -276,6 +314,13 @@ export function withIndexStale(outcome: SearchOutcome, ageSeconds: number | null
retrieved: trail?.retrieved ?? outcome.cards?.length ?? outcome.results.length,
pool: trail?.pool ?? outcome.total,
degraded: Object.freeze([stale, ...(trail?.degraded ?? [])]),
+ // The walked provenance is not a degradation statement, so unlike the
+ // corpus statement it does not give way to the stale note: the rebuilt
+ // trail is the one the pipeline would have built with this code in its
+ // sink, and that build carries the arm's ordered paths whenever the
+ // arm contributed surfaced rows. Absent stays absent, so an arm-off
+ // answer's rebuilt trail is shaped exactly as before.
+ ...(trail?.relationalPaths?.length ? { relationalPaths: trail.relationalPaths } : {}),
});
if (trail !== undefined) return Object.freeze({ ...outcome, retrievalTrail });
// A healthy answer has no trail; it goes where the outcome builders put
diff --git a/src/core/search/pipeline/post-rank.ts b/src/core/search/pipeline/post-rank.ts
index 745204f7..414ed0fe 100644
--- a/src/core/search/pipeline/post-rank.ts
+++ b/src/core/search/pipeline/post-rank.ts
@@ -15,13 +15,28 @@ import { join } from "node:path";
import { emitGatedTelemetry } from "../../brain/continuity/emit.ts";
import { privateRegionTexts } from "../../redactor.ts";
+import {
+ MAX_CHAIN_DEPTH,
+ SUPERSEDED_BY_KEY,
+ isTombstoned,
+} from "../../brain/lifecycle/tombstone.ts";
import {
buildMemoryTrustAssessment,
buildRetrievalDecisionTrace,
} from "../../brain/trust/retrieval-receipts.ts";
import { trustGateAdjuster } from "../../brain/trust/retrieval-gate.ts";
import { applyRelationPolarityPhase } from "../graph-phases.ts";
-import { resolvedTransportReach } from "../../graph/transport-reach.ts";
+import { clamp01 } from "../../math.ts";
+import { isVisible, pageVisibility } from "../../graph/visibility.ts";
+import { SUPERSEDED_BY_RELATION } from "../../graph/relation-vocab.ts";
+import { couplingVerdict, type CouplingVerdict } from "../correction-coupling.ts";
+import { SUCCESSOR_CARRY } from "../relation-polarity.ts";
+import {
+ applyPoolFilters,
+ resolvePoolFilters,
+ type FilterContext,
+ type PoolFilters,
+} from "./pool-filters.ts";
import { applyRankAdjusters, type RankAdjuster } from "../rank-adjust.ts";
import { applyReinforceBoost, loadReinforceStrengths } from "../reinforce.ts";
import { applyCrossEncoderRerank } from "../rerank/index.ts";
@@ -29,15 +44,17 @@ import { applyRelationalRerankPin } from "./relational-arm.ts";
import type { DecisionRerankExtras } from "../rerank/decision-model.ts";
import { RERANK_QUESTIONS } from "../../decision-model/questions.ts";
import type { FrontmatterMap } from "../../types.ts";
-import { pageVisibility } from "../../graph/visibility.ts";
import {
applyReachFilter,
+ isPathOwnerVisible,
+ isPathReadableAtReach,
readCachedFrontmatter,
readCachedFrontmatterEntry,
supersedeFadeAdjuster,
type FrontmatterCache,
} from "../result-filters.ts";
import { applyStructuredExclusions } from "../structured-lanes.ts";
+import type { HydratedChunk } from "../store/chunks.ts";
import {
RETRIEVAL_DEGRADATION,
noteDegradation,
@@ -126,6 +143,304 @@ function decisionMetaFields(meta: FrontmatterMap): Readonly<Record<string, strin
return Object.keys(out).length > 0 ? out : null;
}
+// ----- Serve-with-correction coupling ---------------------------------------
+
+// The chain walk reads its edge relation through the relation
+// vocabulary's single boundary: SUPERSEDED_BY_RELATION is the same word
+// as the frontmatter key ({@link SUPERSEDED_BY_KEY}), but a distinct
+// vocabulary - this one names an indexed edge relation.
+
+/**
+ * Provenance stamped on a correction row the coupling stage pulled in,
+ * naming the retired-but-serveable row it legitimized - the machine
+ * reason vocabulary the polarity phase's `supersedes_matched:` belongs to.
+ */
+export const CORRECTION_FOR_REASON_PREFIX = "correction_for:";
+
+interface CouplingOutcome {
+ readonly pool: ReadonlyArray<BrainSearchResult>;
+ /** True when the stage appended a correction row absent from the pool. */
+ readonly pulledIn: boolean;
+}
+
+/**
+ * Resolve a row's `superseded_by` chain to its tip document id, walking
+ * the index's typed edges - the frontmatter's own pointers, one edge
+ * fetch per hop, bounded by the lifecycle chain cap. Null when any hop
+ * dangles, the walk cycles, or the cap is hit: an unresolved tip is the
+ * coupling predicate's fail-closed input.
+ */
+function resolveChainTipDocumentId(
+ store: PostRankInput["store"],
+ startDocumentId: number,
+): number | null {
+ let documentId: number | null = startDocumentId;
+ const visited = new Set<number>();
+ for (let hop = 0; hop < MAX_CHAIN_DEPTH; hop++) {
+ if (documentId === null || visited.has(documentId)) return null;
+ visited.add(documentId);
+ // A page declaring several successors is pathological; the
+ // target-ordered first edge keeps the walk deterministic.
+ const edges = store
+ .typedRelationEdgesForDocuments([documentId])
+ .filter((edge) => edge.relation === SUPERSEDED_BY_RELATION)
+ .toSorted((a, b) => (a.target < b.target ? -1 : a.target > b.target ? 1 : 0));
+ if (edges.length === 0) return documentId;
+ documentId = edges[0]!.targetDocumentId;
+ }
+ return null;
+}
+
+/**
+ * May the caller's full filter set serve this correction page? The
+ * composed verdict carried as the predicate's `successorReadable` input:
+ * the page must be readable, not itself tombstoned, inside the caller's
+ * agent scope and visibility scope, and readable at its reach. Every
+ * answer here is fail-closed - a page that fails any rung makes the row
+ * it would legitimize drop instead of surface bare.
+ */
+function correctionReadableAtCaller(
+ path: string,
+ vault: string,
+ frontmatterCache: FrontmatterCache,
+ store: PostRankInput["store"],
+ filters: PoolFilters,
+): boolean {
+ const entry = readCachedFrontmatterEntry(frontmatterCache, vault, path);
+ if (entry.unreadable || isTombstoned(entry.meta)) return false;
+ if (
+ filters.agentScope !== null &&
+ !isPathOwnerVisible(vault, path, filters.agentScope, frontmatterCache)
+ ) {
+ return false;
+ }
+ if (!isVisible(pageVisibility(entry.meta), filters.visibilityScope)) return false;
+ const indexedTags = store.indexedVisibilityByPaths([path]).get(path);
+ return isPathReadableAtReach(vault, path, filters.reach, frontmatterCache, indexedTags);
+}
+
+/**
+ * The row shape both the tip probe and the appended correction are built
+ * into: a representative chunk projected into a result row - the one
+ * shape every pool filter answers, which never reads the projection's
+ * scores.
+ */
+function rowFromHead(
+ head: HydratedChunk,
+ score: number,
+ reasons: ReadonlyArray<string>,
+): BrainSearchResult {
+ return {
+ documentId: head.documentId,
+ chunkId: head.chunkId,
+ path: head.path,
+ title: head.title,
+ content: head.content,
+ startLine: head.startLine,
+ endLine: head.endLine,
+ score,
+ keywordScore: 0,
+ semanticScore: 0,
+ linkBoost: 0,
+ recencyBoost: 0,
+ searchType: "link",
+ reasons: Object.freeze([...reasons]),
+ };
+}
+
+/**
+ * Would a row for this correction page survive the caller's full filter
+ * set? {@link correctionReadableAtCaller} carries the readability, status,
+ * agent-scope, visibility-scope and reach rungs; the property, degree and
+ * composite-scope rungs are the caller's opt-in pool filters, and rather
+ * than re-spelling them as extra verdict rungs the tip candidate is
+ * probed through {@link applyPoolFilters} itself - the ONE pipeline the
+ * widened-pool re-filter runs, so the verdict and that re-filter cannot
+ * disagree. A tip the probe drops counts as unresolved, and its
+ * predecessor drops with it: a dropped correction can never leave its
+ * predecessor served bare.
+ */
+function correctionSurvivesPoolFilters(
+ head: HydratedChunk,
+ filters: PoolFilters,
+ ctx: FilterContext,
+): boolean {
+ return applyPoolFilters([rowFromHead(head, 0, [])], filters, ctx).visible.length === 1;
+}
+
+/**
+ * The coupling verdict for one retired row whose chain walk already
+ * resolved to `tipDocumentId` (null when the walk's tip is the row's own
+ * id, the unresolved corner): the tip must be a DISTINCT readable page
+ * that survives the caller's full filter set, fail-closed on every rung.
+ * The predecessor's own verdict and a chain-tip correction's verdict for
+ * itself are the same question over a different start row, so both ask
+ * it here - one spelling of the rule.
+ */
+function chainTipVerdict(
+ store: PostRankInput["store"],
+ vault: string,
+ frontmatterCache: FrontmatterCache,
+ filters: PoolFilters,
+ filterCtx: FilterContext,
+ predecessorPath: string,
+ tipDocumentId: number | null,
+): CouplingVerdict {
+ const representative =
+ tipDocumentId === null
+ ? undefined
+ : store.representativeChunks([tipDocumentId]).get(tipDocumentId);
+ const successorPath = representative?.path ?? null;
+ return couplingVerdict({
+ predecessorPath,
+ successorPath,
+ successorReadable:
+ successorPath !== null &&
+ representative !== undefined &&
+ correctionReadableAtCaller(successorPath, vault, frontmatterCache, store, filters) &&
+ correctionSurvivesPoolFilters(representative, filters, filterCtx),
+ });
+}
+
+/**
+ * The serve-with-correction coupling over the pool's retired-but-serveable
+ * rows (truth-correctable-time-aware, contract item 3, Task 18). A row
+ * whose page carries a `superseded_by` pointer but survived the status
+ * filter is served only beside its resolved chain-tip correction when the
+ * caller's FULL filter set would serve that correction - decided by
+ * {@link couplingVerdict} over the composed readability rungs plus the
+ * {@link correctionSurvivesPoolFilters} probe - and is dropped
+ * otherwise, so a withheld correction takes its predecessor with it. The
+ * tip arrives as a link-type row beside the row it corrects, carrying a
+ * share of its score so the pair survives the final slice together.
+ *
+ * A pool with no retired rows returns the input untouched (same array,
+ * same order): the neutral path is byte-identical by construction.
+ */
+function applyCorrectionCoupling(
+ pool: ReadonlyArray<BrainSearchResult>,
+ store: PostRankInput["store"],
+ vault: string,
+ frontmatterCache: FrontmatterCache,
+ filters: PoolFilters,
+): CouplingOutcome {
+ interface RetiredRow {
+ readonly result: BrainSearchResult;
+ readonly tipDocumentId: number | null;
+ }
+ const retired: RetiredRow[] = [];
+ for (const result of pool) {
+ const pointer = readCachedFrontmatter(frontmatterCache, vault, result.path)[SUPERSEDED_BY_KEY];
+ if (typeof pointer !== "string" || pointer.trim() === "") continue;
+ retired.push({ result, tipDocumentId: resolveChainTipDocumentId(store, result.documentId) });
+ }
+ if (retired.length === 0) return { pool, pulledIn: false };
+
+ const droppedChunkIds = new Set<number>();
+ const filterCtx: FilterContext = { vault, store, frontmatterCache };
+ interface PendingCorrection {
+ readonly documentId: number;
+ readonly predecessors: string[];
+ carriedScore: number;
+ }
+ const pending = new Map<string, PendingCorrection>();
+ for (const { result, tipDocumentId } of retired) {
+ // A blocked (schema-constrained) or stale `superseded_by` index edge
+ // leaves the walk no first hop, and the walk then answers the START
+ // document as its own tip. That is not a resolved chain - the page's
+ // frontmatter declares a successor that its own id cannot answer - so
+ // it is classified as unresolved and the row drops fail-closed: a
+ // retired row is served only beside a DISTINCT readable chain-tip
+ // correction, never bare.
+ const tipId = tipDocumentId !== result.documentId ? tipDocumentId : null;
+ const verdict = chainTipVerdict(
+ store,
+ vault,
+ frontmatterCache,
+ filters,
+ filterCtx,
+ result.path,
+ tipId,
+ );
+ // A chain-tip correction that is itself a retired row the pool never
+ // carried (its own pointer postdates the index, or its chain is
+ // otherwise unresolved) asks the same question for itself before it
+ // can be appended beside this row: appended bare, its own drop
+ // verdict would re-enter the pool exactly the way the branch below
+ // forbids. The drop counts as unresolved for the predecessor too,
+ // and the fail-closed branch takes the predecessor with it.
+ if (verdict.action === "serve_coupled") {
+ const tipPointer = readCachedFrontmatter(frontmatterCache, vault, verdict.correctionPath)[
+ SUPERSEDED_BY_KEY
+ ];
+ if (typeof tipPointer === "string" && tipPointer.trim() !== "") {
+ const ownTipId = resolveChainTipDocumentId(store, tipId!);
+ const ownVerdict = chainTipVerdict(
+ store,
+ vault,
+ frontmatterCache,
+ filters,
+ filterCtx,
+ verdict.correctionPath,
+ ownTipId !== tipId ? ownTipId : null,
+ );
+ if (ownVerdict.action === "drop") {
+ droppedChunkIds.add(result.chunkId);
+ continue;
+ }
+ }
+ }
+ if (verdict.action === "drop") {
+ droppedChunkIds.add(result.chunkId);
+ continue;
+ }
+ const carried = clamp01(result.score * SUCCESSOR_CARRY);
+ const existing = pending.get(verdict.correctionPath);
+ if (existing !== undefined) {
+ existing.carriedScore = Math.max(existing.carriedScore, carried);
+ if (!existing.predecessors.includes(result.path)) existing.predecessors.push(result.path);
+ continue;
+ }
+ pending.set(verdict.correctionPath, {
+ documentId: tipId!,
+ predecessors: [result.path],
+ carriedScore: carried,
+ });
+ }
+
+ const kept = pool.filter((r) => !droppedChunkIds.has(r.chunkId));
+ const representatives = store.representativeChunks(
+ Array.from(new Set(Array.from(pending.values(), (c) => c.documentId))),
+ );
+ const appended: BrainSearchResult[] = [];
+ for (const [correctionPath, entry] of pending) {
+ // Already served by its own rank: the correction is beside the row
+ // that needs it, and its own reasons already explain the match.
+ if (kept.some((r) => r.path === correctionPath)) continue;
+ const head = representatives.get(entry.documentId);
+ if (head === undefined) continue;
+ appended.push(
+ Object.freeze(
+ rowFromHead(
+ head,
+ entry.carriedScore,
+ entry.predecessors.map((p) => `${CORRECTION_FOR_REASON_PREFIX} ${p}`),
+ ),
+ ),
+ );
+ }
+ if (appended.length === 0) return { pool: kept, pulledIn: false };
+ // Same tie-break family as the ranker and the polarity phase, so a
+ // pulled correction lands beside the row it corrects deterministically.
+ const out = [...kept, ...appended];
+ out.sort((a, b) => {
+ if (b.score !== a.score) return b.score - a.score;
+ if (b.keywordScore !== a.keywordScore) return b.keywordScore - a.keywordScore;
+ return a.chunkId - b.chunkId;
+ });
+ return { pool: out, pulledIn: true };
+}
+
export async function applyPostRankPhases(input: PostRankInput): Promise<PostRankOutcome> {
const { store, config, opts, frontmatterCache } = input;
const warnings: string[] = [];
@@ -139,33 +454,53 @@ export async function applyPostRankPhases(input: PostRankInput): Promise<PostRan
const polarized = config.recall.relationPolarityEnabled
? applyRelationPolarityPhase(store, excluded, opts.includeSuperseded === true)
: excluded;
- // Root A again, and it has to be: the polarity phase resolves typed
- // `superseded_by` edges to documents that were NEVER in the filtered
- // pool, fetches their representative chunks off the store and appends
- // them with full path, title and content. Nothing between that append
- // and the outcome re-asks any pool filter, so a public page naming a
- // reserved successor was a route to that successor's body at remote
- // reach - the pool filter never saw it, because it was not in the pool
- // to see. Re-asking over the whole pool rather than the pulled-in rows
- // alone is deliberate: the verdict is idempotent and every already-
- // filtered row answers off the shared frontmatter cache, so one
- // spelling of the rule costs less than a second one that tracked which
- // rows were new.
- //
- // RECORDED, not fixed here: the caller's `visibility` scope and its
- // `agentScope` have the same gap at this seam, and they predate this
- // boundary - a pulled-in successor bypasses `applyVisibilityScope` and
- // `applyAgentScope` exactly as it bypassed the reach rule. Closing
- // those means re-resolving the caller's whole filter set after a
- // post-rank phase, which is a change to the ownership boundary rather
- // than to this one.
- const reachable = applyReachFilter(
+ // Serve-with-correction coupling (truth-correctable-time-aware,
+ // contract item 3): a retired-but-serveable row - a page whose
+ // frontmatter declares a successor but which survived the status
+ // filter - is served only beside its resolved, readable chain-tip
+ // correction and is dropped otherwise, fail-closed. The predicate
+ // replaces the polarity branch's best-effort treatment of retired
+ // rows, where an unresolved successor used to leave the predecessor
+ // served bare.
+ const poolFilters = resolvePoolFilters(opts);
+ const coupled = applyCorrectionCoupling(
polarized,
- resolvedTransportReach(opts.transportReach),
+ store,
config.vault,
frontmatterCache,
- store,
+ poolFilters,
);
+ // Root A again, and it has to be: the polarity phase resolves typed
+ // `superseded_by` edges to documents that were NEVER in the filtered
+ // pool, fetches their representative chunks off the store and appends
+ // them with full path, title and content; the coupling stage appends
+ // chain-tip corrections the same way. Nothing between that append and
+ // the outcome used to re-ask any pool filter, so a public page naming a
+ // reserved successor was a route to that successor's body at remote
+ // reach, and the caller's `visibility` scope and `agentScope` had the
+ // same gap - the recorded defect this stage now closes. Re-asking over
+ // the whole pool rather than the pulled-in rows alone is deliberate:
+ // every pass is idempotent and every already-filtered row answers off
+ // the shared frontmatter cache, so one spelling of the rule costs less
+ // than a second one that tracked which rows were new. With no pull-in
+ // the single reach re-filter below is exactly what ran before, and a
+ // pool with neither pull-in nor retired row is byte-identical.
+ const polarityPulled = polarized.length !== excluded.length;
+ // The caller's post-rank filter set re-asked over a pool a post-rank
+ // phase widened goes through applyPoolFilters - the ONE pipeline the
+ // visibility census pins as applyVisibilityScope's single call site.
+ // Every pass is idempotent over the rows that already answered it, so
+ // re-running the whole pool costs shared-cache reads and keeps one
+ // spelling of each rule; tracking which rows were new would be a
+ // second copy of the same bookkeeping.
+ const reachable =
+ polarityPulled || coupled.pulledIn
+ ? applyPoolFilters(coupled.pool, poolFilters, {
+ vault: config.vault,
+ store,
+ frontmatterCache,
+ }).visible
+ : applyReachFilter(coupled.pool, poolFilters.reach, config.vault, frontmatterCache, store);
// Self-tuning reinforce (Search & Recall Quality Suite): opt-in. When
// the caller passes a reinforce set, the persisted ledger lifts
// proven-useful memories by a bounded boost BEFORE the top_k cut, so
diff --git a/src/core/search/pipeline/relational-arm.ts b/src/core/search/pipeline/relational-arm.ts
index a71f79f4..5938c8a0 100644
--- a/src/core/search/pipeline/relational-arm.ts
+++ b/src/core/search/pipeline/relational-arm.ts
@@ -3,13 +3,44 @@
* query's wikilink seeds, fans out over typed edges, and contributes one
* representative chunk per reached node - with the link types and hop
* distance it was reached by, for attribution.
+ *
+ * Deepened traversal (truth-correctable-time-aware): the walk runs under
+ * the resolved traversal width budgets, abandons its frontier when the
+ * caller's deadline predicate reports the composite recall clock fired,
+ * and - when the entity-bridge flag allows and the store provides the
+ * reader - walks `chunk_entities` entity bridges beside the typed edges.
+ * The per-call options default to the same environment-over-machine-config
+ * resolution every search knob follows, resolved against the config file
+ * the caller's own resolution read (`options.configPath`, threaded from
+ * the resolved search config): the arm answers the caller's config map,
+ * never a fresh read of the default path the caller may not have used.
*/
import { DEFAULT_RELATION_TYPES, normalizeRelation } from "../../graph/relation-vocab.ts";
+import { normalizeAgentScope } from "../../graph/agent-scope.ts";
import { loadSchemaPack } from "../../brain/schema-pack.ts";
import { rrfKey } from "../../scope-key.ts";
-import { relationalFanout } from "../relational-fanout.ts";
+import { resolvedTransportReach, type TransportReach } from "../../graph/transport-reach.ts";
+import { EXACT_WIKILINK_RE } from "../../brain/wikilink.ts";
+import { SUPERSEDED_BY_KEY } from "../../brain/lifecycle/tombstone.ts";
+import { discoverConfig } from "../../config.ts";
+import { envOrConfig, parseBool } from "../../validate.ts";
+import {
+ relationalFanout,
+ resolveTraversalBudgets,
+ type RelationalFanoutStore,
+ type RelationalPathStep,
+ type TraversalBudgets,
+} from "../relational-fanout.ts";
import { parseRelationalQuery } from "../relational-query.ts";
+import {
+ isPathOwnerVisible,
+ isPathReadableAtReach,
+ readCachedFrontmatterEntry,
+ type FrontmatterCache,
+} from "../result-filters.ts";
+import { parseValidityWindow } from "../validity.ts";
+import { SearchError } from "../search-error.ts";
import type { BrainSearchResult } from "../search-result.ts";
import type { Store } from "../store.ts";
import type { ResolvedSearchConfig, SearchOptions } from "../types.ts";
@@ -17,9 +48,96 @@ import type { ResolvedSearchConfig, SearchOptions } from "../types.ts";
/** Bounded typed-edge fan-out depth for the relational arm (t_09b7ccea). */
const RELATIONAL_MAX_DEPTH = 2;
+/** Environment override for walking entity bridges. */
+export const ENTITY_BRIDGES_ENV = "OPEN_SECOND_BRAIN_SEARCH_ENTITY_BRIDGES";
+/** Machine-config key for walking entity bridges. */
+export const ENTITY_BRIDGES_CONFIG = "search_entity_bridges_enabled";
+
+/**
+ * Whether the arm walks entity bridges: on by default (design decision 11),
+ * overridable per environment or machine config. A present but invalid
+ * value is a misconfiguration and is refused with a `SearchError` naming
+ * the key in force - never silently defaulted.
+ */
+export function resolveEntityBridgesEnabled(input: {
+ readonly env?: NodeJS.ProcessEnv;
+ readonly config?: Readonly<Record<string, string>>;
+}): boolean {
+ const env = input.env ?? {};
+ const config = input.config ?? {};
+ const raw = envOrConfig(env, config, ENTITY_BRIDGES_ENV, ENTITY_BRIDGES_CONFIG);
+ if (raw === null) return true;
+ // The key actually in force, by the same env-over-config precedence the
+ // raw value resolved with - the refusal names the key the operator
+ // wrote, never the one that lost the precedence race.
+ const inForce = env[ENTITY_BRIDGES_ENV] ? ENTITY_BRIDGES_ENV : ENTITY_BRIDGES_CONFIG;
+ try {
+ return parseBool(raw, true, inForce);
+ } catch (e) {
+ throw new SearchError("INVALID_INPUT", `${inForce}: ${(e as Error).message}`);
+ }
+}
+
+/** Per-call runtime overrides for the arm; every member defaults to resolved config. */
+export interface RelationalArmOptions {
+ /** Traversal width budgets. Default: {@link resolveTraversalBudgets} over env + machine config. */
+ readonly budgets?: TraversalBudgets;
+ /**
+ * Fired-clock predicate bounding the walk (the composite recall
+ * deadline). Default: none - the width caps still bound the walk.
+ */
+ readonly isExpired?: () => boolean;
+ /**
+ * Walk entity bridges. Default: {@link resolveEntityBridgesEnabled} over
+ * env + machine config, AND the store must provide the bridge reader.
+ */
+ readonly entityBridges?: boolean;
+ /**
+ * The caller's transport reach, gating every provenance path node
+ * (per-node gating, the `brain_derive_fact` premise-gate precedent). A
+ * node whose page is unreadable at this reach is omitted from the path,
+ * never named and never counted. Default: the same resolution the
+ * row-level filters apply (`resolvedTransportReach`) - an absent reach
+ * answers remote, the narrowest, so provenance never names a page the
+ * row gate withholds.
+ */
+ readonly reach?: TransportReach;
+ /**
+ * The caller's agent-ownership scope, gating provenance path nodes the
+ * same way the row-level filters gate content rows: a node whose page
+ * another agent owns is omitted from the path, never named. Null /
+ * absent means no scope requested - no ownership filtering, the opt-in
+ * default every unscoped search ran with before.
+ */
+ readonly agentScope?: string | null;
+ /**
+ * The config file the caller's own config resolution read, threaded
+ * from the resolved search config. Default: null - the knobs resolve
+ * env-only, exactly as a caller that consulted no config file did.
+ */
+ readonly configPath?: string | null;
+}
+
export interface RelationalReach {
readonly via: ReadonlyArray<string>;
readonly hops: number;
+ /**
+ * The ordered steps that reached this node, gated per node at the
+ * caller's reach and owner scope: a step whose page is unreadable there
+ * or owned by another agent is omitted - never named, and never
+ * counted, so the provenance a row shows reads the same whether the
+ * walk crossed unreadable documents or not (the views'
+ * identical-to-absent convention: a count would tell the caller that a
+ * node it may not see exists).
+ */
+ readonly path: ReadonlyArray<RelationalPathStep>;
+ /**
+ * Set when a readable path node is a non-tip superseded predecessor with
+ * a CLOSED validity window, read from frontmatter only (`superseded_by`
+ * plus `valid_until` already past) - never from the ledger. The bare tip
+ * name the frontmatter pointer declares.
+ */
+ readonly supersededBy?: string;
}
export interface RelationalArmOutcome {
@@ -40,23 +158,79 @@ export function noRelationalArm(): RelationalArmOutcome {
return { rankedChunkIds: [], reachByChunk: new Map() };
}
+/**
+ * The machine config map the arm's own knobs resolve against: the file
+ * at the caller's resolved config path, or no file at all when the
+ * caller resolved env-only - the same map the search call's own config
+ * resolution consulted, never a fresh read of the default path the
+ * caller may not have used. A present-but-unreadable caller path fails
+ * the same way here as it did there - deliberately not guarded into a
+ * silent default.
+ */
+function machineConfigData(configPath: string | null | undefined): Record<string, string> {
+ return configPath ? discoverConfig(configPath).data : {};
+}
+
+/**
+ * The fanout view of the store. The walk merges bridges whenever the store
+ * view carries the reader, so this wrapper is the flag's enforcement point:
+ * bridges on AND the store carrying the reader yields a view that exposes
+ * it; anything else yields a view with typed edges only, so a flag-off run
+ * is byte-identical to a store with no reader at all.
+ */
+function fanoutStoreFor(store: Store, bridges: boolean): RelationalFanoutStore {
+ const reader = (store as Partial<RelationalFanoutStore>).entityBridgesForDocuments;
+ if (typeof reader !== "function") return store;
+ if (!bridges) {
+ return { typedRelationEdgesForDocuments: (ids) => store.typedRelationEdgesForDocuments(ids) };
+ }
+ return {
+ typedRelationEdgesForDocuments: (ids) => store.typedRelationEdgesForDocuments(ids),
+ entityBridgesForDocuments: (ids) => reader.call(store, ids),
+ };
+}
+
/**
* A bounded depth-2 typed-edge fan-out from the resolved seeds. A
* non-relational query (no wikilink seed plus schema-vocabulary edge-type
- * token) contributes nothing. Source identity from the shared key module
- * dedups the lane (federation hardening).
+ * token) contributes nothing - and the knob resolution runs only after
+ * that early return, so a non-relational query pays no config-file read
+ * and a malformed knob value fails no search the knobs cannot affect.
+ * Source identity from the shared key module dedups the lane (federation
+ * hardening).
*/
-export function runRelationalArm(store: Store, vault: string, query: string): RelationalArmOutcome {
+export function runRelationalArm(
+ store: Store,
+ vault: string,
+ query: string,
+ opts: RelationalArmOptions = {},
+): RelationalArmOutcome {
const outcome = noRelationalArm();
const relQuery = parseRelationalQuery(query, relationalEdgeVocabulary(vault));
if (relQuery === null) return outcome;
const seedDocIds = resolveSeedDocumentIds(store, relQuery.seeds);
if (seedDocIds.length === 0) return outcome;
- const nodes = relationalFanout(store, seedDocIds, {
+ const config = machineConfigData(opts.configPath);
+ const budgets = opts.budgets ?? resolveTraversalBudgets({ env: process.env, config });
+ const bridges = opts.entityBridges ?? resolveEntityBridgesEnabled({ env: process.env, config });
+ const nodes = relationalFanout(fanoutStoreFor(store, bridges), seedDocIds, {
maxDepth: RELATIONAL_MAX_DEPTH,
edgeTypes: relQuery.edgeTypes,
+ ...budgets,
+ ...(opts.isExpired !== undefined ? { isExpired: opts.isExpired } : {}),
});
const reps = store.representativeChunks(nodes.map((n) => n.documentId));
+ // Per-node gating for the ordered path provenance: one titles read and
+ // one frontmatter cache per arm run, shared by every node's gate. The
+ // caller's owner scope rides beside the transport reach, so a
+ // reach-readable node another agent owns is withheld the same way. The
+ // absent reach resolves exactly as the row-level filters resolve it,
+ // so a withheld page is never named in provenance the rows do not show.
+ const reach = resolvedTransportReach(opts.reach);
+ const agentScope = normalizeAgentScope(opts.agentScope ?? undefined);
+ const frontmatterCache: FrontmatterCache = new Map();
+ const titles = store.documentTitles();
+ const nowMs = Date.now();
const seenKeys = new Set<string>();
for (const node of nodes) {
const rep = reps.get(node.documentId);
@@ -64,8 +238,13 @@ export function runRelationalArm(store: Store, vault: string, query: string): Re
const key = rrfKey({ origin: null, path: rep.path, chunkId: rep.chunkId });
if (seenKeys.has(key)) continue;
seenKeys.add(key);
+ const gated = gatePath(vault, node.path, titles, reach, agentScope, frontmatterCache, nowMs);
outcome.rankedChunkIds.push(rep.chunkId);
- outcome.reachByChunk.set(rep.chunkId, { via: node.viaLinkTypes, hops: node.hops });
+ outcome.reachByChunk.set(rep.chunkId, {
+ via: node.viaLinkTypes,
+ hops: node.hops,
+ ...gated,
+ });
}
return outcome;
}
@@ -116,10 +295,89 @@ function resolveSeedDocumentIds(store: Store, seeds: ReadonlyArray<string>): num
return out;
}
+/**
+ * The bare tip a frontmatter `superseded_by` pointer names, when the page
+ * is a non-tip superseded predecessor whose validity window has CLOSED.
+ * Closedness follows the shared frontmatter grammar's INCLUSIVE end
+ * (`parseValidityWindow` in `src/core/search/validity.ts` snaps a bare
+ * `valid_until` date to its whole final day, so the boundary instant
+ * itself is still inside the window): closed once now is strictly past
+ * the end. Frontmatter only - never the ledger. A missing pointer, an
+ * unparseable window, an open side, or a window still open answers null.
+ */
+function closedSupersessionTip(
+ vault: string,
+ path: string,
+ cache: FrontmatterCache,
+ nowMs: number,
+): string | null {
+ const entry = readCachedFrontmatterEntry(cache, vault, path);
+ if (entry.unreadable) return null;
+ const raw = entry.meta[SUPERSEDED_BY_KEY];
+ if (typeof raw !== "string" || raw.trim() === "") return null;
+ const window = parseValidityWindow(entry.meta);
+ if (window === null || window.invalid || window.validUntilMs === null) return null;
+ if (window.validUntilMs >= nowMs) return null;
+ const wikilink = EXACT_WIKILINK_RE.exec(raw.trim());
+ return (wikilink !== null ? wikilink[1]! : raw).trim();
+}
+
+/**
+ * Gate one node's walked path at the caller's reach and owner scope:
+ * unreadable steps and steps another agent owns (under a requested scope)
+ * are omitted alike, so a hidden node's document id is never named, never
+ * counted, and never contributes the supersession annotation; the first
+ * readable, in-scope step carrying a closed supersession names the
+ * reach's `supersededBy` tip. Nothing reports how many steps were
+ * dropped - the provenance answer must read the same whether the walk
+ * crossed unreadable documents or not (the views'
+ * identical-to-absent convention).
+ */
+function gatePath(
+ vault: string,
+ steps: ReadonlyArray<RelationalPathStep>,
+ titles: ReadonlyMap<number, { readonly path: string }>,
+ reach: TransportReach,
+ agentScope: string | null,
+ cache: FrontmatterCache,
+ nowMs: number,
+): {
+ readonly path: ReadonlyArray<RelationalPathStep>;
+ readonly supersededBy?: string;
+} {
+ const gated: RelationalPathStep[] = [];
+ let supersededBy: string | undefined;
+ for (const step of steps) {
+ const meta = titles.get(step.documentId);
+ const unreadable =
+ meta === undefined ||
+ !isPathReadableAtReach(vault, meta.path, reach, cache) ||
+ // The same owner-scope verdict the row-level filters apply to
+ // content rows: an owner-private page another agent owns is as
+ // withheld from provenance as an unreadable one. No requested
+ // scope means no ownership filtering - the opt-in default.
+ (agentScope !== null && !isPathOwnerVisible(vault, meta.path, agentScope, cache));
+ if (unreadable) continue;
+ gated.push(step);
+ if (supersededBy === undefined) {
+ const tip = closedSupersessionTip(vault, meta.path, cache, nowMs);
+ if (tip !== null) supersededBy = tip;
+ }
+ }
+ return {
+ path: Object.freeze(gated),
+ ...(supersededBy !== undefined ? { supersededBy } : {}),
+ };
+}
+
/**
* Relational rerank pin (t_d9f863e9): the protect rule applied at the
* cross-encoder hand-off. Rerank may PROMOTE relational-origin candidates,
- * never SINK them below their pre-rerank heuristic order.
+ * never SINK them below their pre-rerank heuristic order - tightened
+ * (truth-correctable-time-aware) by the direct-hit ceiling: a
+ * relational-origin row may also never cross ABOVE an organic direct hit
+ * (a row the keyword lane scored), because the traversal widens the pool
+ * and never outranks what the lanes matched.
*
* This is deliberately NOT a second floor beside the cross-encoder's
* `minScore` (the premise warned against a parallel mechanism): `minScore`
@@ -127,18 +385,24 @@ function resolveSeedDocumentIds(store: Store, seeds: ReadonlyArray<string>): num
* rerank stage has spoken, which makes the pin strictly weaker than
* rerank-off - a relational candidate may rise wherever the rerank genuinely
* scores it above peers, and never falls below the line the heuristic ranker
- * gave it.
+ * gave it unless the ceiling demands it (the ceiling wins: admission below
+ * the organic tail is the structural guarantee the pin protects).
*
* Mechanism: every candidate in `preRerank` carrying `relationalOrigin`
* (stamped by the ranker from the arm's contribution set) holds the
- * position it occupied there. Candidates are processed in PRE-rerank order
- * - the floors are ordered, so honouring an earlier floor can never push a
- * later candidate past its own, and each pass is a removal plus an
- * insertion at `min(currentIndex, floor)`. A candidate already at or above
- * its floor (it rose, or the order did not change) is left untouched and
- * gains no receipt; a candidate the rule moved gains
- * `relational_pin: floored at pre-rerank position N` so the explain trail
- * shows which rows the pin held. Deterministic given the two orders.
+ * position it occupied there, and is processed in PRE-rerank order - the
+ * floors are ordered, so honouring an earlier floor can never push a later
+ * candidate past its own. Each pass removes the candidate and inserts it
+ * at its target: the pre-rerank index when it sank, else just below the
+ * deepest organic direct hit when it crossed the ceiling line (later
+ * ceiling moves land after the earlier ones and after every already-placed
+ * peer, so the relational block's pre-rerank order survives). A candidate
+ * already at or above its floor and below the ceiling line is left
+ * untouched and gains no receipt; a moved candidate gains
+ * `relational_pin: floored at pre-rerank position N` (sunk) or
+ * `relational_pin: held below the organic direct hits` (ceiling) so the
+ * explain trail shows which rows the pin held. Deterministic given the two
+ * orders.
*
* The pin is active only where the arm contributed something, so pools
* without relational-origin rows return the rerank order unchanged.
@@ -157,26 +421,68 @@ export function applyRelationalRerankPin(
if (floors.size === 0) return postRerank;
// Walk the protected candidates in PRE-rerank order (floors are strictly
- // increasing along that walk), lifting each sunk one to its floor.
+ // increasing along that walk): lift each sunk one to its floor, and hold
+ // each one below the deepest organic direct hit.
const working: BrainSearchResult[] = [...postRerank];
const floored = new Set<number>();
+ const ceilinged = new Set<number>();
+ // Relational rows already placed, pre-rerank order - a ceiling move must
+ // never land above one of them.
+ const placedPeers: number[] = [];
for (const [chunkId, floor] of floors) {
const at = working.findIndex((r) => r.chunkId === chunkId);
- if (at === -1 || at <= floor) continue;
- const [row] = working.splice(at, 1);
- working.splice(floor, 0, row!);
- floored.add(chunkId);
+ if (at === -1) {
+ placedPeers.push(chunkId);
+ continue;
+ }
+ let target = at;
+ if (target > floor) target = floor;
+ // The ceiling line: one past the deepest organic direct hit (a row the
+ // keyword lane scored that the arm did not originate). A pool with no
+ // direct hits has no line and the ceiling never fires.
+ let cut = 0;
+ for (let i = 0; i < working.length; i++) {
+ const r = working[i]!;
+ if (r.keywordScore > 0 && r.relationalOrigin !== true) cut = i + 1;
+ }
+ // Which rule moved the row is decided by which fired, never by where
+ // the row landed - a floor lift can legitimately land on the cut index.
+ let movedByCeiling = false;
+ if (target < cut) {
+ movedByCeiling = true;
+ target = cut;
+ for (const peerId of placedPeers) {
+ const pi = working.findIndex((r) => r.chunkId === peerId);
+ if (pi !== -1 && pi + 1 > target) target = pi + 1;
+ }
+ }
+ if (target !== at) {
+ const [row] = working.splice(at, 1);
+ working.splice(target, 0, row!);
+ (movedByCeiling ? ceilinged : floored).add(chunkId);
+ }
+ placedPeers.push(chunkId);
}
- if (floored.size === 0) return postRerank;
- return working.map((r) =>
- floored.has(r.chunkId)
- ? Object.freeze({
- ...r,
- reasons: Object.freeze([
- ...r.reasons,
- `relational_pin: floored at pre-rerank position ${floors.get(r.chunkId)}`,
- ]),
- })
- : r,
- );
+ if (floored.size === 0 && ceilinged.size === 0) return postRerank;
+ return working.map((r) => {
+ if (floored.has(r.chunkId)) {
+ return Object.freeze({
+ ...r,
+ reasons: Object.freeze([
+ ...r.reasons,
+ `relational_pin: floored at pre-rerank position ${floors.get(r.chunkId)}`,
+ ]),
+ });
+ }
+ if (ceilinged.has(r.chunkId)) {
+ return Object.freeze({
+ ...r,
+ reasons: Object.freeze([
+ ...r.reasons,
+ "relational_pin: held below the organic direct hits",
+ ]),
+ });
+ }
+ return r;
+ });
}
diff --git a/src/core/search/ranker.ts b/src/core/search/ranker.ts
index 256790ce..c8fdbd04 100644
--- a/src/core/search/ranker.ts
+++ b/src/core/search/ranker.ts
@@ -541,12 +541,17 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSea
// semantic) so a genuinely related node can enter the fused ranking. Only
// in rrf mode, where the lane above already contributes their score.
// searchType "link" - a typed-graph traversal hit. Empty lane = no
- // additions, so ranking stays byte-identical.
+ // additions, so ranking stays byte-identical. The admitted ids are
+ // tracked separately: searchType "link" has other producers (polarity
+ // pull-in, graph traversal), so structural admission keys on THIS set,
+ // never on the searchType.
+ const relationalOnlyIds = new Set<number>();
if (rrfByChunk !== null && inputs.relationalRankedChunkIds) {
for (const chunkId of inputs.relationalRankedChunkIds) {
if (candidates.has(chunkId)) continue;
const hyd = inputs.hydrated.get(chunkId);
if (hyd === undefined) continue;
+ relationalOnlyIds.add(chunkId);
candidates.set(chunkId, {
chunkId,
documentId: hyd.documentId,
@@ -844,6 +849,16 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSea
// Equal contributions (including both zero) and an absent window fall
// straight through to the historical ladder, byte-identically.
ranked.sort((a, b) => {
+ // Structural direct-hit precedence (truth-correctable-time-aware): a
+ // relational-only admission is admitted BELOW the organic tail in the
+ // pre-rerank fused order. The arm's lane weight is neutral, so on raw
+ // RRF a relational-only rank 1 could float above a deep keyword direct
+ // hit; this rung makes that structurally impossible - the traversal
+ // widens the pool, it never outranks what the lanes matched. With the
+ // arm off the set is empty and the rung never fires, byte-identically.
+ const aRelationalOnly = relationalOnlyIds.has(a.chunkId);
+ const bRelationalOnly = relationalOnlyIds.has(b.chunkId);
+ if (aRelationalOnly !== bRelationalOnly) return aRelationalOnly ? 1 : -1;
if (b.score !== a.score) return b.score - a.score;
if (temporalIntent !== null) {
const aTemporal = a.breakdown?.temporal ?? 0;
diff --git a/src/core/search/relational-fanout.ts b/src/core/search/relational-fanout.ts
index 5591e500..14a27c0a 100644
--- a/src/core/search/relational-fanout.ts
+++ b/src/core/search/relational-fanout.ts
@@ -10,8 +10,26 @@
* Deterministic and language-agnostic: it walks only typed edges already in
* the index (edge types validated against the schema vocabulary upstream),
* never inspecting note prose.
+ *
+ * Deepened traversal (truth-correctable-time-aware): the walk runs under
+ * width budgets - a seed cap, a per-node expansion cap, a total-node cap -
+ * skips expanding hub nodes (whose walked-edge degree exceeds a threshold),
+ * and abandons the frontier deterministically once a caller-supplied
+ * deadline predicate reports the clock fired, keeping every node already
+ * reached. All four budgets ship as named constants and are overridable
+ * through the `OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_*` environment variables
+ * (or their `search_traversal_*` config keys) via {@link resolveTraversalBudgets}.
+ *
+ * Seeds are special only as walk entry points (capped, deduped, never
+ * pre-seeded into the reached set). A typed edge pointing AT a seed id is
+ * walked like any other edge and reaches that id like any target - the cap
+ * cases in the fanout test pin this, so a self-loop or a cycle back to a
+ * seed surfaces the seed exactly once, at the hop distance that reached it.
*/
+import { SearchError } from "./search-error.ts";
+import { parseInteger } from "../validate.ts";
+
/** The subset of Store this module needs; keeps it unit-testable. */
export interface RelationalFanoutStore {
typedRelationEdgesForDocuments(documentIds: ReadonlyArray<number>): Array<{
@@ -20,6 +38,40 @@ export interface RelationalFanoutStore {
readonly target: string;
readonly targetDocumentId: number | null;
}>;
+ /**
+ * Optional entity-bridge reader (truth-correctable-time-aware): the
+ * deduplicated `chunk_entities` co-occurrence pairs of the given
+ * documents, in deterministic target-id order per source. Present =
+ * every pair is walked as one directed edge labeled
+ * {@link ENTITY_BRIDGE_RELATION}, appended after the same source's
+ * typed edges and counted by every width cap. Absent (or answering
+ * empty) = the walk is byte-identical to the typed-only walk.
+ */
+ entityBridgesForDocuments?(
+ documentIds: ReadonlyArray<number>,
+ ): ReadonlyArray<RelationalBridgeEdge>;
+}
+
+/**
+ * One entity-bridge edge: two documents that mention the same normalized
+ * entity. Directed source -> target; the reader dedups (one edge per pair
+ * no matter how many entities they share).
+ */
+export interface RelationalBridgeEdge {
+ readonly sourceDocumentId: number;
+ readonly targetDocumentId: number;
+}
+
+/**
+ * One ordered step of the path that reached a node: the document the step
+ * arrived at, and the relation that carried the walk into it (typed
+ * relation name, or {@link ENTITY_BRIDGE_RELATION} for an entity bridge).
+ * The originating seed is not a step - the path starts at the seed's first
+ * reached neighbour.
+ */
+export interface RelationalPathStep {
+ readonly documentId: number;
+ readonly relation: string;
}
export interface RelationalNode {
@@ -30,6 +82,12 @@ export interface RelationalNode {
readonly edgeRichness: number;
/** Distinct link types this node was reached via, sorted. */
readonly viaLinkTypes: ReadonlyArray<string>;
+ /**
+ * The ordered steps of the walk that reached this node FIRST (minimum
+ * hops; later arrivals never rewrite it). The caller reach-gates these
+ * steps per node before provenance is rendered.
+ */
+ readonly path: ReadonlyArray<RelationalPathStep>;
/**
* Deterministic rank score `1/hops + min(MAX_RICHNESS_BONUS, RICHNESS_BONUS
* * edgeRichness)`. Ranges in `(0, 1 + MAX_RICHNESS_BONUS]` (currently
@@ -42,6 +100,138 @@ export interface RelationalNode {
readonly score: number;
}
+/** Maximum hop depth. Clamped to >= 1. */
+const DEFAULT_MAX_DEPTH = 2;
+/** Per-edge richness bonus, capped so a nearer node always outranks a farther one. */
+const RICHNESS_BONUS = 0.05;
+const MAX_RICHNESS_BONUS = 0.49;
+
+// ─── traversal budgets (truth-correctable-time-aware) ───────────────────────
+
+/** How many query seeds the walk admits, in the order the caller supplied. */
+export const TRAVERSAL_MAX_SEEDS = 8;
+/** How many walked edges of one node the walk may follow, in edge order. */
+export const TRAVERSAL_MAX_EXPANSION_PER_NODE = 4;
+/** How many nodes the walk may reach in total, across every depth. */
+export const TRAVERSAL_MAX_TOTAL_NODES = 16;
+/**
+ * A reached node whose walked-edge degree (resolvable walked edges, typed
+ * edges plus entity bridges) EXCEEDS this threshold is reached but never
+ * expanded: its own fan-out is withheld from the frontier.
+ */
+export const TRAVERSAL_HUB_DEGREE_THRESHOLD = 12;
+
+/**
+ * The relation label every entity-bridge edge walks under (design decision
+ * 11: bridges are machine-derived, never part of the query edge-type
+ * vocabulary, so the edge-type restriction does not filter them and
+ * attribution renders them as `via entity`).
+ */
+export const ENTITY_BRIDGE_RELATION = "entity";
+
+/** Environment override for {@link TRAVERSAL_MAX_SEEDS}. */
+export const TRAVERSAL_MAX_SEEDS_ENV = "OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_MAX_SEEDS";
+/** Environment override for {@link TRAVERSAL_MAX_EXPANSION_PER_NODE}. */
+export const TRAVERSAL_MAX_EXPANSION_PER_NODE_ENV =
+ "OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_MAX_EXPANSION_PER_NODE";
+/** Environment override for {@link TRAVERSAL_MAX_TOTAL_NODES}. */
+export const TRAVERSAL_MAX_TOTAL_NODES_ENV = "OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_MAX_TOTAL_NODES";
+/** Environment override for {@link TRAVERSAL_HUB_DEGREE_THRESHOLD}. */
+export const TRAVERSAL_HUB_DEGREE_THRESHOLD_ENV =
+ "OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_HUB_DEGREE_THRESHOLD";
+
+/** Machine-config key for {@link TRAVERSAL_MAX_SEEDS}. */
+export const TRAVERSAL_MAX_SEEDS_CONFIG = "search_traversal_max_seeds";
+/** Machine-config key for {@link TRAVERSAL_MAX_EXPANSION_PER_NODE}. */
+export const TRAVERSAL_MAX_EXPANSION_PER_NODE_CONFIG = "search_traversal_max_expansion_per_node";
+/** Machine-config key for {@link TRAVERSAL_MAX_TOTAL_NODES}. */
+export const TRAVERSAL_MAX_TOTAL_NODES_CONFIG = "search_traversal_max_total_nodes";
+/** Machine-config key for {@link TRAVERSAL_HUB_DEGREE_THRESHOLD}. */
+export const TRAVERSAL_HUB_DEGREE_THRESHOLD_CONFIG = "search_traversal_hub_degree_threshold";
+
+/** The four traversal width budgets, resolved from env/config over defaults. */
+export interface TraversalBudgets {
+ readonly maxSeeds: number;
+ readonly maxExpansionPerNode: number;
+ readonly maxTotalNodes: number;
+ readonly hubDegreeThreshold: number;
+}
+
+interface RawBudgetSetting {
+ readonly raw: string;
+ readonly field: string;
+}
+
+/**
+ * One budget's raw value with the name of the source actually in force,
+ * by the same env-over-config precedence `envOrConfig` applies (a present
+ * but empty value counts as unset). Named because a refusal must name the
+ * key the operator wrote, not both keys.
+ */
+function rawBudget(
+ env: NodeJS.ProcessEnv,
+ config: Readonly<Record<string, string>> | undefined,
+ envKey: string,
+ configKey: string,
+): RawBudgetSetting | null {
+ const fromEnv = env[envKey];
+ if (fromEnv !== undefined && fromEnv !== "") return { raw: fromEnv, field: envKey };
+ const fromConfig = config?.[configKey];
+ if (fromConfig !== undefined && fromConfig !== "") return { raw: fromConfig, field: configKey };
+ return null;
+}
+
+/**
+ * Resolve the four traversal budgets from the environment (preferred) or
+ * the machine config map, falling back to the shipped constants. A value
+ * that is not an integer >= 1 is a misconfiguration and is refused with a
+ * `SearchError` naming the key in force - never silently defaulted. The
+ * environment is optional so a caller holding only a config map resolves
+ * against the constants-and-config pair.
+ */
+export function resolveTraversalBudgets(input: {
+ readonly env?: NodeJS.ProcessEnv;
+ readonly config?: Readonly<Record<string, string>>;
+}): TraversalBudgets {
+ const env = input.env ?? {};
+ const { config } = input;
+ const int = (envKey: string, configKey: string, fallback: number, label: string): number => {
+ const raw = rawBudget(env, config, envKey, configKey);
+ if (raw === null) return fallback;
+ try {
+ return parseInteger(raw.raw, fallback, raw.field, { min: 1 });
+ } catch (e) {
+ throw new SearchError("INVALID_INPUT", `${label}: ${(e as Error).message}`);
+ }
+ };
+ return Object.freeze({
+ maxSeeds: int(
+ TRAVERSAL_MAX_SEEDS_ENV,
+ TRAVERSAL_MAX_SEEDS_CONFIG,
+ TRAVERSAL_MAX_SEEDS,
+ "relational traversal budget",
+ ),
+ maxExpansionPerNode: int(
+ TRAVERSAL_MAX_EXPANSION_PER_NODE_ENV,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE_CONFIG,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE,
+ "relational traversal budget",
+ ),
+ maxTotalNodes: int(
+ TRAVERSAL_MAX_TOTAL_NODES_ENV,
+ TRAVERSAL_MAX_TOTAL_NODES_CONFIG,
+ TRAVERSAL_MAX_TOTAL_NODES,
+ "relational traversal budget",
+ ),
+ hubDegreeThreshold: int(
+ TRAVERSAL_HUB_DEGREE_THRESHOLD_ENV,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD_CONFIG,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD,
+ "relational traversal budget",
+ ),
+ });
+}
+
export interface RelationalFanoutOptions {
/** Maximum hop depth. Defaults to 2; clamped to >= 1. */
readonly maxDepth?: number;
@@ -50,22 +240,53 @@ export interface RelationalFanoutOptions {
* edge; a non-empty list restricts the walk to those relations.
*/
readonly edgeTypes?: ReadonlyArray<string>;
+ /** Seed cap. Defaults to {@link TRAVERSAL_MAX_SEEDS}; clamped to >= 1. */
+ readonly maxSeeds?: number;
+ /**
+ * How many walked edges of one node may be followed. Defaults to
+ * {@link TRAVERSAL_MAX_EXPANSION_PER_NODE}; clamped to >= 1.
+ */
+ readonly maxExpansionPerNode?: number;
+ /** Total reached-node cap. Defaults to {@link TRAVERSAL_MAX_TOTAL_NODES}; clamped to >= 1. */
+ readonly maxTotalNodes?: number;
+ /**
+ * Walked-edge degree above which a reached node is not expanded.
+ * Defaults to {@link TRAVERSAL_HUB_DEGREE_THRESHOLD}; clamped to >= 1.
+ */
+ readonly hubDegreeThreshold?: number;
+ /**
+ * Fired-clock predicate bounding the walk (the composite recall deadline).
+ * Checked once before each depth round; once it reports true, the walk
+ * stops and every node already reached is kept - so a node is never
+ * half-expanded by the clock, and a round the clock admits completes.
+ * Absent means the caller takes no deadline - the width caps above still
+ * bound the walk.
+ */
+ readonly isExpired?: () => boolean;
}
-const DEFAULT_MAX_DEPTH = 2;
-/** Per-edge richness bonus, capped so a nearer node always outranks a farther one. */
-const RICHNESS_BONUS = 0.05;
-const MAX_RICHNESS_BONUS = 0.49;
-
interface MutableNode {
hops: number;
edgeRichness: number;
viaLinkTypes: Set<string>;
+ path: RelationalPathStep[];
}
/**
* Fan out from `seedDocumentIds` over typed edges, bounded to `maxDepth`
- * hops, returning reached nodes (seeds excluded) ranked deterministically.
+ * hops and the traversal width budgets, returning reached nodes (seeds
+ * excluded) ranked deterministically. Each node carries the ordered steps
+ * of the path that reached it first - the raw provenance the arm
+ * reach-gates per node before anything renders it.
+ *
+ * Budget semantics, all deterministic in the caller's edge order:
+ * - only the first `maxSeeds` distinct seeds enter the walk;
+ * - each node expands at most its first `maxExpansionPerNode` walked
+ * edges (restriction-passing with a resolvable target);
+ * - once `maxTotalNodes` nodes have been reached the walk stops;
+ * - a reached node whose walked-edge degree exceeds
+ * `hubDegreeThreshold` is kept but never expanded;
+ * - a fired `isExpired` abandons the frontier, keeping what is reached.
*/
export function relationalFanout(
store: RelationalFanoutStore,
@@ -75,30 +296,108 @@ export function relationalFanout(
const maxDepth = Math.max(1, opts.maxDepth ?? DEFAULT_MAX_DEPTH);
const allowed = new Set((opts.edgeTypes ?? []).map((t) => t));
const restrict = allowed.size > 0;
+ const maxSeeds = Math.max(1, opts.maxSeeds ?? TRAVERSAL_MAX_SEEDS);
+ const maxExpansionPerNode = Math.max(
+ 1,
+ opts.maxExpansionPerNode ?? TRAVERSAL_MAX_EXPANSION_PER_NODE,
+ );
+ const maxTotalNodes = Math.max(1, opts.maxTotalNodes ?? TRAVERSAL_MAX_TOTAL_NODES);
+ const hubDegreeThreshold = Math.max(1, opts.hubDegreeThreshold ?? TRAVERSAL_HUB_DEGREE_THRESHOLD);
+ const isExpired = opts.isExpired;
- const seeds = new Set(seedDocumentIds);
+ const seedIds = [...new Set(seedDocumentIds)].slice(0, maxSeeds);
const reached = new Map<number, MutableNode>();
- let frontier = [...seeds];
+ // The ordered steps of the first path to each id: seeds start with none,
+ // every reached node extends the path that reached its SOURCE.
+ const pathById = new Map<number, RelationalPathStep[]>(
+ seedIds.map((id) => [id, [] as RelationalPathStep[]]),
+ );
+ // Set when the total-node cap ends the walk early; the depth loop then
+ // keeps everything already in `reached`.
+ let stop = false;
- for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {
+ let frontier = seedIds;
+ for (let depth = 1; depth <= maxDepth && frontier.length > 0 && !stop; depth++) {
+ // The one clock check: before each depth round. A round the clock
+ // admits completes; a round it fires never starts.
+ if (isExpired?.() === true) break;
const edges = store.typedRelationEdgesForDocuments(frontier);
- const nextFrontier: number[] = [];
+ // One batched edge fetch per depth; grouped per source node so the
+ // per-node expansion cap and the hub-degree rule answer a per-node
+ // question without a second query. Entity bridges (when the store
+ // provides the reader) join the same per-source grouping, appended
+ // after the source's typed edges.
+ const bySource = new Map<number, typeof edges>();
for (const edge of edges) {
- if (restrict && !allowed.has(edge.relation)) continue;
- const targetId = edge.targetDocumentId;
- if (targetId === null || seeds.has(targetId)) continue;
- const existing = reached.get(targetId);
- if (existing === undefined) {
- reached.set(targetId, {
- hops: depth,
- edgeRichness: 1,
- viaLinkTypes: new Set([edge.relation]),
- });
- nextFrontier.push(targetId);
- } else {
- existing.edgeRichness += 1;
- existing.viaLinkTypes.add(edge.relation);
- // hops keeps the minimum (first reached), which is `depth` order.
+ const mine = bySource.get(edge.sourceDocumentId);
+ if (mine) mine.push(edge);
+ else bySource.set(edge.sourceDocumentId, [edge]);
+ }
+ const bridgesBySource = new Map<number, number[]>();
+ if (store.entityBridgesForDocuments !== undefined) {
+ for (const bridge of store.entityBridgesForDocuments(frontier)) {
+ const mine = bridgesBySource.get(bridge.sourceDocumentId);
+ if (mine) mine.push(bridge.targetDocumentId);
+ else bridgesBySource.set(bridge.sourceDocumentId, [bridge.targetDocumentId]);
+ }
+ }
+ const nextFrontier: number[] = [];
+ for (const sourceId of frontier) {
+ if (stop) break;
+ const declared = bySource.get(sourceId) ?? [];
+ // A node's WALKED edges: the ones the traversal could actually
+ // follow - restriction-passing with a resolvable target, then the
+ // source's entity bridges (machine-derived, exempt from the query's
+ // edge-type restriction by design). Degree and expansion answer this
+ // combined list, so a dangling edge neither inflates a hub nor
+ // spends a node's expansion budget, while a bridge counts exactly
+ // like a typed edge. A target that happens to be a seed id is walked
+ // like any target (see the module header).
+ const walked = declared.filter(
+ (edge) => (!restrict || allowed.has(edge.relation)) && edge.targetDocumentId !== null,
+ );
+ const bridgeTargets = bridgesBySource.get(sourceId) ?? [];
+ // Hub skipping: a node the walk REACHED keeps its provenance but its
+ // fan-out is withheld from the frontier. A seed is exempt - it is the
+ // caller's deliberate entry point, not a node the walk reached, and
+ // its expansion is already bounded by the per-node cap (the cap cases
+ // in the fanout test pin a 20-edge seed expanding past the threshold).
+ if (depth > 1 && walked.length + bridgeTargets.length > hubDegreeThreshold) continue;
+ let followed = 0;
+ const parentPath = pathById.get(sourceId) ?? [];
+ const walkTarget = (targetId: number, relation: string): boolean => {
+ if (followed >= maxExpansionPerNode) return false;
+ followed += 1;
+ const existing = reached.get(targetId);
+ if (existing === undefined) {
+ if (reached.size >= maxTotalNodes) {
+ stop = true;
+ return false;
+ }
+ const path = [...parentPath, { documentId: targetId, relation }];
+ pathById.set(targetId, path);
+ reached.set(targetId, {
+ hops: depth,
+ edgeRichness: 1,
+ viaLinkTypes: new Set([relation]),
+ path,
+ });
+ nextFrontier.push(targetId);
+ } else {
+ existing.edgeRichness += 1;
+ existing.viaLinkTypes.add(relation);
+ // hops keeps the minimum (first reached), which is `depth` order -
+ // and so does `path`: later arrivals never rewrite it.
+ }
+ return true;
+ };
+ for (const edge of walked) {
+ if (!walkTarget(edge.targetDocumentId!, edge.relation)) break;
+ }
+ if (!stop) {
+ for (const targetId of bridgeTargets) {
+ if (!walkTarget(targetId, ENTITY_BRIDGE_RELATION)) break;
+ }
}
}
frontier = nextFrontier;
@@ -117,6 +416,7 @@ export function relationalFanout(
viaLinkTypes: Object.freeze(
[...node.viaLinkTypes].toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
),
+ path: Object.freeze(node.path.map((step) => Object.freeze({ ...step }))),
score,
}),
);
diff --git a/src/core/search/retrieval-trail.ts b/src/core/search/retrieval-trail.ts
index 11ee87fc..33f449ea 100644
--- a/src/core/search/retrieval-trail.ts
+++ b/src/core/search/retrieval-trail.ts
@@ -271,6 +271,34 @@ export interface RetrievalDegradation {
readonly detail?: RetrievalDegradationDetail;
}
+/**
+ * The stable typed code identifying a relational ordered-path trail entry
+ * (truth-correctable-time-aware). Its own vocabulary member, NOT a
+ * {@link RETRIEVAL_DEGRADATION} code: a walked provenance path is not a
+ * narrowing, and a degradation row would make every consumer treat a
+ * healthy answer as a degraded one. It rides the trail because the trail
+ * is the one typed, machine-readable channel beside the rows - the
+ * additive `relational:` reason strings stay human provenance.
+ */
+export const RETRIEVAL_RELATIONAL_PATH_CODE = "relational-path";
+
+/**
+ * One relational row's ordered path, machine-readable: the document ids
+ * that stayed readable at the caller's reach and owner scope, in walk
+ * order. Path nodes the gates withhold are omitted from `path` - never
+ * named, and never counted, so the entry reads the same whether the walk
+ * crossed unreadable documents or not (the views' identical-to-absent
+ * convention: a count would tell the caller that a node it may not see
+ * exists). Present on the trail only when the relational arm contributed
+ * a gated path - absent otherwise, keeping a healthy arm-off answer
+ * byte-identical.
+ */
+export interface RelationalPathTrailEntry {
+ readonly code: typeof RETRIEVAL_RELATIONAL_PATH_CODE;
+ /** Readable document ids along the walked path, in walk order. */
+ readonly path: ReadonlyArray<number>;
+}
+
/**
* What the corpus supports when nothing degraded and nothing matched -
* the three surfaced fields of a {@link NegativeRecallVerdict}. The
@@ -305,6 +333,12 @@ export interface RetrievalTrail {
* the search can support.
*/
readonly empty?: RetrievalCorpusStatement;
+ /**
+ * The relational arm's reach-gated ordered paths, one entry per surfaced
+ * relational row in ranked order. Absent (never empty) when the arm
+ * contributed nothing.
+ */
+ readonly relationalPaths?: ReadonlyArray<RelationalPathTrailEntry>;
}
/**
@@ -438,8 +472,11 @@ export function buildRetrievalTrail(input: {
readonly pool: number;
readonly degraded: ReadonlyArray<RetrievalDegradation>;
readonly empty?: RetrievalCorpusStatement | undefined;
+ readonly relationalPaths?: ReadonlyArray<RelationalPathTrailEntry> | undefined;
}): RetrievalTrail | undefined {
- if (input.retrieved > 0 && input.degraded.length === 0) return undefined;
+ if (input.retrieved > 0 && input.degraded.length === 0 && !input.relationalPaths?.length) {
+ return undefined;
+ }
return Object.freeze({
retrieved: input.retrieved,
pool: input.pool,
@@ -447,6 +484,8 @@ export function buildRetrievalTrail(input: {
// A degradation already accounts for the empty; the corpus statement
// is the answer only when nothing else is.
...(input.empty !== undefined && input.degraded.length === 0 ? { empty: input.empty } : {}),
+ // Absent, never empty: an arm-off run keeps the pre-change shape.
+ ...(input.relationalPaths?.length ? { relationalPaths: input.relationalPaths } : {}),
});
}
@@ -483,6 +522,14 @@ export function retrievalTrailEnvelope(outcome: {
},
}
: {}),
+ ...(trail.relationalPaths?.length
+ ? {
+ relational_paths: trail.relationalPaths.map((entry) => ({
+ code: entry.code,
+ path: [...entry.path],
+ })),
+ }
+ : {}),
},
};
}
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index 844a8fd6..b975c89d 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -375,9 +375,28 @@ export async function search(
}
// Typed-edge relational arm (t_09b7ccea): a fourth RRF arm, engaged
- // only for a relationship-shaped query under rrf fusion.
+ // only for a relationship-shaped query under rrf fusion. The deepened
+ // traversal rides the same composite clock every other phase answers
+ // to - the walk abandons its frontier once the deadline has fired -
+ // and gates its ordered provenance paths at the caller's transport
+ // reach and owner scope (an absent reach resolves to the same remote
+ // default the row-level filters apply, so provenance never names a
+ // page those rows withhold). The
+ // width budgets need no threading: the arm resolves them itself from
+ // the same env and the config file this call's resolution read (the
+ // resolved config's path, threaded through). With the arm off this
+ // whole expression is `noRelationalArm()` exactly as before.
const relational = isRelationalArmActive(effectiveConfig, opts)
- ? runRelationalArm(store, effectiveConfig.vault, query)
+ ? runRelationalArm(store, effectiveConfig.vault, query, {
+ configPath: effectiveConfig.configPath,
+ ...(deadline !== null ? { isExpired: () => deadlineExpired(deadline) } : {}),
+ ...(opts.transportReach !== undefined ? { reach: opts.transportReach } : {}),
+ // The caller's owner scope gates the provenance path nodes the
+ // same way the row-level filters gate content rows: a
+ // reach-readable node another agent owns is omitted from the
+ // ordered path, never named and never counted in the trail.
+ ...(opts.agentScope !== undefined ? { agentScope: opts.agentScope } : {}),
+ })
: noRelationalArm();
// Hydrate.
@@ -573,6 +592,10 @@ export async function search(
poolSize,
degraded,
corpus,
+ // The arm's reach-gated paths ride into the outcome builder so
+ // the retrieval trail renders them; empty (arm off) projects to
+ // no trail entry at all.
+ ...(relational.reachByChunk.size > 0 ? { relationalReach: relational.reachByChunk } : {}),
...(postRank.decisionModel?.answerable !== undefined
? { decisionModel: { answerable: postRank.decisionModel.answerable } }
: {}),
diff --git a/src/core/search/store.ts b/src/core/search/store.ts
index d96b2f31..57214759 100644
--- a/src/core/search/store.ts
+++ b/src/core/search/store.ts
@@ -40,6 +40,7 @@ import * as chunks from "./store/chunks.ts";
import * as census from "./store/counts.ts";
import * as documents from "./store/documents.ts";
import * as abi from "./store/embedding-abi.ts";
+import * as entityBridges from "./store/entity-bridges.ts";
import * as keyword from "./store/keyword.ts";
import * as lifecycle from "./store/lifecycle.ts";
import * as links from "./store/links.ts";
@@ -849,6 +850,20 @@ export class Store {
return chunkEntities.chunkEntityMatches(this.db, candidateChunkIds, queryEntities);
}
+ /**
+ * The entity bridges of the given documents (deepened traversal,
+ * truth-correctable-time-aware): the deduplicated `chunk_entities`
+ * co-occurrence pairs, ordered by source then target id. Living on the
+ * typed surface is the wiring the relational arm's store view looks
+ * for, so the bridge flag has a reader to enable - a store without this
+ * method walks typed edges only.
+ */
+ entityBridgesForDocuments(
+ documentIds: ReadonlyArray<number>,
+ ): Array<entityBridges.EntityBridgePair> {
+ return entityBridges.entityBridgesForDocuments(this.db, documentIds);
+ }
+
// ── counts ─────────────────────────────────────────────────────────────────
counts(): census.StoreCounts {
diff --git a/src/core/search/store/entity-bridges.ts b/src/core/search/store/entity-bridges.ts
new file mode 100644
index 00000000..d44a46d3
--- /dev/null
+++ b/src/core/search/store/entity-bridges.ts
@@ -0,0 +1,54 @@
+/**
+ * Entity-bridge edges over the `chunk_entities` table
+ * (truth-correctable-time-aware, design decision 11): two documents that
+ * mention the same normalized entity get one bridge edge, so the relational
+ * fan-out can walk entity co-occurrence beside the declared typed edges.
+ *
+ * Bridges are machine-derived, never part of the query edge-type
+ * vocabulary - `parseRelationalQuery` validation is unaffected, and the
+ * walk labels them `entity` (see `ENTITY_BRIDGE_RELATION` in
+ * `relational-fanout.ts`). The reader is a pure read: one join over
+ * `chunk_entities` twice through `chunks`, deduplicated per document pair
+ * (sharing three entities is still one bridge), self pairs excluded, and
+ * ordered by source then target document id so the walk that consumes it
+ * is deterministic.
+ */
+
+import type { Database } from "bun:sqlite";
+
+import { sqlPlaceholders } from "./sql.ts";
+
+/** One deduplicated co-occurrence bridge: source mentions what target mentions. */
+export interface EntityBridgePair {
+ readonly sourceDocumentId: number;
+ readonly targetDocumentId: number;
+}
+
+/**
+ * The entity bridges of the given source documents: every OTHER document
+ * sharing at least one normalized entity with one of them, one pair per
+ * document pair, ascending by source then target id. Empty input answers
+ * empty without touching the database.
+ */
+export function entityBridgesForDocuments(
+ db: Database,
+ documentIds: ReadonlyArray<number>,
+): Array<EntityBridgePair> {
+ if (documentIds.length === 0) return [];
+ const placeholders = sqlPlaceholders(documentIds);
+ return db
+ .query<{ source_document_id: number; target_document_id: number }, number[]>(
+ "SELECT DISTINCT c.document_id AS source_document_id, c2.document_id AS target_document_id " +
+ "FROM chunk_entities e " +
+ "JOIN chunks c ON c.id = e.chunk_id " +
+ "JOIN chunk_entities e2 ON e2.entity = e.entity " +
+ "JOIN chunks c2 ON c2.id = e2.chunk_id " +
+ `WHERE c.document_id IN (${placeholders}) AND c2.document_id <> c.document_id ` +
+ "ORDER BY source_document_id ASC, target_document_id ASC",
+ )
+ .all(...(documentIds as number[]))
+ .map((r) => ({
+ sourceDocumentId: r.source_document_id,
+ targetDocumentId: r.target_document_id,
+ }));
+}
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 15666045..f9cf6cf9 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -1567,6 +1567,13 @@ export interface ResolvedFreshenConfig {
export interface ResolvedSearchConfig {
readonly vault: string;
readonly dbPath: string;
+ /**
+ * The config file this resolution read, or null when it consulted no
+ * file (env-only). Carried so a per-phase re-read (the relational
+ * arm's knobs) answers the caller's own config map, never a fresh
+ * read of the default path this resolution may not have used.
+ */
+ readonly configPath?: string | null;
/**
* Vault-wide scope rules, both polarities. Resolved through
* `src/core/vault-scope` from `<vault>/Brain/_brain.yaml` β†’
diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.ts
index c4b4e90a..ebbe2a19 100644
--- a/src/mcp/brain/knowledge-tools.ts
+++ b/src/mcp/brain/knowledge-tools.ts
@@ -45,13 +45,28 @@ import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";
import { isoSecond } from "../../core/brain/time.ts";
import { normalizeAgentArgument } from "../../core/agent-identity.ts";
import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";
+import { listEntities } from "../../core/brain/entities/registry.ts";
+import {
+ ENTITY_STATUS_SCOPE,
+ entityStatusInScope,
+} from "../../core/brain/entities/status-scope.ts";
+import {
+ appendStatedClaims,
+ StatedClaimsRefusal,
+ type StatedClaim,
+} from "../../core/brain/truth/stated-claims.ts";
import { listDeadEnds, recordDeadEnd } from "../../core/brain/dead-ends.ts";
import { buildCodegraphReport } from "../../core/partner/codegraph-report.ts";
import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../../core/brain/temporal/foresight.ts";
import { aggregateQuantities } from "../../core/brain/truth/aggregate.ts";
import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";
import { computeTruthStateWithConflicts } from "../../core/brain/truth/conflicts.ts";
-import { appendClaimEvent, readClaimEvents } from "../../core/brain/truth/store.ts";
+import {
+ appendClaimEvent,
+ ClaimWindowRefusal,
+ readClaimEvents,
+} from "../../core/brain/truth/store.ts";
+import { claimEventLimit, matchClaimEvents } from "../../core/brain/truth/events-window.ts";
import {
allClaims,
buildClaimGraph,
@@ -66,6 +81,7 @@ import {
} from "../../core/brain/claim-graph.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { contextReach } from "../tool-contract.ts";
+import type { TransportReach } from "../../core/graph/transport-reach.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { vaultPathField } from "../vault-path-field.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
@@ -78,6 +94,7 @@ import {
} from "../coerce.ts";
import { coercePositiveInteger, toolSafeguard, vaultRelativeSafe } from "./shared.ts";
import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
+import { resolveTimeBounds } from "./time-bounds.ts";
/**
* Vault-relative locations these two handlers read BY PATH, rather than
@@ -583,8 +600,10 @@ function toolBrainIdeaDiscovery(
/**
* Operator/agent surface over the entity claim ledger: ingest one
* claim, render slots/conflicts from the fold, aggregate exact-match
- * quantities, report cross-agent collisions. Read ops are pure folds
- * over the append-only ledger.
+ * quantities, report cross-agent collisions, recall a windowed slice of
+ * the ledger via the events operation, and commit grounded agent-stated
+ * claims via the state operation with per-claim anchoring verdicts. The
+ * read ops are pure folds over the append-only ledger.
*/
function toolBrainTruth(
ctx: ServerContext,
@@ -596,10 +615,12 @@ function toolBrainTruth(
op !== "slots" &&
op !== "conflicts" &&
op !== "aggregate" &&
- op !== "collisions"
+ op !== "collisions" &&
+ op !== "events" &&
+ op !== "state"
) {
throw unknownOperationError(
- "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",
+ "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions|events|state",
);
}
const requireStr = (name: string): string => {
@@ -609,6 +630,17 @@ function toolBrainTruth(
}
return value;
};
+ // An optional string parameter is either a string or absent; any other
+ // type is refused rather than silently ignored - a mistyped bound that
+ // read as "no filter" would widen what the caller sees.
+ const optionalStr = (name: string): string | undefined => {
+ const value = args[name];
+ if (value === undefined) return undefined;
+ if (typeof value !== "string") {
+ throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a string`);
+ }
+ return value;
+ };
if (op === "ingest") {
const quantityValue = args["quantity_value"];
@@ -637,23 +669,165 @@ function toolBrainTruth(
const agent =
normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
resolveAgentName(ctx.configPath ?? undefined);
- const result = appendClaimEvent(ctx.vault, {
- ts: isoSecond(new Date()),
- agent,
- entity: requireStr("entity"),
- aspect: requireStr("aspect"),
- value: requireStr("value"),
- ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),
- source: requireStr("source"),
- });
+ // Declared optional validity fields (design decision 3): explicit
+ // input wins outright, bound by bound, over what ingest resolves
+ // from the source record's frontmatter; absent fields leave every
+ // line byte-identical to the pre-window ledger.
+ const validFrom = optionalStr("valid_from");
+ const validUntil = optionalStr("valid_until");
+ // The source's window resolves at the CALLER's reach: a source page
+ // the caller cannot read is treated exactly like an absent one -
+ // windowless claim, no validity keys in the response, no signal
+ // distinguishing withheld from absent. Without this gate the ingest
+ // response would read a withheld page's validity frontmatter back
+ // and triple as an existence oracle. (The CLI verb runs at operator
+ // reach and passes no gate.)
+ const readable = readableAtContextReachOrUndefined(ctx);
+ // The store's window refusal is strict by design; here it is a
+ // mistyped parameter, so it answers as the same failure class as the
+ // sibling mistyped inputs (entity, since/until, limit) - typed
+ // INVALID_PARAMS, never an internal error.
+ let result;
+ try {
+ result = appendClaimEvent(
+ ctx.vault,
+ {
+ ts: isoSecond(new Date()),
+ agent,
+ entity: requireStr("entity"),
+ aspect: requireStr("aspect"),
+ value: requireStr("value"),
+ ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),
+ ...(validFrom !== undefined ? { validFrom } : {}),
+ ...(validUntil !== undefined ? { validUntil } : {}),
+ source: requireStr("source"),
+ },
+ readable !== undefined ? { readableSource: readable } : {},
+ );
+ } catch (exc) {
+ if (exc instanceof ClaimWindowRefusal) {
+ throw new MCPError(INVALID_PARAMS, `brain_truth ingest: ${(exc as Error).message}`);
+ }
+ throw exc;
+ }
return {
ok: true,
entity: result.event.entity,
aspect: result.event.aspect,
path: result.path,
+ ...(result.event.validFrom !== undefined ? { valid_from: result.event.validFrom } : {}),
+ ...(result.event.validUntil !== undefined ? { valid_until: result.event.validUntil } : {}),
};
}
+ // Windowed recall over the ledger (truth-correctable-time-aware,
+ // Task 8): the response body is the shared claimEventsReport, so the
+ // CLI subcommand answers byte-identically at the same query.
+ if (op === "events") {
+ const bounds = resolveTimeBounds(optionalStr("since"), optionalStr("until"));
+ let limit: number;
+ try {
+ limit = claimEventLimit(args["limit"]);
+ } catch (exc) {
+ throw new MCPError(INVALID_PARAMS, `brain_truth events: ${(exc as Error).message}`);
+ }
+ return claimEventsReport(ctx.vault, ctx.agentName, contextReach(ctx), {
+ entity: optionalStr("entity"),
+ sinceMs: bounds.sinceMs,
+ untilMs: bounds.untilMs,
+ limit,
+ });
+ }
+
+ // Grounded agent-stated claims (truth-correctable-time-aware, Task 8),
+ // through lane 1's grounded-claim core: the payload boundary refuses
+ // WHOLE calls (unknown relation, missing text, missing source, empty
+ // agent, malformed ts) before ANY write, and anchoring verdicts are
+ // per claim - the one
+ // partial-commit lane in this subsystem, safe because each event is an
+ // independent append in an append-only ledger and the response reports
+ // exactly what landed.
+ if (op === "state") {
+ const claims = args["claims"];
+ if (!Array.isArray(claims) || claims.length === 0) {
+ throw new MCPError(INVALID_PARAMS, "brain_truth state: claims must be a non-empty array");
+ }
+ const stated = claims.map((raw, index): StatedClaim => {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new MCPError(INVALID_PARAMS, `brain_truth state: claims[${index}] must be an object`);
+ }
+ const claim = raw as Record<string, unknown>;
+ // Type-shaped fields only; an empty subject or object is not a
+ // refusal here but a per-claim ungrounded verdict downstream.
+ const readField = (name: string): string => {
+ const value = claim[name];
+ if (typeof value !== "string") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_truth state: claims[${index}].${name} must be a string`,
+ );
+ }
+ return value;
+ };
+ return {
+ subject: readField("subject"),
+ relation: readField("relation"),
+ object: readField("object"),
+ };
+ });
+ const agentArg = args["agent"];
+ if (agentArg !== undefined && typeof agentArg !== "string") {
+ throw new MCPError(INVALID_PARAMS, "brain_truth state: agent must be a string");
+ }
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ // The source's frontmatter window resolves at the CALLER's reach,
+ // exactly as ingest gates it: a withheld source freezes a windowless
+ // event and the committed rows carry no validity keys, so the state
+ // response reads a withheld page's frontmatter no more than an
+ // absent one's.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ try {
+ const outcome = appendStatedClaims(
+ ctx.vault,
+ {
+ claims: stated,
+ text: requireStr("text"),
+ agent,
+ ts: isoSecond(new Date()),
+ source: requireStr("source"),
+ },
+ {
+ entities: statedClaimEntities(ctx.vault),
+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
+ ...(readable !== undefined ? { readableSource: readable } : {}),
+ },
+ );
+ return {
+ ok: true,
+ operation: "state",
+ committed: outcome.committed.map((result) => ({ ...result.event })),
+ ungrounded: outcome.ungrounded.map(({ claim, reasons }) => ({
+ subject: claim.subject,
+ relation: claim.relation,
+ object: claim.object,
+ reasons,
+ })),
+ };
+ } catch (exc) {
+ // Both refusal channels are mistyped-input refusals - the payload
+ // boundary's, and the store's when the stated claim's window
+ // resolves from the source record's frontmatter and inverts there
+ // - so both answer as the same failure class the ingest operation
+ // maps, never an internal error.
+ if (exc instanceof StatedClaimsRefusal || exc instanceof ClaimWindowRefusal) {
+ throw new MCPError(INVALID_PARAMS, `brain_truth state: ${exc.message}`);
+ }
+ throw exc;
+ }
+ }
+
const events = readClaimEvents(ctx.vault).events;
if (op === "slots" || op === "conflicts") {
const state = computeTruthStateWithConflicts(events);
@@ -855,6 +1029,73 @@ function toolBrainClaims(
// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------
+/**
+ * The registry slice the stated-claims anchoring consumes: canonical-
+ * scope entities only (the anchoring kernel's status discipline,
+ * applied where the registry is read), narrowed to AtomicEntityLike.
+ * Shared by the MCP `state` operation and the CLI `brain truth state`
+ * subcommand so the two surfaces anchor identically.
+ */
+export function statedClaimEntities(vault: string): ReadonlyArray<{
+ readonly id: string;
+ readonly name: string;
+ readonly aliases: ReadonlyArray<string>;
+ readonly status: string;
+}> {
+ return listEntities(vault)
+ .filter((entity) => entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical))
+ .map(({ id, name, aliases, status }) => ({ id, name, aliases, status }));
+}
+
+/**
+ * One windowed events query, shared by the MCP `events` operation and
+ * the CLI `brain truth events` subcommand so the two surfaces cannot
+ * drift on shape, ordering, gating or paging. Bounds arrive already
+ * resolved (unix-ms); the page size must already be validated.
+ *
+ * Windowed recall (truth-correctable-time-aware, Tasks 8-9):
+ * `sinceMs`/`untilMs` filter ASSERTION `ts` only; the per-claim
+ * validity windows ride on the rows verbatim and are never consulted
+ * here (contract item 1 keeps the two temporal vocabularies separate).
+ * Every matched row passes the same per-row owner/reach gate
+ * `brain_claims` asks, and the account covers ONLY the rows that pass
+ * it: a withheld row is dropped and nothing counts it (the views'
+ * identical-to-absent convention - a dropped-but-counted row would tell
+ * the caller that a claim it may not see exists, and per entity or
+ * window would let it measure the hidden population). A filtered answer
+ * is therefore byte-identical to the answer over a vault that never
+ * held the withheld rows.
+ */
+export function claimEventsReport(
+ vault: string,
+ agentName: string | undefined,
+ reach: TransportReach,
+ query: {
+ readonly entity?: string;
+ readonly sinceMs: number | null;
+ readonly untilMs: number | null;
+ readonly limit: number;
+ },
+): Record<string, unknown> {
+ const entityFilter =
+ query.entity !== undefined && query.entity.trim() !== "" ? query.entity : undefined;
+ const view = everyArtifactRefView(gatedOwnerScopeView(vault, agentName), reachView(vault, reach));
+ const matched = matchClaimEvents(readClaimEvents(vault).events, {
+ ...(entityFilter !== undefined ? { entity: entityFilter } : {}),
+ sinceMs: query.sinceMs,
+ untilMs: query.untilMs,
+ });
+ const gated = view.filtersNothing ? matched : matched.filter((event) => view.row(event.source));
+ return {
+ ok: true,
+ operation: "events",
+ entity: entityFilter === undefined ? null : normalizeEntityName(entityFilter),
+ events: gated.slice(0, query.limit),
+ total: gated.length,
+ truncated: gated.length > query.limit,
+ };
+}
+
export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_claims",
@@ -1062,28 +1303,77 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_truth",
description:
- "Entity claim ledger: ingest a claim, render current-truth slots with superseded history, list contested conflicts (ask_user), aggregate exact-match quantities, report cross-agent collisions.",
+ "Entity claim ledger: ingest a claim, render current-truth slots, list conflicts, aggregate quantities, report collisions, window recall via the events operation, or commit grounded agent-stated claims via the state operation with per-claim anchoring verdicts.",
inputSchema: {
type: "object",
properties: {
operation: {
type: "string",
- enum: ["ingest", "slots", "conflicts", "aggregate", "collisions"],
+ enum: ["ingest", "slots", "conflicts", "aggregate", "collisions", "events", "state"],
description: "Tool operation.",
},
entity: {
type: "string",
- description: "Entity name (ingest, slots filter, aggregate filter).",
+ description: "Entity name (ingest, slots filter, aggregate filter, events filter).",
},
aspect: { type: "string", description: "Aspect slot for ingest." },
value: { type: "string", description: "Claim value for ingest." },
- source: { type: "string", description: "Provenance wikilink/path for ingest." },
- agent: { type: "string", description: "Agent identity override for ingest." },
+ source: { type: "string", description: "Provenance wikilink/path for ingest and state." },
+ agent: { type: "string", description: "Agent identity override for ingest and state." },
quantity_value: { type: "number", description: "Numeric value for quantity claims." },
quantity_unit: { type: "string", description: "Unit token for quantity claims." },
quantity_action: { type: "string", description: "Measured action for quantity claims." },
+ valid_from: {
+ type: "string",
+ description:
+ "ingest: validity window start (bare ISO date or canonical UTC timestamp); wins over the source frontmatter's valid_from.",
+ },
+ valid_until: {
+ type: "string",
+ description:
+ "ingest: exclusive validity window end (bare ISO date or canonical UTC timestamp); wins over the source frontmatter's valid_until.",
+ },
action: { type: "string", description: "Measured action for aggregate." },
unit: { type: "string", description: "Unit token for aggregate (omit for unitless)." },
+ since: {
+ type: "string",
+ description:
+ "events: inclusive lower bound on the events' assertion ts (ISO date/datetime, today/yesterday, last week/month, <n>h/<n>d/<n>w). Never a validity filter.",
+ },
+ until: {
+ type: "string",
+ description:
+ "events: inclusive upper bound on the events' assertion ts, same grammar as since. Never a validity filter.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "events: page size (default 200, capped at 1000); rows are ascending assertion ts, so tail-following paginates by advancing since.",
+ },
+ claims: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ subject: { type: "string", description: "Entity the claim is about." },
+ relation: {
+ type: "string",
+ description:
+ "Relation-vocabulary token between subject and object (related, extends, depends_on, refines, contradicts, superseded_by).",
+ },
+ object: { type: "string", description: "Entity the claim points at." },
+ },
+ required: ["subject", "relation", "object"],
+ additionalProperties: false,
+ },
+ description:
+ "state: the agent-stated claims to ground; each commits only when its subject and object anchor in text.",
+ },
+ text: {
+ type: "string",
+ description: "state: the assertion text every claim is anchored against.",
+ },
},
required: ["operation"],
additionalProperties: false,
diff --git a/src/mcp/brain/lifecycle-tools.ts b/src/mcp/brain/lifecycle-tools.ts
index 58f92ae6..444a02d9 100644
--- a/src/mcp/brain/lifecycle-tools.ts
+++ b/src/mcp/brain/lifecycle-tools.ts
@@ -1,6 +1,7 @@
/**
- * Cross-type tombstone + supersede lifecycle MCP tool (Belief lifecycle
- * suite, Track A anchor, t_7d5a3589).
+ * Cross-type tombstone + supersede + correct lifecycle MCP tool (Belief
+ * lifecycle suite, Track A anchor, t_7d5a3589; correct verb from
+ * truth-correctable-time-aware).
*
* One tool, `brain_lifecycle`, dispatching on `action`:
* - `tombstone` mark a memory `_status: tombstoned` in place
@@ -8,6 +9,10 @@
* - `temporal-replace` close one fact and open another at a shared instant
* - `tip` resolve a supersede chain to its live tip
* - `curator` read slices over observed-use verdicts
+ * - `correct` sweep one record's correction: discovery,
+ * per-target retirement through the end-state
+ * policy, mention retargeting, ledger correction
+ * events and bundle-correlated receipts
*
* MCP mirror of the `o2b brain lifecycle` CLI verb; both delegate to the
* core lifecycle module so the on-disk shape cannot drift.
@@ -15,6 +20,7 @@
import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
import { curatorSlices, type CuratorEntry } from "../../core/brain/lifecycle/curator.ts";
+import { correct, CorrectionError } from "../../core/brain/lifecycle/correction.ts";
import {
temporalReplace,
TemporalReplaceError,
@@ -49,7 +55,7 @@ async function toolBrainLifecycle(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
- return wrapToolErrors(TOOL, [TombstoneError, TemporalReplaceError], async () => {
+ return wrapToolErrors(TOOL, [TombstoneError, TemporalReplaceError, CorrectionError], async () => {
const action = coerceStr(args, "action", true)!;
const agent = coerceStr(args, "agent", false) ?? undefined;
// Every write answers at the caller's reach: a page it may not read is
@@ -130,6 +136,52 @@ async function toolBrainLifecycle(
resolved_all: res.resolvedAll,
};
}
+ case "correct": {
+ const target = coerceStr(args, "target", true)!;
+ const value = coerceStr(args, "value", false) ?? undefined;
+ const successor = coerceStr(args, "successor", false) ?? undefined;
+ const windowEnd = coerceStr(args, "window_end", false) ?? undefined;
+ const reason = coerceStr(args, "reason", false) ?? undefined;
+ const flatlyWrong = args["flatly_wrong"] === true;
+ // Dry run is the DEFAULT: the applied sequence needs an explicit
+ // false, so a caller that omits the flag gets the blast radius
+ // and nothing else.
+ const dryRun = args["dry_run"] !== false;
+ const res = correct({
+ vault: ctx.vault,
+ target,
+ ...(value !== undefined ? { value } : {}),
+ ...(successor !== undefined ? { successor } : {}),
+ ...(windowEnd !== undefined ? { windowEnd } : {}),
+ ...(reason !== undefined ? { reason } : {}),
+ flatlyWrong,
+ dryRun,
+ ...(agent ? { agent } : {}),
+ ...reachOpt,
+ });
+ return {
+ action,
+ bundle_id: res.bundleId,
+ dry_run: res.dryRun,
+ blast_radius: {
+ target: res.blastRadius.target,
+ replaced_by: res.blastRadius.replacedBy,
+ contests: res.blastRadius.contests,
+ mentions: res.blastRadius.mentions,
+ claims: res.blastRadius.claims,
+ },
+ retirements: res.retirements.map((r) => ({
+ path: r.path,
+ end_state: r.endState,
+ valid_until: r.validUntil,
+ reason_code: r.reasonCode,
+ changed: r.changed,
+ })),
+ retarget: res.retarget,
+ ledger: res.ledger,
+ receipts: res.receipts,
+ };
+ }
case "curator": {
const highUseMin = coerceNonNegativeInteger(TOOL, "high_use_min", args["high_use_min"]);
const slices = curatorSlices(ctx.vault, highUseMin !== undefined ? { highUseMin } : {});
@@ -150,7 +202,7 @@ async function toolBrainLifecycle(
}
default:
throw unknownOperationError(
- `${TOOL}: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator`,
+ `${TOOL}: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator, correct`,
);
}
});
@@ -160,13 +212,13 @@ export const LIFECYCLE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: TOOL,
description:
- "Cross-type lifecycle. action: tombstone marks a memory tombstoned in place (kept for audit); supersede tombstones a predecessor and links a successor; temporal-replace closes one fact and opens a successor at a shared instant; tip resolves a chain tip; curator slices observed-use verdicts.",
+ "Cross-type lifecycle. action: tombstone marks a memory tombstoned in place; supersede links a successor; temporal-replace closes one fact and opens another at a shared instant; tip resolves a chain tip; curator slices observed-use verdicts; correct sweeps a correction, dry run by default.",
inputSchema: {
type: "object",
properties: {
action: {
type: "string",
- enum: ["tombstone", "supersede", "temporal-replace", "tip", "curator"],
+ enum: ["tombstone", "supersede", "temporal-replace", "tip", "curator", "correct"],
description: "Which lifecycle operation to run.",
},
path: {
@@ -175,7 +227,7 @@ export const LIFECYCLE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
reason: {
type: "string",
- description: "tombstone/supersede: operator-facing reason for the change.",
+ description: "tombstone/supersede/correct: operator-facing reason for the change.",
},
superseded_by: {
type: "string",
@@ -189,7 +241,7 @@ export const LIFECYCLE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
successor: {
type: "string",
description:
- "supersede: successor id/wikilink. temporal-replace: vault-relative path of the successor.",
+ "supersede: successor id/wikilink. temporal-replace: successor path. correct: successor id/wikilink for the superseded_by pointer and retarget.",
},
at: {
type: "string",
@@ -202,6 +254,30 @@ export const LIFECYCLE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
minimum: 0,
description: "curator: minimum USED count for the high-used slice.",
},
+ target: {
+ type: "string",
+ description: "correct: vault-relative path of the record being corrected.",
+ },
+ value: {
+ type: "string",
+ description:
+ "correct: the corrected value the ledger correction events assert; absent appends nothing to the ledger.",
+ },
+ flatly_wrong: {
+ type: "boolean",
+ description:
+ "correct: the caller declares the prior claim was never true, so the target tombstones instead of validity-closing.",
+ },
+ window_end: {
+ type: "string",
+ description:
+ "correct: explicit window end for a time-scoped correction (canonical ISO-8601 UTC); defaults to the correction instant.",
+ },
+ dry_run: {
+ type: "boolean",
+ description:
+ "correct: report the blast radius and write nothing (the default). Pass false to apply the sweep.",
+ },
agent: {
type: "string",
description: "Optional agent identity override; defaults to the server-resolved name.",
diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.ts
index 23df6e6d..5ca2444e 100644
--- a/src/mcp/brain/recall-tools.ts
+++ b/src/mcp/brain/recall-tools.ts
@@ -67,8 +67,7 @@ import {
expandSessionRecall,
searchSessionRecall,
} from "../../core/brain/session-recall.ts";
-import { resolveTimeRange } from "../../core/search/time-range.ts";
-import { SearchError } from "../../core/search/types.ts";
+import { resolveTimeBounds } from "./time-bounds.ts";
import { aggregateQueryDemand, serializeQueryDemandReport } from "../../core/brain/query-demand.ts";
import { buildRetrievalPlan, serializeRetrievalPlan } from "../../core/brain/retrieval-plan.ts";
import { isoSecond } from "../../core/brain/time.ts";
@@ -82,7 +81,6 @@ import {
} from "../../core/brain/payload-registry.ts";
import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
-import { searchErrorData } from "../search-tools.ts";
import { contextReach } from "../tool-contract.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { vaultPathField } from "../vault-path-field.ts";
@@ -910,10 +908,11 @@ async function toolBrainSessionGrep(
);
// Conversation-chronology bounds (S1): `since` / `before` parse through
// the shared time-range grammar (ISO date/datetime, today/yesterday,
- // <n>h/<n>d/<n>w). `before` maps onto the range's inclusive upper edge.
+ // <n>h/<n>d/<n>w) via the shared time-bounds wrapper. `before` maps
+ // onto the range's inclusive upper edge.
const since = optionalStringArg("brain_session_grep", args, "since");
const before = optionalStringArg("brain_session_grep", args, "before");
- const bounds = resolveSessionGrepBounds(since, before);
+ const bounds = resolveTimeBounds(since, before);
// Inline-raw disclosure (C2): opt-in flag inlines the raw captures beside
// each derived record and stamps an extracted discriminator. Omitted, the
// response stays byte-identical.
@@ -942,33 +941,6 @@ async function toolBrainSessionGrep(
};
}
-/**
- * Resolve `since` / `before` session-grep bounds through the shared
- * time-range grammar, mapping `before` onto the inclusive upper edge. An
- * unparseable point or an inverted range surfaces as an INVALID_PARAMS
- * error rather than a silently ignored filter.
- */
-function resolveSessionGrepBounds(
- since: string | undefined,
- before: string | undefined,
-): { sinceMs: number | null; untilMs: number | null } {
- if (since === undefined && before === undefined) return { sinceMs: null, untilMs: null };
- try {
- return resolveTimeRange(
- {
- ...(since !== undefined ? { since } : {}),
- ...(before !== undefined ? { until: before } : {}),
- },
- Date.now(),
- );
- } catch (exc) {
- if (exc instanceof SearchError) {
- throw new MCPError(INVALID_PARAMS, exc.message, searchErrorData(exc));
- }
- throw exc;
- }
-}
-
/**
* Private continuity rows are session data a remote caller does not get:
* the recall tools answer about them exactly as about a row that does not
diff --git a/src/mcp/brain/time-bounds.ts b/src/mcp/brain/time-bounds.ts
new file mode 100644
index 00000000..dbbb57ac
--- /dev/null
+++ b/src/mcp/brain/time-bounds.ts
@@ -0,0 +1,64 @@
+/**
+ * Shared time-bounds wrapper (truth-correctable-time-aware, Task 7):
+ * one `since`/`until` resolution for every MCP recall surface.
+ *
+ * Bounds parse through the shared time-range grammar (`resolveTimeRange`:
+ * ISO date/datetime, today/yesterday, last week/month, `<n>h`/`<n>d`/
+ * `<n>w`; the upper edge is inclusive). A grammar refusal - an
+ * unparseable point or an inverted range - surfaces as an
+ * `MCPError(INVALID_PARAMS)` carrying the search error's typed data,
+ * never as a silently ignored filter. The lifted form of the bounds
+ * resolver `brain_session_grep` used to carry privately.
+ */
+
+import { resolveTimeRange } from "../../core/search/time-range.ts";
+import { SearchError } from "../../core/search/types.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { searchErrorData } from "../search-tools.ts";
+
+/** Resolved conversation/assertion-chronology bounds; null is open. */
+export interface TimeBounds {
+ readonly sinceMs: number | null;
+ readonly untilMs: number | null;
+}
+
+/**
+ * Resolve `since` / `until` through the shared time-range grammar.
+ * Absent bounds stay open. A grammar refusal surfaces as a
+ * `SearchError` - the core type - so the per-transport mappings live
+ * with the transports: {@link resolveTimeBounds} maps it to
+ * `MCPError(INVALID_PARAMS)`, and the CLI truth verb maps the same
+ * failure to its exit-2 usage error, both surfaces refusing through
+ * this one parser instead of forking the grammar.
+ */
+export function parseTimeBounds(since: string | undefined, until: string | undefined): TimeBounds {
+ if (since === undefined && until === undefined) {
+ return { sinceMs: null, untilMs: null };
+ }
+ return resolveTimeRange(
+ {
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ },
+ Date.now(),
+ );
+}
+
+/**
+ * Resolve `since` / `until` through the shared time-range grammar,
+ * mapping `SearchError` to `MCPError(INVALID_PARAMS)`. Absent bounds
+ * stay open.
+ */
+export function resolveTimeBounds(
+ since: string | undefined,
+ until: string | undefined,
+): TimeBounds {
+ try {
+ return parseTimeBounds(since, until);
+ } catch (exc) {
+ if (exc instanceof SearchError) {
+ throw new MCPError(INVALID_PARAMS, exc.message, searchErrorData(exc));
+ }
+ throw exc;
+ }
+}
diff --git a/tests/cli/brain-truth.test.ts b/tests/cli/brain-truth.test.ts
index 36975f39..3231a072 100644
--- a/tests/cli/brain-truth.test.ts
+++ b/tests/cli/brain-truth.test.ts
@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendClaimEvent, readClaimEvents } from "../../src/core/brain/truth/store.ts";
+import { upsertEntity } from "../../src/core/brain/entities/registry.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -178,6 +179,323 @@ test("truth with an unknown op exits 2", async () => {
expect(res.returncode).toBe(2);
});
+// ----- truth events + windowed ingest (truth-correctable-time-aware, Task 9)
+
+interface ClaimEventRow {
+ readonly ts: string;
+ readonly entity: string;
+ readonly aspect: string;
+ readonly value: string;
+ readonly source: string;
+ readonly validFrom?: string;
+ readonly validUntil?: string;
+}
+
+interface EventsBody {
+ readonly ok: boolean;
+ readonly operation: string;
+ readonly entity: string | null;
+ readonly events: ReadonlyArray<ClaimEventRow>;
+ readonly total: number;
+ readonly truncated: boolean;
+}
+
+test("truth events prints the MCP events shape over a windowed slice", async () => {
+ appendClaimEvent(vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude-dev-agent",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ validFrom: "2026-06-01",
+ validUntil: "2026-09-01",
+ source: "[[Brain/notes/a.md]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-10T12:00:00Z",
+ agent: "claude-dev-agent",
+ entity: "Project Atlas",
+ aspect: "status",
+ value: "on track",
+ source: "[[Brain/notes/b.md]]",
+ });
+ const res = await runCli([
+ "brain",
+ "truth",
+ "events",
+ "--vault",
+ vault,
+ "--entity",
+ "Alice Mason",
+ "--since",
+ "2026-06-01",
+ "--json",
+ ]);
+ expect(res.returncode).toBe(0);
+ const body = JSON.parse(res.stdout) as unknown as EventsBody;
+ expect(body.ok).toBe(true);
+ expect(body.operation).toBe("events");
+ expect(body.entity).toBe("alice mason");
+ expect(body.events.map((e) => e.ts)).toEqual(["2026-06-01T10:00:00Z"]);
+ expect(body.events[0]!.validFrom).toBe("2026-06-01");
+ expect(body.events[0]!.validUntil).toBe("2026-09-01");
+ expect(body.total).toBe(1);
+ expect("withheld" in body).toBe(false);
+ expect(body.truncated).toBe(false);
+});
+
+test("truth ingest accepts --valid-from and --valid-until", async () => {
+ const res = await runCli([
+ "brain",
+ "truth",
+ "ingest",
+ "--vault",
+ vault,
+ "--entity",
+ "Alice Mason",
+ "--aspect",
+ "employer",
+ "--value",
+ "Google",
+ "--source",
+ "[[Brain/notes/standup.md]]",
+ "--valid-from",
+ "2026-06-01",
+ "--valid-until",
+ "2026-09-01",
+ "--json",
+ ]);
+ expect(res.returncode).toBe(0);
+ const [event] = readClaimEvents(vault).events;
+ expect(event!.validFrom).toBe("2026-06-01");
+ expect(event!.validUntil).toBe("2026-09-01");
+});
+
+test("truth ingest refuses an empty or inverted validity window as a usage error", async () => {
+ // A mistyped window is the same failure class as the sibling mistyped
+ // inputs (--since garbage, --limit 0): usage, exit 2 - not an
+ // operational failure.
+ const res = await runCli([
+ "brain",
+ "truth",
+ "ingest",
+ "--vault",
+ vault,
+ "--entity",
+ "Alice Mason",
+ "--aspect",
+ "employer",
+ "--value",
+ "Google",
+ "--source",
+ "[[Brain/notes/standup.md]]",
+ "--valid-from",
+ "2026-09-01",
+ "--valid-until",
+ "2026-06-01",
+ "--json",
+ ]);
+ expect(res.returncode).toBe(2);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("truth ingest refuses an unparseable validity bound as a usage error", async () => {
+ const res = await runCli([
+ "brain",
+ "truth",
+ "ingest",
+ "--vault",
+ vault,
+ "--entity",
+ "Alice Mason",
+ "--aspect",
+ "employer",
+ "--value",
+ "Google",
+ "--source",
+ "[[Brain/notes/standup.md]]",
+ "--valid-from",
+ "garbage",
+ "--json",
+ ]);
+ expect(res.returncode).toBe(2);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("truth events refuses unparseable bounds with a usage error", async () => {
+ const res = await runCli([
+ "brain",
+ "truth",
+ "events",
+ "--vault",
+ vault,
+ "--since",
+ "not a date",
+ "--json",
+ ]);
+ expect(res.returncode).toBe(2);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("truth events refuses a non-positive or fractional limit", async () => {
+ for (const limit of ["0", "-3", "1.5"]) {
+ const res = await runCli(["brain", "truth", "events", "--vault", vault, "--limit", limit]);
+ expect(res.returncode).toBe(2);
+ }
+});
+
+test("truth events refuses a non-numeric limit naming the raw flag value", async () => {
+ // Number("abc") is NaN, which the shared limit guard's refusal would
+ // stringify as "null" - naming nothing the operator typed. The CLI
+ // validates the flag is finite before that message is composed and
+ // names the raw flag value it was handed.
+ for (const limit of ["abc", "many"]) {
+ const res = await runCli(["brain", "truth", "events", "--vault", vault, "--limit", limit]);
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain(`got ${JSON.stringify(limit)}`);
+ }
+});
+
+// ----- truth state (grounded agent-stated claims, Task 9) -------------------
+
+function seedCliRegistry(): void {
+ upsertEntity(vault, {
+ category: "people",
+ name: "Alice Mason",
+ aliases: ["Alice"],
+ agent: "claude",
+ now: new Date("2026-06-01T00:00:00Z"),
+ });
+ upsertEntity(vault, {
+ category: "projects",
+ name: "Project Atlas",
+ aliases: ["Atlas"],
+ agent: "claude",
+ now: new Date("2026-06-01T00:00:00Z"),
+ });
+}
+
+interface StateBody {
+ readonly ok: boolean;
+ readonly operation: string;
+ readonly committed: ReadonlyArray<Record<string, unknown>>;
+ readonly ungrounded: ReadonlyArray<{
+ readonly subject: string;
+ readonly relation: string;
+ readonly object: string;
+ readonly reasons: ReadonlyArray<string>;
+ }>;
+}
+
+function stateArgs(vaultFlag: string, extra: ReadonlyArray<string>): string[] {
+ return ["brain", "truth", "state", "--vault", vaultFlag, ...extra, "--json"];
+}
+
+test("truth state commits a grounded claim and prints the verdict", async () => {
+ seedCliRegistry();
+ const res = await runCli(
+ stateArgs(vault, [
+ "--subject",
+ "Alice Mason",
+ "--relation",
+ "extends",
+ "--object",
+ "Atlas",
+ "--text",
+ "Alice Mason said the Atlas extension plan is ready for review today.",
+ "--source",
+ "[[Brain/notes/session.md]]",
+ ]),
+ );
+ expect(res.returncode).toBe(0);
+ const body = JSON.parse(res.stdout) as unknown as StateBody;
+ expect(body.ok).toBe(true);
+ expect(body.operation).toBe("state");
+ expect(body.committed).toHaveLength(1);
+ const row = body.committed[0] as Record<string, unknown>;
+ expect(row["entity"]).toBe("alice mason");
+ expect(row["aspect"]).toBe("extends");
+ expect(row["value"]).toBe("Atlas");
+ expect(row["extractor"]).toBe("agent_stated");
+ expect(body.ungrounded).toHaveLength(0);
+ const [stored] = readClaimEvents(vault).events;
+ expect(stored!.extractor).toBe("agent_stated");
+});
+
+test("truth state reports an ungrounded claim with reasons and writes nothing", async () => {
+ seedCliRegistry();
+ const res = await runCli(
+ stateArgs(vault, [
+ "--subject",
+ "Alice Mason",
+ "--relation",
+ "related",
+ "--object",
+ "Project Osiris",
+ "--text",
+ "Alice walked through the Project Atlas plan all morning.",
+ "--source",
+ "[[Brain/notes/session.md]]",
+ ]),
+ );
+ expect(res.returncode).toBe(0);
+ const body = JSON.parse(res.stdout) as unknown as StateBody;
+ expect(body.committed).toHaveLength(0);
+ expect(body.ungrounded).toHaveLength(1);
+ expect(body.ungrounded[0]!.reasons).toContain("object_unanchored");
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("truth state refuses an unknown relation with a usage error", async () => {
+ seedCliRegistry();
+ const res = await runCli(
+ stateArgs(vault, [
+ "--subject",
+ "Alice Mason",
+ "--relation",
+ "invented_by",
+ "--object",
+ "Atlas",
+ "--text",
+ "Alice Mason reviewed Atlas today.",
+ "--source",
+ "[[Brain/notes/session.md]]",
+ ]),
+ );
+ expect(res.returncode).toBe(2);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("truth state refuses an inverted source window as a usage error", async () => {
+ // The stated claim carries no explicit window, so the store resolves
+ // one from the source record's frontmatter; an inverted window there
+ // raises the store's typed refusal, which - like ingest's - is a
+ // mistyped input and must answer as the usage failure class (exit 2),
+ // not the sibling ingest path's exit-2-vs-exit-1 divergence.
+ seedCliRegistry();
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "session.md"),
+ "---\nkind: note\nvalid_from: 2026-06-01\nvalid_until: 2026-01-01\n---\n\nsession page\n",
+ );
+ const res = await runCli(
+ stateArgs(vault, [
+ "--subject",
+ "Alice Mason",
+ "--relation",
+ "related",
+ "--object",
+ "Atlas",
+ "--text",
+ "Alice Mason reviewed Atlas today.",
+ "--source",
+ "[[Brain/notes/session.md]]",
+ ]),
+ );
+ expect(res.returncode).toBe(2);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
test("facts decompose splits a file into assertions", async () => {
const file = join(tmp, "session.md");
writeFileSync(
diff --git a/tests/contract/serve-with-correction.test.ts b/tests/contract/serve-with-correction.test.ts
new file mode 100644
index 00000000..16a501ef
--- /dev/null
+++ b/tests/contract/serve-with-correction.test.ts
@@ -0,0 +1,176 @@
+/**
+ * The wave-level contract (truth-correctable-time-aware, Task 21).
+ *
+ * Sub-suite A's temporal ledger and sub-suite B's serve-with-correction
+ * coupling compose into one guarantee on every serving surface: a record
+ * retired through a validity close stays serveable, but appears only
+ * beside its resolved, readable chain-tip correction, and is dropped
+ * fail-closed the moment that correction is unreadable; a flatly-wrong
+ * correction tombstones, and the tombstone stays hidden everywhere
+ * before any coupling question arises. The ledger side of the same
+ * composition is pinned too: the correction event carries the closed
+ * window, folds as a same-source self-correction (never a conflict) and
+ * classifies as a succession in the dedicated channel.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { brainDirs } from "../../src/core/brain/paths.ts";
+import { queryByTopic } from "../../src/core/brain/query.ts";
+import { correct } from "../../src/core/brain/lifecycle/correction.ts";
+import { appendClaimEvent, readClaimEvents } from "../../src/core/brain/truth/store.ts";
+import { computeTruthStateWithConflicts } from "../../src/core/brain/truth/conflicts.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+const NOW = new Date("2026-06-15T12:00:00Z");
+const CORRECTION_TS = "2026-06-15T12:00:00Z";
+const TARGET = "Brain/preferences/pref-old.md";
+const TARGET_SOURCE = "[[Brain/preferences/pref-old.md]]";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-contract-correction-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-contract-correction-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** The corrected record, its successor and the stale claim the ledger holds. */
+function seedPair(): void {
+ mkdirSync(brainDirs(vault).preferences, { recursive: true });
+ writeFileSync(
+ join(vault, TARGET),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-old",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-01T00:00:00Z",
+ "_confirmed_at: 2026-05-01T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ "topic: deploy-timeout",
+ "principle: Keep the deploy timeout at 30 seconds.",
+ "pinned: false",
+ "---",
+ "",
+ "The stale body.",
+ "",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(brainDirs(vault).preferences, "pref-new.md"),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-new",
+ "_status: confirmed",
+ "created_at: 2026-06-02T00:00:00Z",
+ "unconfirmed_until: 2026-06-02T00:00:00Z",
+ "_confirmed_at: 2026-06-02T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ "topic: deploy-timeout-v2",
+ "principle: Keep the deploy timeout at two minutes.",
+ "pinned: false",
+ "---",
+ "",
+ "The live body.",
+ "",
+ ].join("\n"),
+ );
+ appendClaimEvent(
+ vault,
+ {
+ ts: "2026-05-02T00:00:00Z",
+ agent: "tester",
+ entity: "deploy timeout",
+ aspect: "limit",
+ value: "30s",
+ source: TARGET_SOURCE,
+ validFrom: "2026-05-02T00:00:00Z",
+ validUntil: "2026-06-10T00:00:00Z",
+ },
+ { configPath },
+ );
+}
+
+function applyCorrection(overrides: { flatlyWrong?: boolean }): ReturnType<typeof correct> {
+ return correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ ...overrides,
+ });
+}
+
+describe("serve-with-correction contract", () => {
+ test("a validity-closed correction keeps the predecessor serveable and closes the ledger window", () => {
+ seedPair();
+
+ const res = applyCorrection({});
+ const retirement = res.retirements[0]!;
+ expect(retirement.endState).toBe("validity_close");
+ expect(retirement.reasonCode).toBe("supersede");
+ expect(retirement.validUntil).toBe(CORRECTION_TS);
+
+ const event = readClaimEvents(vault).events.find((e) => e.value === "two minutes");
+ expect(event).toBeDefined();
+ expect(event!.validFrom).toBe(CORRECTION_TS);
+
+ const out = queryByTopic(vault, "deploy-timeout");
+ expect(out.preference?.id).toBe("pref-old");
+ });
+
+ test("the serveable predecessor is dropped fail-closed once its chain-tip correction is unreadable", () => {
+ seedPair();
+ applyCorrection({});
+
+ rmSync(join(brainDirs(vault).preferences, "pref-new.md"));
+
+ const out = queryByTopic(vault, "deploy-timeout");
+ expect(out.preference).toBeNull();
+ });
+
+ test("a flatly-wrong correction tombstones the predecessor out of every surface", () => {
+ seedPair();
+
+ const res = applyCorrection({ flatlyWrong: true });
+ const retirement = res.retirements[0]!;
+ expect(retirement.endState).toBe("tombstone");
+ expect(retirement.reasonCode).toBe("tombstone");
+ expect(retirement.validUntil).toBeNull();
+
+ const out = queryByTopic(vault, "deploy-timeout");
+ expect(out.preference).toBeNull();
+ });
+
+ test("the corrected slot folds as a same-source self-correction in the succession channel", () => {
+ seedPair();
+ applyCorrection({});
+
+ const state = computeTruthStateWithConflicts(readClaimEvents(vault).events);
+ expect(state.conflicts).toHaveLength(0);
+ expect(state.successions).toHaveLength(1);
+ });
+});
diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.ts
index a15578b7..ea333bb4 100644
--- a/tests/core/architecture/visibility-surface-census.test.ts
+++ b/tests/core/architecture/visibility-surface-census.test.ts
@@ -306,7 +306,19 @@ const NOTE_CONTENT_PRODUCERS: ReadonlyArray<ProducerRule> = Object.freeze([
{ specifierIncludes: "/brain/expiration-set.ts", identifiers: ["setExpiration"] },
{
specifierIncludes: "/brain/truth/",
- identifiers: ["computeTruthStateWithConflicts", "aggregateQuantities", "detectAgentCollisions"],
+ identifiers: [
+ "computeTruthStateWithConflicts",
+ "aggregateQuantities",
+ "detectAgentCollisions",
+ // Ledger validity windows (contract item 1): any surface reading
+ // the validity axis off claim events is swept in.
+ "claimWindow",
+ "windowsIntersect",
+ "isValidityPoint",
+ // Grounded agent-stated claims (task 4): a surface stating claims
+ // reads the assertion text its claims anchor in.
+ "appendStatedClaims",
+ ],
},
{
specifierIncludes: "/brain/decisions/record.ts",
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 22876fbe..9eb85d62 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -1302,8 +1302,11 @@ const DIRECT_WRITE_ROWS = 77;
*
* 109 -> 110: `src/core/search/freshen.ts` writes the freshen-on-read state
* file through `atomicWriteFileSync`.
+ *
+ * 110 -> 111: `src/core/brain/lifecycle/correction.ts` retires the corrected
+ * record through `writeFrontmatterAtomic`.
*/
-const SHARED_HELPER_ROWS = 110;
+const SHARED_HELPER_ROWS = 111;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1391,8 +1394,10 @@ const UNSTAMPED_DIRECT_ROWS = 76;
* stages hub candidates through the shared atomic JSONL writer. 105 -> 106:
* the session focus writes through the shared atomic text writer. 106 -> 107:
* the freshen-on-read state file writes through the shared atomic writer.
+ * 107 -> 108: the correction sweep retires its target's frontmatter through
+ * the shared atomic frontmatter writer.
*/
-const UNSTAMPED_SHARED_ROWS = 107;
+const UNSTAMPED_SHARED_ROWS = 108;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain/artifact-ref-view.test.ts b/tests/core/brain/artifact-ref-view.test.ts
index 5e3179b9..d8c1f96f 100644
--- a/tests/core/brain/artifact-ref-view.test.ts
+++ b/tests/core/brain/artifact-ref-view.test.ts
@@ -118,6 +118,79 @@ describe("what a log entry offers the rule", () => {
});
});
+describe("an extensionless vault-page spelling", () => {
+ const HIDDEN_PAGE_REL = "Brain/notes/private";
+ const OPEN_PAGE_REL = "Brain/notes/open";
+
+ beforeEach(() => {
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(join(vault, `${HIDDEN_PAGE_REL}.md`), "---\ntopic: hidden\n---\n\nhidden\n");
+ writeFileSync(join(vault, `${OPEN_PAGE_REL}.md`), "open page\n");
+ });
+
+ /** A view that hides exactly the hidden notes page above. */
+ const hidingNotesPage = () => artifactRefView(vault, (rel) => rel !== `${HIDDEN_PAGE_REL}.md`);
+
+ test("resolves to the same target as its .md form and is withheld", () => {
+ // A gate that resolved only the .md form failed OPEN for the bare
+ // wikilink shape - the conventional Obsidian spelling.
+ const view = hidingNotesPage();
+ expect(view.visible("[[Brain/notes/private]]")).toBe(false);
+ expect(view.visible("Brain/notes/private")).toBe(false);
+ expect(view.visible(`[[${HIDDEN_PAGE_REL}.md]]`)).toBe(false);
+ });
+
+ test("a readable page stays visible under the extensionless spelling", () => {
+ expect(hidingNotesPage().visible("[[Brain/notes/open]]")).toBe(true);
+ });
+
+ test("the bare spelling wins when that file exists, as the write side resolves it", () => {
+ // One extensionless file beside its .md twin: the bare candidate is
+ // the page the reference names - the same first-existing rule the
+ // ingest window resolver applies - so hiding one does not hide the
+ // other.
+ writeFileSync(join(vault, "Brain", "notes", "dual"), "bare twin\n");
+ const view = artifactRefView(vault, (rel) => rel !== "Brain/notes/dual");
+ expect(view.visible("[[Brain/notes/dual]]")).toBe(false);
+ expect(view.visible("[[Brain/notes/dual.md]]")).toBe(true);
+ });
+
+ test("a spelling naming no page names nothing here, and stays visible", () => {
+ // A convention like `Notes/<slug>-applied` in a log payload is not a
+ // page: with neither candidate on disk the reference resolves to
+ // nothing and the row keeps today's visibility, instead of inheriting
+ // the verdict of the missing `.md` page it used to resolve to. The
+ // rule therefore hides that twin too - the verdict the reference must
+ // NOT inherit now that it names nothing.
+ const view = artifactRefView(
+ vault,
+ (rel) => rel !== `${HIDDEN_PAGE_REL}.md` && rel !== "Brain/notes/never-written.md",
+ );
+ expect(view.visible("[[Brain/notes/never-written]]")).toBe(true);
+ expect(view.visible("Brain/notes/never-written")).toBe(true);
+ });
+
+ test("a bare spelling naming a directory is never judged as a page", () => {
+ // The bare candidate must be a regular file: a directory the rule
+ // withholds (Brain/inbox, a convention folder) is not a page, and a
+ // reference to it keeps today's visibility instead of dropping the
+ // rows that carry it.
+ mkdirSync(join(vault, "Brain", "notes", "shaped"), { recursive: true });
+ const view = artifactRefView(
+ vault,
+ (rel) => rel !== `${HIDDEN_PAGE_REL}.md` && rel !== "Brain/notes/shaped",
+ );
+ expect(view.visible("[[Brain/notes/shaped]]")).toBe(true);
+ expect(view.visible("Brain/notes/shaped")).toBe(true);
+ });
+
+ test("a bare id spelling is never read as a path", () => {
+ // Ids keep the artifact-directory resolution: an extensionless id
+ // that resolves to no artifact still names nothing.
+ expect(hidingView().visible("pref-never-existed")).toBe(true);
+ });
+});
+
describe("a reference that leaves the vault", () => {
test("is hidden without asking the rule, so nothing beside the vault is read", () => {
const asked: string[] = [];
diff --git a/tests/core/brain/coupling-surfaces.test.ts b/tests/core/brain/coupling-surfaces.test.ts
new file mode 100644
index 00000000..185fbd67
--- /dev/null
+++ b/tests/core/brain/coupling-surfaces.test.ts
@@ -0,0 +1,218 @@
+/**
+ * Serve-with-correction coupling across the Brain serving surfaces
+ * (truth-correctable-time-aware, Task 19).
+ *
+ * Every surface that serves a retired-but-serveable record decides
+ * through `couplingVerdict`: the record appears only beside its
+ * resolved, readable chain-tip correction and is dropped fail-closed
+ * otherwise - a withheld correction takes its predecessor with it. The
+ * surfaces covered here are recall by topic (`queryByTopic`), the
+ * context pack, the active.md digest and the dream scan.
+ *
+ * Today's exclusion wiring is pinned too: a tombstoned retired record
+ * stays hidden everywhere (the status filter's job, before any coupling
+ * question arises), a retired record with no successor pointer is not in
+ * the predicate's regime and keeps today's behavior, and every surface's
+ * non-retired output is unchanged.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { queryByTopic } from "../../../src/core/brain/query.ts";
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+import { renderActive } from "../../../src/core/brain/active.ts";
+import { scanBrain } from "../../../src/core/brain/dream-scan.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-coupling-surfaces-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-coupling-surfaces-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** Frontmatter lines plus body of a retired record, written vault-relative. */
+function writeRetired(
+ id: string,
+ fields: { topic: string; supersededBy?: string; tombstoned?: boolean },
+): void {
+ const lines = [
+ "---",
+ "kind: brain-retired",
+ `id: ${id}`,
+ // Group C fields use the `_`-prefixed shape on disk; a tombstoned
+ // record carries the tombstone status in the same field, which is
+ // what the shared exclusion predicate reads.
+ fields.tombstoned === true ? "_status: tombstoned" : "_status: retired",
+ "retired_at: 2026-06-01T00:00:00Z",
+ "retired_reason: stale-no-evidence",
+ "retired_by: '[[Brain/log/2026-06-01]]'",
+ "created_at: 2026-05-01T00:00:00Z",
+ "tags: [brain, brain/retired]",
+ `topic: ${fields.topic}`,
+ `principle: Retired rule for ${fields.topic}.`,
+ "pinned: false",
+ ...(fields.tombstoned ? ["tombstoned_at: 2026-06-02T00:00:00Z"] : []),
+ ...(fields.supersededBy !== undefined ? [`superseded_by: "[[${fields.supersededBy}]]"`] : []),
+ "---",
+ "",
+ "The retired body text.",
+ "",
+ ].join("\n");
+ writeFileSync(join(brainDirs(vault).retired, `${id}.md`), lines);
+}
+
+/** A preference page, the usual shape of a correction. */
+function writePreferencePage(id: string, topic: string, supersededBy?: string): void {
+ const lines = [
+ "---",
+ "kind: brain-preference",
+ `id: ${id}`,
+ "_status: confirmed",
+ "created_at: 2026-06-02T00:00:00Z",
+ "unconfirmed_until: 2026-06-02T00:00:00Z",
+ "_confirmed_at: 2026-06-02T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ `topic: ${topic}`,
+ `principle: Live rule for ${topic}.`,
+ "pinned: false",
+ ...(supersededBy !== undefined ? [`superseded_by: "[[${supersededBy}]]"`] : []),
+ "---",
+ "",
+ `The live body for ${topic}.`,
+ "",
+ ].join("\n");
+ mkdirSync(brainDirs(vault).preferences, { recursive: true });
+ writeFileSync(join(brainDirs(vault).preferences, `${id}.md`), lines);
+}
+
+describe("recall by topic", () => {
+ test("a retired record with a resolved, readable correction stays recallable", () => {
+ writePreferencePage("pref-new", "alpha-v2");
+ writeRetired("ret-old", { topic: "alpha", supersededBy: "pref-new" });
+
+ const out = queryByTopic(vault, "alpha");
+ expect(out.preference?.id).toBe("ret-old");
+ });
+
+ test("a retired record whose correction is unresolved is dropped fail-closed", () => {
+ writeRetired("ret-dangling", { topic: "beta", supersededBy: "pref-ghost" });
+
+ const out = queryByTopic(vault, "beta");
+ expect(out.preference).toBeNull();
+ });
+
+ test("a retired record with no successor pointer keeps today's behavior", () => {
+ writeRetired("ret-plain", { topic: "gamma" });
+
+ const out = queryByTopic(vault, "gamma");
+ expect(out.preference?.id).toBe("ret-plain");
+ });
+
+ test("a tombstoned retired record stays hidden even with a resolved correction", () => {
+ writePreferencePage("pref-new", "delta-v2");
+ writeRetired("ret-dead", { topic: "delta", supersededBy: "pref-new", tombstoned: true });
+
+ const out = queryByTopic(vault, "delta");
+ expect(out.preference).toBeNull();
+ });
+
+ test("non-retired output is unchanged: the correction itself still resolves", () => {
+ writePreferencePage("pref-new", "alpha-v2");
+ writeRetired("ret-old", { topic: "alpha", supersededBy: "pref-new" });
+
+ const out = queryByTopic(vault, "alpha-v2");
+ expect(out.preference?.id).toBe("pref-new");
+ });
+});
+
+describe("context pack", () => {
+ test("historical injection keeps a superseded ancestor beside its resolved correction", () => {
+ writePreferencePage("pref-tip", "tip topic");
+ writePreferencePage("pref-anc", "ancestor topic", "pref-tip");
+
+ const historical = packContext(vault, { maxTokens: 4000, includeHistorical: true });
+ const ids = historical.items.map((i) => i.id).toSorted();
+ expect(ids).toEqual(["pref-anc", "pref-tip"]);
+ });
+
+ test("historical injection drops an ancestor whose correction is unresolved", () => {
+ writePreferencePage("pref-anc-dangling", "dangling topic", "pref-ghost");
+
+ const historical = packContext(vault, { maxTokens: 4000, includeHistorical: true });
+ expect(historical.items.map((i) => i.id)).not.toContain("pref-anc-dangling");
+ });
+
+ test("default injection still serves only chain tips, unchanged", () => {
+ writePreferencePage("pref-tip", "tip topic");
+ writePreferencePage("pref-anc", "ancestor topic", "pref-tip");
+ writePreferencePage("pref-plain", "plain topic");
+
+ const out = packContext(vault, { maxTokens: 4000 });
+ const ids = out.items.map((i) => i.id).toSorted();
+ expect(ids).toEqual(["pref-plain", "pref-tip"]);
+ });
+});
+
+describe("active.md digest", () => {
+ test("the digest keeps a retired record whose correction resolves", () => {
+ writePreferencePage("pref-new", "epsilon-v2");
+ writeRetired("ret-old", { topic: "epsilon", supersededBy: "pref-new" });
+
+ const body = renderActive(vault).body;
+ expect(body).toContain("ret-old");
+ });
+
+ test("the digest drops a retired record whose correction is unresolved", () => {
+ writeRetired("ret-dangling", { topic: "zeta", supersededBy: "pref-ghost" });
+
+ const body = renderActive(vault).body;
+ expect(body).not.toContain("ret-dangling");
+ });
+
+ test("a retired record with no successor pointer keeps today's rendering", () => {
+ writeRetired("ret-plain", { topic: "eta" });
+
+ const body = renderActive(vault).body;
+ expect(body).toContain("ret-plain");
+ });
+});
+
+describe("dream scan", () => {
+ test("the scan keeps a retired record whose correction resolves", () => {
+ writePreferencePage("pref-new", "theta-v2");
+ writeRetired("ret-old", { topic: "theta", supersededBy: "pref-new" });
+
+ const scan = scanBrain(vault);
+ expect(scan.retired.map((r) => r.id)).toContain("ret-old");
+ });
+
+ test("the scan drops a retired record whose correction is unresolved", () => {
+ writeRetired("ret-dangling", { topic: "iota", supersededBy: "pref-ghost" });
+
+ const scan = scanBrain(vault);
+ expect(scan.retired.map((r) => r.id)).not.toContain("ret-dangling");
+ });
+
+ test("a retired record with no successor pointer is scanned as before", () => {
+ writeRetired("ret-plain", { topic: "kappa" });
+
+ const scan = scanBrain(vault);
+ expect(scan.retired.map((r) => r.id)).toContain("ret-plain");
+ });
+});
diff --git a/tests/core/brain/lifecycle/correction.test.ts b/tests/core/brain/lifecycle/correction.test.ts
new file mode 100644
index 00000000..4a262bf4
--- /dev/null
+++ b/tests/core/brain/lifecycle/correction.test.ts
@@ -0,0 +1,903 @@
+/**
+ * The correct-verb sweep core (truth-correctable-time-aware, Task 16).
+ *
+ * One verb corrects one record: discovery gathers the affected set
+ * within the caller's reach (the claim-graph closure over
+ * `whatReplaced`/`whatContests`, a match-only wikilink mention scan,
+ * and the same-entity/aspect truth-ledger claims), a dry run writes
+ * nothing and returns that blast-radius report, and the applied run
+ * retires the target through the correction end-state policy, retargets
+ * mentions with per-write failure carry, appends ledger correction
+ * events under the corrected record's own source (same-source value
+ * change reads as self-correction in the fold, never a conflict), and
+ * emits bundle-correlated receipts with
+ * `correction_bundle:<bundleId>` in `evidence_triggers`.
+ *
+ * Pinned too: replay converges (no double retirement, receipts report
+ * `appended: false`, a closed window stays closed), Brain/log and
+ * receipt lines are never rewritten, a target outside the caller's
+ * reach is refused as missing before anything is written, and every
+ * write passes the vault-identity guard.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { brainDirs } from "../../../../src/core/brain/paths.ts";
+import { appendLogEvent } from "../../../../src/core/brain/log.ts";
+import { CorrectionError, correct } from "../../../../src/core/brain/lifecycle/correction.ts";
+import { parseFrontmatter } from "../../../../src/core/vault.ts";
+import { appendClaimEvent, readClaimEvents } from "../../../../src/core/brain/truth/store.ts";
+import { computeTruthStateWithConflicts } from "../../../../src/core/brain/truth/conflicts.ts";
+import { readDecisionChangeReceipts } from "../../../../src/core/brain/decisions/receipts.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+const NOW = new Date("2026-06-15T12:00:00Z");
+const CORRECTION_TS = "2026-06-15T12:00:00Z";
+const TARGET = "Brain/preferences/pref-old.md";
+const TARGET_SOURCE = "[[Brain/preferences/pref-old.md]]";
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-correction-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-correction-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** Seed the target record, its successor, a mentioning page and one claim. */
+function seedTarget(): void {
+ mkdirSync(brainDirs(vault).preferences, { recursive: true });
+ writeFileSync(
+ join(vault, TARGET),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-old",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-01T00:00:00Z",
+ "_confirmed_at: 2026-05-01T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ "topic: deploy-timeout",
+ "principle: Deploy timeout stays at thirty seconds.",
+ "pinned: false",
+ "---",
+ "",
+ "The rule body for the deploy timeout.",
+ "",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "Brain/preferences/pref-new.md"),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-new",
+ "_status: confirmed",
+ "created_at: 2026-06-10T00:00:00Z",
+ "unconfirmed_until: 2026-06-10T00:00:00Z",
+ "_confirmed_at: 2026-06-10T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ "topic: deploy-timeout",
+ "principle: Deploy timeout is two minutes.",
+ "pinned: false",
+ "---",
+ "",
+ "The corrected rule body.",
+ "",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "Brain/preferences/pref-other.md"),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-other",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-01T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: unrelated",
+ "principle: Mentions [[pref-old]] in prose.",
+ "pinned: false",
+ "---",
+ "",
+ "See [[pref-old]] for the old rule.",
+ "",
+ ].join("\n"),
+ );
+ appendClaimEvent(
+ vault,
+ {
+ ts: "2026-05-02T00:00:00Z",
+ agent: "tester",
+ entity: "deploy timeout",
+ aspect: "limit",
+ value: "30s",
+ source: TARGET_SOURCE,
+ },
+ { configPath },
+ );
+}
+
+/** The target's frontmatter after a run. */
+function targetMeta(): Record<string, unknown> {
+ return parseFrontmatter(join(vault, TARGET))[0] as Record<string, unknown>;
+}
+
+function logFiles(): string[] {
+ const dir = join(vault, "Brain", "log");
+ if (!existsSync(dir)) return [];
+ return readdirSync(dir)
+ .toSorted()
+ .map((name) => join(dir, name));
+}
+
+const WITHHELD_MENTION = "Brain/private/hidden-mention.md";
+
+/** Seed a page outside the test caller's reach that mentions the target. */
+function seedWithheldMention(): string {
+ mkdirSync(join(vault, "Brain", "private"), { recursive: true });
+ writeFileSync(
+ join(vault, WITHHELD_MENTION),
+ [
+ "---",
+ "kind: note",
+ "id: hidden-mention",
+ "---",
+ "",
+ "Hidden context: see [[pref-old]].",
+ "",
+ ].join("\n"),
+ );
+ return readFileSync(join(vault, WITHHELD_MENTION), "utf8");
+}
+
+/** Everything except the withheld page: the test caller's readable set. */
+function readableExceptWithheld(rel: string): boolean {
+ return rel !== WITHHELD_MENTION;
+}
+
+describe("dry run", () => {
+ test("writes nothing and returns the blast-radius report", () => {
+ seedTarget();
+ const before = readFileSync(join(vault, TARGET), "utf8");
+ const mentionBefore = readFileSync(join(vault, "Brain/preferences/pref-other.md"), "utf8");
+ const eventsBefore = readClaimEvents(vault).events.length;
+
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ });
+
+ expect(res.dryRun).toBe(true);
+ expect(res.blastRadius.target).toBe(TARGET);
+ // The closure reads the graph as it stands: the target carries no
+ // successor pointer yet, so nothing has replaced it at discovery time.
+ expect(res.blastRadius.replacedBy).toBeNull();
+ expect(res.blastRadius.mentions).toContain("Brain/preferences/pref-other.md");
+ expect(res.blastRadius.claims.map((c) => c.value)).toContain("30s");
+ expect(res.retarget.rewritten).toEqual([]);
+ expect(res.ledger).toEqual([]);
+ expect(res.retirements).toEqual([]);
+ expect(res.receipts).toEqual([]);
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe(before);
+ expect(readFileSync(join(vault, "Brain/preferences/pref-other.md"), "utf8")).toBe(
+ mentionBefore,
+ );
+ expect(readClaimEvents(vault).events.length).toBe(eventsBefore);
+ });
+});
+
+describe("reach-bounded retargeting", () => {
+ test("a restricted dry run names no out-of-reach page anywhere in the retarget report", () => {
+ seedTarget();
+ const withheldBefore = seedWithheldMention();
+
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor: "pref-new",
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ readable: readableExceptWithheld,
+ });
+
+ expect(res.dryRun).toBe(true);
+ expect(res.blastRadius.mentions).not.toContain(WITHHELD_MENTION);
+ expect(res.retarget.matched).not.toContain(WITHHELD_MENTION);
+ expect(res.retarget.failed.map((f) => f.path)).not.toContain(WITHHELD_MENTION);
+ // The withheld path is not disclosed under any other key either.
+ expect(JSON.stringify(res)).not.toContain("hidden-mention");
+ expect(readFileSync(join(vault, WITHHELD_MENTION), "utf8")).toBe(withheldBefore);
+ });
+
+ test("a restricted applied run leaves out-of-reach pages unwritten and unnamed", () => {
+ seedTarget();
+ const withheldBefore = seedWithheldMention();
+
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ readable: readableExceptWithheld,
+ });
+
+ expect(res.retarget.matched).not.toContain(WITHHELD_MENTION);
+ expect(res.retarget.rewritten).not.toContain(WITHHELD_MENTION);
+ expect(res.retarget.failed.map((f) => f.path)).not.toContain(WITHHELD_MENTION);
+ expect(JSON.stringify(res)).not.toContain("hidden-mention");
+ // No content injection into the withheld page: its bytes are unchanged.
+ expect(readFileSync(join(vault, WITHHELD_MENTION), "utf8")).toBe(withheldBefore);
+ // In-reach mentions are still retargeted.
+ expect(res.retarget.rewritten).toContain("Brain/preferences/pref-other.md");
+ });
+});
+
+describe("claims reach gate", () => {
+ test("slot claims sourced to readable extension-bearing paths stay in the blast radius", () => {
+ seedTarget();
+ // A second claim in the target's own slot, sourced to the readable
+ // mentioning page with the extension-bearing spelling every other
+ // caller hands the readable predicate (claim-graph node paths,
+ // mention-scan paths).
+ appendClaimEvent(
+ vault,
+ {
+ ts: "2026-05-03T00:00:00Z",
+ agent: "tester",
+ entity: "deploy timeout",
+ aspect: "limit",
+ value: "45s",
+ source: "[[Brain/preferences/pref-other.md]]",
+ },
+ { configPath },
+ );
+ // And one sourced to a page the caller may not read.
+ const withheldSource = "Brain/private/hidden-source.md";
+ mkdirSync(join(vault, "Brain", "private"), { recursive: true });
+ writeFileSync(
+ join(vault, withheldSource),
+ ["---", "kind: note", "id: hidden-source", "---", "", "Hidden.", ""].join("\n"),
+ );
+ appendClaimEvent(
+ vault,
+ {
+ ts: "2026-05-04T00:00:00Z",
+ agent: "tester",
+ entity: "deploy timeout",
+ aspect: "limit",
+ value: "15s",
+ source: `[[${withheldSource}]]`,
+ },
+ { configPath },
+ );
+
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor: "pref-new",
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ // The predicate answers the extension-bearing spellings the other
+ // callers pass, so a claim's source must arrive in that shape.
+ readable: (rel) => rel.endsWith(".md") && rel !== withheldSource,
+ });
+
+ const values = res.blastRadius.claims.map((c) => c.value);
+ expect(values).toContain("30s"); // the target's own claim
+ expect(values).toContain("45s"); // readable, extension-bearing source
+ expect(values).not.toContain("15s"); // withheld source stays out
+ });
+
+ test("a same-named page in another folder is never the target, reach gate or not", () => {
+ seedTarget();
+ // A second page sharing the target's basename but not its folder,
+ // seeded with a claim in the target's own slot. A basename fold of
+ // the source matched it as the target's own event, so its claim
+ // entered the blast radius without passing the reach gate and its
+ // source could stand in for the target's on an applied correction.
+ const impostor = "Brain/private/pref-old.md";
+ mkdirSync(join(vault, "Brain", "private"), { recursive: true });
+ writeFileSync(
+ join(vault, impostor),
+ ["---", "kind: note", "id: pref-old", "---", "", "An unrelated page.", ""].join("\n"),
+ );
+ appendClaimEvent(
+ vault,
+ {
+ ts: "2026-05-05T00:00:00Z",
+ agent: "tester",
+ entity: "deploy timeout",
+ aspect: "limit",
+ value: "impostor",
+ source: `[[${impostor}]]`,
+ },
+ { configPath },
+ );
+
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor: "pref-new",
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ readable: (rel) => rel.endsWith(".md") && rel !== impostor,
+ });
+
+ // The impostor is not the target and is withheld: neither its claim
+ // nor any slot attribution of the target's own claim may name it.
+ const values = res.blastRadius.claims.map((c) => c.value);
+ expect(values).toContain("30s"); // the target's own claim
+ expect(values).not.toContain("impostor");
+ for (const claimRow of res.blastRadius.claims) {
+ expect(claimRow.source).not.toContain(impostor);
+ }
+ });
+});
+
+describe("applied run", () => {
+ test("validity-close retires the target and retargets mentions", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ expect(res.dryRun).toBe(false);
+ const retirement = res.retirements[0]!;
+ expect(retirement.endState).toBe("validity_close");
+ expect(retirement.reasonCode).toBe("supersede");
+ expect(retirement.validUntil).toBe(CORRECTION_TS);
+ expect(retirement.changed).toBe(true);
+
+ const meta = targetMeta();
+ expect(meta["_status"]).toBe("confirmed");
+ expect(meta["valid_until"]).toBe(CORRECTION_TS);
+ expect(meta["superseded_by"]).toBe("[[pref-new]]");
+
+ expect(res.retarget.rewritten).toContain("Brain/preferences/pref-other.md");
+ expect(readFileSync(join(vault, "Brain/preferences/pref-other.md"), "utf8")).toContain(
+ "[[pref-new]]",
+ );
+ });
+
+ test("a flatly-wrong correction tombstones with a null window end", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "the number was never thirty seconds",
+ successor: "pref-new",
+ flatlyWrong: true,
+ reason: "fabricated figure",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ const retirement = res.retirements[0]!;
+ expect(retirement.endState).toBe("tombstone");
+ expect(retirement.reasonCode).toBe("tombstone");
+ expect(retirement.validUntil).toBeNull();
+ expect(targetMeta()["_status"]).toBe("tombstoned");
+ });
+
+ test("ledger correction events keep the corrected record's source and never conflict", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ expect(res.ledger).toEqual([
+ { entity: "deploy timeout", aspect: "limit", value: "two minutes", source: TARGET_SOURCE },
+ ]);
+ const events = readClaimEvents(vault).events;
+ const corrected = events.find((e) => e.value === "two minutes");
+ expect(corrected).toBeDefined();
+ expect(corrected!.source).toBe(TARGET_SOURCE);
+ expect(corrected!.entity).toBe("deploy timeout");
+ expect(corrected!.aspect).toBe("limit");
+ expect(corrected!.validFrom).toBe(CORRECTION_TS);
+
+ // Same-source value change reads as self-correction in the fold:
+ // the slot carries no conflict after the sweep.
+ const state = computeTruthStateWithConflicts(events);
+ expect(state.conflicts).toEqual([]);
+ });
+
+ test("receipts carry the bundle id in evidence_triggers", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ const trigger = `correction_bundle:${res.bundleId}`;
+ expect(trigger.startsWith("correction_bundle:")).toBe(true);
+ const receipts = readDecisionChangeReceipts(vault).receipts;
+ const bundled = receipts.filter((r) => r.evidence_triggers.includes(trigger));
+ expect(bundled.length).toBeGreaterThanOrEqual(1);
+ const retirement = bundled.find((r) => r.subject === TARGET);
+ expect(retirement).toBeDefined();
+ expect(retirement!.reason_code).toBe("supersede");
+ expect(retirement!.before).toBe("status:confirmed");
+ expect(retirement!.after).toBe(`validity_close until ${CORRECTION_TS}`);
+ });
+
+ test("Brain/log lines are never rewritten, even when they mention the target", () => {
+ seedTarget();
+ appendLogEvent(vault, {
+ timestamp: "2026-06-01T00:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-old]]", agent: "tester" },
+ });
+ const logBefore = logFiles()
+ .map((f) => readFileSync(f, "utf8"))
+ .join("");
+
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ const logAfter = logFiles()
+ .map((f) => readFileSync(f, "utf8"))
+ .join("");
+ expect(logAfter).toContain("[[pref-old]]");
+ // The pre-existing testimony is byte-identical; the sweep may only append.
+ expect(logAfter.startsWith(logBefore)).toBe(true);
+ });
+
+ test("every target a caller may not read is refused as missing before anything is written", () => {
+ seedTarget();
+ const before = readFileSync(join(vault, TARGET), "utf8");
+ expect(() =>
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ readable: (rel) => rel !== TARGET,
+ }),
+ ).toThrow(CorrectionError);
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe(before);
+ });
+
+ test("a receipt-ask failure is reported, not fatal: the retirement lands and the sweep succeeds", () => {
+ seedTarget();
+ // The receipt shard's path is shadowed by a directory, so every
+ // decision-change receipt ask throws (the file cannot be appended
+ // to) - the same accountability-log hiccup the tombstone
+ // pre-receipt's fail-soft discipline in this sweep anticipates.
+ mkdirSync(join(vault, "Brain", "truth", "decision-change.jsonl"), { recursive: true });
+
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ // The applied sweep completed: the retirement is on the record, the
+ // mentions are retargeted and the ledger correction event landed.
+ expect(targetMeta()["valid_until"]).toBe(CORRECTION_TS);
+ expect(targetMeta()["superseded_by"]).toBe("[[pref-new]]");
+ expect(res.retirements[0]!.changed).toBe(true);
+ expect(res.retarget.rewritten).toContain("Brain/preferences/pref-other.md");
+ expect(res.ledger).toHaveLength(1);
+ // The failed asks are reported as not appended, never thrown.
+ expect(res.receipts.length).toBeGreaterThan(0);
+ expect(res.receipts.every((r) => r.appended === false)).toBe(true);
+ });
+
+ test("a target naming no file is refused", () => {
+ seedTarget();
+ expect(() =>
+ correct({
+ vault,
+ configPath,
+ target: "Brain/preferences/pref-absent.md",
+ value: "two minutes",
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ }),
+ ).toThrow(CorrectionError);
+ });
+});
+
+describe("successor input", () => {
+ test("a successor that normalizes to empty is refused on a dry run", () => {
+ seedTarget();
+ // `|||` normalizes to the empty id (pipe-stripped), as does a fence
+ // with only an alias; either would otherwise flow into the pointer
+ // and retarget writes as a malformed `[[]]`.
+ for (const successor of ["|||", "[[|alias]]"]) {
+ expect(() =>
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor,
+ reason: "the timeout changed",
+ now: NOW,
+ agent: "tester",
+ }),
+ ).toThrow(CorrectionError);
+ }
+ });
+
+ test("a successor that normalizes to empty is refused on an applied run and writes nothing", () => {
+ seedTarget();
+ const before = readFileSync(join(vault, TARGET), "utf8");
+ const eventsBefore = readClaimEvents(vault).events.length;
+ expect(() =>
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "|||",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ }),
+ ).toThrow(CorrectionError);
+ // The refusal precedes every write: no malformed superseded_by
+ // pointer, no ledger correction event.
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe(before);
+ expect(readClaimEvents(vault).events.length).toBe(eventsBefore);
+ });
+});
+
+describe("replay convergence", () => {
+ test("a flatly-wrong replay over an already-closed window is a named refusal, not an internal error", () => {
+ // First sweep validity-closes the target at the correction instant.
+ seedTarget();
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+ const metaAfterFirst = targetMeta();
+ const eventsAfterFirst = readClaimEvents(vault).events;
+
+ // The replay flips the end-state policy to tombstone, so the record
+ // does not read as already-retired; the ledger correction then
+ // resolves its open until-bound from the record's own frontmatter -
+ // the close this very sweep wrote - and the window inverts. The
+ // replay has converged, so the sweep must refuse by name rather
+ // than let the store's internal-class refusal escape mid-replay.
+ let refused: unknown;
+ try {
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "the number was never thirty seconds",
+ flatlyWrong: true,
+ reason: "fabricated figure",
+ dryRun: false,
+ now: new Date("2026-06-16T12:00:00Z"),
+ agent: "tester",
+ });
+ } catch (err) {
+ refused = err;
+ }
+ expect(refused).toBeInstanceOf(CorrectionError);
+ expect((refused as Error).name).toBe("CorrectionError");
+ expect((refused as Error).message).toContain("already validity-closed");
+ expect((refused as Error).message).toContain(CORRECTION_TS);
+
+ // The refusal is strict: the retirement write never ran, so the
+ // record keeps its closed window and confirmed status, and the
+ // ledger carries no correction event from the aborted replay.
+ const metaAfterSecond = targetMeta();
+ expect(metaAfterSecond["valid_until"]).toBe(metaAfterFirst["valid_until"]);
+ expect(metaAfterSecond["_status"]).toBe("confirmed");
+ expect(metaAfterSecond["superseded_by"]).toBe(metaAfterFirst["superseded_by"]);
+ const eventsAfterSecond = readClaimEvents(vault).events;
+ expect(
+ eventsAfterSecond.filter((e) => e.value === "the number was never thirty seconds"),
+ ).toHaveLength(0);
+ expect(eventsAfterSecond.length).toBe(eventsAfterFirst.length);
+ });
+
+ test("a second run retires nothing, re-appends nothing and reports appended receipts", () => {
+ seedTarget();
+ const first = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+ const metaAfterFirst = targetMeta();
+ const eventsAfterFirst = readClaimEvents(vault).events;
+
+ const second = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: new Date("2026-06-16T12:00:00Z"),
+ agent: "tester",
+ });
+
+ expect(second.retirements[0]!.changed).toBe(false);
+ // The closed window stays closed at the original instant.
+ expect(targetMeta()["valid_until"]).toBe(metaAfterFirst["valid_until"]);
+ // The ledger keeps one correction event: a re-assertion is not a new fact.
+ const eventsAfterSecond = readClaimEvents(vault).events;
+ expect(
+ eventsAfterSecond.filter((e) => e.value === "two minutes" && e.source === TARGET_SOURCE)
+ .length,
+ ).toBe(eventsAfterFirst.filter((e) => e.value === "two minutes").length);
+ // The receipts report the replay as appended: false.
+ expect(second.receipts.every((r) => r.appended === false)).toBe(true);
+ expect(first.receipts.length).toBeGreaterThan(0);
+ });
+});
+
+describe("tombstone receipts", () => {
+ test("a fresh flatly-wrong run without a successor emits exactly one retirement receipt carrying the bundle trigger", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "the number was never thirty seconds",
+ flatlyWrong: true,
+ reason: "fabricated figure",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ const receipts = readDecisionChangeReceipts(vault).receipts.filter((r) => r.subject === TARGET);
+ // The shared tombstone writer's own receipt and the sweep's bundle
+ // receipt are the SAME retirement: one receipt lands, and it carries
+ // the bundle trigger no other writer could have supplied.
+ expect(receipts.length).toBe(1);
+ expect(receipts[0]!.evidence_triggers).toContain(`correction_bundle:${res.bundleId}`);
+ expect(receipts[0]!.after).toBe("status:tombstoned");
+ expect(receipts[0]!.before).toBe("status:confirmed");
+ const retirementReceipt = res.receipts.find((r) => r.subject === TARGET);
+ expect(retirementReceipt!.appended).toBe(true);
+ });
+
+ test("a fresh flatly-wrong run with a successor emits exactly one retirement receipt carrying the bundle trigger", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "the number was never thirty seconds",
+ successor: "pref-new",
+ flatlyWrong: true,
+ reason: "fabricated figure",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+
+ const receipts = readDecisionChangeReceipts(vault).receipts.filter((r) => r.subject === TARGET);
+ expect(receipts.length).toBe(1);
+ expect(receipts[0]!.evidence_triggers).toContain(`correction_bundle:${res.bundleId}`);
+ // The pointer spelling matches the retirement's superseded_by pointer.
+ expect(receipts[0]!.after).toBe("status:tombstoned superseded_by:[[pref-new]]");
+ });
+
+ test("an applied flatly-wrong replay reports the retirement and its receipt as not appended", () => {
+ seedTarget();
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "the number was never thirty seconds",
+ flatlyWrong: true,
+ reason: "fabricated figure",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+ const receiptsAfterFirst = readDecisionChangeReceipts(vault).receipts.filter(
+ (r) => r.subject === TARGET,
+ );
+
+ const second = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ value: "the number was never thirty seconds",
+ flatlyWrong: true,
+ reason: "fabricated figure",
+ dryRun: false,
+ now: new Date("2026-06-16T12:00:00Z"),
+ agent: "tester",
+ });
+
+ expect(second.retirements[0]!.changed).toBe(false);
+ // The replay reports the retirement receipt as not appended, instead
+ // of minting a fresh no-change receipt under a mutated idempotency key.
+ expect(second.receipts.length).toBeGreaterThan(0);
+ expect(second.receipts.some((r) => r.subject === TARGET)).toBe(true);
+ expect(second.receipts.every((r) => r.appended === false)).toBe(true);
+ const receiptsAfterSecond = readDecisionChangeReceipts(vault).receipts.filter(
+ (r) => r.subject === TARGET,
+ );
+ expect(receiptsAfterSecond.length).toBe(receiptsAfterFirst.length);
+ });
+});
+
+describe("optional inputs", () => {
+ test("a correction with no corrected value appends nothing to the ledger", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+ expect(res.ledger).toEqual([]);
+ expect(res.retirements[0]!.endState).toBe("validity_close");
+ });
+
+ test("an explicit window end closes validity there instead of at the correction instant", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor: "pref-new",
+ windowEnd: "2026-07-01T00:00:00Z",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+ expect(res.retirements[0]!.validUntil).toBe("2026-07-01T00:00:00Z");
+ expect(targetMeta()["valid_until"]).toBe("2026-07-01T00:00:00Z");
+ });
+
+ test("a malformed window end is refused before anything is written", () => {
+ seedTarget();
+ const before = readFileSync(join(vault, TARGET), "utf8");
+ const eventsBefore = readClaimEvents(vault).events.length;
+ // The shapes the ledger append boundary refuses: relative phrases,
+ // offset-bearing datetimes, empty strings.
+ for (const bad of ["next tuesday", "2026-07-01T00:00:00+02:00", ""]) {
+ expect(() =>
+ correct({
+ vault,
+ configPath,
+ target: TARGET,
+ windowEnd: bad,
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ }),
+ ).toThrow(CorrectionError);
+ }
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe(before);
+ expect(readClaimEvents(vault).events.length).toBe(eventsBefore);
+ });
+
+ test("a bare ISO date window end is accepted, matching the ledger grammar", () => {
+ seedTarget();
+ const res = correct({
+ vault,
+ configPath,
+ target: TARGET,
+ successor: "pref-new",
+ windowEnd: "2026-07-01",
+ reason: "the timeout changed",
+ dryRun: false,
+ now: NOW,
+ agent: "tester",
+ });
+ expect(res.retirements[0]!.validUntil).toBe("2026-07-01");
+ expect(targetMeta()["valid_until"]).toBe("2026-07-01");
+ });
+});
diff --git a/tests/core/brain/truth/conflicts.test.ts b/tests/core/brain/truth/conflicts.test.ts
index 486f4613..b42ceb54 100644
--- a/tests/core/brain/truth/conflicts.test.ts
+++ b/tests/core/brain/truth/conflicts.test.ts
@@ -122,3 +122,104 @@ describe("computeTruthStateWithConflicts", () => {
expect(computeTruthStateWithConflicts([])).toEqual(computeTruthState([]));
});
});
+
+describe("succession channel", () => {
+ test("present non-overlapping windows classify as succession, never a conflict", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ const state = computeTruthStateWithConflicts(events);
+ // Five days apart from distinct sources: the assertion-time rule
+ // would contest; the disjoint windows make it a succession.
+ expect(state.conflicts).toHaveLength(0);
+ expect(state.slots[0]!.contested).toBe(false);
+ expect(state.successions).toHaveLength(1);
+ expect(state.successions![0]!.predecessor.value).toBe("Google");
+ expect(state.successions![0]!.successor.value).toBe("Meta");
+ });
+
+ test("intersecting windows fall through to the contest rule verbatim", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2026-06-01" }),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ const state = computeTruthStateWithConflicts(events);
+ expect(state.conflicts).toHaveLength(1);
+ expect(state.successions).toBeUndefined();
+ });
+
+ test("any windowless claim falls through to the contest rule verbatim", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({ value: "Meta", source: "[[Brain/notes/later.md]]" }),
+ ];
+ const state = computeTruthStateWithConflicts(events);
+ expect(state.conflicts).toHaveLength(1);
+ expect(state.successions).toBeUndefined();
+ });
+
+ test("an expired window never suppresses contestation on its own", () => {
+ // The expired window intersects the successor's open window, so the
+ // pair keeps the assertion-time contest despite the expiry.
+ const events = [
+ claim({ validFrom: "2020-01-01", validUntil: "2021-01-01" }),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2020-06-01",
+ }),
+ ];
+ const state = computeTruthStateWithConflicts(events);
+ expect(state.conflicts).toHaveLength(1);
+ expect(state.successions).toBeUndefined();
+ });
+
+ test("successions appear even when nothing contests", () => {
+ const events = [
+ claim({ ts: "2026-01-01T10:00:00Z", validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ // Far apart in assertion time: no contest either way, succession still reported.
+ const state = computeTruthStateWithConflicts(events);
+ expect(state.conflicts).toHaveLength(0);
+ expect(state.successions).toHaveLength(1);
+ });
+
+ test("successions are presence-gated: absent, not empty, whenever empty", () => {
+ const state = computeTruthStateWithConflicts([
+ claim(),
+ claim({ ts: "2026-08-01T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" }),
+ ]);
+ expect("successions" in state).toBe(false);
+ expect(state.successions).toBeUndefined();
+ expect(JSON.stringify(state)).not.toContain("successions");
+ });
+
+ test("a present succession serializes by conditional spread", () => {
+ const state = computeTruthStateWithConflicts([
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ]);
+ const round = JSON.parse(JSON.stringify(state)) as { successions?: unknown[] };
+ expect(round.successions).toHaveLength(1);
+ });
+});
diff --git a/tests/core/brain/truth/correction-policy.test.ts b/tests/core/brain/truth/correction-policy.test.ts
new file mode 100644
index 00000000..d8c66c9f
--- /dev/null
+++ b/tests/core/brain/truth/correction-policy.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Correction end-state policy (truth-correctable-time-aware, contract
+ * item 2): one pure function deciding how a corrected predecessor
+ * retires. A flatly-wrong claim tombstones (hidden - nothing surfaces,
+ * correction included); every other correction closes validity at the
+ * explicit window end when time-scoped, else at the correction
+ * instant, so the predecessor stays serveable inside its historical
+ * window. Pure and deterministic - no I/O, no clock.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ correctionEndState,
+ type CorrectionEndStateInput,
+} from "../../../../src/core/brain/truth/correction-policy.ts";
+
+function input(over: Partial<CorrectionEndStateInput> = {}): CorrectionEndStateInput {
+ return { flatlyWrong: false, ...over };
+}
+
+describe("correctionEndState", () => {
+ test("a flatly-wrong claim tombstones with a null validUntil", () => {
+ expect(correctionEndState(input({ flatlyWrong: true }), "2026-06-01T10:00:00Z")).toEqual({
+ endState: "tombstone",
+ validUntil: null,
+ });
+ });
+
+ test("flatlyWrong wins over an explicit window end", () => {
+ const result = correctionEndState(
+ input({ flatlyWrong: true, windowEnd: "2026-12-31" }),
+ "2026-06-01T10:00:00Z",
+ );
+ expect(result).toEqual({ endState: "tombstone", validUntil: null });
+ });
+
+ test("a time-scoped correction closes validity at the explicit window end", () => {
+ expect(
+ correctionEndState(input({ windowEnd: "2026-12-31T23:59:59Z" }), "2026-06-01T10:00:00Z"),
+ ).toEqual({ endState: "validity_close", validUntil: "2026-12-31T23:59:59Z" });
+ });
+
+ test("a bare-date window end passes through verbatim", () => {
+ expect(correctionEndState(input({ windowEnd: "2026-12-31" }), "2026-06-01T10:00:00Z")).toEqual({
+ endState: "validity_close",
+ validUntil: "2026-12-31",
+ });
+ });
+
+ test("an unscoped correction closes validity at the correction instant", () => {
+ expect(correctionEndState(input(), "2026-06-01T10:00:00Z")).toEqual({
+ endState: "validity_close",
+ validUntil: "2026-06-01T10:00:00Z",
+ });
+ });
+
+ test("results are pure and deterministic across calls", () => {
+ const first = correctionEndState(input({ windowEnd: "2026-12-31" }), "2026-06-01T10:00:00Z");
+ const second = correctionEndState(input({ windowEnd: "2026-12-31" }), "2026-06-01T10:00:00Z");
+ expect(first).toEqual(second);
+ expect(first).not.toBe(second);
+ // The input object is never mutated.
+ const probe: CorrectionEndStateInput = { flatlyWrong: false, windowEnd: "2026-12-31" };
+ correctionEndState(probe, "2026-06-01T10:00:00Z");
+ expect(probe).toEqual({ flatlyWrong: false, windowEnd: "2026-12-31" });
+ });
+});
diff --git a/tests/core/brain/truth/events-window.test.ts b/tests/core/brain/truth/events-window.test.ts
new file mode 100644
index 00000000..0ff3eaf0
--- /dev/null
+++ b/tests/core/brain/truth/events-window.test.ts
@@ -0,0 +1,212 @@
+/**
+ * `selectClaimEvents` / `eventsWindowBounds` (pure events-window
+ * selection for the brain_truth `events` operation): second-precision
+ * `ts` bounds, the normalized-entity filter, and the named list limits.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ CLAIM_EVENT_MAX_LIST_LIMIT,
+ DEFAULT_EVENT_LIST_LIMIT,
+ eventsWindowBounds,
+ selectClaimEvents,
+} from "../../../../src/core/brain/truth/events-window.ts";
+import { isoSecond } from "../../../../src/core/brain/time.ts";
+import { TRUTH_SCHEMA_VERSION, type ClaimEvent } from "../../../../src/core/brain/truth/types.ts";
+
+function claimEvent(
+ overrides: Partial<ClaimEvent> & Pick<ClaimEvent, "ts" | "entity">,
+): ClaimEvent {
+ return Object.freeze({
+ v: TRUTH_SCHEMA_VERSION,
+ agent: "claude",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[Brain/notes/a.md]]",
+ ...overrides,
+ });
+}
+
+/**
+ * A claim carrying validity fields, built through a JSON round-trip so
+ * this suite compiles before and after the optional validity fields land
+ * on `ClaimEvent` (contract item 1).
+ */
+function windowed(e: ClaimEvent, validFrom: string, validUntil: string): ClaimEvent {
+ return JSON.parse(JSON.stringify({ ...e, validFrom, validUntil })) as ClaimEvent;
+}
+
+const T0 = Date.UTC(2026, 4, 1, 10, 0, 0);
+
+describe("eventsWindowBounds", () => {
+ test("open bounds pass through as null", () => {
+ expect(eventsWindowBounds(null, null)).toEqual({ since: null, until: null });
+ });
+
+ test("sub-second bounds resolve to whole-second stamps", () => {
+ const halfSecond = T0 + 500;
+ expect(eventsWindowBounds(halfSecond, halfSecond)).toEqual({
+ since: "2026-05-01T10:00:00Z",
+ until: "2026-05-01T10:00:00Z",
+ });
+ });
+
+ test("exact-second bounds keep their stamp verbatim", () => {
+ expect(eventsWindowBounds(T0, T0 + 1000)).toEqual({
+ since: "2026-05-01T10:00:00Z",
+ until: "2026-05-01T10:00:01Z",
+ });
+ });
+
+ test("non-finite bounds are refused by name, never reaching new Date(NaN)", () => {
+ // A NaN or infinite bound used to die inside toISOString() as an
+ // unnamed "Invalid time value" RangeError; the boundary refuses it
+ // with the same named style the limit validation uses, naming the
+ // offending argument.
+ expect(() => eventsWindowBounds(NaN, null)).toThrow(RangeError);
+ expect(() => eventsWindowBounds(NaN, null)).toThrow(/claim events since bound/);
+ expect(() => eventsWindowBounds(null, Number.POSITIVE_INFINITY)).toThrow(
+ /claim events until bound/,
+ );
+ expect(() => selectClaimEvents([], { sinceMs: NaN })).toThrow(/since/);
+ expect(() => selectClaimEvents([], { untilMs: NaN })).toThrow(/until/);
+ });
+});
+
+describe("selectClaimEvents", () => {
+ test("selects nothing from an empty ledger", () => {
+ expect(selectClaimEvents([], {})).toEqual({ rows: [], total: 0, truncated: false });
+ });
+
+ test("without filters every event is matched in ascending order", () => {
+ const events = [
+ claimEvent({ ts: isoSecond(new Date(T0)), entity: "alice mason" }),
+ claimEvent({ ts: isoSecond(new Date(T0 + 1000)), entity: "bob" }),
+ claimEvent({ ts: isoSecond(new Date(T0 + 2000)), entity: "alice mason" }),
+ ];
+ const out = selectClaimEvents(events, {});
+ expect(out.rows.map((e) => e.ts)).toEqual([
+ "2026-05-01T10:00:00Z",
+ "2026-05-01T10:00:01Z",
+ "2026-05-01T10:00:02Z",
+ ]);
+ expect(out.total).toBe(3);
+ expect(out.truncated).toBe(false);
+ });
+
+ test("the since bound includes the whole second it floors into", () => {
+ const events = [
+ claimEvent({ ts: "2026-05-01T09:59:59Z", entity: "a" }),
+ claimEvent({ ts: "2026-05-01T10:00:00Z", entity: "a" }),
+ claimEvent({ ts: "2026-05-01T10:00:01Z", entity: "a" }),
+ ];
+ // 10:00:00.500 floors to 10:00:00, whose events stay inside the window.
+ const out = selectClaimEvents(events, { sinceMs: T0 + 500 });
+ expect(out.rows.map((e) => e.ts)).toEqual(["2026-05-01T10:00:00Z", "2026-05-01T10:00:01Z"]);
+ });
+
+ test("the until bound includes the whole second containing it and nothing past it", () => {
+ const events = [
+ claimEvent({ ts: "2026-05-01T23:59:58Z", entity: "a" }),
+ claimEvent({ ts: "2026-05-01T23:59:59Z", entity: "a" }),
+ claimEvent({ ts: "2026-05-02T00:00:00Z", entity: "a" }),
+ ];
+ // The grammar's inclusive day edge resolves until=2026-05-01 to
+ // 23:59:59.999; the whole second containing it stays inside the
+ // window and the next day's midnight second does not.
+ const dayEndMs = Date.UTC(2026, 4, 1, 23, 59, 59, 999);
+ const out = selectClaimEvents(events, { untilMs: dayEndMs });
+ expect(out.rows.map((e) => e.ts)).toEqual(["2026-05-01T23:59:58Z", "2026-05-01T23:59:59Z"]);
+ });
+
+ test("an exact-second until bound includes an event stamped at that second", () => {
+ const events = [
+ claimEvent({ ts: "2026-05-01T10:00:00Z", entity: "a" }),
+ claimEvent({ ts: "2026-05-01T10:00:01Z", entity: "a" }),
+ ];
+ const out = selectClaimEvents(events, { untilMs: T0 });
+ expect(out.rows.map((e) => e.ts)).toEqual(["2026-05-01T10:00:00Z"]);
+ });
+
+ test("a fractional-second event stamp compares at its whole second", () => {
+ const events = [
+ claimEvent({ ts: "2026-05-01T10:00:00.500Z", entity: "a" }),
+ claimEvent({ ts: "2026-05-01T10:00:01Z", entity: "a" }),
+ ];
+ const out = selectClaimEvents(events, { sinceMs: T0, untilMs: T0 });
+ expect(out.rows.map((e) => e.ts)).toEqual(["2026-05-01T10:00:00.500Z"]);
+ });
+
+ test("the entity filter normalizes and composes with the bounds", () => {
+ const events = [
+ claimEvent({ ts: isoSecond(new Date(T0)), entity: "alice mason" }),
+ claimEvent({ ts: isoSecond(new Date(T0 + 1000)), entity: "bob" }),
+ claimEvent({ ts: isoSecond(new Date(T0 + 86_400_000)), entity: "alice mason" }),
+ ];
+ const out = selectClaimEvents(events, {
+ entity: "Alice Mason",
+ sinceMs: T0,
+ untilMs: T0 + 5000,
+ });
+ expect(out.rows).toHaveLength(1);
+ expect(out.rows[0]!.entity).toBe("alice mason");
+ expect(out.total).toBe(1);
+ });
+
+ test("an empty entity string filters nothing", () => {
+ const events = [claimEvent({ ts: isoSecond(new Date(T0)), entity: "alice mason" })];
+ expect(selectClaimEvents(events, { entity: "" }).rows).toHaveLength(1);
+ });
+
+ test("validity fields pass through verbatim on selected rows", () => {
+ const event = windowed(
+ claimEvent({ ts: isoSecond(new Date(T0)), entity: "alice mason" }),
+ "2026-01-01T00:00:00Z",
+ "2026-12-31T00:00:00Z",
+ );
+ const out = selectClaimEvents([event], {});
+ expect(out.rows).toEqual([event]);
+ expect(out.rows[0]!.validFrom).toBe("2026-01-01T00:00:00Z");
+ expect(out.rows[0]!.validUntil).toBe("2026-12-31T00:00:00Z");
+ });
+
+ test("the default limit pages the match and reports the truncation", () => {
+ const events = Array.from({ length: DEFAULT_EVENT_LIST_LIMIT + 50 }, (_, i) =>
+ claimEvent({ ts: isoSecond(new Date(T0 + i * 1000)), entity: "a" }),
+ );
+ const out = selectClaimEvents(events, {});
+ expect(out.rows).toHaveLength(DEFAULT_EVENT_LIST_LIMIT);
+ expect(out.total).toBe(DEFAULT_EVENT_LIST_LIMIT + 50);
+ expect(out.truncated).toBe(true);
+ expect(out.rows[0]!.ts).toBe(isoSecond(new Date(T0)));
+ });
+
+ test("an explicit limit under the default pages exactly that many", () => {
+ const events = Array.from({ length: 5 }, (_, i) =>
+ claimEvent({ ts: isoSecond(new Date(T0 + i * 1000)), entity: "a" }),
+ );
+ const out = selectClaimEvents(events, { limit: 3 });
+ expect(out.rows).toHaveLength(3);
+ expect(out.total).toBe(5);
+ expect(out.truncated).toBe(true);
+ });
+
+ test(`the hard cap is ${CLAIM_EVENT_MAX_LIST_LIMIT}`, () => {
+ const events = Array.from({ length: CLAIM_EVENT_MAX_LIST_LIMIT + 100 }, (_, i) =>
+ claimEvent({ ts: isoSecond(new Date(T0 + i * 1000)), entity: "a" }),
+ );
+ const out = selectClaimEvents(events, { limit: CLAIM_EVENT_MAX_LIST_LIMIT * 5 });
+ expect(out.rows).toHaveLength(CLAIM_EVENT_MAX_LIST_LIMIT);
+ expect(out.total).toBe(CLAIM_EVENT_MAX_LIST_LIMIT + 100);
+ expect(out.truncated).toBe(true);
+ });
+
+ test("a limit below 1 or fractional is refused, never silently applied", () => {
+ const events = [claimEvent({ ts: isoSecond(new Date(T0)), entity: "a" })];
+ expect(() => selectClaimEvents(events, { limit: 0 })).toThrow(/limit/);
+ expect(() => selectClaimEvents(events, { limit: -3 })).toThrow(/limit/);
+ expect(() => selectClaimEvents(events, { limit: 1.5 })).toThrow(/limit/);
+ });
+});
diff --git a/tests/core/brain/truth/stated-claims.test.ts b/tests/core/brain/truth/stated-claims.test.ts
new file mode 100644
index 00000000..f7ae889f
--- /dev/null
+++ b/tests/core/brain/truth/stated-claims.test.ts
@@ -0,0 +1,272 @@
+/**
+ * Grounded agent-stated claim core (truth-correctable-time-aware,
+ * task 4): a stated claim { subject, relation, object } asserted with
+ * its assertion `text` commits as one ledger event with the
+ * `agent_stated` extractor tag - entity is the normalized subject,
+ * aspect the relation token (validated against the single relation
+ * vocabulary), value the object display form. The payload boundary
+ * refuses whole calls (unknown relation, missing text, missing source,
+ * empty agent, malformed ts) with nothing written; the anchoring verdict
+ * is per claim, so
+ * grounded claims commit while ungrounded claims are reported back
+ * with machine reason codes. Anchoring uses the one occurrence kernel
+ * (`anchorEntityForms`, quality-gated normalized match forms,
+ * minimum length 3).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ anchorEntityForms,
+ type AtomicEntityLike,
+} from "../../../../src/core/brain/atomic-facts.ts";
+import {
+ appendStatedClaims,
+ StatedClaimsRefusal,
+ type StatedClaim,
+} from "../../../../src/core/brain/truth/stated-claims.ts";
+import { readClaimEvents } from "../../../../src/core/brain/truth/store.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-truth-stated-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const PAYLOAD = {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude-dev-agent",
+ source: "[[Brain/notes/standup.md]]",
+ text: "Alice Mason joined Google in June after leaving Meta.",
+} as const;
+
+function claim(over: Partial<StatedClaim> = {}): StatedClaim {
+ return { subject: "Alice Mason", relation: "extends", object: "Google", ...over };
+}
+
+const ALICE: AtomicEntityLike = {
+ id: "ent-alice",
+ name: "Alice Mason",
+ aliases: ["AM", "Alice"],
+ status: "active",
+};
+
+describe("anchorEntityForms", () => {
+ test("returns the quality-gated normalized forms that occur in the text", () => {
+ expect(anchorEntityForms("Alice Mason joined Google.", ["Alice Mason", "Google"])).toEqual([
+ "alice mason",
+ "google",
+ ]);
+ });
+
+ test("drops forms shorter than three characters before matching", () => {
+ // "al" would substring-match "Alice", but the quality gate excludes it.
+ expect(anchorEntityForms("Alice walked.", ["al"])).toEqual([]);
+ });
+
+ test("drops structurally invalid forms", () => {
+ expect(anchorEntityForms("nothing anchors here", ["!!!"])).toEqual([]);
+ });
+});
+
+describe("appendStatedClaims", () => {
+ test("commits a grounded claim as a ledger event with the agent_stated tag", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, { ...PAYLOAD, claims: [claim()] }),
+ );
+ expect(outcome.ungrounded).toEqual([]);
+ expect(outcome.committed).toHaveLength(1);
+ const event = outcome.committed[0]!.event;
+ expect(event.entity).toBe("alice mason");
+ expect(event.aspect).toBe("extends");
+ expect(event.value).toBe("Google");
+ expect(event.extractor).toBe("agent_stated");
+ expect(event.source).toBe(PAYLOAD.source);
+ expect(event.agent).toBe(PAYLOAD.agent);
+ // The event is in the ledger.
+ const events = readClaimEvents(vault).events;
+ expect(events).toHaveLength(1);
+ expect(events[0]!.extractor).toBe("agent_stated");
+ });
+
+ test("refuses an unknown relation before any write", () => {
+ expect(() =>
+ withDeviceId("", () =>
+ appendStatedClaims(vault, { ...PAYLOAD, claims: [claim({ relation: "joined" })] }),
+ ),
+ ).toThrow(StatedClaimsRefusal);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("one unknown relation refuses the whole payload, valid claims included", () => {
+ expect(() =>
+ withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ claims: [claim(), claim({ subject: "Alice Mason", relation: "hates" })],
+ }),
+ ),
+ ).toThrow(/unknown relation/);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("missing text refuses the whole payload", () => {
+ expect(() =>
+ withDeviceId("", () =>
+ appendStatedClaims(vault, { ...PAYLOAD, text: " ", claims: [claim()] }),
+ ),
+ ).toThrow(/text/);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("missing source refuses the whole payload", () => {
+ expect(() =>
+ withDeviceId("", () =>
+ appendStatedClaims(vault, { ...PAYLOAD, source: "", claims: [claim()] }),
+ ),
+ ).toThrow(/source/);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("a malformed ts refuses the whole payload through the refusal channel, before any write", () => {
+ // Two grounded claims: a boundary that validated ts only inside the
+ // append loop would leave the payload's refusal to the store's plain
+ // Error - outside the documented refusal channel - instead of this
+ // whole-call refusal with nothing written.
+ expect(() =>
+ withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ ts: "2026-06-01 10:00:00",
+ claims: [claim(), claim({ object: "Meta" })],
+ }),
+ ),
+ ).toThrow(StatedClaimsRefusal);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("an empty agent refuses the whole payload through the refusal channel, before any write", () => {
+ expect(() =>
+ withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ agent: " ",
+ claims: [claim(), claim({ object: "Meta" })],
+ }),
+ ),
+ ).toThrow(StatedClaimsRefusal);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("an unanchored subject is reported back and never written", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ claims: [claim({ subject: "Bob Stone" })],
+ }),
+ );
+ expect(outcome.committed).toEqual([]);
+ expect(outcome.ungrounded).toHaveLength(1);
+ expect(outcome.ungrounded[0]!.reasons).toEqual(["subject_unanchored"]);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+
+ test("an unanchored object is reported back with its own reason", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ claims: [claim({ object: "Apple" })],
+ }),
+ );
+ expect(outcome.committed).toEqual([]);
+ expect(outcome.ungrounded[0]!.reasons).toEqual(["object_unanchored"]);
+ });
+
+ test("verdicts are per claim: a grounded claim commits beside reported-back ones", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ claims: [claim(), claim({ subject: "Bob Stone" }), claim({ object: "Apple" })],
+ }),
+ );
+ expect(outcome.committed).toHaveLength(1);
+ expect(outcome.committed[0]!.event.value).toBe("Google");
+ expect(outcome.ungrounded).toHaveLength(2);
+ expect(outcome.ungrounded.map((u) => u.reasons).toSorted()).toEqual([
+ ["object_unanchored"],
+ ["subject_unanchored"],
+ ]);
+ expect(readClaimEvents(vault).events).toHaveLength(1);
+ });
+
+ test("both anchors missing report both reasons", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ claims: [claim({ subject: "Bob Stone", object: "Apple" })],
+ }),
+ );
+ expect(outcome.ungrounded[0]!.reasons).toEqual(["subject_unanchored", "object_unanchored"]);
+ });
+
+ test("a form shorter than the quality gate never anchors a subject", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, {
+ ...PAYLOAD,
+ claims: [claim({ subject: "Al" })],
+ }),
+ );
+ // "Al" occurs inside "Alice" but the minimum-length gate excludes it.
+ expect(outcome.committed).toEqual([]);
+ expect(outcome.ungrounded[0]!.reasons).toEqual(["subject_unanchored"]);
+ });
+
+ test("registry aliases extend the anchoring forms of a named entity", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(
+ vault,
+ {
+ ...PAYLOAD,
+ text: "Alice joined Google in June after leaving Meta.",
+ claims: [claim()],
+ },
+ { entities: [ALICE] },
+ ),
+ );
+ // The text says "Alice", not "Alice Mason": the alias anchors.
+ expect(outcome.ungrounded).toEqual([]);
+ expect(outcome.committed).toHaveLength(1);
+ expect(outcome.committed[0]!.event.entity).toBe("alice mason");
+ });
+
+ test("a claim with an empty subject reports missing_subject", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, { ...PAYLOAD, claims: [claim({ subject: " " })] }),
+ );
+ expect(outcome.committed).toEqual([]);
+ expect(outcome.ungrounded[0]!.reasons).toEqual(["missing_subject"]);
+ });
+
+ test("a claim with an empty object reports missing_object", () => {
+ const outcome = withDeviceId("", () =>
+ appendStatedClaims(vault, { ...PAYLOAD, claims: [claim({ object: "" })] }),
+ );
+ expect(outcome.committed).toEqual([]);
+ expect(outcome.ungrounded[0]!.reasons).toEqual(["missing_object"]);
+ });
+
+ test("an empty claims payload writes nothing and reports nothing", () => {
+ const outcome = withDeviceId("", () => appendStatedClaims(vault, { ...PAYLOAD, claims: [] }));
+ expect(outcome.committed).toEqual([]);
+ expect(outcome.ungrounded).toEqual([]);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/truth/store.test.ts b/tests/core/brain/truth/store.test.ts
index 5a9932b8..8f7381d8 100644
--- a/tests/core/brain/truth/store.test.ts
+++ b/tests/core/brain/truth/store.test.ts
@@ -15,6 +15,7 @@ import {
appendClaimEvent,
CLAIM_EVENT_MAX_COUNT,
claimShardPath,
+ ClaimWindowRefusal,
readClaimEvents,
readTruthState,
sweepClaimEvents,
@@ -23,6 +24,7 @@ import {
writeTruthState,
} from "../../../../src/core/brain/truth/store.ts";
import { computeTruthState } from "../../../../src/core/brain/truth/fold.ts";
+import { computeTruthStateWithConflicts } from "../../../../src/core/brain/truth/conflicts.ts";
import { withDeviceId } from "../../../helpers/device-id.ts";
let vault: string;
@@ -216,3 +218,222 @@ test("the claim shard name is claims.jsonl or claims.<deviceId>.jsonl, byte for
join(truthDir(vault), "claims.laptop-01.jsonl"),
);
});
+
+describe("claim validity windows (presence-gated, schema v1)", () => {
+ const WINDOWLESS_LINE =
+ JSON.stringify({
+ v: 1,
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude-dev-agent",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[Brain/notes/standup.md]]",
+ }) + "\n";
+
+ test("a windowless append writes a byte-identical line (no validity keys)", () => {
+ const written = append();
+ const line = readFileSync(written.path, "utf8");
+ expect(line).toBe(WINDOWLESS_LINE);
+ const row = JSON.parse(line) as Record<string, unknown>;
+ expect("validFrom" in row).toBe(false);
+ expect("validUntil" in row).toBe(false);
+ });
+
+ test("present validity fields serialize by conditional spread, before source", () => {
+ const written = append({ validFrom: "2026-01-01", validUntil: "2026-06-30T23:59:59Z" });
+ const row = JSON.parse(readFileSync(written.path, "utf8")) as Record<string, unknown>;
+ expect(row["validFrom"]).toBe("2026-01-01");
+ expect(row["validUntil"]).toBe("2026-06-30T23:59:59Z");
+ const keys = Object.keys(row);
+ expect(keys.indexOf("validUntil")).toBe(keys.indexOf("source") - 1);
+ expect(written.event.validFrom).toBe("2026-01-01");
+ });
+
+ test("an invalid validity value refuses the append with a named error", () => {
+ expect(() => append({ validFrom: "yesterday" })).toThrow(/validFrom/);
+ expect(() => append({ validUntil: "2026-01-01T10:00:00+02:00" })).toThrow(/validUntil/);
+ });
+
+ test("a window refusal is typed, so tool surfaces map it to invalid params", () => {
+ // The MCP boundary maps this class to INVALID_PARAMS and the CLI
+ // verb to exit 2; the store keeps refusing strictly either way.
+ expect(() => append({ validFrom: "yesterday" })).toThrow(ClaimWindowRefusal);
+ expect(() => append({ validFrom: "2026-06-01", validUntil: "2026-01-01" })).toThrow(
+ ClaimWindowRefusal,
+ );
+ });
+
+ test("an empty or inverted window refuses the append", () => {
+ // Half-open [from, until): a bare-date until is the exclusive day
+ // start, so equal bare-date bounds are an empty window and rejected,
+ // as are same-instant bounds and any inverted pair.
+ expect(() =>
+ append({ validFrom: "2026-01-01T00:00:00Z", validUntil: "2026-01-01T00:00:00Z" }),
+ ).toThrow();
+ expect(() => append({ validFrom: "2026-06-01", validUntil: "2026-06-01" })).toThrow();
+ expect(() => append({ validFrom: "2026-06-01", validUntil: "2026-01-01" })).toThrow();
+ });
+
+ test("a state file with a valid successions channel reads back; a corrupt one reads null", () => {
+ append({ validFrom: "2025-01-01", validUntil: "2025-12-31" });
+ append({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ });
+ const withSuccessions = computeTruthStateWithConflicts(readClaimEvents(vault).events);
+ expect(withSuccessions.successions).toHaveLength(1);
+ writeTruthState(vault, withSuccessions);
+ expect(readTruthState(vault)).toEqual(withSuccessions);
+
+ const corrupt = JSON.parse(readFileSync(truthStatePath(vault), "utf8")) as Record<
+ string,
+ unknown
+ >;
+ corrupt["successions"] = [{ entity: "alice mason", aspect: "employer", bogus: true }];
+ writeFileSync(truthStatePath(vault), JSON.stringify(corrupt));
+ expect(readTruthState(vault)).toBeNull();
+ });
+
+ test("the new binary reads old lines (fields absent) unchanged", () => {
+ mkdirSync(truthDir(vault), { recursive: true });
+ writeFileSync(join(truthDir(vault), "claims.jsonl"), WINDOWLESS_LINE);
+ const { events, warnings } = readClaimEvents(vault);
+ expect(warnings).toHaveLength(0);
+ expect(events).toHaveLength(1);
+ expect(events[0]!.validFrom).toBeUndefined();
+ expect(events[0]!.validUntil).toBeUndefined();
+ });
+
+ test("the new binary reads new lines and validates the fields when present", () => {
+ mkdirSync(truthDir(vault), { recursive: true });
+ const good = {
+ v: 1,
+ ts: "2026-06-01T09:00:00Z",
+ agent: "a",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ validFrom: "2026-01-01",
+ validUntil: "2026-06-01T00:00:00Z",
+ source: "[[x]]",
+ };
+ const badFrom = { ...good, ts: "2026-06-02T09:00:00Z", validFrom: "not a date" };
+ const inverted = {
+ ...good,
+ ts: "2026-06-03T09:00:00Z",
+ validFrom: "2026-06-01T00:00:00Z",
+ validUntil: "2026-01-01T00:00:00Z",
+ };
+ writeFileSync(
+ join(truthDir(vault), "claims.jsonl"),
+ [good, badFrom, inverted].map((r) => JSON.stringify(r)).join("\n") + "\n",
+ );
+ const { events, warnings } = readClaimEvents(vault);
+ expect(events).toHaveLength(1);
+ expect(events[0]!.validFrom).toBe("2026-01-01");
+ expect(warnings).toHaveLength(2);
+ expect(warnings.map((w) => w.message).toSorted()).toEqual([
+ "invalid claim validFrom: not a date",
+ "invalid claim validity window: validFrom must parse before validUntil",
+ ]);
+ });
+
+ test("unknown keys on a line stay ignored (old binaries read new lines verbatim)", () => {
+ // The old-binary half of the read/write matrix: an older reader
+ // rebuilds the row from known keys only, so a NEW line's validity
+ // fields (and any future field) degrade to the assertion-time axis.
+ // Pinned here against the CURRENT reader: unknown keys are dropped,
+ // not warnings.
+ mkdirSync(truthDir(vault), { recursive: true });
+ const future = {
+ v: 1,
+ ts: "2026-06-01T09:00:00Z",
+ agent: "a",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[x]]",
+ futureField: { nested: true },
+ };
+ writeFileSync(join(truthDir(vault), "claims.jsonl"), JSON.stringify(future) + "\n");
+ const { events, warnings } = readClaimEvents(vault);
+ expect(warnings).toHaveLength(0);
+ expect(events).toHaveLength(1);
+ const row = events[0] as unknown as Record<string, unknown>;
+ expect("futureField" in row).toBe(false);
+ });
+
+ test("the extractor serializes by conditional spread, after source", () => {
+ const written = append({
+ extractor: "agent_stated",
+ validFrom: "2026-01-01",
+ validUntil: "2026-06-30",
+ });
+ const row = JSON.parse(readFileSync(written.path, "utf8")) as Record<string, unknown>;
+ expect(row["extractor"]).toBe("agent_stated");
+ const keys = Object.keys(row);
+ expect(keys.indexOf("extractor")).toBe(keys.length - 1);
+ // The pinned window/source adjacency is unaffected by the tag.
+ expect(keys.indexOf("source")).toBe(keys.indexOf("validUntil") + 1);
+ });
+
+ test("an extractorless append stays byte-identical (no extractor key)", () => {
+ const written = append();
+ const line = readFileSync(written.path, "utf8");
+ expect(line).toBe(WINDOWLESS_LINE);
+ });
+
+ test("a foreign extractor value refuses the append with a named error", () => {
+ // Strict on write: this binary emits exactly one tag.
+ expect(() =>
+ append({ extractor: "model_mined" } as unknown as Parameters<typeof append>[0]),
+ ).toThrow(/extractor/);
+ });
+
+ test("the reader tolerates a future extractor value and passes it through verbatim", () => {
+ mkdirSync(truthDir(vault), { recursive: true });
+ const futureTagged = {
+ v: 1,
+ ts: "2026-06-01T09:00:00Z",
+ agent: "a",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[x]]",
+ extractor: "model_mined",
+ };
+ writeFileSync(join(truthDir(vault), "claims.jsonl"), JSON.stringify(futureTagged) + "\n");
+ const { events, warnings } = readClaimEvents(vault);
+ expect(warnings).toHaveLength(0);
+ expect(events).toHaveLength(1);
+ // A future tag is passed through verbatim, whatever it spells; the
+ // projection sidesteps the closed write-time vocabulary in the type.
+ expect(String(events[0]!.extractor)).toBe("model_mined");
+ });
+
+ test("an extractor that is not a non-empty string drops the line with a warning", () => {
+ mkdirSync(truthDir(vault), { recursive: true });
+ const badTag = {
+ v: 1,
+ ts: "2026-06-01T09:00:00Z",
+ agent: "a",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[x]]",
+ extractor: 42,
+ };
+ writeFileSync(join(truthDir(vault), "claims.jsonl"), JSON.stringify(badTag) + "\n");
+ const { events, warnings } = readClaimEvents(vault);
+ expect(events).toHaveLength(0);
+ expect(warnings.map((w) => w.message)).toEqual(["invalid claim extractor: 42"]);
+ });
+});
diff --git a/tests/core/brain/truth/succession.test.ts b/tests/core/brain/truth/succession.test.ts
new file mode 100644
index 00000000..76aee48f
--- /dev/null
+++ b/tests/core/brain/truth/succession.test.ts
@@ -0,0 +1,258 @@
+/**
+ * Succession channel (truth-correctable-time-aware, contract item 1):
+ * two same-slot claims with present, non-intersecting validity windows
+ * classify as succession, never as conflict. Everything else - any
+ * windowless claim, intersecting windows - keeps the assertion-time
+ * contest rule verbatim. Pure functions only.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ classifyClaimSuccessions,
+ isSuccessionPair,
+ valuesSuccessionSeparated,
+} from "../../../../src/core/brain/truth/succession.ts";
+import type { ClaimEvent } from "../../../../src/core/brain/truth/types.ts";
+
+function claim(over: Partial<ClaimEvent> = {}): ClaimEvent {
+ return {
+ v: 1,
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude-dev-agent",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[Brain/notes/standup.md]]",
+ ...over,
+ };
+}
+
+describe("isSuccessionPair", () => {
+ test("present non-overlapping windows classify as succession", () => {
+ const a = claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" });
+ const b = claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ });
+ expect(isSuccessionPair(a, b)).toBe(true);
+ expect(isSuccessionPair(b, a)).toBe(true);
+ });
+
+ test("adjacent bare-date windows sharing a boundary day are succession", () => {
+ // Half-open [from, until): a bare-date until is the exclusive day
+ // start, so back-to-back bare-date windows (`until: 2026-06-01`,
+ // `from: 2026-06-01`) are disjoint and classify as succession - the
+ // canonical hand-written hand-over shape - never a conflict.
+ const a = claim({ validFrom: "2025-06-01", validUntil: "2026-06-01" });
+ const b = claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-06-01",
+ });
+ expect(isSuccessionPair(a, b)).toBe(true);
+ expect(isSuccessionPair(b, a)).toBe(true);
+ });
+
+ test("any windowless claim keeps the contest rule (never succession)", () => {
+ const windowed = claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" });
+ expect(isSuccessionPair(claim(), windowed)).toBe(false);
+ expect(isSuccessionPair(windowed, claim())).toBe(false);
+ });
+
+ test("intersecting windows never classify as succession", () => {
+ const a = claim({ validFrom: "2025-01-01", validUntil: "2026-06-01" });
+ const b = claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ });
+ expect(isSuccessionPair(a, b)).toBe(false);
+ });
+
+ test("an expired window still qualifies when the pair is disjoint", () => {
+ // Expiry is irrelevant to the axis rule: presence plus
+ // non-intersection decides.
+ const expired = claim({ validFrom: "2020-01-01", validUntil: "2021-01-01" });
+ const current = claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ });
+ expect(isSuccessionPair(expired, current)).toBe(true);
+ });
+
+ test("re-assertions of one value are never succession", () => {
+ const a = claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" });
+ const b = claim({ validFrom: "2026-01-01" });
+ expect(isSuccessionPair(a, b)).toBe(false);
+ });
+});
+
+describe("valuesSuccessionSeparated", () => {
+ test("two value groups whose every cross-pair is disjoint are separated", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ expect(valuesSuccessionSeparated(events, "Google", "Meta")).toBe(true);
+ // Value comparison is the fold's normalized identity.
+ expect(valuesSuccessionSeparated(events, "google", "META")).toBe(true);
+ });
+
+ test("one windowless event in a group keeps the values contestable", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ // A re-assertion of Google without a window poisons the group.
+ claim({ ts: "2026-06-02T10:00:00Z" }),
+ claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ expect(valuesSuccessionSeparated(events, "Google", "Meta")).toBe(false);
+ });
+
+ test("an intersecting cross-pair keeps the values contestable", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2026-06-01" }),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ expect(valuesSuccessionSeparated(events, "Google", "Meta")).toBe(false);
+ });
+});
+
+describe("classifyClaimSuccessions", () => {
+ test("one disjoint windowed pair yields one succession, ordered by window end", () => {
+ const predecessor = claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" });
+ const successor = claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Meta",
+ agent: "codex-agent",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ });
+ const successions = classifyClaimSuccessions([successor, predecessor]);
+ expect(successions).toHaveLength(1);
+ const s = successions[0]!;
+ expect(s.entity).toBe("alice mason");
+ expect(s.aspect).toBe("employer");
+ expect(s.predecessor.value).toBe("Google");
+ expect(s.successor.value).toBe("Meta");
+ expect(s.detectedAt).toBe("2026-06-10T10:00:00Z");
+ });
+
+ test("successor ordering follows window end, not assertion order", () => {
+ // The later-asserted claim holds the EARLIER window: it is the
+ // predecessor (a backdated correction), the other the successor.
+ const backdated = claim({
+ ts: "2026-06-10T10:00:00Z",
+ value: "Google",
+ validFrom: "2025-01-01",
+ validUntil: "2025-12-31",
+ });
+ const live = claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ });
+ const successions = classifyClaimSuccessions([backdated, live]);
+ expect(successions).toHaveLength(1);
+ expect(successions[0]!.predecessor.value).toBe("Google");
+ expect(successions[0]!.successor.value).toBe("Meta");
+ });
+
+ test("windowless and intersecting pairs yield nothing", () => {
+ expect(
+ classifyClaimSuccessions([
+ claim(),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ }),
+ ]),
+ ).toHaveLength(0);
+ expect(
+ classifyClaimSuccessions([
+ claim({ validFrom: "2025-01-01", validUntil: "2026-06-01" }),
+ claim({ value: "Meta", source: "[[Brain/notes/later.md]]", validFrom: "2026-01-01" }),
+ ]),
+ ).toHaveLength(0);
+ });
+
+ test("successions group per slot and sort by entity then aspect", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ claim({
+ entity: "bob hale",
+ aspect: "role",
+ value: "dev",
+ source: "[[Brain/notes/bob.md]]",
+ validFrom: "2024-01-01",
+ validUntil: "2024-12-31",
+ }),
+ claim({
+ entity: "bob hale",
+ aspect: "role",
+ ts: "2026-07-01T10:00:00Z",
+ value: "ops",
+ source: "[[Brain/notes/bob2.md]]",
+ validFrom: "2025-01-01",
+ }),
+ ];
+ const successions = classifyClaimSuccessions(events);
+ expect(successions).toHaveLength(2);
+ expect(successions.map((s) => `${s.entity}/${s.aspect}`)).toEqual([
+ "alice mason/employer",
+ "bob hale/role",
+ ]);
+ });
+
+ test("other-entity events never leak into a slot's classification", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ entity: "bob hale",
+ value: "Meta",
+ source: "[[Brain/notes/bob.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ expect(classifyClaimSuccessions(events)).toHaveLength(0);
+ });
+
+ test("classification is deterministic and empty-safe", () => {
+ const events = [
+ claim({ validFrom: "2025-01-01", validUntil: "2025-12-31" }),
+ claim({
+ value: "Meta",
+ source: "[[Brain/notes/later.md]]",
+ validFrom: "2026-01-01",
+ }),
+ ];
+ expect(classifyClaimSuccessions(events)).toEqual(
+ classifyClaimSuccessions([...events].toReversed()),
+ );
+ expect(classifyClaimSuccessions([])).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/truth/validity.test.ts b/tests/core/brain/truth/validity.test.ts
new file mode 100644
index 00000000..14956753
--- /dev/null
+++ b/tests/core/brain/truth/validity.test.ts
@@ -0,0 +1,357 @@
+/**
+ * Ledger validity windows (truth-correctable-time-aware, contract item 1):
+ * window parsing shares the `src/core/search/validity.ts` grammar with one
+ * ledger-specific difference (bare dates resolve to their day start on
+ * BOTH edges, so the until bound is exclusive - half-open; datetimes
+ * parse; relative phrases are rejected), `claimWindow` is null exactly
+ * for windowless events, and `windowsIntersect` is the half-open rule
+ * with null as plus/minus infinity. The ingest-default cases pin the
+ * frozen-at-ingest resolution: explicit input wins outright, a readable
+ * source record's frontmatter window fills the missing bounds, an
+ * unreadable or windowless source stores a windowless event
+ * byte-identical to today's output, and mtime is never a window source.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ claimWindow,
+ isValidityPoint,
+ resolveIngestWindow,
+ windowsIntersect,
+} from "../../../../src/core/brain/truth/validity.ts";
+import type { ClaimEvent } from "../../../../src/core/brain/truth/types.ts";
+import { appendClaimEvent } from "../../../../src/core/brain/truth/store.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
+
+function claim(over: Partial<ClaimEvent> = {}): ClaimEvent {
+ return {
+ v: 1,
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude-dev-agent",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Google",
+ valueKind: "text",
+ source: "[[Brain/notes/standup.md]]",
+ ...over,
+ };
+}
+
+describe("claimWindow", () => {
+ test("a windowless event has no window", () => {
+ expect(claimWindow(claim())).toBeNull();
+ });
+
+ test("a bare-date from day-snaps to the day start", () => {
+ const window = claimWindow(claim({ validFrom: "2026-01-01" }));
+ expect(window).not.toBeNull();
+ expect(window!.fromMs).toBe(Date.UTC(2026, 0, 1));
+ expect(window!.untilMs).toBeNull();
+ });
+
+ test("a bare-date until resolves to that day's start, exclusive", () => {
+ // Half-open [from, until): a bare-date until is the exclusive day
+ // start, never a cover of its own day, so adjacent bare-date windows
+ // (`until: 2026-01-01`, then `from: 2026-01-01`) stay disjoint.
+ const window = claimWindow(claim({ validUntil: "2026-01-01" }));
+ expect(window).not.toBeNull();
+ expect(window!.fromMs).toBeNull();
+ expect(window!.untilMs).toBe(Date.UTC(2026, 0, 1));
+ });
+
+ test("adjacent bare-date windows do not intersect", () => {
+ const a = claimWindow(claim({ validFrom: "2025-12-01", validUntil: "2026-01-01" }));
+ const b = claimWindow(claim({ validFrom: "2026-01-01", validUntil: "2026-02-01" }));
+ expect(windowsIntersect(a!, b!)).toBe(false);
+ });
+
+ test("canonical UTC datetimes parse exactly", () => {
+ const window = claimWindow(
+ claim({ validFrom: "2026-01-01T00:00:00Z", validUntil: "2026-06-30T12:00:00Z" }),
+ );
+ expect(window!.fromMs).toBe(Date.parse("2026-01-01T00:00:00Z"));
+ expect(window!.untilMs).toBe(Date.parse("2026-06-30T12:00:00Z"));
+ });
+
+ test("a datetime without an offset reads as UTC", () => {
+ const window = claimWindow(claim({ validFrom: "2026-01-01T10:30:00" }));
+ expect(window!.fromMs).toBe(Date.parse("2026-01-01T10:30:00Z"));
+ });
+
+ test("relative phrases never parse", () => {
+ expect(claimWindow(claim({ validFrom: "yesterday" }))!.fromMs).toBeNull();
+ expect(claimWindow(claim({ validUntil: "last week" }))!.untilMs).toBeNull();
+ expect(claimWindow(claim({ validFrom: "3 days ago" }))!.fromMs).toBeNull();
+ });
+
+ test("an impossible calendar date never parses", () => {
+ expect(claimWindow(claim({ validFrom: "2026-02-30" }))!.fromMs).toBeNull();
+ });
+
+ test("an unparseable present bound reads as unbounded on that side", () => {
+ // The write boundary (appendClaimEvent / coerceClaim) rejects these
+ // with a named error, so this branch is defensive tolerance for
+ // hand-built events only.
+ const window = claimWindow(claim({ validFrom: "not a date", validUntil: "2026-01-01" }));
+ expect(window).not.toBeNull();
+ expect(window!.fromMs).toBeNull();
+ });
+});
+
+describe("windowsIntersect", () => {
+ test("overlapping half-open windows intersect", () => {
+ expect(windowsIntersect({ fromMs: 10, untilMs: 20 }, { fromMs: 15, untilMs: 25 })).toBe(true);
+ });
+
+ test("touching half-open windows do not intersect", () => {
+ expect(windowsIntersect({ fromMs: 10, untilMs: 20 }, { fromMs: 20, untilMs: 30 })).toBe(false);
+ expect(windowsIntersect({ fromMs: 20, untilMs: 30 }, { fromMs: 10, untilMs: 20 })).toBe(false);
+ });
+
+ test("disjoint windows do not intersect", () => {
+ expect(windowsIntersect({ fromMs: 10, untilMs: 20 }, { fromMs: 40, untilMs: 50 })).toBe(false);
+ });
+
+ test("a missing bound is minus infinity on the from side", () => {
+ expect(windowsIntersect({ fromMs: null, untilMs: 20 }, { fromMs: 10, untilMs: 30 })).toBe(true);
+ expect(windowsIntersect({ fromMs: null, untilMs: 5 }, { fromMs: 10, untilMs: 30 })).toBe(false);
+ });
+
+ test("a missing bound is plus infinity on the until side", () => {
+ expect(windowsIntersect({ fromMs: 10, untilMs: null }, { fromMs: 20, untilMs: 30 })).toBe(true);
+ // [40, 50) starts after [10, infinity) begins and ends never, so the
+ // non-intersecting counterpart must end before the from side opens.
+ expect(windowsIntersect({ fromMs: 10, untilMs: null }, { fromMs: 40, untilMs: 50 })).toBe(true);
+ expect(windowsIntersect({ fromMs: 10, untilMs: null }, { fromMs: null, untilMs: 5 })).toBe(
+ false,
+ );
+ });
+
+ test("two fully open windows intersect", () => {
+ expect(windowsIntersect({ fromMs: null, untilMs: null }, { fromMs: 0, untilMs: 1 })).toBe(true);
+ expect(windowsIntersect({ fromMs: null, untilMs: null }, { fromMs: null, untilMs: null })).toBe(
+ true,
+ );
+ });
+
+ test("a later-opening unbounded window still intersects an earlier unbounded one", () => {
+ expect(windowsIntersect({ fromMs: 10, untilMs: null }, { fromMs: 20, untilMs: null })).toBe(
+ true,
+ );
+ });
+});
+
+describe("isValidityPoint", () => {
+ test("accepts bare ISO dates and canonical UTC timestamps", () => {
+ expect(isValidityPoint("2026-01-01")).toBe(true);
+ expect(isValidityPoint("2026-01-01T10:00:00Z")).toBe(true);
+ expect(isValidityPoint("2026-01-01T10:00:00.500Z")).toBe(true);
+ });
+
+ test("rejects relative phrases, offsets, and garbage", () => {
+ expect(isValidityPoint("yesterday")).toBe(false);
+ expect(isValidityPoint("last week")).toBe(false);
+ expect(isValidityPoint("2026-01-01T10:00:00+02:00")).toBe(false);
+ expect(isValidityPoint("")).toBe(false);
+ expect(isValidityPoint(" ")).toBe(false);
+ expect(isValidityPoint("not a date")).toBe(false);
+ expect(isValidityPoint("2026-02-30")).toBe(false);
+ });
+});
+
+describe("resolveIngestWindow", () => {
+ test("explicit input wins outright - a readable source cannot leak in", () => {
+ const resolved = resolveIngestWindow(
+ { validFrom: "2026-02-01", validUntil: "2026-03-01" },
+ { validFrom: "2026-01-01", validUntil: "2026-06-30" },
+ );
+ expect(resolved.validFrom).toBe("2026-02-01");
+ expect(resolved.validUntil).toBe("2026-03-01");
+ });
+
+ test("absent input adopts the source record's frontmatter window verbatim", () => {
+ const resolved = resolveIngestWindow(
+ {},
+ { validFrom: "2026-01-01", validUntil: "2026-06-30T23:59:59Z" },
+ );
+ expect(resolved.validFrom).toBe("2026-01-01");
+ expect(resolved.validUntil).toBe("2026-06-30T23:59:59Z");
+ });
+
+ test("resolution is per bound: an explicit from pairs with a source until", () => {
+ const resolved = resolveIngestWindow(
+ { validFrom: "2026-02-01" },
+ { validFrom: "2026-01-01", validUntil: "2026-06-30" },
+ );
+ expect(resolved.validFrom).toBe("2026-02-01");
+ expect(resolved.validUntil).toBe("2026-06-30");
+ });
+
+ test("an unreadable source (null) resolves only the explicit bounds", () => {
+ const resolved = resolveIngestWindow({ validFrom: "2026-02-01" }, null);
+ expect(resolved.validFrom).toBe("2026-02-01");
+ expect(resolved.validUntil).toBeUndefined();
+ expect(resolveIngestWindow({}, null)).toEqual({});
+ });
+
+ test("an unparseable source bound is treated as absent", () => {
+ // A malformed source window must never refuse an otherwise-valid
+ // ingest nor leak garbage into the ledger.
+ const resolved = resolveIngestWindow(
+ {},
+ { validFrom: "yesterday", validUntil: "also not a date" },
+ );
+ expect(resolved).toEqual({});
+ });
+
+ test("empty source bounds are absent", () => {
+ const resolved = resolveIngestWindow({}, { validFrom: " ", validUntil: "" });
+ expect(resolved).toEqual({});
+ });
+
+ test("mtime-shaped source metadata is never a window source", () => {
+ // Only the two named frontmatter keys participate; any other
+ // record metadata (recorded_at, an mtime proxy) is ignored.
+ const resolved = resolveIngestWindow({}, {
+ recordedAt: "2026-05-01",
+ validUntil: "2026-06-30",
+ } as Record<string, string>);
+ expect(resolved.validFrom).toBeUndefined();
+ expect(resolved.validUntil).toBe("2026-06-30");
+ });
+});
+
+describe("ingest window defaults (appendClaimEvent)", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-truth-window-"));
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ function writeSource(rel: string, frontmatter: string): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, `---\n${frontmatter}---\nbody\n`);
+ }
+
+ function firstLine(): string {
+ const shard = withDeviceId("", () => appendClaimEvent(vault, STANDUP_CLAIM)).path;
+ return readFileSync(shard, "utf8").trim();
+ }
+
+ const STANDUP_CLAIM = {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude-dev-agent",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/standup.md]]",
+ } as const;
+
+ test("a readable source's frontmatter window is stored frozen on the event", () => {
+ writeSource("Brain/notes/standup.md", "valid_from: 2026-01-01\nvalid_until: 2026-06-30\n");
+ const line = firstLine();
+ const row = JSON.parse(line) as Record<string, unknown>;
+ expect(row["validFrom"]).toBe("2026-01-01");
+ expect(row["validUntil"]).toBe("2026-06-30");
+ });
+
+ test("an extensionless wikilink source resolves through the .md variant", () => {
+ writeSource("Brain/notes/standup.md", "valid_from: 2026-01-01\n");
+ const written = withDeviceId("", () =>
+ appendClaimEvent(vault, { ...STANDUP_CLAIM, source: "[[Brain/notes/standup]]" }),
+ );
+ expect(written.event.validFrom).toBe("2026-01-01");
+ expect(written.event.validUntil).toBeUndefined();
+ });
+
+ test("a directory at the bare spelling never shadows its .md twin", () => {
+ // The bare candidate must be a regular file to name a page: a
+ // directory where the extensionless spelling lands is not the
+ // record, and accepting it used to shadow the .md twin beside it -
+ // the same regular-file rule the artifact-ref view's isVaultFile
+ // applies to the read side.
+ mkdirSync(join(vault, "Brain", "notes", "standup"), { recursive: true });
+ writeSource("Brain/notes/standup.md", "valid_from: 2026-01-01\n");
+ const written = withDeviceId("", () =>
+ appendClaimEvent(vault, { ...STANDUP_CLAIM, source: "[[Brain/notes/standup]]" }),
+ );
+ expect(written.event.validFrom).toBe("2026-01-01");
+ expect(written.event.validUntil).toBeUndefined();
+ });
+
+ test("an explicit window wins outright over the source record's window", () => {
+ writeSource("Brain/notes/standup.md", "valid_from: 2026-01-01\nvalid_until: 2026-06-30\n");
+ const written = withDeviceId("", () =>
+ appendClaimEvent(vault, { ...STANDUP_CLAIM, validFrom: "2026-02-01" }),
+ );
+ expect(written.event.validFrom).toBe("2026-02-01");
+ // Explicit from + no explicit until: the source's until still fills
+ // the open side (per-bound resolution).
+ expect(written.event.validUntil).toBe("2026-06-30");
+ });
+
+ test("an unreadable source stores a windowless event byte-identical to today's output", () => {
+ const line = firstLine();
+ expect(line).toBe(
+ '{"v":1,"ts":"2026-06-01T10:00:00Z","agent":"claude-dev-agent","entity":"alice mason","aspect":"employer","value":"Google","valueKind":"text","source":"[[Brain/notes/standup.md]]"}',
+ );
+ });
+
+ test("a windowless source stores a windowless event byte-identical to today's output", () => {
+ writeSource("Brain/notes/standup.md", "status: active\n");
+ expect(firstLine()).toBe(
+ '{"v":1,"ts":"2026-06-01T10:00:00Z","agent":"claude-dev-agent","entity":"alice mason","aspect":"employer","value":"Google","valueKind":"text","source":"[[Brain/notes/standup.md]]"}',
+ );
+ });
+
+ test("a source file mtime alone never produces a window", () => {
+ // The source exists and is readable but carries no validity
+ // frontmatter; its filesystem mtime is an assertion-time proxy and
+ // must not become validity.
+ writeSource("Brain/notes/standup.md", "recorded_at: 2026-05-01\n");
+ expect(firstLine()).not.toContain("validFrom");
+ expect(firstLine()).not.toContain("validUntil");
+ });
+
+ test("a source traversal escape is treated as an unreadable source", () => {
+ const written = withDeviceId("", () =>
+ appendClaimEvent(vault, { ...STANDUP_CLAIM, source: "../../outside-vault" }),
+ );
+ expect(written.event.validFrom).toBeUndefined();
+ expect(written.event.validUntil).toBeUndefined();
+ });
+
+ test("a source the reach gate withholds stores a windowless event byte-identical to today's output", () => {
+ // The MCP tools pass the caller's readable predicate; a source page
+ // it withholds must resolve no window, exactly like an absent one -
+ // the frozen event and the response shape carry no signal
+ // distinguishing withheld from absent.
+ writeSource("Brain/notes/standup.md", "valid_from: 2026-01-01\nvalid_until: 2026-06-30\n");
+ const written = withDeviceId("", () =>
+ appendClaimEvent(vault, STANDUP_CLAIM, { readableSource: () => false }),
+ );
+ expect(readFileSync(written.path, "utf8").trim()).toBe(
+ '{"v":1,"ts":"2026-06-01T10:00:00Z","agent":"claude-dev-agent","entity":"alice mason","aspect":"employer","value":"Google","valueKind":"text","source":"[[Brain/notes/standup.md]]"}',
+ );
+ });
+
+ test("a source the reach gate admits still resolves its frontmatter window", () => {
+ writeSource("Brain/notes/standup.md", "valid_from: 2026-01-01\n");
+ const written = withDeviceId("", () =>
+ appendClaimEvent(vault, STANDUP_CLAIM, {
+ readableSource: (rel) => rel === "Brain/notes/standup.md",
+ }),
+ );
+ expect(written.event.validFrom).toBe("2026-01-01");
+ expect(written.event.validUntil).toBeUndefined();
+ });
+});
diff --git a/tests/core/search/correction-coupling.test.ts b/tests/core/search/correction-coupling.test.ts
new file mode 100644
index 00000000..6a0958db
--- /dev/null
+++ b/tests/core/search/correction-coupling.test.ts
@@ -0,0 +1,115 @@
+/**
+ * Contract item 3 (truth-correctable-time-aware, Task 15): the
+ * serve-with-correction coupling predicate.
+ *
+ * A retired-but-serveable row is served only beside its chain-tip
+ * correction; an unresolved or out-of-reach successor drops the row
+ * fail-closed, so a withheld page stays indistinguishable from an
+ * absent one. Every serving surface consumes this predicate, so the
+ * rule table here is the single spelling of the guarantee.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { chainVerdict, couplingVerdict } from "../../../src/core/search/correction-coupling.ts";
+
+const PREDECESSOR = "Brain/preferences/pref-old-rule.md";
+const SUCCESSOR = "Brain/preferences/pref-new-rule.md";
+
+describe("couplingVerdict", () => {
+ test("a resolved and readable successor serves the row beside its correction", () => {
+ expect(
+ couplingVerdict({
+ predecessorPath: PREDECESSOR,
+ successorPath: SUCCESSOR,
+ successorReadable: true,
+ }),
+ ).toEqual({ action: "serve_coupled", correctionPath: SUCCESSOR });
+ });
+
+ test("an unresolved successor (null path) drops the row", () => {
+ expect(
+ couplingVerdict({
+ predecessorPath: PREDECESSOR,
+ successorPath: null,
+ successorReadable: true,
+ }),
+ ).toEqual({ action: "drop" });
+ });
+
+ test("a successor out of the caller's reach drops the row", () => {
+ expect(
+ couplingVerdict({
+ predecessorPath: PREDECESSOR,
+ successorPath: SUCCESSOR,
+ successorReadable: false,
+ }),
+ ).toEqual({ action: "drop" });
+ });
+
+ test("an unresolved AND unreadable successor drops the row", () => {
+ expect(
+ couplingVerdict({
+ predecessorPath: PREDECESSOR,
+ successorPath: null,
+ successorReadable: false,
+ }),
+ ).toEqual({ action: "drop" });
+ });
+
+ test("the verdict carries the successor path verbatim as the correction path", () => {
+ const nested = "Brain/decisions/nested/correction-page.md";
+ const verdict = couplingVerdict({
+ predecessorPath: PREDECESSOR,
+ successorPath: nested,
+ successorReadable: true,
+ });
+ expect(verdict).toEqual({ action: "serve_coupled", correctionPath: nested });
+ });
+
+ test("the predicate is pure and deterministic: same input, same verdict", () => {
+ const input = {
+ predecessorPath: PREDECESSOR,
+ successorPath: SUCCESSOR,
+ successorReadable: true,
+ };
+ expect(couplingVerdict(input)).toEqual(couplingVerdict(input));
+ expect(couplingVerdict({ ...input, successorReadable: false })).toEqual(
+ couplingVerdict({ ...input, successorReadable: false }),
+ );
+ });
+
+ test("the predicate performs no I/O: it answers for pages that do not exist", () => {
+ // Paths that name no file anywhere still resolve a verdict - the
+ // predicate reads nothing, callers resolve readability before asking.
+ const nowhere = "Brain/nowhere/neither-page.md";
+ expect(
+ couplingVerdict({
+ predecessorPath: nowhere,
+ successorPath: nowhere,
+ successorReadable: false,
+ }),
+ ).toEqual({ action: "drop" });
+ });
+});
+
+describe("chainVerdict", () => {
+ test("a fully resolved chain serves the row beside the resolved tip", () => {
+ expect(chainVerdict(PREDECESSOR, { resolvedAll: true, cycle: false, tip: SUCCESSOR })).toEqual({
+ action: "serve_coupled",
+ correctionPath: SUCCESSOR,
+ });
+ });
+
+ test("a dangling successor hop drops the row fail-closed", () => {
+ expect(chainVerdict(PREDECESSOR, { resolvedAll: false, cycle: false, tip: SUCCESSOR })).toEqual(
+ { action: "drop" },
+ );
+ });
+
+ test("a cyclic chain drops the row fail-closed", () => {
+ expect(chainVerdict(PREDECESSOR, { resolvedAll: true, cycle: true, tip: PREDECESSOR })).toEqual(
+ { action: "drop" },
+ );
+ });
+});
diff --git a/tests/core/search/fusion.test.ts b/tests/core/search/fusion.test.ts
index cde7f819..9fe77e97 100644
--- a/tests/core/search/fusion.test.ts
+++ b/tests/core/search/fusion.test.ts
@@ -63,3 +63,160 @@ test("a single populated lane still ranks by position", () => {
expect(fused.get(5)!).toBeGreaterThan(fused.get(6)!);
expect(fused.get(6)!).toBeGreaterThan(fused.get(7)!);
});
+
+// ─── structural direct-hit precedence (truth-correctable-time-aware) ─────────
+
+import { rankResults } from "../../../src/core/search/ranker.ts";
+import { applyRelationalRerankPin } from "../../../src/core/search/pipeline/relational-arm.ts";
+import type { KeywordHit, SemanticHit, HydratedChunk } from "../../../src/core/search/store.ts";
+import type { BrainSearchResult } from "../../../src/core/search/search-result.ts";
+
+const NOW = 1_750_000_000_000;
+const OLD = NOW / 1000 - 365 * 24 * 3600; // no recency boost
+
+function hyd(chunkId: number, docId: number): HydratedChunk {
+ return Object.freeze({
+ chunkId,
+ documentId: docId,
+ path: `doc${docId}.md`,
+ title: `Doc ${docId}`,
+ content: `chunk ${chunkId}`,
+ startLine: 1,
+ endLine: 1,
+ mtime: OLD,
+ });
+}
+
+/**
+ * keyword: 1 (rank 1) and 9 (a DEEP direct hit, rank 2); semantic: 2;
+ * relational lane: 3 alone. On raw RRF the relational-only rank 1 ties the
+ * keyword rank 1 and clears the deep direct hit - exactly the float the
+ * structural admission exists to prevent.
+ */
+function precedenceInputs() {
+ const keyword: KeywordHit[] = [
+ { chunkId: 1, documentId: 10, bm25: -10 },
+ { chunkId: 9, documentId: 90, bm25: -0.5 },
+ ];
+ const semantic: SemanticHit[] = [{ chunkId: 2, documentId: 20, distance: 0.1 }];
+ const hydrated = new Map<number, HydratedChunk>([
+ [1, hyd(1, 10)],
+ [2, hyd(2, 20)],
+ [9, hyd(9, 90)],
+ [3, hyd(3, 30)],
+ ]);
+ return {
+ keyword,
+ semantic,
+ hydrated,
+ inboundLinkSources: new Map(),
+ tagsByDoc: new Map(),
+ relationalRankedChunkIds: [3],
+ };
+}
+
+const RRF_OPTS = {
+ keywordWeight: 0.6,
+ semanticWeight: 0.6,
+ limit: 10,
+ nowMs: NOW,
+ fusionMode: "rrf" as const,
+ rrfK: 60,
+};
+
+test("a relational-only row is admitted after the last organic row", () => {
+ const ranked = rankResults(precedenceInputs(), RRF_OPTS);
+ const ids = ranked.map((r) => r.chunkId);
+ expect(ids).toEqual([1, 2, 9, 3]);
+ expect(ranked[ranked.length - 1]!.searchType).toBe("link");
+});
+
+test("a relational-only row at relational-rank 1 never outranks a keyword direct hit", () => {
+ const ranked = rankResults(precedenceInputs(), RRF_OPTS);
+ const ids = ranked.map((r) => r.chunkId);
+ // Chunk 9 is a keyword direct hit two ranks deep; chunk 3 leads the
+ // relational lane. The direct hit stays above it.
+ expect(ids.indexOf(9)).toBeLessThan(ids.indexOf(3));
+});
+
+test("with the arm absent or empty the fused order is byte-identical", () => {
+ const { relationalRankedChunkIds, ...organic } = precedenceInputs();
+ const without = rankResults(organic, RRF_OPTS);
+ expect(without.map((r) => r.chunkId)).toEqual([1, 2, 9]);
+ const emptyLane = rankResults({ ...organic, relationalRankedChunkIds: [] }, RRF_OPTS);
+ expect(JSON.stringify(emptyLane)).toBe(JSON.stringify(without));
+});
+
+/** A result row with controllable direct-hit and origin markers. */
+function pinRow(
+ chunkId: number,
+ opts: { keywordScore?: number; relational?: boolean } = {},
+): BrainSearchResult {
+ return Object.freeze({
+ documentId: chunkId * 10,
+ chunkId,
+ path: `doc${chunkId}.md`,
+ title: null,
+ content: `chunk ${chunkId}`,
+ startLine: 1,
+ endLine: 1,
+ score: 1,
+ keywordScore: opts.keywordScore ?? 0,
+ semanticScore: 0,
+ linkBoost: 0,
+ recencyBoost: 0,
+ searchType: (opts.keywordScore ?? 0) > 0 ? "keyword" : "link",
+ ...(opts.relational ? { relationalOrigin: true } : {}),
+ reasons: Object.freeze([]),
+ });
+}
+
+test("the rerank pin holds a relational-origin row below the organic direct hits", () => {
+ // Pre-rerank: direct hit, semantic row, then the relational block.
+ // The cross-encoder lifts relational row 3 above the direct hit.
+ const pre = [
+ pinRow(1, { keywordScore: 0.9 }),
+ pinRow(2),
+ pinRow(3, { relational: true }),
+ pinRow(4, { relational: true }),
+ ];
+ const post = [
+ pinRow(3, { relational: true }),
+ pinRow(1, { keywordScore: 0.9 }),
+ pinRow(2),
+ pinRow(4, { relational: true }),
+ ];
+ const pinned = applyRelationalRerankPin(pre, post);
+ // Row 3 lands just below the deepest direct hit - the only organic row it
+ // may not cross is the hit; the semantic row between is crossed freely,
+ // and the move never sinks it past its pre-rerank floor (index 2).
+ expect(pinned.map((r) => r.chunkId)).toEqual([1, 2, 3, 4]);
+ expect(pinned[2]!.reasons).toContain("relational_pin: held below the organic direct hits");
+ // The peer that stayed put keeps its relative line: 3 before 4.
+ expect(pinned.map((r) => r.chunkId).indexOf(3)).toBeLessThan(
+ pinned.map((r) => r.chunkId).indexOf(4),
+ );
+});
+
+test("the direct-hit ceiling wins over the pre-rerank floor when they conflict", () => {
+ // Pre-rerank floor of row 3 is 2, but two direct hits now sit above the
+ // ceiling line; the structural admission wins and the row is held below
+ // both, named by the receipt.
+ const pre = [pinRow(1, { keywordScore: 0.9 }), pinRow(2), pinRow(3, { relational: true })];
+ const post = [
+ pinRow(3, { relational: true }),
+ pinRow(1, { keywordScore: 0.9 }),
+ pinRow(5, { keywordScore: 0.8 }),
+ ];
+ const pinned = applyRelationalRerankPin(pre, post);
+ expect(pinned.map((r) => r.chunkId)).toEqual([1, 5, 3]);
+ expect(pinned[2]!.reasons).toContain("relational_pin: held below the organic direct hits");
+});
+
+test("a pool already below the direct hits is returned untouched by the ceiling", () => {
+ const pre = [pinRow(1, { keywordScore: 0.9 }), pinRow(2), pinRow(3, { relational: true })];
+ const post = [pinRow(1, { keywordScore: 0.9 }), pinRow(3, { relational: true }), pinRow(2)];
+ const pinned = applyRelationalRerankPin(pre, post);
+ expect(pinned.map((r) => r.chunkId)).toEqual([1, 3, 2]);
+ expect(pinned.every((r) => !r.reasons.some((x) => x.startsWith("relational_pin:")))).toBe(true);
+});
diff --git a/tests/core/search/post-rank-coupling.test.ts b/tests/core/search/post-rank-coupling.test.ts
new file mode 100644
index 00000000..c8132f6a
--- /dev/null
+++ b/tests/core/search/post-rank-coupling.test.ts
@@ -0,0 +1,280 @@
+/**
+ * Serve-with-correction coupling on the search pipeline
+ * (truth-correctable-time-aware, Task 18).
+ *
+ * The post-rank retired-row branch consumes `couplingVerdict`: a
+ * retired-but-serveable row is served only beside its resolved, readable
+ * chain-tip correction and is dropped otherwise. Correction content pulled
+ * in re-runs the full caller filter set (status, visibility scope, agent
+ * scope, reach), closing the recorded gap where polarity-pulled successors
+ * bypassed visibility and agent scope. With no retired rows the pool is
+ * unchanged, and tombstoned rows stay dropped by the status filter before
+ * the predicate runs.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { search } from "../../../src/core/search/search.ts";
+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+let config: ResolvedSearchConfig;
+
+beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("post-rank-coupling"));
+ config = makeConfig({ vault, dbPath });
+});
+
+afterEach(() => cleanup());
+
+/** A page frontmatter block plus body, written vault-relative. */
+function page(rel: string, frontmatter: ReadonlyArray<string>, body: string): void {
+ const head = frontmatter.length === 0 ? "" : `---\n${frontmatter.join("\n")}\n---\n`;
+ writeMd(vault, rel, `${head}\n${body}\n`);
+}
+
+const CORRECTION_REASON_PREFIX = "correction_for:";
+
+function paths(results: ReadonlyArray<{ readonly path: string }>): string[] {
+ return results.map((r) => r.path).toSorted();
+}
+
+/** A result's stable projection: everything the wall clock does not own. */
+function stable(r: { path: string; reasons: ReadonlyArray<string> }): {
+ path: string;
+ reasons: ReadonlyArray<string>;
+} {
+ return {
+ path: r.path,
+ reasons: r.reasons.filter((reason) => !reason.startsWith("recency:")),
+ };
+}
+
+describe("post-rank coupling", () => {
+ test("a retired-but-serveable row is served beside its chain-tip correction", async () => {
+ page("predecessor.md", ['superseded_by: "[[mid-step]]"'], "falcon migration corridor map.");
+ page("mid-step.md", ['superseded_by: "[[correction-tip]]"'], "waypoint ledger for the survey.");
+ page("correction-tip.md", [], "settled wing morphology measurements.");
+ await indexVault(config);
+
+ // Only the predecessor matches the query, so the chain tip can only
+ // arrive by coupling pull-in, never by its own rank.
+ const out = await search(config, { query: "falcon migration corridor", limit: 10 });
+ expect(out.results.some((r) => r.path === "predecessor.md")).toBe(true);
+ const tip = out.results.find((r) => r.path === "correction-tip.md");
+ expect(tip).toBeDefined();
+ expect(tip!.reasons).toContain(`${CORRECTION_REASON_PREFIX} predecessor.md`);
+ // The non-tip mid step is not the correction; only the tip is pulled
+ // in by coupling. (mid-step itself arrives through the polarity
+ // phase's successor pull-in, and stays: its own chain tip is the same
+ // readable correction, so it is served coupled too.)
+ const mid = out.results.find((r) => r.path === "mid-step.md");
+ if (mid !== undefined) {
+ expect(mid!.reasons.some((reason) => reason.startsWith(CORRECTION_REASON_PREFIX))).toBe(
+ false,
+ );
+ }
+ });
+
+ test("a retired row whose chain tip is unresolved is dropped fail-closed", async () => {
+ page("orphan-predecessor.md", ['superseded_by: "[[ghost-page]]"'], "alloy composition table.");
+ await indexVault(config);
+
+ const out = await search(config, { query: "alloy composition table", limit: 10 });
+ expect(out.results.some((r) => r.path === "orphan-predecessor.md")).toBe(false);
+ });
+
+ test("a retired row whose superseded_by edge is schema-blocked is dropped, not served bare", async () => {
+ // The schema pack's link constraint declares no note->receipt pair for
+ // `superseded_by`, so the indexer marks the predecessor's pointer edge
+ // blocked and the chain walk finds no typed edge to follow - while the
+ // page's own frontmatter still declares the successor. The walk then
+ // answers the start page as its own chain tip; that corner must count
+ // as unresolved, or the retired row would be served bare.
+ writeMd(
+ vault,
+ "Brain/_brain.yaml",
+ [
+ "schema_version: 1",
+ "schema:",
+ " page_types: [note, receipt]",
+ " link_types:",
+ " - superseded_by",
+ " link_constraints:",
+ " - superseded_by=note->note",
+ ].join("\n") + "\n",
+ );
+ page(
+ "blocked-predecessor.md",
+ ["type: note", 'superseded_by: "[[blocked-correction]]"'],
+ "kestrel hovering scan notes.",
+ );
+ page("blocked-correction.md", ["type: receipt"], "revised kestrel hovering survey.");
+ const stats = await indexVault(config);
+ // The fixture pins the block: the pointer edge exists but is excluded
+ // from the typed-edge reader the chain walk uses.
+ expect(stats.relationViolations).toHaveLength(1);
+
+ const out = await search(config, { query: "kestrel hovering scan", limit: 10 });
+ expect(out.results.some((r) => r.path === "blocked-predecessor.md")).toBe(false);
+ });
+
+ test("a retired row whose pointer postdates the index is dropped, not served bare", async () => {
+ // The pointer is written AFTER the index run: the live frontmatter
+ // declares a successor the index carries no superseded_by edge for,
+ // so the chain walk again answers the start page as its own tip.
+ page("stale-predecessor.md", [], "basalt column survey grid.");
+ await indexVault(config);
+ page(
+ "stale-predecessor.md",
+ ['superseded_by: "[[stale-correction]]"'],
+ "basalt column survey grid.",
+ );
+ page("stale-correction.md", [], "revised basalt column survey grid.");
+
+ const out = await search(config, { query: "basalt column survey", limit: 10 });
+ expect(out.results.some((r) => r.path === "stale-predecessor.md")).toBe(false);
+ });
+
+ test("a chain-tip correction that is itself retired with an unresolved chain serves neither row bare", async () => {
+ // The predecessor's pointer edge IS indexed, so its chain resolves
+ // onto the correction - but the correction's own pointer postdates
+ // the index, so the correction's own chain walk answers the
+ // correction as its own tip: unresolved, exactly the stale-pointer
+ // corner the stage drops pool rows for. Appended bare as its
+ // predecessor's correction, the dropped verdict would re-enter the
+ // pool the way the fail-closed rule forbids, so the correction asks
+ // its own coupling question and the predecessor drops with it.
+ page(
+ "chained-predecessor.md",
+ ['superseded_by: "[[chained-correction]]"'],
+ "granite quarry output ledger.",
+ );
+ page("chained-correction.md", [], "revised granite quarry output ledger.");
+ await indexVault(config);
+ page(
+ "chained-correction.md",
+ ['superseded_by: "[[chained-ghost-tip]]"'],
+ "revised granite quarry output ledger.",
+ );
+
+ const out = await search(config, { query: "granite quarry output ledger", limit: 10 });
+ expect(out.results.some((r) => r.path === "chained-predecessor.md")).toBe(false);
+ expect(out.results.some((r) => r.path === "chained-correction.md")).toBe(false);
+ });
+
+ test("a retired row is dropped when its correction is outside the caller's agent scope", async () => {
+ page(
+ "scoped-predecessor.md",
+ ['superseded_by: "[[private-correction]]"'],
+ "nickel plating bath recipe.",
+ );
+ page("private-correction.md", ["owner: agent-a"], "revised nickel plating bath recipe.");
+ await indexVault(config);
+
+ const scoped = await search(config, {
+ query: "nickel plating bath recipe",
+ limit: 10,
+ agentScope: "agent-b",
+ });
+ expect(scoped.results.some((r) => r.path === "scoped-predecessor.md")).toBe(false);
+ expect(scoped.results.some((r) => r.path === "private-correction.md")).toBe(false);
+
+ const unscoped = await search(config, { query: "nickel plating bath recipe", limit: 10 });
+ expect(paths(unscoped.results)).toEqual(["private-correction.md", "scoped-predecessor.md"]);
+ });
+
+ test("a retired row is dropped when its correction is outside the caller's visibility scope", async () => {
+ page(
+ "tagged-predecessor.md",
+ ['superseded_by: "[[tagged-correction]]"'],
+ "harbor depth survey.",
+ );
+ page("tagged-correction.md", ["visibility: internal"], "revised harbor depth survey.");
+ await indexVault(config);
+
+ const inside = await search(config, {
+ query: "harbor depth survey",
+ limit: 10,
+ visibility: ["internal"],
+ });
+ expect(paths(inside.results)).toEqual(["tagged-correction.md", "tagged-predecessor.md"]);
+
+ const outside = await search(config, {
+ query: "harbor depth survey",
+ limit: 10,
+ visibility: ["external"],
+ });
+ expect(outside.results.some((r) => r.path === "tagged-predecessor.md")).toBe(false);
+ expect(outside.results.some((r) => r.path === "tagged-correction.md")).toBe(false);
+ });
+
+ test("a retired row is dropped when its correction fails the caller's composite scope filter", async () => {
+ // The composite session/project scope is one of the pool filters the
+ // coupling verdict's own readability rungs do not carry: without the
+ // verdict asking it, an out-of-scope correction passes the verdict,
+ // rides into the widened pool, and only then falls to the re-filter -
+ // leaving its predecessor served bare. The verdict has to answer the
+ // same filter application the pool answers to.
+ page(
+ "coupled-predecessor.md",
+ ['superseded_by: "[[other-project-correction]]"', "project: alpha"],
+ "meadow soil drainage survey.",
+ );
+ page("other-project-correction.md", ["project: beta"], "revised meadow soil drainage survey.");
+ await indexVault(config);
+
+ // No scope requested: the pair is served coupled, proving the fixture
+ // itself is sound and the drop below is caused by the scope request.
+ const unscoped = await search(config, { query: "meadow soil drainage survey", limit: 10 });
+ expect(paths(unscoped.results)).toEqual([
+ "coupled-predecessor.md",
+ "other-project-correction.md",
+ ]);
+
+ const alpha = await search(config, {
+ query: "meadow soil drainage survey",
+ limit: 10,
+ scope: { project: "alpha" },
+ });
+ // The correction is out of scope, so the predecessor it would
+ // legitimize is dropped with it - never served bare.
+ expect(alpha.results.some((r) => r.path === "coupled-predecessor.md")).toBe(false);
+ expect(alpha.results.some((r) => r.path === "other-project-correction.md")).toBe(false);
+ });
+
+ test("a tombstoned retired row stays dropped even though its correction is readable", async () => {
+ page(
+ "tombstoned-predecessor.md",
+ ["_status: tombstoned", 'superseded_by: "[[correction-tip]]"'],
+ "aperture coupling constant, retracted.",
+ );
+ page("correction-tip.md", [], "revised aperture coupling constant.");
+ await indexVault(config);
+
+ const out = await search(config, { query: "aperture coupling constant", limit: 10 });
+ expect(out.results.some((r) => r.path === "tombstoned-predecessor.md")).toBe(false);
+ expect(paths(out.results)).toEqual(["correction-tip.md"]);
+ });
+
+ test("a pool with no retired rows is unchanged: no drops and no coupling provenance", async () => {
+ page("plain-a.md", [], "orchard pruning in early spring.");
+ page("plain-b.md", [], "orchard irrigation schedules.");
+ await indexVault(config);
+
+ const first = await search(config, { query: "orchard", limit: 10 });
+ const second = await search(config, { query: "orchard", limit: 10 });
+ expect(paths(first.results)).toEqual(["plain-a.md", "plain-b.md"]);
+ for (const r of first.results) {
+ expect(r.reasons.some((reason) => reason.startsWith(CORRECTION_REASON_PREFIX))).toBe(false);
+ }
+ // Recency scores carry the wall clock, so two runs compare on the
+ // stable projection only: which rows, in which order, with which
+ // non-clock provenance. The pin is the absence of coupling edits.
+ expect(first.results.map(stable)).toEqual(second.results.map(stable));
+ });
+});
diff --git a/tests/core/search/relational-arm.test.ts b/tests/core/search/relational-arm.test.ts
index df83602c..c20ec994 100644
--- a/tests/core/search/relational-arm.test.ts
+++ b/tests/core/search/relational-arm.test.ts
@@ -5,6 +5,8 @@
*/
import { test, expect, beforeEach, afterEach, spyOn } from "bun:test";
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
import { indexVault } from "../../../src/core/search/indexer.ts";
import { search } from "../../../src/core/search/search.ts";
@@ -113,3 +115,359 @@ test("a non-relational query is byte-identical between arm on and off (rrf)", as
const on = await search(cfgOn, { query: "alpha topic" });
expect(project(on)).toEqual(project(off));
});
+
+// ─── entity bridges and arm runtime options (truth-correctable-time-aware) ───
+
+import { Database } from "bun:sqlite";
+
+import {
+ ENTITY_BRIDGES_CONFIG,
+ ENTITY_BRIDGES_ENV,
+ resolveEntityBridgesEnabled,
+ runRelationalArm,
+} from "../../../src/core/search/pipeline/relational-arm.ts";
+import { SearchError } from "../../../src/core/search/search-error.ts";
+import type { TraversalBudgets } from "../../../src/core/search/relational-fanout.ts";
+import { TRAVERSAL_MAX_SEEDS_ENV } from "../../../src/core/search/relational-fanout.ts";
+
+test("entity bridges resolve on by default and follow env over config", () => {
+ expect(resolveEntityBridgesEnabled({ env: {} })).toBe(true);
+ expect(
+ resolveEntityBridgesEnabled({ env: {}, config: { [ENTITY_BRIDGES_CONFIG]: "false" } }),
+ ).toBe(false);
+ expect(
+ resolveEntityBridgesEnabled({
+ env: { [ENTITY_BRIDGES_ENV]: "true" },
+ config: { [ENTITY_BRIDGES_CONFIG]: "false" },
+ }),
+ ).toBe(true);
+ expect(() => resolveEntityBridgesEnabled({ env: { [ENTITY_BRIDGES_ENV]: "maybe" } })).toThrow(
+ SearchError,
+ );
+ expect(() => resolveEntityBridgesEnabled({ env: { [ENTITY_BRIDGES_ENV]: "maybe" } })).toThrow(
+ new RegExp(ENTITY_BRIDGES_ENV),
+ );
+ // The refusal names the key ACTUALLY in force: a machine-config value
+ // gone bad names the config key, never the env key that lost the
+ // precedence race.
+ let configRefusal = "";
+ try {
+ resolveEntityBridgesEnabled({ env: {}, config: { [ENTITY_BRIDGES_CONFIG]: "maybe" } });
+ } catch (e) {
+ configRefusal = (e as Error).message;
+ }
+ expect(configRefusal).toContain(ENTITY_BRIDGES_CONFIG);
+ expect(configRefusal).not.toContain(ENTITY_BRIDGES_ENV);
+});
+
+/** The slice of Store the arm needs, with typed edges plus optional bridges. */
+function armFixtureStore(opts: {
+ docs: Record<string, number>;
+ typed: Array<[from: number, relation: string, to: number]>;
+ bridges?: Map<number, number[]>;
+ withReader?: boolean;
+}): Store {
+ const byId = new Map(Object.entries(opts.docs).map(([name, id]) => [id, `${name}.md`]));
+ return {
+ getDocumentIdByPath(path: string) {
+ for (const [id, p] of byId) if (p === path) return id;
+ return null;
+ },
+ documentTitles() {
+ return new Map([...byId].map(([id, path]) => [id, { path, title: null }]));
+ },
+ typedRelationEdgesForDocuments(ids: ReadonlyArray<number>) {
+ const set = new Set(ids);
+ return opts.typed
+ .filter(([from]) => set.has(from))
+ .map(([from, relation, to]) => ({
+ sourceDocumentId: from,
+ relation,
+ target: byId.get(to) ?? "",
+ targetDocumentId: to,
+ }));
+ },
+ ...(opts.withReader
+ ? {
+ entityBridgesForDocuments(ids: ReadonlyArray<number>) {
+ const out: Array<{ sourceDocumentId: number; targetDocumentId: number }> = [];
+ for (const id of ids) {
+ for (const target of opts.bridges?.get(id) ?? []) {
+ out.push({ sourceDocumentId: id, targetDocumentId: target });
+ }
+ }
+ return out;
+ },
+ }
+ : {}),
+ representativeChunks(ids: ReadonlyArray<number>) {
+ const out = new Map();
+ for (const id of ids) {
+ const path = byId.get(id);
+ if (path === undefined) continue;
+ out.set(id, {
+ chunkId: id,
+ documentId: id,
+ path,
+ title: null,
+ content: "",
+ startLine: 1,
+ endLine: 1,
+ mtime: 0,
+ });
+ }
+ return out;
+ },
+ } as unknown as Store;
+}
+
+test("the arm walks entity bridges only when the flag is on", () => {
+ // The per-test vault from beforeEach; the arm's own vocabulary falls
+ // back to the default relation vocabulary for an unreadable schema pack.
+ // seed --related--> typed ; seed ~entity~> bridged
+ const shared = { seed: 1, typed: 2, bridged: 3 };
+ const store = armFixtureStore({
+ docs: shared,
+ typed: [[1, "related", 2]],
+ bridges: new Map([[1, [3]]]),
+ withReader: true,
+ });
+ const on = runRelationalArm(store, vault, "[[seed]] related", { entityBridges: true });
+ expect(on.reachByChunk.get(3)?.via).toEqual(["entity"]);
+ const off = runRelationalArm(store, vault, "[[seed]] related", { entityBridges: false });
+ expect(off.reachByChunk.has(3)).toBe(false);
+ // Flag off is byte-identical to a store with no bridge reader at all.
+ const bare = armFixtureStore({ docs: shared, typed: [[1, "related", 2]] });
+ const bareRun = runRelationalArm(bare, vault, "[[seed]] related", {});
+ expect(JSON.stringify(off)).toBe(JSON.stringify(bareRun));
+});
+
+test("the arm threads the traversal budgets and the deadline into the walk", () => {
+ const store = armFixtureStore({
+ docs: { seed: 1, near: 2, far: 3 },
+ typed: [
+ [1, "related", 2],
+ [2, "related", 3],
+ ],
+ });
+ const budgets: TraversalBudgets = {
+ maxSeeds: 8,
+ maxExpansionPerNode: 4,
+ maxTotalNodes: 1,
+ hubDegreeThreshold: 12,
+ };
+ const capped = runRelationalArm(store, vault, "[[seed]] related", { budgets });
+ expect([...capped.reachByChunk.keys()]).toEqual([2]);
+ const expired = runRelationalArm(store, vault, "[[seed]] related", { isExpired: () => true });
+ expect(expired.rankedChunkIds).toEqual([]);
+});
+
+test("a malformed traversal knob value does not fail a non-relational query", () => {
+ // The config-file re-read and the budget/bridge resolution run only
+ // once the arm knows it will walk: a non-relational query pays no knob
+ // resolution, so a malformed knob value fails no search the knob
+ // cannot affect - and still refuses the relational query it governs.
+ const store = armFixtureStore({ docs: { seed: 1, near: 2 }, typed: [[1, "related", 2]] });
+ const prior = process.env[TRAVERSAL_MAX_SEEDS_ENV];
+ process.env[TRAVERSAL_MAX_SEEDS_ENV] = "maybe";
+ try {
+ expect(() => runRelationalArm(store, vault, "alpha topic", {})).not.toThrow();
+ expect(() => runRelationalArm(store, vault, "[[seed]] related", {})).toThrow(SearchError);
+ } finally {
+ if (prior === undefined) delete process.env[TRAVERSAL_MAX_SEEDS_ENV];
+ else process.env[TRAVERSAL_MAX_SEEDS_ENV] = prior;
+ }
+});
+
+// ─── the search call site threads the arm's runtime options (wiring) ─────────
+//
+// The integrator's pins: the composite recall deadline and the caller's
+// transport reach actually reach the arm in production, the real Store
+// carries the bridge reader the arm's flag enables, and the arm's gated
+// paths land in the retrieval trail. Every pin holds an arm-off mirror so
+// the off shape stays byte-identical.
+
+import { Store } from "../../../src/core/search/store.ts";
+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";
+import { RETRIEVAL_DEGRADATION } from "../../../src/core/search/retrieval-trail.ts";
+import { startFakeHttp, type FakeRequest, type FakeResponseSpec } from "../../helpers/fake-http.ts";
+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
+
+test("the search call site gates the arm's ordered paths at the caller's reach", async () => {
+ await build();
+ // The middle node reserves itself against remote reads; the far node is
+ // readable there. Only a call site that hands the reach to the arm can
+ // withhold the middle hop from the far row's provenance.
+ writeMd(
+ vault,
+ "neighbor.md",
+ '---\nvisibility: ["private"]\nextends: "[[far]]"\n---\n\nbeta divergent content.',
+ );
+ await indexVault(makeConfig({ vault, dbPath }));
+ const cfg = makeConfig({ vault, dbPath, fusionMode: "rrf", relationalArmEnabled: true });
+ const remote = await search(cfg, {
+ query: "alpha [[seed]] related extends",
+ transportReach: TRANSPORT_REACH.remote,
+ });
+ const far = remote.results.find((r) => r.path === "far.md");
+ expect(far).toBeDefined();
+ // The relational reason names the walk but never a withheld count: the
+ // unreadable middle hop is already absent from the provenance path.
+ expect(far!.reasons.some((x) => x.startsWith("relational: via "))).toBe(true);
+ expect(far!.reasons.some((x) => x.includes("withheld"))).toBe(false);
+ // Local reach reads every hop: the same walk withholds nothing, and
+ // the reason shape is the same either way.
+ const local = await search(cfg, { query: "alpha [[seed]] related extends" });
+ const farLocal = local.results.find((r) => r.path === "far.md");
+ expect(farLocal).toBeDefined();
+ expect(farLocal!.reasons.some((x) => x.startsWith("relational: via "))).toBe(true);
+ expect(farLocal!.reasons.some((x) => x.includes("withheld"))).toBe(false);
+});
+
+test("the arm's ordered paths land in the retrieval trail and stay absent when the arm is off", async () => {
+ await build();
+ const cfgOn = makeConfig({ vault, dbPath, fusionMode: "rrf", relationalArmEnabled: true });
+ const on = await search(cfgOn, { query: "alpha [[seed]] related" });
+ const entries = on.retrievalTrail?.relationalPaths;
+ expect(entries).toBeDefined();
+ expect(entries!.length).toBeGreaterThan(0);
+ for (const entry of entries!) {
+ expect(entry.code).toBe("relational-path");
+ expect("withheld" in entry).toBe(false);
+ expect(entry.path.length).toBeGreaterThan(0);
+ }
+ // Arm off: no paths on the trail, whatever else the answer carries -
+ // the pre-change trail shape, byte for byte.
+ const cfgOff = makeConfig({ vault, dbPath, fusionMode: "rrf" });
+ const off = await search(cfgOff, { query: "alpha [[seed]] related" });
+ expect(off.retrievalTrail?.relationalPaths).toBeUndefined();
+ expect("relationalPaths" in (off.retrievalTrail ?? {})).toBe(false);
+});
+
+test("the search call site threads the composite deadline into the arm's walk", async () => {
+ if (!sqliteVecLoadable()) return;
+ await build();
+ const server = await startFakeHttp();
+ try {
+ const cfg = {
+ ...makeConfig({
+ vault,
+ dbPath,
+ fusionMode: "rrf",
+ relationalArmEnabled: true,
+ semantic: {
+ enabled: true,
+ provider: "openai-compat",
+ baseUrl: server.url,
+ model: "fake-model",
+ apiKey: FAKE_PROVIDER_KEY,
+ dimension: 4,
+ timeoutMs: 5_000,
+ concurrency: 2,
+ batchSize: 8,
+ costGateUsd: 0,
+ maxRetries: 1,
+ },
+ }),
+ hybridDeadlineMs: 300,
+ };
+ await indexVault(cfg, { embeddings: true });
+ // A semantic lane that never answers: the composite clock fires on its
+ // timer at the budget, deterministically before the arm runs, so the
+ // arm's first clock check sees a fired deadline and abandons the walk.
+ server.setHandler(() => new Promise<never>(() => {}));
+ const cut = await search(cfg, { query: "alpha [[seed]] related extends", semantic: true });
+ const codes = cut.retrievalTrail?.degraded.map((d) => d.code) ?? [];
+ expect(codes).toContain(RETRIEVAL_DEGRADATION.hybridDeadlineExceeded);
+ expect(cut.results.some((r) => r.path === "far.md")).toBe(false);
+ // The same query with the deadline off (0) runs the walk: the two-hop
+ // node the fired clock withheld is surfaced. The handler answers the
+ // embed request with the same deterministic vectors the helper's
+ // default serves, so only the clock differs between the two runs.
+ server.setHandler((req: FakeRequest): FakeResponseSpec => {
+ if (req.path.endsWith("/embeddings") && req.method === "POST") {
+ const body = (req.body ?? {}) as { input?: string[]; model?: string };
+ const inputs = Array.isArray(body.input) ? body.input : [];
+ return {
+ status: 200,
+ body: {
+ data: inputs.map((text, index) => ({
+ object: "embedding",
+ embedding: [text.split(/\s+/).filter(Boolean).length, index, text.length, 1],
+ index,
+ })),
+ model: body.model ?? "fake-model",
+ },
+ };
+ }
+ return { status: 404, body: { error: "not_found" } };
+ });
+ const unbounded = await search(
+ { ...cfg, hybridDeadlineMs: 0 },
+ {
+ query: "alpha [[seed]] related extends",
+ semantic: true,
+ },
+ );
+ expect(unbounded.results.some((r) => r.path === "far.md")).toBe(true);
+ } finally {
+ await server.close();
+ }
+});
+
+test("the real store carries the bridge reader and the arm walks it live", async () => {
+ await build();
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const seedId = store.getDocumentIdByPath("seed.md");
+ const noiseId = store.getDocumentIdByPath("noise.md");
+ expect(seedId).not.toBeNull();
+ expect(noiseId).not.toBeNull();
+ const seedChunk = store.representativeChunks([seedId!]).get(seedId!)!;
+ const noiseChunk = store.representativeChunks([noiseId!]).get(noiseId!)!;
+ store.replaceEntities(seedChunk.chunkId, ["shared-entity"]);
+ store.replaceEntities(noiseChunk.chunkId, ["shared-entity"]);
+ // The typed surface answers the deduplicated ordered pair, and the
+ // arm's store view picks the reader up from it: bridges on walks the
+ // co-occurrence edge beside the typed one; bridges off never reaches
+ // the bridged document.
+ expect(store.entityBridgesForDocuments([seedId!])).toEqual([
+ { sourceDocumentId: seedId!, targetDocumentId: noiseId! },
+ ]);
+ const on = runRelationalArm(store, vault, "[[seed]] related", { entityBridges: true });
+ expect(on.reachByChunk.get(noiseChunk.chunkId)?.via).toEqual(["entity"]);
+ const off = runRelationalArm(store, vault, "[[seed]] related", { entityBridges: false });
+ expect(off.reachByChunk.has(noiseChunk.chunkId)).toBe(false);
+ } finally {
+ await store.close();
+ }
+});
+
+test("the arm's knobs resolve from the caller's config path, not the default file", async () => {
+ await build();
+ // A config file at a non-default path turning bridges off: the arm
+ // must consult the path its caller threaded (the resolved search
+ // config carries it), and consult no file at all when none is
+ // threaded - never a fresh read of the default config path.
+ const configPath = join(vault, "arm-config.yaml");
+ writeFileSync(configPath, "search_entity_bridges_enabled: false\n");
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const seedId = store.getDocumentIdByPath("seed.md");
+ const noiseId = store.getDocumentIdByPath("noise.md");
+ const seedChunk = store.representativeChunks([seedId!]).get(seedId!)!;
+ const noiseChunk = store.representativeChunks([noiseId!]).get(noiseId!)!;
+ store.replaceEntities(seedChunk.chunkId, ["shared-entity"]);
+ store.replaceEntities(noiseChunk.chunkId, ["shared-entity"]);
+ // The threaded path's off switch governs the walk.
+ const threaded = runRelationalArm(store, vault, "[[seed]] related", { configPath });
+ expect(threaded.reachByChunk.has(noiseChunk.chunkId)).toBe(false);
+ // No threaded path resolves env-only: the file is not consulted and
+ // the bridges default (on) applies.
+ const unthreaded = runRelationalArm(store, vault, "[[seed]] related", {});
+ expect(unthreaded.reachByChunk.get(noiseChunk.chunkId)?.via).toEqual(["entity"]);
+ } finally {
+ await store.close();
+ }
+});
diff --git a/tests/core/search/relational-fanout.test.ts b/tests/core/search/relational-fanout.test.ts
index 5740b69f..eaa5bd22 100644
--- a/tests/core/search/relational-fanout.test.ts
+++ b/tests/core/search/relational-fanout.test.ts
@@ -2,8 +2,25 @@ import { test, expect } from "bun:test";
import {
relationalFanout,
+ resolveTraversalBudgets,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD,
+ TRAVERSAL_HUB_DEGREE_THRESHOLD_ENV,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE_ENV,
+ TRAVERSAL_MAX_SEEDS,
+ TRAVERSAL_MAX_SEEDS_ENV,
+ TRAVERSAL_MAX_TOTAL_NODES,
+ TRAVERSAL_MAX_TOTAL_NODES_ENV,
type RelationalFanoutStore,
} from "../../../src/core/search/relational-fanout.ts";
+import { SearchError } from "../../../src/core/search/search-error.ts";
+import {
+ TRAVERSAL_HUB_DEGREE_THRESHOLD as HUB_FROM_BARREL,
+ TRAVERSAL_MAX_EXPANSION_PER_NODE as EXPANSION_FROM_BARREL,
+ TRAVERSAL_MAX_SEEDS as SEEDS_FROM_BARREL,
+ TRAVERSAL_MAX_TOTAL_NODES as TOTAL_FROM_BARREL,
+ resolveTraversalBudgets as resolveFromBarrel,
+} from "../../../src/core/search/index.ts";
type Edge = {
sourceDocumentId: number;
@@ -12,6 +29,11 @@ type Edge = {
targetDocumentId: number | null;
};
+/** Index a node list by document id. */
+function byIdOf<T extends { documentId: number }>(nodes: T[]): Map<number, T> {
+ return new Map(nodes.map((n) => [n.documentId, n]));
+}
+
/** A fake store whose typed edges are a fixed adjacency list. */
function fakeStore(edges: Edge[]): RelationalFanoutStore {
return {
@@ -70,3 +92,309 @@ test("richness aggregates multiple edges reaching one node; seeds are excluded",
expect(nodes[0]!.edgeRichness).toBe(2);
expect(nodes[0]!.viaLinkTypes).toEqual(["extends", "related"]);
});
+
+// ─── traversal budgets, hub skipping, deadline (truth-correctable-time-aware) ─
+
+/** One typed edge `from -> to`, with the relation defaulting to `related`. */
+function edge(from: number, to: number, relation = "related"): Edge {
+ return { sourceDocumentId: from, relation, target: `doc-${to}`, targetDocumentId: to };
+}
+
+test("traversal budgets ship the planned defaults", () => {
+ expect(TRAVERSAL_MAX_SEEDS).toBe(8);
+ expect(TRAVERSAL_MAX_EXPANSION_PER_NODE).toBe(4);
+ expect(TRAVERSAL_MAX_TOTAL_NODES).toBe(16);
+ expect(TRAVERSAL_HUB_DEGREE_THRESHOLD).toBe(12);
+});
+
+test("the public search surface exposes the traversal budgets", () => {
+ // The config/documentation surface names the knobs through the same
+ // barrel every CLI and MCP consumer already imports - never a private
+ // deep import into the search internals.
+ expect(SEEDS_FROM_BARREL).toBe(TRAVERSAL_MAX_SEEDS);
+ expect(EXPANSION_FROM_BARREL).toBe(TRAVERSAL_MAX_EXPANSION_PER_NODE);
+ expect(TOTAL_FROM_BARREL).toBe(TRAVERSAL_MAX_TOTAL_NODES);
+ expect(HUB_FROM_BARREL).toBe(TRAVERSAL_HUB_DEGREE_THRESHOLD);
+ expect(resolveFromBarrel({ env: {} })).toEqual(resolveTraversalBudgets({ env: {} }));
+});
+
+test("resolveTraversalBudgets defaults to the shipped constants", () => {
+ expect(resolveTraversalBudgets({ env: {} })).toEqual({
+ maxSeeds: TRAVERSAL_MAX_SEEDS,
+ maxExpansionPerNode: TRAVERSAL_MAX_EXPANSION_PER_NODE,
+ maxTotalNodes: TRAVERSAL_MAX_TOTAL_NODES,
+ hubDegreeThreshold: TRAVERSAL_HUB_DEGREE_THRESHOLD,
+ });
+});
+
+test("resolveTraversalBudgets overrides from config and prefers env", () => {
+ const config = {
+ search_traversal_max_seeds: "3",
+ search_traversal_max_expansion_per_node: "2",
+ search_traversal_max_total_nodes: "9",
+ search_traversal_hub_degree_threshold: "5",
+ };
+ expect(resolveTraversalBudgets({ env: {}, config })).toEqual({
+ maxSeeds: 3,
+ maxExpansionPerNode: 2,
+ maxTotalNodes: 9,
+ hubDegreeThreshold: 5,
+ });
+ const env = {
+ [TRAVERSAL_MAX_SEEDS_ENV]: "5",
+ [TRAVERSAL_MAX_EXPANSION_PER_NODE_ENV]: "1",
+ [TRAVERSAL_MAX_TOTAL_NODES_ENV]: "7",
+ [TRAVERSAL_HUB_DEGREE_THRESHOLD_ENV]: "20",
+ };
+ expect(resolveTraversalBudgets({ env, config })).toEqual({
+ maxSeeds: 5,
+ maxExpansionPerNode: 1,
+ maxTotalNodes: 7,
+ hubDegreeThreshold: 20,
+ });
+});
+
+test("resolveTraversalBudgets refuses an out-of-range or non-integer override by name", () => {
+ expect(() => resolveTraversalBudgets({ env: { [TRAVERSAL_MAX_SEEDS_ENV]: "0" } })).toThrow(
+ SearchError,
+ );
+ expect(() => resolveTraversalBudgets({ env: { [TRAVERSAL_MAX_SEEDS_ENV]: "two" } })).toThrow(
+ /OPEN_SECOND_BRAIN_SEARCH_TRAVERSAL_MAX_SEEDS/,
+ );
+ expect(() =>
+ resolveTraversalBudgets({ config: { search_traversal_max_total_nodes: "-1" } }),
+ ).toThrow(/search_traversal_max_total_nodes/);
+});
+
+test("the seed cap bounds the walk to the first TRAVERSAL_MAX_SEEDS seeds", () => {
+ // Ten isolated seeds, each with one private neighbour below every cap.
+ const edges: Edge[] = [];
+ for (let s = 1; s <= 10; s++) edges.push(edge(s, 100 + s));
+ const nodes = relationalFanout(fakeStore(edges), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {
+ maxDepth: 1,
+ });
+ expect(nodes.map((n) => n.documentId).toSorted((a, b) => a - b)).toEqual([
+ 101, 102, 103, 104, 105, 106, 107, 108,
+ ]);
+});
+
+test("the per-node cap bounds expansion to the first edges of each node", () => {
+ // Seed 1 declares six edges; only the first four may be followed.
+ const edges = [1, 2, 3, 4, 5, 6].map((to) => edge(1, to));
+ const nodes = relationalFanout(fakeStore(edges), [1], { maxDepth: 1 });
+ expect(nodes.map((n) => n.documentId).toSorted((a, b) => a - b)).toEqual([1, 2, 3, 4]);
+});
+
+test("the total-node cap bounds the reached set", () => {
+ // A per-node override lets one seed declare twenty children; the walk
+ // still keeps only the first TRAVERSAL_MAX_TOTAL_NODES of them.
+ const edges = Array.from({ length: 20 }, (_, i) => edge(1, i + 1));
+ const nodes = relationalFanout(fakeStore(edges), [1], {
+ maxDepth: 1,
+ maxExpansionPerNode: 32,
+ });
+ expect(nodes).toHaveLength(TRAVERSAL_MAX_TOTAL_NODES);
+ expect(nodes.map((n) => n.documentId)).toEqual([
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ ]);
+});
+
+test("a node past the hub degree threshold is reached but not expanded", () => {
+ // Seed 1 -> hub (13 edges, over the threshold) and -> plain (12 edges,
+ // exactly at it). The hub's children stay unreached; the plain node's
+ // are walked.
+ const hub = 2;
+ const plain = 3;
+ const edges: Edge[] = [edge(1, hub), edge(1, plain)];
+ for (let c = 0; c < 13; c++) edges.push(edge(hub, 100 + c));
+ for (let c = 0; c < 12; c++) edges.push(edge(plain, 200 + c));
+ const byId = new Map(
+ relationalFanout(fakeStore(edges), [1], { maxDepth: 2 }).map((n) => [n.documentId, n]),
+ );
+ expect(byId.get(hub)!.hops).toBe(1);
+ expect(byId.has(100)).toBe(false);
+ expect(byId.has(200)).toBe(true);
+});
+
+test("a fired deadline abandons the frontier keeping the nodes already reached", () => {
+ // 1 -> 2 -> 3, depth 2. The clock fires before the second round, so
+ // the depth-1 node stays and the depth-2 node never appears.
+ const store = fakeStore([edge(1, 2), edge(2, 3)]);
+ let checks = 0;
+ const nodes = relationalFanout(store, [1], {
+ maxDepth: 2,
+ isExpired: () => {
+ checks += 1;
+ return checks > 1;
+ },
+ });
+ expect(nodes.map((n) => n.documentId)).toEqual([2]);
+});
+
+test("a deadline that is already fired abandons the walk before any expansion", () => {
+ const store = fakeStore([edge(1, 2), edge(2, 3)]);
+ const nodes = relationalFanout(store, [1], { maxDepth: 2, isExpired: () => true });
+ expect(nodes).toEqual([]);
+});
+
+test("the walk is deterministic across repeated runs under the caps", () => {
+ const edges: Edge[] = [];
+ for (let s = 1; s <= 10; s++) {
+ edges.push(edge(s, 100 + s));
+ edges.push(edge(s, 200 + s, "extends"));
+ }
+ const store = fakeStore(edges);
+ const seeds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ const first = relationalFanout(store, seeds, { maxDepth: 2 });
+ const second = relationalFanout(store, seeds, { maxDepth: 2 });
+ expect(JSON.stringify(second)).toBe(JSON.stringify(first));
+});
+
+// ─── entity bridges from chunk_entities (truth-correctable-time-aware) ───────
+
+/**
+ * A fake store with typed edges plus an entity-bridge adjacency list.
+ * `bridges` maps a source document id to the targets its entity set
+ * bridges to, in the order the real reader returns them (target id asc).
+ */
+function bridgedStore(edges: Edge[], bridges: Map<number, number[]>): RelationalFanoutStore {
+ return {
+ typedRelationEdgesForDocuments(ids) {
+ const set = new Set(ids);
+ return edges.filter((e) => set.has(e.sourceDocumentId));
+ },
+ entityBridgesForDocuments(ids) {
+ const out: Array<{ sourceDocumentId: number; targetDocumentId: number }> = [];
+ for (const id of [...ids].toSorted((a, b) => a - b)) {
+ for (const target of bridges.get(id) ?? [])
+ out.push({ sourceDocumentId: id, targetDocumentId: target });
+ }
+ return out;
+ },
+ };
+}
+
+test("entity bridges walk as entity-labeled edges beside the typed edges", () => {
+ // Seed 1: one typed edge to 2, one entity bridge to 3. Both are reached
+ // at hop 1; the bridge node's link type is the `entity` label.
+ const store = bridgedStore([edge(1, 2, "related")], new Map([[1, [3]]]));
+ const byId = new Map(relationalFanout(store, [1], { maxDepth: 1 }).map((n) => [n.documentId, n]));
+ expect(byId.get(2)!.viaLinkTypes).toEqual(["related"]);
+ expect(byId.get(3)!.viaLinkTypes).toEqual(["entity"]);
+ expect(byId.get(3)!.hops).toBe(1);
+});
+
+test("bridge edges count toward hub degree and consume the expansion budget", () => {
+ // Node 2 is reached by one typed edge and carries 12 typed children plus
+ // one bridge child: walked degree 13 exceeds the threshold, so none of
+ // its children - bridge child included - are reached. Node 3 carries 12
+ // typed children only, exactly at the threshold, and expands.
+ const edges: Edge[] = [edge(1, 2), edge(1, 3)];
+ for (let c = 0; c < 12; c++) edges.push(edge(2, 100 + c));
+ for (let c = 0; c < 12; c++) edges.push(edge(3, 200 + c));
+ const store = bridgedStore(edges, new Map([[2, [300]]]));
+ const byId = new Map(relationalFanout(store, [1], { maxDepth: 2 }).map((n) => [n.documentId, n]));
+ expect(byId.has(300)).toBe(false);
+ expect(byId.has(200)).toBe(true);
+ // The expansion cap spans both edge kinds: seed 1 has two typed edges
+ // and two bridges with a per-node cap of 3, so only the first bridge
+ // target is reached.
+ const capped = bridgedStore([edge(1, 2), edge(1, 3)], new Map([[1, [4, 5]]]));
+ const ids = relationalFanout(capped, [1], { maxDepth: 1, maxExpansionPerNode: 3 })
+ .map((n) => n.documentId)
+ .toSorted((a, b) => a - b);
+ expect(ids).toEqual([2, 3, 4]);
+});
+
+test("bridge targets spend the total-node cap and a bridge may reach a seed id", () => {
+ // Seed 1 with one typed edge (target 2) and bridges to 1..20: the total
+ // cap admits the first TRAVERSAL_MAX_TOTAL_NODES walked targets in edge
+ // order, and a bridge pointing back at the seed reaches it like any
+ // target (the walk is over reached ids, seeds are entry points only).
+ const store = bridgedStore([edge(1, 2)], new Map([[1, [1, 2, 3]]]));
+ const nodes = relationalFanout(store, [1], { maxDepth: 1, maxExpansionPerNode: 32 });
+ // Node 2 is reached twice (typed edge plus bridge) and outranks the
+ // once-reached pair; the seed id 1 - reached only through the bridge -
+ // surfaces among them.
+ expect(nodes.map((n) => n.documentId)).toEqual([2, 1, 3]);
+ expect(byIdOf(nodes).get(1)!.viaLinkTypes).toEqual(["entity"]);
+});
+
+test("an absent bridge reader leaves the walk byte-identical to the typed-only walk", () => {
+ // The same typed fixture, walked once by a store without the reader and
+ // once by a store whose reader answers empty: identical output, so the
+ // pre-bridge walk is a strict special case.
+ const edges: Edge[] = [edge(1, 2, "related"), edge(2, 3, "extends")];
+ const without = relationalFanout(fakeStore(edges), [1], { maxDepth: 2 });
+ const withEmpty = relationalFanout(bridgedStore(edges, new Map()), [1], { maxDepth: 2 });
+ expect(JSON.stringify(withEmpty)).toBe(JSON.stringify(without));
+});
+
+// ─── the chunk_entities bridge reader (truth-correctable-time-aware) ─────────
+
+import { Database } from "bun:sqlite";
+
+import { entityBridgesForDocuments } from "../../../src/core/search/store/entity-bridges.ts";
+
+/** Minimal `chunks` + `chunk_entities` fixture with the reader's join columns. */
+function bridgeDb(): Database {
+ const db = new Database(":memory:");
+ db.run("CREATE TABLE chunks (id INTEGER PRIMARY KEY, document_id INTEGER NOT NULL)");
+ db.run(
+ "CREATE TABLE chunk_entities (" +
+ "chunk_id INTEGER NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, " +
+ "entity TEXT NOT NULL, PRIMARY KEY (chunk_id, entity))",
+ );
+ return db;
+}
+
+function bridgeFixtures(db: Database, rows: Array<[chunkId: number, documentId: number]>): void {
+ for (const [chunkId, documentId] of rows) {
+ db.run("INSERT INTO chunks (id, document_id) VALUES (?, ?)", [chunkId, documentId]);
+ }
+}
+
+function addEntities(db: Database, chunkId: number, entities: ReadonlyArray<string>): void {
+ for (const e of entities)
+ db.run("INSERT INTO chunk_entities (chunk_id, entity) VALUES (?, ?)", [chunkId, e]);
+}
+
+test("the bridge reader joins chunk_entities into deduplicated ordered pairs", () => {
+ using db = bridgeDb();
+ bridgeFixtures(db, [
+ [1, 10],
+ [2, 20],
+ [3, 30],
+ [4, 40],
+ ]);
+ // Docs 10 and 20 share TWO entities; doc 30 shares one with 10; doc 40
+ // shares nothing.
+ addEntities(db, 1, ["alpha", "beta"]);
+ addEntities(db, 2, ["alpha", "beta"]);
+ addEntities(db, 3, ["beta"]);
+ addEntities(db, 4, ["gamma"]);
+ expect(entityBridgesForDocuments(db, [10])).toEqual([
+ { sourceDocumentId: 10, targetDocumentId: 20 },
+ { sourceDocumentId: 10, targetDocumentId: 30 },
+ ]);
+ // Asking for both sources keeps the same per-source ordering.
+ expect(entityBridgesForDocuments(db, [10, 20])).toEqual([
+ { sourceDocumentId: 10, targetDocumentId: 20 },
+ { sourceDocumentId: 10, targetDocumentId: 30 },
+ { sourceDocumentId: 20, targetDocumentId: 10 },
+ { sourceDocumentId: 20, targetDocumentId: 30 },
+ ]);
+});
+
+test("the bridge reader excludes self pairs and answers empty input with empty", () => {
+ using db = bridgeDb();
+ bridgeFixtures(db, [
+ [1, 10],
+ [2, 10],
+ ]);
+ // Both chunks of document 10 carry the entity; no self pair may appear.
+ addEntities(db, 1, ["alpha"]);
+ addEntities(db, 2, ["alpha"]);
+ expect(entityBridgesForDocuments(db, [10])).toEqual([]);
+ expect(entityBridgesForDocuments(db, [])).toEqual([]);
+});
diff --git a/tests/core/search/relational-path.test.ts b/tests/core/search/relational-path.test.ts
new file mode 100644
index 00000000..8ab07563
--- /dev/null
+++ b/tests/core/search/relational-path.test.ts
@@ -0,0 +1,495 @@
+/**
+ * Ordered path provenance with per-node reach gating
+ * (truth-correctable-time-aware): the fan-out records the ordered
+ * `{ documentId, relation }` steps that reached each node; the arm gates
+ * every path node at the caller's transport reach and owner scope
+ * (unreadable or out-of-scope nodes are omitted, never named and never
+ * counted), annotates a readable non-tip superseded predecessor with a
+ * closed validity window, and attribution renders the hop distance.
+ */
+
+import { test, expect, beforeEach, afterEach, spyOn } from "bun:test";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { relationalFanout } from "../../../src/core/search/relational-fanout.ts";
+import { Store } from "../../../src/core/search/store.ts";
+import { runRelationalArm } from "../../../src/core/search/pipeline/relational-arm.ts";
+import { decorateFinalResults } from "../../../src/core/search/pipeline/attribution.ts";
+import {
+ buildRetrievalTrail,
+ retrievalTrailEnvelope,
+ RETRIEVAL_RELATIONAL_PATH_CODE,
+ type RelationalPathTrailEntry,
+} from "../../../src/core/search/retrieval-trail.ts";
+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+beforeEach(() => {
+ const v = createTempVault("relational-path");
+ vault = v.vault;
+ dbPath = v.dbPath;
+ cleanup = v.cleanup;
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+// ─── the fanout records the ordered path ─────────────────────────────────────
+
+test("a reached node carries the ordered steps that first reached it", () => {
+ const store = {
+ typedRelationEdgesForDocuments(ids: ReadonlyArray<number>) {
+ const set = new Set(ids);
+ return [
+ { sourceDocumentId: 1, relation: "related", target: "b", targetDocumentId: 2 },
+ { sourceDocumentId: 1, relation: "related", target: "d", targetDocumentId: 4 },
+ { sourceDocumentId: 2, relation: "extends", target: "c", targetDocumentId: 3 },
+ { sourceDocumentId: 4, relation: "related", target: "c", targetDocumentId: 3 },
+ ].filter((e) => set.has(e.sourceDocumentId));
+ },
+ };
+ const byId = new Map(relationalFanout(store, [1], { maxDepth: 2 }).map((n) => [n.documentId, n]));
+ // Node 3 is reachable at the same depth two ways; the path is the one
+ // that reached it FIRST in deterministic frontier order (node 2 expanded
+ // before node 4). Later arrivals never rewrite it.
+ expect(byId.get(2)!.path).toEqual([{ documentId: 2, relation: "related" }]);
+ expect(byId.get(3)!.path).toEqual([
+ { documentId: 2, relation: "related" },
+ { documentId: 3, relation: "extends" },
+ ]);
+});
+
+test("a bridge step carries the entity relation in the path", () => {
+ const store = {
+ typedRelationEdgesForDocuments() {
+ return [];
+ },
+ entityBridgesForDocuments() {
+ return [{ sourceDocumentId: 1, targetDocumentId: 2 }];
+ },
+ };
+ const nodes = relationalFanout(store, [1], { maxDepth: 1 });
+ expect(nodes.map((n) => n.path)).toEqual([[{ documentId: 2, relation: "entity" }]]);
+});
+
+// ─── per-node reach gating in the arm ────────────────────────────────────────
+
+/** seed --related--> mid --extends--> far, indexed for real. */
+async function buildPathVault(): Promise<void> {
+ writeMd(
+ vault,
+ "seed.md",
+ '---\nrelated: "[[mid]]"\n---\n\nalpha seed document for the path walk.',
+ );
+ writeMd(vault, "mid.md", '---\nextends: "[[far]]"\n---\n\nbeta mid document for the path walk.');
+ writeMd(vault, "far.md", "# Far\n\ngamma far document for the path walk.");
+ await indexVault(makeConfig({ vault, dbPath }));
+}
+
+test("path nodes unreadable at the caller's reach are omitted, never named and never counted", async () => {
+ await buildPathVault();
+ writeMd(vault, "mid.md", '---\nvisibility: ["private"]\nextends: "[[far]]"\n---\n\nbeta mid.');
+ await indexVault(makeConfig({ vault, dbPath }));
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const remote = runRelationalArm(store, vault, "[[seed]] related extends", {
+ reach: TRANSPORT_REACH.remote,
+ });
+ const farEntry = [...remote.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(farEntry).toBeDefined();
+ // The withheld middle node is omitted from the ordered path; the far
+ // node itself is readable and keeps its own step.
+ expect(farEntry![1].path).toEqual([{ documentId: farEntry![0], relation: "extends" }]);
+ // Nothing counts it: a withheld node is dropped under the views'
+ // identical-to-absent convention, so the provenance answer is the
+ // same whether the walk crossed an unreadable document or not.
+ expect("withheld" in farEntry![1]).toBe(false);
+ // At an explicitly local reach the same walk keeps the whole path.
+ const local = runRelationalArm(store, vault, "[[seed]] related extends", {
+ reach: TRANSPORT_REACH.local,
+ });
+ const farLocal = [...local.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(farLocal![1].path.map((step) => step.relation)).toEqual(["related", "extends"]);
+ } finally {
+ await store.close();
+ }
+});
+
+test("an absent reach behaves like remote: provenance never names a page the row gate withholds", async () => {
+ // The row-level filters resolve an absent reach to remote
+ // (`resolvedTransportReach`), so the arm's per-node provenance gate
+ // must answer the same question with the same answer: a page the
+ // remote row gate withholds is never named in an ordered path and
+ // never contributes its supersession tip - a library caller passing no
+ // reach must not learn more from provenance than the rows show.
+ await buildPathVault();
+ writeMd(
+ vault,
+ "mid.md",
+ '---\nvisibility: ["private"]\nextends: "[[far]]"\nsuperseded_by: "[[far]]"\nvalid_until: "2020-01-01"\n---\n\nbeta mid.',
+ );
+ await indexVault(makeConfig({ vault, dbPath }));
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const midId = store.getDocumentIdByPath("mid.md");
+ expect(midId).not.toBeNull();
+ const midChunk = store.representativeChunks([midId!]).get(midId!)!;
+ const absent = runRelationalArm(store, vault, "[[seed]] related extends", {});
+ const absentEntry = absent.reachByChunk.get(midChunk.chunkId);
+ expect(absentEntry).toBeDefined();
+ // The withheld middle page's id is never named and its closed-window
+ // tip never announced: provenance reads the same as the row gate.
+ expect(absentEntry!.path).toEqual([]);
+ expect(absentEntry!.supersededBy).toBeUndefined();
+ // An explicitly local reach keeps the wide walk: the local caller
+ // sees the whole path and the annotation.
+ const local = runRelationalArm(store, vault, "[[seed]] related extends", {
+ reach: TRANSPORT_REACH.local,
+ });
+ const localEntry = local.reachByChunk.get(midChunk.chunkId);
+ expect(localEntry).toBeDefined();
+ expect(localEntry!.path).toEqual([{ documentId: midId!, relation: "related" }]);
+ expect(localEntry!.supersededBy).toBe("far");
+ } finally {
+ await store.close();
+ }
+});
+
+test("path nodes outside the caller's owner scope are omitted, never named and never counted", async () => {
+ // Owner scope is the same isolation the row-level filters apply: a
+ // path node that is reach-readable but owned by another agent must be
+ // withheld from the provenance exactly like an unreadable one, or its
+ // document id would ride along in the trail as an existence signal the
+ // content rows never give.
+ await buildPathVault();
+ writeMd(vault, "mid.md", '---\nowner: agent-a\nextends: "[[far]]"\n---\n\nbeta mid.');
+ await indexVault(makeConfig({ vault, dbPath }));
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const scoped = runRelationalArm(store, vault, "[[seed]] related extends", {
+ agentScope: "agent-b",
+ });
+ const farScoped = [...scoped.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(farScoped).toBeDefined();
+ // The owner-hidden middle node is omitted from the ordered path; the
+ // far node keeps only its own step, and nothing counts the omission.
+ expect(farScoped![1].path).toEqual([{ documentId: farScoped![0], relation: "extends" }]);
+ expect("withheld" in farScoped![1]).toBe(false);
+ // No step anywhere names the hidden node's document id.
+ const hiddenId = store.getDocumentIdByPath("mid.md");
+ for (const [, reach] of scoped.reachByChunk) {
+ for (const step of reach.path) {
+ expect(step.documentId).not.toBe(hiddenId);
+ }
+ }
+ // Without a requested scope the same walk keeps the whole path: the
+ // ownership gate is opt-in isolation, never a default narrowing.
+ const unscoped = runRelationalArm(store, vault, "[[seed]] related extends", {});
+ const farUnscoped = [...unscoped.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(farUnscoped![1].path.map((step) => step.relation)).toEqual(["related", "extends"]);
+ } finally {
+ await store.close();
+ }
+});
+
+test("a readable non-tip predecessor with a closed window is annotated from frontmatter", async () => {
+ // Every write and index completes before a store is opened: an open
+ // write-mode store holds the writer lock the indexer needs.
+ await buildPathVault();
+ writeMd(
+ vault,
+ "mid.md",
+ '---\nextends: "[[far]]"\nsuperseded_by: "[[far]]"\nvalid_until: "2020-01-01"\n---\n\nbeta mid.',
+ );
+ await indexVault(makeConfig({ vault, dbPath }));
+ const closed = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const outcome = runRelationalArm(closed, vault, "[[seed]] related extends", {});
+ const farEntry = [...outcome.reachByChunk].find(([, reach]) => reach.hops === 2);
+ // The frontmatter pointer names the tip; the window is already past.
+ expect(farEntry![1].supersededBy).toBe("far");
+ } finally {
+ await closed.close();
+ }
+ // An open window is not a closed one: the same pointer with a future
+ // validity end stays unannotated.
+ writeMd(
+ vault,
+ "mid.md",
+ '---\nextends: "[[far]]"\nsuperseded_by: "[[far]]"\nvalid_until: "2099-12-31"\n---\n\nbeta mid.',
+ );
+ await indexVault(makeConfig({ vault, dbPath }));
+ const open = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ try {
+ const openOutcome = runRelationalArm(open, vault, "[[seed]] related extends", {});
+ const openFar = [...openOutcome.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(openFar![1].supersededBy).toBeUndefined();
+ } finally {
+ await open.close();
+ }
+});
+
+test("the closed-window annotation reads the grammar's inclusive end as still inside the window", async () => {
+ // The shared frontmatter grammar (src/core/search/validity.ts) snaps a
+ // bare `valid_until` date to its whole final day - the end is
+ // inclusive - so at the boundary instant itself the window is still
+ // open and the page is not yet a closed predecessor. One millisecond
+ // past the end, the annotation appears.
+ await buildPathVault();
+ writeMd(
+ vault,
+ "mid.md",
+ '---\nextends: "[[far]]"\nsuperseded_by: "[[far]]"\nvalid_until: "2099-12-31"\n---\n\nbeta mid.',
+ );
+ await indexVault(makeConfig({ vault, dbPath }));
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "write", loadVec: false });
+ // The grammar's day-end edge: the last millisecond of 2099-12-31.
+ const dayEndMs = Date.UTC(2099, 11, 31) + 24 * 60 * 60 * 1000 - 1;
+ const clockAt = (ms: number): (() => void) => {
+ const spy = spyOn(Date, "now").mockReturnValue(ms);
+ return () => spy.mockRestore();
+ };
+ try {
+ const restoreAtBoundary = clockAt(dayEndMs);
+ try {
+ const atBoundary = runRelationalArm(store, vault, "[[seed]] related extends", {});
+ const farEntry = [...atBoundary.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(farEntry).toBeDefined();
+ expect(farEntry![1].supersededBy).toBeUndefined();
+ } finally {
+ restoreAtBoundary();
+ }
+ const restorePastBoundary = clockAt(dayEndMs + 1);
+ try {
+ const pastBoundary = runRelationalArm(store, vault, "[[seed]] related extends", {});
+ const farPast = [...pastBoundary.reachByChunk].find(([, reach]) => reach.hops === 2);
+ expect(farPast).toBeDefined();
+ expect(farPast![1].supersededBy).toBe("far");
+ } finally {
+ restorePastBoundary();
+ }
+ } finally {
+ await store.close();
+ }
+});
+
+// ─── attribution renders the hop distance and the annotation ─────────────────
+
+test("the attribution reason renders hops and the annotation, never a withheld count", () => {
+ const base = {
+ documentId: 1,
+ chunkId: 11,
+ path: "a.md",
+ title: null,
+ content: "body",
+ startLine: 1,
+ endLine: 1,
+ score: 1,
+ keywordScore: 0,
+ semanticScore: 0,
+ linkBoost: 0,
+ recencyBoost: 0,
+ searchType: "link" as const,
+ reasons: [],
+ breakdown: undefined,
+ };
+ const reach = new Map([
+ [
+ 11,
+ {
+ via: ["extends"],
+ hops: 2,
+ path: [{ documentId: 3, relation: "extends" }],
+ },
+ ],
+ [
+ 12,
+ {
+ via: ["related"],
+ hops: 1,
+ path: [{ documentId: 2, relation: "related" }],
+ supersededBy: "tip",
+ },
+ ],
+ ]);
+ const decorated = decorateFinalResults({
+ store: {
+ typedRelationsForDocuments: () => new Map(),
+ } as never,
+ results: [
+ { ...base, chunkId: 11, documentId: 3 },
+ { ...base, chunkId: 12, documentId: 2 },
+ ],
+ structured: undefined,
+ activeLearned: null,
+ canonicalMatchByChunk: undefined,
+ canonicalSourceIds: [],
+ secondPass: undefined,
+ targetedChunkIds: new Set(),
+ relationalReach: reach,
+ });
+ const reasons = decorated.map((r) => r.reasons);
+ expect(reasons[0]).toEqual(["relational: via extends (2 hops)"]);
+ expect(reasons[1]).toEqual(["relational: via related (1 hop)", "superseded_by: tip"]);
+ // No reason string states how many path nodes were withheld: the
+ // omitted steps are already absent from the path, and a count would
+ // tell the caller a node it may not see exists.
+ for (const row of reasons) {
+ for (const reason of row) expect(reason).not.toContain("withheld");
+ }
+});
+
+// ─── the ordered path lands in the retrieval trail as a typed code ───────────
+
+test("the trail carries the relational path with readable ids, and never a withheld count", () => {
+ const trail = buildRetrievalTrail({
+ retrieved: 1,
+ pool: 3,
+ degraded: [],
+ relationalPaths: [{ code: RETRIEVAL_RELATIONAL_PATH_CODE, path: [2, 3] }],
+ });
+ expect(trail?.relationalPaths).toEqual([{ code: "relational-path", path: [2, 3] }]);
+ const envelope = retrievalTrailEnvelope({ retrievalTrail: trail });
+ expect(envelope.retrieval_trail).toMatchObject({
+ relational_paths: [{ code: "relational-path", path: [2, 3] }],
+ });
+ expect(JSON.stringify(envelope)).not.toContain("withheld");
+ // Absent paths keep the envelope byte-identical to the pre-change shape.
+ const plain = buildRetrievalTrail({
+ retrieved: 1,
+ pool: 3,
+ degraded: [{ code: "index-stale" }],
+ });
+ expect(plain?.relationalPaths).toBeUndefined();
+ expect(
+ "relational_paths" in
+ (retrievalTrailEnvelope({ retrievalTrail: plain }).retrieval_trail as object),
+ ).toBe(false);
+});
+
+// ─── the outcome builder passes the paths to the trail (integrator wiring) ───
+
+import { buildSearchOutcome, withIndexStale } from "../../../src/core/search/pipeline/outcome.ts";
+import type { BrainSearchResult, SearchOutcome } from "../../../src/core/search/types.ts";
+
+/** A minimal result row the outcome builder and attribution both accept. */
+function row(chunkId: number, documentId: number): BrainSearchResult {
+ return {
+ documentId,
+ chunkId,
+ path: `doc-${documentId}.md`,
+ title: null,
+ content: "body",
+ startLine: 1,
+ endLine: 1,
+ score: 1,
+ keywordScore: 0,
+ semanticScore: 0,
+ linkBoost: 0,
+ recencyBoost: 0,
+ searchType: "link",
+ reasons: [],
+ breakdown: undefined,
+ };
+}
+
+test("the outcome builder projects surfaced relational rows into the trail, ranked order", async () => {
+ await buildPathVault();
+ const config = makeConfig({ vault, dbPath });
+ const store = await Store.open(config, { mode: "write", loadVec: false });
+ try {
+ const baseInput = {
+ store,
+ config,
+ opts: { query: "alpha seed document" },
+ query: "alpha seed document",
+ pathPrefix: undefined,
+ results: [row(11, 3), row(12, 2)],
+ warnings: [],
+ secondPass: undefined,
+ routedSurface: "default" as const,
+ trustReceipts: null,
+ frontmatterCache: new Map(),
+ poolSize: 3,
+ degraded: [],
+ corpus: null,
+ };
+ const reach = new Map([
+ [
+ 12,
+ {
+ via: ["related"],
+ hops: 1,
+ path: [{ documentId: 2, relation: "related" }],
+ },
+ ],
+ [
+ 11,
+ {
+ via: ["extends"],
+ hops: 2,
+ path: [{ documentId: 3, relation: "extends" }],
+ },
+ ],
+ ]);
+ const outcome = buildSearchOutcome({ ...baseInput, relationalReach: reach });
+ // One entry per surfaced relational row, in ranked order, carrying the
+ // readable document ids. A walked-but-unreadable node contributes no
+ // entry and no count: the answer reads the same as a walk that never
+ // crossed it.
+ expect(outcome.retrievalTrail?.relationalPaths).toEqual([
+ { code: "relational-path", path: [3] },
+ { code: "relational-path", path: [2] },
+ ]);
+ // The arm-off shape: no reach map, no trail at all on a healthy answer.
+ const off = buildSearchOutcome(baseInput);
+ expect(off.retrievalTrail).toBeUndefined();
+ // Reach entries for rows that did not surface project to nothing.
+ const sunk = buildSearchOutcome({
+ ...baseInput,
+ results: [row(99, 9)],
+ poolSize: 1,
+ relationalReach: reach,
+ });
+ expect(sunk.retrievalTrail).toBeUndefined();
+ } finally {
+ await store.close();
+ }
+});
+
+test("the stale-index rebuild carries the arm's paths and stays byte-identical without them", () => {
+ const paths: RelationalPathTrailEntry[] = [
+ { code: RETRIEVAL_RELATIONAL_PATH_CODE, path: [2, 3] },
+ ];
+ const withPaths = {
+ results: [],
+ warnings: [],
+ total: 3,
+ idfWeightedCoverage: 0,
+ retrievalTrail: { retrieved: 1, pool: 3, degraded: [], relationalPaths: paths },
+ } as unknown as SearchOutcome;
+ const stale = withIndexStale(withPaths, 100_000);
+ expect(stale.retrievalTrail?.degraded.map((d) => d.code)).toEqual(["index-stale"]);
+ // Provenance is not a degradation statement: it survives the rebuild.
+ expect(stale.retrievalTrail?.relationalPaths).toEqual(paths);
+ // Without paths the rebuilt trail is exactly the pre-change shape.
+ const plain = {
+ results: [],
+ warnings: [],
+ total: 3,
+ idfWeightedCoverage: 0,
+ retrievalTrail: { retrieved: 1, pool: 3, degraded: [] },
+ } as unknown as SearchOutcome;
+ const stalePlain = withIndexStale(plain, 100_000);
+ expect(stalePlain.retrievalTrail).toEqual({
+ retrieved: 1,
+ pool: 3,
+ degraded: [{ code: "index-stale", detail: { ageSeconds: 100_000 } }],
+ });
+ expect("relationalPaths" in (stalePlain.retrievalTrail ?? {})).toBe(false);
+});
diff --git a/tests/core/search/typed-relations.test.ts b/tests/core/search/typed-relations.test.ts
index 03aeed67..bef2e10b 100644
--- a/tests/core/search/typed-relations.test.ts
+++ b/tests/core/search/typed-relations.test.ts
@@ -73,6 +73,11 @@ test("a plain page with no relation frontmatter produces no typed edges", async
test("search surfaces a result page's declared relations inline", async () => {
writeMd(vault, "a.md", PAGE_A);
+ // The declared successor must exist and be readable: the
+ // serve-with-correction coupling drops a retired-but-serveable page
+ // whose chain tip is unresolved, and this test's subject is inline
+ // relation surfacing, not retired-row serving.
+ writeMd(vault, "c.md", "The settled successor record for the alpha page.");
const cfg = makeConfig({ vault, dbPath });
await indexVault(cfg);
diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.ts
index 94694c6a..ae0ccdf7 100644
--- a/tests/helpers/tool-probe-catalogue.ts
+++ b/tests/helpers/tool-probe-catalogue.ts
@@ -297,7 +297,7 @@ export const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REAS
* test that reads them.
*/
export const PROBE_ENTRY_COUNT = 101;
-export const PROBE_RECIPE_COUNT = 233;
+export const PROBE_RECIPE_COUNT = 234;
export const PROBE_TWO_SIDED_COUNT = 32;
/**
@@ -803,6 +803,15 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
},
reason: REASON.writerEcho,
},
+ {
+ args: {
+ action: "correct",
+ target: "notes/shared.md",
+ value: "probe",
+ reason: "probe",
+ },
+ reason: REASON.writerEcho,
+ },
],
},
{
diff --git a/tests/mcp/brain-lifecycle-correct.test.ts b/tests/mcp/brain-lifecycle-correct.test.ts
new file mode 100644
index 00000000..21dbd515
--- /dev/null
+++ b/tests/mcp/brain-lifecycle-correct.test.ts
@@ -0,0 +1,525 @@
+/**
+ * The `brain_lifecycle` `correct` action and the `o2b brain lifecycle
+ * correct` CLI verb (truth-correctable-time-aware, Task 17).
+ *
+ * Both surfaces expose the correct-verb sweep core with `dry_run`
+ * defaulting to true, a `flatly_wrong` flag, an optional `window_end`,
+ * and reach-gated targets: a target the caller may not read is refused
+ * as missing before anything is written. The receipt reason codes stay
+ * the existing vocabulary, name-aligned with the verb and action
+ * (`supersede` for validity_close, `tombstone` for tombstone).
+ */
+
+import { afterEach, afterAll, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { parseFrontmatter } from "../../src/core/vault.ts";
+import { appendClaimEvent, readClaimEvents } from "../../src/core/brain/truth/store.ts";
+import {
+ buildReachLogFixture,
+ reachServer,
+ type ReachLogFixture,
+} from "../helpers/reach-log-fixture.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { cmdBrainLifecycle } from "../../src/cli/brain/verbs/lifecycle.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { tempDirs } from "../helpers/temp-dir.ts";
+
+afterAll(() => {
+ delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+});
+
+const mkTemp = tempDirs();
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-lifecycle-correct-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-lifecycle-correct-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "lifecycle-correct-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+async function call(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_lifecycle", arguments: args },
+ })) as { result?: { content: ReadonlyArray<{ type: string; text: string }> }; error?: unknown };
+ if (response.error !== undefined) return { error: response.error } as Record<string, unknown>;
+ return JSON.parse(response.result!.content[0]!.text) as Record<string, unknown>;
+}
+
+function seedPair(): { target: string; successor: string } {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ const target = "Brain/preferences/pref-old.md";
+ writeFileSync(
+ join(vault, target),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-old",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-01T00:00:00Z",
+ "_confirmed_at: 2026-05-01T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ "topic: deploy-timeout",
+ "principle: Deploy timeout stays at thirty seconds.",
+ "pinned: false",
+ "---",
+ "",
+ "The rule body.",
+ "",
+ ].join("\n"),
+ );
+ const successor = "Brain/preferences/pref-new.md";
+ writeFileSync(
+ join(vault, successor),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-new",
+ "_status: confirmed",
+ "created_at: 2026-06-10T00:00:00Z",
+ "unconfirmed_until: 2026-06-10T00:00:00Z",
+ "_confirmed_at: 2026-06-10T00:00:00Z",
+ "_evidenced_by: []",
+ "tags: [brain, brain/preference]",
+ "topic: deploy-timeout",
+ "principle: Deploy timeout is two minutes.",
+ "pinned: false",
+ "---",
+ "",
+ "The corrected rule body.",
+ "",
+ ].join("\n"),
+ );
+ appendClaimEvent(vault, {
+ ts: "2026-05-02T00:00:00Z",
+ agent: "tester",
+ entity: "deploy timeout",
+ aspect: "limit",
+ value: "30s",
+ source: "[[Brain/preferences/pref-old.md]]",
+ });
+ return { target, successor };
+}
+
+describe("brain_lifecycle correct", () => {
+ test("dry_run defaults to true and writes nothing", async () => {
+ const { target } = seedPair();
+ const before = readFileSync(join(vault, target), "utf8");
+ const eventsBefore = readClaimEvents(vault).events.length;
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ });
+
+ expect(res["dry_run"]).toBe(true);
+ const blast = res["blast_radius"] as Record<string, unknown>;
+ expect(blast["target"]).toBe(target);
+ expect(Array.isArray(blast["claims"])).toBe(true);
+ expect((blast["claims"] as unknown[]).length).toBe(1);
+ expect(readFileSync(join(vault, target), "utf8")).toBe(before);
+ expect(readClaimEvents(vault).events.length).toBe(eventsBefore);
+ });
+
+ test("an applied validity-close retires with the supersede reason code", async () => {
+ const { target } = seedPair();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target,
+ value: "two minutes",
+ successor: "pref-new",
+ reason: "the timeout changed",
+ dry_run: false,
+ });
+
+ expect(res["dry_run"]).toBe(false);
+ const retirements = res["retirements"] as ReadonlyArray<Record<string, unknown>>;
+ expect(retirements.length).toBe(1);
+ expect(retirements[0]!["end_state"]).toBe("validity_close");
+ expect(retirements[0]!["reason_code"]).toBe("supersede");
+
+ const meta = parseFrontmatter(join(vault, target))[0] as Record<string, unknown>;
+ expect(meta["_status"]).toBe("confirmed");
+ // The wall clock owns the close instant; the pin is its canonical
+ // ISO-8601 UTC second shape, not which instant it names.
+ expect(meta["valid_until"]).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
+ expect(meta["superseded_by"]).toBe("[[pref-new]]");
+
+ const receipts = res["receipts"] as ReadonlyArray<Record<string, unknown>>;
+ expect(receipts.every((r) => r["appended"] === true)).toBe(true);
+ });
+
+ test("a flatly-wrong correction tombstones with the tombstone reason code", async () => {
+ const { target } = seedPair();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target,
+ value: "the number was never thirty seconds",
+ successor: "pref-new",
+ flatly_wrong: true,
+ reason: "fabricated figure",
+ dry_run: false,
+ });
+
+ const retirements = res["retirements"] as ReadonlyArray<Record<string, unknown>>;
+ expect(retirements[0]!["end_state"]).toBe("tombstone");
+ expect(retirements[0]!["reason_code"]).toBe("tombstone");
+ expect(retirements[0]!["valid_until"]).toBeNull();
+ const meta = parseFrontmatter(join(vault, target))[0] as Record<string, unknown>;
+ expect(meta["_status"]).toBe("tombstoned");
+ });
+
+ test("an optional window_end closes validity there", async () => {
+ const { target } = seedPair();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target,
+ successor: "pref-new",
+ window_end: "2026-07-01T00:00:00Z",
+ reason: "the timeout changed",
+ dry_run: false,
+ });
+ const retirements = res["retirements"] as ReadonlyArray<Record<string, unknown>>;
+ expect(retirements[0]!["valid_until"]).toBe("2026-07-01T00:00:00Z");
+ });
+
+ test("a malformed window_end is refused before anything is written", async () => {
+ const { target } = seedPair();
+ const before = readFileSync(join(vault, target), "utf8");
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target,
+ window_end: "soon after the incident",
+ dry_run: false,
+ });
+ expect(res["error"]).toBeDefined();
+ expect(readFileSync(join(vault, target), "utf8")).toBe(before);
+ });
+
+ test("a target below the caller's reach is refused as missing", async () => {
+ const base = mkTemp("o2b-lifecycle-correct-reach-");
+ const f: ReachLogFixture = buildReachLogFixture(base, true);
+ const withheld = join(f.vault, "Brain", "preferences", "pref-withheld.md");
+ writeFileSync(
+ withheld,
+ [
+ "---",
+ `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`,
+ "kind: brain-preference",
+ "id: pref-withheld",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-01T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: withheld-topic",
+ "principle: Withheld from remote callers.",
+ "pinned: false",
+ "---",
+ "",
+ "Withheld body.",
+ "",
+ ].join("\n"),
+ );
+ const bytesBefore = readFileSync(withheld, "utf8");
+ try {
+ const server = reachServer(f, "remote");
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target: "Brain/preferences/pref-withheld.md",
+ value: "two minutes",
+ reason: "the timeout changed",
+ dry_run: false,
+ });
+ expect(JSON.stringify(res)).toContain("does not exist");
+ expect(readFileSync(withheld, "utf8")).toBe(bytesBefore);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ test("a remote dry run does not name a withheld mentioning page in retarget", async () => {
+ const base = mkTemp("o2b-lifecycle-correct-retarget-dry-");
+ const f: ReachLogFixture = buildReachLogFixture(base, true);
+ try {
+ const target = "Brain/preferences/pref-public.md";
+ mkdirSync(join(f.vault, "Brain", "preferences"), { recursive: true });
+ writeFileSync(
+ join(f.vault, target),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-public",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-08T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: public-topic",
+ "principle: Readable at remote reach.",
+ "pinned: false",
+ "---",
+ "",
+ "Public body.",
+ "",
+ ].join("\n"),
+ );
+ const withheld = "Brain/inbox/sig-hidden.md";
+ mkdirSync(join(f.vault, "Brain", "inbox"), { recursive: true });
+ writeFileSync(
+ join(f.vault, withheld),
+ [
+ "---",
+ `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`,
+ "kind: brain-preference",
+ "id: sig-hidden",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-08T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: hidden-topic",
+ "principle: Mentions [[pref-public]] while withheld.",
+ "pinned: false",
+ "---",
+ "",
+ "Hidden body referencing [[pref-public]].",
+ "",
+ ].join("\n"),
+ );
+ const server = reachServer(f, "remote");
+ await initialize(server);
+ const res = await call(server, { action: "correct", target });
+ const retarget = res["retarget"] as Record<string, unknown>;
+ expect(retarget["matched"] as ReadonlyArray<string>).not.toContain(withheld);
+ expect(
+ (retarget["failed"] as ReadonlyArray<Record<string, unknown>>).map((f) => f["path"]),
+ ).not.toContain(withheld);
+ // No response key discloses the withheld page.
+ expect(JSON.stringify(res)).not.toContain("sig-hidden");
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ test("a remote applied run does not rewrite a withheld mentioning page", async () => {
+ const base = mkTemp("o2b-lifecycle-correct-retarget-apply-");
+ const f: ReachLogFixture = buildReachLogFixture(base, true);
+ try {
+ const target = "Brain/preferences/pref-public.md";
+ mkdirSync(join(f.vault, "Brain", "preferences"), { recursive: true });
+ writeFileSync(
+ join(f.vault, target),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-public",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-08T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: public-topic",
+ "principle: Readable at remote reach.",
+ "pinned: false",
+ "---",
+ "",
+ "Public body.",
+ "",
+ ].join("\n"),
+ );
+ const peer = "Brain/preferences/pref-peer.md";
+ writeFileSync(
+ join(f.vault, peer),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-peer",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-08T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: peer-topic",
+ "principle: Mentions [[pref-public]] in reach.",
+ "pinned: false",
+ "---",
+ "",
+ "See [[pref-public]] for the old rule.",
+ "",
+ ].join("\n"),
+ );
+ const withheld = "Brain/inbox/sig-hidden.md";
+ mkdirSync(join(f.vault, "Brain", "inbox"), { recursive: true });
+ writeFileSync(
+ join(f.vault, withheld),
+ [
+ "---",
+ `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`,
+ "kind: brain-preference",
+ "id: sig-hidden",
+ "_status: confirmed",
+ "created_at: 2026-05-01T00:00:00Z",
+ "unconfirmed_until: 2026-05-08T00:00:00Z",
+ "tags: [brain, brain/preference]",
+ "topic: hidden-topic",
+ "principle: Mentions [[pref-public]] while withheld.",
+ "pinned: false",
+ "---",
+ "",
+ "Hidden body referencing [[pref-public]].",
+ "",
+ ].join("\n"),
+ );
+ const bytesBefore = readFileSync(join(f.vault, withheld), "utf8");
+ const server = reachServer(f, "remote");
+ await initialize(server);
+ const res = await call(server, {
+ action: "correct",
+ target,
+ successor: "pref-public-2",
+ dry_run: false,
+ });
+ const retarget = res["retarget"] as Record<string, unknown>;
+ expect(retarget["rewritten"] as ReadonlyArray<string>).not.toContain(withheld);
+ expect(retarget["matched"] as ReadonlyArray<string>).not.toContain(withheld);
+ expect(
+ (retarget["failed"] as ReadonlyArray<Record<string, unknown>>).map((f) => f["path"]),
+ ).not.toContain(withheld);
+ // The withheld page's bytes are unchanged: no content injection.
+ expect(readFileSync(join(f.vault, withheld), "utf8")).toBe(bytesBefore);
+ // In-reach mentions are still retargeted.
+ expect(retarget["rewritten"] as ReadonlyArray<string>).toContain(peer);
+ expect(readFileSync(join(f.vault, peer), "utf8")).toContain("[[pref-public-2]]");
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("o2b brain lifecycle correct", () => {
+ test("dry run is the default and reports the blast radius without writing", async () => {
+ const { target } = seedPair();
+ const before = readFileSync(join(vault, target), "utf8");
+ const eventsBefore = readClaimEvents(vault).events.length;
+
+ const out: string[] = [];
+ const originalWrite = process.stdout.write.bind(process.stdout);
+ process.stdout.write = (chunk: string | Uint8Array): boolean => {
+ out.push(String(chunk));
+ return true;
+ };
+ let exit: number;
+ try {
+ exit = await cmdBrainLifecycle([
+ "correct",
+ target,
+ "--value",
+ "two minutes",
+ "--successor",
+ "pref-new",
+ "--reason",
+ "the timeout changed",
+ "--config",
+ configPath,
+ "--json",
+ ]);
+ } finally {
+ process.stdout.write = originalWrite;
+ }
+ expect(exit).toBe(0);
+ const payload = JSON.parse(out.join("")) as Record<string, unknown>;
+ expect(payload["dry_run"]).toBe(true);
+ expect(readFileSync(join(vault, target), "utf8")).toBe(before);
+ expect(readClaimEvents(vault).events.length).toBe(eventsBefore);
+ });
+
+ test("an applied run retires the target and reports the bundle", async () => {
+ const { target } = seedPair();
+ const out: string[] = [];
+ const originalWrite = process.stdout.write.bind(process.stdout);
+ process.stdout.write = (chunk: string | Uint8Array): boolean => {
+ out.push(String(chunk));
+ return true;
+ };
+ let exit: number;
+ try {
+ exit = await cmdBrainLifecycle([
+ "correct",
+ target,
+ "--value",
+ "two minutes",
+ "--successor",
+ "pref-new",
+ "--reason",
+ "the timeout changed",
+ "--apply",
+ "--config",
+ configPath,
+ "--json",
+ ]);
+ } finally {
+ process.stdout.write = originalWrite;
+ }
+ expect(exit).toBe(0);
+ const payload = JSON.parse(out.join("")) as Record<string, unknown>;
+ expect(payload["dry_run"]).toBe(false);
+ const bundleId = payload["bundle_id"] as string;
+ expect(typeof bundleId).toBe("string");
+ const retirements = payload["retirements"] as ReadonlyArray<Record<string, unknown>>;
+ expect(retirements[0]!["reason_code"]).toBe("supersede");
+ const meta = parseFrontmatter(join(vault, target))[0] as Record<string, unknown>;
+ // The wall clock owns the close instant; the pin is its canonical
+ // ISO-8601 UTC second shape, not which instant it names.
+ expect(meta["valid_until"]).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
+ expect(existsSync(join(vault, target))).toBe(true);
+ });
+
+ test("the correct verb requires a target", async () => {
+ const exit = await cmdBrainLifecycle(["correct", "--config", configPath]);
+ expect(exit).toBe(2);
+ });
+});
diff --git a/tests/mcp/brain-retention.test.ts b/tests/mcp/brain-retention.test.ts
index baac1c33..1a2b493c 100644
--- a/tests/mcp/brain-retention.test.ts
+++ b/tests/mcp/brain-retention.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, renameSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -14,8 +14,12 @@ let ctx: { vault: string; configPath: string };
beforeEach(() => {
vault = mkdtempSync(join(tmpdir(), "o2b-retention-mcp-"));
mkdirSync(vault, { recursive: true });
- bootstrapBrain(vault, {});
+ // The vault registers itself: a config written into the vault and passed
+ // explicitly keeps this file off the machine-level config lookup, whose
+ // answer depends on which other test files share this shard's process.
ctx = { vault, configPath: join(vault, "config.yaml") };
+ writeFileSync(ctx.configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath: ctx.configPath });
writeSignal(vault, {
topic: "discarded-signal",
signal: "negative",
diff --git a/tests/mcp/brain-truth.test.ts b/tests/mcp/brain-truth.test.ts
index 5641fe98..4421bea3 100644
--- a/tests/mcp/brain-truth.test.ts
+++ b/tests/mcp/brain-truth.test.ts
@@ -5,13 +5,17 @@
*/
import { afterEach, beforeEach, expect, test } from "bun:test";
-import { mkdtempSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
-import { appendClaimEvent } from "../../src/core/brain/truth/store.ts";
+import { readClaimEvents, appendClaimEvent } from "../../src/core/brain/truth/store.ts";
+import { computeTruthStateWithConflicts } from "../../src/core/brain/truth/conflicts.ts";
+import { upsertEntity } from "../../src/core/brain/entities/registry.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
let tmp: string;
@@ -79,6 +83,30 @@ async function call(
return JSON.parse(res.result!.content![0]!.text!) as Record<string, unknown>;
}
+/**
+ * The whole JSON-RPC response, for assertions on the failure CLASS: a
+ * handler-mapped refusal answers as a JSON-RPC error carrying the
+ * invalid-params code, while an unmapped internal error would arrive as
+ * an isError tool result (or an internal_error envelope).
+ */
+async function callRaw(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<{
+ error?: { code: number; message: string; data?: { code?: string } };
+ result?: { isError?: boolean };
+}> {
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 99,
+ method: "tools/call",
+ params: { name: "brain_truth", arguments: args },
+ })) as {
+ error?: { code: number; message: string; data?: { code?: string } };
+ result?: { isError?: boolean };
+ };
+}
+
test("ingest then slots round-trips one claim through the fold", async () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
@@ -143,3 +171,646 @@ test("unknown operation is an invalid-params error", async () => {
await initialize(server);
await expect(call(server, { operation: "bogus" })).rejects.toThrow(/operation/);
});
+
+// ----- operation: "events" (truth-correctable-time-aware, Task 8) -----------
+
+interface ClaimEventRow {
+ readonly ts: string;
+ readonly entity: string;
+ readonly aspect: string;
+ readonly value: string;
+ readonly source: string;
+ readonly validFrom?: string;
+ readonly validUntil?: string;
+}
+
+interface EventsResponse {
+ readonly ok: boolean;
+ readonly operation: string;
+ readonly entity: string | null;
+ readonly events: ReadonlyArray<ClaimEventRow>;
+ readonly total: number;
+ readonly truncated: boolean;
+}
+
+/**
+ * Write a readable source page. The events operation's per-row gate
+ * fails closed on a page whose file cannot be read, so an event naming
+ * a page that was never written is withheld below local reach - the
+ * tests that expect rows served must back them with real pages.
+ */
+function writeSourcePage(name: string, visibilityLine = ""): void {
+ const dir = join(vault, "Brain", "notes");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, name), `---\nkind: note${visibilityLine}\n---\n\n${name} source page\n`);
+}
+
+function seedWindowedLedger(): void {
+ for (const name of ["a.md", "b.md", "c.md"]) writeSourcePage(name);
+ appendClaimEvent(vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ validFrom: "2026-06-01",
+ validUntil: "2026-09-01",
+ source: "[[Brain/notes/a.md]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-05T09:30:00Z",
+ agent: "claude",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Meta",
+ source: "[[Brain/notes/b.md]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-10T12:00:00Z",
+ agent: "claude",
+ entity: "Project Atlas",
+ aspect: "status",
+ value: "on track",
+ source: "[[Brain/notes/c.md]]",
+ });
+}
+
+test("events returns rows in stable ascending assertion-ts order with validity fields verbatim", async () => {
+ seedWindowedLedger();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const body = (await call(server, { operation: "events" })) as unknown as EventsResponse;
+ expect(body.ok).toBe(true);
+ expect(body.operation).toBe("events");
+ expect(body.entity).toBe(null);
+ expect(body.total).toBe(3);
+ expect(body.truncated).toBe(false);
+ expect(body.events.map((e) => e.ts)).toEqual([
+ "2026-06-01T10:00:00Z",
+ "2026-06-05T09:30:00Z",
+ "2026-06-10T12:00:00Z",
+ ]);
+ expect(body.events[0]!.entity).toBe("alice mason");
+ expect(body.events[0]!.validFrom).toBe("2026-06-01");
+ expect(body.events[0]!.validUntil).toBe("2026-09-01");
+ expect(body.events[1]!.validFrom).toBeUndefined();
+ // The slots response stays byte-identical: `events` there is the count.
+ const slots = await call(server, { operation: "slots" });
+ expect(slots["events"]).toBe(3);
+});
+
+test("events filters by normalized entity composing with the assertion-time window", async () => {
+ seedWindowedLedger();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const body = (await call(server, {
+ operation: "events",
+ entity: "Alice Mason",
+ since: "2026-06-02",
+ until: "2026-06-05",
+ })) as unknown as EventsResponse;
+ // The display-form spelling resolves to the canonical entity, and the
+ // day-edge bounds are inclusive: since keeps 06-05, until cuts 06-10.
+ expect(body.entity).toBe("alice mason");
+ expect(body.events.map((e) => e.ts)).toEqual(["2026-06-05T09:30:00Z"]);
+ expect(body.total).toBe(1);
+});
+
+test("events pages with limit and reports truncation", async () => {
+ seedWindowedLedger();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const body = (await call(server, { operation: "events", limit: 2 })) as unknown as EventsResponse;
+ expect(body.events).toHaveLength(2);
+ expect(body.total).toBe(3);
+ expect(body.truncated).toBe(true);
+ // Tail-following pagination: an advancing `since` never skips a
+ // boundary event - it floors into its second, so the boundary row is
+ // re-seen (the caller dedups by ts) rather than skipped.
+ const tail = (await call(server, {
+ operation: "events",
+ limit: 2,
+ since: body.events[1]!.ts,
+ })) as unknown as EventsResponse;
+ expect(tail.events.map((e) => e.ts)).toEqual(["2026-06-05T09:30:00Z", "2026-06-10T12:00:00Z"]);
+ expect(tail.truncated).toBe(false);
+ const past = (await call(server, {
+ operation: "events",
+ since: "2026-06-06",
+ })) as unknown as EventsResponse;
+ expect(past.events.map((e) => e.ts)).toEqual(["2026-06-10T12:00:00Z"]);
+});
+
+test("events answers a caller denied a source page exactly as if the row were absent", async () => {
+ writeSourcePage("public.md");
+ writeSourcePage("private.md", `\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`);
+ appendClaimEvent(vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/public.md]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-02T10:00:00Z",
+ agent: "claude",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Meta",
+ source: "[[Brain/notes/private.md]]",
+ });
+ // The extensionless wikilink spelling names the SAME page: the
+ // conventional Obsidian shape the ingest window resolver accepts. A
+ // gate that resolves only the .md form fails open for this row.
+ appendClaimEvent(vault, {
+ ts: "2026-06-03T10:00:00Z",
+ agent: "claude",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Amazon",
+ source: "[[Brain/notes/private]]",
+ });
+ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });
+ await initialize(remote);
+ const seen = (await call(remote, { operation: "events" })) as unknown as EventsResponse;
+ // A withheld row is dropped and NOTHING counts it (the views'
+ // identical-to-absent convention): the account covers only rows the
+ // caller may read, under either spelling of the same withheld page.
+ expect(seen.total).toBe(1);
+ expect("withheld" in seen).toBe(false);
+ expect(seen.events.map((e) => e.value)).toEqual(["Google"]);
+ expect(JSON.stringify(seen)).not.toContain("private");
+ const local = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
+ await initialize(local);
+ const localBody = (await call(local, { operation: "events" })) as unknown as EventsResponse;
+ expect(localBody.events).toHaveLength(3);
+ expect(localBody.total).toBe(3);
+ expect("withheld" in localBody).toBe(false);
+ // The identical-answer property, vault against vault: the same remote
+ // query over a vault holding only the readable row answers byte for
+ // byte what the vault with two extra withheld rows answered, so no
+ // pivot (entity, window, limit) can measure the hidden population.
+ const b = secondVault();
+ try {
+ mkdirSync(join(b.vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(b.vault, "Brain", "notes", "public.md"),
+ `---\nkind: note\n---\n\npublic.md source page\n`,
+ );
+ appendClaimEvent(b.vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "claude",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/public.md]]",
+ });
+ const remoteB = new MCPServer(
+ { vault: b.vault, configPath: b.configPath },
+ { reach: TRANSPORT_REACH.remote },
+ );
+ await initialize(remoteB);
+ const withoutHidden = (await call(remoteB, { operation: "events" })) as unknown as Record<
+ string,
+ unknown
+ >;
+ expect(JSON.stringify(withoutHidden)).toBe(JSON.stringify({ ...seen }));
+ } finally {
+ rmSync(b.configHome, { recursive: true, force: true });
+ }
+});
+
+test("events refuses unparseable bounds and invalid limits as invalid params", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ // The shared grammar's refusal surfaces verbatim (the same convention
+ // the time-bounds wrapper pins); the message names the offending input.
+ await expect(call(server, { operation: "events", since: "not a date" })).rejects.toThrow(
+ /not a date/,
+ );
+ await expect(
+ call(server, { operation: "events", since: "2026-06-05", until: "2026-06-01" }),
+ ).rejects.toThrow();
+ await expect(call(server, { operation: "events", limit: 0 })).rejects.toThrow(/limit/);
+ await expect(call(server, { operation: "events", limit: 1.5 })).rejects.toThrow(/limit/);
+ await expect(call(server, { operation: "events", limit: "many" })).rejects.toThrow(/limit/);
+});
+
+// ----- operation: "state" (grounded agent-stated claims, Task 8) ------------
+
+interface StateResponse {
+ readonly ok: boolean;
+ readonly operation: string;
+ readonly committed: ReadonlyArray<ClaimEventRow & { readonly extractor?: string }>;
+ readonly ungrounded: ReadonlyArray<{
+ readonly subject: string;
+ readonly relation: string;
+ readonly object: string;
+ readonly reasons: ReadonlyArray<string>;
+ }>;
+}
+
+function seedRegistry(): void {
+ upsertEntity(vault, {
+ category: "people",
+ name: "Alice Mason",
+ aliases: ["Alice"],
+ agent: "claude",
+ now: new Date("2026-06-01T00:00:00Z"),
+ });
+ upsertEntity(vault, {
+ category: "projects",
+ name: "Project Atlas",
+ aliases: ["Atlas"],
+ agent: "claude",
+ now: new Date("2026-06-01T00:00:00Z"),
+ });
+}
+
+test("state commits a grounded agent-stated claim as an agent_stated ledger event", async () => {
+ seedRegistry();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const body = (await call(server, {
+ operation: "state",
+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],
+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",
+ source: "[[Brain/notes/session.md]]",
+ })) as unknown as StateResponse;
+ expect(body.ok).toBe(true);
+ expect(body.operation).toBe("state");
+ expect(body.committed).toHaveLength(1);
+ const row = body.committed[0]!;
+ expect(row.entity).toBe("alice mason");
+ expect(row.aspect).toBe("extends");
+ expect(row.value).toBe("Project Atlas");
+ expect(row.extractor).toBe("agent_stated");
+ expect(row.source).toBe("[[Brain/notes/session.md]]");
+ expect(body.ungrounded).toHaveLength(0);
+ const [stored] = readClaimEvents(vault).events;
+ expect(stored!.extractor).toBe("agent_stated");
+});
+
+test("state anchors subjects and objects through registry aliases", async () => {
+ seedRegistry();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ // The claim names the full label, the text only the alias: anchoring
+ // goes through the registry's quality-gated match forms, not string
+ // equality between the claim and the text.
+ const body = (await call(server, {
+ operation: "state",
+ claims: [{ subject: "Alice Mason", relation: "related", object: "Project Atlas" }],
+ text: "Alice opened the Atlas kickoff deck this morning.",
+ source: "[[Brain/notes/session.md]]",
+ })) as unknown as StateResponse;
+ expect(body.committed).toHaveLength(1);
+ expect(body.committed[0]!.entity).toBe("alice mason");
+});
+
+test("state reports ungrounded claims back per claim with reasons and commits the rest", async () => {
+ seedRegistry();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const body = (await call(server, {
+ operation: "state",
+ claims: [
+ { subject: "Alice Mason", relation: "related", object: "Project Atlas" },
+ { subject: "Alice Mason", relation: "related", object: "Project Osiris" },
+ ],
+ // The stated label itself is one anchoring form (lane 1's verdict
+ // contract), so the ungrounded claim's object must not occur in the
+ // text at all - "Osiris" alone is a different, shorter form.
+ text: "Alice walked through the Project Atlas plan all morning.",
+ source: "[[Brain/notes/session.md]]",
+ })) as unknown as StateResponse;
+ // Each event is an independent append in an append-only ledger, so the
+ // grounded claim commits and only the ungrounded one is reported back.
+ expect(body.committed).toHaveLength(1);
+ expect(body.committed[0]!.value).toBe("Project Atlas");
+ expect(body.ungrounded).toHaveLength(1);
+ expect(body.ungrounded[0]!.object).toBe("Project Osiris");
+ expect(body.ungrounded[0]!.reasons).toContain("object_unanchored");
+ expect(readClaimEvents(vault).events).toHaveLength(1);
+});
+
+test("state refuses unknown relations before any write", async () => {
+ seedRegistry();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ await expect(
+ call(server, {
+ operation: "state",
+ claims: [
+ { subject: "Alice Mason", relation: "related", object: "Project Atlas" },
+ { subject: "Alice Mason", relation: "invented_by", object: "Project Atlas" },
+ ],
+ text: "Alice Mason reviewed Project Atlas today.",
+ source: "[[Brain/notes/session.md]]",
+ }),
+ ).rejects.toThrow(/invented_by/);
+ // Refuse-before-write: nothing landed, not even the valid claim.
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("state refuses a missing or empty text or source before any write", async () => {
+ seedRegistry();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const claim = [{ subject: "Alice Mason", relation: "related", object: "Project Atlas" }];
+ await expect(
+ call(server, {
+ operation: "state",
+ claims: claim,
+ text: "Alice Mason reviewed Project Atlas today.",
+ }),
+ ).rejects.toThrow(/source/);
+ await expect(
+ call(server, { operation: "state", claims: claim, source: "[[Brain/notes/a.md]]" }),
+ ).rejects.toThrow(/text/);
+ await expect(
+ call(server, { operation: "state", text: "x", source: "[[Brain/notes/a.md]]" }),
+ ).rejects.toThrow(/claims/);
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+test("state normalizes the relation token and resolves its agent override", async () => {
+ seedRegistry();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const body = (await call(server, {
+ operation: "state",
+ claims: [{ subject: "Alice Mason", relation: "Related", object: "Project Atlas" }],
+ text: "Alice Mason and Project Atlas met.",
+ source: "[[Brain/notes/session.md]]",
+ agent: "scribe-agent",
+ })) as unknown as StateResponse;
+ expect(body.committed[0]!.aspect).toBe("related");
+ expect(readClaimEvents(vault).events[0]!.agent).toBe("scribe-agent");
+});
+
+test("state refuses a malformed source window as invalid params, not an internal error", async () => {
+ // The stated claim carries no explicit window, so the store resolves
+ // one from the source record's frontmatter; an inverted window there
+ // raises the store's typed refusal, which the state operation must map
+ // exactly as ingest maps it - typed INVALID_PARAMS, never an
+ // internal error escaping the handler.
+ seedRegistry();
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "session.md"),
+ "---\nkind: note\nvalid_from: 2026-06-01\nvalid_until: 2026-01-01\n---\n\nsession page\n",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const raw = await callRaw(server, {
+ operation: "state",
+ claims: [{ subject: "Alice Mason", relation: "related", object: "Project Atlas" }],
+ text: "Alice Mason reviewed Project Atlas today.",
+ source: "[[Brain/notes/session.md]]",
+ });
+ expect(raw.error).toBeDefined();
+ expect(raw.error!.code).toBe(-32602);
+ expect(raw.error!.data?.code).toBe("invalid_params");
+ expect(raw.error!.message).toMatch(/validity window/);
+ expect(raw.result?.isError).toBeUndefined();
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
+
+// ----- sub-suite A integration checkpoint (Task 10) -------------------------
+
+test("ingest declares optional validity fields that win over source resolution", async () => {
+ writeSourcePage("windowed.md", '\nvalid_from: "2026-01-01"\nvalid_until: "2026-12-31"');
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const explicit = (await call(server, {
+ operation: "ingest",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/windowed.md]]",
+ valid_from: "2026-06-01",
+ valid_until: "2026-09-01",
+ })) as unknown as Record<string, unknown>;
+ // Explicit input wins outright over the source's own window.
+ expect(explicit["valid_from"]).toBe("2026-06-01");
+ expect(explicit["valid_until"]).toBe("2026-09-01");
+ const [stored] = readClaimEvents(vault).events;
+ expect(stored!.validFrom).toBe("2026-06-01");
+ expect(stored!.validUntil).toBe("2026-09-01");
+});
+
+test("a windowed events call returns events ingested with resolved frozen windows", async () => {
+ // No explicit window: ingest resolves the window from the readable
+ // source record's frontmatter and freezes it on the event.
+ writeSourcePage("from-frontmatter.md", '\nvalid_from: "2026-05-01"\nvalid_until: "2026-08-01"');
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const ingested = await call(server, {
+ operation: "ingest",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/from-frontmatter.md]]",
+ });
+ expect(ingested["ok"]).toBe(true);
+ const body = (await call(server, {
+ operation: "events",
+ entity: "alice mason",
+ })) as unknown as EventsResponse;
+ expect(body.events).toHaveLength(1);
+ expect(body.events[0]!.validFrom).toBe("2026-05-01");
+ expect(body.events[0]!.validUntil).toBe("2026-08-01");
+ // The succession channel and the events surface agree on the axis
+ // rule: two same-slot claims with present, non-intersecting windows
+ // classify as succession in the fold (never a conflict, never
+ // ask_user - the pinned conflicts response carries neither), and the
+ // same events return from the events operation carrying their frozen
+ // windows verbatim (contract item 1, one axis rule, two readers).
+ appendClaimEvent(vault, {
+ ts: "2026-09-02T10:00:00Z",
+ agent: "claude",
+ entity: "alice mason",
+ aspect: "employer",
+ value: "Meta",
+ validFrom: "2026-09-01",
+ // Explicit: the shared source's frontmatter window (until
+ // 2026-08-01) would invert against this from-bound if left open.
+ validUntil: "2026-12-31",
+ source: "[[Brain/notes/from-frontmatter.md]]",
+ });
+ const fold = computeTruthStateWithConflicts(readClaimEvents(vault).events);
+ expect(fold.conflicts).toHaveLength(0);
+ expect(fold.successions).toHaveLength(1);
+ expect(fold.successions![0]!.predecessor.value).toBe("Google");
+ const pinned = (await call(server, { operation: "conflicts" })) as unknown as {
+ conflicts: unknown[];
+ };
+ expect(pinned.conflicts).toHaveLength(0);
+ const both = (await call(server, { operation: "events" })) as unknown as EventsResponse;
+ // Ascending assertion ts: the fold-predecessor (Google, window closed
+ // 2026-08-01) was asserted today by the ingest above; the succession
+ // successor (Meta) was back-dated into September.
+ expect(both.total).toBe(2);
+ expect(both.events.map((e) => e.value)).toEqual(["Meta", "Google"]);
+ expect(both.events[0]!.validFrom).toBe("2026-09-01");
+ expect(both.events[0]!.validUntil).toBe("2026-12-31");
+ expect(both.events[1]!.validFrom).toBe("2026-05-01");
+ expect(both.events[1]!.validUntil).toBe("2026-08-01");
+});
+
+// ----- withheld-source boundary (reach-gated window resolution) -------------
+
+interface IngestResponse {
+ readonly ok: boolean;
+ readonly entity: string;
+ readonly aspect: string;
+ readonly path: string;
+ readonly valid_from?: string;
+ readonly valid_until?: string;
+}
+
+/**
+ * A second single-vault fixture beside the beforeEach one, so a response
+ * over a vault where the source page exists (withheld) can be compared
+ * with the same call over a vault where it does not.
+ */
+function secondVault(): { vault: string; configPath: string; configHome: string } {
+ const vaultB = join(tmp, "vault-b");
+ const configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-truth-cfg-b-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vaultB}\nagent_name: claude\n`);
+ bootstrapBrain(vaultB, { configPath });
+ return { vault: vaultB, configPath, configHome };
+}
+
+test("ingest treats a source beyond the caller's reach exactly like an absent one", async () => {
+ // Vault A: the source page exists, is withheld below remote reach, and
+ // carries the validity frontmatter a remote caller must not read back.
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "hidden.md"),
+ `---\nkind: note\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n` +
+ `valid_from: "2026-01-01"\nvalid_until: "2027-01-01"\n---\n\nhidden source page\n`,
+ );
+ const b = secondVault();
+ try {
+ const args = {
+ operation: "ingest",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/hidden.md]]",
+ };
+ const remoteA = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });
+ const remoteB = new MCPServer(
+ { vault: b.vault, configPath: b.configPath },
+ { reach: TRANSPORT_REACH.remote },
+ );
+ await initialize(remoteA);
+ await initialize(remoteB);
+ const withHidden = (await call(remoteA, args)) as unknown as IngestResponse;
+ const withoutPage = (await call(remoteB, args)) as unknown as IngestResponse;
+ // Byte-identical once the vault-specific shard path is set aside: no
+ // validity keys, no signal distinguishing withheld from absent.
+ expect("valid_from" in withHidden).toBe(false);
+ expect("valid_until" in withHidden).toBe(false);
+ expect("valid_from" in withoutPage).toBe(false);
+ expect(JSON.stringify({ ...withHidden, path: null })).toBe(
+ JSON.stringify({ ...withoutPage, path: null }),
+ );
+ // And the frozen event is windowless in both ledgers.
+ expect(readClaimEvents(vault).events[0]!.validFrom).toBeUndefined();
+ expect(readClaimEvents(vault).events[0]!.validUntil).toBeUndefined();
+ expect(readClaimEvents(b.vault).events[0]!.validFrom).toBeUndefined();
+ // The gate withholds exactly the unreadable: a readable source's
+ // window still resolves for the same remote caller.
+ writeSourcePage("shown.md", '\nvalid_from: "2026-05-01"\nvalid_until: "2026-08-01"');
+ const shown = (await call(remoteA, {
+ operation: "ingest",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Meta",
+ source: "[[Brain/notes/shown.md]]",
+ })) as unknown as IngestResponse;
+ expect(shown["valid_from"]).toBe("2026-05-01");
+ expect(shown["valid_until"]).toBe("2026-08-01");
+ } finally {
+ rmSync(b.configHome, { recursive: true, force: true });
+ }
+});
+
+test("state treats a source beyond the caller's reach exactly like an absent one", async () => {
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "hidden.md"),
+ `---\nkind: note\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n` +
+ `valid_from: "2026-01-01"\nvalid_until: "2027-01-01"\n---\n\nhidden source page\n`,
+ );
+ const b = secondVault();
+ try {
+ const args = {
+ operation: "state",
+ claims: [{ subject: "Alice Mason", relation: "related", object: "Project Atlas" }],
+ text: "Alice Mason and Project Atlas met this morning.",
+ source: "[[Brain/notes/hidden.md]]",
+ };
+ const remoteA = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });
+ const remoteB = new MCPServer(
+ { vault: b.vault, configPath: b.configPath },
+ { reach: TRANSPORT_REACH.remote },
+ );
+ await initialize(remoteA);
+ await initialize(remoteB);
+ const withHidden = (await call(remoteA, args)) as unknown as StateResponse;
+ const withoutPage = (await call(remoteB, args)) as unknown as StateResponse;
+ // The assertion ts is per call, so it is set aside with the rest of
+ // what names the call rather than the answer; every source-derived
+ // byte must agree.
+ const stripTs = (body: StateResponse): string =>
+ JSON.stringify({
+ ...body,
+ committed: body.committed.map(({ ts: _ts, ...rest }) => rest),
+ });
+ expect(withHidden.committed).toHaveLength(1);
+ expect(withoutPage.committed).toHaveLength(1);
+ expect(stripTs(withHidden)).toBe(stripTs(withoutPage));
+ expect(withHidden.committed[0]!.validFrom).toBeUndefined();
+ expect(withHidden.committed[0]!.validUntil).toBeUndefined();
+ expect(readClaimEvents(vault).events[0]!.validFrom).toBeUndefined();
+ expect(readClaimEvents(b.vault).events[0]!.validFrom).toBeUndefined();
+ } finally {
+ rmSync(b.configHome, { recursive: true, force: true });
+ }
+});
+
+// ----- boundary discipline (malformed window is a param error) --------------
+
+test("ingest refuses a malformed validity bound as invalid params, not an internal error", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ for (const bad of [
+ { valid_from: "garbage" },
+ { valid_until: "also garbage" },
+ { valid_from: "2026-09-01", valid_until: "2026-06-01" },
+ ]) {
+ const raw = await callRaw(server, {
+ operation: "ingest",
+ entity: "Alice Mason",
+ aspect: "employer",
+ value: "Google",
+ source: "[[Brain/notes/standup.md]]",
+ ...bad,
+ });
+ // The sibling mistyped inputs (limit, since/until) answer as typed
+ // INVALID_PARAMS; a mistyped validity bound is the same failure
+ // class, never an internal error.
+ expect(raw.error).toBeDefined();
+ expect(raw.error!.code).toBe(-32602);
+ expect(raw.error!.data?.code).toBe("invalid_params");
+ expect(raw.error!.message).toMatch(/valid[FU]/);
+ expect(raw.result?.isError).toBeUndefined();
+ }
+ expect(readClaimEvents(vault).events).toHaveLength(0);
+});
diff --git a/tests/mcp/search-relations.test.ts b/tests/mcp/search-relations.test.ts
index bbbb028c..8ee970a8 100644
--- a/tests/mcp/search-relations.test.ts
+++ b/tests/mcp/search-relations.test.ts
@@ -63,6 +63,11 @@ beforeEach(async () => {
"The quick brown fox jumps over the lazy dog.",
].join("\n"),
);
+ // The declared successor must exist and be readable: the
+ // serve-with-correction coupling drops a retired-but-serveable page
+ // whose chain tip is unresolved, and this file's subject is inline
+ // relation surfacing, not retired-row serving.
+ writeFileSync(join(vault, "notes", "gamma.md"), "The settled successor record for alpha.\n");
ctx = { vault, configPath };
const config = resolveSearchConfig({ vault, configPath });
await indexVault(config, {});
diff --git a/tests/mcp/surface-error-codes.test.ts b/tests/mcp/surface-error-codes.test.ts
index ff82c36c..c1aa2206 100644
--- a/tests/mcp/surface-error-codes.test.ts
+++ b/tests/mcp/surface-error-codes.test.ts
@@ -461,7 +461,7 @@ describe("every operation-dispatching tool answers unknown_operation", () => {
[
"brain_truth",
{ operation: BOGUS },
- "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",
+ "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions|events|state",
],
["brain_dead_ends", { operation: BOGUS }, "brain_dead_ends: operation must be record|list"],
[
@@ -500,7 +500,7 @@ describe("every operation-dispatching tool answers unknown_operation", () => {
[
"brain_lifecycle",
{ action: BOGUS },
- "brain_lifecycle: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator",
+ "brain_lifecycle: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator, correct",
],
["brain_writes", { action: BOGUS }, "brain_writes: 'action' must be one of list, plan_revert"],
[
diff --git a/tests/mcp/time-bounds.test.ts b/tests/mcp/time-bounds.test.ts
new file mode 100644
index 00000000..bfe4f5ea
--- /dev/null
+++ b/tests/mcp/time-bounds.test.ts
@@ -0,0 +1,69 @@
+/**
+ * `resolveTimeBounds` (shared time-bounds wrapper): the lifted
+ * `since`/`until` resolution every recall surface consumes - resolved
+ * through the shared time-range grammar, with a `SearchError` mapped to
+ * `MCPError(INVALID_PARAMS)` so an unparseable bound surfaces as an
+ * invalid-params tool error instead of a silently ignored filter.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { resolveTimeBounds } from "../../src/mcp/brain/time-bounds.ts";
+import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
+
+describe("resolveTimeBounds", () => {
+ test("absent bounds stay open", () => {
+ expect(resolveTimeBounds(undefined, undefined)).toEqual({
+ sinceMs: null,
+ untilMs: null,
+ });
+ });
+
+ test("an ISO date since resolves to its UTC day start", () => {
+ expect(resolveTimeBounds("2026-05-01", undefined)).toEqual({
+ sinceMs: Date.UTC(2026, 4, 1),
+ untilMs: null,
+ });
+ });
+
+ test("the upper bound maps onto the grammar's inclusive until edge", () => {
+ expect(resolveTimeBounds(undefined, "2026-05-01")).toEqual({
+ sinceMs: null,
+ untilMs: Date.UTC(2026, 4, 1) + 86_400_000 - 1,
+ });
+ });
+
+ test("ISO datetimes pass through in UTC", () => {
+ expect(resolveTimeBounds("2026-05-01T10:30:00Z", "2026-05-02T10:30:00Z")).toEqual({
+ sinceMs: Date.UTC(2026, 4, 1, 10, 30, 0),
+ untilMs: Date.UTC(2026, 4, 2, 10, 30, 0),
+ });
+ });
+
+ test("relative bounds resolve backwards from the current clock", () => {
+ const bounds = resolveTimeBounds("2d", "1h");
+ expect(bounds.sinceMs).toBeLessThan(Date.now());
+ expect(bounds.untilMs).toBeLessThan(Date.now());
+ expect(bounds.sinceMs).toBeLessThan(bounds.untilMs!);
+ });
+
+ test("an unparseable bound is an INVALID_PARAMS error, not a dropped filter", () => {
+ try {
+ resolveTimeBounds("not a time", undefined);
+ throw new Error("expected resolveTimeBounds to throw");
+ } catch (err) {
+ expect(err).toBeInstanceOf(MCPError);
+ expect((err as MCPError).code).toBe(INVALID_PARAMS);
+ }
+ });
+
+ test("an inverted range is an INVALID_PARAMS error", () => {
+ try {
+ resolveTimeBounds("2026-05-02", "2026-05-01");
+ throw new Error("expected resolveTimeBounds to throw");
+ } catch (err) {
+ expect(err).toBeInstanceOf(MCPError);
+ expect((err as MCPError).code).toBe(INVALID_PARAMS);
+ }
+ });
+});
diff --git a/uv.lock b/uv.lock
index f6ef08d7..3c365a12 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.76.0"
+version = "1.77.0"
source = { editable = "." }