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: belief lifecycle and decision memory (v1.33.0) (#141)

Sol Aitken77513f2bbb9b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index c7984059..748a583e 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.32.0",
+ "version": "1.33.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 1fb6cc98..fe337624 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.32.0",
+ "version": "1.33.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 881c13eb..e5995fe8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,30 @@ 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.33.0] - 2026-07-18
+
+A belief lifecycle and decision memory wave: eleven units that give memories a full lifecycle (tombstone, supersede, temporal replacement, tension triage) and make decisions first-class, auditable citizens of the brain (records, ratings, commitment tiers, change receipts, governed recall). Everything is deterministic (the kernel still calls no LLM), every mutation is logged or receipted, and vaults that do not opt in behave byte-identically.
+
+### Added
+
+- Cross-type tombstone and supersede lifecycle (`o2b brain lifecycle`, MCP `brain_lifecycle`): idempotent soft delete via frontmatter (`_status: tombstoned`, reason, timestamp, optional `superseded_by`) across preferences, signals, and learnings; tombstoned and superseded-non-tip entries leave recall, inject, and `Brain/active.md` but stay on disk for audit; curator slices list injected-never-used, contradicted, and high-used memories from observed-use verdicts.
+- Atomic temporal fact-replacement (`o2b brain lifecycle temporal-replace`): closes the predecessor and opens the successor at one shared instant with half-open `[valid_from, valid_to)` intervals, whole-day semantics for date-only facts, and both-or-neither write atomicity; the successor link reuses `superseded_by`.
+- Persisted claim-graph query surface (`o2b brain claims`, MCP `brain_claims`): one bounded, deterministically rebuildable projection (`Brain/claim-graph.json`) over existing `superseded_by`/`contradicts` relations and bi-temporal validity, answering current truth, truth-at-instant, what-replaced, and what-contests; current-truth by default, history opt-in.
+- Supersedes-chain consumer policy: context packs inject only chain tips under budget (an explicit historical flag keeps the chain), recall annotates superseded hits with a pointer to their replacement, and the dream pass accelerates decay of low-recall superseded ancestors (`chain-decay` events, named threshold constants).
+- Decision-record note family (`o2b brain decision`, MCP `brain_decision`): `type: decision` notes under `Brain/decisions/` with chosen, assumption, `review_date` (opens exactly one review obligation, idempotently), outcome backfill, optional pre-mortem, and similar-decision recall with recorded outcomes.
+- Rated decision capture: `rating` (1-5) plus `rationale` round-trip through decision frontmatter, `list --rated` sorts by rating, `compare` reads decisions side by side; rated decisions stay out of signal and preference recall.
+- Commitment tier vocabulary: optional `commitment: exploring | leaning | decided | locked` on preferences, theses, and decision records; injected text renders the tier label in place of the raw confidence float when set and is byte-identical when unset.
+- Decision-change receipts: `decision_change.v1` JSONL alongside the truth ledger recording before, after, evidence, confidence delta, alternatives, actor, and reason code with durable idempotency keys; emitted on decision record/outcome/rating, lifecycle tombstone/supersede, and material confidence-band drops; `o2b brain decision history` pages the trail with an opaque cursor and normalized subject matching.
+- Rated-decision recall governor: deterministic token-overlap prompt matching resurfaces rated decisions verbatim under `decision_recall.max_per_session` and `decision_recall.min_spacing_turns` (config plus env twins); disabled and byte-identical when unset, with governor state flags on both CLI and MCP.
+- Conversation chronology: session imports stamp `authored_at` on turn signals, the search index (schema v10) carries and returns it (`authored_at` in CLI JSON, `authoredAt` in MCP results), exact hybrid-score ties break toward more recently authored content, `session-grep` accepts `--since`/`--before`, and `o2b brain authored-at-backfill` upgrades existing vaults idempotently (dry-run default, no re-embedding).
+- Tension objects (`o2b brain tension`, MCP `brain_tension`): detected contradictions persist under `Brain/tensions/` with a deterministic dedup key and an open -> confirmed/dismissed/resolved state machine; re-detection refreshes instead of duplicating; context packs warn when a subject note of an unresolved tension is injected.
+
+### Changed
+
+- The MCP tool surface grows from 98 to 102 tools (`brain_lifecycle`, `brain_claims`, `brain_decision`, `brain_tension`); `brain_session_grep` gains `since`/`before` parameters and `brain_search` results expose `authoredAt`.
+- Search store schema advances to v10 with a nullable `authored_at` column; existing indexes migrate in place and documents without a turn instant are unchanged.
+- Context-pack reports gain an additive `warnings` array (unresolved-tension notices) and items carry optional `commitment`; packs without tensions or tiers stay byte-identical.
+
## [1.32.0] - 2026-07-18
A memory write-path integrity and store safety wave: eleven units across four subsystems that make every durable write choke point validate its input, every destructive vault operation snapshot first, and every embeddings failure surface as a typed, actionable outcome. All gates are deterministic (the kernel still calls no LLM), every rejection is a typed error or a logged, visible skip, and no new dependency is added.
@@ -6508,6 +6532,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.33.0]: https://github.com/itechmeat/open-second-brain/compare/v1.32.0...v1.33.0
[1.32.0]: https://github.com/itechmeat/open-second-brain/compare/v1.31.0...v1.32.0
[1.31.0]: https://github.com/itechmeat/open-second-brain/compare/v1.30.1...v1.31.0
[1.30.1]: https://github.com/itechmeat/open-second-brain/compare/v1.30.0...v1.30.1
diff --git a/README.md b/README.md
index 54bd4094..16a05e61 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm
## What is new
-Open Second Brain 1.32.0 is a memory write-path integrity and store safety release. Every durable write choke point now validates its input: embedding vectors are rejected before they can poison the semantic index, entity labels are stripped of Markdown decoration and structurally validated before graph persistence, and extracted facts pass a deterministic durability gate (with an optional operator write-approval queue) before landing in the brain. Destructive vault operations (`forget-source`, entity prune) take a snapshot first and report the recovery point. Embeddings quota exhaustion is now a distinct, actionable outcome with Retry-After-aware backoff, e5-family models get their required instruction prefixes, and MCP responses carry opaque store references instead of absolute host paths. The kernel still calls no LLM.
+Open Second Brain 1.33.0 is a belief lifecycle and decision memory release. Memories now have a full lifecycle: an idempotent tombstone and supersede operation spans every memory type, facts can be replaced atomically at one instant with gap-free half-open validity intervals, a persisted claim graph answers "what is true now, what used to be true, what replaced it, what contests it" in one query, and injection prefers the tip of a supersedes chain while recall points superseded hits at their replacement. Decisions become first-class: recorded with assumption and review date (which opens a review obligation), rated and compared, tiered by commitment (exploring, leaning, decided, locked), receipted on every change with before/after/evidence trails, and resurfaced verbatim into matching sessions under per-session caps and spacing. Detected contradictions persist as triageable tension objects that warn at injection time until resolved, and transcript turns keep their authored time all the way into search ranking and time-bounded queries. The kernel still calls no LLM.
## Why
diff --git a/docs/brainstorm/belief-lifecycle-decision-memory/cli-output/claude.md b/docs/brainstorm/belief-lifecycle-decision-memory/cli-output/claude.md
new file mode 100644
index 00000000..de5b3f54
--- /dev/null
+++ b/docs/brainstorm/belief-lifecycle-decision-memory/cli-output/claude.md
@@ -0,0 +1,41 @@
+### Variant 1: Foundation-first shared kernels
+
+- **Approach**: Land two new shared modules before any feature unit: a supersession-lifecycle kernel (`src/core/brain/lifecycle/` - temporal boundary ops with half-open intervals, tombstone/supersede state machine, chain traversal to tip, receipt emission) and a decision-record kernel (decision note type + frontmatter schema, commitment tier, rating store). Units 1, 3, 4, 5, 11 become thin consumers of the first kernel; units 7, 8, 9, 10 of the second; units 2 and 6 stay standalone. The first two commits of the wave are pure infrastructure with tests but no user-visible behavior.
+- **Trade-offs**:
+ - Pro: chain traversal, interval semantics, and receipt idempotency are written once - four supersession units and five decision units cannot drift on interval math or tip-resolution rules.
+ - Pro: matches the repo's stated "shared choke points over scattered per-call-site checks" convention and the v1.30.1 one-directional layering.
+ - Pro: unit 11's receipts hook naturally into the kernel's single write path instead of being retrofitted into five call sites.
+ - Con: kernel design must be right before any consumer exists; requirements discovered in unit 5 or 9 (injection budgets, spacing) force kernel rework mid-wave.
+ - Con: the first commits violate the spirit of "one atomic feature commit per unit" - they are release-invisible scaffolding, and a slipped wave ships dead code in v1.33.0.
+ - Con: serializes the wave - little can start until both kernels merge to the branch.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 2: Fully isolated units, existing surfaces only
+
+- **Approach**: No new shared modules. Each unit lands self-contained against existing choke points: units 1/3/4/5 each read/write `superseded_by` through `enrich.ts` and frontmatter directly, units 7-11 each define their own frontmatter fields and query slices, unit 11 writes receipts as its own JSONL alongside the truth ledger. Overlap (chain walking in 3/4/5, injection changes in 5 and 9, contradiction reads in 3 and 6) is duplicated per unit and deferred to a possible post-wave refactor.
+- **Trade-offs**:
+ - Pro: maximal commit atomicity and parallelism - any unit can be built, reviewed, or dropped from the wave independently; no unit is blocked on an abstraction that doesn't exist yet.
+ - Pro: lowest up-front design risk; each unit's blast radius is exactly its own diff.
+ - Con: at least three independent implementations of "walk the supersedes chain to its tip" and two of "interval validity at an instant" - divergence here produces user-visible inconsistency (recall says X is current, inject says Y is).
+ - Con: units 5 and 9 both patch the injection loop with caps/preference logic; the second one merged must rebase over the first's uncoordinated changes, and their budget/spacing rules can conflict silently.
+ - Con: contradicts the repo's post-v1.30.1 direction and guarantees a v1.33.x dedup refactor.
+- **Complexity**: medium
+- **Risk**: high
+
+### Variant 3: Cluster tracks with anchor-unit-owned abstractions
+
+- **Approach**: Organize the wave into three tracks, where the first unit of each track ("anchor") ships the track's shared abstraction as part of its own feature commit, and later units in the track consume it. Track A (supersession spine, order 4 β†’ 1 β†’ 3 β†’ 5): unit 4's generalized tombstone/supersede lifecycle module is the shared core; unit 1 adds the temporal-boundary op on top; unit 3's claim-graph projection reads through it; unit 5 consumes its chain-tip resolver. Track B (decision memory, order 7 β†’ 8 β†’ 10 β†’ 11 β†’ 9): unit 7's decision-record note type is the anchor; 8/10/11 extend its schema and store; unit 9 lands last. The only cross-track shared piece is a small injection-governor helper (caps, spacing, tip-preference) introduced by whichever of 5/9 lands first and reused by the other; units 2 and 6 are order-free standalones (6 reads the same contradiction relations as 3 but through the existing `contradicts` surface, not a new one).
+- **Trade-offs**:
+ - Pro: every commit is a real feature (no infrastructure-only commits), yet shared logic still has exactly one home - the anchor unit's module - satisfying both the atomic-commit rule and the choke-point convention.
+ - Pro: abstractions are designed against a concrete first consumer, then hardened by the second, avoiding Variant 1's speculative-API risk.
+ - Pro: dependency ordering is explicit and shallow (two chains plus two free units), so the wave degrades gracefully - a track can stop early and still ship its landed prefix.
+ - Con: intra-track ordering constraints limit parallelism (unit 5 waits on 4; unit 9 waits on 7/8 and the injection governor).
+ - Con: anchor commits (4 and 7) are larger than average because they carry the shared module plus their own feature.
+ - Con: if a mid-track unit (e.g. 3) exposes a flaw in the anchor's abstraction, fixing it means amending an already-landed commit's module - churn inside the release branch.
+- **Complexity**: medium
+- **Risk**: low
+
+### Recommended: Variant 3
+
+**Rationale**: The wave's real coupling is exactly two clusters (supersession spine, decision family) plus one injection touchpoint, and anchor-owned abstractions put each shared piece in one place without Variant 1's speculative infrastructure commits or Variant 2's guaranteed chain-walking divergence between recall, inject, and dream. It is the only variant that keeps every commit an atomic user-visible feature (the project's own release convention) while honoring the post-v1.30.1 "shared choke points, one-directional layering" rule, and its shallow ordering means a partially completed wave still ships coherently as v1.33.0.
diff --git a/docs/brainstorm/belief-lifecycle-decision-memory/cli-output/prompt.md b/docs/brainstorm/belief-lifecycle-decision-memory/cli-output/prompt.md
new file mode 100644
index 00000000..cb3a62bf
--- /dev/null
+++ b/docs/brainstorm/belief-lifecycle-decision-memory/cli-output/prompt.md
@@ -0,0 +1,88 @@
+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
+
+An 11-unit feature wave for Open Second Brain themed "belief lifecycle and decision memory". The variants requested are for the wave architecture as a whole (where to put shared abstractions vs isolated per-unit changes), not for the worth of individual units. The units:
+
+1. `t_3ba9c404` (p3) - Atomic temporal fact-replacement: close an open fact and open its successor at one shared timestamp instant, half-open valid_from/valid_to intervals at timestamp precision (whole-day semantics preserved for date-only facts). Distinct from the existing conflict-resolution supersede (winner-picking only). Reuse the `superseded_by` relation as the successor link; scope to the temporal-boundary layer only.
+
+2. `t_347e8224` (p3) - Preserve conversation chronology: retain each transcript turn's authored time as `authored_at`, surface it in search results, break exact hybrid-score ties in favor of more recently-authored content, add since/before time bounds to list. Idempotent dry-run-first backfill for existing vaults, no re-embedding.
+
+3. `t_6916369f` (p3) - Unify temporal/supersession/contradiction into one persisted claim-graph query surface: a bounded, persisted projection OVER existing relations (superseded_by, contradicts) and bi-temporal validity fields (valid_from/valid_until derived in dream), answering "what is true now / what used to be true / what replaced it / what contests it" in one query. Current-truth default, opt-in history. Not a rewrite of extractors. Surface provenance per claim.
+
+4. `t_7d5a3589` (p2) - General cross-type soft-delete (tombstone) + supersession lifecycle: idempotent tombstone via Markdown frontmatter status + reason + timestamp (re-issue is a no-op), supersede with replacement tracking, generalized beyond the claim ledger to preferences/signals/learnings. Curator read slices over observed-use verdicts (injected-never-used, contradicted, high-used) through the existing read surface. Tombstoned/superseded entries excluded from recall but preserved for audit; wired into dream/compaction.
+
+5. `t_d9365884` (p2) - Supersedes-chain consumer policy over general memory driving three behaviors: inject prefers chain tips under budget (unless the query is explicitly historical), recall annotates superseded items with a pointer to their replacement, decay accelerates for low-recall superseded items. Acceptance: a chain of 3 superseding memories injects only the tip by default, surfaces replacement pointers on recall, retires low-recall ancestors on the dream pass.
+
+6. `t_0e3f2bee` (p3) - Persist detected contradictions as first-class tension objects: deterministic Markdown notes with a state machine (open -> confirmed/dismissed/resolved) in frontmatter, plus an injection-time warning when subject notes of an unresolved tension enter a context pack. Lifecycle object is the higher-value half and can ship first.
+
+7. `t_ac03214d` (p3) - Decision-record artifact: capture a decision with its assumption, scheduled review_date, and outcome backfilled when known; review_date opens an obligation; on a new decision, surface historically-similar past decisions and their outcomes via existing search/similarity. Optional pre-mortem field.
+
+8. `t_6fe43fcc` (p3) - Rated decision capture separate from memory facts: human-triggered surface storing decisions, ratings, and rationale apart from ordinary signals; searchable and comparable. Focused on the rated searchable engine, not the artifact format (that is unit 7).
+
+9. `t_5712fa39` (p3) - Recall rated past decisions verbatim into live sessions on matching prompts, governed by per-session injection caps and spacing rules. Builds on existing injection + observed-use + trust rating; the missing piece is prompt-match -> verbatim-resurface plus the cap/spacing governor.
+
+10. `t_e112c63c` (p3) - Commitment-tier vocabulary: optional four-value decision-commitment axis (exploring/leaning/decided/locked) distinct from confidence, set on decision-tracking memories (preferences, declared-thesis entries), rendered in injected/context-pack text as the tier label; round-trips through frontmatter without breaking confidence-band display when unset.
+
+11. `t_3547314d` (p3) - Decision-change receipts: a `decision_change.v1` receipt recording before, after, evidence triggers, confidence delta, alternatives, actor, rationale, reason code at the moment a belief/preference changes; durable idempotency keys; history query with pagination. Hidden chain-of-thought fields rejected - only accountable provenance. Natural home alongside the supersession/dream pipeline.
+
+Cross-unit observations to weigh: units 1, 3, 4, 5 all touch supersession (`superseded_by`); units 7, 8, 9, 10, 11 form a decision-memory family; unit 6 (tensions) and unit 3 (claim graph) both consume contradiction relations; units 5 and 9 both modify injection; unit 2 is search/chronology-only. The wave ships as ONE release (v1.33.0) on one branch with per-unit atomic commits.
+
+# Project context
+
+Open Second Brain (o2b): TypeScript on Bun, CLI (`o2b`) + MCP server over an Obsidian-compatible Markdown vault; bun:sqlite + optional sqlite-vec for search; deterministic kernel - no LLM calls in core. Vault is synced peer-to-peer (Syncthing), no git transport.
+
+Recent commits:
+- 61e93d24 fix(config): derive vault store reference from a keyed installation secret (#140)
+- 9a649dd6 feat: memory write-path integrity and store safety wave (v1.32.0) (#139)
+- f2a037eb feat: today operator surface - dashboard, open loops, marker write-back (v1.31.0) (#138)
+- 13bde6c3 refactor: remove all import cycles, decompose search.ts (v1.30.1) (#137)
+- fd5661f9 feat: governance visibility - vitals scorecard + batch-inflation lint (v1.30.0) (#136)
+
+Related files (verified on main):
+- Supersession: src/core/search/enrich.ts:23 SUPERSEDED_RELATION="superseded_by" (:116 stamps superseded flag on hits); src/core/search/types.ts:611-613 and :856-859 document demote-predecessor/boost-successor and contradicts warning reasons; src/mcp/brain/knowledge-tools.ts:352 renders superseded_by, :704 current-truth slots; src/core/brain/portability/graph.ts:35 RELATION_FIELDS includes contradicts + superseded_by; src/core/brain/preference.ts:256 superseded_by field.
+- Truth ledger (append-only): src/core/brain/truth/store.ts appendClaimEvent:89, readClaimEvents:129, TruthState:266/319, sweep:350, cap CLAIM_EVENT_MAX_COUNT=10000; grounding.ts GroundingScore:61 bandFor:100 (bands strongly_supported|mixed|contested|contradicted).
+- Contradiction detection: src/core/brain/health/contradiction.ts detectNoteContradictions:200, deriveNoteStance:154. Declared-thesis register: src/core/brain/health/thesis.ts (Brain/theses/thesis-<slug>.md, ThesisPage:70, ThesisError:68, stale/graveyard detectors).
+- Bi-temporal validity: dream-plan.ts:132-133 valid_from/valid_until; dream.ts:458-459 emission, extractTemporalValidity:1308; dream-refresh.ts freshness_trend:53.
+- Injection loop: inject-failopen.ts; observed-use.ts OBSERVED_USE_VERDICTS USED|IGNORED|CONTRADICTED:25 (deterministic token-echo/stance heuristics, persisted as recall_observed_use events); trust/self-approval-guardrail.ts; recall gate src/mcp/search-tools.ts toolBrainRecallGate:662; recall-telemetry.ts.
+- Injected text: src/core/brain/active.ts regenerateActive:94 renders confidence band + numeric tail; context-pack.ts packContext:286 ContextPackItem:70; preference.ts confidence band:130 + confidence_value:132-137 (Wilson x freshness).
+- Obligations: obligations.ts ObligationPage:61 (cadence:64, completions:74, nextDueDate:172, ObligationError). Attributes: attributes.ts assignNoteAttribute:129, validateAttributeAssignment:69.
+- Session import: sessions/import.ts importSession/importSessionPath; resolveEventInstant:122 ALREADY preserves turn timestamp into created_at/recorded_at/valid_from bi-temporal slots; session_grep in src/mcp/brain/recall-tools.ts + core session-recall.ts - NO since/before created_at filter on the query surface today; search fusion src/core/search/fusion.ts rrfFuse DEFAULT_RRF_K=60, ranker.ts tierByDoc:39; src/core/search/time-range.ts exists for search-side time parsing.
+- Provenance: provenance/provenance.ts ProvenanceLevel stated|deduced|inferred:41, provenanceTrustRank:69, Provenance:74, sourceIdentityHash:91. Git decision mining: git/decisions.ts detectDecisionSignals:37, mineCommitDecisions:110.
+- v1.32.0 write path (fresh on main): src/core/brain/gates/durability.ts classifyDurability:191 (+config durability.denylist); src/core/brain/pending.ts (write_approval.enabled staging, apply/reject); signal-retire.ts retireSignal:97; write-advisory.ts adviseIncomingFeedback:103; snapshot-gate.ts withDestructiveSnapshot:87.
+- Registration: CLI = switch dispatcher src/cli/brain.ts + thin verbs src/cli/brain/verbs/*.ts + data-only help-text.ts; MCP = frozen ToolDefinition[] slices (src/mcp/brain/*-tools.ts) assembled by src/mcp/tools.ts buildToolTable:319.
+- Idea lineage: idea-lineage.ts transitionStage:296 (creation|promotion|retirement -> observation|synthesis|conclusion).
+- Log event kinds: src/core/brain/types.ts BRAIN_LOG_EVENT_KIND:158 (~27 kinds; new belief/decision event kinds extend this one const object); daily files Brain/log/<date>.md.
+- Decision surfaces today: RECONCILE_DOMAIN.decisions (types.ts:363, never auto-resolved operator bucket); git-mined decision signals; idea-lineage conclusion stage. NO dedicated decision note type exists - greenfield, but should reuse the decisions reconcile domain and lineage stage mapping.
+
+Conventions:
+- Typed errors per subsystem (SearchError codes for search/embeddings; typed brain-side rejections for vault writes); no silent fallbacks, no stubs; errors surface explicitly.
+- Config keys resolved through src/core/config.ts helpers with env overrides; constants extracted, no magic literals.
+- One-directional layering restored in v1.30.1 (no import cycles); shared choke points over scattered per-call-site checks.
+- Language-agnostic classification only: structural signals, config-supplied vocabularies, no built-in natural-language word lists.
+- Markdown vault is the source of truth; frontmatter carries typed fields; destructive operations go through the v1.32.0 snapshot gate (withDestructiveSnapshot).
+- Every unit lands as one atomic conventional commit with its tests, formatted (oxfmt) and lint-clean (oxlint).
+
+Constraints:
+- Do not change existing public CLI/MCP APIs incompatibly; additive surfaces only.
+- No new external dependencies.
+- No LLM calls in the deterministic kernel (prompt-matching for unit 9 must be deterministic, e.g. token/anchor matching).
+- The vault has no git; any history/receipt store must be Markdown/JSONL native and Syncthing-safe.
+- Preserve byte-identical behavior for vaults that do not opt into new fields.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **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-3 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/belief-lifecycle-decision-memory/design.md b/docs/brainstorm/belief-lifecycle-decision-memory/design.md
new file mode 100644
index 00000000..749680d3
--- /dev/null
+++ b/docs/brainstorm/belief-lifecycle-decision-memory/design.md
@@ -0,0 +1,187 @@
+# Belief lifecycle and decision memory - wave design
+
+**Status:** approved for implementation
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+**Release:** v1.33.0, single PR, per-unit atomic commits
+
+## Problem statement
+
+Open Second Brain records beliefs but not their lifecycle. Supersession exists
+only as a bare `superseded_by` relation scoped to the claim ledger; a wrong or
+replaced memory is edited or removed with no tombstone, no replacement link,
+and no receipt of why the belief changed. Detected contradictions have no
+durable state, so they silently re-fire. Decisions - the highest-value operator
+memories - have no first-class artifact, no rating, no review obligation, no
+commitment vocabulary, and are never proactively resurfaced. Transcript turns
+lose their authored time at the search layer, so recall cannot prefer recent
+statements or answer time-bounded questions.
+
+## Scope
+
+Eleven kanban tasks shipped as one release, organized as two anchored tracks
+plus two standalone units (consultant Variant 3):
+
+**Track A - supersession spine** (anchor first, later units consume it):
+- `t_7d5a3589` (anchor) - cross-type tombstone + supersede lifecycle module,
+ curator read slices over observed-use verdicts.
+- `t_3ba9c404` - atomic temporal fact-replacement with half-open
+ `valid_from`/`valid_to` intervals.
+- `t_6916369f` - persisted claim-graph projection + one query surface
+ ("true now / used to be true / replaced by / contested by").
+- `t_d9365884` - supersedes-chain consumer policy: inject prefers chain tips,
+ recall annotates replacements, decay accelerates for low-recall ancestors.
+
+**Track B - decision memory** (anchor first):
+- `t_ac03214d` (anchor) - decision-record note type: assumption, review_date
+ (opens an obligation), outcome backfill, similar-decision recall, optional
+ pre-mortem field.
+- `t_6fe43fcc` - rated decision capture: rating + rationale fields and a
+ searchable list/compare surface, separate from ordinary signals.
+- `t_e112c63c` - commitment tier (`exploring | leaning | decided | locked`)
+ rendered in injected text in place of the raw confidence float when set.
+- `t_3547314d` - `decision_change.v1` receipts: before/after/evidence/
+ confidence-delta/actor/reason at the moment a belief changes, idempotent,
+ with a paginated history query.
+- `t_5712fa39` - recall rated decisions verbatim on deterministically matching
+ prompts, governed by per-session caps and spacing.
+
+**Standalone units:**
+- `t_347e8224` - conversation chronology: `authored_at` on indexed transcript
+ turns, surfaced in search, recency tie-break on exact hybrid-score ties,
+ since/before bounds, idempotent dry-run-first backfill.
+- `t_0e3f2bee` - tension objects: persisted contradiction notes with an
+ open -> confirmed/dismissed/resolved state machine and injection-time
+ warnings for unresolved tensions.
+
+## Out of scope
+
+- `t_469e4cfa` (typed revertible lifecycle history / undo) - needs its own ADR
+ wave; receipts here are append-only accountability, not rollback.
+- `t_b0c9d0a3` (overwrite-only exact-state lane) - separate storage
+ architecture.
+- Any rewrite of existing extractors, conflict-resolution supersede, or the
+ truth ledger event format.
+- LLM-based prompt matching or transcript classification (kernel stays
+ deterministic).
+
+## Chosen approach
+
+Consultant Variant 3: cluster tracks with anchor-unit-owned abstractions. The
+first unit of each track ships the track's shared module as part of its own
+feature commit; later units consume it. No infrastructure-only commits, no
+cross-subsystem framework. The single cross-track shared piece is an
+injection-governor helper introduced by the chain-policy unit and reused by
+the rated-decision recall unit.
+
+## Design decisions
+
+- **Lifecycle module home**: Track A's shared core lands as
+ `src/core/brain/lifecycle/tombstone.ts` (tombstone/supersede state machine,
+ idempotency, chain-tip resolver `resolveChainTip`) plus
+ `src/core/brain/lifecycle/temporal-replace.ts` (half-open interval
+ replacement). One-directional imports only: lifecycle imports from
+ `preference.ts`/`types.ts`, never the reverse.
+- **Tombstone is frontmatter, not deletion**: `_status: "tombstoned"`,
+ `tombstoned_at`, `tombstone_reason`, optional `superseded_by`. Re-issuing a
+ tombstone is a no-op returning the existing state. Tombstoned and
+ superseded-non-tip entries are excluded from recall/inject/active.md but
+ remain on disk for audit; dream/compaction respects the exclusion.
+- **Temporal replacement reuses `superseded_by`** as the successor link. The
+ operation closes the predecessor (`valid_to = T`) and opens the successor
+ (`valid_from = T`) at one shared instant; intervals are half-open
+ `[valid_from, valid_to)`. Date-only facts keep whole-day semantics. This
+ layer does not touch the existing conflict-resolution supersede in
+ hygiene/resolve-conflicts.
+- **Claim graph is a projection, not a store of record**: built from existing
+ relations (`superseded_by`, `contradicts`) plus bi-temporal validity fields,
+ persisted as a bounded JSON artifact under the brain store, rebuilt
+ deterministically; query surface is one CLI verb (`o2b brain claims`) and one
+ MCP tool answering point-in-time and history questions. Current-truth is the
+ default; history is opt-in.
+- **Chain consumer policy** lives at existing choke points: inject
+ (context-pack/inject path prefers `resolveChainTip` results under budget),
+ recall (annotates superseded hits with the replacement pointer via the
+ existing enrich layer), decay (dream pass accelerates retirement of
+ low-recall superseded ancestors). Historical queries bypass tip-preference
+ via an explicit flag, not language detection.
+- **Decision records are a new note family** under `Brain/decisions/` with
+ frontmatter `type: decision`, `chosen`, `assumption`, `review_date`,
+ `outcome` (backfilled), optional `premortem`, plus rating fields from the
+ rated-capture unit (`rating`, `rationale`). `review_date` maps onto the
+ existing obligations engine (one obligation per decision review). Outcome
+ backfill is a logged mutation. Similar-decision recall reuses the existing
+ search machinery scoped to the decision family.
+- **Commitment tier is additive**: optional frontmatter `commitment` with the
+ four-value vocabulary on preferences, theses, and decision records;
+ `active.ts` and the context-pack formatter render the tier label when set
+ and fall back to the confidence band byte-identically when unset.
+- **Receipts are JSONL, Syncthing-safe**: `decision_change.v1` records append
+ to a receipts log alongside the truth ledger shards, keyed by a durable
+ idempotency key (hash of subject id + before-state + after-state); replays
+ are no-ops. History query paginates with an opaque cursor. Free-text hidden
+ reasoning fields are rejected by the schema; only the accountable fields
+ listed in the task ship. Receipt emission hooks the lifecycle module's
+ supersede/tombstone path and the preference-confidence update path.
+- **Injection governor** is one helper (`src/core/brain/inject-governor.ts`)
+ owning per-session caps, spacing, and tip-preference bookkeeping; introduced
+ by the chain-policy unit, extended (caps/spacing for rated decisions) by the
+ recall unit. Prompt matching for decision recall is deterministic
+ token/anchor overlap - no LLM, no language-specific word lists.
+- **Chronology**: `authored_at` carried from the already-preserved turn
+ instant (`resolveEventInstant`) into indexed documents and search results;
+ exact hybrid-score ties break toward more recent `authored_at`; `session_grep`
+ and session-recall gain `since`/`before` bounds parsed by the existing
+ `time-range.ts`; backfill command is idempotent, dry-run by default, and
+ never re-embeds.
+- **Tensions**: `Brain/tensions/tension-<slug>.md` notes created from detected
+ contradictions with `_status: open | confirmed | dismissed | resolved`;
+ deterministic dedup key (subject pair + stance signature) so re-detection
+ updates instead of duplicating; context-pack build emits a warning line when
+ a subject note of an unresolved tension is included.
+- **Event kinds**: new `BRAIN_LOG_EVENT_KIND` entries (`tombstone`,
+ `temporal-replace`, `decision-record`, `decision-outcome`,
+ `decision-change-receipt`, `tension`, `chain-decay`) extend the existing
+ const object.
+- **Errors and config**: each new module declares its own `XxxError extends
+ Error`; config keys follow the paired `FOO_CONFIG_KEY`/`OPEN_SECOND_BRAIN_*`
+ env pattern in `src/core/config.ts` (`decision_recall.max_per_session`,
+ `decision_recall.min_spacing_turns`).
+
+## File changes
+
+New: `src/core/brain/lifecycle/tombstone.ts`, `lifecycle/temporal-replace.ts`,
+`src/core/brain/claim-graph.ts`, `src/core/brain/decisions/record.ts`,
+`decisions/receipts.ts`, `src/core/brain/inject-governor.ts`,
+`src/core/brain/tensions.ts`, CLI verbs (`lifecycle`, `claims`, `decision`,
+`tensions`, `backfill-authored-at` under existing verb files where natural),
+MCP tool additions in existing `src/mcp/brain/*-tools.ts` slices, tests
+mirroring each module under `tests/`.
+
+Modified: `src/core/brain/types.ts` (event kinds), `preference.ts` (commitment
+field passthrough), `active.ts` + `context-pack.ts` (tier render, tension
+warnings, tip preference), `dream.ts`/`dream-refresh.ts` (decay, exclusion),
+`src/core/search/enrich.ts` (replacement pointer annotation),
+`src/core/search/fusion.ts` or `ranker.ts` (recency tie-break),
+`src/core/search/indexer.ts`/`walker.ts` (authored_at),
+`src/mcp/brain/recall-tools.ts` (since/before), `src/core/brain/obligations.ts`
+(decision-review obligation source), `src/cli/brain.ts` + `help-text.ts`,
+`src/core/config.ts`, docs (`README.md`, `CHANGELOG.md`,
+`docs/cli-reference.md`, `docs/mcp.md`).
+
+## Risks and open questions
+
+- Anchor commits (t_7d5a3589, t_ac03214d) are larger than average; mitigated
+ by TDD and by keeping curator slices/pre-mortem optional sub-features inside
+ the same commit.
+- A mid-track flaw in the anchor abstraction means churn on the release
+ branch; acceptable, branch is unpushed until phase 6.
+- Injection changes (chain tips + rated-decision recall + tension warnings)
+ all touch context assembly; the injection governor and context-pack are the
+ only two choke points allowed to change, and each unit adds tests proving
+ the others' behavior is preserved.
+- Recency tie-break must not reorder non-tied results: applies strictly on
+ exact score equality after fusion.
+- Backfill touches every indexed session document; dry-run default plus
+ snapshot-free (non-destructive, additive field) keeps it safe; no
+ re-embedding by construction.
diff --git a/docs/brainstorm/belief-lifecycle-decision-memory/plan.md b/docs/brainstorm/belief-lifecycle-decision-memory/plan.md
new file mode 100644
index 00000000..de7a0f33
--- /dev/null
+++ b/docs/brainstorm/belief-lifecycle-decision-memory/plan.md
@@ -0,0 +1,160 @@
+# Belief lifecycle and decision memory - implementation plan
+
+Ordering follows consultant Variant 3: each track's anchor lands first and
+owns the track's shared abstraction; later units in the track consume it.
+Tracks are mutually independent; standalone units are order-free. Each unit
+lands as one atomic conventional commit with its tests, formatted (oxfmt) and
+lint-clean (oxlint).
+
+Sequence: A1 -> A2 -> A3 -> A4 -> B1 -> B2 -> B3 -> B4 -> B5 -> S1 -> S2 -> L
+(Track B may run in parallel with Track A on the same branch; S1/S2 anytime.)
+
+## Tasks
+
+### Task A1 - cross-type tombstone + supersede lifecycle (`t_7d5a3589`, p2, Track A anchor)
+- **Files**: new `src/core/brain/lifecycle/tombstone.ts` (state machine,
+ idempotent tombstone, supersede-with-replacement, `resolveChainTip`),
+ exclusion wiring in recall/inject/active/dream paths, curator read slices
+ over observed-use verdicts surfaced through the existing read surface
+ (brain_brief/schema_inspect style), CLI verb + MCP addition, event kinds in
+ `src/core/brain/types.ts`, tests.
+- **Acceptance**: tombstoning any memory type (preference, signal, learning)
+ sets `_status`/`tombstoned_at`/`tombstone_reason` frontmatter without
+ deleting the file; re-issuing is a byte-identical no-op; supersede records
+ the replacement link; tombstoned and superseded-non-tip entries stop
+ appearing in recall, inject, and `Brain/active.md` but remain readable for
+ audit; curator slices list injected-never-used, contradicted, and high-used
+ memories from observed-use verdicts; every lifecycle mutation logs a typed
+ event.
+- **Depends on**: none.
+
+### Task A2 - atomic temporal fact-replacement (`t_3ba9c404`, p3)
+- **Files**: new `src/core/brain/lifecycle/temporal-replace.ts`, tests.
+- **Acceptance**: one operation closes the predecessor (`valid_to = T`) and
+ opens the successor (`valid_from = T`) at one shared instant with half-open
+ `[valid_from, valid_to)` semantics; date-only facts keep whole-day
+ semantics; the pair is written atomically (both or neither); the successor
+ link reuses `superseded_by`; point-in-time evaluation of the pair yields no
+ gap and no overlap for any probe instant (property test); the existing
+ conflict-resolution supersede path is untouched (its tests stay green).
+- **Depends on**: A1 (same module family, chain link conventions).
+
+### Task A3 - persisted claim-graph query surface (`t_6916369f`, p3)
+- **Files**: new `src/core/brain/claim-graph.ts` (bounded persisted
+ projection + rebuild), CLI verb `o2b brain claims`, MCP tool in the
+ knowledge slice, tests.
+- **Acceptance**: the projection composes existing `superseded_by`/
+ `contradicts` relations and `valid_from`/`valid_until` fields plus
+ provenance per claim; one query answers "true at instant T", "current
+ truth", "what replaced X", "what contests X"; current-truth is the default
+ and history/retracted content is opt-in; the projection is bounded (cap
+ constant) and deterministically rebuildable; no extractor is modified.
+- **Depends on**: A1, A2 (reads chain and interval conventions).
+
+### Task A4 - supersedes-chain consumer policy (`t_d9365884`, p2)
+- **Files**: new `src/core/brain/inject-governor.ts` (tip-preference
+ bookkeeping), inject path (context-pack), `src/core/search/enrich.ts`
+ (replacement-pointer annotation on superseded hits), dream decay
+ acceleration, tests.
+- **Acceptance**: a chain of 3 superseding memories injects only the tip
+ under budget by default; an explicit historical flag keeps the chain; recall
+ results for superseded items carry a pointer to their replacement; the dream
+ pass retires low-recall superseded ancestors faster than live memories
+ (deterministic threshold constants); non-chain memories behave
+ byte-identically to today.
+- **Depends on**: A1 (`resolveChainTip`).
+
+### Task B1 - decision-record artifact (`t_ac03214d`, p3, Track B anchor)
+- **Files**: new `src/core/brain/decisions/record.ts` (note family under
+ `Brain/decisions/`, frontmatter schema, outcome backfill, similar-decision
+ lookup), obligation wiring for `review_date`, CLI verb + MCP addition, event
+ kinds, tests.
+- **Acceptance**: capturing a decision writes a `type: decision` note with
+ `chosen`, `assumption`, `review_date`, empty `outcome`, optional
+ `premortem`; `review_date` opens exactly one obligation, idempotently;
+ outcome backfill mutates the note and logs the mutation; capturing a new
+ decision surfaces historically similar decisions with their recorded
+ outcomes via existing search; malformed input rejects with a typed error.
+- **Depends on**: none.
+
+### Task B2 - rated decision capture (`t_6fe43fcc`, p3)
+- **Files**: `src/core/brain/decisions/record.ts` (rating/rationale fields,
+ list/compare queries), CLI/MCP surface, tests.
+- **Acceptance**: a decision can be captured or updated with `rating` and
+ `rationale` kept separate from ordinary signals; rated decisions are
+ listable, sortable by rating, and searchable without polluting
+ signal/preference recall; rating updates are logged; unrated decisions
+ render unchanged.
+- **Depends on**: B1.
+
+### Task B3 - commitment-tier vocabulary (`t_e112c63c`, p3)
+- **Files**: `src/core/brain/preference.ts` (optional field passthrough),
+ thesis + decision frontmatter, `src/core/brain/active.ts` and context-pack
+ formatter (tier label render), tests.
+- **Acceptance**: optional `commitment: exploring | leaning | decided |
+ locked` round-trips through frontmatter on preferences, theses, and decision
+ records; when set, injected text renders the tier label in place of the raw
+ confidence float; when unset, output is byte-identical to today; invalid
+ tier values reject with a typed error.
+- **Depends on**: B1 (decision frontmatter exists).
+
+### Task B4 - decision-change receipts (`t_3547314d`, p3)
+- **Files**: new `src/core/brain/decisions/receipts.ts` (`decision_change.v1`
+ JSONL append + paginated history query), hooks in the lifecycle
+ supersede/tombstone path and preference-confidence update path, CLI/MCP
+ history surface, tests.
+- **Acceptance**: a belief/preference change emits one receipt carrying
+ before, after, evidence triggers, confidence delta, alternatives, actor,
+ rationale, reason code; the idempotency key makes replays no-ops; the
+ history query paginates with an opaque cursor and reports exact counts;
+ records with unexpected free-text reasoning fields are rejected; no receipt
+ fires for reads.
+- **Depends on**: A1 (lifecycle hook points), B1 (decision store).
+
+### Task B5 - rated-decision recall with caps and spacing (`t_5712fa39`, p3)
+- **Files**: `src/core/brain/inject-governor.ts` (caps/spacing extension),
+ deterministic prompt-match (token/anchor overlap) over rated decisions,
+ injection wiring, config keys (`decision_recall.max_per_session`,
+ `decision_recall.min_spacing_turns`), tests.
+- **Acceptance**: a prompt deterministically matching a rated decision
+ resurfaces it verbatim in the session; per-session cap and spacing rules
+ prevent repeats (both enforced by the governor and covered by tests); no
+ LLM call and no language-specific word lists in matching; with the feature
+ unconfigured, injection output is byte-identical to today.
+- **Depends on**: A4 (governor exists), B2 (ratings exist).
+
+### Task S1 - conversation chronology (`t_347e8224`, p3, standalone)
+- **Files**: `src/core/search/indexer.ts`/`walker.ts` (carry `authored_at`),
+ search result shaping, `fusion.ts`/`ranker.ts` (exact-tie recency
+ tie-break), `src/mcp/brain/recall-tools.ts` + session-recall core
+ (since/before bounds via existing `time-range.ts`), idempotent dry-run-first
+ backfill command, tests.
+- **Acceptance**: indexed transcript turns expose `authored_at` in search
+ results; exact hybrid-score ties order newer-first while any non-tied pair
+ keeps today's order (regression test); `session_grep`/session-recall accept
+ since/before bounds; backfill is dry-run by default, idempotent on re-run,
+ and performs no re-embedding; documents without a turn instant are
+ unchanged.
+- **Depends on**: none.
+
+### Task S2 - tension objects with lifecycle (`t_0e3f2bee`, p3, standalone)
+- **Files**: new `src/core/brain/tensions.ts` (note family under
+ `Brain/tensions/`, state machine open -> confirmed/dismissed/resolved,
+ dedup key), context-pack injection-time warning, CLI verb + MCP addition,
+ tests.
+- **Acceptance**: a detected contradiction persists as a tension note whose
+ state lives in frontmatter; re-detection of the same subject pair updates
+ the existing note instead of duplicating; confirm/dismiss/resolve
+ transitions validate against the state machine and log events; building a
+ context pack containing a subject note of an unresolved tension emits a
+ warning naming the tension; dismissed/resolved tensions emit nothing.
+- **Depends on**: none.
+
+### Task L - docs, CHANGELOG, version bump
+- **Files**: `README.md`, `CHANGELOG.md` (`## [1.33.0]` + link reference),
+ `docs/cli-reference.md`, `docs/mcp.md`, `package.json` 1.33.0 +
+ `bun run scripts/sync-version.ts`.
+- **Acceptance**: one CHANGELOG entry covers all eleven units;
+ `bun run sync-version:check` passes; README gains short sections for the
+ lifecycle, claim-graph, decision, and tension surfaces.
+- **Depends on**: all previous tasks.
diff --git a/docs/brainstorm/belief-lifecycle-decision-memory/variants.md b/docs/brainstorm/belief-lifecycle-decision-memory/variants.md
new file mode 100644
index 00000000..bd246bcc
--- /dev/null
+++ b/docs/brainstorm/belief-lifecycle-decision-memory/variants.md
@@ -0,0 +1,80 @@
+# Belief lifecycle and decision memory - variant audit trail
+
+Consultant: Claude Code (`claude -p`), prompt in `cli-output/prompt.md`, raw
+output in `cli-output/claude.md`. Three variants were requested for the wave
+architecture as a whole (where shared abstractions live), not for the worth
+of individual units. The fallback consultant (Codex) was not invoked because
+the primary run succeeded with three parseable variants.
+
+## Variant 1: Foundation-first shared kernels
+
+- **Approach**: land two infrastructure modules before any feature unit - a
+ supersession-lifecycle kernel and a decision-record kernel - then implement
+ all units as thin consumers.
+- **Trade-offs**:
+ - Pro: interval math, chain traversal, and receipt idempotency written once.
+ - Pro: matches the shared-choke-point convention.
+ - Con: kernel APIs are designed speculatively before any consumer exists;
+ requirements discovered late force mid-wave kernel rework.
+ - Con: infrastructure-only commits violate the one-atomic-feature-commit
+ convention and could ship dead code if the wave slips.
+ - Con: serializes the whole wave behind two kernel commits.
+- **Complexity**: large
+- **Risk**: medium
+
+## Variant 2: Fully isolated units, existing surfaces only
+
+- **Approach**: no new shared modules; every unit patches existing choke
+ points independently, duplicating chain walking, interval validity, and
+ injection changes per unit.
+- **Trade-offs**:
+ - Pro: maximal commit atomicity and parallelism; smallest per-unit risk.
+ - Con: at least three divergent implementations of chain-tip resolution and
+ two of interval validity - user-visible inconsistency between recall,
+ inject, and dream.
+ - Con: the two injection units patch the same loop uncoordinated; silent
+ conflicts in budget/spacing rules.
+ - Con: guarantees a post-wave dedup refactor, against the post-v1.30.1
+ direction.
+- **Complexity**: medium
+- **Risk**: high
+
+## Variant 3: Cluster tracks with anchor-unit-owned abstractions
+
+- **Approach**: two tracks (supersession spine, decision memory) whose first
+ unit ships the track's shared module inside its own feature commit; later
+ units consume it. One small cross-track injection-governor helper introduced
+ by the first injection unit and reused by the second. Two standalone units.
+- **Trade-offs**:
+ - Pro: every commit is a real feature, yet shared logic has exactly one
+ home; abstractions are designed against a concrete first consumer.
+ - Pro: shallow explicit ordering; a track can stop early and still ship its
+ landed prefix coherently.
+ - Con: intra-track ordering limits parallelism.
+ - Con: anchor commits are larger than average; a mid-track flaw in the
+ anchor abstraction means churn inside the release branch.
+- **Complexity**: medium
+- **Risk**: low
+
+## Consultant recommendation
+
+Variant 3. "The wave's real coupling is exactly two clusters (supersession
+spine, decision family) plus one injection touchpoint, and anchor-owned
+abstractions put each shared piece in one place without Variant 1's
+speculative infrastructure commits or Variant 2's guaranteed chain-walking
+divergence between recall, inject, and dream. It is the only variant that
+keeps every commit an atomic user-visible feature (the project's own release
+convention) while honoring the post-v1.30.1 'shared choke points,
+one-directional layering' rule, and its shallow ordering means a partially
+completed wave still ships coherently as v1.33.0." (quoted verbatim from the
+consultant output)
+
+## Orchestrator decision
+
+Variant 3 is adopted without override. It repeats the architecture pattern
+that succeeded for the v1.32.0 wave (cluster-scoped kernels, per-unit atomic
+commits) while adapting it to this wave's shape: here the shared modules ride
+inside anchor feature commits instead of standalone kernel commits, which
+keeps every commit release-visible. The accepted ordering constraints
+(A1 before A2/A3/A4, B1 before B2/B3/B4, A4+B2 before B5) are recorded in
+`plan.md`.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index dd33f371..51a15d4a 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -249,6 +249,19 @@ o2b brain doctor gains the `symlink-escape` error (vault-internal s
Extracted facts pass a deterministic durability gate before persisting: structural signals only (temp paths, progress counters, run-id and timestamp shapes, measurement-token dominance, exit-status shapes), extendable with `durability.denylist` regexes; rejections log `durability-skip` events and are surfaced by count in the route result. Entity labels are sanitized (`**Foo**` becomes `Foo`) and structurally validated at every intake boundary, with `entities.label_denylist` as the only vocabulary source. Feedback writes that closely resemble a confirmed same-scope preference return a conflict advisory (and log `write-conflict-advisory`) while the write proceeds. Embedding-side: `embedding_prefix_query`/`embedding_prefix_passage` (env twins, e5 preset defaults) control instruction prefixes, invalid vectors are rejected with `EMBEDDING_INVALID_VECTOR`, and quota exhaustion surfaces as non-retriable `EMBEDDING_QUOTA_EXHAUSTED` with Retry-After-aware backoff for plain rate limits.
+### Belief lifecycle and decision memory (since v1.33.0)
+
+```text
+o2b brain lifecycle tombstone <path> --reason <r> | supersede <path> --by <path> | temporal-replace <pred> <succ> --at <instant> | tip <path> | curator [--slice <s>] - cross-type soft-delete and supersession: tombstone is idempotent frontmatter (file stays for audit, leaves recall/inject/active.md), temporal-replace closes and opens at one shared instant with half-open [valid_from, valid_to) intervals, tip resolves the supersedes chain, curator lists injected-never-used / contradicted / high-used memories
+o2b brain claims [--at <instant>] [--history] [--replaced <id>] [--contests <id>] [--rebuild] - claim-graph queries over existing relations and validity fields; current truth by default, history opt-in; --rebuild persists Brain/claim-graph.json deterministically
+o2b brain decision record --title <t> --chosen <c> [--assumption <a>] [--review-date <d>] [--premortem <p>] [--commitment <tier>] | outcome <slug> <text> | rate <slug> <1-5> [--rationale <r>] | show | list [--rated] | compare <slug...> | similar --title <t> | history [--subject <id>] [--cursor <c>] | recall --prompt <p> [--turn <n>] [--count <n>] [--last-turn <n>] [--surfaced-ids <ids>] - decision records under Brain/decisions/; record opens one review obligation per review_date, history pages decision_change.v1 receipts, recall is governed by decision_recall.max_per_session and decision_recall.min_spacing_turns
+o2b brain tension detect [--jaccard <n>] | list [--unresolved] | show <id> | confirm <id> | dismiss <id> | resolve <id> - persisted contradictions under Brain/tensions/ with an open -> confirmed/dismissed/resolved state machine; re-detection refreshes the existing note; unresolved tensions warn at context-pack build time
+o2b brain authored-at-backfill [--apply] - stamp authored_at on pre-1.33.0 session signals from their preserved turn instant; dry-run default, idempotent, never re-embeds
+o2b brain session-grep gains --since <time> and --before <time> bounds on turn time
+```
+
+Supersession is now consumer-aware: context packs inject only the tip of a supersedes chain under budget (an explicit historical flag keeps the whole chain), recall annotates superseded hits with their replacement, and the dream pass accelerates decay of low-recall superseded ancestors (`chain-decay` events). Decisions carry an optional commitment tier (`exploring | leaning | decided | locked`, also valid on preferences and theses) that renders in injected text in place of the raw confidence float when set. Every decision mutation and lifecycle transition appends an accountable `decision_change.v1` receipt (before, after, evidence, confidence delta, actor, reason code) with durable idempotency keys. Search results expose `authored_at` when the source turn carried an instant, and exact hybrid-score ties order newer-first.
+
## Stability and trust (since v1.0.0)
```text
diff --git a/docs/mcp.md b/docs/mcp.md
index d9278e21..bc3fd426 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -492,3 +492,15 @@ Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default
the incoming principle closely resembles a confirmed same-scope preference
(the write still proceeds); the advisory names the preference id and the
similarity evidence.
+- Since v1.33.0 four belief-lifecycle tools join the surface (102 total):
+ `brain_lifecycle` (tombstone / supersede / temporal-replace / tip /
+ curator), `brain_claims` (claim-graph queries: current truth,
+ truth-at-instant, replaced-by, contested-by), `brain_decision`
+ (record / outcome / rate / list / compare / similar / history / recall),
+ and `brain_tension` (detect / list / show / confirm / dismiss / resolve).
+ Decision-change receipts store only accountable provenance; free-text
+ hidden-reasoning fields are rejected by the closed schema.
+- Since v1.33.0 `brain_session_grep` accepts `since` / `before` turn-time
+ bounds and `brain_search` results carry `authoredAt` when the indexed
+ document preserved a turn instant. Context-pack reports list unresolved
+ tension warnings for injected subject notes.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 17cd41dc..b121739b 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.32.0",
+ "version": "1.33.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index f0ef3f18..16a86d1f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.32.0",
+ "version": "1.33.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 a8bbabee..8a3d98bd 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.32.0"
+version: "1.33.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 e2dd8cab..a32c6bf0 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.32.0",
+ "version": "1.33.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/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index a8bbabee..8a3d98bd 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.32.0"
+version: "1.33.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 3c3174e3..0836d8ce 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.32.0"
+version = "1.33.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.ts b/src/cli/brain.ts
index 12218627..c0067499 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -12,6 +12,10 @@ import {
cmdBrainInit,
cmdBrainFeedback,
cmdBrainNote,
+ cmdBrainLifecycle,
+ cmdBrainClaims,
+ cmdBrainDecision,
+ cmdBrainTension,
cmdBrainDream,
cmdBrainApplyEvidence,
cmdBrainDigest,
@@ -63,6 +67,7 @@ import {
cmdBrainBankImport,
cmdBrainBacklinks,
cmdBrainSemanticsBackfill,
+ cmdBrainAuthoredAtBackfill,
cmdBrainMcpLandscape,
cmdBrainMerge,
cmdBrainExplorer,
@@ -162,6 +167,14 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainFeedback(rest);
case "note":
return await cmdBrainNote(rest);
+ case "lifecycle":
+ return await cmdBrainLifecycle(rest);
+ case "claims":
+ return await cmdBrainClaims(rest);
+ case "decision":
+ return await cmdBrainDecision(rest);
+ case "tension":
+ return await cmdBrainTension(rest);
case "dream":
return await cmdBrainDream(rest);
case "apply-evidence":
@@ -266,6 +279,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainBacklinks(rest);
case "semantics-backfill":
return await cmdBrainSemanticsBackfill(rest);
+ case "authored-at-backfill":
+ return await cmdBrainAuthoredAtBackfill(rest);
case "mcp-landscape":
return await cmdBrainMcpLandscape(rest);
case "scan-inline":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 7667aa18..63083b2c 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -15,6 +15,10 @@ Brain verbs (observing memory):
dream Deterministic dreaming pass; stage/validate/apply staged 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
+ claims Claim-graph query: current truth, truth-at-T, replaced-by, contested-by
+ decision Capture/review decisions: record/outcome/show/list/similar
+ tension Detect + triage persisted contradictions: detect/list/show/confirm/dismiss/resolve
digest Render the recent-changes digest (markdown or --json)
intent-review Read-only pre-dream review of active signal clusters
retention Recommendation-only keep/improve/park/prune review
@@ -72,6 +76,7 @@ Brain verbs (observing memory):
bank-import Reconstruct the page graph from a bank bundle (--mode skip|overwrite|merge)
backlinks List inbound references to a Brain artifact id
semantics-backfill Preview deterministic typed preference-edge backfill proposals
+ authored-at-backfill Backfill authored_at on session signals (dry-run default; --apply to write)
mcp-landscape List MCP servers configured across the vault (packages, env names)
scan-inline Capture @osb markers from folders listed under notes.read_paths in _brain.yaml
import-session Replay signals from a registered agent session .jsonl (or directory)
@@ -171,6 +176,51 @@ export const VERB_HELP: Record<string, string> = {
"Append one narrative-milestone line to Brain/log/<today>.md under the `note`\n" +
"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" +
+ "[--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",
+ claims:
+ "usage: o2b brain claims [--at <instant>] [--history] [--replaced <id>] [--contests <id>] [--rebuild] [--vault <path>] [--json]\n" +
+ "Query the claim-graph projection over existing superseded_by / contradicts /\n" +
+ "valid_from / valid_until relations. Default is current truth; --at <ISO|YYYY-MM-DD>\n" +
+ "gives truth at that instant; --history lists every claim (tombstoned included);\n" +
+ "--replaced <id> follows the supersede chain to the live tip; --contests <id>\n" +
+ "lists contesting claims; --rebuild rebuilds and persists Brain/claim-graph.json.\n",
+ decision:
+ "usage: o2b brain decision <record|outcome|rate|show|list|compare|similar|history|recall> [...] [--vault <path>] [--json]\n" +
+ "Decision-record note family under Brain/decisions/. record --title <t> --chosen <c>\n" +
+ "--assumption <a> --review-date <YYYY-MM-DD> [--premortem <p>] [--notes <n>]\n" +
+ "[--rating <1-5>] [--rationale <r>] captures a type: decision note and opens one review\n" +
+ "obligation idempotently; outcome <slug> --outcome <text> backfills the hindsight\n" +
+ "outcome; rate <slug> --rating <1-5> [--rationale <r>] sets a rating (logged); show\n" +
+ "<slug> and list [--rated] read stored decisions (--rated sorts by rating); compare\n" +
+ "<slug...> reads decisions side by side; similar --title <t> [--chosen <c>] surfaces\n" +
+ "historically similar decisions with their recorded outcomes; history [--subject <id>]\n" +
+ "[--cursor <c>] [--limit <n>] pages decision-change receipts (before/after, confidence\n" +
+ "delta, reason code) appended alongside the truth ledger; recall --prompt <text>\n" +
+ "[--turn <n>] [--count <n>] [--last-turn <n>] [--surfaced-ids <id> ...]\n" +
+ "deterministically resurfaces a rated decision matching the prompt when\n" +
+ "decision_recall.max_per_session is configured (byte-identical when unset); the\n" +
+ "count/last-turn/surfaced-ids flags thread the per-session cap and spacing state.\n",
+ tension:
+ "usage: o2b brain tension <detect|list|show|confirm|dismiss|resolve> [...] [--vault <path>] [--json]\n" +
+ "Triage persisted contradictions under Brain/tensions/. detect [--jaccard <n>] scans\n" +
+ "the configured note corpus (notes.read_paths) and persists a\n" +
+ "tension note (open state) with a dedup key (subject pair + stance signature) so\n" +
+ "re-detection updates the existing note instead of duplicating. list [--unresolved]\n" +
+ "and show <slug> read; confirm <slug> moves open -> confirmed; dismiss <slug>\n" +
+ "[--reason <r>] and resolve <slug> [--reason <r>] close it (open|confirmed ->\n" +
+ "dismissed|resolved). Invalid transitions are rejected. A context pack that injects\n" +
+ "a subject note of an unresolved (open|confirmed) tension emits a warning; dismissed\n" +
+ "and resolved tensions warn about nothing.\n",
digest:
"usage: o2b brain digest [--vault <path>] [--since <ISO>] [--until <ISO>] [--json] [--silent-if-empty]\n" +
"Renders the 24-hour change digest. Empty + --silent-if-empty exits 2.\n",
@@ -408,6 +458,12 @@ export const VERB_HELP: Record<string, string> = {
"Dry-run only. Previews deterministic typed preference-edge backfill\n" +
"proposals, currently the inverse superseded_by edge when an active\n" +
"preference supersedes a retired preference that lacks the pointer.\n",
+ "authored-at-backfill":
+ "usage: o2b brain authored-at-backfill [--apply] [--vault <path>] [--json]\n" +
+ "Dry-run by default. Stamps the additive authored_at frontmatter field\n" +
+ "onto session-imported signals that preserved a transcript turn instant\n" +
+ "(valid_from/recorded_at) but predate the field. Idempotent, and never\n" +
+ "re-embeds - it only edits frontmatter. Pass --apply to write.\n",
codec:
"usage: o2b brain codec --compress | --expand [--in <file>]\n" +
"Run the deterministic, lossless session codec over stdin (or --in <file>)\n" +
@@ -720,8 +776,10 @@ export const VERB_HELP: Record<string, string> = {
" --workday-start HH:MM --workday-end HH:MM clip focus blocks to a daily window\n" +
" [--json]\n",
"session-grep":
- "usage: o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--vault <path>] [--json]\n" +
- "Search imported session recall raw turns and summary nodes.\n",
+ "usage: o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--since <t>] [--before <t>] [--vault <path>] [--json]\n" +
+ "Search imported session recall raw turns and summary nodes. --since and\n" +
+ "--before bound results to a time window (ISO date/datetime, today/\n" +
+ "yesterday/last week/last month, or <n>h/<n>d/<n>w); --before is inclusive.\n",
"session-describe":
"usage: o2b brain session-describe --session-id <id> [--vault <path>] [--json]\n" +
"Describe counts and summary depths for an imported session recall DAG.\n",
diff --git a/src/cli/brain/verbs/authored-at-backfill.ts b/src/cli/brain/verbs/authored-at-backfill.ts
new file mode 100644
index 00000000..596e7be6
--- /dev/null
+++ b/src/cli/brain/verbs/authored-at-backfill.ts
@@ -0,0 +1,69 @@
+import { planAuthoredAtBackfill } from "../../../core/brain/authored-at-backfill.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { resolveAgentName } from "../../../core/config.ts";
+import { brainVerbContext, info, ok, okJson, parse } from "../helpers.ts";
+
+/**
+ * `o2b brain authored-at-backfill` (conversation chronology, S1).
+ *
+ * Materialise the additive `authored_at` frontmatter field on
+ * session-imported signals that preserved a transcript turn instant but
+ * predate the field. Dry-run by DEFAULT (report only); `--apply` writes.
+ * Idempotent, and never re-embeds - it only edits frontmatter.
+ */
+export async function cmdBrainAuthoredAtBackfill(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ apply: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+ const apply = flags["apply"] === true;
+
+ const result = planAuthoredAtBackfill(vault, { apply });
+
+ if (apply && result.updated > 0) {
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(new Date()),
+ eventType: BRAIN_LOG_EVENT_KIND.authoredAtBackfill,
+ body: {
+ agent: resolveAgentName(config),
+ updated: String(result.updated),
+ scanned: String(result.scanned),
+ },
+ });
+ } catch (err) {
+ process.stderr.write(
+ `warning: append authored-at-backfill log failed: ${(err as Error).message}\n`,
+ );
+ }
+ }
+
+ if (flags["json"]) {
+ okJson({
+ dry_run: !apply,
+ scanned: result.scanned,
+ updated: result.updated,
+ candidates: result.candidates.map((c) => ({ path: c.path, authored_at: c.authoredAt })),
+ });
+ return 0;
+ }
+
+ if (apply) {
+ ok(
+ `authored-at-backfill: updated ${result.updated} of ${result.candidates.length} candidate(s)`,
+ );
+ } else {
+ ok(
+ `authored-at-backfill dry-run: ${result.candidates.length} candidate(s) (scanned ${result.scanned})`,
+ );
+ info("re-run with --apply to write the authored_at field");
+ }
+ for (const c of result.candidates) {
+ info(` ${c.path}: authored_at=${c.authoredAt}`);
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/claims.ts b/src/cli/brain/verbs/claims.ts
new file mode 100644
index 00000000..b9e57364
--- /dev/null
+++ b/src/cli/brain/verbs/claims.ts
@@ -0,0 +1,137 @@
+/**
+ * `o2b brain claims` - claim-graph query surface (Belief lifecycle
+ * suite, A3, t_6916369f).
+ *
+ * Reads the persisted `Brain/claim-graph.json` projection (building an
+ * in-memory one when none exists) and answers point-in-time and history
+ * questions. Current-truth is the default; history is opt-in.
+ *
+ * o2b brain claims current truth (default)
+ * o2b brain claims --at <instant> truth at instant T
+ * o2b brain claims --history every claim, tombstoned included
+ * o2b brain claims --replaced <id> the claim that replaced X
+ * o2b brain claims --contests <id> claims that contest X
+ * o2b brain claims --rebuild rebuild + persist the projection
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ allClaims,
+ buildClaimGraph,
+ currentTruth,
+ loadClaimGraph,
+ rebuildClaimGraph,
+ truthAt,
+ whatContests,
+ whatReplaced,
+ type ClaimGraph,
+ type ClaimNode,
+} from "../../../core/brain/claim-graph.ts";
+import { normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE_ERROR_EXIT = 2;
+const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+function usageError(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return USAGE_ERROR_EXIT;
+}
+
+function renderNode(n: ClaimNode): Record<string, unknown> {
+ return {
+ id: n.id,
+ path: n.path,
+ topic: n.topic,
+ principle: n.principle,
+ valid_from: n.valid_from,
+ valid_until: n.valid_until,
+ superseded_by: n.superseded_by,
+ contradicts: n.contradicts,
+ provenance: n.provenance,
+ tombstoned: n.tombstoned,
+ };
+}
+
+/** Load the persisted projection, or build a fresh in-memory one. */
+function resolveGraph(vault: string): ClaimGraph {
+ return loadClaimGraph(vault) ?? buildClaimGraph(vault);
+}
+
+export async function cmdBrainClaims(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ at: { type: "string" },
+ history: { type: "boolean" },
+ replaced: { type: "string" },
+ contests: { type: "string" },
+ rebuild: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const wantsJson = flags["json"] === true;
+
+ try {
+ if (flags["rebuild"]) {
+ const graph = rebuildClaimGraph(vault);
+ if (wantsJson) {
+ okJson({ rebuilt: true, node_count: graph.node_count, truncated: graph.truncated });
+ } else {
+ ok(
+ `rebuilt claim graph: ${graph.node_count} claims${graph.truncated ? " (truncated)" : ""}`,
+ );
+ }
+ return 0;
+ }
+
+ const replaced = normalizeFlagString(flags["replaced"]);
+ if (replaced) {
+ const tip = whatReplaced(resolveGraph(vault), replaced);
+ if (wantsJson) {
+ okJson({ replaced, tip: tip ? renderNode(tip) : null });
+ } else {
+ ok(tip ? `${replaced} -> ${tip.id}` : `no replacement found for ${replaced}`);
+ }
+ return 0;
+ }
+
+ const contests = normalizeFlagString(flags["contests"]);
+ if (contests) {
+ const rows = whatContests(resolveGraph(vault), contests);
+ if (wantsJson) {
+ okJson({ contests, claims: rows.map(renderNode) });
+ } else {
+ ok(`${rows.length} claim(s) contest ${contests}`);
+ }
+ return 0;
+ }
+
+ const at = normalizeFlagString(flags["at"]);
+ let rows: ClaimNode[];
+ if (at) {
+ const iso = DATE_ONLY_RE.test(at) ? `${at}T00:00:00Z` : at;
+ const probe = Date.parse(iso);
+ if (Number.isNaN(probe)) {
+ return usageError(`brain claims --at must be an ISO instant or YYYY-MM-DD date; got ${at}`);
+ }
+ rows = truthAt(resolveGraph(vault), probe);
+ } else if (flags["history"]) {
+ rows = allClaims(resolveGraph(vault));
+ } else {
+ rows = currentTruth(resolveGraph(vault));
+ }
+
+ if (wantsJson) {
+ okJson({ count: rows.length, claims: rows.map(renderNode) });
+ } else {
+ ok(`${rows.length} claim(s)`);
+ for (const n of rows) ok(` ${n.id}: ${n.principle}`);
+ }
+ return 0;
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? String(exc)}\n`);
+ return 1;
+ }
+}
diff --git a/src/cli/brain/verbs/decision.ts b/src/cli/brain/verbs/decision.ts
new file mode 100644
index 00000000..6f9ecb25
--- /dev/null
+++ b/src/cli/brain/verbs/decision.ts
@@ -0,0 +1,385 @@
+/**
+ * `o2b brain decision <action>` - decision-record note family CLI
+ * (Belief lifecycle suite, Track B anchor, t_ac03214d).
+ *
+ * Actions:
+ * - `record --title <t> --chosen <c> --assumption <a> --review-date <d>
+ * [--premortem <p>] [--notes <n>]`
+ * - `outcome <slug> --outcome <text>` backfill the hindsight outcome
+ * - `show <slug>`
+ * - `list`
+ * - `similar --title <t> [--chosen <c>]` historically similar decisions
+ * - `recall --prompt <t> [--turn <n>] [--count <n>] [--last-turn <n>]
+ * [--surfaced-ids <id> ...]` resurface a rated decision,
+ * threading the per-session cap and spacing state
+ *
+ * CLI mirror of the `brain_decision` MCP tool; both delegate to the core
+ * decision module so the on-disk shape cannot drift.
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ backfillOutcome,
+ compareDecisions,
+ findSimilarDecisions,
+ listDecisions,
+ listRatedDecisions,
+ recordDecision,
+ showDecision,
+ updateRating,
+} from "../../../core/brain/decisions/record.ts";
+import type { BrainCommitmentTier } from "../../../core/brain/types.ts";
+import { queryDecisionChangeHistory } from "../../../core/brain/decisions/receipts.ts";
+import { recallRatedDecisions } from "../../../core/brain/decisions/recall.ts";
+import { normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE_ERROR_EXIT = 2;
+
+function usageError(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return USAGE_ERROR_EXIT;
+}
+
+export async function cmdBrainDecision(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ agent: { type: "string" },
+ title: { type: "string" },
+ chosen: { type: "string" },
+ assumption: { type: "string" },
+ "review-date": { type: "string" },
+ premortem: { type: "string" },
+ notes: { type: "string" },
+ outcome: { type: "string" },
+ rating: { type: "string" },
+ rationale: { type: "string" },
+ commitment: { type: "string" },
+ rated: { type: "boolean" },
+ subject: { type: "string" },
+ cursor: { type: "string" },
+ limit: { type: "string" },
+ prompt: { type: "string" },
+ turn: { type: "string" },
+ count: { type: "string" },
+ "last-turn": { type: "string" },
+ "surfaced-ids": { type: "string-array" },
+ json: { type: "boolean" },
+ });
+
+ const action = positional[0];
+ if (action === undefined) {
+ return usageError(
+ "brain decision requires an action: record | outcome | rate | show | list | compare | similar | history | recall",
+ );
+ }
+
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+ const wantsJson = flags["json"] === true;
+
+ try {
+ switch (action) {
+ case "record": {
+ const title = normalizeFlagString(flags["title"]);
+ const chosen = normalizeFlagString(flags["chosen"]);
+ const assumption = normalizeFlagString(flags["assumption"]);
+ const reviewDate = normalizeFlagString(flags["review-date"]);
+ if (!title || !chosen || !assumption || !reviewDate) {
+ return usageError(
+ "brain decision record requires --title, --chosen, --assumption, --review-date",
+ );
+ }
+ const premortem = normalizeFlagString(flags["premortem"]);
+ const notes = normalizeFlagString(flags["notes"]);
+ const ratingRaw = normalizeFlagString(flags["rating"]);
+ const rating = ratingRaw === null ? undefined : Number(ratingRaw);
+ if (rating !== undefined && !Number.isFinite(rating)) {
+ return usageError("brain decision record --rating must be a number");
+ }
+ const rationale = normalizeFlagString(flags["rationale"]);
+ const commitment = normalizeFlagString(flags["commitment"]);
+ const res = recordDecision(vault, {
+ title,
+ chosen,
+ assumption,
+ reviewDate,
+ ...(premortem ? { premortem } : {}),
+ ...(notes ? { notes } : {}),
+ ...(rating !== undefined ? { rating } : {}),
+ ...(rationale ? { rationale } : {}),
+ ...(commitment ? { commitment: commitment as BrainCommitmentTier } : {}),
+ agent: explicitAgent ?? "",
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({
+ id: res.record.id,
+ slug: res.record.slug,
+ review_date: res.record.reviewDate,
+ review_obligation: res.reviewObligationSlug,
+ obligation_created: res.obligationCreated,
+ });
+ } else {
+ ok(`recorded ${res.record.id} (review obligation: ${res.reviewObligationSlug})`);
+ }
+ return 0;
+ }
+ case "outcome": {
+ const slug = positional[1];
+ const outcome = normalizeFlagString(flags["outcome"]);
+ if (slug === undefined || !outcome) {
+ return usageError("brain decision outcome requires <slug> --outcome <text>");
+ }
+ const res = backfillOutcome(vault, {
+ slug,
+ outcome,
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({ id: res.id, slug: res.slug, outcome: res.outcome });
+ } else {
+ ok(`outcome recorded for ${res.id}`);
+ }
+ return 0;
+ }
+ case "rate": {
+ const slug = positional[1];
+ const ratingRaw = normalizeFlagString(flags["rating"]);
+ if (slug === undefined || ratingRaw === null) {
+ return usageError("brain decision rate requires <slug> --rating <n>");
+ }
+ const rating = Number(ratingRaw);
+ if (!Number.isFinite(rating)) {
+ return usageError("brain decision rate --rating must be a number");
+ }
+ const rationale = normalizeFlagString(flags["rationale"]);
+ const res = updateRating(vault, {
+ slug,
+ rating,
+ ...(rationale ? { rationale } : {}),
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({ id: res.id, slug: res.slug, rating: res.rating, rationale: res.rationale });
+ } else {
+ ok(`rated ${res.id}: ${res.rating}`);
+ }
+ return 0;
+ }
+ case "compare": {
+ const slugs = positional.slice(1);
+ if (slugs.length === 0) {
+ return usageError("brain decision compare requires one or more slugs");
+ }
+ const rows = compareDecisions(vault, slugs);
+ if (wantsJson) {
+ okJson({
+ decisions: rows.map((d) => ({
+ id: d.id,
+ slug: d.slug,
+ title: d.title,
+ chosen: d.chosen,
+ rating: d.rating,
+ rationale: d.rationale,
+ outcome: d.outcome,
+ })),
+ });
+ } else if (rows.length === 0) {
+ ok("no matching decisions");
+ } else {
+ for (const d of rows) {
+ ok(`${d.id}: ${d.chosen} (rating ${d.rating ?? "none"})`);
+ }
+ }
+ return 0;
+ }
+ case "show": {
+ const slug = positional[1];
+ if (slug === undefined) return usageError("brain decision show requires a slug");
+ const res = showDecision(vault, slug);
+ if (res === null) {
+ process.stderr.write(`error: no decision: ${slug}\n`);
+ return 1;
+ }
+ if (wantsJson) {
+ okJson({
+ id: res.id,
+ slug: res.slug,
+ title: res.title,
+ chosen: res.chosen,
+ assumption: res.assumption,
+ review_date: res.reviewDate,
+ outcome: res.outcome,
+ premortem: res.premortem,
+ rating: res.rating,
+ rationale: res.rationale,
+ // Commitment tier (B3): emitted only when set so an unset
+ // decision stays byte-identical to a pre-B3 response.
+ ...(res.commitment !== null ? { commitment: res.commitment } : {}),
+ });
+ } else {
+ ok(`${res.id}: chose "${res.chosen}" (review ${res.reviewDate ?? "none"})`);
+ }
+ return 0;
+ }
+ case "list": {
+ const ratedOnly = flags["rated"] === true;
+ const all = ratedOnly ? listRatedDecisions(vault) : listDecisions(vault);
+ if (wantsJson) {
+ okJson({
+ decisions: all.map((d) => ({
+ id: d.id,
+ slug: d.slug,
+ title: d.title,
+ chosen: d.chosen,
+ rating: d.rating,
+ review_date: d.reviewDate,
+ outcome: d.outcome,
+ ...(d.commitment !== null ? { commitment: d.commitment } : {}),
+ })),
+ });
+ } else if (all.length === 0) {
+ ok(ratedOnly ? "no rated decisions" : "no decisions");
+ } else {
+ for (const d of all) {
+ const rt = d.rating !== null ? ` [${d.rating}]` : "";
+ ok(`${d.id}${rt}: ${d.chosen}${d.outcome ? ` -> ${d.outcome}` : ""}`);
+ }
+ }
+ return 0;
+ }
+ case "similar": {
+ const title = normalizeFlagString(flags["title"]);
+ if (!title) return usageError("brain decision similar requires --title <text>");
+ const chosen = normalizeFlagString(flags["chosen"]);
+ const hits = findSimilarDecisions(vault, {
+ title,
+ ...(chosen ? { chosen } : {}),
+ });
+ if (wantsJson) {
+ okJson({
+ similar: hits.map((h) => ({
+ id: h.id,
+ slug: h.slug,
+ title: h.title,
+ outcome: h.outcome,
+ jaccard: h.jaccard,
+ })),
+ });
+ } else if (hits.length === 0) {
+ ok("no similar decisions");
+ } else {
+ for (const h of hits) {
+ ok(`${h.id} (${h.jaccard.toFixed(2)})${h.outcome ? ` -> ${h.outcome}` : ""}`);
+ }
+ }
+ return 0;
+ }
+ case "history": {
+ const subject = normalizeFlagString(flags["subject"]);
+ const cursor = normalizeFlagString(flags["cursor"]);
+ const limitRaw = normalizeFlagString(flags["limit"]);
+ const limit = limitRaw === null ? undefined : Number(limitRaw);
+ if (limit !== undefined && (!Number.isInteger(limit) || limit <= 0)) {
+ return usageError("brain decision history --limit must be a positive integer");
+ }
+ const page = queryDecisionChangeHistory(vault, {
+ ...(subject ? { subject } : {}),
+ ...(cursor ? { cursor } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ if (wantsJson) {
+ okJson({
+ total: page.total,
+ next_cursor: page.nextCursor,
+ receipts: page.receipts.map((r) => ({
+ ts: r.ts,
+ subject: r.subject,
+ before: r.before,
+ after: r.after,
+ confidence_delta: r.confidence_delta,
+ reason_code: r.reason_code,
+ actor: r.actor,
+ idempotency_key: r.idempotency_key,
+ })),
+ });
+ } else if (page.receipts.length === 0) {
+ ok("no decision-change receipts");
+ } else {
+ for (const r of page.receipts) {
+ ok(`${r.ts} ${r.subject}: ${r.before} -> ${r.after} (${r.reason_code})`);
+ }
+ if (page.nextCursor) ok(`-- more: --cursor ${page.nextCursor}`);
+ }
+ return 0;
+ }
+ case "recall": {
+ const prompt = normalizeFlagString(flags["prompt"]);
+ if (!prompt) return usageError("brain decision recall requires --prompt <text>");
+ const turnRaw = normalizeFlagString(flags["turn"]);
+ const turn = turnRaw === null ? 0 : Number(turnRaw);
+ if (!Number.isInteger(turn) || turn < 0) {
+ return usageError("brain decision recall --turn must be a non-negative integer");
+ }
+ // Governor state passthrough (B5): let the CLI exercise the same
+ // per-session cap and spacing the MCP recall action accepts.
+ const countRaw = normalizeFlagString(flags["count"]);
+ const count = countRaw === null ? 0 : Number(countRaw);
+ if (!Number.isInteger(count) || count < 0) {
+ return usageError("brain decision recall --count must be a non-negative integer");
+ }
+ const lastTurnRaw = normalizeFlagString(flags["last-turn"]);
+ let lastTurn: number | null = null;
+ if (lastTurnRaw !== null) {
+ lastTurn = Number(lastTurnRaw);
+ if (!Number.isInteger(lastTurn) || lastTurn < 0) {
+ return usageError("brain decision recall --last-turn must be a non-negative integer");
+ }
+ }
+ const surfacedIds = Array.isArray(flags["surfaced-ids"])
+ ? (flags["surfaced-ids"] as string[])
+ : [];
+ const res = recallRatedDecisions(vault, {
+ prompt,
+ turn,
+ state: {
+ surfacedIds,
+ lastTurn,
+ count: count || surfacedIds.length,
+ },
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({
+ enabled: res.enabled,
+ surfaced: res.surfaced
+ ? { id: res.surfaced.id, slug: res.surfaced.slug, rating: res.surfaced.rating }
+ : null,
+ text: res.text,
+ state: {
+ surfaced_ids: res.state.surfacedIds,
+ last_turn: res.state.lastTurn,
+ count: res.state.count,
+ },
+ });
+ } else if (!res.enabled) {
+ ok("decision recall not configured");
+ } else if (res.surfaced === null) {
+ ok("no decision recalled");
+ } else {
+ ok(res.text);
+ }
+ return 0;
+ }
+ default:
+ return usageError(`unknown decision action: ${action}`);
+ }
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? String(exc)}\n`);
+ return 1;
+ }
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 27f2d7f5..310ba671 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -1,6 +1,10 @@
export { cmdBrainInit } from "./init.ts";
export { cmdBrainFeedback } from "./feedback.ts";
export { cmdBrainNote } from "./note.ts";
+export { cmdBrainLifecycle } from "./lifecycle.ts";
+export { cmdBrainClaims } from "./claims.ts";
+export { cmdBrainDecision } from "./decision.ts";
+export { cmdBrainTension } from "./tension.ts";
export { cmdBrainDream } from "./dream.ts";
export { cmdBrainApplyEvidence } from "./apply-evidence.ts";
export { cmdBrainDigest } from "./digest.ts";
@@ -47,6 +51,7 @@ export { cmdBrainBankExport } from "./bank-export.ts";
export { cmdBrainBankImport } from "./bank-import.ts";
export { cmdBrainBacklinks } from "./backlinks.ts";
export { cmdBrainSemanticsBackfill } from "./semantics-backfill.ts";
+export { cmdBrainAuthoredAtBackfill } from "./authored-at-backfill.ts";
export { cmdBrainMcpLandscape } from "./mcp-landscape.ts";
export { cmdBrainMerge } from "./merge.ts";
export { cmdBrainExplorer } from "./explorer.ts";
diff --git a/src/cli/brain/verbs/lifecycle.ts b/src/cli/brain/verbs/lifecycle.ts
new file mode 100644
index 00000000..6cb26b5c
--- /dev/null
+++ b/src/cli/brain/verbs/lifecycle.ts
@@ -0,0 +1,213 @@
+/**
+ * `o2b brain lifecycle <action>` - cross-type tombstone + supersede
+ * lifecycle CLI (Belief lifecycle suite, Track A anchor, t_7d5a3589).
+ *
+ * Actions:
+ * - `tombstone <path> --reason <r> [--superseded-by <id>]`
+ * - `supersede <predecessor> <successor> [--reason <r>]`
+ * - `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
+ *
+ * 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 { curatorSlices } from "../../../core/brain/lifecycle/curator.ts";
+import { temporalReplace } from "../../../core/brain/lifecycle/temporal-replace.ts";
+import {
+ resolveChainTipInVault,
+ supersede,
+ tombstone,
+} from "../../../core/brain/lifecycle/tombstone.ts";
+import { normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE_ERROR_EXIT = 2;
+
+function usageError(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return USAGE_ERROR_EXIT;
+}
+
+/** Project curator slice rows into the CLI's snake_cased JSON shape. */
+function renderCuratorRows(
+ rows: ReadonlyArray<{
+ key: string;
+ reuse: { used: number; ignored: number; contradicted: number };
+ }>,
+): unknown[] {
+ return rows.map((r) => ({
+ key: r.key,
+ used: r.reuse.used,
+ ignored: r.reuse.ignored,
+ contradicted: r.reuse.contradicted,
+ }));
+}
+
+export async function cmdBrainLifecycle(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ agent: { type: "string" },
+ reason: { type: "string" },
+ "superseded-by": { type: "string" },
+ "high-use-min": { type: "string" },
+ at: { type: "string" },
+ json: { type: "boolean" },
+ });
+
+ const action = positional[0];
+ if (action === undefined) {
+ return usageError(
+ "brain lifecycle requires an action: tombstone | supersede | temporal-replace | tip | curator",
+ );
+ }
+
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+ const wantsJson = flags["json"] === true;
+
+ try {
+ switch (action) {
+ case "tombstone": {
+ const path = positional[1];
+ if (path === undefined) {
+ return usageError("brain lifecycle tombstone requires a note path");
+ }
+ const reason = normalizeFlagString(flags["reason"]);
+ if (!reason) {
+ return usageError("brain lifecycle tombstone requires --reason <text>");
+ }
+ const supersededBy = normalizeFlagString(flags["superseded-by"]);
+ const res = tombstone({
+ vault,
+ path,
+ reason,
+ ...(supersededBy ? { supersededBy } : {}),
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({
+ changed: res.changed,
+ path: res.path,
+ tombstoned: res.state.tombstoned,
+ superseded_by: res.state.supersededBy,
+ });
+ } else {
+ ok(res.changed ? `tombstoned ${res.path}` : `already tombstoned: ${res.path}`);
+ }
+ return 0;
+ }
+ case "supersede": {
+ const predecessor = positional[1];
+ const successor = positional[2];
+ if (predecessor === undefined || successor === undefined) {
+ return usageError("brain lifecycle supersede requires <predecessor> <successor>");
+ }
+ const reason = normalizeFlagString(flags["reason"]);
+ const res = supersede({
+ vault,
+ predecessor,
+ successor,
+ ...(reason ? { reason } : {}),
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({
+ changed: res.changed,
+ path: res.path,
+ superseded_by: res.state.supersededBy,
+ });
+ } else {
+ ok(
+ res.changed
+ ? `superseded ${res.path} -> ${res.state.supersededBy}`
+ : `already tombstoned: ${res.path}`,
+ );
+ }
+ return 0;
+ }
+ case "temporal-replace": {
+ const predecessor = positional[1];
+ const successor = positional[2];
+ if (predecessor === undefined || successor === undefined) {
+ return usageError("brain lifecycle temporal-replace requires <predecessor> <successor>");
+ }
+ const at = normalizeFlagString(flags["at"]);
+ if (!at) {
+ return usageError(
+ "brain lifecycle temporal-replace requires --at <ISO-8601 instant or YYYY-MM-DD>",
+ );
+ }
+ const res = temporalReplace({
+ vault,
+ predecessor,
+ successor,
+ at,
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({
+ at: res.at,
+ predecessor: res.predecessor,
+ successor: res.successor,
+ agent: res.agent,
+ });
+ } else {
+ ok(`temporal-replace ${res.predecessor} -> ${res.successor} at ${res.at}`);
+ }
+ return 0;
+ }
+ case "tip": {
+ const id = positional[1];
+ if (id === undefined) {
+ return usageError("brain lifecycle tip requires an id");
+ }
+ const res = resolveChainTipInVault(vault, id);
+ if (wantsJson) {
+ okJson({
+ tip: res.tip,
+ steps: res.steps,
+ cycle: res.cycle,
+ resolved_all: res.resolvedAll,
+ });
+ } else {
+ ok(`tip: ${res.tip} (${res.steps} hop${res.steps === 1 ? "" : "s"})`);
+ }
+ return 0;
+ }
+ case "curator": {
+ const highUseMinRaw = normalizeFlagString(flags["high-use-min"]);
+ const highUseMin = highUseMinRaw === null ? undefined : Number(highUseMinRaw);
+ if (highUseMin !== undefined && (!Number.isFinite(highUseMin) || highUseMin < 0)) {
+ return usageError("brain lifecycle curator --high-use-min must be a non-negative number");
+ }
+ const slices = curatorSlices(vault, highUseMin !== undefined ? { highUseMin } : {});
+ if (wantsJson) {
+ okJson({
+ injected_never_used: renderCuratorRows(slices.injectedNeverUsed),
+ contradicted: renderCuratorRows(slices.contradicted),
+ high_used: renderCuratorRows(slices.highUsed),
+ });
+ } else {
+ ok(
+ `injected-never-used: ${slices.injectedNeverUsed.length}, ` +
+ `contradicted: ${slices.contradicted.length}, ` +
+ `high-used: ${slices.highUsed.length}`,
+ );
+ }
+ return 0;
+ }
+ default:
+ return usageError(`unknown lifecycle action: ${action}`);
+ }
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? String(exc)}\n`);
+ return 1;
+ }
+}
diff --git a/src/cli/brain/verbs/session-recall.ts b/src/cli/brain/verbs/session-recall.ts
index b9ace2fb..dfad4842 100644
--- a/src/cli/brain/verbs/session-recall.ts
+++ b/src/cli/brain/verbs/session-recall.ts
@@ -3,6 +3,8 @@ 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 { CliError, brainVerbContext, parse } from "../helpers.ts";
export async function cmdBrainSessionGrep(argv: string[]): Promise<number> {
@@ -13,8 +15,14 @@ export async function cmdBrainSessionGrep(argv: string[]): Promise<number> {
"session-id": { type: "string" },
limit: { type: "string" },
"snippet-chars": { type: "string" },
+ since: { type: "string" },
+ before: { type: "string" },
});
const vault = brainVerbContext(flags).vault;
+ // Conversation-chronology bounds (S1): --since / --before parse through
+ // the shared time-range grammar; --before maps onto the inclusive upper
+ // edge. Absent bounds leave the search unbounded (byte-identical).
+ const bounds = sessionGrepBounds(stringOptional(flags["since"]), stringOptional(flags["before"]));
const result = searchSessionRecall(vault, {
query: requiredString(flags["query"], "brain session-grep", "--query"),
...(stringOptional(flags["session-id"]) !== undefined
@@ -35,11 +43,32 @@ export async function cmdBrainSessionGrep(argv: string[]): Promise<number> {
),
}
: {}),
+ ...(bounds.sinceMs !== null ? { sinceMs: bounds.sinceMs } : {}),
+ ...(bounds.untilMs !== null ? { untilMs: bounds.untilMs } : {}),
});
writeOutput(result, flags["json"] === true);
return 0;
}
+function sessionGrepBounds(
+ 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 CliError(exc.message);
+ throw exc;
+ }
+}
+
export async function cmdBrainSessionDescribe(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
vault: { type: "string" },
diff --git a/src/cli/brain/verbs/tension.ts b/src/cli/brain/verbs/tension.ts
new file mode 100644
index 00000000..6fba3a44
--- /dev/null
+++ b/src/cli/brain/verbs/tension.ts
@@ -0,0 +1,183 @@
+/**
+ * `o2b brain tension <action>` - tension-object lifecycle CLI (Belief
+ * lifecycle suite, S2, t_0e3f2bee).
+ *
+ * Actions:
+ * - `detect [--jaccard <n>] [--path <p>]` scan the note corpus, persist tensions
+ * - `list [--unresolved]` list persisted tensions
+ * - `show <slug>` read one tension
+ * - `confirm <slug> [--reason <r>]` open -> confirmed
+ * - `dismiss <slug> [--reason <r>]` open|confirmed -> dismissed
+ * - `resolve <slug> [--reason <r>]` open|confirmed -> resolved
+ *
+ * CLI mirror of the `brain_tension` MCP tool; both delegate to the core
+ * tensions module so the on-disk shape cannot drift. `detect` is the
+ * operator trigger that runs the contradiction detector over the
+ * configured note corpus (`notes.read_paths`) and persists findings; the
+ * other actions triage what detection found.
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ confirmTension,
+ detectTensionsInVault,
+ dismissTension,
+ listTensions,
+ listUnresolvedTensions,
+ resolveTension,
+ showTension,
+ type TensionRecord,
+} from "../../../core/brain/tensions.ts";
+import { normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE_ERROR_EXIT = 2;
+
+function usageError(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return USAGE_ERROR_EXIT;
+}
+
+/** Project a tension record into the CLI's snake_cased JSON shape. */
+function renderRow(t: TensionRecord): Record<string, unknown> {
+ return {
+ id: t.id,
+ slug: t.slug,
+ status: t.status,
+ subject_a: t.subjectA,
+ subject_b: t.subjectB,
+ stance_a: t.stanceA,
+ stance_b: t.stanceB,
+ detected_count: t.detectedCount,
+ resolution_reason: t.resolutionReason,
+ };
+}
+
+export async function cmdBrainTension(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ agent: { type: "string" },
+ reason: { type: "string" },
+ jaccard: { type: "string" },
+ unresolved: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+
+ const action = positional[0];
+ if (action === undefined) {
+ return usageError(
+ "brain tension requires an action: detect | list | show | confirm | dismiss | resolve",
+ );
+ }
+
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+ const wantsJson = flags["json"] === true;
+
+ const transitionArgs = () => ({
+ ...(normalizeFlagString(flags["reason"])
+ ? { reason: normalizeFlagString(flags["reason"])! }
+ : {}),
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+
+ try {
+ switch (action) {
+ case "detect":
+ case "scan": {
+ const jaccardRaw = normalizeFlagString(flags["jaccard"]);
+ let jaccard: number | undefined;
+ if (jaccardRaw !== null) {
+ const parsed = Number(jaccardRaw);
+ if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 1) {
+ return usageError("--jaccard must be a number in (0, 1]");
+ }
+ jaccard = parsed;
+ }
+ const res = detectTensionsInVault(vault, {
+ ...(jaccard !== undefined ? { jaccard } : {}),
+ ...(explicitAgent ? { agent: explicitAgent } : {}),
+ configPath: config,
+ });
+ if (wantsJson) {
+ okJson({
+ created: res.created,
+ updated: res.updated,
+ scanned_files: res.scannedFiles,
+ tensions: res.records.map(renderRow),
+ });
+ } else {
+ ok(
+ `scanned ${res.scannedFiles} note(s): ${res.created} created, ` +
+ `${res.updated} refreshed`,
+ );
+ }
+ return 0;
+ }
+ case "list": {
+ const rows =
+ flags["unresolved"] === true ? listUnresolvedTensions(vault) : listTensions(vault);
+ if (wantsJson) {
+ okJson({ tensions: rows.map(renderRow) });
+ } else if (rows.length === 0) {
+ ok(flags["unresolved"] === true ? "no unresolved tensions" : "no tensions");
+ } else {
+ for (const t of rows) {
+ ok(`${t.id} [${t.status}]: ${t.subjectA} vs ${t.subjectB}`);
+ }
+ }
+ return 0;
+ }
+ case "show": {
+ const slug = positional[1];
+ if (slug === undefined) return usageError("brain tension show requires a slug");
+ const t = showTension(vault, slug);
+ if (t === null) {
+ process.stderr.write(`error: no tension: ${slug}\n`);
+ return 1;
+ }
+ if (wantsJson) {
+ okJson({
+ ...renderRow(t),
+ subject: t.subject,
+ jaccard: t.jaccard,
+ quote_a: t.quoteA,
+ quote_b: t.quoteB,
+ created_at: t.createdAt,
+ detected_at: t.detectedAt,
+ status_changed_at: t.statusChangedAt,
+ });
+ } else {
+ ok(`${t.id} [${t.status}]: ${t.subjectA} (${t.stanceA}) vs ${t.subjectB} (${t.stanceB})`);
+ }
+ return 0;
+ }
+ case "confirm":
+ case "dismiss":
+ case "resolve": {
+ const slug = positional[1];
+ if (slug === undefined) return usageError(`brain tension ${action} requires a slug`);
+ const fn =
+ action === "confirm"
+ ? confirmTension
+ : action === "dismiss"
+ ? dismissTension
+ : resolveTension;
+ const t = fn(vault, slug, transitionArgs());
+ if (wantsJson) {
+ okJson(renderRow(t));
+ } else {
+ ok(`${t.id} -> ${t.status}`);
+ }
+ return 0;
+ }
+ default:
+ return usageError(`unknown tension action: ${action}`);
+ }
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? String(exc)}\n`);
+ return 1;
+ }
+}
diff --git a/src/cli/search.ts b/src/cli/search.ts
index 2b96b43f..2b923b12 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -770,6 +770,9 @@ function jsonForOutcome(o: SearchOutcome): unknown {
end_line: r.endLine,
search_type: r.searchType,
reasons: r.reasons,
+ // Conversation chronology (S1): present only for a note carrying an
+ // authored_at instant, so the shape stays byte-identical otherwise.
+ ...(r.authoredAt !== undefined ? { authored_at: r.authoredAt } : {}),
...(r.origin !== undefined ? { origin: r.origin } : {}),
...(o.evidencePack ? { why_retrieved: r.reasons } : {}),
document_id: r.documentId,
@@ -808,8 +811,14 @@ function renderOutcomeHuman(o: SearchOutcome, verbose: boolean): string {
const score = r.score.toFixed(2);
const originSuffix = r.origin !== undefined ? ` β€’ ${r.origin}` : "";
lines.push(`[${i + 1}] ${r.path} β€’ ${score}${originSuffix}`);
+ // Conversation chronology (S1): show the authoring instant only for a
+ // note that carries one; a note without stays byte-identical.
+ const authoredSuffix =
+ r.authoredAt !== undefined
+ ? ` β€’ authored ${new Date(r.authoredAt * 1000).toISOString()}`
+ : "";
lines.push(
- ` line ${r.startLine}-${r.endLine} β€’ ${r.searchType}` +
+ ` line ${r.startLine}-${r.endLine} β€’ ${r.searchType}${authoredSuffix}` +
(verbose
? ` β€’ kw=${r.keywordScore.toFixed(2)} sem=${r.semanticScore.toFixed(2)} link=${r.linkBoost.toFixed(2)} rec=${r.recencyBoost.toFixed(2)}`
: ""),
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index 7f184288..8a1b4ad7 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -44,6 +44,7 @@ import {
loadGuardrailsConfigSafe,
} from "./policy.ts";
import { parsePreference, parseRetired } from "./preference.ts";
+import { BRAIN_TOMBSTONE_STATUS } from "./types.ts";
import { brainActivePath, brainDirs } from "./paths.ts";
import { isoSecond } from "./time.ts";
import { sortByProvenanceTrust } from "./provenance/trust-order.ts";
@@ -199,7 +200,12 @@ function readActivePreferences(vault: string): BrainPreference[] {
if (!name.endsWith(".md")) continue;
const full = join(dirs.preferences, name);
try {
- out.push(parsePreference(full));
+ const pref = parsePreference(full);
+ // Belief lifecycle suite (t_7d5a3589): a tombstoned (incl.
+ // superseded-non-tip) preference remains on disk for audit but
+ // never appears in the active-preferences digest.
+ if ((pref.status as string) === BRAIN_TOMBSTONE_STATUS) continue;
+ out.push(pref);
} catch {
// Corrupted or status/folder-mismatched file β€” silently omit
// here. `brain_doctor` is the surface that flags it. See the
@@ -323,12 +329,16 @@ function renderQuarantineLine(p: BrainPreference): string {
}
/**
- * Numeric `confidence_value` tail rendered next to the band in the
- * `confidence:` metadata. Empty when the field is `null` (legacy
- * preference written before v0.10.3 β€” the next dream refresh lifts
- * it to a real number).
+ * Tail rendered next to the confidence band in the `confidence:`
+ * metadata. When a commitment tier is set (Belief lifecycle suite, B3),
+ * the tier label is rendered in place of the raw confidence float; the
+ * band itself is unchanged. When no tier is set, the numeric
+ * `confidence_value` is rendered as before (empty when it is `null`, e.g.
+ * a legacy preference written before v0.10.3). Unset commitment therefore
+ * keeps the output byte-identical to today.
*/
function formatConfidenceValueTail(p: BrainPreference): string {
+ if (p.commitment !== undefined) return ` (${p.commitment})`;
if (p.confidence_value === null) return "";
return ` (${p.confidence_value.toFixed(2)})`;
}
diff --git a/src/core/brain/authored-at-backfill.ts b/src/core/brain/authored-at-backfill.ts
new file mode 100644
index 00000000..cabd5256
--- /dev/null
+++ b/src/core/brain/authored-at-backfill.ts
@@ -0,0 +1,152 @@
+/**
+ * Conversation-chronology backfill (S1 / t_347e8224).
+ *
+ * Going forward, `importSession` stamps each session-imported signal with
+ * an `authored_at` frontmatter field carrying the transcript turn instant
+ * (see `sessions/import.ts`). Vaults imported before this feature have the
+ * instant preserved only in the bi-temporal `valid_from` / `recorded_at`
+ * slots. This module materialises the additive `authored_at` field for
+ * those pre-existing signals so the search layer can expose it and break
+ * exact hybrid-score ties toward more recent statements.
+ *
+ * Contract:
+ * - Dry-run by DEFAULT: `planAuthoredAtBackfill` never writes; the
+ * caller opts into mutation with `applyAuthoredAtBackfill`.
+ * - Idempotent: a signal that already carries `authored_at` is skipped,
+ * so a re-run over an already-backfilled vault is a no-op.
+ * - Additive only, NO re-embedding by construction: the operation writes
+ * one frontmatter field and never touches the search index or any
+ * embedding provider.
+ * - Documents without a turn instant are unchanged: a signal that never
+ * preserved `valid_from` / `recorded_at` is not a transcript turn and
+ * is left exactly as-is.
+ *
+ * Only session-sourced brain-signals under `Brain/inbox/` (which contains
+ * `processed/`) are considered - the sole write target of the session
+ * import path.
+ */
+
+import { existsSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
+
+import { BRAIN_INBOX_REL } from "./paths.ts";
+import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
+import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+
+/** One signal that carries a preserved turn instant but no `authored_at`. */
+export interface AuthoredAtBackfillCandidate {
+ /** Absolute path to the signal file. */
+ readonly path: string;
+ /** The `authored_at` value that would be (or was) written. */
+ readonly authoredAt: string;
+}
+
+export interface AuthoredAtBackfillResult {
+ /** Whether the run mutated files (`false` for a dry run). */
+ readonly applied: boolean;
+ /** Signal files scanned (brain-signals under the inbox tree). */
+ readonly scanned: number;
+ /** Signals that qualify for a backfill (missing `authored_at`). */
+ readonly candidates: ReadonlyArray<AuthoredAtBackfillCandidate>;
+ /** Files actually rewritten (0 on a dry run). */
+ readonly updated: number;
+}
+
+export interface AuthoredAtBackfillOptions {
+ /**
+ * When true, rewrite each candidate's frontmatter with the additive
+ * `authored_at` field. Default false β†’ a pure dry run that only reports.
+ */
+ readonly apply?: boolean;
+}
+
+/** Read a trimmed non-empty string frontmatter field, else null. */
+function trimmedField(meta: Record<string, unknown>, key: string): string | null {
+ const raw = meta[key];
+ if (typeof raw !== "string") return null;
+ const trimmed = raw.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+/** Recursively collect `.md` file paths under a directory. */
+function collectMarkdown(dir: string, out: string[]): void {
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const name of entries) {
+ const full = join(dir, name);
+ let st;
+ try {
+ st = statSync(full);
+ } catch {
+ continue;
+ }
+ if (st.isDirectory()) {
+ collectMarkdown(full, out);
+ continue;
+ }
+ if (name.endsWith(".md")) out.push(full);
+ }
+}
+
+/**
+ * Scan the inbox tree for session-imported signals that preserved a turn
+ * instant (`valid_from` / `recorded_at`) but predate the `authored_at`
+ * field. When `apply` is set, materialise the field; otherwise report the
+ * candidates without writing.
+ */
+export function planAuthoredAtBackfill(
+ vault: string,
+ opts: AuthoredAtBackfillOptions = {},
+): AuthoredAtBackfillResult {
+ const apply = opts.apply === true;
+ const inbox = join(vault, BRAIN_INBOX_REL);
+ const candidates: AuthoredAtBackfillCandidate[] = [];
+ let scanned = 0;
+ let updated = 0;
+
+ if (!existsSync(inbox)) {
+ return Object.freeze({ applied: apply, scanned, candidates: Object.freeze([]), updated });
+ }
+
+ const files: string[] = [];
+ collectMarkdown(inbox, files);
+ files.sort();
+
+ for (const path of files) {
+ let meta: Record<string, unknown>;
+ let body: string;
+ try {
+ const [parsedMeta, parsedBody] = parseFrontmatter(path);
+ meta = parsedMeta as Record<string, unknown>;
+ body = parsedBody;
+ } catch {
+ // A file with unreadable/absent frontmatter is not a signal we own.
+ continue;
+ }
+ if (meta["kind"] !== "brain-signal") continue;
+ if (meta["source_type"] !== BRAIN_SIGNAL_SOURCE_TYPE.session) continue;
+ scanned++;
+ // Already backfilled β†’ idempotent skip.
+ if (trimmedField(meta, "authored_at") !== null) continue;
+ // The transcript turn instant: what the import preserved when the turn
+ // carried a usable timestamp. Absent β†’ no turn instant β†’ leave unchanged.
+ const instant = trimmedField(meta, "valid_from") ?? trimmedField(meta, "recorded_at");
+ if (instant === null) continue;
+ candidates.push(Object.freeze({ path, authoredAt: instant }));
+ if (apply) {
+ writeFrontmatterAtomic(path, { ...meta, authored_at: instant }, body, { overwrite: true });
+ updated++;
+ }
+ }
+
+ return Object.freeze({
+ applied: apply,
+ scanned,
+ candidates: Object.freeze(candidates),
+ updated,
+ });
+}
diff --git a/src/core/brain/claim-graph.ts b/src/core/brain/claim-graph.ts
new file mode 100644
index 00000000..ecb39bf9
--- /dev/null
+++ b/src/core/brain/claim-graph.ts
@@ -0,0 +1,290 @@
+/**
+ * Persisted claim-graph projection (Belief lifecycle suite, A3,
+ * t_6916369f).
+ *
+ * A bounded, deterministically-rebuildable JSON projection over the
+ * relations already present in Brain memory frontmatter - `superseded_by`
+ * (supersession chains), `contradicts` (contested claims), the
+ * bi-temporal `valid_from` / `valid_until` fields, and `provenance`. It
+ * is a VIEW, not a store of record: nothing here writes memory files or
+ * touches any extractor. Rebuild reads the current vault and overwrites
+ * the artifact.
+ *
+ * One query surface answers four questions:
+ * - "current truth" -> {@link currentTruth}
+ * - "true at instant T" -> {@link truthAt}
+ * - "what replaced X" -> {@link whatReplaced}
+ * - "what contests X" -> {@link whatContests}
+ * Current-truth is the default; history / retracted content is opt-in via
+ * {@link allClaims}.
+ *
+ * Import direction (design invariant): imports from `types.ts`, the
+ * shared vault/path helpers, and the sibling lifecycle modules
+ * (`tombstone.ts` chain conventions, `temporal-replace.ts` validity
+ * evaluation), never the reverse.
+ */
+
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import type { FrontmatterMap } from "../types.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { parseFrontmatter } from "../vault.ts";
+import { brainDirs, claimGraphPath } from "./paths.ts";
+import { isTombstoned, normalizeChainLink, resolveChainTip } from "./lifecycle/tombstone.ts";
+import { isValidAt } from "./lifecycle/temporal-replace.ts";
+
+// ----- Constants ------------------------------------------------------------
+
+/**
+ * Hard cap on projected nodes. The projection is a bounded artifact by
+ * design: a runaway vault cannot produce an unbounded JSON file. Nodes
+ * are sorted by path before truncation so the retained set is
+ * deterministic.
+ */
+export const CLAIM_GRAPH_MAX_NODES = 5000;
+
+/** Current on-disk schema version of the projection artifact. */
+export const CLAIM_GRAPH_VERSION = 1;
+
+/** Brain memory subdirectories the projection scans (relative to `Brain/`). */
+const SCANNED_SUBDIRS = ["preferences", "retired", "inbox", "inbox/processed", "theses"] as const;
+
+// ----- Errors ---------------------------------------------------------------
+
+export class ClaimGraphError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "ClaimGraphError";
+ }
+}
+
+// ----- Types ----------------------------------------------------------------
+
+export interface ClaimNode {
+ /** Bare basename id (e.g. `pref-foo`). */
+ readonly id: string;
+ /** Vault-relative POSIX path. */
+ readonly path: string;
+ readonly topic: string;
+ readonly principle: string;
+ readonly valid_from: string | null;
+ readonly valid_until: string | null;
+ /** Normalized successor id, or `null` when this node is a chain tip. */
+ readonly superseded_by: string | null;
+ /** Normalized ids this node declares it contradicts. */
+ readonly contradicts: ReadonlyArray<string>;
+ readonly provenance: string | null;
+ readonly tombstoned: boolean;
+}
+
+export interface ClaimGraph {
+ readonly version: number;
+ readonly generated_at: string;
+ readonly node_count: number;
+ /** True when the node cap dropped claims from the projection. */
+ readonly truncated: boolean;
+ readonly nodes: ReadonlyArray<ClaimNode>;
+}
+
+export interface BuildClaimGraphOptions {
+ /** Override the node cap (defaults to {@link CLAIM_GRAPH_MAX_NODES}). */
+ readonly maxNodes?: number;
+ /** Wall clock for `generated_at`. Defaults to `new Date()`. */
+ readonly now?: Date;
+}
+
+// ----- Field extraction -----------------------------------------------------
+
+function scalar(meta: FrontmatterMap, key: string): string | null {
+ const value = meta[key];
+ return typeof value === "string" && value !== "" ? value : null;
+}
+
+function normalizedList(meta: FrontmatterMap, key: string): string[] {
+ const value = meta[key];
+ const raw =
+ typeof value === "string" && value !== ""
+ ? [value]
+ : Array.isArray(value)
+ ? (value as ReadonlyArray<string>)
+ : [];
+ const out: string[] = [];
+ for (const item of raw) {
+ if (typeof item !== "string" || item.trim() === "") continue;
+ out.push(normalizeChainLink(item));
+ }
+ return out.toSorted();
+}
+
+function toNode(vault: string, absPath: string): ClaimNode | null {
+ let meta: FrontmatterMap;
+ try {
+ [meta] = parseFrontmatter(absPath);
+ } catch {
+ return null;
+ }
+ if (Object.keys(meta).length === 0) return null;
+ const rel = relative(vault, absPath).split("\\").join("/");
+ const id = normalizeChainLink(absPath);
+ const superseded = scalar(meta, "superseded_by");
+ return {
+ id,
+ path: rel,
+ topic: scalar(meta, "topic") ?? "",
+ principle: scalar(meta, "principle") ?? "",
+ valid_from: scalar(meta, "valid_from"),
+ valid_until: scalar(meta, "valid_until"),
+ superseded_by: superseded === null ? null : normalizeChainLink(superseded),
+ contradicts: normalizedList(meta, "contradicts"),
+ provenance: scalar(meta, "provenance"),
+ tombstoned: isTombstoned(meta),
+ };
+}
+
+function collectMarkdown(dir: string, out: string[]): void {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
+ out.push(join(dir, entry.name));
+ }
+}
+
+// ----- Build / persist ------------------------------------------------------
+
+/**
+ * Build the claim-graph projection from the current vault. Deterministic:
+ * nodes are sorted by vault-relative path, and truncation (when the node
+ * cap is exceeded) keeps the lexicographically-first `maxNodes`.
+ */
+export function buildClaimGraph(vault: string, opts: BuildClaimGraphOptions = {}): ClaimGraph {
+ const maxNodes = opts.maxNodes ?? CLAIM_GRAPH_MAX_NODES;
+ if (!Number.isInteger(maxNodes) || maxNodes <= 0) {
+ throw new ClaimGraphError(
+ `buildClaimGraph: maxNodes must be a positive integer; got ${maxNodes}`,
+ );
+ }
+ const brain = brainDirs(vault).brain;
+ const files: string[] = [];
+ for (const sub of SCANNED_SUBDIRS) collectMarkdown(join(brain, sub), files);
+
+ const nodes: ClaimNode[] = [];
+ for (const file of files) {
+ const node = toNode(vault, file);
+ if (node !== null) nodes.push(node);
+ }
+ nodes.sort((a, b) => a.path.localeCompare(b.path));
+
+ const truncated = nodes.length > maxNodes;
+ const kept = truncated ? nodes.slice(0, maxNodes) : nodes;
+ return {
+ version: CLAIM_GRAPH_VERSION,
+ generated_at: (opts.now ?? new Date()).toISOString(),
+ node_count: kept.length,
+ truncated,
+ nodes: kept,
+ };
+}
+
+/** Persist a projection to `Brain/claim-graph.json`. */
+export function writeClaimGraph(vault: string, graph: ClaimGraph): void {
+ atomicWriteFileSync(claimGraphPath(vault), `${JSON.stringify(graph, null, 2)}\n`);
+}
+
+/** Build the projection and persist it in one step. */
+export function rebuildClaimGraph(vault: string, opts: BuildClaimGraphOptions = {}): ClaimGraph {
+ const graph = buildClaimGraph(vault, opts);
+ writeClaimGraph(vault, graph);
+ return graph;
+}
+
+/** Load the persisted projection, or `null` when none has been built. */
+export function loadClaimGraph(vault: string): ClaimGraph | null {
+ const path = claimGraphPath(vault);
+ if (!existsSync(path)) return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(readFileSync(path, "utf8"));
+ } catch (err) {
+ throw new ClaimGraphError(
+ `loadClaimGraph: corrupt projection at ${path}: ${(err as Error).message}`,
+ {
+ cause: err,
+ },
+ );
+ }
+ if (
+ parsed === null ||
+ typeof parsed !== "object" ||
+ !Array.isArray((parsed as ClaimGraph).nodes)
+ ) {
+ throw new ClaimGraphError(`loadClaimGraph: projection at ${path} is not a claim graph`);
+ }
+ return parsed as ClaimGraph;
+}
+
+// ----- Queries --------------------------------------------------------------
+
+/**
+ * Claims true at `probeMs` under half-open validity. Tombstoned claims
+ * (wrong beliefs) never count as truth; a temporally-superseded
+ * predecessor is not tombstoned and remains the truth for its own valid
+ * window, so a past probe returns it and a present probe returns the
+ * successor. Sorted by path.
+ */
+export function truthAt(graph: ClaimGraph, probeMs: number): ClaimNode[] {
+ return graph.nodes.filter((n) => !n.tombstoned && isValidAt(n, probeMs));
+}
+
+/** Claims true right now (the default view). */
+export function currentTruth(graph: ClaimGraph, now: Date = new Date()): ClaimNode[] {
+ return truthAt(graph, now.getTime());
+}
+
+/** Every claim in the projection, including tombstoned ones (history / audit). */
+export function allClaims(graph: ClaimGraph): ClaimNode[] {
+ return [...graph.nodes];
+}
+
+/**
+ * Resolve the claim that ultimately replaced `id` by walking the
+ * `superseded_by` chain to its live tip. Returns the tip node, or `null`
+ * when `id` is unknown or the chain tip is not in the projection.
+ */
+export function whatReplaced(graph: ClaimGraph, id: string): ClaimNode | null {
+ const byId = new Map(graph.nodes.map((n) => [n.id, n] as const));
+ const start = normalizeChainLink(id);
+ if (!byId.has(start)) return null;
+ const res = resolveChainTip(start, (link) => {
+ const node = byId.get(link);
+ return node ? { supersededBy: node.superseded_by } : null;
+ });
+ return byId.get(res.tip) ?? null;
+}
+
+/**
+ * Claims that contest `id`: either those the target declares it
+ * contradicts, or those that declare they contradict the target
+ * (contradiction is treated as a symmetric contest). Sorted by path.
+ */
+export function whatContests(graph: ClaimGraph, id: string): ClaimNode[] {
+ const target = normalizeChainLink(id);
+ const out: ClaimNode[] = [];
+ const seen = new Set<string>();
+ const targetNode = graph.nodes.find((n) => n.id === target) ?? null;
+ const declaredByTarget = new Set(targetNode?.contradicts ?? []);
+ for (const node of graph.nodes) {
+ if (node.id === target) continue;
+ const contestsTarget = node.contradicts.includes(target) || declaredByTarget.has(node.id);
+ if (contestsTarget && !seen.has(node.id)) {
+ seen.add(node.id);
+ out.push(node);
+ }
+ }
+ return out;
+}
diff --git a/src/core/brain/commitment.ts b/src/core/brain/commitment.ts
new file mode 100644
index 00000000..e4f0f24d
--- /dev/null
+++ b/src/core/brain/commitment.ts
@@ -0,0 +1,62 @@
+/**
+ * Commitment-tier vocabulary (Belief lifecycle suite, B3, t_e112c63c).
+ *
+ * A commitment tier is an OPTIONAL, operator-facing epistemic stance on a
+ * belief: how firmly the memory is held, independent of the numeric
+ * confidence the dream pass computes from evidence. The four-value
+ * ladder runs from tentative to fixed:
+ *
+ * exploring -> leaning -> decided -> locked
+ *
+ * It is additive on preferences, theses, and decision records. When set,
+ * the injection formatter renders the tier label in place of the raw
+ * confidence float; when unset, output is byte-identical to today. This
+ * module is the single source of truth for the vocabulary, the typed
+ * error, the write-time validator, and the tolerant reader, so the three
+ * note families cannot drift.
+ */
+
+import { BRAIN_COMMITMENT_TIER, isCommitmentTier, type BrainCommitmentTier } from "./types.ts";
+
+export { BRAIN_COMMITMENT_TIER, isCommitmentTier, type BrainCommitmentTier } from "./types.ts";
+
+const COMMITMENT_TIER_VALUES: ReadonlyArray<BrainCommitmentTier> =
+ Object.values(BRAIN_COMMITMENT_TIER);
+
+/** Frontmatter key under which the tier is stored (unprefixed, user-editable). */
+export const COMMITMENT_TIER_KEY = "commitment";
+
+/** Typed error for an invalid commitment tier on the write path. */
+export class CommitmentError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "CommitmentError";
+ }
+}
+
+/**
+ * Validate a caller-supplied commitment tier on the WRITE path. Returns
+ * the narrowed tier, or `null` for an absent/blank value (unset is
+ * always legal - the field is optional). An invalid non-empty value
+ * rejects with a {@link CommitmentError}.
+ */
+export function validateCommitmentTier(raw: unknown): BrainCommitmentTier | null {
+ if (raw === undefined || raw === null) return null;
+ if (typeof raw === "string" && raw.trim() === "") return null;
+ if (isCommitmentTier(raw)) return raw;
+ throw new CommitmentError(
+ `commitment must be one of ${COMMITMENT_TIER_VALUES.join(", ")} (got ${JSON.stringify(raw)})`,
+ );
+}
+
+/**
+ * Tolerant READ of the commitment tier from a parsed frontmatter map.
+ * Returns the tier when the stored value is valid, otherwise `null` - a
+ * hand-edited junk value never crashes parsing of the whole note.
+ */
+export function readCommitmentTier(
+ meta: Readonly<Record<string, unknown>>,
+): BrainCommitmentTier | null {
+ const value = meta[COMMITMENT_TIER_KEY];
+ return isCommitmentTier(value) ? value : null;
+}
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index 45b0e3d0..d25105e2 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -25,7 +25,12 @@ import {
type ContextSafetyReport,
} from "./safety/context-guard.ts";
import { brainDirs } from "./paths.ts";
+import { isTombstoned } from "./lifecycle/tombstone.ts";
+import { preferChainTips } from "./inject-governor.ts";
+import { tensionWarningsForContextItems } from "./tensions.ts";
import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
+import { readCommitmentTier } from "./commitment.ts";
+import type { BrainCommitmentTier } from "./types.ts";
import {
deriveEpistemicStatus,
EPISTEMIC_STATUS,
@@ -86,6 +91,13 @@ export interface ContextPackItem extends ContextTransformAnnotations {
readonly epistemic: EpistemicStatus;
/** `evidenced_by` wikilinks grounding this item; empty when it cites none. */
readonly evidenceRefs: ReadonlyArray<string>;
+ /**
+ * Commitment tier (Belief lifecycle suite, B3) when the source note
+ * declares one: `exploring | leaning | decided | locked`. Additive and
+ * present only when set, so a pack over commitment-free notes stays
+ * byte-identical.
+ */
+ readonly commitment?: BrainCommitmentTier;
/**
* Value-per-token density score (impact-per-token allocation,
* t_affa3bd9): structural signal per estimated token that broke this
@@ -111,6 +123,14 @@ export interface ContextPackReport {
readonly receiptId?: string;
readonly telemetryId?: string;
readonly lanes?: ContextLanesReport;
+ /**
+ * Injection-time tension warnings (Belief lifecycle suite, S2,
+ * t_0e3f2bee): one line per UNRESOLVED (open or confirmed) tension whose
+ * subject note is present in `items`. Present only when at least one such
+ * warning fires, so a vault with no unresolved tensions touching the pack
+ * keeps the report byte-identical.
+ */
+ readonly warnings?: ReadonlyArray<string>;
}
export interface ContextPackOptions {
@@ -181,6 +201,13 @@ export interface ContextPackOptions {
* on the `density_ranking_context_pack` config key.
*/
readonly densityRanking?: boolean;
+ /**
+ * Belief lifecycle suite (A4, t_d9365884): keep superseded ancestors in
+ * the pack instead of collapsing each supersedes-chain to its live tip.
+ * The explicit historical flag - history is opt-in, never inferred from
+ * the query. Omitted/false injects only chain tips.
+ */
+ readonly includeHistorical?: boolean;
}
interface Candidate {
@@ -195,7 +222,15 @@ interface Candidate {
readonly tokens: number;
readonly epistemic: EpistemicStatus;
readonly evidenceRefs: ReadonlyArray<string>;
+ readonly commitment: BrainCommitmentTier | null;
readonly safety?: ContextSafetyReport;
+ /**
+ * Normalized `superseded_by` pointer when this memory has been
+ * replaced (Belief lifecycle suite, A4). Drives inject tip-preference:
+ * a superseded ancestor is dropped in favour of its live tip unless
+ * the caller opts into `includeHistorical`.
+ */
+ readonly supersededBy: string | null;
}
function withOptionalLanes(
@@ -234,6 +269,10 @@ function collectCandidates(vault: string, delimitUntrusted: boolean): Candidate[
} catch {
continue;
}
+ // Belief lifecycle suite (t_7d5a3589): a tombstoned (incl.
+ // superseded-non-tip) memory stays on disk for audit but is never
+ // injected into a context pack.
+ if (isTombstoned(meta)) continue;
const id = typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");
const tier = readTier(meta);
const created = typeof meta["created_at"] === "string" ? meta["created_at"] : "";
@@ -248,6 +287,10 @@ function collectCandidates(vault: string, delimitUntrusted: boolean): Candidate[
const createdAtMs = created ? Date.parse(created) : fallbackMtimeMs;
const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";
const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";
+ const supersededBy =
+ typeof meta["superseded_by"] === "string" && meta["superseded_by"] !== ""
+ ? (meta["superseded_by"] as string)
+ : null;
const contextLane = normalizeContextLane(meta["context_lane"]);
const epistemic = deriveEpistemicStatus(meta);
const guarded = guardBrainContextSnippet(body, {
@@ -276,6 +319,8 @@ function collectCandidates(vault: string, delimitUntrusted: boolean): Candidate[
tokens: estimateTokens(guarded.safeText),
epistemic: epistemic.status,
evidenceRefs: epistemic.evidenceRefs,
+ commitment: readCommitmentTier(meta),
+ supersededBy,
...(contextSafetyReport(guarded) ? { safety: contextSafetyReport(guarded) } : {}),
});
}
@@ -304,7 +349,14 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
// Default off, so the surfaced bodies are byte-identical to the legacy
// blocklist guard unless the vault enables the flag.
const delimitUntrusted = loadGuardrailsConfigSafe(vault).untrusted_source_delimiting;
- const candidates = collectCandidates(vault, delimitUntrusted);
+ // Belief lifecycle suite (A4, t_d9365884): prefer supersedes-chain tips.
+ // A superseded ancestor is dropped in favour of its live tip so a chain
+ // of replacements injects only the current belief; `includeHistorical`
+ // keeps the whole chain (explicit flag, never inferred). A vault with no
+ // supersession chains passes through byte-identically.
+ const candidates = preferChainTips(collectCandidates(vault, delimitUntrusted), {
+ historical: opts.includeHistorical === true,
+ }).kept;
// Focus boost (within-tier only): computed once per candidate, 0 for
// every candidate when no active focus is supplied, so the default
@@ -394,6 +446,7 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
trimmed,
epistemic: c.epistemic,
evidenceRefs: c.evidenceRefs,
+ ...(c.commitment !== null ? { commitment: c.commitment } : {}),
// When the per-memory char budget trimmed this item, recompute density
// from the emitted (post-trim) body/tokens so the surfaced value reflects
// the actual content/token-cost the agent receives, not the pre-budget
@@ -517,6 +570,17 @@ function finalizeContextPackReport(
startedAtMs: number,
): ContextPackReport {
let enriched = report;
+ // Belief lifecycle suite (S2, t_0e3f2bee): flag any injected memory that
+ // is a subject of an unresolved (open/confirmed) tension. Additive: with
+ // no such tension the helper returns [] and the `warnings` key is never
+ // added, so a tension-free pack stays byte-identical.
+ const tensionWarnings = tensionWarningsForContextItems(
+ vault,
+ report.items.map((item) => item.id),
+ );
+ if (tensionWarnings.length > 0) {
+ enriched = { ...enriched, warnings: tensionWarnings };
+ }
// Gated emissions route through the lazy emit kernel (t_5d7aa7c5):
// with the option absent the thunk never runs, and a broken
// continuity store can no longer fail the pack (fail-open).
diff --git a/src/core/brain/decisions/recall.ts b/src/core/brain/decisions/recall.ts
new file mode 100644
index 00000000..60d52c88
--- /dev/null
+++ b/src/core/brain/decisions/recall.ts
@@ -0,0 +1,116 @@
+/**
+ * Rated-decision recall wiring (Belief lifecycle suite, B5, t_5712fa39).
+ *
+ * The injection-side orchestrator that ties the deterministic prompt
+ * matcher and per-session governor (`inject-governor.ts`) to the rated
+ * decision store (`record.ts`) and the config keys (`config.ts`): given a
+ * prompt, the current turn, and the caller-owned session state, it
+ * resurfaces at most one rated decision verbatim, subject to the
+ * per-session cap and spacing.
+ *
+ * Unconfigured behaviour is byte-identical: when
+ * `decision_recall.max_per_session` is unset the resolver returns `null`,
+ * the governor disables recall, and this returns `enabled: false` with an
+ * empty surface and an unchanged state.
+ *
+ * Deterministic and language-agnostic end to end: no LLM, no
+ * language-specific word lists - matching is structural token overlap.
+ */
+
+import {
+ resolveDecisionRecallMaxPerSession,
+ resolveDecisionRecallMinSpacingTurns,
+} from "../../config.ts";
+import {
+ EMPTY_DECISION_RECALL_STATE,
+ governDecisionRecall,
+ matchRatedDecisions,
+ type DecisionRecallState,
+ type RatedDecisionCandidate,
+} from "../inject-governor.ts";
+import { listRatedDecisions, type DecisionRecord } from "./record.ts";
+
+export interface RecallRatedDecisionsInput {
+ /** The incoming user prompt to match against rated decisions. */
+ readonly prompt: string;
+ /** Monotonic current turn index (for spacing). Defaults to 0. */
+ readonly turn?: number;
+ /** Caller-owned session state; defaults to the empty state. */
+ readonly state?: DecisionRecallState;
+ readonly configPath?: string;
+ /** Optional override of the match threshold (else the governor default). */
+ readonly minOverlap?: number;
+}
+
+export interface RecallRatedDecisionsResult {
+ /** False when recall is unconfigured (byte-identical, nothing surfaced). */
+ readonly enabled: boolean;
+ /** The decision resurfaced this turn (verbatim), or `null` when gated. */
+ readonly surfaced: DecisionRecord | null;
+ /** Verbatim injection text for the surfaced decision, or "" when none. */
+ readonly text: string;
+ /** Next session state (advanced only when a decision was surfaced). */
+ readonly state: DecisionRecallState;
+}
+
+/** Structural match text for a decision: title + chosen + rationale. */
+function candidateText(d: DecisionRecord): string {
+ return [d.title, d.chosen, d.rationale].filter((s) => s.length > 0).join(" ");
+}
+
+/** Verbatim recall block rendered for injection. */
+function renderVerbatim(d: DecisionRecord): string {
+ const lines = [
+ `Recalled decision \`${d.id}\` (rating ${d.rating ?? "n/a"}): ${d.title}`,
+ `chose: ${d.chosen}`,
+ ];
+ if (d.rationale) lines.push(`rationale: ${d.rationale}`);
+ if (d.outcome) lines.push(`outcome: ${d.outcome}`);
+ return lines.join("\n");
+}
+
+/**
+ * Resurface at most one rated decision matching the prompt, governed by
+ * the per-session cap and spacing. Read-only on the decision store.
+ */
+export function recallRatedDecisions(
+ vault: string,
+ input: RecallRatedDecisionsInput,
+): RecallRatedDecisionsResult {
+ const state = input.state ?? EMPTY_DECISION_RECALL_STATE;
+ const maxPerSession = resolveDecisionRecallMaxPerSession(input.configPath);
+ const enabled = maxPerSession !== null;
+ if (!enabled) {
+ return { enabled: false, surfaced: null, text: "", state };
+ }
+ const minSpacingTurns = resolveDecisionRecallMinSpacingTurns(input.configPath) ?? 0;
+ const turn = input.turn ?? 0;
+
+ const rated = listRatedDecisions(vault);
+ const candidates: RatedDecisionCandidate[] = rated.map((d) => ({
+ id: d.id,
+ rating: d.rating ?? 0,
+ text: candidateText(d),
+ }));
+ const matches = matchRatedDecisions(
+ input.prompt,
+ candidates,
+ input.minOverlap !== undefined ? { minOverlap: input.minOverlap } : {},
+ );
+ const governed = governDecisionRecall({
+ matches,
+ state,
+ turn,
+ config: { maxPerSession, minSpacingTurns },
+ });
+ if (governed.surface === null) {
+ return { enabled: true, surfaced: null, text: "", state: governed.state };
+ }
+ const surfaced = rated.find((d) => d.id === governed.surface!.id) ?? null;
+ return {
+ enabled: true,
+ surfaced,
+ text: surfaced ? renderVerbatim(surfaced) : "",
+ state: governed.state,
+ };
+}
diff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.ts
new file mode 100644
index 00000000..45c42073
--- /dev/null
+++ b/src/core/brain/decisions/receipts.ts
@@ -0,0 +1,491 @@
+/**
+ * Decision-change receipts (Belief lifecycle suite, B4, t_3547314d).
+ *
+ * A `decision_change.v1` receipt is an append-only accountability record
+ * emitted at the moment a belief changes: what it was (`before`), what it
+ * became (`after`), the evidence that triggered the change, the
+ * confidence delta, the alternatives considered, the actor, a rationale,
+ * and a machine reason code. Receipts are append-only accountability, NOT
+ * rollback (typed revertible history is a separate ADR wave, out of scope
+ * here).
+ *
+ * Storage mirrors the truth ledger's shard discipline (`truth/store.ts`):
+ * device-sharded append-only JSONL alongside the truth ledger shards
+ * (`Brain/truth/decision-change[.<deviceId>].jsonl`), Syncthing-safe and
+ * fail-closed per line. The claim reader ignores these shards (its regex
+ * only matches `claims*.jsonl`), and this reader ignores claim shards.
+ *
+ * Durability + idempotency: the key is a sha256 of `subject + before +
+ * after`, so replaying the same change is a no-op - the second append
+ * finds the key already present and returns the existing receipt. The
+ * schema is CLOSED: any field outside the accountable set (e.g. a hidden
+ * free-text reasoning field) is rejected with a typed error. History is
+ * queryable with an opaque cursor and exact counts. Reads never write.
+ */
+
+import { mkdirSync, appendFileSync, readdirSync, readFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { join } from "node:path";
+
+import { resolveDeviceId } from "../../config.ts";
+import { appendLogEvent } from "../log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
+
+/** Schema tag stamped on every receipt line. */
+export const DECISION_CHANGE_SCHEMA_VERSION = "decision_change.v1";
+
+/**
+ * Sentinel `before`/`after` state for a receipt whose belief did not
+ * exist on that side of the change (a creation has no prior state). The
+ * closed schema requires a non-empty string, so an absent state is this
+ * explicit marker rather than the empty string.
+ */
+export const RECEIPT_ABSENT_STATE = "(absent)";
+
+/**
+ * Closed reason-code vocabulary for decision-record change receipts. A
+ * decision mutation stamps exactly one of these so the change trail is
+ * machine-filterable alongside the lifecycle codes (supersede/tombstone).
+ */
+export const DECISION_CHANGE_REASON = Object.freeze({
+ record: "decision-record",
+ outcome: "decision-outcome",
+ rating: "decision-rating",
+} as const);
+
+/** Same canonical UTC shape the truth ledger and log writer emit. */
+const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
+
+/** `decision-change.jsonl` or `decision-change.<deviceId>.jsonl`. */
+const RECEIPT_SHARD_RE = /^decision-change(?:\.([a-z0-9-]{1,32}))?\.jsonl$/;
+
+/** Cap on the length of any single string field (mirrors note-text caps). */
+const FIELD_MAX_LEN = 2000;
+
+/** Default page size for {@link queryDecisionChangeHistory}. */
+export const DECISION_HISTORY_DEFAULT_LIMIT = 50;
+
+/** Every failure path in this module raises this typed error. */
+export class ReceiptError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "ReceiptError";
+ }
+}
+
+// ----- Shapes ---------------------------------------------------------------
+
+export interface DecisionChangeReceipt {
+ readonly v: typeof DECISION_CHANGE_SCHEMA_VERSION;
+ readonly ts: string;
+ /** Id/wikilink of the belief that changed. */
+ readonly subject: string;
+ /** Canonical before-state string. */
+ readonly before: string;
+ /** Canonical after-state string. */
+ readonly after: string;
+ /** Wikilinks/ids of the evidence that triggered the change. */
+ readonly evidence_triggers: ReadonlyArray<string>;
+ /** Confidence movement (after - before), or `null` when not applicable. */
+ readonly confidence_delta: number | null;
+ /** Alternatives considered but not chosen. */
+ readonly alternatives: ReadonlyArray<string>;
+ /** Agent/human who made the change. */
+ readonly actor: string;
+ /** Accountable justification (a permitted free-text field). */
+ readonly rationale: string;
+ /** Machine reason code (e.g. `supersede`, `tombstone`, `confidence-refresh`). */
+ readonly reason_code: string;
+ /** sha256(subject + before + after); replays are no-ops. */
+ readonly idempotency_key: string;
+}
+
+export interface AppendReceiptInput {
+ readonly subject: string;
+ readonly before: string;
+ readonly after: string;
+ readonly evidenceTriggers?: ReadonlyArray<string>;
+ readonly confidenceDelta?: number | null;
+ readonly alternatives?: ReadonlyArray<string>;
+ readonly actor: string;
+ readonly rationale?: string;
+ readonly reasonCode: string;
+ /** ISO-8601 UTC instant; defaults to now. */
+ readonly ts?: string;
+ readonly configPath?: string;
+}
+
+export interface AppendReceiptResult {
+ readonly appended: boolean;
+ readonly path: string;
+ readonly receipt: DecisionChangeReceipt;
+}
+
+/**
+ * The closed set of accepted input keys. Any key outside this set is a
+ * schema violation - this is what rejects a hidden free-text reasoning
+ * field smuggled onto the input.
+ */
+const ALLOWED_INPUT_KEYS: ReadonlySet<string> = new Set([
+ "subject",
+ "before",
+ "after",
+ "evidenceTriggers",
+ "confidenceDelta",
+ "alternatives",
+ "actor",
+ "rationale",
+ "reasonCode",
+ "ts",
+ "configPath",
+]);
+
+// ----- Paths ----------------------------------------------------------------
+
+/** Receipt shards live alongside the truth ledger shards. */
+export function receiptsDir(vault: string): string {
+ return join(vault, "Brain", "truth");
+}
+
+/** The receipt shard this device appends to. */
+export function receiptShardPath(vault: string, configPath?: string): string {
+ const deviceId = resolveDeviceId(configPath);
+ const name = deviceId === "" ? "decision-change.jsonl" : `decision-change.${deviceId}.jsonl`;
+ return join(receiptsDir(vault), name);
+}
+
+// ----- Validation -----------------------------------------------------------
+
+function requireString(value: unknown, label: string): string {
+ if (typeof value !== "string" || value.trim() === "") {
+ throw new ReceiptError(`receipt: ${label} is required`);
+ }
+ if (value.length > FIELD_MAX_LEN) {
+ throw new ReceiptError(`receipt: ${label} exceeds ${FIELD_MAX_LEN} chars`);
+ }
+ return value.trim();
+}
+
+function optionalStringList(value: unknown, label: string): ReadonlyArray<string> {
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
+ throw new ReceiptError(`receipt: ${label} must be a list of strings`);
+ }
+ return value.map((v) => (v as string).trim()).filter((v) => v.length > 0);
+}
+
+function computeIdempotencyKey(subject: string, before: string, after: string): string {
+ return createHash("sha256").update(`${subject}\n${before}\n${after}`, "utf8").digest("hex");
+}
+
+/**
+ * Reduce a receipt subject to its bare identifier for read-side matching.
+ *
+ * Receipts store `subject` in whichever shape the writer had on hand: a
+ * decision record's B4 hook stamps a wikilink (`[[decision-adopt-bun]]`,
+ * `record.ts`), while the lifecycle tombstone/supersede hook stamps a bare
+ * vault-relative path (`Brain/decisions/decision-adopt-bun.md`,
+ * `lifecycle/tombstone.ts`). A history query filtering by subject would
+ * otherwise require the caller to know which writer produced a given
+ * receipt. This strips, in order: a `[[ ]]` wikilink fence (and any
+ * `|alias` display suffix), a leading directory prefix, and a trailing
+ * `.md` extension - so the bare id, wikilink, and full-path forms of the
+ * same subject all normalize to one value. Storage is untouched; this is
+ * read-side normalization only, applied at query time in
+ * {@link queryDecisionChangeHistory}.
+ */
+export function normalizeDecisionSubject(raw: string): string {
+ let value = raw.trim();
+ const fence = /^\[\[([^\]]+)\]\]$/.exec(value);
+ if (fence) value = fence[1]!.trim();
+ const pipe = value.indexOf("|");
+ if (pipe >= 0) value = value.slice(0, pipe).trim();
+ const slash = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
+ if (slash >= 0) value = value.slice(slash + 1);
+ if (value.toLowerCase().endsWith(".md")) value = value.slice(0, -3);
+ return value;
+}
+
+// ----- Append ---------------------------------------------------------------
+
+/**
+ * Validate and append one decision-change receipt. Idempotent: if a
+ * receipt with the same `subject + before + after` key already exists,
+ * this is a no-op returning the existing receipt with `appended: false`.
+ */
+export function appendDecisionChangeReceipt(
+ vault: string,
+ input: AppendReceiptInput,
+): AppendReceiptResult {
+ // Closed-schema gate: reject any unexpected field before doing anything.
+ for (const key of Object.keys(input)) {
+ if (!ALLOWED_INPUT_KEYS.has(key)) {
+ throw new ReceiptError(`receipt: unexpected field ${JSON.stringify(key)} is not permitted`);
+ }
+ }
+
+ const subject = requireString(input.subject, "subject");
+ const before = requireString(input.before, "before");
+ const after = requireString(input.after, "after");
+ const actor = requireString(input.actor, "actor");
+ const reasonCode = requireString(input.reasonCode, "reasonCode");
+ const rationale =
+ input.rationale === undefined || input.rationale === null
+ ? ""
+ : requireString(input.rationale, "rationale");
+ const evidenceTriggers = optionalStringList(input.evidenceTriggers, "evidenceTriggers");
+ const alternatives = optionalStringList(input.alternatives, "alternatives");
+ let confidenceDelta: number | null = null;
+ if (input.confidenceDelta !== undefined && input.confidenceDelta !== null) {
+ if (typeof input.confidenceDelta !== "number" || !Number.isFinite(input.confidenceDelta)) {
+ throw new ReceiptError("receipt: confidenceDelta must be a finite number or null");
+ }
+ confidenceDelta = input.confidenceDelta;
+ }
+ const ts = input.ts ?? new Date().toISOString();
+ if (!ISO_UTC_TS_RE.test(ts)) {
+ throw new ReceiptError(`receipt: ts must be canonical ISO-8601 UTC: ${JSON.stringify(ts)}`);
+ }
+
+ const idempotencyKey = computeIdempotencyKey(subject, before, after);
+
+ // Idempotency: a matching key already on disk makes this a no-op.
+ const existing = readDecisionChangeReceipts(vault).receipts.find(
+ (r) => r.idempotency_key === idempotencyKey,
+ );
+ if (existing) {
+ return Object.freeze({
+ appended: false,
+ path: receiptShardPath(vault, input.configPath),
+ receipt: existing,
+ });
+ }
+
+ const receipt: DecisionChangeReceipt = Object.freeze({
+ v: DECISION_CHANGE_SCHEMA_VERSION,
+ ts,
+ subject,
+ before,
+ after,
+ evidence_triggers: Object.freeze([...evidenceTriggers]),
+ confidence_delta: confidenceDelta,
+ alternatives: Object.freeze([...alternatives]),
+ actor,
+ rationale,
+ reason_code: reasonCode,
+ idempotency_key: idempotencyKey,
+ });
+
+ mkdirSync(receiptsDir(vault), { recursive: true });
+ const path = receiptShardPath(vault, input.configPath);
+ appendFileSync(path, JSON.stringify(receipt) + "\n");
+ // Surface the change in the merged activity timeline. Emitted only on an
+ // actual append, never on an idempotent replay, so the log never
+ // double-counts a change. Fail-soft: a log hiccup must not lose the receipt.
+ try {
+ appendLogEvent(vault, {
+ timestamp: ts,
+ eventType: BRAIN_LOG_EVENT_KIND.decisionChangeReceipt,
+ body: {
+ subject,
+ reason_code: reasonCode,
+ idempotency_key: idempotencyKey,
+ agent: actor,
+ },
+ });
+ } catch {
+ // The JSONL receipt is authoritative; the timeline mirror is best-effort.
+ }
+ return Object.freeze({ appended: true, path, receipt });
+}
+
+// ----- Read -----------------------------------------------------------------
+
+export interface ReceiptParseWarning {
+ readonly path: string;
+ readonly lineNumber: number;
+ readonly message: string;
+}
+
+export interface ReadReceiptsResult {
+ readonly receipts: ReadonlyArray<DecisionChangeReceipt>;
+ readonly warnings: ReadonlyArray<ReceiptParseWarning>;
+}
+
+/**
+ * Read every receipt merged across device shards, sorted by
+ * (ts, shardId, line). Fail-closed per line: a malformed or
+ * unknown-version line surfaces as a warning, never throws. Never writes.
+ */
+export function readDecisionChangeReceipts(vault: string): ReadReceiptsResult {
+ const dir = receiptsDir(vault);
+ let names: string[];
+ try {
+ names = readdirSync(dir).toSorted();
+ } catch {
+ return { receipts: [], warnings: [] };
+ }
+
+ interface Tagged {
+ readonly receipt: DecisionChangeReceipt;
+ readonly shardId: string;
+ readonly line: number;
+ }
+ const tagged: Tagged[] = [];
+ const warnings: ReceiptParseWarning[] = [];
+
+ for (const name of names) {
+ const m = RECEIPT_SHARD_RE.exec(name);
+ if (!m) continue;
+ const shardId = m[1] ?? "";
+ if (shardId.startsWith("sync-conflict")) continue;
+ const path = join(dir, name);
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (err) {
+ warnings.push({
+ path,
+ lineNumber: 0,
+ message: `failed to read shard: ${(err as NodeJS.ErrnoException).message ?? String(err)}`,
+ });
+ continue;
+ }
+ const lines = text.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (line.trim() === "") continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ warnings.push({ path, lineNumber: i + 1, message: `malformed JSONL line` });
+ continue;
+ }
+ const receipt = coerceReceipt(parsed, path, i + 1, warnings);
+ if (receipt !== null) tagged.push({ receipt, shardId, line: i });
+ }
+ }
+
+ tagged.sort((a, b) => {
+ if (a.receipt.ts !== b.receipt.ts) return a.receipt.ts < b.receipt.ts ? -1 : 1;
+ if (a.shardId !== b.shardId) return a.shardId < b.shardId ? -1 : 1;
+ return a.line - b.line;
+ });
+
+ return { receipts: tagged.map((t) => t.receipt), warnings };
+}
+
+function coerceReceipt(
+ parsed: unknown,
+ path: string,
+ lineNumber: number,
+ warnings: ReceiptParseWarning[],
+): DecisionChangeReceipt | null {
+ if (typeof parsed !== "object" || parsed === null) {
+ warnings.push({ path, lineNumber, message: "not an object" });
+ return null;
+ }
+ const r = parsed as Record<string, unknown>;
+ if (r["v"] !== DECISION_CHANGE_SCHEMA_VERSION) {
+ warnings.push({ path, lineNumber, message: `unknown schema version ${String(r["v"])}` });
+ return null;
+ }
+ if (
+ typeof r["subject"] !== "string" ||
+ typeof r["before"] !== "string" ||
+ typeof r["after"] !== "string" ||
+ typeof r["idempotency_key"] !== "string"
+ ) {
+ warnings.push({ path, lineNumber, message: "missing required field" });
+ return null;
+ }
+ return Object.freeze({
+ v: DECISION_CHANGE_SCHEMA_VERSION,
+ ts: typeof r["ts"] === "string" ? r["ts"] : "",
+ subject: r["subject"] as string,
+ before: r["before"] as string,
+ after: r["after"] as string,
+ evidence_triggers: Array.isArray(r["evidence_triggers"])
+ ? (r["evidence_triggers"] as string[]).filter((v) => typeof v === "string")
+ : [],
+ confidence_delta:
+ typeof r["confidence_delta"] === "number" ? (r["confidence_delta"] as number) : null,
+ alternatives: Array.isArray(r["alternatives"])
+ ? (r["alternatives"] as string[]).filter((v) => typeof v === "string")
+ : [],
+ actor: typeof r["actor"] === "string" ? (r["actor"] as string) : "",
+ rationale: typeof r["rationale"] === "string" ? (r["rationale"] as string) : "",
+ reason_code: typeof r["reason_code"] === "string" ? (r["reason_code"] as string) : "",
+ idempotency_key: r["idempotency_key"] as string,
+ });
+}
+
+// ----- History query --------------------------------------------------------
+
+export interface DecisionHistoryQuery {
+ /** Filter to a single subject id/wikilink. */
+ readonly subject?: string;
+ /** Opaque cursor from a prior page's `nextCursor`. */
+ readonly cursor?: string;
+ /** Page size; defaults to {@link DECISION_HISTORY_DEFAULT_LIMIT}. */
+ readonly limit?: number;
+}
+
+export interface DecisionHistoryPage {
+ readonly receipts: ReadonlyArray<DecisionChangeReceipt>;
+ /** Exact count of receipts matching the filter (across all pages). */
+ readonly total: number;
+ /** Opaque cursor for the next page, or `null` when exhausted. */
+ readonly nextCursor: string | null;
+}
+
+/** Encode a numeric offset as an opaque cursor. */
+function encodeCursor(offset: number): string {
+ return Buffer.from(`o:${offset}`, "utf8").toString("base64url");
+}
+
+/** Decode an opaque cursor to its offset; rejects a malformed cursor. */
+function decodeCursor(cursor: string): number {
+ let decoded: string;
+ try {
+ decoded = Buffer.from(cursor, "base64url").toString("utf8");
+ } catch {
+ throw new ReceiptError("receipt: malformed cursor");
+ }
+ const m = /^o:(\d+)$/.exec(decoded);
+ if (!m) throw new ReceiptError("receipt: malformed cursor");
+ return Number.parseInt(m[1]!, 10);
+}
+
+/**
+ * Paginated, subject-filterable history over the receipt log. Returns the
+ * page, an opaque `nextCursor` (null when exhausted), and the exact total
+ * matching the filter. Read-only: never appends.
+ */
+export function queryDecisionChangeHistory(
+ vault: string,
+ query: DecisionHistoryQuery,
+): DecisionHistoryPage {
+ const limit = query.limit ?? DECISION_HISTORY_DEFAULT_LIMIT;
+ if (!Number.isInteger(limit) || limit <= 0) {
+ throw new ReceiptError("receipt: limit must be a positive integer");
+ }
+ const offset = query.cursor !== undefined ? decodeCursor(query.cursor) : 0;
+ if (offset < 0) throw new ReceiptError("receipt: malformed cursor");
+
+ const all = readDecisionChangeReceipts(vault).receipts;
+ let matching = all;
+ if (query.subject !== undefined) {
+ // Read-side only: receipts store subjects in whichever shape their
+ // writer had on hand (bare id, wikilink, or vault-relative path), so
+ // both sides are normalized to the bare id before comparing.
+ const wanted = normalizeDecisionSubject(query.subject);
+ matching = all.filter((r) => normalizeDecisionSubject(r.subject) === wanted);
+ }
+ const total = matching.length;
+ const page = matching.slice(offset, offset + limit);
+ const nextOffset = offset + page.length;
+ const nextCursor = nextOffset < total ? encodeCursor(nextOffset) : null;
+ return Object.freeze({ receipts: page, total, nextCursor });
+}
diff --git a/src/core/brain/decisions/record.ts b/src/core/brain/decisions/record.ts
new file mode 100644
index 00000000..93617979
--- /dev/null
+++ b/src/core/brain/decisions/record.ts
@@ -0,0 +1,632 @@
+/**
+ * Decision-record note family (Belief lifecycle suite, Track B anchor,
+ * t_ac03214d).
+ *
+ * A decision is the highest-value operator memory: the choice made, the
+ * key assumption riding on it, a date to review whether it held, an
+ * (initially empty) outcome that hindsight backfills, and an optional
+ * pre-mortem ("how could this go wrong"). Each decision is a Markdown
+ * page under `Brain/decisions/decision-<slug>.md`: operator-readable in
+ * Obsidian, greppable, versionable - mirroring the `obligations.ts` and
+ * `health/thesis.ts` page models.
+ *
+ * The `review_date` maps onto the existing obligations engine: capturing
+ * a decision opens exactly one review obligation, idempotently (a second
+ * attempt on the same review slug is a no-op, never a duplicate). Outcome
+ * backfill is a logged mutation. Capturing a new decision can surface
+ * historically similar decisions with their recorded outcomes via the
+ * shared similarity machinery (`similarity.ts`) - deterministic,
+ * language-agnostic token overlap, no model call.
+ *
+ * Import direction: this module imports from obligations / paths / log /
+ * similarity / vault helpers, never the reverse.
+ */
+
+import { existsSync, mkdirSync, readdirSync } from "node:fs";
+
+import { normalizeAgentArgument } from "../../agent-identity.ts";
+import { resolveAgentName } from "../../config.ts";
+import { sanitiseTextField } from "../../redactor.ts";
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { parseFrontmatter, slugify } from "../../vault.ts";
+import { appendLogEvent } from "../log.ts";
+import { addObligation } from "../obligations.ts";
+import { decisionPath, decisionsDir, obligationPath, validateIsoDate } from "../paths.ts";
+import { jaccard, tokenise } from "../similarity.ts";
+import { isoSecond } from "../time.ts";
+import { BRAIN_LOG_EVENT_KIND, type BrainCommitmentTier } from "../types.ts";
+import { readCommitmentTier, validateCommitmentTier } from "../commitment.ts";
+import {
+ appendDecisionChangeReceipt,
+ DECISION_CHANGE_REASON,
+ RECEIPT_ABSENT_STATE,
+ type AppendReceiptInput,
+} from "./receipts.ts";
+
+// ----- Constants ------------------------------------------------------------
+
+/** Frontmatter `type` discriminator carried by every decision note. */
+export const DECISION_TYPE = "decision";
+/** Cap on the short prose frontmatter fields (chosen/assumption/etc). */
+const FIELD_MAX_LEN = 512;
+/** Cap on the decision title. */
+const TITLE_MAX_LEN = 200;
+/**
+ * Cadence stamped on the review obligation. A decision review is
+ * effectively a one-shot check; `yearly` is the least-nagging recurring
+ * cadence the obligations engine offers, so a completed-then-advanced
+ * obligation does not re-fire for a year.
+ */
+export const DECISION_REVIEW_CADENCE = "yearly";
+/** Default jaccard floor for {@link findSimilarDecisions}. */
+export const DECISION_SIMILARITY_THRESHOLD = 0.2;
+/** Prefix applied to the review-obligation title. */
+const REVIEW_OBLIGATION_TITLE_PREFIX = "Review decision:";
+/** Inclusive lower bound of a decision rating (B2). */
+export const DECISION_RATING_MIN = 1;
+/** Inclusive upper bound of a decision rating (B2). */
+export const DECISION_RATING_MAX = 5;
+/** Receipt before/after state prefix for the chosen option (B4 trail). */
+const RECEIPT_CHOSEN_PREFIX = "chosen:";
+/** Receipt before/after state prefix for the hindsight outcome (B4 trail). */
+const RECEIPT_OUTCOME_PREFIX = "outcome:";
+/** Receipt before/after state prefix for the quality rating (B4 trail). */
+const RECEIPT_RATING_PREFIX = "rating:";
+/** Receipt state token for an unset rating (B4 trail). */
+const RECEIPT_RATING_UNSET = "none";
+
+// ----- Errors ---------------------------------------------------------------
+
+/** Every failure path in this module raises this typed error. */
+export class DecisionError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "DecisionError";
+ }
+}
+
+// ----- Shapes ---------------------------------------------------------------
+
+export interface DecisionRecord {
+ readonly slug: string;
+ /** Filename basename without `.md`. Equals `decision-<slug>`. */
+ readonly id: string;
+ /** Frontmatter type discriminator; always {@link DECISION_TYPE}. */
+ readonly type: typeof DECISION_TYPE;
+ /** The decision question / statement (drives the slug). */
+ readonly title: string;
+ /** The option that was chosen. */
+ readonly chosen: string;
+ /** The key assumption the decision rides on. */
+ readonly assumption: string;
+ /** Review date (`YYYY-MM-DD`), or null when none was captured. */
+ readonly reviewDate: string | null;
+ /** Hindsight outcome; empty until {@link backfillOutcome} runs. */
+ readonly outcome: string;
+ /** Optional pre-mortem ("how could this go wrong"). */
+ readonly premortem: string | null;
+ readonly createdAt: string;
+ readonly agent: string;
+ /**
+ * Quality self-assessment in [{@link DECISION_RATING_MIN},
+ * {@link DECISION_RATING_MAX}] (B2). `null` when the decision is
+ * unrated; an unrated decision omits the frontmatter key entirely so
+ * its on-disk shape is byte-identical to a B1 decision.
+ */
+ readonly rating: number | null;
+ /** Free-form justification for the rating (B2); empty when unrated. */
+ readonly rationale: string;
+ /**
+ * Optional commitment tier (B3): `exploring | leaning | decided |
+ * locked`. `null` when unset; round-trips through frontmatter, emitted
+ * only when set so unset decisions stay byte-identical.
+ */
+ readonly commitment: BrainCommitmentTier | null;
+ /** Free-form operator prose from the note body. */
+ readonly notes: string;
+ readonly path: string;
+}
+
+export interface RecordDecisionInput {
+ readonly title: string;
+ readonly chosen: string;
+ readonly assumption: string;
+ /** Review date (`YYYY-MM-DD`); opens exactly one review obligation. */
+ readonly reviewDate: string;
+ readonly premortem?: string;
+ readonly notes?: string;
+ /** Optional quality rating captured at record time (B2). */
+ readonly rating?: number;
+ /** Optional rationale for the rating (B2). */
+ readonly rationale?: string;
+ /** Optional commitment tier captured at record time (B3); validated on write. */
+ readonly commitment?: BrainCommitmentTier;
+ readonly agent: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface RecordDecisionResult {
+ readonly record: DecisionRecord;
+ /** Slug of the opened review obligation. */
+ readonly reviewObligationSlug: string;
+ /** False when the review obligation already existed (idempotent). */
+ readonly obligationCreated: boolean;
+}
+
+export interface BackfillOutcomeInput {
+ readonly slug: string;
+ readonly outcome: string;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface UpdateRatingInput {
+ readonly slug: string;
+ readonly rating: number;
+ readonly rationale?: string;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface SimilarDecision {
+ readonly slug: string;
+ readonly id: string;
+ readonly title: string;
+ readonly chosen: string;
+ readonly outcome: string;
+ readonly jaccard: number;
+}
+
+export interface SimilarDecisionQuery {
+ readonly title: string;
+ readonly chosen?: string;
+ /** Never return a decision with this slug (the one being captured). */
+ readonly excludeSlug?: string;
+}
+
+export interface FindSimilarDecisionsOptions {
+ readonly threshold?: number;
+ readonly limit?: number;
+}
+
+// ----- Field helpers --------------------------------------------------------
+
+function requireField(value: unknown, label: string): string {
+ if (typeof value !== "string") {
+ throw new DecisionError(`decision: ${label} is required`);
+ }
+ const cleaned = sanitiseTextField(value, {
+ maxLen: label === "title" ? TITLE_MAX_LEN : FIELD_MAX_LEN,
+ singleLine: true,
+ }).trim();
+ if (!cleaned) throw new DecisionError(`decision: ${label} is required`);
+ return cleaned;
+}
+
+function optionalField(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const cleaned = sanitiseTextField(value, { maxLen: FIELD_MAX_LEN, singleLine: true }).trim();
+ return cleaned.length > 0 ? cleaned : null;
+}
+
+function requireReviewDate(value: string): string {
+ try {
+ return validateIsoDate(value);
+ } catch {
+ throw new DecisionError(`decision: review_date is not a valid calendar date: ${value}`);
+ }
+}
+
+/**
+ * Validate a rating: an integer in the inclusive
+ * [{@link DECISION_RATING_MIN}, {@link DECISION_RATING_MAX}] band.
+ */
+function requireRating(value: number): number {
+ if (!Number.isInteger(value) || value < DECISION_RATING_MIN || value > DECISION_RATING_MAX) {
+ throw new DecisionError(
+ `decision: rating must be an integer in [${DECISION_RATING_MIN}, ${DECISION_RATING_MAX}]`,
+ );
+ }
+ return value;
+}
+
+/**
+ * Parse a stored rating, tolerating a hand-edited value; null when
+ * absent or invalid. The flat frontmatter parser returns scalars as
+ * strings, so a numeric string (`"4"`) is accepted as well as a number.
+ */
+function parseRating(value: unknown): number | null {
+ let n: number;
+ if (typeof value === "number") n = value;
+ else if (typeof value === "string" && value.trim() !== "") n = Number(value);
+ else return null;
+ if (!Number.isInteger(n) || n < DECISION_RATING_MIN || n > DECISION_RATING_MAX) return null;
+ return n;
+}
+
+// ----- Change receipts (B4) -------------------------------------------------
+
+/**
+ * Emit one decision-change receipt for a decision mutation. A mutation
+ * whose before-state equals its after-state changed no belief, so it
+ * emits nothing (an operator re-applying the same value is a no-op, in
+ * the spirit of the receipt idempotency key). Fail-soft otherwise: the
+ * decision note and its `decision-*` log event are authoritative, so an
+ * accountability-log hiccup must never fail the mutation itself. This
+ * mirrors the lifecycle supersede/tombstone receipt path.
+ */
+function emitDecisionChangeReceipt(vault: string, input: AppendReceiptInput): void {
+ if (input.before === input.after) return;
+ try {
+ appendDecisionChangeReceipt(vault, input);
+ } catch {
+ // Receipt is best-effort accountability; the decision note and its
+ // `decision-*` log event remain authoritative.
+ }
+}
+
+// ----- (De)serialization ----------------------------------------------------
+
+function render(record: Omit<DecisionRecord, "path">): string {
+ const lines = [
+ "---",
+ `type: ${DECISION_TYPE}`,
+ `id: ${record.id}`,
+ `title: ${JSON.stringify(record.title)}`,
+ `chosen: ${JSON.stringify(record.chosen)}`,
+ `assumption: ${JSON.stringify(record.assumption)}`,
+ `review_date: ${record.reviewDate ?? ""}`,
+ `outcome: ${JSON.stringify(record.outcome)}`,
+ ];
+ if (record.premortem !== null) lines.push(`premortem: ${JSON.stringify(record.premortem)}`);
+ // Rating fields are omitted entirely when unset so an unrated decision
+ // is byte-identical to a B1-era note (additive-only surface).
+ if (record.rating !== null) {
+ lines.push(`rating: ${record.rating}`);
+ lines.push(`rationale: ${JSON.stringify(record.rationale)}`);
+ }
+ // Commitment tier (B3): emitted only when set so an unset decision is
+ // byte-identical to a pre-B3 note.
+ if (record.commitment !== null) lines.push(`commitment: ${record.commitment}`);
+ lines.push(`created_at: ${record.createdAt}`);
+ lines.push(`agent: ${JSON.stringify(record.agent)}`);
+ lines.push("---", "", record.notes, "");
+ return lines.join("\n");
+}
+
+function parsePage(vault: string, slug: string): DecisionRecord | null {
+ const path = decisionPath(vault, slug);
+ if (!existsSync(path)) return null;
+ const [meta, body] = parseFrontmatter(path);
+ if (meta["type"] !== DECISION_TYPE) return null;
+ const reviewRaw = typeof meta["review_date"] === "string" ? meta["review_date"].trim() : "";
+ let reviewDate: string | null = null;
+ if (reviewRaw.length > 0) {
+ try {
+ reviewDate = validateIsoDate(reviewRaw);
+ } catch {
+ reviewDate = null;
+ }
+ }
+ const premortemRaw = typeof meta["premortem"] === "string" ? meta["premortem"] : "";
+ return Object.freeze({
+ slug,
+ id: `decision-${slug}`,
+ type: DECISION_TYPE,
+ title: typeof meta["title"] === "string" ? meta["title"] : slug,
+ chosen: typeof meta["chosen"] === "string" ? meta["chosen"] : "",
+ assumption: typeof meta["assumption"] === "string" ? meta["assumption"] : "",
+ reviewDate,
+ outcome: typeof meta["outcome"] === "string" ? meta["outcome"] : "",
+ premortem: premortemRaw.length > 0 ? premortemRaw : null,
+ createdAt: typeof meta["created_at"] === "string" ? meta["created_at"] : "",
+ agent: typeof meta["agent"] === "string" ? meta["agent"] : "",
+ rating: parseRating(meta["rating"]),
+ rationale: typeof meta["rationale"] === "string" ? meta["rationale"] : "",
+ commitment: readCommitmentTier(meta),
+ notes: body.trim(),
+ path,
+ });
+}
+
+// ----- Review obligation ----------------------------------------------------
+
+function reviewObligationTitle(decisionTitle: string): string {
+ return `${REVIEW_OBLIGATION_TITLE_PREFIX} ${decisionTitle}`;
+}
+
+/**
+ * Ensure the single review obligation for a decision exists, anchored at
+ * `reviewDate`. Idempotent: if the obligation slug already exists, this
+ * is a no-op returning `{ created: false }` rather than raising the
+ * obligations engine's duplicate error.
+ */
+export function ensureReviewObligation(
+ vault: string,
+ input: { title: string; reviewDate: string; agent: string; now?: Date },
+): { slug: string; created: boolean } {
+ const obligationTitle = reviewObligationTitle(input.title);
+ const slug = slugify(obligationTitle);
+ if (existsSync(obligationPath(vault, slug))) {
+ return { slug, created: false };
+ }
+ const page = addObligation(vault, {
+ title: obligationTitle,
+ cadence: DECISION_REVIEW_CADENCE,
+ agent: input.agent,
+ anchor: input.reviewDate,
+ ...(input.now !== undefined ? { now: input.now } : {}),
+ });
+ return { slug: page.slug, created: true };
+}
+
+// ----- Capture --------------------------------------------------------------
+
+/**
+ * Capture a decision: write the `type: decision` note, open its review
+ * obligation, and log a `decision-record` event. Refuses to clobber an
+ * existing decision slug (an update is a distinct, later operation).
+ */
+export function recordDecision(vault: string, input: RecordDecisionInput): RecordDecisionResult {
+ const title = requireField(input.title, "title");
+ const chosen = requireField(input.chosen, "chosen");
+ const assumption = requireField(input.assumption, "assumption");
+ const reviewDate = requireReviewDate(input.reviewDate);
+ const premortem = optionalField(input.premortem);
+ const rating = input.rating !== undefined ? requireRating(input.rating) : null;
+ const rationale =
+ rating !== null
+ ? sanitiseTextField(input.rationale ?? "", { maxLen: FIELD_MAX_LEN, singleLine: true }).trim()
+ : "";
+ const commitment = validateCommitmentTier(input.commitment);
+ const now = input.now ?? new Date();
+ const slug = slugify(title);
+
+ if (existsSync(decisionPath(vault, slug))) {
+ throw new DecisionError(`decision already exists: ${slug} (backfill or remove it first)`);
+ }
+
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+
+ const record: Omit<DecisionRecord, "path"> = {
+ slug,
+ id: `decision-${slug}`,
+ type: DECISION_TYPE,
+ title,
+ chosen,
+ assumption,
+ reviewDate,
+ outcome: "",
+ premortem,
+ createdAt: isoSecond(now),
+ agent,
+ rating,
+ rationale,
+ commitment,
+ notes: (input.notes ?? "").trim(),
+ };
+
+ mkdirSync(decisionsDir(vault), { recursive: true });
+ const path = decisionPath(vault, slug);
+ atomicWriteFileSync(path, render(record));
+
+ const review = ensureReviewObligation(vault, { title, reviewDate, agent, now });
+
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.decisionRecord,
+ body: {
+ decision: `[[${record.id}]]`,
+ chosen,
+ review_date: reviewDate,
+ obligation: review.created ? review.slug : `${review.slug} (existing)`,
+ agent,
+ },
+ });
+
+ // B4 change trail: a decision's creation is a belief change with an
+ // absent before-state (no prior belief existed), per the closed schema.
+ emitDecisionChangeReceipt(vault, {
+ subject: `[[${record.id}]]`,
+ before: RECEIPT_ABSENT_STATE,
+ after: `${RECEIPT_CHOSEN_PREFIX}${chosen}`,
+ actor: agent,
+ rationale: assumption,
+ reasonCode: DECISION_CHANGE_REASON.record,
+ ts: isoSecond(now),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+
+ return {
+ record: Object.freeze({ ...record, path }),
+ reviewObligationSlug: review.slug,
+ obligationCreated: review.created,
+ };
+}
+
+// ----- Outcome backfill -----------------------------------------------------
+
+/**
+ * Backfill the `outcome` of an existing decision (a logged mutation).
+ * Preserves every other field and the body. Rejects an unknown slug or
+ * an empty outcome with a typed error.
+ */
+export function backfillOutcome(vault: string, input: BackfillOutcomeInput): DecisionRecord {
+ const slug = slugify(input.slug);
+ const prior = parsePage(vault, slug);
+ if (prior === null) throw new DecisionError(`no decision: ${slug}`);
+ const outcome = sanitiseTextField(input.outcome, {
+ maxLen: FIELD_MAX_LEN,
+ singleLine: true,
+ }).trim();
+ if (!outcome) throw new DecisionError("decision: outcome is required for backfill");
+ const now = input.now ?? new Date();
+
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+
+ const { path: _path, ...rest } = prior;
+ const next: Omit<DecisionRecord, "path"> = { ...rest, outcome };
+ atomicWriteFileSync(prior.path, render(next));
+
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.decisionOutcome,
+ body: {
+ decision: `[[${prior.id}]]`,
+ outcome,
+ agent,
+ },
+ });
+
+ // B4 change trail: backfilling the outcome moves the belief state from
+ // the prior outcome (empty until the first backfill) to the new one.
+ emitDecisionChangeReceipt(vault, {
+ subject: `[[${prior.id}]]`,
+ before: `${RECEIPT_OUTCOME_PREFIX}${prior.outcome}`,
+ after: `${RECEIPT_OUTCOME_PREFIX}${outcome}`,
+ actor: agent,
+ reasonCode: DECISION_CHANGE_REASON.outcome,
+ ts: isoSecond(now),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+
+ return Object.freeze({ ...next, path: prior.path });
+}
+
+// ----- Rating (B2) ----------------------------------------------------------
+
+/**
+ * Set or change the `rating` (and optional `rationale`) of an existing
+ * decision (a logged mutation). Preserves every other field and the body.
+ * Rejects an unknown slug or an out-of-range rating with a typed error.
+ */
+export function updateRating(vault: string, input: UpdateRatingInput): DecisionRecord {
+ const slug = slugify(input.slug);
+ const prior = parsePage(vault, slug);
+ if (prior === null) throw new DecisionError(`no decision: ${slug}`);
+ const rating = requireRating(input.rating);
+ const rationale =
+ input.rationale !== undefined
+ ? sanitiseTextField(input.rationale, { maxLen: FIELD_MAX_LEN, singleLine: true }).trim()
+ : prior.rationale;
+ const now = input.now ?? new Date();
+
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+
+ const { path: _path, ...rest } = prior;
+ const next: Omit<DecisionRecord, "path"> = { ...rest, rating, rationale };
+ atomicWriteFileSync(prior.path, render(next));
+
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.decisionRating,
+ body: {
+ decision: `[[${prior.id}]]`,
+ rating: String(rating),
+ ...(rationale ? { rationale } : {}),
+ agent,
+ },
+ });
+
+ // B4 change trail: rating is a belief-quality change; the before-state
+ // is the prior rating (`none` when previously unrated).
+ emitDecisionChangeReceipt(vault, {
+ subject: `[[${prior.id}]]`,
+ before: `${RECEIPT_RATING_PREFIX}${prior.rating ?? RECEIPT_RATING_UNSET}`,
+ after: `${RECEIPT_RATING_PREFIX}${rating}`,
+ actor: agent,
+ ...(rationale ? { rationale } : {}),
+ reasonCode: DECISION_CHANGE_REASON.rating,
+ ts: isoSecond(now),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+
+ return Object.freeze({ ...next, path: prior.path });
+}
+
+/**
+ * Every rated decision, sorted by descending rating (ties break on slug).
+ * Unrated decisions are excluded - this is the rated-capture list surface,
+ * separate from ordinary signal/preference recall.
+ */
+export function listRatedDecisions(vault: string): DecisionRecord[] {
+ return listDecisions(vault)
+ .filter((d) => d.rating !== null)
+ .toSorted((a, b) => (b.rating ?? 0) - (a.rating ?? 0) || a.slug.localeCompare(b.slug));
+}
+
+/**
+ * Read a specific set of decisions side by side for comparison, in the
+ * order requested. Unknown slugs are skipped (a comparison of what exists).
+ */
+export function compareDecisions(vault: string, slugs: ReadonlyArray<string>): DecisionRecord[] {
+ const out: DecisionRecord[] = [];
+ for (const slug of slugs) {
+ const page = parsePage(vault, slugify(slug));
+ if (page !== null) out.push(page);
+ }
+ return out;
+}
+
+// ----- Reads ----------------------------------------------------------------
+
+/** One decision, or null. */
+export function showDecision(vault: string, slug: string): DecisionRecord | null {
+ return parsePage(vault, slugify(slug));
+}
+
+/** Every decision, sorted by slug. */
+export function listDecisions(vault: string): DecisionRecord[] {
+ const dir = decisionsDir(vault);
+ if (!existsSync(dir)) return [];
+ const out: DecisionRecord[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md") || !name.startsWith("decision-")) continue;
+ const slug = name.replace(/^decision-/u, "").replace(/\.md$/u, "");
+ const page = parsePage(vault, slug);
+ if (page !== null) out.push(page);
+ }
+ return out.toSorted((a, b) => a.slug.localeCompare(b.slug));
+}
+
+// ----- Similar-decision lookup ----------------------------------------------
+
+/**
+ * Surface historically similar decisions with their recorded outcomes,
+ * ranked by descending token-overlap (jaccard) of the query's
+ * title+chosen against each stored decision's title+chosen. Deterministic
+ * and language-agnostic (shared `tokenise`/`jaccard`, no stopword list,
+ * no model). Ties break on slug for stable output.
+ */
+export function findSimilarDecisions(
+ vault: string,
+ query: SimilarDecisionQuery,
+ opts: FindSimilarDecisionsOptions = {},
+): SimilarDecision[] {
+ const threshold = opts.threshold ?? DECISION_SIMILARITY_THRESHOLD;
+ const queryTokens = tokenise(`${query.title} ${query.chosen ?? ""}`);
+ if (queryTokens.size === 0) return [];
+ const out: SimilarDecision[] = [];
+ for (const decision of listDecisions(vault)) {
+ if (query.excludeSlug !== undefined && decision.slug === query.excludeSlug) continue;
+ const tokens = tokenise(`${decision.title} ${decision.chosen}`);
+ const score = jaccard(queryTokens, tokens);
+ if (score < threshold) continue;
+ out.push({
+ slug: decision.slug,
+ id: decision.id,
+ title: decision.title,
+ chosen: decision.chosen,
+ outcome: decision.outcome,
+ jaccard: score,
+ });
+ }
+ out.sort((a, b) => b.jaccard - a.jaccard || a.slug.localeCompare(b.slug));
+ return opts.limit !== undefined ? out.slice(0, opts.limit) : out;
+}
diff --git a/src/core/brain/dream-plan.ts b/src/core/brain/dream-plan.ts
index 6aa8f6a3..11a95f22 100644
--- a/src/core/brain/dream-plan.ts
+++ b/src/core/brain/dream-plan.ts
@@ -19,6 +19,13 @@ export interface SignalRecord {
export interface PreferenceRecord {
readonly path: string;
readonly pref: BrainPreference;
+ /**
+ * Raw `superseded_by` frontmatter pointer (Belief lifecycle suite, A4).
+ * The typed parser drops it, so scanBrain captures it from raw
+ * frontmatter to drive accelerated decay of low-recall superseded
+ * ancestors. `null` when the memory is a chain tip.
+ */
+ readonly supersededBy: string | null;
}
export interface RetiredRecord {
@@ -143,6 +150,13 @@ export interface RetirePlan {
readonly principle: string;
readonly reason: BrainRetiredReason;
readonly supersededBy?: string;
+ /**
+ * Belief lifecycle suite (A4, t_d9365884): this retire fired on the
+ * accelerated chain-decay window (a low-recall superseded ancestor),
+ * i.e. it would not yet have retired under the normal stale window. The
+ * apply path emits a `chain-decay` event for these.
+ */
+ readonly chainDecay?: boolean;
}
export interface NotedRedundantPlan {
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 08ec4a96..f8d78c68 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -50,6 +50,13 @@ import { writePreferenceTxn } from "./preference-txn.ts";
import { appendLogEvent, type BrainLogEntry } from "./log.ts";
import { moveToRetired, parsePreference } from "./preference.ts";
import { parseSignal } from "./signal.ts";
+import { isTombstoned } from "./lifecycle/tombstone.ts";
+import { appendDecisionChangeReceipt } from "./decisions/receipts.ts";
+import {
+ CHAIN_DECAY_STALE_DAYS,
+ effectiveStaleThresholdDays,
+ isLowRecallSupersededAncestor,
+} from "./inject-governor.ts";
import { isPinned } from "./pin.ts";
import { createSnapshot, pruneSnapshots } from "./snapshot.ts";
import { loadBrainConfig, resolveGuardrails } from "./policy.ts";
@@ -506,6 +513,33 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
);
}
+ // Belief lifecycle suite (B4): the preference-confidence update path
+ // emits a decision-change receipt for each material confidence band
+ // change captured this pass. `bandDrops` is the existing, already-
+ // computed set of material weakenings (a band actually dropped), so
+ // this rides on data the refresh already produced without touching its
+ // byte-identical no-op guarantees. The receipt's idempotency key
+ // (subject + before + after) makes a re-run a no-op. Fail-soft.
+ for (const d of refresh.bandDrops) {
+ const before = `confidence:${d.previous}${d.previous_value !== null ? `(${d.previous_value.toFixed(2)})` : ""}`;
+ const after = `confidence:${d.next}(${d.next_value.toFixed(2)})`;
+ try {
+ appendDecisionChangeReceipt(vault, {
+ subject: d.id,
+ before,
+ after,
+ confidenceDelta: d.previous_value !== null ? d.next_value - d.previous_value : null,
+ actor: opts.agentName ?? "dream",
+ rationale: `applied ${d.applied} / violated ${d.violated}`,
+ reasonCode: "confidence-refresh",
+ ts: now.toISOString(),
+ });
+ } catch {
+ // Accountability mirror is best-effort; the refreshed preference
+ // bytes remain authoritative.
+ }
+ }
+
for (const r of plan.retires) {
const fromPath = preferencePath(vault, r.slug);
if (!existsSync(fromPath)) continue;
@@ -540,6 +574,19 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
retired_by: wikilinkToRun,
...(r.supersededBy ? { superseded_by: r.supersededBy } : {}),
});
+ // Belief lifecycle suite (A4): record the accelerated retirement of
+ // a low-recall superseded ancestor as a dedicated audit event.
+ if (r.chainDecay) {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.chainDecay,
+ body: {
+ preference: `[[ret-${r.slug}]]`,
+ reason: r.reason,
+ stale_days: String(CHAIN_DECAY_STALE_DAYS),
+ },
+ });
+ }
} catch (err) {
// A retire failure is logged via the `skip-corrupted-frontmatter`
// pathway only if it stemmed from a parse error during the
@@ -879,6 +926,9 @@ function scanBrain(vault: string): ScanResult {
for (const name of readdirSync(dirs.inbox)) {
if (!name.endsWith(".md")) continue;
const full = join(dirs.inbox, name);
+ // Belief lifecycle suite (t_7d5a3589): a tombstoned signal is
+ // excluded from the dream pass so it is never re-clustered.
+ if (isTombstoned(parseFrontmatter(full)[0])) continue;
try {
const sig = parseSignal(full);
signals.push({ path: full, signal: sig, active: true });
@@ -891,6 +941,7 @@ function scanBrain(vault: string): ScanResult {
for (const name of readdirSync(dirs.processed)) {
if (!name.endsWith(".md")) continue;
const full = join(dirs.processed, name);
+ if (isTombstoned(parseFrontmatter(full)[0])) continue;
try {
const sig = parseSignal(full);
signals.push({ path: full, signal: sig, active: false });
@@ -903,9 +954,18 @@ function scanBrain(vault: string): ScanResult {
for (const name of readdirSync(dirs.preferences)) {
if (!name.endsWith(".md")) continue;
const full = join(dirs.preferences, name);
+ const rawMeta = parseFrontmatter(full)[0];
+ if (isTombstoned(rawMeta)) continue;
+ // Belief lifecycle suite (A4): capture the raw superseded_by pointer
+ // (the typed parser drops it) so accelerated chain decay can see a
+ // temporally-superseded ancestor.
+ const supersededBy =
+ typeof rawMeta["superseded_by"] === "string" && rawMeta["superseded_by"] !== ""
+ ? (rawMeta["superseded_by"] as string)
+ : null;
try {
const pref = parsePreference(full);
- preferences.push({ path: full, pref });
+ preferences.push({ path: full, pref, supersededBy });
} catch {
corrupted.push({ path: full });
}
@@ -1381,6 +1441,16 @@ function planAutoRetires(
effectiveStatus === BRAIN_PREFERENCE_STATUS.confirmed ||
effectiveStatus === BRAIN_PREFERENCE_STATUS.quarantine
) {
+ // Belief lifecycle suite (A4): a low-recall superseded ancestor
+ // decays on the accelerated window so it leaves the working set
+ // faster than a live memory. Non-superseded / well-used prefs keep
+ // the normal window, so a vault with no chains is byte-identical.
+ const effectiveApplied = refreshed ? refreshed.applied_count : rec.pref.applied_count;
+ const chainDecay = isLowRecallSupersededAncestor({
+ supersededBy: rec.supersededBy,
+ appliedCount: effectiveApplied,
+ });
+ const staleDays = effectiveStaleThresholdDays(chainDecay, cfg.retire.stale_evidence_days);
if (!effectiveLastEvidence) {
// Confirmed with no evidence at all? Shouldn't happen, but
// gate on the same staleness rule using `confirmed_at`. We
@@ -1389,7 +1459,7 @@ function planAutoRetires(
const confirmedAt = refreshed ? refreshed.confirmed_at : rec.pref.confirmed_at;
if (!confirmedAt) continue;
const days = daysBetween(Date.parse(confirmedAt), now.getTime());
- if (days > cfg.retire.stale_evidence_days) {
+ if (days > staleDays) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
preference: renderPrefLink({
@@ -1403,6 +1473,7 @@ function planAutoRetires(
slug,
principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.staleNoEvidence,
+ ...(chainDecay ? { chainDecay: true } : {}),
});
refresh.updated.delete(slug);
}
@@ -1410,7 +1481,7 @@ function planAutoRetires(
continue;
}
const days = daysBetween(Date.parse(effectiveLastEvidence), now.getTime());
- if (days > cfg.retire.stale_evidence_days) {
+ if (days > staleDays) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
preference: renderPrefLink({
@@ -1424,6 +1495,7 @@ function planAutoRetires(
slug,
principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.staleNoEvidence,
+ ...(chainDecay ? { chainDecay: true } : {}),
});
refresh.updated.delete(slug);
}
diff --git a/src/core/brain/health/thesis.ts b/src/core/brain/health/thesis.ts
index 59f873a0..9d38472d 100644
--- a/src/core/brain/health/thesis.ts
+++ b/src/core/brain/health/thesis.ts
@@ -46,7 +46,8 @@ import { parseFrontmatter, slugify } from "../../vault.ts";
import { nextDueDate, parseCadence, type ObligationCadence } from "../obligations.ts";
import { thesesDir, thesisPath, validateIsoDate } from "../paths.ts";
import { isoDate, isoSecond } from "../time.ts";
-import { type BrainSignalSign } from "../types.ts";
+import { type BrainSignalSign, type BrainCommitmentTier } from "../types.ts";
+import { readCommitmentTier, validateCommitmentTier } from "../commitment.ts";
import {
DEFAULT_NEGATION_MARKERS,
deriveNoteStance,
@@ -84,6 +85,12 @@ export interface ThesisPage {
/** Last time supporting evidence landed, or null if never. */
readonly lastSupportAt: string | null;
readonly agent: string;
+ /**
+ * Optional commitment tier (Belief lifecycle suite, B3): how firmly the
+ * standing position is held. `null` when unset; round-trips through
+ * frontmatter, emitted only when set so unset theses stay byte-identical.
+ */
+ readonly commitment: BrainCommitmentTier | null;
readonly notes: string;
readonly path: string;
}
@@ -95,6 +102,8 @@ export interface RecordThesisInput {
readonly falsification?: string;
/** Review cadence; defaults to `monthly`. */
readonly cadence?: string;
+ /** Optional commitment tier (B3); validated on write. */
+ readonly commitment?: BrainCommitmentTier;
readonly agent: string;
readonly notes?: string;
/** Overrides `last_updated` (defaults to today, UTC). */
@@ -111,6 +120,8 @@ export interface UpdateThesisInput {
readonly counterEvidence?: string;
readonly falsification?: string;
readonly cadence?: string;
+ /** Optional commitment tier (B3); validated on write when supplied. */
+ readonly commitment?: BrainCommitmentTier;
readonly notes?: string;
readonly now?: Date;
}
@@ -177,11 +188,11 @@ function render(page: Omit<ThesisPage, "path">): string {
`last_updated: ${page.lastUpdated}`,
`last_support_at: ${page.lastSupportAt ?? ""}`,
`agent: ${JSON.stringify(page.agent)}`,
- "---",
- "",
- renderBody(page),
- "",
];
+ // Commitment tier (B3): emitted only when set so unset theses stay
+ // byte-identical to today.
+ if (page.commitment !== null) lines.push(`commitment: ${page.commitment}`);
+ lines.push("---", "", renderBody(page), "");
return lines.join("\n");
}
@@ -222,6 +233,7 @@ function parsePage(vault: string, slug: string): ThesisPage | null {
lastUpdated: parseIsoOrEmpty(meta["last_updated"]),
lastSupportAt: lastSupport.length > 0 ? lastSupport : null,
agent: typeof meta["agent"] === "string" ? meta["agent"] : "",
+ commitment: readCommitmentTier(meta),
notes: sections.get(SECTION_NOTES) ?? "",
path,
});
@@ -249,6 +261,7 @@ export function recordThesis(vault: string, input: RecordThesisInput): ThesisPag
lastUpdated: input.lastUpdated ? validateIsoDate(input.lastUpdated) : isoDate(now),
lastSupportAt: input.lastSupportAt ? validateIsoDate(input.lastSupportAt) : null,
agent: input.agent,
+ commitment: validateCommitmentTier(input.commitment),
notes: (input.notes ?? "").trim(),
};
mkdirSync(thesesDir(vault), { recursive: true });
@@ -280,6 +293,8 @@ export function updateThesis(vault: string, input: UpdateThesisInput): ThesisPag
lastUpdated: isoDate(now),
lastSupportAt: prior.lastSupportAt,
agent: prior.agent,
+ commitment:
+ input.commitment !== undefined ? validateCommitmentTier(input.commitment) : prior.commitment,
notes: input.notes !== undefined ? input.notes.trim() : prior.notes,
};
atomicWriteFileSync(prior.path, render(page));
diff --git a/src/core/brain/inject-governor.ts b/src/core/brain/inject-governor.ts
new file mode 100644
index 00000000..74309bdb
--- /dev/null
+++ b/src/core/brain/inject-governor.ts
@@ -0,0 +1,250 @@
+/**
+ * Injection governor (Belief lifecycle suite, A4, t_d9365884).
+ *
+ * The single helper that owns supersedes-chain consumer policy at the
+ * injection choke point: it prefers chain tips over their superseded
+ * ancestors so a chain of replacements injects only the current belief,
+ * and it names the deterministic thresholds the dream pass uses to retire
+ * low-recall superseded ancestors faster than live memories.
+ *
+ * Introduced here by the chain-policy unit; the rated-decision recall
+ * unit (B5) extends the same governor with per-session caps and spacing.
+ *
+ * Pure and language-agnostic: every chain/decay decision is structural
+ * (`superseded_by` presence, an integer recall count), never lexical.
+ * The B5 prompt-match is deterministic structural token overlap
+ * (`similarity.ts` jaccard) - no LLM, no language-specific word lists.
+ */
+
+import { jaccard, tokenise } from "./similarity.ts";
+
+// ----- Decay thresholds -----------------------------------------------------
+
+/**
+ * A superseded ancestor counts as low-recall when its `applied_count` is
+ * at or below this. Zero means "never actually used in real work": the
+ * safest ancestors to let the dream pass retire early.
+ */
+export const CHAIN_DECAY_LOW_RECALL_MAX_APPLIED = 0;
+
+/**
+ * Accelerated stale-evidence window (days) for a low-recall superseded
+ * ancestor. Deliberately short: once a belief is superseded and the
+ * ancestor was never load-bearing, it should fall out of the working set
+ * quickly rather than waiting out the full `retire.stale_evidence_days`.
+ */
+export const CHAIN_DECAY_STALE_DAYS = 7;
+
+// ----- Tip preference -------------------------------------------------------
+
+/** Minimal shape the governor needs to reason about a chain position. */
+export interface ChainCandidate {
+ readonly supersededBy?: string | null;
+}
+
+export interface PreferChainTipsOptions {
+ /**
+ * Keep the whole chain instead of collapsing to tips. This is the
+ * explicit historical flag - history is opt-in, never inferred from
+ * the query text.
+ */
+ readonly historical?: boolean;
+}
+
+export interface PreferChainTipsResult<T> {
+ /** Candidates to inject: chain tips plus every non-chain memory. */
+ readonly kept: T[];
+ /** Superseded ancestors dropped in favour of their tips. */
+ readonly dropped: T[];
+}
+
+/** True when a candidate carries a non-empty `superseded_by` pointer. */
+export function isSuperseded(candidate: ChainCandidate): boolean {
+ const value = candidate.supersededBy;
+ return typeof value === "string" && value.trim() !== "";
+}
+
+/**
+ * Prefer chain tips: drop any candidate that has been superseded so a
+ * chain injects only its live tip. A memory with no `superseded_by`
+ * pointer (the overwhelming common case) is always kept, so a vault with
+ * no supersession chains passes through byte-identically. The historical
+ * flag keeps the whole chain.
+ */
+export function preferChainTips<T extends ChainCandidate>(
+ candidates: ReadonlyArray<T>,
+ opts: PreferChainTipsOptions = {},
+): PreferChainTipsResult<T> {
+ if (opts.historical) return { kept: [...candidates], dropped: [] };
+ const kept: T[] = [];
+ const dropped: T[] = [];
+ for (const candidate of candidates) {
+ if (isSuperseded(candidate)) dropped.push(candidate);
+ else kept.push(candidate);
+ }
+ return { kept, dropped };
+}
+
+// ----- Decay acceleration ---------------------------------------------------
+
+export interface LowRecallSupersededInput {
+ readonly supersededBy?: string | null;
+ readonly appliedCount: number;
+}
+
+/**
+ * True when a memory is BOTH a superseded ancestor AND low-recall - the
+ * exact class the dream pass may retire on the accelerated window. A live
+ * (non-superseded) memory or a well-used ancestor is never accelerated.
+ */
+export function isLowRecallSupersededAncestor(
+ input: LowRecallSupersededInput,
+ opts: { readonly maxApplied?: number } = {},
+): boolean {
+ const maxApplied = opts.maxApplied ?? CHAIN_DECAY_LOW_RECALL_MAX_APPLIED;
+ return isSuperseded(input) && input.appliedCount <= maxApplied;
+}
+
+/**
+ * Resolve the effective stale-evidence window for a preference. An
+ * accelerated (low-recall superseded ancestor) memory uses the shorter of
+ * {@link CHAIN_DECAY_STALE_DAYS} and the vault's normal window, so
+ * acceleration can never make a memory retire SLOWER than today.
+ */
+export function effectiveStaleThresholdDays(accelerated: boolean, normalDays: number): number {
+ return accelerated ? Math.min(CHAIN_DECAY_STALE_DAYS, normalDays) : normalDays;
+}
+
+// ----- Rated-decision recall (B5, t_5712fa39) --------------------------------
+
+/**
+ * Minimum structural token overlap (jaccard of prompt tokens vs a rated
+ * decision's tokens) for a prompt to be treated as a match. Deterministic
+ * and language-agnostic - no LLM, no stopword list.
+ */
+export const DECISION_RECALL_MIN_OVERLAP = 0.2;
+
+/** One rated decision offered to the prompt matcher. */
+export interface RatedDecisionCandidate {
+ readonly id: string;
+ /** Rating in [1, 5]; higher ranks first on an overlap tie. */
+ readonly rating: number;
+ /** Verbatim text to match against (e.g. title + chosen). */
+ readonly text: string;
+}
+
+/** A prompt-match hit: which decision matched and how strongly. */
+export interface RatedDecisionMatch {
+ readonly id: string;
+ readonly rating: number;
+ readonly overlap: number;
+}
+
+/**
+ * Deterministically match a prompt against rated decisions by structural
+ * token overlap. Returns hits at or above `minOverlap`, ranked by
+ * descending overlap, then descending rating, then id (stable). Pure: no
+ * disk, no model, no language-specific vocabulary.
+ */
+export function matchRatedDecisions(
+ prompt: string,
+ candidates: ReadonlyArray<RatedDecisionCandidate>,
+ opts: { readonly minOverlap?: number } = {},
+): RatedDecisionMatch[] {
+ const minOverlap = opts.minOverlap ?? DECISION_RECALL_MIN_OVERLAP;
+ const promptTokens = tokenise(prompt);
+ if (promptTokens.size === 0) return [];
+ const out: RatedDecisionMatch[] = [];
+ for (const c of candidates) {
+ const overlap = jaccard(promptTokens, tokenise(c.text));
+ if (overlap < minOverlap) continue;
+ out.push({ id: c.id, rating: c.rating, overlap });
+ }
+ out.sort((a, b) => b.overlap - a.overlap || b.rating - a.rating || a.id.localeCompare(b.id));
+ return out;
+}
+
+/** Per-session caps + spacing for rated-decision recall. */
+export interface DecisionRecallConfig {
+ /**
+ * Maximum recalls per session. `null` DISABLES recall entirely - the
+ * governor surfaces nothing, so an unconfigured vault stays
+ * byte-identical.
+ */
+ readonly maxPerSession: number | null;
+ /** Minimum turns between two recalls. `0` means no spacing gate. */
+ readonly minSpacingTurns: number;
+}
+
+/** Session bookkeeping the governor threads across turns (caller-owned). */
+export interface DecisionRecallState {
+ /** Ids already surfaced this session (never re-surfaced). */
+ readonly surfacedIds: ReadonlyArray<string>;
+ /** Turn index of the most recent recall, or `null` when none yet. */
+ readonly lastTurn: number | null;
+ /** Total recalls surfaced this session. */
+ readonly count: number;
+}
+
+/** The zero state for a fresh session. */
+export const EMPTY_DECISION_RECALL_STATE: DecisionRecallState = Object.freeze({
+ surfacedIds: Object.freeze([]),
+ lastTurn: null,
+ count: 0,
+});
+
+export interface GovernDecisionRecallInput {
+ readonly matches: ReadonlyArray<RatedDecisionMatch>;
+ readonly state: DecisionRecallState;
+ /** Monotonic current turn index. */
+ readonly turn: number;
+ readonly config: DecisionRecallConfig;
+}
+
+export interface GovernDecisionRecallResult {
+ /** The single decision to resurface this turn, or `null` when gated. */
+ readonly surface: RatedDecisionMatch | null;
+ /** Next session state (advanced only when a decision was surfaced). */
+ readonly state: DecisionRecallState;
+}
+
+/**
+ * Apply per-session cap and spacing to a ranked match list, surfacing at
+ * most one new rated decision this turn. Gates, in order:
+ * 1. recall disabled (`maxPerSession === null`) -> surface nothing;
+ * 2. per-session cap reached -> surface nothing;
+ * 3. spacing: fewer than `minSpacingTurns` since the last recall ->
+ * surface nothing;
+ * 4. otherwise surface the top-ranked match not already surfaced.
+ * The returned state advances only when a decision is surfaced, so a
+ * gated turn leaves the state (and thus future gating) unchanged.
+ */
+export function governDecisionRecall(input: GovernDecisionRecallInput): GovernDecisionRecallResult {
+ const { config, state, turn, matches } = input;
+ if (config.maxPerSession === null || config.maxPerSession <= 0) {
+ return { surface: null, state };
+ }
+ if (state.count >= config.maxPerSession) {
+ return { surface: null, state };
+ }
+ if (
+ state.lastTurn !== null &&
+ config.minSpacingTurns > 0 &&
+ turn - state.lastTurn < config.minSpacingTurns
+ ) {
+ return { surface: null, state };
+ }
+ const already = new Set(state.surfacedIds);
+ const pick = matches.find((m) => !already.has(m.id));
+ if (pick === undefined) {
+ return { surface: null, state };
+ }
+ return {
+ surface: pick,
+ state: Object.freeze({
+ surfacedIds: Object.freeze([...state.surfacedIds, pick.id]),
+ lastTurn: turn,
+ count: state.count + 1,
+ }),
+ };
+}
diff --git a/src/core/brain/lifecycle/curator.ts b/src/core/brain/lifecycle/curator.ts
new file mode 100644
index 00000000..da44d521
--- /dev/null
+++ b/src/core/brain/lifecycle/curator.ts
@@ -0,0 +1,75 @@
+/**
+ * Curator read slices over observed-use verdicts (Belief lifecycle
+ * suite, Track A anchor, t_7d5a3589).
+ *
+ * A read-only projection that folds the session-end observed-use
+ * verdicts ({@link observedReuseRates}) into three actionable slices a
+ * curator uses to decide what to tombstone, resurface, or trust:
+ *
+ * - `injectedNeverUsed` - memories that were injected/observed but no
+ * transcript turn ever echoed them (all IGNORED). Retirement bait.
+ * - `contradicted` - memories a later turn structurally contradicted.
+ * - `highUsed` - memories echoed often enough to be load-bearing.
+ *
+ * Pure aggregation, no mutation. Language-agnostic: every input is a
+ * count already computed by the observed-use kernel.
+ */
+
+import { observedReuseRates, type ObservedReuse } from "../observed-use.ts";
+
+/**
+ * Default minimum USED-verdict count for a memory to count as
+ * high-used. A named constant rather than an inline literal; callers may
+ * override per call via {@link CuratorSlicesOptions.highUseMin}.
+ */
+export const CURATOR_HIGH_USE_MIN_DEFAULT = 3;
+
+/** One curator slice row: the artifact key plus its folded reuse stats. */
+export interface CuratorEntry {
+ /** Join key - vault-relative path when known, else the memory id. */
+ readonly key: string;
+ readonly reuse: ObservedReuse;
+}
+
+export interface CuratorSlices {
+ readonly injectedNeverUsed: ReadonlyArray<CuratorEntry>;
+ readonly contradicted: ReadonlyArray<CuratorEntry>;
+ readonly highUsed: ReadonlyArray<CuratorEntry>;
+}
+
+export interface CuratorSlicesOptions {
+ /** Minimum USED count for the high-used slice. Defaults to the constant. */
+ readonly highUseMin?: number;
+}
+
+/** Stable ordering: primary metric descending, then key ascending. */
+function byMetricThenKey(
+ metric: (e: CuratorEntry) => number,
+): (a: CuratorEntry, b: CuratorEntry) => number {
+ return (a, b) => metric(b) - metric(a) || a.key.localeCompare(b.key);
+}
+
+/**
+ * Compute the three curator slices from a vault's observed-use verdicts.
+ */
+export function curatorSlices(vault: string, opts: CuratorSlicesOptions = {}): CuratorSlices {
+ const highUseMin = opts.highUseMin ?? CURATOR_HIGH_USE_MIN_DEFAULT;
+ const rates = observedReuseRates(vault);
+
+ const injectedNeverUsed: CuratorEntry[] = [];
+ const contradicted: CuratorEntry[] = [];
+ const highUsed: CuratorEntry[] = [];
+
+ for (const [key, reuse] of rates) {
+ const entry: CuratorEntry = { key, reuse };
+ if (reuse.total > 0 && reuse.used === 0) injectedNeverUsed.push(entry);
+ if (reuse.contradicted > 0) contradicted.push(entry);
+ if (reuse.used >= highUseMin) highUsed.push(entry);
+ }
+
+ injectedNeverUsed.sort(byMetricThenKey((e) => e.reuse.ignored));
+ contradicted.sort(byMetricThenKey((e) => e.reuse.contradicted));
+ highUsed.sort(byMetricThenKey((e) => e.reuse.used));
+
+ return { injectedNeverUsed, contradicted, highUsed };
+}
diff --git a/src/core/brain/lifecycle/temporal-replace.ts b/src/core/brain/lifecycle/temporal-replace.ts
new file mode 100644
index 00000000..6caf2a52
--- /dev/null
+++ b/src/core/brain/lifecycle/temporal-replace.ts
@@ -0,0 +1,230 @@
+/**
+ * Atomic temporal fact-replacement (Belief lifecycle suite, A2,
+ * t_3ba9c404).
+ *
+ * One operation closes a predecessor fact (`valid_until = T`) and opens
+ * a successor fact (`valid_from = T`) at one shared instant, reusing
+ * `superseded_by` as the successor link. Intervals are half-open
+ * `[valid_from, valid_until)`: at exactly T the predecessor is no longer
+ * valid and the successor is, so point-in-time evaluation of the pair
+ * has no gap and no overlap. Date-only facts (`YYYY-MM-DD`) keep
+ * whole-day semantics - the boundary is a whole day, evaluated as its
+ * `T00:00:00Z` start.
+ *
+ * The pair is written atomically (both or neither): both files are
+ * validated and their new content computed before any write, and a
+ * failed second write rolls the first back to its captured bytes.
+ *
+ * This layer does NOT touch the existing conflict-resolution supersede
+ * in `hygiene/resolve-conflicts.ts`; it is a distinct, explicit
+ * operator/agent operation over bi-temporal validity fields.
+ *
+ * Import direction (design invariant): imports from `types.ts` and the
+ * shared vault/log helpers plus the sibling `tombstone.ts` link
+ * conventions, never the reverse.
+ */
+
+import { readFileSync } from "node:fs";
+import { relative } from "node:path";
+
+import { normalizeAgentArgument } from "../../agent-identity.ts";
+import { resolveAgentName } from "../../config.ts";
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import type { FrontmatterMap } from "../../types.ts";
+import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
+import { appendLogEvent } from "../log.ts";
+import { resolveNotePath } from "../note-path.ts";
+import { isoSecond } from "../time.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
+import { normalizeChainLink, SUPERSEDED_BY_KEY } from "./tombstone.ts";
+
+// ----- Constants ------------------------------------------------------------
+
+/** Frontmatter key: bi-temporal event-time start (inclusive). */
+export const VALID_FROM_KEY = "valid_from";
+/** Frontmatter key: bi-temporal event-time end (exclusive, half-open). */
+export const VALID_UNTIL_KEY = "valid_until";
+/** Date-only fact shape (whole-day validity). */
+const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
+/** Full ISO-8601 UTC instant shape. */
+const ISO_INSTANT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
+
+// ----- Errors ---------------------------------------------------------------
+
+/** Every failure path in this module raises this typed error. */
+export class TemporalReplaceError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "TemporalReplaceError";
+ }
+}
+
+// ----- Point-in-time evaluation ---------------------------------------------
+
+/** A bi-temporal fact's validity bounds, as stored in frontmatter. */
+export interface ValidityBounds {
+ readonly valid_from?: unknown;
+ readonly valid_until?: unknown;
+}
+
+/**
+ * Convert a stored boundary to a UTC-milliseconds instant. A date-only
+ * boundary (`YYYY-MM-DD`) resolves to that day's `T00:00:00Z` start so
+ * whole-day facts evaluate consistently against any probe within the
+ * day. Returns `null` for an absent or unparseable boundary.
+ */
+export function boundaryToMs(value: unknown): number | null {
+ if (typeof value !== "string" || value === "") return null;
+ const iso = DATE_ONLY_RE.test(value) ? `${value}T00:00:00Z` : value;
+ const ms = Date.parse(iso);
+ return Number.isNaN(ms) ? null : ms;
+}
+
+/**
+ * Evaluate whether a fact is valid at `probeMs` under half-open
+ * `[valid_from, valid_until)` semantics. An absent bound is unbounded on
+ * that side. `valid_from` is inclusive, `valid_until` exclusive - so two
+ * facts sharing a boundary T (predecessor `valid_until = T`, successor
+ * `valid_from = T`) never overlap at T and leave no gap around it.
+ */
+export function isValidAt(fact: ValidityBounds, probeMs: number): boolean {
+ const from = boundaryToMs(fact.valid_from);
+ const until = boundaryToMs(fact.valid_until);
+ if (from !== null && probeMs < from) return false;
+ if (until !== null && probeMs >= until) return false;
+ return true;
+}
+
+// ----- Replacement ----------------------------------------------------------
+
+interface NormalizedInstant {
+ /** The exact string stored on disk (date-only preserved verbatim). */
+ readonly stored: string;
+}
+
+function normalizeInstant(at: string | Date): NormalizedInstant {
+ if (at instanceof Date) {
+ if (Number.isNaN(at.getTime())) {
+ throw new TemporalReplaceError("temporalReplace: 'at' is an invalid Date");
+ }
+ return { stored: isoSecond(at) };
+ }
+ const value = at.trim();
+ if (DATE_ONLY_RE.test(value)) return { stored: value };
+ if (ISO_INSTANT_RE.test(value)) {
+ const ms = Date.parse(value);
+ if (Number.isNaN(ms)) {
+ throw new TemporalReplaceError(`temporalReplace: 'at' is not a valid instant: ${at}`);
+ }
+ // Canonicalize sub-second precision away to the log/heading shape.
+ return { stored: isoSecond(new Date(ms)) };
+ }
+ throw new TemporalReplaceError(
+ `temporalReplace: 'at' must be an ISO-8601 UTC instant or a YYYY-MM-DD date; got ${JSON.stringify(at)}`,
+ );
+}
+
+export interface TemporalReplaceInput {
+ readonly vault: string;
+ /** Vault-relative POSIX path of the predecessor fact being closed. */
+ readonly predecessor: string;
+ /** Vault-relative POSIX path of the successor fact being opened. */
+ readonly successor: string;
+ /** Shared instant T: ISO-8601 UTC instant or `YYYY-MM-DD` date. */
+ readonly at: string | Date;
+ readonly agent?: string;
+ readonly configPath?: string;
+}
+
+export interface TemporalReplaceResult {
+ /** The shared instant as stored on disk. */
+ readonly at: string;
+ /** Vault-relative predecessor path. */
+ readonly predecessor: string;
+ /** Vault-relative successor path. */
+ readonly successor: string;
+ readonly agent: string;
+ readonly loggedAt: string;
+}
+
+function relForVault(vault: string, absPath: string): string {
+ return relative(vault, absPath).split("\\").join("/");
+}
+
+/**
+ * Close the predecessor and open the successor at one shared instant.
+ * Writes both files atomically (both or neither) and logs one
+ * `temporal-replace` event.
+ */
+export function temporalReplace(input: TemporalReplaceInput): TemporalReplaceResult {
+ let absPred: string;
+ let absSucc: string;
+ try {
+ absPred = resolveNotePath(input.vault, input.predecessor, { mustExist: true });
+ absSucc = resolveNotePath(input.vault, input.successor, { mustExist: true });
+ } catch (err) {
+ throw new TemporalReplaceError(
+ `temporalReplace: a fact does not resolve inside the vault: ${(err as Error).message}`,
+ { cause: err },
+ );
+ }
+ if (absPred === absSucc) {
+ throw new TemporalReplaceError("temporalReplace: predecessor and successor must differ");
+ }
+
+ const relPred = relForVault(input.vault, absPred);
+ const relSucc = relForVault(input.vault, absSucc);
+ const { stored } = normalizeInstant(input.at);
+
+ const [predMeta, predBody] = parseFrontmatter(absPred);
+ const [succMeta, succBody] = parseFrontmatter(absSucc);
+ const successorLink = `[[${normalizeChainLink(input.successor)}]]`;
+
+ const predNext: FrontmatterMap = { ...(predMeta as FrontmatterMap) };
+ predNext[VALID_UNTIL_KEY] = stored;
+ predNext[SUPERSEDED_BY_KEY] = successorLink;
+
+ const succNext: FrontmatterMap = { ...(succMeta as FrontmatterMap) };
+ succNext[VALID_FROM_KEY] = stored;
+
+ // Capture original bytes so a failed second write can be rolled back:
+ // the pair is written atomically (both or neither).
+ const origPred = readFileSync(absPred, "utf8");
+ let predWritten = false;
+ try {
+ writeFrontmatterAtomic(absPred, predNext, predBody, { overwrite: true });
+ predWritten = true;
+ writeFrontmatterAtomic(absSucc, succNext, succBody, { overwrite: true });
+ } catch (err) {
+ if (predWritten) {
+ try {
+ atomicWriteFileSync(absPred, origPred);
+ } catch (restoreErr) {
+ throw new TemporalReplaceError(
+ `temporalReplace: successor write failed AND predecessor rollback failed for ${relPred}: ${(restoreErr as Error).message}`,
+ { cause: restoreErr },
+ );
+ }
+ }
+ throw new TemporalReplaceError(
+ `temporalReplace: failed to write the fact pair (${relPred} -> ${relSucc}): ${(err as Error).message}`,
+ { cause: err },
+ );
+ }
+
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+ const loggedAt = isoSecond(new Date());
+ appendLogEvent(input.vault, {
+ timestamp: loggedAt,
+ eventType: BRAIN_LOG_EVENT_KIND.temporalReplace,
+ body: {
+ predecessor: relPred,
+ successor: relSucc,
+ at: stored,
+ agent,
+ },
+ });
+
+ return { at: stored, predecessor: relPred, successor: relSucc, agent, loggedAt };
+}
diff --git a/src/core/brain/lifecycle/tombstone.ts b/src/core/brain/lifecycle/tombstone.ts
new file mode 100644
index 00000000..d731613b
--- /dev/null
+++ b/src/core/brain/lifecycle/tombstone.ts
@@ -0,0 +1,432 @@
+/**
+ * Cross-type tombstone + supersede lifecycle (Belief lifecycle suite,
+ * Track A anchor, t_7d5a3589).
+ *
+ * A memory of ANY type - preference, signal, learning note - can be
+ * tombstoned without deletion: the file gains `_status: tombstoned`,
+ * `tombstoned_at`, `tombstone_reason`, and (for a supersede) a
+ * `superseded_by` replacement pointer. The bytes stay on disk for
+ * audit; recall / inject / active.md / dream exclude tombstoned
+ * entries via {@link isTombstoned}.
+ *
+ * `supersede` is a tombstone that also records where the belief moved:
+ * the predecessor is tombstoned and pointed at its successor. A chain
+ * of supersessions is walked to its live tip by {@link resolveChainTip}.
+ *
+ * Idempotency: re-issuing a tombstone on an already-tombstoned file is a
+ * byte-identical no-op that returns the existing state and emits no
+ * event.
+ *
+ * Import direction (design invariant): this module imports from
+ * `preference.ts` / `types.ts` and the shared vault/log helpers, never
+ * the reverse.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join, relative } 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 { appendLogEvent } from "../log.ts";
+import { appendDecisionChangeReceipt } from "../decisions/receipts.ts";
+import { BRAIN_ROOT_REL } from "../paths.ts";
+import { resolveNotePath } from "../note-path.ts";
+import { isoSecond } from "../time.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_TOMBSTONE_STATUS } from "../types.ts";
+
+// ----- Constants ------------------------------------------------------------
+
+/** On-disk frontmatter key holding a memory's operational status. */
+export const LIFECYCLE_STATUS_KEY = "_status";
+/** Normalized (un-prefixed) status key produced by `normalizeDerivedKeys`. */
+export const LIFECYCLE_STATUS_KEY_NORMALIZED = "status";
+/** Frontmatter key: ISO-8601 UTC second the tombstone was applied. */
+export const TOMBSTONED_AT_KEY = "tombstoned_at";
+/** Frontmatter key: operator-supplied tombstone reason. */
+export const TOMBSTONE_REASON_KEY = "tombstone_reason";
+/** Frontmatter key: wikilink to the successor that replaced this entry. */
+export const SUPERSEDED_BY_KEY = "superseded_by";
+/** Default reason stamped when a supersede does not pass an explicit one. */
+export const SUPERSEDE_DEFAULT_REASON = "superseded";
+/** Cap on tombstone-reason length (mirrors the note-text field cap). */
+const REASON_MAX_LEN = 512;
+/**
+ * Hard cap on chain-walk depth. Guards against a pathological or
+ * cyclic `superseded_by` graph turning {@link resolveChainTip} into an
+ * unbounded loop; far beyond any realistic supersession depth.
+ */
+export const MAX_CHAIN_DEPTH = 64;
+
+// ----- Errors ---------------------------------------------------------------
+
+/** Every failure path in this module raises this typed error. */
+export class TombstoneError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "TombstoneError";
+ }
+}
+
+// ----- Lifecycle state ------------------------------------------------------
+
+export interface LifecycleState {
+ readonly tombstoned: boolean;
+ /** ISO-8601 UTC second, or `null` when not tombstoned. */
+ readonly tombstonedAt: string | null;
+ readonly tombstoneReason: string | null;
+ /** Normalized successor wikilink (`[[...]]`), or `null`. */
+ readonly supersededBy: string | null;
+}
+
+function scalar(meta: Readonly<Record<string, unknown>>, key: string): string | null {
+ const value = meta[key];
+ return typeof value === "string" && value !== "" ? value : null;
+}
+
+/**
+ * Read the lifecycle state carried by a raw frontmatter map (the output
+ * of {@link parseFrontmatter}). Tolerant of both the `_status` on-disk
+ * shape and the normalized `status` shape so it works whether the caller
+ * passed raw or `normalizeDerivedKeys`-processed frontmatter.
+ */
+export function readLifecycleState(meta: Readonly<Record<string, unknown>>): LifecycleState {
+ const status =
+ scalar(meta, LIFECYCLE_STATUS_KEY) ?? scalar(meta, LIFECYCLE_STATUS_KEY_NORMALIZED);
+ const tombstoned = status === BRAIN_TOMBSTONE_STATUS;
+ return {
+ tombstoned,
+ tombstonedAt: scalar(meta, TOMBSTONED_AT_KEY),
+ tombstoneReason: scalar(meta, TOMBSTONE_REASON_KEY),
+ supersededBy: scalar(meta, SUPERSEDED_BY_KEY),
+ };
+}
+
+/**
+ * True when a raw frontmatter map marks a tombstoned memory. This is the
+ * shared exclusion predicate wired into recall / inject / active.md /
+ * dream so a tombstoned (or superseded-non-tip, which is tombstoned with
+ * a `superseded_by` pointer) entry stops appearing.
+ */
+export function isTombstoned(meta: Readonly<Record<string, unknown>>): boolean {
+ return readLifecycleState(meta).tombstoned;
+}
+
+// ----- Link normalization ---------------------------------------------------
+
+/**
+ * Reduce a wikilink / bare id / basename to its bare identifier: strip
+ * the `[[ ]]` fence and any `|alias` display suffix, then the `.md`
+ * extension and directory components. Returns the trimmed identifier.
+ */
+export function normalizeChainLink(raw: string): string {
+ let value = raw.trim();
+ const fence = /^\[\[([^\]]+)\]\]$/.exec(value);
+ if (fence) value = fence[1]!.trim();
+ const pipe = value.indexOf("|");
+ if (pipe >= 0) value = value.slice(0, pipe).trim();
+ // Drop directory components and the markdown extension so a stored
+ // vault-relative path and a bare basename resolve to the same node.
+ const slash = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
+ if (slash >= 0) value = value.slice(slash + 1);
+ if (value.toLowerCase().endsWith(".md")) value = value.slice(0, -3);
+ return value;
+}
+
+/** Render a bare identifier as a canonical wikilink for on-disk storage. */
+function toWikilink(raw: string): string {
+ return `[[${normalizeChainLink(raw)}]]`;
+}
+
+// ----- Tombstone / supersede ------------------------------------------------
+
+export interface TombstoneInput {
+ readonly vault: string;
+ /** Vault-relative POSIX path of the target memory file. */
+ readonly path: string;
+ /** Operator-facing reason. Required, non-empty after trim. */
+ readonly reason: string;
+ /** Optional successor id / wikilink stored as `superseded_by`. */
+ readonly supersededBy?: string;
+ /** Identity override; resolver default used when omitted or blank. */
+ readonly agent?: string;
+ /** Wall clock for the timestamps. Defaults to `new Date()`. */
+ readonly now?: Date;
+ /** Config path for `resolveAgentName`. Optional. */
+ readonly configPath?: string;
+}
+
+export interface TombstoneResult {
+ /** `false` when the file was already tombstoned (no-op). */
+ readonly changed: boolean;
+ /** Vault-relative POSIX path of the target. */
+ readonly path: string;
+ readonly state: LifecycleState;
+ /** Identity written into the log entry (only when `changed`). */
+ readonly agent?: string;
+ /** ISO-8601 UTC second of the emitted event (only when `changed`). */
+ readonly loggedAt?: string;
+}
+
+function relForVault(vault: string, absPath: string): string {
+ return relative(vault, absPath).split("\\").join("/");
+}
+
+/**
+ * Tombstone a memory of any type in place. Sets `_status: tombstoned`
+ * plus `tombstoned_at` / `tombstone_reason` (and `superseded_by` when a
+ * successor is supplied), preserving the body and all other frontmatter.
+ * Idempotent: an already-tombstoned file is left byte-identical and the
+ * existing state is returned with `changed: false`.
+ */
+export function tombstone(input: TombstoneInput): TombstoneResult {
+ const reason = sanitiseTextField(input.reason, {
+ maxLen: REASON_MAX_LEN,
+ singleLine: true,
+ }).trim();
+ if (!reason) {
+ throw new TombstoneError("tombstone: reason is required");
+ }
+
+ let abs: string;
+ try {
+ abs = resolveNotePath(input.vault, input.path, { mustExist: true });
+ } catch (err) {
+ throw new TombstoneError(
+ `tombstone: target does not resolve inside the vault: ${(err as Error).message}`,
+ { cause: err },
+ );
+ }
+
+ const relPath = relForVault(input.vault, abs);
+ const [rawMeta, body] = parseFrontmatter(abs);
+
+ const existing = readLifecycleState(rawMeta);
+ if (existing.tombstoned) {
+ // Idempotent no-op: never rewrite, never log.
+ return { changed: false, path: relPath, state: existing };
+ }
+
+ const priorStatus =
+ scalar(rawMeta, LIFECYCLE_STATUS_KEY) ??
+ scalar(rawMeta, LIFECYCLE_STATUS_KEY_NORMALIZED) ??
+ "unknown";
+ const tombstonedAt = isoSecond(input.now ?? new Date());
+ const supersededBy = input.supersededBy ? toWikilink(input.supersededBy) : null;
+
+ const nextMeta: FrontmatterMap = { ...(rawMeta as FrontmatterMap) };
+ nextMeta[LIFECYCLE_STATUS_KEY] = BRAIN_TOMBSTONE_STATUS;
+ nextMeta[TOMBSTONED_AT_KEY] = tombstonedAt;
+ nextMeta[TOMBSTONE_REASON_KEY] = reason;
+ if (supersededBy !== null) nextMeta[SUPERSEDED_BY_KEY] = supersededBy;
+
+ try {
+ writeFrontmatterAtomic(abs, nextMeta, body, { overwrite: true });
+ } catch (err) {
+ throw new TombstoneError(`tombstone: failed to write ${relPath}: ${(err as Error).message}`, {
+ cause: err,
+ });
+ }
+
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+ appendLogEvent(input.vault, {
+ timestamp: tombstonedAt,
+ eventType: BRAIN_LOG_EVENT_KIND.tombstone,
+ body: {
+ path: relPath,
+ reason,
+ prior_status: priorStatus,
+ ...(supersededBy !== null ? { superseded_by: supersededBy } : {}),
+ agent,
+ },
+ });
+
+ // Belief lifecycle suite (B4): a supersede/tombstone is a belief change,
+ // so it emits a decision-change receipt. The receipt's own idempotency
+ // key (subject + before + after) makes a replay a no-op, mirroring the
+ // tombstone no-op above. Fail-soft: an accountability-log hiccup must
+ // never fail the tombstone write itself.
+ try {
+ appendDecisionChangeReceipt(input.vault, {
+ subject: relPath,
+ before: `status:${priorStatus}`,
+ after:
+ supersededBy !== null
+ ? `status:tombstoned superseded_by:${supersededBy}`
+ : "status:tombstoned",
+ actor: agent,
+ rationale: reason,
+ reasonCode: supersededBy !== null ? "supersede" : "tombstone",
+ ...(supersededBy !== null ? { alternatives: [priorStatus] } : {}),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+ } catch {
+ // Receipt is best-effort accountability; the tombstone frontmatter and
+ // its `tombstone` log event remain authoritative.
+ }
+
+ return {
+ changed: true,
+ path: relPath,
+ state: {
+ tombstoned: true,
+ tombstonedAt,
+ tombstoneReason: reason,
+ supersededBy,
+ },
+ agent,
+ loggedAt: tombstonedAt,
+ };
+}
+
+export interface SupersedeInput {
+ readonly vault: string;
+ /** Vault-relative POSIX path of the predecessor being replaced. */
+ readonly predecessor: string;
+ /** Successor id / wikilink that supersedes the predecessor. */
+ readonly successor: string;
+ /** Optional reason; defaults to {@link SUPERSEDE_DEFAULT_REASON}. */
+ readonly reason?: string;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+/**
+ * Supersede a predecessor with a successor: tombstone the predecessor and
+ * record the replacement pointer. Thin wrapper over {@link tombstone}.
+ */
+export function supersede(input: SupersedeInput): TombstoneResult {
+ const successor = input.successor.trim();
+ if (!successor) {
+ throw new TombstoneError("supersede: successor is required");
+ }
+ return tombstone({
+ vault: input.vault,
+ path: input.predecessor,
+ reason: input.reason ?? SUPERSEDE_DEFAULT_REASON,
+ supersededBy: successor,
+ ...(input.agent !== undefined ? { agent: input.agent } : {}),
+ ...(input.now !== undefined ? { now: input.now } : {}),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+}
+
+// ----- Chain resolution -----------------------------------------------------
+
+export interface ChainLookupEntry {
+ /** Successor wikilink / id, or `null` when this node is a tip. */
+ readonly supersededBy: string | null;
+}
+
+/** Resolve a normalized node id to its chain entry, or `null` if unknown. */
+export type ChainLookup = (link: string) => ChainLookupEntry | null;
+
+export interface ResolveChainTipResult {
+ /** Normalized identifier of the resolved tip. */
+ readonly tip: string;
+ /** Number of successor hops walked from the start. */
+ readonly steps: number;
+ /** True when a cycle short-circuited the walk. */
+ readonly cycle: boolean;
+ /**
+ * True when every hop resolved to a known node. `false` when the walk
+ * stopped at an id the lookup could not resolve (dangling successor).
+ */
+ readonly resolvedAll: boolean;
+}
+
+/**
+ * Walk a chain of `superseded_by` links from `start` to its live tip.
+ * Pure: the caller supplies the {@link ChainLookup}, so this is unit- and
+ * property-testable without disk. Cycle- and depth-guarded.
+ */
+export function resolveChainTip(
+ start: string,
+ lookup: ChainLookup,
+ opts: { readonly maxDepth?: number } = {},
+): ResolveChainTipResult {
+ const maxDepth = opts.maxDepth ?? MAX_CHAIN_DEPTH;
+ const visited = new Set<string>();
+ let current = normalizeChainLink(start);
+ let steps = 0;
+ visited.add(current);
+
+ while (steps < maxDepth) {
+ const entry = lookup(current);
+ if (entry === null) {
+ // Reached an id the lookup cannot resolve (unknown start or a
+ // dangling successor): the walk stops at the last known node.
+ return { tip: current, steps, cycle: false, resolvedAll: false };
+ }
+ if (entry.supersededBy === null || entry.supersededBy === "") {
+ return { tip: current, steps, cycle: false, resolvedAll: true };
+ }
+ const next = normalizeChainLink(entry.supersededBy);
+ if (visited.has(next)) {
+ return { tip: current, steps, cycle: true, resolvedAll: true };
+ }
+ visited.add(next);
+ current = next;
+ steps++;
+ }
+ // Depth cap reached without terminating: treat as a pathological chain.
+ return { tip: current, steps, cycle: true, resolvedAll: true };
+}
+
+/**
+ * Build a {@link ChainLookup} over every markdown file under `Brain/`,
+ * keyed by bare basename. Reads each file's frontmatter once. A node
+ * that exists but carries no `superseded_by` resolves to a tip entry;
+ * an unknown basename resolves to `null`.
+ */
+export function buildChainLookup(vault: string): ChainLookup {
+ const index = new Map<string, ChainLookupEntry>();
+ const root = join(vault, BRAIN_ROOT_REL);
+ if (existsSync(root)) walk(root, index);
+ return (link: string): ChainLookupEntry | null => index.get(normalizeChainLink(link)) ?? null;
+}
+
+function walk(dir: string, index: Map<string, ChainLookupEntry>): void {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name.startsWith(".")) continue;
+ walk(full, index);
+ continue;
+ }
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
+ let meta: FrontmatterMap;
+ try {
+ [meta] = parseFrontmatter(full);
+ } catch {
+ continue;
+ }
+ const id = normalizeChainLink(entry.name);
+ const supersededBy = scalar(meta, SUPERSEDED_BY_KEY);
+ index.set(id, { supersededBy });
+ }
+}
+
+/**
+ * Convenience: resolve a chain tip against the live vault. Builds the
+ * lookup from disk on each call - callers that resolve many tips in one
+ * pass should reuse a {@link buildChainLookup} result via
+ * {@link resolveChainTip} directly.
+ */
+export function resolveChainTipInVault(
+ vault: string,
+ start: string,
+ opts: { readonly maxDepth?: number } = {},
+): ResolveChainTipResult {
+ return resolveChainTip(start, buildChainLookup(vault), opts);
+}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 0948b063..57c49614 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -56,6 +56,9 @@ export const BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");
export const BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");
/** Declared-thesis register pages: `Brain/theses/thesis-<slug>.md` (D3). */
export const BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");
+export const BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");
+/** Persisted contradiction (tension) notes: `Brain/tensions/tension-<slug>.md` (S2). */
+export const BRAIN_TENSIONS_REL = posix.join(BRAIN_ROOT_REL, "tensions");
export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, "log");
export const BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");
/** Obsidian Bases view definitions: `Brain/bases/<view>.base` (v1.15.0). */
@@ -81,10 +84,17 @@ export const BRAIN_ACTIVE_FILE = "active.md";
export const BRAIN_LESSONS_FILE = "lessons.md";
export const BRAIN_PINNED_FILE = "pinned.md";
export const BRAIN_INDEX_FILE = "_INDEX.md";
+/** Persisted claim-graph projection artifact (Belief lifecycle suite, A3). */
+export const BRAIN_CLAIM_GRAPH_FILE = "claim-graph.json";
/** Vault-relative path of the `o2b index` output file. */
export const BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);
+/** Path of the persisted claim-graph projection: `Brain/claim-graph.json`. */
+export function claimGraphPath(vault: string): string {
+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_CLAIM_GRAPH_FILE), vault);
+}
+
const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
// Run IDs follow `dream-<YYYY-MM-DD>-<HHMMSS>`; we accept the same generic
@@ -299,6 +309,28 @@ export function thesisPath(vault: string, slug: string): string {
return ensureInsideVault(join(vault, BRAIN_THESES_REL, `thesis-${s}.md`), vault);
}
+/** Decision-record note-family dir: `Brain/decisions/`. */
+export function decisionsDir(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_DECISIONS_REL), vault);
+}
+
+/** A single decision page: `Brain/decisions/decision-<slug>.md`. */
+export function decisionPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_DECISIONS_REL, `decision-${s}.md`), vault);
+}
+
+/** Persisted-contradiction note-family dir: `Brain/tensions/` (S2). */
+export function tensionsDir(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_TENSIONS_REL), vault);
+}
+
+/** A single tension page: `Brain/tensions/tension-<slug>.md` (S2). */
+export function tensionPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_TENSIONS_REL, `tension-${s}.md`), vault);
+}
+
/** Proposal scan watermark path: `Brain/procedural-memory/proposal-watermark.json`. */
export function proposalWatermarkPath(vault: string): string {
return ensureInsideVault(
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 3e8ea8d9..1785ebd0 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -54,6 +54,7 @@ import {
BRAIN_MEMORY_LAYER,
BRAIN_PREFERENCE_STATUS,
BRAIN_RETIRED_REASON,
+ BRAIN_TOMBSTONE_STATUS,
type BrainConfidence,
type BrainEvidenceSummary,
type BrainMemoryLayer,
@@ -61,8 +62,10 @@ import {
type BrainPreferenceStatus,
type BrainRetired,
type BrainRetiredReason,
+ type BrainCommitmentTier,
isBrainMemoryLayer,
} from "./types.ts";
+import { readCommitmentTier, validateCommitmentTier } from "./commitment.ts";
import type { PageLifecycle } from "./page-meta/lifecycle.ts";
import type { PageTier } from "./page-meta/tier.ts";
import { computeContentHash } from "./content-hash.ts";
@@ -150,6 +153,13 @@ export interface WritePreferenceInput {
* only when supplied so legacy fixtures stay byte-identical.
*/
readonly tier?: PageTier;
+ /**
+ * Optional commitment tier (Belief lifecycle suite, B3, t_e112c63c):
+ * `exploring | leaning | decided | locked`. User-editable, unprefixed
+ * in YAML. Validated on write; emitted only when supplied so legacy
+ * fixtures stay byte-identical.
+ */
+ readonly commitment?: BrainCommitmentTier;
readonly pinned?: boolean;
/**
* Directional freshness trend (Time-Aware Recall & Activation Suite,
@@ -550,6 +560,12 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma
if (input.tier !== undefined) {
metadata["tier"] = input.tier;
}
+ // `commitment` tier (B3): validated on write, emitted only when a valid
+ // tier is supplied so unset preferences stay byte-identical.
+ const commitment = validateCommitmentTier(input.commitment);
+ if (commitment !== null) {
+ metadata["commitment"] = commitment;
+ }
// Brain lifecycle suite (F5): bi-temporal validity, emitted only when
// supplied (e.g. dream filled it from the source signal's ISO text).
// Reader-side support already exists via readBitemporalSlots; legacy
@@ -734,7 +750,12 @@ export function parsePreference(
// status-folder-mismatch the parser surfaces below as a typed error
// (doctor downgrades it to a warning) β€” see Β§4 of the design doc.
const statusValues = Object.values(BRAIN_PREFERENCE_STATUS) as ReadonlyArray<string>;
- if (!statusValues.includes(status) && status !== "retired") {
+ // `tombstoned` (Belief lifecycle suite, t_7d5a3589) is a cross-type
+ // lifecycle status the tombstone module stamps into `_status` in place.
+ // It is tolerated on read - like `retired` - so an audit read and the
+ // doctor see a coherent tombstoned entry rather than a corrupt file;
+ // recall / inject / active.md / dream exclude it via `isTombstoned`.
+ if (!statusValues.includes(status) && status !== "retired" && status !== BRAIN_TOMBSTONE_STATUS) {
throw new Error(
`preference status must be one of ${statusValues.join(", ")}; got ${JSON.stringify(status)} (${path})`,
);
@@ -791,6 +812,7 @@ export function parsePreference(
...(optionalScalarString(meta, "supersedes") !== undefined
? { supersedes: optionalScalarString(meta, "supersedes") }
: {}),
+ ...(readCommitmentTier(meta) !== null ? { commitment: readCommitmentTier(meta)! } : {}),
...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])
? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }
: {}),
@@ -1218,7 +1240,10 @@ function enforceStatusFolderInvariant(
parent === "preferences" &&
status !== BRAIN_PREFERENCE_STATUS.unconfirmed &&
status !== BRAIN_PREFERENCE_STATUS.confirmed &&
- status !== BRAIN_PREFERENCE_STATUS.quarantine
+ status !== BRAIN_PREFERENCE_STATUS.quarantine &&
+ // A tombstoned preference stays in `preferences/` for audit; the
+ // lifecycle module marks it in place rather than moving the file.
+ status !== BRAIN_TOMBSTONE_STATUS
) {
throw new BrainStatusFolderMismatchError(
"preference file frontmatter status does not match preferences/ folder",
diff --git a/src/core/brain/query.ts b/src/core/brain/query.ts
index 00494dbe..3cc048dd 100644
--- a/src/core/brain/query.ts
+++ b/src/core/brain/query.ts
@@ -35,6 +35,8 @@ import type { BrainLogEntry } from "./log.ts";
import { listLogDates, readLogDay } from "./log-jsonl.ts";
import { parsePreference, parseRetired } from "./preference.ts";
import { parseSignal } from "./signal.ts";
+import { isTombstoned } from "./lifecycle/tombstone.ts";
+import { parseFrontmatter } from "../vault.ts";
import { normaliseWikilinkTarget } from "./wikilink.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
import type { BrainPreference, BrainRetired, BrainSignal } from "./types.ts";
@@ -318,9 +320,13 @@ function collectSignals(dir: string, topic: string, out: BrainSignal[]): void {
if (!entry.name.startsWith("sig-") || !entry.name.endsWith(".md")) {
continue;
}
+ const path = join(dir, entry.name);
+ // Belief lifecycle suite (t_7d5a3589): a tombstoned signal is
+ // excluded from recall.
+ if (isTombstoned(parseFrontmatter(path)[0])) continue;
let sig: BrainSignal;
try {
- sig = parseSignal(join(dir, entry.name));
+ sig = parseSignal(path);
} catch {
// Corrupted frontmatter is the doctor's concern; queries skip.
continue;
@@ -350,6 +356,9 @@ function findPreferenceForTopic(
continue;
}
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;
try {
const parsed = kind === "preference" ? parsePreference(path) : parseRetired(path);
if (parsed.topic === topic) return parsed;
diff --git a/src/core/brain/session-recall.ts b/src/core/brain/session-recall.ts
index 5f77296c..63f6bfa4 100644
--- a/src/core/brain/session-recall.ts
+++ b/src/core/brain/session-recall.ts
@@ -30,6 +30,17 @@ export interface SessionRecallSearchInput {
readonly sessionId?: string;
readonly limit?: number;
readonly snippetChars?: number;
+ /**
+ * Conversation-chronology time bounds (S1 / t_347e8224). Inclusive
+ * unix-ms lower / upper bounds on a record's effective instant (its
+ * turn `timestamp`, falling back to `createdAt`). A record whose
+ * instant falls outside the range is excluded; a record with no
+ * parseable instant is kept only when no bound is set. Absent bounds β†’
+ * byte-identical to the pre-feature unbounded search. Callers parse
+ * `since` / `before` strings through `time-range.ts` before calling.
+ */
+ readonly sinceMs?: number;
+ readonly untilMs?: number;
}
export interface SessionRecallHit {
@@ -150,6 +161,7 @@ export function searchSessionRecall(
const limit = Math.max(1, input.limit ?? DEFAULT_LIMIT);
const snippetChars = Math.max(1, input.snippetChars ?? DEFAULT_SNIPPET_CHARS);
const hits = sessionRecallRecords(vault, input.sessionId)
+ .filter((record) => recordInTimeRange(record, input.sinceMs, input.untilMs))
.map((record) => hitFor(record, needle, snippetChars))
.filter((hit): hit is SessionRecallHit => hit !== null)
.sort((left, right) => right.score - left.score || left.id.localeCompare(right.id))
@@ -557,6 +569,28 @@ function occurrenceCount(text: string, needle: string): number {
return count;
}
+/**
+ * Whether a record's effective instant falls within the inclusive
+ * `[sinceMs, untilMs]` bounds (conversation chronology, S1). The instant
+ * is the turn `timestamp`, falling back to the record `createdAt` (the
+ * same precedence `compareRecords` uses). A record with no parseable
+ * instant is kept only when no bound is set - a bounded query is a
+ * deliberate time filter, so an undatable record cannot silently pass it.
+ */
+function recordInTimeRange(
+ record: ContinuityRecord,
+ sinceMs: number | undefined,
+ untilMs: number | undefined,
+): boolean {
+ if (sinceMs === undefined && untilMs === undefined) return true;
+ const raw = String(record.payload["timestamp"] ?? record.createdAt);
+ const ms = Date.parse(raw);
+ if (!Number.isFinite(ms)) return false;
+ if (sinceMs !== undefined && ms < sinceMs) return false;
+ if (untilMs !== undefined && ms > untilMs) return false;
+ return true;
+}
+
function compareRecords(left: ContinuityRecord, right: ContinuityRecord): number {
const leftTimestamp = String(left.payload["timestamp"] ?? left.createdAt);
const rightTimestamp = String(right.payload["timestamp"] ?? right.createdAt);
diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.ts
index 5461590c..f626a011 100644
--- a/src/core/brain/sessions/import.ts
+++ b/src/core/brain/sessions/import.ts
@@ -279,7 +279,16 @@ export async function importSession(
created_at: isoSecond(instant),
date: isoDate(instant),
slug: input.topic,
- ...(fromTurn ? { recorded_at: isoSecond(instant), valid_from: isoSecond(instant) } : {}),
+ ...(fromTurn
+ ? {
+ recorded_at: isoSecond(instant),
+ valid_from: isoSecond(instant),
+ // Conversation chronology (S1): carry the turn instant as
+ // the authoring time so the search layer can expose it and
+ // break exact hybrid-score ties toward more recent turns.
+ authored_at: isoSecond(instant),
+ }
+ : {}),
...(input.scope ? { scope: input.scope } : {}),
source: [`[[${sessionRef}]]`],
source_type: BRAIN_SIGNAL_SOURCE_TYPE.session,
diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.ts
index 488d8371..d385b726 100644
--- a/src/core/brain/signal.ts
+++ b/src/core/brain/signal.ts
@@ -113,6 +113,16 @@ export interface WriteSignalInput {
*/
readonly valid_from?: string;
readonly recorded_at?: string;
+ /**
+ * Conversation-chronology authoring instant (S1 / t_347e8224). The
+ * transcript turn instant a session-imported signal was authored at,
+ * carried from `resolveEventInstant`. Additive and optional: absent β†’
+ * the written file is byte-identical to the historical path. Stamped
+ * alongside `valid_from` / `recorded_at` when the import preserves the
+ * turn's original event-time, so the search layer can expose it and
+ * break exact hybrid-score ties toward more recent statements.
+ */
+ readonly authored_at?: string;
/**
* Caller-settable expiration (C5 / t_a82b674e). ISO date
* (`YYYY-MM-DD`) or full timestamp. Additive and optional: absent β†’
@@ -350,6 +360,11 @@ export function writeSignal(
if (sanitised.recorded_at && sanitised.recorded_at.trim()) {
metadata["recorded_at"] = sanitised.recorded_at.trim();
}
+ // Conversation-chronology authoring instant (S1). Emitted only when
+ // supplied, so legacy / live / non-turn writes stay byte-identical.
+ if (sanitised.authored_at && sanitised.authored_at.trim()) {
+ metadata["authored_at"] = sanitised.authored_at.trim();
+ }
// Caller-settable expiration (C5): validated + emitted only when
// supplied so legacy / live writes stay byte-identical. Reader-side
// support is via parseSignal's optional read + the expiration filter.
diff --git a/src/core/brain/tensions.ts b/src/core/brain/tensions.ts
new file mode 100644
index 00000000..62b20d56
--- /dev/null
+++ b/src/core/brain/tensions.ts
@@ -0,0 +1,704 @@
+/**
+ * Tension objects: persisted contradiction lifecycle (Belief lifecycle
+ * suite, S2, t_0e3f2bee).
+ *
+ * A detected contradiction is a fleeting finding today - the semantic
+ * health detectors surface it and it silently re-fires on the next pass.
+ * A tension object gives that finding a durable home: a Markdown note
+ * under `Brain/tensions/tension-<slug>.md` whose `_status` walks a small
+ * state machine `open -> confirmed | dismissed | resolved`. The slug is
+ * derived from a deterministic DEDUP KEY (the subject pair plus the
+ * stance signature), so re-detecting the same contradiction UPDATES the
+ * existing note in place instead of spawning a duplicate.
+ *
+ * This module CONSUMES the existing contradiction detector
+ * (`health/contradiction.ts` - {@link detectNoteContradictions}); it does
+ * not re-implement detection. The dedup key is built purely from
+ * structural signals (ids + derived stance signs), so it stays
+ * language-agnostic and identical on every Syncthing peer.
+ *
+ * Injection-time warning: {@link tensionWarningsForContextItems} lets the
+ * context-pack builder flag when it is about to inject a memory that is a
+ * subject of an UNRESOLVED (open or confirmed) tension. Dismissed and
+ * resolved tensions warn about nothing.
+ *
+ * Import direction: this module imports from health/contradiction /
+ * paths / log / vault helpers, never the reverse.
+ */
+
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readdirSync } from "node:fs";
+
+import { normalizeAgentArgument } from "../agent-identity.ts";
+import { resolveAgentName } from "../config.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { sanitiseTextField } from "../redactor.ts";
+import { parseFrontmatter } from "../vault.ts";
+import {
+ detectNoteContradictions,
+ type DetectNoteContradictionsOptions,
+ type NoteContradictionFinding,
+ type NoteForContradiction,
+} from "./health/contradiction.ts";
+import { appendLogEvent } from "./log.ts";
+import { buildNoteWalkRules, resolveNoteRoots, walkMarkdownFiles } from "./notes/note-walk.ts";
+import { tensionPath, tensionsDir } from "./paths.ts";
+import { BRAIN_HEALTH_DEFAULTS } from "./policy.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND, type BrainSignalSign } from "./types.ts";
+
+// ----- Constants ------------------------------------------------------------
+
+/** Frontmatter `type` discriminator carried by every tension note. */
+export const TENSION_TYPE = "tension";
+/** On-disk frontmatter key holding a tension's lifecycle status. */
+export const TENSION_STATUS_KEY = "_status";
+/** Cap on the operator-supplied resolution/dismiss reason. */
+const REASON_MAX_LEN = 512;
+/** Cap on a quoted subject-bearing span stored in the note body. */
+const QUOTE_MAX_LEN = 512;
+/** Length of the dedup-hash suffix appended to the readable slug stem. */
+const DEDUP_HASH_LEN = 12;
+/** Readable-stem cap so the composed slug stays a sane filename length. */
+const SLUG_STEM_MAX_LEN = 48;
+/**
+ * Byte cap for a note read during a vault scan. Files over the cap are
+ * skipped (and not counted as scanned), matching the open-loop scanner's
+ * 1 MiB ceiling so one pathological file cannot stall detection.
+ */
+const NOTE_SCAN_MAX_BYTES = 1024 * 1024;
+
+/** The lifecycle states a tension can occupy. */
+export const TENSION_STATUS = {
+ open: "open",
+ confirmed: "confirmed",
+ dismissed: "dismissed",
+ resolved: "resolved",
+} as const;
+export type TensionStatus = (typeof TENSION_STATUS)[keyof typeof TENSION_STATUS];
+
+/**
+ * The states in which a tension still demands attention. Only these
+ * produce an injection-time warning; dismissed and resolved are terminal
+ * and silent.
+ */
+export const TENSION_UNRESOLVED_STATUSES: ReadonlySet<TensionStatus> = new Set([
+ TENSION_STATUS.open,
+ TENSION_STATUS.confirmed,
+]);
+
+/** The three operator transition verbs. */
+export const TENSION_TRANSITION = {
+ confirm: "confirm",
+ dismiss: "dismiss",
+ resolve: "resolve",
+} as const;
+export type TensionTransition = (typeof TENSION_TRANSITION)[keyof typeof TENSION_TRANSITION];
+
+/**
+ * The state machine: each transition maps to its resulting status and the
+ * set of source states it is legal from. Any transition whose current
+ * status is not in `from` raises {@link TensionError}.
+ */
+const TRANSITIONS: Readonly<
+ Record<
+ TensionTransition,
+ { readonly to: TensionStatus; readonly from: ReadonlySet<TensionStatus> }
+ >
+> = {
+ confirm: { to: TENSION_STATUS.confirmed, from: new Set([TENSION_STATUS.open]) },
+ dismiss: {
+ to: TENSION_STATUS.dismissed,
+ from: new Set([TENSION_STATUS.open, TENSION_STATUS.confirmed]),
+ },
+ resolve: {
+ to: TENSION_STATUS.resolved,
+ from: new Set([TENSION_STATUS.open, TENSION_STATUS.confirmed]),
+ },
+};
+
+// ----- Errors ---------------------------------------------------------------
+
+/** Every failure path in this module raises this typed error. */
+export class TensionError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "TensionError";
+ }
+}
+
+// ----- Shapes ---------------------------------------------------------------
+
+export interface TensionRecord {
+ readonly slug: string;
+ /** Filename basename without `.md`. Equals `tension-<slug>`. */
+ readonly id: string;
+ readonly type: typeof TENSION_TYPE;
+ readonly status: TensionStatus;
+ /** Lower-sorted subject id of the contradicting pair. */
+ readonly subjectA: string;
+ /** Higher-sorted subject id of the contradicting pair. */
+ readonly subjectB: string;
+ /** Sorted shared subject tokens, space-joined, for display. */
+ readonly subject: string;
+ /** Derived stance of {@link subjectA}. */
+ readonly stanceA: BrainSignalSign;
+ /** Derived stance of {@link subjectB}. */
+ readonly stanceB: BrainSignalSign;
+ /** Prose token overlap that put the pair over the detector threshold. */
+ readonly jaccard: number;
+ /** Deterministic dedup key (subject pair + stance signature). */
+ readonly dedupKey: string;
+ /** How many times this contradiction has been detected. */
+ readonly detectedCount: number;
+ readonly createdAt: string;
+ /** ISO second of the most recent detection. */
+ readonly detectedAt: string;
+ /** ISO second of the most recent status transition, or null. */
+ readonly statusChangedAt: string | null;
+ /** Operator reason recorded on dismiss/resolve, or null. */
+ readonly resolutionReason: string | null;
+ readonly agent: string;
+ /** Subject-bearing span quoted from {@link subjectA}. */
+ readonly quoteA: string;
+ /** Subject-bearing span quoted from {@link subjectB}. */
+ readonly quoteB: string;
+ readonly path: string;
+}
+
+export interface PersistTensionOptions {
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface PersistTensionResult {
+ readonly record: TensionRecord;
+ /** False when an existing tension for this dedup key was refreshed. */
+ readonly created: boolean;
+}
+
+export interface DetectTensionsOptions extends DetectNoteContradictionsOptions {
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+export interface DetectTensionsResult {
+ readonly records: ReadonlyArray<TensionRecord>;
+ /** How many tensions were newly created this run. */
+ readonly created: number;
+ /** How many existing tensions were refreshed this run. */
+ readonly updated: number;
+}
+
+export interface TransitionOptions {
+ readonly reason?: string;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+}
+
+// ----- Dedup key + slug -----------------------------------------------------
+
+/**
+ * Canonicalise a finding into `{ idLow, idHigh, signLow, signHigh, ... }`
+ * with the pair ordered by id, so the two orderings of one contradiction
+ * yield one identity. Stances travel with their id under the sort.
+ */
+function canonicalPair(finding: NoteContradictionFinding): {
+ idLow: string;
+ idHigh: string;
+ signLow: BrainSignalSign;
+ signHigh: BrainSignalSign;
+ quoteLow: string;
+ quoteHigh: string;
+} {
+ const aFirst = finding.aId <= finding.bId;
+ return aFirst
+ ? {
+ idLow: finding.aId,
+ idHigh: finding.bId,
+ signLow: finding.aSign,
+ signHigh: finding.bSign,
+ quoteLow: finding.aQuote,
+ quoteHigh: finding.bQuote,
+ }
+ : {
+ idLow: finding.bId,
+ idHigh: finding.aId,
+ signLow: finding.bSign,
+ signHigh: finding.aSign,
+ quoteLow: finding.bQuote,
+ quoteHigh: finding.aQuote,
+ };
+}
+
+/**
+ * Deterministic dedup key: the id-sorted subject pair joined with the
+ * stance signature. Two detections of the same pair with the same stances
+ * collapse onto one key; a stance flip produces a distinct key (and note),
+ * because the belief at stake genuinely changed.
+ */
+export function tensionDedupKey(finding: NoteContradictionFinding): string {
+ const { idLow, idHigh, signLow, signHigh } = canonicalPair(finding);
+ return `${idLow} ${idHigh} ${signLow}-${signHigh}`;
+}
+
+/**
+ * Filesystem-safe slug for a dedup key: a readable stem (the sorted id
+ * pair) plus a short sha256 suffix of the full key. The suffix guarantees
+ * uniqueness (so two pairs whose stems collide after truncation stay
+ * distinct) and stance-sensitivity, while staying deterministic across
+ * peers.
+ */
+function tensionSlug(finding: NoteContradictionFinding): string {
+ const { idLow, idHigh } = canonicalPair(finding);
+ const dedupKey = tensionDedupKey(finding);
+ const stem = `${stripId(idLow)}-${stripId(idHigh)}`
+ .replace(/[^a-z0-9]+/gu, "-")
+ .replace(/^-+|-+$/gu, "")
+ .slice(0, SLUG_STEM_MAX_LEN)
+ .replace(/-+$/gu, "");
+ const hash = createHash("sha256").update(dedupKey, "utf8").digest("hex").slice(0, DEDUP_HASH_LEN);
+ return stem ? `${stem}-${hash}` : hash;
+}
+
+/** Lowercase an id for the readable slug stem (structural, not semantic). */
+function stripId(id: string): string {
+ return id.trim().toLowerCase();
+}
+
+// ----- (De)serialization ----------------------------------------------------
+
+function render(record: Omit<TensionRecord, "path">): string {
+ const lines = [
+ "---",
+ `type: ${TENSION_TYPE}`,
+ `id: ${record.id}`,
+ `${TENSION_STATUS_KEY}: ${record.status}`,
+ `subject_a: ${record.subjectA}`,
+ `subject_b: ${record.subjectB}`,
+ `subject: ${JSON.stringify(record.subject)}`,
+ `stance_a: ${record.stanceA}`,
+ `stance_b: ${record.stanceB}`,
+ `jaccard: ${record.jaccard}`,
+ `dedup_key: ${JSON.stringify(record.dedupKey)}`,
+ `detected_count: ${record.detectedCount}`,
+ `created_at: ${record.createdAt}`,
+ `detected_at: ${record.detectedAt}`,
+ ];
+ if (record.statusChangedAt !== null) lines.push(`status_changed_at: ${record.statusChangedAt}`);
+ if (record.resolutionReason !== null) {
+ lines.push(`resolution_reason: ${JSON.stringify(record.resolutionReason)}`);
+ }
+ lines.push(`agent: ${JSON.stringify(record.agent)}`);
+ lines.push("---", "");
+ lines.push(`- ${record.subjectA}: ${record.quoteA}`);
+ lines.push(`- ${record.subjectB}: ${record.quoteB}`);
+ lines.push("");
+ return lines.join("\n");
+}
+
+function coerceStatus(value: unknown): TensionStatus {
+ if (
+ typeof value === "string" &&
+ (Object.values(TENSION_STATUS) as ReadonlyArray<string>).includes(value)
+ ) {
+ return value as TensionStatus;
+ }
+ // A hand-edit that corrupts the status reads as `open` (the safe,
+ // still-demands-attention default) rather than silently vanishing.
+ return TENSION_STATUS.open;
+}
+
+function coerceSign(value: unknown): BrainSignalSign {
+ return value === "negative" ? "negative" : "positive";
+}
+
+function scalarString(meta: Readonly<Record<string, unknown>>, key: string): string {
+ const value = meta[key];
+ return typeof value === "string" ? value : "";
+}
+
+function parsePage(vault: string, slug: string): TensionRecord | null {
+ const path = tensionPath(vault, slug);
+ if (!existsSync(path)) return null;
+ const [meta, body] = parseFrontmatter(path);
+ if (meta["type"] !== TENSION_TYPE) return null;
+ const statusChangedRaw = scalarString(meta, "status_changed_at");
+ const reasonRaw = scalarString(meta, "resolution_reason");
+ const detectedCount = Number(meta["detected_count"]);
+ const jaccard = Number(meta["jaccard"]);
+ // Body carries the two quote bullets; parse them back for round-trip.
+ const quotes = parseQuoteBody(body);
+ const subjectA = scalarString(meta, "subject_a");
+ const subjectB = scalarString(meta, "subject_b");
+ return Object.freeze({
+ slug,
+ id: `tension-${slug}`,
+ type: TENSION_TYPE,
+ status: coerceStatus(meta[TENSION_STATUS_KEY]),
+ subjectA,
+ subjectB,
+ subject: scalarString(meta, "subject"),
+ stanceA: coerceSign(meta["stance_a"]),
+ stanceB: coerceSign(meta["stance_b"]),
+ jaccard: Number.isFinite(jaccard) ? jaccard : 0,
+ dedupKey: scalarString(meta, "dedup_key"),
+ detectedCount: Number.isInteger(detectedCount) && detectedCount > 0 ? detectedCount : 1,
+ createdAt: scalarString(meta, "created_at"),
+ detectedAt: scalarString(meta, "detected_at"),
+ statusChangedAt: statusChangedRaw.length > 0 ? statusChangedRaw : null,
+ resolutionReason: reasonRaw.length > 0 ? reasonRaw : null,
+ agent: scalarString(meta, "agent"),
+ quoteA: quotes.get(subjectA) ?? "",
+ quoteB: quotes.get(subjectB) ?? "",
+ path,
+ });
+}
+
+/** Parse the `- <id>: <quote>` body bullets back into a per-id map. */
+function parseQuoteBody(body: string): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const line of body.split("\n")) {
+ const m = /^-\s+([^:]+):\s*(.*)$/u.exec(line.trim());
+ if (m) out.set(m[1]!.trim(), m[2]!.trim());
+ }
+ return out;
+}
+
+// ----- Agent + reason helpers -----------------------------------------------
+
+function resolveAgent(explicit: string | undefined, configPath: string | undefined): string {
+ return normalizeAgentArgument(explicit ?? null) ?? resolveAgentName(configPath);
+}
+
+function cleanReason(reason: string | undefined): string | null {
+ if (reason === undefined) return null;
+ const cleaned = sanitiseTextField(reason, { maxLen: REASON_MAX_LEN, singleLine: true }).trim();
+ return cleaned.length > 0 ? cleaned : null;
+}
+
+function cleanQuote(quote: string): string {
+ return sanitiseTextField(quote, { maxLen: QUOTE_MAX_LEN, singleLine: true }).trim();
+}
+
+// ----- Persist --------------------------------------------------------------
+
+/**
+ * Persist one detected contradiction as a tension note. On first sight of
+ * a dedup key this creates an `open` note and logs a `tension` (detected)
+ * event; on re-detection it refreshes the existing note (jaccard, quotes,
+ * `detected_at`, `detected_count`) WITHOUT touching its `_status`,
+ * `created_at`, or transition history, and emits nothing.
+ */
+export function persistTension(
+ vault: string,
+ finding: NoteContradictionFinding,
+ opts: PersistTensionOptions = {},
+): PersistTensionResult {
+ const { idLow, idHigh, signLow, signHigh, quoteLow, quoteHigh } = canonicalPair(finding);
+ const slug = tensionSlug(finding);
+ const dedupKey = tensionDedupKey(finding);
+ const now = opts.now ?? new Date();
+ const stampedAt = isoSecond(now);
+ const agent = resolveAgent(opts.agent, opts.configPath);
+
+ const prior = parsePage(vault, slug);
+ if (prior !== null) {
+ // Idempotent refresh: bump detection bookkeeping, preserve lifecycle.
+ const next: Omit<TensionRecord, "path"> = {
+ ...prior,
+ subject: finding.subject,
+ stanceA: signLow,
+ stanceB: signHigh,
+ jaccard: finding.jaccard,
+ dedupKey,
+ detectedCount: prior.detectedCount + 1,
+ detectedAt: stampedAt,
+ quoteA: cleanQuote(quoteLow),
+ quoteB: cleanQuote(quoteHigh),
+ };
+ mkdirSync(tensionsDir(vault), { recursive: true });
+ atomicWriteFileSync(prior.path, render(next));
+ return { record: Object.freeze({ ...next, path: prior.path }), created: false };
+ }
+
+ const record: Omit<TensionRecord, "path"> = {
+ slug,
+ id: `tension-${slug}`,
+ type: TENSION_TYPE,
+ status: TENSION_STATUS.open,
+ subjectA: idLow,
+ subjectB: idHigh,
+ subject: finding.subject,
+ stanceA: signLow,
+ stanceB: signHigh,
+ jaccard: finding.jaccard,
+ dedupKey,
+ detectedCount: 1,
+ createdAt: stampedAt,
+ detectedAt: stampedAt,
+ statusChangedAt: null,
+ resolutionReason: null,
+ agent,
+ quoteA: cleanQuote(quoteLow),
+ quoteB: cleanQuote(quoteHigh),
+ };
+
+ mkdirSync(tensionsDir(vault), { recursive: true });
+ const path = tensionPath(vault, slug);
+ atomicWriteFileSync(path, render(record));
+
+ appendLogEvent(vault, {
+ timestamp: stampedAt,
+ eventType: BRAIN_LOG_EVENT_KIND.tension,
+ body: {
+ tension: `[[${record.id}]]`,
+ action: "detected",
+ status: record.status,
+ subject_a: idLow,
+ subject_b: idHigh,
+ agent,
+ },
+ });
+
+ return { record: Object.freeze({ ...record, path }), created: true };
+}
+
+/**
+ * Run the note contradiction detector over `notes` and persist every
+ * finding as a tension. Consumes {@link detectNoteContradictions}; does
+ * not re-implement detection. Returns the persisted records plus how many
+ * were created vs refreshed.
+ */
+export function detectTensions(
+ vault: string,
+ notes: ReadonlyArray<NoteForContradiction>,
+ opts: DetectTensionsOptions,
+): DetectTensionsResult {
+ const findings = detectNoteContradictions(notes, {
+ jaccard: opts.jaccard,
+ ...(opts.negationMarkers !== undefined ? { negationMarkers: opts.negationMarkers } : {}),
+ });
+ const records: TensionRecord[] = [];
+ let created = 0;
+ let updated = 0;
+ for (const finding of findings) {
+ const res = persistTension(vault, finding, {
+ ...(opts.agent !== undefined ? { agent: opts.agent } : {}),
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
+ });
+ records.push(res.record);
+ if (res.created) created++;
+ else updated++;
+ }
+ return { records, created, updated };
+}
+
+export interface DetectTensionsInVaultOptions {
+ /**
+ * Explicit note roots to scan. When omitted (or all-blank) the roots
+ * come from `notes.read_paths` in `Brain/_brain.yaml`; a vault with no
+ * configured read paths scans nothing and creates no tensions, so an
+ * un-opted-in vault is byte-identical to today.
+ */
+ readonly paths?: ReadonlyArray<string>;
+ /**
+ * Minimum prose jaccard for two notes to count as the same subject.
+ * Defaults to the shared health threshold
+ * ({@link BRAIN_HEALTH_DEFAULTS.contradiction_jaccard}).
+ */
+ readonly jaccard?: number;
+ readonly negationMarkers?: ReadonlySet<string>;
+ readonly agent?: string;
+ readonly now?: Date;
+ readonly configPath?: string;
+ /** Byte cap per scanned file; defaults to {@link NOTE_SCAN_MAX_BYTES}. */
+ readonly maxFileSizeBytes?: number;
+}
+
+export interface DetectTensionsInVaultResult extends DetectTensionsResult {
+ /** How many note files were read and fed to the detector. */
+ readonly scannedFiles: number;
+}
+
+/**
+ * Production entry point for tension detection: load the configured note
+ * corpus (`notes.read_paths`) as prose notes and persist every detected
+ * contradiction as a tension. This is the operator-triggerable scan behind
+ * the `detect` action on the tension CLI verb and MCP tool; without it the
+ * detector ({@link detectTensions}) had no production caller and the
+ * operator could never create a tension.
+ *
+ * Each markdown file under a configured root becomes one
+ * {@link NoteForContradiction}: `id` is the frontmatter `id` when present
+ * (else the vault-relative path), `subject` is the optional frontmatter
+ * `subject` bucket, and `text` is the note body. The Brain machinery root
+ * and `vault.ignore_paths` are excluded by the shared note walker.
+ */
+export function detectTensionsInVault(
+ vault: string,
+ opts: DetectTensionsInVaultOptions = {},
+): DetectTensionsInVaultResult {
+ const roots = resolveNoteRoots(vault, opts.paths);
+ if (roots.length === 0) return { records: [], created: 0, updated: 0, scannedFiles: 0 };
+
+ const rules = buildNoteWalkRules(vault);
+ const cap = opts.maxFileSizeBytes ?? NOTE_SCAN_MAX_BYTES;
+ const notes: NoteForContradiction[] = [];
+ for (const file of walkMarkdownFiles(vault, roots, rules, { maxFileSizeBytes: cap })) {
+ let meta: Readonly<Record<string, unknown>>;
+ let body: string;
+ try {
+ [meta, body] = parseFrontmatter(file.absPath);
+ } catch {
+ continue; // unreadable or malformed frontmatter - skip, do not count
+ }
+ const rawId = meta["id"];
+ const id = typeof rawId === "string" && rawId.trim() !== "" ? rawId.trim() : file.relPath;
+ const rawSubject = meta["subject"];
+ const subject =
+ typeof rawSubject === "string" && rawSubject.trim() !== "" ? rawSubject.trim() : undefined;
+ notes.push({ id, ...(subject !== undefined ? { subject } : {}), text: body });
+ }
+
+ const result = detectTensions(vault, notes, {
+ jaccard: opts.jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,
+ ...(opts.negationMarkers !== undefined ? { negationMarkers: opts.negationMarkers } : {}),
+ ...(opts.agent !== undefined ? { agent: opts.agent } : {}),
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
+ });
+ return { ...result, scannedFiles: notes.length };
+}
+
+// ----- Transitions ----------------------------------------------------------
+
+function transition(
+ vault: string,
+ slug: string,
+ verb: TensionTransition,
+ opts: TransitionOptions,
+): TensionRecord {
+ const prior = parsePage(vault, slug);
+ if (prior === null) throw new TensionError(`no tension: ${slug}`);
+ const rule = TRANSITIONS[verb];
+ if (!rule.from.has(prior.status)) {
+ throw new TensionError(
+ `invalid tension transition: cannot ${verb} a tension in state '${prior.status}'`,
+ );
+ }
+ const now = opts.now ?? new Date();
+ const stampedAt = isoSecond(now);
+ const agent = resolveAgent(opts.agent, opts.configPath);
+ const reason = cleanReason(opts.reason);
+
+ const next: Omit<TensionRecord, "path"> = {
+ ...prior,
+ status: rule.to,
+ statusChangedAt: stampedAt,
+ resolutionReason: reason ?? prior.resolutionReason,
+ };
+ atomicWriteFileSync(prior.path, render(next));
+
+ appendLogEvent(vault, {
+ timestamp: stampedAt,
+ eventType: BRAIN_LOG_EVENT_KIND.tension,
+ body: {
+ tension: `[[${prior.id}]]`,
+ action: verb,
+ from: prior.status,
+ status: rule.to,
+ subject_a: prior.subjectA,
+ subject_b: prior.subjectB,
+ ...(reason !== null ? { reason } : {}),
+ agent,
+ },
+ });
+
+ return Object.freeze({ ...next, path: prior.path });
+}
+
+/** Confirm a tension (`open -> confirmed`). Invalid otherwise. */
+export function confirmTension(
+ vault: string,
+ slug: string,
+ opts: TransitionOptions = {},
+): TensionRecord {
+ return transition(vault, slug, TENSION_TRANSITION.confirm, opts);
+}
+
+/** Dismiss a tension (`open | confirmed -> dismissed`). Invalid otherwise. */
+export function dismissTension(
+ vault: string,
+ slug: string,
+ opts: TransitionOptions = {},
+): TensionRecord {
+ return transition(vault, slug, TENSION_TRANSITION.dismiss, opts);
+}
+
+/** Resolve a tension (`open | confirmed -> resolved`). Invalid otherwise. */
+export function resolveTension(
+ vault: string,
+ slug: string,
+ opts: TransitionOptions = {},
+): TensionRecord {
+ return transition(vault, slug, TENSION_TRANSITION.resolve, opts);
+}
+
+// ----- Reads ----------------------------------------------------------------
+
+/** One tension, or null. */
+export function showTension(vault: string, slug: string): TensionRecord | null {
+ return parsePage(vault, slug);
+}
+
+/** Every tension, sorted by slug. */
+export function listTensions(vault: string): TensionRecord[] {
+ const dir = tensionsDir(vault);
+ if (!existsSync(dir)) return [];
+ const out: TensionRecord[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md") || !name.startsWith("tension-")) continue;
+ const slug = name.replace(/^tension-/u, "").replace(/\.md$/u, "");
+ const page = parsePage(vault, slug);
+ if (page !== null) out.push(page);
+ }
+ return out.toSorted((a, b) => a.slug.localeCompare(b.slug));
+}
+
+/** Every tension still in an unresolved (open or confirmed) state. */
+export function listUnresolvedTensions(vault: string): TensionRecord[] {
+ return listTensions(vault).filter((t) => TENSION_UNRESOLVED_STATUSES.has(t.status));
+}
+
+// ----- Injection-time warnings ----------------------------------------------
+
+/**
+ * Warning lines for the context-pack builder: for every UNRESOLVED
+ * tension whose subject pair intersects `itemIds`, one line naming the
+ * tension and the injected subject(s) it touches. Dismissed and resolved
+ * tensions contribute nothing. Returns `[]` when no vault tension matches,
+ * so a tension-free vault keeps the pack output byte-identical.
+ */
+export function tensionWarningsForContextItems(
+ vault: string,
+ itemIds: ReadonlyArray<string>,
+): string[] {
+ const ids = new Set(itemIds);
+ const out: string[] = [];
+ for (const tension of listUnresolvedTensions(vault)) {
+ const touched: string[] = [];
+ if (ids.has(tension.subjectA)) touched.push(tension.subjectA);
+ if (ids.has(tension.subjectB)) touched.push(tension.subjectB);
+ if (touched.length === 0) continue;
+ out.push(
+ `unresolved tension [[${tension.id}]] (${tension.status}) involves injected memory ` +
+ touched.join(", "),
+ );
+ }
+ return out;
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index e4cb513d..ef2b58f7 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -291,9 +291,139 @@ export const BRAIN_LOG_EVENT_KIND = {
* signal from the dream pass; this event records that it happened.
*/
signalRetire: "signal-retire",
+ /**
+ * `tombstone` (Belief lifecycle suite, Track A anchor, t_7d5a3589) - a
+ * memory of any type (preference, signal, learning) was tombstoned:
+ * marked `_status: tombstoned` in frontmatter without deletion,
+ * optionally carrying a `superseded_by` replacement pointer (a
+ * supersede). Payload carries the vault-relative `path`, the `reason`,
+ * the `prior_status` the entry held before tombstoning, an optional
+ * `superseded_by` wikilink, and the `agent`. Re-issuing a tombstone is
+ * a byte-identical no-op and emits no event.
+ */
+ tombstone: "tombstone",
+ /**
+ * `temporal-replace` (Belief lifecycle suite, A2, t_3ba9c404) - an
+ * atomic temporal fact replacement closed a predecessor
+ * (`valid_until = T`) and opened a successor (`valid_from = T`) at one
+ * shared instant, reusing `superseded_by` as the successor link.
+ * Payload carries the vault-relative `predecessor` and `successor`
+ * paths, the shared instant `at`, and the `agent`. The pair is written
+ * atomically (both or neither); this event records that it happened.
+ */
+ temporalReplace: "temporal-replace",
+ /**
+ * `chain-decay` (Belief lifecycle suite, A4, t_d9365884) - the dream
+ * pass retired a low-recall superseded ancestor on the accelerated
+ * chain-decay window rather than the normal stale-evidence window.
+ * Payload carries the retired `preference` wikilink, the `reason`, and
+ * the `stale_days` window that fired. A memory that is not a superseded
+ * ancestor never produces this event, so a chain-free vault is
+ * byte-identical.
+ */
+ chainDecay: "chain-decay",
+ /**
+ * `decision-record` (Belief lifecycle suite, Track B anchor, t_ac03214d)
+ * - a first-class decision note was captured under `Brain/decisions/`.
+ * Payload carries the `decision` wikilink, the `chosen` option, the
+ * `review_date`, whether a review `obligation` was opened, and the
+ * `agent`. One event per capture; re-capturing an existing decision
+ * slug rejects instead of double-logging.
+ */
+ decisionRecord: "decision-record",
+ /**
+ * `decision-outcome` (Belief lifecycle suite, B1, t_ac03214d) - the
+ * `outcome` field of an existing decision note was backfilled. Payload
+ * carries the `decision` wikilink, the recorded `outcome`, and the
+ * `agent`. Distinct from `decision-record` so the capture and the
+ * later hindsight backfill stay separately auditable.
+ */
+ decisionOutcome: "decision-outcome",
+ /**
+ * `decision-rating` (Belief lifecycle suite, B2, t_6fe43fcc) - the
+ * `rating` (and optional `rationale`) of an existing decision note was
+ * set or changed. Payload carries the `decision` wikilink, the new
+ * `rating`, an optional `rationale`, and the `agent`. Distinct from
+ * `decision-outcome` because a rating is a quality self-assessment, not
+ * the observed outcome; overloading either kind would blur the audit.
+ */
+ decisionRating: "decision-rating",
+ /**
+ * `decision-change-receipt` (Belief lifecycle suite, B4, t_3547314d) - a
+ * `decision_change.v1` receipt was appended to the receipts log at the
+ * moment a belief changed (a supersede/tombstone or a preference
+ * confidence update). Payload carries the `subject`, the `reason_code`,
+ * the `idempotency_key`, and the `agent`. Emitted only on an actual
+ * append; an idempotent replay is a no-op and logs nothing, so the
+ * merged timeline never double-counts a change.
+ */
+ decisionChangeReceipt: "decision-change-receipt",
+ /**
+ * `authored-at-backfill` (conversation chronology, S1 / t_347e8224) -
+ * the idempotent backfill stamped the `authored_at` frontmatter field
+ * onto session-imported signals that preserved a transcript turn
+ * instant but predate the field. Emitted once per non-dry-run apply.
+ * Payload carries the number of files `updated`, the number `scanned`,
+ * and the `agent`. A dry run and a re-run that finds nothing to add
+ * emit nothing, so the merged timeline records only real mutations.
+ */
+ authoredAtBackfill: "authored-at-backfill",
+ /**
+ * `tension` (Belief lifecycle suite, S2, t_0e3f2bee) - a detected
+ * contradiction was persisted as a tension note, or an existing tension
+ * moved through its `open -> confirmed | dismissed | resolved` state
+ * machine. Payload carries the `tension` wikilink, the two `subject`
+ * ids, the `action` (`detected | confirm | dismiss | resolve`), the
+ * resulting `status`, and the `agent`; transitions also carry the `from`
+ * status. Re-detection of an already-persisted pair refreshes the note
+ * in place and emits nothing, so the merged timeline records only the
+ * first detection and each deliberate transition.
+ */
+ tension: "tension",
} as const;
export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
+/**
+ * Cross-type lifecycle status value (Belief lifecycle suite, t_7d5a3589).
+ * Written into the `_status` frontmatter slot by the tombstone/supersede
+ * lifecycle module to mark a memory of any type retired-in-place. Lives
+ * here (not in the lifecycle module) so `preference.ts` can tolerate the
+ * value on read without importing from `lifecycle/` - the design's
+ * one-directional import rule (lifecycle imports from types/preference,
+ * never the reverse).
+ */
+export const BRAIN_TOMBSTONE_STATUS = "tombstoned";
+
+/**
+ * Commitment-tier vocabulary (Belief lifecycle suite, B3, t_e112c63c).
+ * An optional, operator-facing epistemic stance on a belief - how firmly
+ * it is held, independent of the evidence-derived confidence float. The
+ * four-value ladder runs tentative -> fixed. Lives here (not in
+ * `commitment.ts`) so `preference.ts` / `types.ts` consumers can carry
+ * the value without importing the validator module - the same
+ * one-directional pattern as {@link BRAIN_TOMBSTONE_STATUS}. The write
+ * validator, tolerant reader, and typed error live in `commitment.ts`.
+ */
+export const BRAIN_COMMITMENT_TIER = {
+ exploring: "exploring",
+ leaning: "leaning",
+ decided: "decided",
+ locked: "locked",
+} as const;
+export type BrainCommitmentTier =
+ (typeof BRAIN_COMMITMENT_TIER)[keyof typeof BRAIN_COMMITMENT_TIER];
+
+const BRAIN_COMMITMENT_TIER_VALUES: ReadonlyArray<BrainCommitmentTier> =
+ Object.values(BRAIN_COMMITMENT_TIER);
+
+/** Type-guard narrowing an arbitrary value to {@link BrainCommitmentTier}. */
+export function isCommitmentTier(value: unknown): value is BrainCommitmentTier {
+ return (
+ typeof value === "string" &&
+ (BRAIN_COMMITMENT_TIER_VALUES as ReadonlyArray<string>).includes(value)
+ );
+}
+
/**
* Precomputed set of every event-kind string. Both the markdown
* parser (`appendLogEvent`) and the JSONL reader (`readLogDay`) need
@@ -542,6 +672,14 @@ export interface BrainPreference {
readonly freshness_trend?: string;
/** Optional wikilink to a retired pref this one replaces. */
readonly supersedes?: string;
+ /**
+ * Optional commitment tier (Belief lifecycle suite, B3, t_e112c63c):
+ * `exploring | leaning | decided | locked`. When set, the injection
+ * formatter renders the tier label in place of the raw confidence
+ * float. Additive optional - absent on legacy files; emitted only when
+ * supplied so unset preferences stay byte-identical.
+ */
+ readonly commitment?: BrainCommitmentTier;
readonly aliases?: ReadonlyArray<string>;
/** Optional runtime schema taxonomy token. Inert metadata. */
readonly schema_type?: string;
diff --git a/src/core/config.ts b/src/core/config.ts
index ec8057f6..8991eefa 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -512,6 +512,63 @@ export function resolveSessionHandoff(configPath?: string): boolean {
return resolveConfigFlag("OPEN_SECOND_BRAIN_SESSION_HANDOFF", "session_handoff", configPath);
}
+/**
+ * Rated-decision recall config keys (Belief lifecycle suite, B5,
+ * t_5712fa39). Both are OPTIONAL and default-OFF: when neither the env
+ * nor the config key is set, {@link resolveDecisionRecallMaxPerSession}
+ * returns `null`, which disables rated-decision recall entirely so the
+ * session-injection output is byte-identical to today.
+ */
+export const DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session";
+export const DECISION_RECALL_MAX_PER_SESSION_ENV_KEY =
+ "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION";
+export const DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns";
+export const DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY =
+ "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS";
+
+/**
+ * Shared body for a non-negative-integer config value: env var (trimmed)
+ * wins, falling back to the config key (trimmed). Returns `null` when
+ * unset, blank, or not a non-negative integer, so an unconfigured value
+ * leaves the caller's default behaviour intact.
+ */
+function resolveConfigNonNegativeInt(
+ envKey: string,
+ configKey: string,
+ configPath?: string,
+): number | null {
+ const env = process.env[envKey]?.trim();
+ const raw = env || discoverConfig(configPath).data[configKey]?.trim();
+ if (!raw || raw.length === 0) return null;
+ const n = Number(raw);
+ if (!Number.isInteger(n) || n < 0) return null;
+ return n;
+}
+
+/**
+ * Max rated-decision recalls per session. `null` (the default) disables
+ * the feature entirely - injection stays byte-identical.
+ */
+export function resolveDecisionRecallMaxPerSession(configPath?: string): number | null {
+ return resolveConfigNonNegativeInt(
+ DECISION_RECALL_MAX_PER_SESSION_ENV_KEY,
+ DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY,
+ configPath,
+ );
+}
+
+/**
+ * Minimum turns between two rated-decision recalls. `null` (unset)
+ * resolves to `0` (no spacing) at the call site.
+ */
+export function resolveDecisionRecallMinSpacingTurns(configPath?: string): number | null {
+ return resolveConfigNonNegativeInt(
+ DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY,
+ DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY,
+ configPath,
+ );
+}
+
/**
* Wikilink output format (Workspace Insight Suite, t_5f31b5f1).
* Default `preserve` keeps every generated/normalized link exactly as
diff --git a/src/core/search/enrich.ts b/src/core/search/enrich.ts
index d6f18b38..f638fef0 100644
--- a/src/core/search/enrich.ts
+++ b/src/core/search/enrich.ts
@@ -111,10 +111,15 @@ export interface DeriveTrustInput {
export function deriveTrust(input: DeriveTrustInput): TrustMetadata {
const ageDays = Math.max(0, Math.floor((input.nowMs - input.mtimeMs) / DAY_MS));
const relations = input.relations ?? [];
+ const supersededEdge = relations.find((r) => r.relation === SUPERSEDED_RELATION);
+ // Belief lifecycle suite (A4): carry a pointer to the replacement so a
+ // superseded recall hit tells the agent what replaced it.
+ const replacement = supersededEdge && supersededEdge.target !== "" ? supersededEdge.target : null;
return Object.freeze({
age_days: ageDays,
- superseded: relations.some((r) => r.relation === SUPERSEDED_RELATION),
+ superseded: supersededEdge !== undefined,
conflict: relations.some((r) => r.relation === CONFLICT_RELATION),
+ replacement,
});
}
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index 1d27773c..70513f49 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -204,6 +204,22 @@ function aliasesFromFrontmatter(frontmatter: Record<string, unknown>): string[]
return raw.filter((v): v is string => typeof v === "string");
}
+/**
+ * The note's `authored_at` frontmatter instant as unix seconds, or null
+ * when undeclared or unparseable (conversation chronology, S1). Tolerant
+ * by design: a malformed value never fails indexing, it just leaves the
+ * document with no turn instant so it ranks byte-identically. A value at
+ * or before the Unix epoch is treated as absent (the import layer's "no
+ * timestamp" sentinel), never a real authoring instant.
+ */
+function authoredAtFromFrontmatter(frontmatter: Record<string, unknown>): number | null {
+ const raw = frontmatter["authored_at"];
+ if (typeof raw !== "string") return null;
+ const ms = Date.parse(raw.trim());
+ if (!Number.isFinite(ms) || ms <= 0) return null;
+ return Math.floor(ms / 1000);
+}
+
const UTF8_FATAL = new TextDecoder("utf-8", { fatal: true });
function readUtf8(absPath: string): string {
@@ -312,6 +328,7 @@ async function indexInto(
mtime: mtimeSec,
size: file.stat.size,
pageType: pageTypeFromFrontmatter(frontmatter),
+ authoredAt: authoredAtFromFrontmatter(frontmatter),
});
// Framework-kind files feed the tier-guard post-pass: keep the
// parsed frontmatter of this run's changed docs that declare a
diff --git a/src/core/search/ranker.ts b/src/core/search/ranker.ts
index 9b0e3d9f..ca90deef 100644
--- a/src/core/search/ranker.ts
+++ b/src/core/search/ranker.ts
@@ -449,6 +449,10 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSea
semanticScore: c.semanticScore,
linkBoost,
recencyBoost: recency,
+ // Conversation chronology (S1): expose the authoring instant only
+ // when the note carries one, so a note with no turn instant keeps
+ // the byte-identical result shape.
+ ...(hyd.authoredAt != null ? { authoredAt: hyd.authoredAt } : {}),
searchType: c.searchType,
reasons: buildReasons({
reuseBoost,
@@ -483,8 +487,18 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSea
}
// Tie-break per design Β§7: final_score desc, keywordScore desc, mtime desc, chunkId asc.
+ // Conversation chronology (S1): on an EXACT hybrid-score tie, order by
+ // more recent authoring instant FIRST - but only when BOTH results carry
+ // an `authored_at`. A pair where either side has none falls through to
+ // the historical tie-break, so any non-tied pair (and every pair without
+ // turn instants) keeps today's order byte-identically.
ranked.sort((a, b) => {
if (b.score !== a.score) return b.score - a.score;
+ const aAuthored = inputs.hydrated.get(a.chunkId)?.authoredAt ?? null;
+ const bAuthored = inputs.hydrated.get(b.chunkId)?.authoredAt ?? null;
+ if (aAuthored !== null && bAuthored !== null && aAuthored !== bAuthored) {
+ return bAuthored - aAuthored;
+ }
if (b.keywordScore !== a.keywordScore) return b.keywordScore - a.keywordScore;
const am = inputs.hydrated.get(a.chunkId)?.mtime ?? 0;
const bm = inputs.hydrated.get(b.chunkId)?.mtime ?? 0;
diff --git a/src/core/search/result-filters.ts b/src/core/search/result-filters.ts
index cc0daf42..3a864576 100644
--- a/src/core/search/result-filters.ts
+++ b/src/core/search/result-filters.ts
@@ -15,6 +15,7 @@ import { isOwnerVisible, pageOwner } from "../graph/agent-scope.ts";
import { filterByProperties } from "./property-filter.ts";
import { deriveTrust } from "./enrich.ts";
import { isTerminalStatus } from "./evidence-pack.ts";
+import { isTombstoned } from "../brain/lifecycle/tombstone.ts";
import type { BrainSearchResult } from "./types.ts";
/**
@@ -64,6 +65,28 @@ export function buildTerminalPaths(
return terminal;
}
+/**
+ * Belief lifecycle suite (t_7d5a3589): drop tombstoned (incl.
+ * superseded-non-tip) rows from a ranked result set. A tombstoned memory
+ * stays on disk for audit but must not be recalled. Reads each unique
+ * path's cached frontmatter once; a vault with no tombstoned entries
+ * passes through byte-identically (nothing is dropped).
+ */
+export function applyStatusFilter(
+ ranked: ReadonlyArray<BrainSearchResult>,
+ vault: string,
+ frontmatterCache: Map<string, FrontmatterMap>,
+): ReadonlyArray<BrainSearchResult> {
+ return ranked.filter((r) => {
+ try {
+ return !isTombstoned(readCachedFrontmatter(frontmatterCache, vault, r.path));
+ } catch {
+ // Unreadable frontmatter is not a tombstone; leave the row in.
+ return true;
+ }
+ });
+}
+
export function applyPropertyFilter(
ranked: ReadonlyArray<BrainSearchResult>,
filters: ReadonlyMap<string, ReadonlyArray<string>>,
diff --git a/src/core/search/schema.ts b/src/core/search/schema.ts
index 29deaad5..7f14a672 100644
--- a/src/core/search/schema.ts
+++ b/src/core/search/schema.ts
@@ -16,7 +16,7 @@ import { SearchError } from "./types.ts";
* this raises `SCHEMA_MISMATCH` on open β€” the operator must reindex
* with a newer binary.
*/
-export const LATEST_SCHEMA_VERSION = 9;
+export const LATEST_SCHEMA_VERSION = 10;
/**
* The wikilink-resolution basename of a stored document path: the final
@@ -409,6 +409,23 @@ export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([
`);
},
},
+ {
+ // v10 (conversation chronology, t_347e8224) - a nullable
+ // `documents.authored_at` column (unix seconds) carrying the
+ // transcript turn instant a session-imported note was authored at.
+ // Surfaced on search results and used to break EXACT hybrid-score
+ // ties toward more recent statements. Additive and reindex-safe:
+ // existing rows default to NULL (no turn instant) until a reindex
+ // repopulates it from the `authored_at` frontmatter field, so a vault
+ // with no transcript-authored notes ranks byte-identically.
+ version: 10,
+ up(db) {
+ const docCols = db.query<{ name: string }, []>("PRAGMA table_info(documents)").all();
+ if (!docCols.some((c) => c.name === "authored_at")) {
+ db.exec("ALTER TABLE documents ADD COLUMN authored_at INTEGER");
+ }
+ },
+ },
]);
/** Read the current schema version from `index_state`. Returns 0 if not yet recorded. */
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index f7ee0a2f..fe7b6939 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -78,6 +78,7 @@ import { toSearchCard } from "./cards.ts";
import {
applyAgentScope,
applyPropertyFilter,
+ applyStatusFilter,
applyVisibilityScope,
attachTrustMetadata,
buildTerminalPaths,
@@ -874,9 +875,13 @@ export async function search(
// match the requested key/value pairs, then visibility scoping (v3)
// drops pages outside the requested visibility scope. Caching by
// document path bounds the read cost to the result set.
+ // Belief lifecycle suite (t_7d5a3589): drop tombstoned (incl.
+ // superseded-non-tip) memories before any other post-rank stage.
+ // A vault with no tombstoned entries passes through unchanged.
+ const statusFiltered = applyStatusFilter(ranked, config.vault, frontmatterCache);
const propFiltered = hasPropertyFilter
- ? applyPropertyFilter(ranked, opts.properties!, config.vault, frontmatterCache)
- : ranked;
+ ? applyPropertyFilter(statusFiltered, opts.properties!, config.vault, frontmatterCache)
+ : statusFiltered;
const visible = applyVisibilityScope(
propFiltered,
visibilityScope,
diff --git a/src/core/search/store.ts b/src/core/search/store.ts
index 8f03562a..58779044 100644
--- a/src/core/search/store.ts
+++ b/src/core/search/store.ts
@@ -72,6 +72,13 @@ export interface DocumentInput {
* endpoint types without re-reading files (v6).
*/
readonly pageType?: string | null;
+ /**
+ * Transcript turn instant this note was authored at, in unix seconds
+ * (conversation chronology, S1 / t_347e8224). Derived from the
+ * `authored_at` frontmatter field. Absent / null for a note with no
+ * turn instant, which then ranks byte-identically to pre-feature.
+ */
+ readonly authoredAt?: number | null;
}
export interface DocumentSummary {
@@ -145,6 +152,13 @@ export interface HydratedChunk {
readonly startLine: number;
readonly endLine: number;
readonly mtime: number;
+ /**
+ * Transcript turn instant (unix seconds) or null (conversation
+ * chronology, S1). Feeds the exact-tie recency tie-break in the ranker
+ * and is surfaced on the search result. Null for notes with no turn
+ * instant, keeping their ordering byte-identical.
+ */
+ readonly authoredAt?: number | null;
}
export interface StoreCounts {
@@ -642,13 +656,14 @@ export class Store {
number,
number,
string | null,
+ number | null,
string,
string,
string,
]
>(
- "INSERT INTO documents(path, basename, title, content_hash, mtime, size, page_type, created_at, updated_at, indexed_at) " +
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
+ "INSERT INTO documents(path, basename, title, content_hash, mtime, size, page_type, authored_at, created_at, updated_at, indexed_at) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT(path) DO UPDATE SET " +
" basename = excluded.basename, " +
" title = excluded.title, " +
@@ -656,6 +671,7 @@ export class Store {
" mtime = excluded.mtime, " +
" size = excluded.size, " +
" page_type = excluded.page_type, " +
+ " authored_at = excluded.authored_at, " +
" updated_at = excluded.updated_at, " +
" indexed_at = excluded.indexed_at " +
"RETURNING id",
@@ -668,6 +684,7 @@ export class Store {
doc.mtime,
doc.size,
doc.pageType ?? null,
+ doc.authoredAt ?? null,
now,
now,
now,
@@ -1761,11 +1778,13 @@ export class Store {
start_line: number;
end_line: number;
mtime: number;
+ authored_at: number | null;
},
number[]
>(
"SELECT c.id AS chunk_id, c.document_id, d.path AS path, d.title AS title, " +
- " c.content AS content, c.start_line AS start_line, c.end_line AS end_line, d.mtime AS mtime " +
+ " c.content AS content, c.start_line AS start_line, c.end_line AS end_line, d.mtime AS mtime, " +
+ " d.authored_at AS authored_at " +
"FROM chunks c JOIN documents d ON d.id = c.document_id " +
`WHERE c.id IN (${placeholders})`,
)
@@ -1780,6 +1799,7 @@ export class Store {
startLine: r.start_line,
endLine: r.end_line,
mtime: r.mtime,
+ authoredAt: r.authored_at,
});
}
return out;
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 2dc24eea..4382e663 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -110,6 +110,13 @@ export interface TrustMetadata {
readonly age_days: number;
readonly superseded: boolean;
readonly conflict: boolean;
+ /**
+ * Belief lifecycle suite (A4, t_d9365884): when the hit is superseded,
+ * the `superseded_by` successor target so recall carries a pointer to
+ * the replacement. `null` when the hit is not superseded or declares no
+ * successor target.
+ */
+ readonly replacement: string | null;
}
export interface BrainSearchResult {
@@ -125,6 +132,15 @@ export interface BrainSearchResult {
readonly semanticScore: number;
readonly linkBoost: number;
readonly recencyBoost: number;
+ /**
+ * Transcript turn instant (unix seconds) this result was authored at
+ * (conversation chronology, S1 / t_347e8224). Present only for a note
+ * carrying an `authored_at` frontmatter instant; absent for every note
+ * with no turn instant, so the result shape stays byte-identical for a
+ * vault without transcript-authored notes. Exact hybrid-score ties are
+ * ordered newer-first by this value.
+ */
+ readonly authoredAt?: number;
readonly searchType: "keyword" | "semantic" | "hybrid" | "link";
/**
* Explainable recall: one entry per scoring layer that contributed
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 36170e8f..61708057 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -36,6 +36,9 @@ import { SYNTHESIS_TOOLS } from "./brain/synthesis-tools.ts";
import { GENERATION_TOOLS } from "./brain/generation-tools.ts";
import { CALENDAR_TOOLS } from "./brain/calendar-tools.ts";
import { MEMORY_BRIDGE_TOOLS } from "./brain/memory-bridge-tools.ts";
+import { LIFECYCLE_TOOLS } from "./brain/lifecycle-tools.ts";
+import { DECISIONS_TOOLS } from "./brain/decisions-tools.ts";
+import { TENSION_TOOLS } from "./brain/tension-tools.ts";
import type { ToolDefinition } from "./tool-contract.ts";
export { vaultRelativeSafe } from "./brain/shared.ts";
@@ -67,4 +70,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
...GENERATION_TOOLS,
...CALENDAR_TOOLS,
...MEMORY_BRIDGE_TOOLS,
+ ...LIFECYCLE_TOOLS,
+ ...DECISIONS_TOOLS,
+ ...TENSION_TOOLS,
]);
diff --git a/src/mcp/brain/decisions-tools.ts b/src/mcp/brain/decisions-tools.ts
new file mode 100644
index 00000000..5baefb2e
--- /dev/null
+++ b/src/mcp/brain/decisions-tools.ts
@@ -0,0 +1,366 @@
+/**
+ * Decision-record note-family MCP tool (Belief lifecycle suite, Track B
+ * anchor, t_ac03214d).
+ *
+ * One tool, `brain_decision`, dispatching on `action`:
+ * - `record` capture a `type: decision` note + open a review obligation
+ * - `outcome` backfill the hindsight outcome of an existing decision
+ * - `show` read one decision
+ * - `list` list every decision
+ * - `similar` historically similar decisions with their outcomes
+ *
+ * MCP mirror of the `o2b brain decision` CLI verb; both delegate to the
+ * core decision module so the on-disk shape cannot drift.
+ */
+
+import {
+ backfillOutcome,
+ compareDecisions,
+ findSimilarDecisions,
+ listDecisions,
+ listRatedDecisions,
+ recordDecision,
+ showDecision,
+ updateRating,
+ DecisionError,
+} from "../../core/brain/decisions/record.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { coerceBool, coerceInt, coerceStr, coerceStrList } from "../coerce.ts";
+import { wrapToolErrors } from "./shared.ts";
+import { DECISION_RATING_MAX, DECISION_RATING_MIN } from "../../core/brain/decisions/record.ts";
+import { BRAIN_COMMITMENT_TIER, type BrainCommitmentTier } from "../../core/brain/types.ts";
+import {
+ queryDecisionChangeHistory,
+ ReceiptError,
+ DECISION_HISTORY_DEFAULT_LIMIT,
+} from "../../core/brain/decisions/receipts.ts";
+import { recallRatedDecisions } from "../../core/brain/decisions/recall.ts";
+
+const TOOL = "brain_decision";
+
+async function toolBrainDecision(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return wrapToolErrors(TOOL, [DecisionError, ReceiptError], async () => {
+ const action = coerceStr(args, "action", true)!;
+ const agent = coerceStr(args, "agent", false) ?? undefined;
+
+ switch (action) {
+ case "record": {
+ const title = coerceStr(args, "title", true)!;
+ const chosen = coerceStr(args, "chosen", true)!;
+ const assumption = coerceStr(args, "assumption", true)!;
+ const reviewDate = coerceStr(args, "review_date", true)!;
+ const premortem = coerceStr(args, "premortem", false) ?? undefined;
+ const notes = coerceStr(args, "notes", false) ?? undefined;
+ const rating =
+ args["rating"] === undefined
+ ? undefined
+ : coerceInt(
+ args,
+ "rating",
+ DECISION_RATING_MIN,
+ DECISION_RATING_MIN,
+ DECISION_RATING_MAX,
+ );
+ const rationale = coerceStr(args, "rationale", false) ?? undefined;
+ const commitment = coerceStr(args, "commitment", false) ?? undefined;
+ const res = recordDecision(ctx.vault, {
+ title,
+ chosen,
+ assumption,
+ reviewDate,
+ ...(premortem ? { premortem } : {}),
+ ...(notes ? { notes } : {}),
+ ...(rating !== undefined ? { rating } : {}),
+ ...(rationale ? { rationale } : {}),
+ ...(commitment ? { commitment: commitment as BrainCommitmentTier } : {}),
+ agent: agent ?? "",
+ });
+ return {
+ action,
+ id: res.record.id,
+ slug: res.record.slug,
+ review_date: res.record.reviewDate,
+ review_obligation: res.reviewObligationSlug,
+ obligation_created: res.obligationCreated,
+ };
+ }
+ case "rate": {
+ const slug = coerceStr(args, "slug", true)!;
+ const rating = coerceInt(
+ args,
+ "rating",
+ DECISION_RATING_MIN,
+ DECISION_RATING_MIN,
+ DECISION_RATING_MAX,
+ );
+ const rationale = coerceStr(args, "rationale", false) ?? undefined;
+ const res = updateRating(ctx.vault, {
+ slug,
+ rating,
+ ...(rationale ? { rationale } : {}),
+ ...(agent ? { agent } : {}),
+ });
+ return { action, id: res.id, slug: res.slug, rating: res.rating, rationale: res.rationale };
+ }
+ case "compare": {
+ const slugs = coerceStrList(args, "slugs");
+ const rows = compareDecisions(ctx.vault, slugs);
+ return {
+ action,
+ decisions: rows.map((d) => ({
+ id: d.id,
+ slug: d.slug,
+ title: d.title,
+ chosen: d.chosen,
+ rating: d.rating,
+ rationale: d.rationale,
+ outcome: d.outcome,
+ })),
+ };
+ }
+ case "outcome": {
+ const slug = coerceStr(args, "slug", true)!;
+ const outcome = coerceStr(args, "outcome", true)!;
+ const res = backfillOutcome(ctx.vault, {
+ slug,
+ outcome,
+ ...(agent ? { agent } : {}),
+ });
+ return { action, id: res.id, slug: res.slug, outcome: res.outcome };
+ }
+ case "show": {
+ const slug = coerceStr(args, "slug", true)!;
+ const res = showDecision(ctx.vault, slug);
+ if (res === null) throw new DecisionError(`no decision: ${slug}`);
+ return {
+ action,
+ id: res.id,
+ slug: res.slug,
+ title: res.title,
+ chosen: res.chosen,
+ assumption: res.assumption,
+ review_date: res.reviewDate,
+ outcome: res.outcome,
+ premortem: res.premortem,
+ // Commitment tier (B3): emitted only when set so an unset
+ // decision stays byte-identical to a pre-B3 response.
+ ...(res.commitment !== null ? { commitment: res.commitment } : {}),
+ };
+ }
+ case "list": {
+ const ratedOnly = coerceBool(args, "rated");
+ const all = ratedOnly ? listRatedDecisions(ctx.vault) : listDecisions(ctx.vault);
+ return {
+ action,
+ decisions: all.map((d) => ({
+ id: d.id,
+ slug: d.slug,
+ title: d.title,
+ chosen: d.chosen,
+ rating: d.rating,
+ review_date: d.reviewDate,
+ outcome: d.outcome,
+ ...(d.commitment !== null ? { commitment: d.commitment } : {}),
+ })),
+ };
+ }
+ case "recall": {
+ const prompt = coerceStr(args, "prompt", true)!;
+ const turn = args["turn"] === undefined ? 0 : coerceInt(args, "turn", 0, 0, 1_000_000);
+ const count = args["count"] === undefined ? 0 : coerceInt(args, "count", 0, 0, 1_000_000);
+ const lastTurnRaw = args["last_turn"];
+ const lastTurn =
+ lastTurnRaw === undefined || lastTurnRaw === null
+ ? null
+ : coerceInt(args, "last_turn", 0, 0, 1_000_000);
+ const surfacedIds = coerceStrList(args, "surfaced_ids");
+ const res = recallRatedDecisions(ctx.vault, {
+ prompt,
+ turn,
+ state: {
+ surfacedIds,
+ lastTurn,
+ count: count || surfacedIds.length,
+ },
+ });
+ return {
+ action,
+ enabled: res.enabled,
+ surfaced: res.surfaced
+ ? { id: res.surfaced.id, slug: res.surfaced.slug, rating: res.surfaced.rating }
+ : null,
+ text: res.text,
+ state: {
+ surfaced_ids: res.state.surfacedIds,
+ last_turn: res.state.lastTurn,
+ count: res.state.count,
+ },
+ };
+ }
+ case "history": {
+ const subject = coerceStr(args, "subject", false) ?? undefined;
+ const cursor = coerceStr(args, "cursor", false) ?? undefined;
+ const limit =
+ args["limit"] === undefined
+ ? DECISION_HISTORY_DEFAULT_LIMIT
+ : coerceInt(args, "limit", DECISION_HISTORY_DEFAULT_LIMIT, 1, 500);
+ const page = queryDecisionChangeHistory(ctx.vault, {
+ ...(subject ? { subject } : {}),
+ ...(cursor ? { cursor } : {}),
+ limit,
+ });
+ return {
+ action,
+ total: page.total,
+ next_cursor: page.nextCursor,
+ receipts: page.receipts.map((r) => ({
+ ts: r.ts,
+ subject: r.subject,
+ before: r.before,
+ after: r.after,
+ confidence_delta: r.confidence_delta,
+ reason_code: r.reason_code,
+ actor: r.actor,
+ idempotency_key: r.idempotency_key,
+ })),
+ };
+ }
+ case "similar": {
+ const title = coerceStr(args, "title", true)!;
+ const chosen = coerceStr(args, "chosen", false) ?? undefined;
+ const hits = findSimilarDecisions(ctx.vault, {
+ title,
+ ...(chosen ? { chosen } : {}),
+ });
+ return {
+ action,
+ similar: hits.map((h) => ({
+ id: h.id,
+ slug: h.slug,
+ title: h.title,
+ outcome: h.outcome,
+ jaccard: h.jaccard,
+ })),
+ };
+ }
+ default:
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${TOOL}: 'action' must be one of record, outcome, rate, show, list, compare, similar, history, recall`,
+ );
+ }
+ });
+}
+
+export const DECISIONS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: TOOL,
+ description:
+ "Decision-record family. action: record captures a `type: decision` note (chosen, assumption, review_date, optional premortem/rating); outcome backfills; rate sets a rating; show/list/compare read; similar finds past decisions; history reads receipts; recall resurfaces a rated decision on a prompt.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: {
+ type: "string",
+ enum: [
+ "record",
+ "outcome",
+ "rate",
+ "show",
+ "list",
+ "compare",
+ "similar",
+ "history",
+ "recall",
+ ],
+ description: "Which decision operation to run.",
+ },
+ title: {
+ type: "string",
+ description: "record/similar: the decision question / statement.",
+ },
+ chosen: {
+ type: "string",
+ description: "record: the chosen option. similar: optional chosen-option hint.",
+ },
+ assumption: {
+ type: "string",
+ description: "record: the key assumption the decision rides on.",
+ },
+ review_date: {
+ type: "string",
+ description: "record: review date (YYYY-MM-DD); opens one review obligation.",
+ },
+ premortem: {
+ type: "string",
+ description: "record: optional pre-mortem (how could this go wrong).",
+ },
+ notes: { type: "string", description: "record: optional free-form body notes." },
+ slug: { type: "string", description: "outcome/rate/show: decision slug." },
+ outcome: { type: "string", description: "outcome: hindsight outcome to backfill." },
+ rating: {
+ type: "integer",
+ minimum: DECISION_RATING_MIN,
+ maximum: DECISION_RATING_MAX,
+ description: `record/rate: quality rating in [${DECISION_RATING_MIN}, ${DECISION_RATING_MAX}].`,
+ },
+ rationale: { type: "string", description: "record/rate: justification for the rating." },
+ commitment: {
+ type: "string",
+ enum: Object.values(BRAIN_COMMITMENT_TIER),
+ description: "record: optional commitment tier (exploring|leaning|decided|locked).",
+ },
+ rated: {
+ type: "boolean",
+ description: "list: return only rated decisions, sorted by rating.",
+ },
+ slugs: {
+ type: "array",
+ items: { type: "string" },
+ description: "compare: decision slugs to read side by side.",
+ },
+ subject: {
+ type: "string",
+ description: "history: filter decision-change receipts to one subject id.",
+ },
+ cursor: { type: "string", description: "history: opaque cursor from a prior page." },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "history: page size (default 50).",
+ },
+ prompt: { type: "string", description: "recall: the incoming prompt to match." },
+ turn: {
+ type: "integer",
+ minimum: 0,
+ description: "recall: monotonic turn index (spacing).",
+ },
+ surfaced_ids: {
+ type: "array",
+ items: { type: "string" },
+ description: "recall: decision ids already surfaced this session.",
+ },
+ last_turn: {
+ type: "integer",
+ minimum: 0,
+ description: "recall: turn of the last recall (spacing state).",
+ },
+ count: { type: "integer", minimum: 0, description: "recall: recalls surfaced so far." },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["action"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainDecision,
+ },
+]);
diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.ts
index 46967cf3..2f45d66a 100644
--- a/src/mcp/brain/knowledge-tools.ts
+++ b/src/mcp/brain/knowledge-tools.ts
@@ -41,6 +41,18 @@ 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 {
+ allClaims,
+ buildClaimGraph,
+ currentTruth,
+ loadClaimGraph,
+ rebuildClaimGraph,
+ truthAt,
+ whatContests,
+ whatReplaced,
+ type ClaimGraph,
+ type ClaimNode,
+} from "../../core/brain/claim-graph.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
@@ -556,9 +568,110 @@ function toolBrainCodegraphReport(
return report as unknown as Record<string, unknown>;
}
+// ----- brain_claims (Belief lifecycle suite, A3) -----------------------------
+
+function renderClaimNode(n: ClaimNode): Record<string, unknown> {
+ return {
+ id: n.id,
+ path: n.path,
+ topic: n.topic,
+ principle: n.principle,
+ valid_from: n.valid_from,
+ valid_until: n.valid_until,
+ superseded_by: n.superseded_by,
+ contradicts: n.contradicts,
+ provenance: n.provenance,
+ tombstoned: n.tombstoned,
+ };
+}
+
+const CLAIMS_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+/** Load the persisted claim graph, or build a fresh in-memory one. */
+function resolveClaimGraph(vault: string): ClaimGraph {
+ return loadClaimGraph(vault) ?? buildClaimGraph(vault);
+}
+
+/**
+ * Claim-graph query surface: current truth (default), truth at an
+ * instant, history, what replaced X, what contests X, or rebuild.
+ */
+function toolBrainClaims(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const operation = coerceStr(args, "operation", false) ?? "current";
+ switch (operation) {
+ case "rebuild": {
+ const graph = rebuildClaimGraph(ctx.vault);
+ return { operation, rebuilt: true, node_count: graph.node_count, truncated: graph.truncated };
+ }
+ case "replaced": {
+ const id = coerceStr(args, "id", true)!;
+ const tip = whatReplaced(resolveClaimGraph(ctx.vault), id);
+ return { operation, id, tip: tip ? renderClaimNode(tip) : null };
+ }
+ case "contests": {
+ const id = coerceStr(args, "id", true)!;
+ const rows = whatContests(resolveClaimGraph(ctx.vault), id);
+ return { operation, id, claims: rows.map(renderClaimNode) };
+ }
+ case "at": {
+ const at = coerceStr(args, "at", true)!;
+ const iso = CLAIMS_DATE_ONLY_RE.test(at) ? `${at}T00:00:00Z` : at;
+ const probe = Date.parse(iso);
+ if (Number.isNaN(probe)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_claims: 'at' must be an ISO instant or YYYY-MM-DD date; got ${at}`,
+ );
+ }
+ const rows = truthAt(resolveClaimGraph(ctx.vault), probe);
+ return { operation, at, count: rows.length, claims: rows.map(renderClaimNode) };
+ }
+ case "history": {
+ const rows = allClaims(resolveClaimGraph(ctx.vault));
+ return { operation, count: rows.length, claims: rows.map(renderClaimNode) };
+ }
+ case "current": {
+ const rows = currentTruth(resolveClaimGraph(ctx.vault));
+ return { operation, count: rows.length, claims: rows.map(renderClaimNode) };
+ }
+ default:
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_claims: 'operation' must be one of current, at, history, replaced, contests, rebuild",
+ );
+ }
+}
+
// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------
export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_claims",
+ description:
+ "Claim-graph query (a projection over superseded_by / contradicts / valid_from / valid_until). operation: current (default) = truth now; at = truth at an instant; history = every claim incl. tombstoned; replaced = what replaced X; contests = what contests X; rebuild = rebuild the projection.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["current", "at", "history", "replaced", "contests", "rebuild"],
+ description: "Which claim-graph query to run (default: current).",
+ },
+ at: {
+ type: "string",
+ description: "at: ISO-8601 instant or YYYY-MM-DD date to evaluate truth.",
+ },
+ id: { type: "string", description: "replaced/contests: the claim id/wikilink to resolve." },
+ },
+ required: [],
+ additionalProperties: false,
+ },
+ handler: toolBrainClaims,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
{
name: "brain_codegraph_report",
description:
diff --git a/src/mcp/brain/lifecycle-tools.ts b/src/mcp/brain/lifecycle-tools.ts
new file mode 100644
index 00000000..e88682c2
--- /dev/null
+++ b/src/mcp/brain/lifecycle-tools.ts
@@ -0,0 +1,202 @@
+/**
+ * Cross-type tombstone + supersede lifecycle MCP tool (Belief lifecycle
+ * suite, Track A anchor, t_7d5a3589).
+ *
+ * One tool, `brain_lifecycle`, dispatching on `action`:
+ * - `tombstone` mark a memory `_status: tombstoned` in place
+ * - `supersede` tombstone a predecessor and record its successor
+ * - `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
+ *
+ * MCP mirror of the `o2b brain lifecycle` CLI verb; both delegate to the
+ * core lifecycle module so the on-disk shape cannot drift.
+ */
+
+import { curatorSlices } from "../../core/brain/lifecycle/curator.ts";
+import {
+ temporalReplace,
+ TemporalReplaceError,
+} from "../../core/brain/lifecycle/temporal-replace.ts";
+import {
+ resolveChainTipInVault,
+ supersede,
+ tombstone,
+ TombstoneError,
+} from "../../core/brain/lifecycle/tombstone.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { coerceStr } from "../coerce.ts";
+import { coerceNonNegativeInteger, wrapToolErrors } from "./shared.ts";
+
+const TOOL = "brain_lifecycle";
+
+/** Project curator slice rows into the tool's snake_cased response shape. */
+function renderCuratorRows(
+ rows: ReadonlyArray<{
+ key: string;
+ reuse: { used: number; ignored: number; contradicted: number };
+ }>,
+): Array<Record<string, unknown>> {
+ return rows.map((r) => ({
+ key: r.key,
+ used: r.reuse.used,
+ ignored: r.reuse.ignored,
+ contradicted: r.reuse.contradicted,
+ }));
+}
+
+async function toolBrainLifecycle(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return wrapToolErrors(TOOL, [TombstoneError, TemporalReplaceError], async () => {
+ const action = coerceStr(args, "action", true)!;
+ const agent = coerceStr(args, "agent", false) ?? undefined;
+
+ switch (action) {
+ case "tombstone": {
+ const path = coerceStr(args, "path", true)!;
+ const reason = coerceStr(args, "reason", true)!;
+ const supersededBy = coerceStr(args, "superseded_by", false) ?? undefined;
+ const res = tombstone({
+ vault: ctx.vault,
+ path,
+ reason,
+ ...(supersededBy ? { supersededBy } : {}),
+ ...(agent ? { agent } : {}),
+ });
+ return {
+ action,
+ changed: res.changed,
+ path: res.path,
+ tombstoned: res.state.tombstoned,
+ superseded_by: res.state.supersededBy,
+ };
+ }
+ case "supersede": {
+ const predecessor = coerceStr(args, "predecessor", true)!;
+ const successor = coerceStr(args, "successor", true)!;
+ const reason = coerceStr(args, "reason", false) ?? undefined;
+ const res = supersede({
+ vault: ctx.vault,
+ predecessor,
+ successor,
+ ...(reason ? { reason } : {}),
+ ...(agent ? { agent } : {}),
+ });
+ return {
+ action,
+ changed: res.changed,
+ path: res.path,
+ superseded_by: res.state.supersededBy,
+ };
+ }
+ case "temporal-replace": {
+ const predecessor = coerceStr(args, "predecessor", true)!;
+ const successor = coerceStr(args, "successor", true)!;
+ const at = coerceStr(args, "at", true)!;
+ const res = temporalReplace({
+ vault: ctx.vault,
+ predecessor,
+ successor,
+ at,
+ ...(agent ? { agent } : {}),
+ });
+ return {
+ action,
+ at: res.at,
+ predecessor: res.predecessor,
+ successor: res.successor,
+ agent: res.agent,
+ };
+ }
+ case "tip": {
+ const id = coerceStr(args, "id", true)!;
+ const res = resolveChainTipInVault(ctx.vault, id);
+ return {
+ action,
+ tip: res.tip,
+ steps: res.steps,
+ cycle: res.cycle,
+ resolved_all: res.resolvedAll,
+ };
+ }
+ case "curator": {
+ const highUseMin = coerceNonNegativeInteger(TOOL, "high_use_min", args["high_use_min"]);
+ const slices = curatorSlices(ctx.vault, highUseMin !== undefined ? { highUseMin } : {});
+ return {
+ action,
+ injected_never_used: renderCuratorRows(slices.injectedNeverUsed),
+ contradicted: renderCuratorRows(slices.contradicted),
+ high_used: renderCuratorRows(slices.highUsed),
+ };
+ }
+ default:
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${TOOL}: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator`,
+ );
+ }
+ });
+}
+
+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.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: {
+ type: "string",
+ enum: ["tombstone", "supersede", "temporal-replace", "tip", "curator"],
+ description: "Which lifecycle operation to run.",
+ },
+ path: {
+ type: "string",
+ description: "tombstone: vault-relative path of the target memory file.",
+ },
+ reason: {
+ type: "string",
+ description: "tombstone/supersede: operator-facing reason for the change.",
+ },
+ superseded_by: {
+ type: "string",
+ description: "tombstone: optional successor id/wikilink stored as superseded_by.",
+ },
+ predecessor: {
+ type: "string",
+ description:
+ "supersede/temporal-replace: vault-relative path of the predecessor being replaced.",
+ },
+ successor: {
+ type: "string",
+ description:
+ "supersede: successor id/wikilink. temporal-replace: vault-relative path of the successor.",
+ },
+ at: {
+ type: "string",
+ description:
+ "temporal-replace: shared instant T (ISO-8601 UTC instant or YYYY-MM-DD date).",
+ },
+ id: { type: "string", description: "tip: id/wikilink whose chain tip to resolve." },
+ high_use_min: {
+ type: "integer",
+ minimum: 0,
+ description: "curator: minimum USED count for the high-used slice.",
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["action"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainLifecycle,
+ },
+]);
diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.ts
index 47107390..3e178590 100644
--- a/src/mcp/brain/recall-tools.ts
+++ b/src/mcp/brain/recall-tools.ts
@@ -56,6 +56,8 @@ 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 { aggregateQueryDemand, serializeQueryDemandReport } from "../../core/brain/query-demand.ts";
import { isoSecond } from "../../core/brain/time.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
@@ -758,6 +760,12 @@ async function toolBrainSessionGrep(
"snippet_chars",
args["snippet_chars"],
);
+ // 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.
+ const since = optionalStringArg("brain_session_grep", args, "since");
+ const before = optionalStringArg("brain_session_grep", args, "before");
+ const bounds = resolveSessionGrepBounds(since, before);
return {
...searchSessionRecall(ctx.vault, {
query: requiredStringArg("brain_session_grep", args, "query"),
@@ -768,10 +776,37 @@ async function toolBrainSessionGrep(
: {}),
...(limit !== undefined ? { limit } : {}),
...(snippetChars !== undefined ? { snippetChars } : {}),
+ ...(bounds.sinceMs !== null ? { sinceMs: bounds.sinceMs } : {}),
+ ...(bounds.untilMs !== null ? { untilMs: bounds.untilMs } : {}),
}),
};
}
+/**
+ * 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);
+ throw exc;
+ }
+}
+
async function toolBrainSessionDescribe(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -1130,7 +1165,8 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_session_grep",
previewBudget: MCP_PREVIEW_BUDGET,
- description: "Search imported session recall raw turns and summary nodes.",
+ description:
+ "Search imported session recall raw turns and summary nodes, optionally bounded to a time window (since/before).",
inputSchema: {
type: "object",
properties: {
@@ -1149,6 +1185,16 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
minimum: 1,
description: "Maximum chars per hit snippet.",
},
+ since: {
+ type: "string",
+ description:
+ "Optional inclusive lower time bound on turn authoring time (ISO date/datetime, today/yesterday/last week/last month, or <n>h/<n>d/<n>w).",
+ },
+ before: {
+ type: "string",
+ description:
+ "Optional inclusive upper time bound on turn authoring time (same grammar as since).",
+ },
},
required: ["query"],
additionalProperties: false,
diff --git a/src/mcp/brain/tension-tools.ts b/src/mcp/brain/tension-tools.ts
new file mode 100644
index 00000000..71815d15
--- /dev/null
+++ b/src/mcp/brain/tension-tools.ts
@@ -0,0 +1,174 @@
+/**
+ * Tension-object lifecycle MCP tool (Belief lifecycle suite, S2,
+ * t_0e3f2bee).
+ *
+ * One tool, `brain_tension`, dispatching on `action`:
+ * - `detect` scan the note corpus and persist detected contradictions
+ * - `list` list persisted tensions (optionally unresolved only)
+ * - `show` read one tension
+ * - `confirm` open -> confirmed
+ * - `dismiss` open|confirmed -> dismissed
+ * - `resolve` open|confirmed -> resolved
+ *
+ * MCP mirror of the `o2b brain tension` CLI verb; both delegate to the
+ * core tensions module so the on-disk shape cannot drift.
+ */
+
+import {
+ confirmTension,
+ detectTensionsInVault,
+ dismissTension,
+ listTensions,
+ listUnresolvedTensions,
+ resolveTension,
+ showTension,
+ TensionError,
+ type TensionRecord,
+} from "../../core/brain/tensions.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { coerceBool, coerceStr } from "../coerce.ts";
+import { wrapToolErrors } from "./shared.ts";
+
+const TOOL = "brain_tension";
+
+/** Project a tension record into the tool's snake_cased response shape. */
+function renderRow(t: TensionRecord): Record<string, unknown> {
+ return {
+ id: t.id,
+ slug: t.slug,
+ status: t.status,
+ subject_a: t.subjectA,
+ subject_b: t.subjectB,
+ stance_a: t.stanceA,
+ stance_b: t.stanceB,
+ detected_count: t.detectedCount,
+ resolution_reason: t.resolutionReason,
+ };
+}
+
+async function toolBrainTension(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return wrapToolErrors(TOOL, [TensionError], async () => {
+ const action = coerceStr(args, "action", true)!;
+ const agent = coerceStr(args, "agent", false) ?? undefined;
+ const reason = coerceStr(args, "reason", false) ?? undefined;
+
+ switch (action) {
+ case "detect":
+ case "scan": {
+ const rawJaccard = args["jaccard"];
+ let jaccard: number | undefined;
+ if (rawJaccard !== undefined && rawJaccard !== null) {
+ if (typeof rawJaccard !== "number" || !Number.isFinite(rawJaccard)) {
+ throw new MCPError(INVALID_PARAMS, `${TOOL}: 'jaccard' must be a number`);
+ }
+ if (rawJaccard <= 0 || rawJaccard > 1) {
+ throw new MCPError(INVALID_PARAMS, `${TOOL}: 'jaccard' must be in (0, 1]`);
+ }
+ jaccard = rawJaccard;
+ }
+ const res = detectTensionsInVault(ctx.vault, {
+ ...(jaccard !== undefined ? { jaccard } : {}),
+ ...(agent ? { agent } : {}),
+ });
+ return {
+ action,
+ created: res.created,
+ updated: res.updated,
+ scanned_files: res.scannedFiles,
+ tensions: res.records.map(renderRow),
+ };
+ }
+ case "list": {
+ const unresolved = coerceBool(args, "unresolved");
+ const rows = unresolved ? listUnresolvedTensions(ctx.vault) : listTensions(ctx.vault);
+ return { action, tensions: rows.map(renderRow) };
+ }
+ case "show": {
+ const slug = coerceStr(args, "slug", true)!;
+ const t = showTension(ctx.vault, slug);
+ if (t === null) throw new TensionError(`no tension: ${slug}`);
+ return {
+ action,
+ ...renderRow(t),
+ subject: t.subject,
+ jaccard: t.jaccard,
+ quote_a: t.quoteA,
+ quote_b: t.quoteB,
+ created_at: t.createdAt,
+ detected_at: t.detectedAt,
+ status_changed_at: t.statusChangedAt,
+ };
+ }
+ case "confirm":
+ case "dismiss":
+ case "resolve": {
+ const slug = coerceStr(args, "slug", true)!;
+ const opts = {
+ ...(reason ? { reason } : {}),
+ ...(agent ? { agent } : {}),
+ };
+ const fn =
+ action === "confirm"
+ ? confirmTension
+ : action === "dismiss"
+ ? dismissTension
+ : resolveTension;
+ const t = fn(ctx.vault, slug, opts);
+ return { action, ...renderRow(t) };
+ }
+ default:
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${TOOL}: 'action' must be one of detect, list, show, confirm, dismiss, resolve`,
+ );
+ }
+ });
+}
+
+export const TENSION_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: TOOL,
+ description:
+ "Persisted-contradiction (tension) lifecycle. action: detect scans notes.read_paths and persists contradictions as open tensions (idempotent); list/show read; confirm=open->confirmed; dismiss/resolve close. Invalid transitions error. Unresolved tensions warn at context-pack injection.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: {
+ type: "string",
+ enum: ["detect", "list", "show", "confirm", "dismiss", "resolve"],
+ description: "Which tension operation to run.",
+ },
+ slug: {
+ type: "string",
+ description: "show/confirm/dismiss/resolve: the tension slug.",
+ },
+ jaccard: {
+ type: "number",
+ description:
+ "detect: minimum prose token overlap (0, 1] for two notes to count as the same subject. Defaults to the shared health threshold.",
+ },
+ unresolved: {
+ type: "boolean",
+ description: "list: return only open/confirmed (unresolved) tensions.",
+ },
+ reason: {
+ type: "string",
+ description: "dismiss/resolve: operator reason recorded on the transition.",
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["action"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainTension,
+ },
+]);
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index 2d633544..e7573b2a 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -197,6 +197,7 @@ const SEARCH_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
endLine: { type: "integer" },
searchType: { type: "string" },
reasons: { type: "array", items: { type: "string" } },
+ authoredAt: { type: "integer" },
score_breakdown: {
type: "object",
properties: {
@@ -635,6 +636,9 @@ async function toolBrainSearch(
endLine: r.endLine,
searchType: r.searchType,
reasons: r.reasons,
+ // Conversation chronology (S1): present only for a note carrying an
+ // authored_at instant, so the shape stays byte-identical otherwise.
+ ...(r.authoredAt !== undefined ? { authoredAt: r.authoredAt } : {}),
...(explain ? { score_breakdown: projectScoreBreakdown(r) } : {}),
...(r.trust !== undefined ? { trust: r.trust } : {}),
...(r.origin !== undefined ? { origin: r.origin } : {}),
diff --git a/tests/cli/brain-authored-at-backfill-cli.test.ts b/tests/cli/brain-authored-at-backfill-cli.test.ts
new file mode 100644
index 00000000..e94e3867
--- /dev/null
+++ b/tests/cli/brain-authored-at-backfill-cli.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { parseFrontmatter } from "../../src/core/vault.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-authored-at-cli-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+async function bootstrap(): Promise<void> {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+ const brainInit = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(brainInit.returncode).toBe(0);
+}
+
+/** A pre-feature session signal: turn instant preserved, no authored_at. */
+function oldSessionSignal(): string {
+ const { path } = writeSignal(vault, {
+ topic: "alpha",
+ signal: "positive",
+ agent: "test",
+ principle: "pre-feature session turn",
+ created_at: "2026-05-20T10:00:00Z",
+ date: "2026-05-20",
+ slug: "alpha",
+ source_type: "session",
+ valid_from: "2026-05-20T10:00:00Z",
+ recorded_at: "2026-05-20T10:00:00Z",
+ });
+ return path;
+}
+
+test("authored-at-backfill dry-run reports candidates without writing", async () => {
+ await bootstrap();
+ const path = oldSessionSignal();
+
+ const result = await runCli(["brain", "authored-at-backfill", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(result.returncode).toBe(0);
+ const payload = JSON.parse(result.stdout);
+ expect(payload.ok).toBe(true);
+ expect(payload.dry_run).toBe(true);
+ expect(payload.updated).toBe(0);
+ expect(payload.candidates).toHaveLength(1);
+ expect(parseFrontmatter(path)[0]["authored_at"]).toBeUndefined();
+});
+
+test("authored-at-backfill --apply stamps the field and is idempotent", async () => {
+ await bootstrap();
+ const path = oldSessionSignal();
+
+ const applied = await runCli(
+ ["brain", "authored-at-backfill", "--vault", vault, "--apply", "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(applied.returncode).toBe(0);
+ expect(JSON.parse(applied.stdout).updated).toBe(1);
+ expect(parseFrontmatter(path)[0]["authored_at"]).toBe("2026-05-20T10:00:00Z");
+
+ const rerun = await runCli(
+ ["brain", "authored-at-backfill", "--vault", vault, "--apply", "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(rerun.returncode).toBe(0);
+ expect(JSON.parse(rerun.stdout).updated).toBe(0);
+});
diff --git a/tests/cli/brain-decision.test.ts b/tests/cli/brain-decision.test.ts
new file mode 100644
index 00000000..880ae6b1
--- /dev/null
+++ b/tests/cli/brain-decision.test.ts
@@ -0,0 +1,358 @@
+/**
+ * Tests for `o2b brain decision <action>` CLI verb (Belief lifecycle
+ * suite, Track B anchor, t_ac03214d).
+ */
+
+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 { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let configDir: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-decision-cli-"));
+ configDir = mkdtempSync(join(tmpdir(), "o2b-brain-decision-cli-cfg-"));
+ vault = join(tmp, "vault");
+ configPath = join(configDir, "config.yaml");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+const env = { OPEN_SECOND_BRAIN_CONFIG: "", VAULT_AGENT_NAME: "" } as const;
+
+describe("o2b brain decision", () => {
+ test("record captures a decision and opens a review obligation", async () => {
+ const r = await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Adopt Bun runtime",
+ "--chosen",
+ "Bun",
+ "--assumption",
+ "Bun stays compatible",
+ "--review-date",
+ "2026-12-01",
+ "--json",
+ ],
+ { env },
+ );
+ expect(r.returncode).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.id).toBe("decision-adopt-bun-runtime");
+ expect(out.obligation_created).toBe(true);
+ });
+
+ test("outcome backfill and list", async () => {
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Adopt Bun runtime",
+ "--chosen",
+ "Bun",
+ "--assumption",
+ "x",
+ "--review-date",
+ "2026-12-01",
+ ],
+ { env },
+ );
+ const oc = await runCli(
+ [
+ "brain",
+ "decision",
+ "outcome",
+ "adopt-bun-runtime",
+ "--config",
+ configPath,
+ "--outcome",
+ "held up",
+ ],
+ { env },
+ );
+ expect(oc.returncode).toBe(0);
+ const list = await runCli(["brain", "decision", "list", "--config", configPath, "--json"], {
+ env,
+ });
+ const { decisions } = JSON.parse(list.stdout);
+ expect(decisions[0].outcome).toBe("held up");
+ });
+
+ test("rate and list --rated (B2)", async () => {
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Option A",
+ "--chosen",
+ "A",
+ "--assumption",
+ "x",
+ "--review-date",
+ "2026-12-01",
+ "--rating",
+ "4",
+ ],
+ { env },
+ );
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Option B",
+ "--chosen",
+ "B",
+ "--assumption",
+ "y",
+ "--review-date",
+ "2026-12-01",
+ ],
+ { env },
+ );
+ const rate = await runCli(
+ ["brain", "decision", "rate", "option-b", "--config", configPath, "--rating", "5", "--json"],
+ { env },
+ );
+ expect(rate.returncode).toBe(0);
+ expect(JSON.parse(rate.stdout).rating).toBe(5);
+
+ const list = await runCli(
+ ["brain", "decision", "list", "--rated", "--config", configPath, "--json"],
+ { env },
+ );
+ const { decisions } = JSON.parse(list.stdout);
+ expect(decisions.map((d: { rating: number }) => d.rating)).toEqual([5, 4]);
+ });
+
+ test("recall is disabled unless configured (B5)", async () => {
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Adopt Bun runtime",
+ "--chosen",
+ "Bun",
+ "--assumption",
+ "x",
+ "--review-date",
+ "2026-12-01",
+ "--rating",
+ "5",
+ ],
+ { env },
+ );
+ const off = await runCli(
+ [
+ "brain",
+ "decision",
+ "recall",
+ "--config",
+ configPath,
+ "--prompt",
+ "adopt Bun runtime",
+ "--json",
+ ],
+ { env },
+ );
+ expect(JSON.parse(off.stdout).enabled).toBe(false);
+
+ const on = await runCli(
+ [
+ "brain",
+ "decision",
+ "recall",
+ "--config",
+ configPath,
+ "--prompt",
+ "adopt Bun runtime for the API",
+ "--json",
+ ],
+ { env: { ...env, OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION: "3" } },
+ );
+ const parsed = JSON.parse(on.stdout);
+ expect(parsed.enabled).toBe(true);
+ expect(parsed.surfaced.slug).toBe("adopt-bun-runtime");
+ });
+
+ test("show/list surface commitment when set and omit it when unset (B3)", async () => {
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Committed choice",
+ "--chosen",
+ "X",
+ "--assumption",
+ "a",
+ "--review-date",
+ "2026-12-01",
+ "--commitment",
+ "decided",
+ ],
+ { env },
+ );
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Loose choice",
+ "--chosen",
+ "Y",
+ "--assumption",
+ "b",
+ "--review-date",
+ "2026-12-01",
+ ],
+ { env },
+ );
+
+ const shownSet = await runCli(
+ ["brain", "decision", "show", "committed-choice", "--config", configPath, "--json"],
+ { env },
+ );
+ expect(JSON.parse(shownSet.stdout).commitment).toBe("decided");
+
+ const shownUnset = await runCli(
+ ["brain", "decision", "show", "loose-choice", "--config", configPath, "--json"],
+ { env },
+ );
+ expect("commitment" in JSON.parse(shownUnset.stdout)).toBe(false);
+
+ const list = await runCli(["brain", "decision", "list", "--config", configPath, "--json"], {
+ env,
+ });
+ const { decisions } = JSON.parse(list.stdout);
+ const committed = decisions.find((d: { slug: string }) => d.slug === "committed-choice");
+ const loose = decisions.find((d: { slug: string }) => d.slug === "loose-choice");
+ expect(committed.commitment).toBe("decided");
+ expect("commitment" in loose).toBe(false);
+ });
+
+ test("recall threads governor cap and surfaced-id state from CLI flags (B5)", async () => {
+ await runCli(
+ [
+ "brain",
+ "decision",
+ "record",
+ "--config",
+ configPath,
+ "--title",
+ "Adopt Bun runtime",
+ "--chosen",
+ "Bun",
+ "--assumption",
+ "x",
+ "--review-date",
+ "2026-12-01",
+ "--rating",
+ "5",
+ ],
+ { env },
+ );
+ const recallEnv = { ...env, OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION: "3" };
+
+ // Fresh state surfaces the matching rated decision.
+ const first = await runCli(
+ [
+ "brain",
+ "decision",
+ "recall",
+ "--config",
+ configPath,
+ "--prompt",
+ "adopt Bun runtime for the API",
+ "--json",
+ ],
+ { env: recallEnv },
+ );
+ expect(JSON.parse(first.stdout).surfaced.slug).toBe("adopt-bun-runtime");
+
+ // --count at the cap gates recall (cap passthrough).
+ const capped = await runCli(
+ [
+ "brain",
+ "decision",
+ "recall",
+ "--config",
+ configPath,
+ "--prompt",
+ "adopt Bun runtime for the API",
+ "--count",
+ "3",
+ "--json",
+ ],
+ { env: recallEnv },
+ );
+ const cappedOut = JSON.parse(capped.stdout);
+ expect(cappedOut.enabled).toBe(true);
+ expect(cappedOut.surfaced).toBeNull();
+
+ // --surfaced-ids marks the only match already seen, so it is not re-surfaced.
+ const seen = await runCli(
+ [
+ "brain",
+ "decision",
+ "recall",
+ "--config",
+ configPath,
+ "--prompt",
+ "adopt Bun runtime for the API",
+ "--surfaced-ids",
+ "decision-adopt-bun-runtime",
+ "--json",
+ ],
+ { env: recallEnv },
+ );
+ const seenOut = JSON.parse(seen.stdout);
+ expect(seenOut.surfaced).toBeNull();
+ expect(seenOut.state.surfaced_ids).toContain("decision-adopt-bun-runtime");
+ });
+
+ test("missing required flags exit non-zero", async () => {
+ const r = await runCli(
+ ["brain", "decision", "record", "--config", configPath, "--title", "x"],
+ { env },
+ );
+ expect(r.returncode).not.toBe(0);
+ });
+});
diff --git a/tests/cli/brain-lifecycle-cli.test.ts b/tests/cli/brain-lifecycle-cli.test.ts
new file mode 100644
index 00000000..7a7520de
--- /dev/null
+++ b/tests/cli/brain-lifecycle-cli.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Tests for `o2b brain lifecycle <action>` CLI verb, focused on the
+ * temporal-replace action (Belief lifecycle suite, A2, t_3ba9c404).
+ *
+ * The core `temporalReplace` had no reachable production caller; this
+ * asserts the CLI verb wires it end to end.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeFrontmatter, parseFrontmatter } from "../../src/core/vault.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let configDir: string;
+let vault: string;
+let configPath: string;
+
+const env = { OPEN_SECOND_BRAIN_CONFIG: "", VAULT_AGENT_NAME: "" } as const;
+const AT = "2026-07-18T12:00:00Z";
+
+function writeFact(slug: string): string {
+ const rel = join("Brain", "preferences", `pref-${slug}.md`);
+ writeFrontmatter(
+ join(vault, rel),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `fact ${slug}`,
+ },
+ "Prose.",
+ );
+ return rel;
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-lifecycle-cli-"));
+ configDir = mkdtempSync(join(tmpdir(), "o2b-brain-lifecycle-cli-cfg-"));
+ vault = join(tmp, "vault");
+ configPath = join(configDir, "config.yaml");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ Bun.write(configPath, `vault: ${vault}\nagent_name: tester\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+describe("o2b brain lifecycle temporal-replace", () => {
+ test("closes the predecessor and opens the successor at one shared instant", async () => {
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+ const r = await runCli(
+ [
+ "brain",
+ "lifecycle",
+ "temporal-replace",
+ pred,
+ succ,
+ "--config",
+ configPath,
+ "--at",
+ AT,
+ "--json",
+ ],
+ { env },
+ );
+ expect(r.returncode).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.at).toBe(AT);
+ expect(out.predecessor).toBe("Brain/preferences/pref-old.md");
+ expect(out.successor).toBe("Brain/preferences/pref-new.md");
+
+ const [predMeta] = parseFrontmatter(join(vault, pred));
+ const [succMeta] = parseFrontmatter(join(vault, succ));
+ expect(predMeta["valid_until"]).toBe(AT);
+ expect(predMeta["superseded_by"]).toBe("[[pref-new]]");
+ expect(succMeta["valid_from"]).toBe(AT);
+ });
+
+ test("requires predecessor, successor, and --at", async () => {
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+ const missingAt = await runCli(
+ ["brain", "lifecycle", "temporal-replace", pred, succ, "--config", configPath],
+ { env },
+ );
+ expect(missingAt.returncode).not.toBe(0);
+
+ const missingSucc = await runCli(
+ ["brain", "lifecycle", "temporal-replace", pred, "--config", configPath, "--at", AT],
+ { env },
+ );
+ expect(missingSucc.returncode).not.toBe(0);
+ });
+});
diff --git a/tests/cli/brain-tension.test.ts b/tests/cli/brain-tension.test.ts
new file mode 100644
index 00000000..5f11b061
--- /dev/null
+++ b/tests/cli/brain-tension.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Tests for `o2b brain tension <action>` CLI verb (Belief lifecycle
+ * suite, S2, t_0e3f2bee).
+ */
+
+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 { runCli } from "../helpers/run-cli.ts";
+import { persistTension } from "../../src/core/brain/tensions.ts";
+import type { NoteContradictionFinding } from "../../src/core/brain/health/contradiction.ts";
+
+let tmp: string;
+let configDir: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-tension-cli-"));
+ configDir = mkdtempSync(join(tmpdir(), "o2b-brain-tension-cli-cfg-"));
+ vault = join(tmp, "vault");
+ configPath = join(configDir, "config.yaml");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+const env = { OPEN_SECOND_BRAIN_CONFIG: "", VAULT_AGENT_NAME: "" } as const;
+
+function seed(): string {
+ const finding: NoteContradictionFinding = {
+ aId: "pref-tabs",
+ bId: "pref-spaces",
+ subject: "tabs use",
+ jaccard: 0.6,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "Always use tabs.",
+ bQuote: "Never use tabs.",
+ action: "ask_user",
+ };
+ return persistTension(vault, finding, { agent: "tester" }).record.slug;
+}
+
+describe("o2b brain tension detect", () => {
+ test("scans the note corpus and persists a tension", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nnotes:\n read_paths:\n - Notes\n",
+ "utf8",
+ );
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Notes", "tabs.md"),
+ "---\nid: note-tabs\n---\nAlways use tabs for indentation in source files.\n",
+ "utf8",
+ );
+ writeFileSync(
+ join(vault, "Notes", "spaces.md"),
+ "---\nid: note-spaces\n---\nNever use tabs for indentation in source files.\n",
+ "utf8",
+ );
+ const r = await runCli(["brain", "tension", "detect", "--config", configPath, "--json"], {
+ env,
+ });
+ expect(r.returncode).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.scanned_files).toBe(2);
+ expect(out.created).toBe(1);
+ expect(out.tensions.length).toBe(1);
+ expect(out.tensions[0].status).toBe("open");
+ });
+
+ test("rejects an out-of-range --jaccard", async () => {
+ const r = await runCli(
+ ["brain", "tension", "detect", "--config", configPath, "--jaccard", "2"],
+ { env },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("--jaccard must be a number in (0, 1]");
+ });
+});
+
+describe("o2b brain tension", () => {
+ test("list surfaces a persisted open tension", async () => {
+ seed();
+ const r = await runCli(["brain", "tension", "list", "--config", configPath, "--json"], { env });
+ expect(r.returncode).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.tensions.length).toBe(1);
+ expect(out.tensions[0].status).toBe("open");
+ });
+
+ test("confirm transitions open -> confirmed", async () => {
+ const slug = seed();
+ const r = await runCli(
+ ["brain", "tension", "confirm", slug, "--config", configPath, "--json"],
+ { env },
+ );
+ expect(r.returncode).toBe(0);
+ expect(JSON.parse(r.stdout).status).toBe("confirmed");
+ });
+
+ test("resolve then confirm is rejected as an invalid transition", async () => {
+ const slug = seed();
+ await runCli(["brain", "tension", "resolve", slug, "--config", configPath], { env });
+ const bad = await runCli(["brain", "tension", "confirm", slug, "--config", configPath], {
+ env,
+ });
+ expect(bad.returncode).toBe(1);
+ expect(bad.stderr).toContain("invalid tension transition");
+ });
+
+ test("dismiss records a reason and drops it from --unresolved", async () => {
+ const slug = seed();
+ await runCli(
+ ["brain", "tension", "dismiss", slug, "--config", configPath, "--reason", "false alarm"],
+ { env },
+ );
+ const r = await runCli(
+ ["brain", "tension", "list", "--config", configPath, "--unresolved", "--json"],
+ { env },
+ );
+ expect(JSON.parse(r.stdout).tensions.length).toBe(0);
+ });
+});
diff --git a/tests/cli/search.test.ts b/tests/cli/search.test.ts
index 017d6c2c..1dc14e49 100644
--- a/tests/cli/search.test.ts
+++ b/tests/cli/search.test.ts
@@ -275,3 +275,41 @@ test("search --evidence-pack --json exposes verification fields (union, complete
expect(pack.completeness.verdict).toBe("sparse");
expect(pack.completeness.uncovered_but_present_in_corpus.toSorted()).toEqual(["alpha", "zephyr"]);
});
+
+test("search query --json surfaces authored_at when present, omits it otherwise", async () => {
+ writeVaultFile(
+ "Brain/inbox/sig-dated.md",
+ "---\nkind: brain-signal\nsource_type: session\nauthored_at: 2026-05-20T10:00:00Z\n---\n\n# Turn\n\nchronology alpha token discussed here.",
+ );
+ writeVaultFile(
+ "Brain/inbox/sig-plain.md",
+ "---\nkind: brain-signal\nsource_type: session\n---\n\n# Turn\n\nchronology alpha token discussed here.",
+ );
+ await runCli(["search", "index"], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+
+ const out = await runCli(["search", "chronology alpha token", "--json", "--limit", "10"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(out.returncode).toBe(0);
+ const obj = JSON.parse(out.stdout);
+ const dated = obj.results.find((r: { path: string }) => r.path === "Brain/inbox/sig-dated.md");
+ const plain = obj.results.find((r: { path: string }) => r.path === "Brain/inbox/sig-plain.md");
+ expect(dated).toBeDefined();
+ expect(plain).toBeDefined();
+ expect(dated.authored_at).toBe(Math.floor(Date.parse("2026-05-20T10:00:00Z") / 1000));
+ expect("authored_at" in plain).toBe(false);
+});
+
+test("search query --verbose prints an authored line only when present", async () => {
+ writeVaultFile(
+ "Brain/inbox/sig-dated.md",
+ "---\nkind: brain-signal\nsource_type: session\nauthored_at: 2026-05-20T10:00:00Z\n---\n\n# Turn\n\nchronology alpha token discussed here.",
+ );
+ await runCli(["search", "index"], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+
+ const out = await runCli(["search", "chronology alpha token", "--verbose"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(out.returncode).toBe(0);
+ expect(out.stdout).toContain("authored 2026-05-20T10:00:00.000Z");
+});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 04572808..4043ab97 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -97,6 +97,23 @@ describe("BRAIN_* const enums", () => {
"write-conflict-advisory",
// A5 (t_66c12a67) fact signal retire lifecycle
"signal-retire",
+ // Belief lifecycle suite (t_7d5a3589) cross-type tombstone + supersede
+ "tombstone",
+ // Belief lifecycle suite (t_3ba9c404) atomic temporal fact-replacement
+ "temporal-replace",
+ // Belief lifecycle suite (t_d9365884) supersedes-chain decay acceleration
+ "chain-decay",
+ // Belief lifecycle suite (t_ac03214d) decision-record capture + outcome backfill
+ "decision-record",
+ "decision-outcome",
+ // Belief lifecycle suite (t_6fe43fcc) decision rating update
+ "decision-rating",
+ // Belief lifecycle suite (t_3547314d) decision-change receipt append
+ "decision-change-receipt",
+ // Conversation chronology (t_347e8224) authored_at backfill
+ "authored-at-backfill",
+ // Belief lifecycle suite (t_0e3f2bee) tension object detect + transitions
+ "tension",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
diff --git a/tests/core/brain/authored-at-backfill.test.ts b/tests/core/brain/authored-at-backfill.test.ts
new file mode 100644
index 00000000..20bd2af2
--- /dev/null
+++ b/tests/core/brain/authored-at-backfill.test.ts
@@ -0,0 +1,124 @@
+/**
+ * Conversation-chronology backfill (S1 / t_347e8224).
+ *
+ * - Dry-run by DEFAULT: never writes; reports the candidates.
+ * - Applies the additive `authored_at` field to session signals that
+ * preserved a turn instant (valid_from/recorded_at) but predate it.
+ * - Idempotent: a re-run over an already-backfilled vault is a no-op.
+ * - Documents without a turn instant are unchanged.
+ * - Non-session / non-signal files are ignored.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { planAuthoredAtBackfill } from "../../../src/core/brain/authored-at-backfill.ts";
+import { parseSignal, writeSignal } from "../../../src/core/brain/signal.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-authored-backfill-"));
+ const dirs = brainDirs(vault);
+ for (const d of [dirs.brain, dirs.inbox, dirs.processed, dirs.retired]) {
+ mkdirSync(d, { recursive: true });
+ }
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+/** A pre-feature session signal: turn instant preserved, no authored_at. */
+function oldSessionSignal(slug: string, instant: string): string {
+ const { path } = writeSignal(vault, {
+ topic: slug,
+ signal: "positive",
+ agent: "test",
+ principle: `pre-feature session turn ${slug}`,
+ created_at: instant,
+ date: instant.slice(0, 10),
+ slug,
+ source_type: "session",
+ valid_from: instant,
+ recorded_at: instant,
+ });
+ return path;
+}
+
+function frontmatter(path: string): Record<string, unknown> {
+ return parseFrontmatter(path)[0] as Record<string, unknown>;
+}
+
+describe("planAuthoredAtBackfill", () => {
+ test("dry-run (default) reports candidates without writing", () => {
+ const path = oldSessionSignal("alpha", "2026-05-20T10:00:00Z");
+ expect(frontmatter(path)["authored_at"]).toBeUndefined();
+
+ const result = planAuthoredAtBackfill(vault);
+ expect(result.applied).toBe(false);
+ expect(result.updated).toBe(0);
+ expect(result.candidates.map((c) => c.authoredAt)).toEqual(["2026-05-20T10:00:00Z"]);
+ // No write happened.
+ expect(frontmatter(path)["authored_at"]).toBeUndefined();
+ });
+
+ test("apply stamps authored_at from the preserved turn instant", () => {
+ const path = oldSessionSignal("beta", "2026-05-20T11:30:00Z");
+
+ const result = planAuthoredAtBackfill(vault, { apply: true });
+ expect(result.applied).toBe(true);
+ expect(result.updated).toBe(1);
+ expect(frontmatter(path)["authored_at"]).toBe("2026-05-20T11:30:00Z");
+ // The rest of the signal still parses cleanly.
+ const sig = parseSignal(path);
+ expect(sig.valid_from).toBe("2026-05-20T11:30:00Z");
+ });
+
+ test("re-run after apply is an idempotent no-op", () => {
+ oldSessionSignal("gamma", "2026-05-20T12:00:00Z");
+ expect(planAuthoredAtBackfill(vault, { apply: true }).updated).toBe(1);
+ const second = planAuthoredAtBackfill(vault, { apply: true });
+ expect(second.updated).toBe(0);
+ expect(second.candidates).toHaveLength(0);
+ });
+
+ test("a signal with no turn instant is unchanged", () => {
+ const { path } = writeSignal(vault, {
+ topic: "live",
+ signal: "positive",
+ agent: "test",
+ principle: "a live signal with no turn instant",
+ created_at: "2026-05-20T13:00:00Z",
+ date: "2026-05-20",
+ slug: "live",
+ source_type: "session",
+ // No valid_from / recorded_at β†’ no turn instant.
+ });
+ const result = planAuthoredAtBackfill(vault, { apply: true });
+ expect(result.updated).toBe(0);
+ expect(frontmatter(path)["authored_at"]).toBeUndefined();
+ });
+
+ test("a non-session signal is not touched", () => {
+ const { path } = writeSignal(vault, {
+ topic: "inline",
+ signal: "positive",
+ agent: "test",
+ principle: "an inline signal, not from a session",
+ created_at: "2026-05-20T14:00:00Z",
+ date: "2026-05-20",
+ slug: "inline",
+ source_type: "inline",
+ valid_from: "2026-05-20T14:00:00Z",
+ });
+ const result = planAuthoredAtBackfill(vault, { apply: true });
+ expect(result.scanned).toBe(0);
+ expect(result.updated).toBe(0);
+ expect(frontmatter(path)["authored_at"]).toBeUndefined();
+ });
+});
diff --git a/tests/core/brain/claim-graph.test.ts b/tests/core/brain/claim-graph.test.ts
new file mode 100644
index 00000000..15037cba
--- /dev/null
+++ b/tests/core/brain/claim-graph.test.ts
@@ -0,0 +1,148 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeFrontmatter } from "../../../src/core/vault.ts";
+import { tombstone } from "../../../src/core/brain/lifecycle/tombstone.ts";
+import { temporalReplace } from "../../../src/core/brain/lifecycle/temporal-replace.ts";
+import {
+ CLAIM_GRAPH_MAX_NODES,
+ allClaims,
+ buildClaimGraph,
+ currentTruth,
+ loadClaimGraph,
+ rebuildClaimGraph,
+ truthAt,
+ whatContests,
+ whatReplaced,
+} from "../../../src/core/brain/claim-graph.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-claim-graph-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeFact(slug: string, meta: Record<string, string | string[]> = {}): string {
+ const rel = join("Brain", "preferences", `pref-${slug}.md`);
+ writeFrontmatter(
+ join(vault, rel),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `fact ${slug}`,
+ tags: ["brain"],
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-02-01T00:00:00Z",
+ ...meta,
+ },
+ "Prose.",
+ );
+ return rel;
+}
+
+test("buildClaimGraph projects nodes from existing frontmatter relations", () => {
+ writeFact("a", { provenance: "stated" });
+ writeFact("b", { contradicts: ["[[pref-a]]"] });
+
+ const graph = buildClaimGraph(vault);
+ expect(graph.nodes.length).toBe(2);
+ const a = graph.nodes.find((n) => n.id === "pref-a")!;
+ const b = graph.nodes.find((n) => n.id === "pref-b")!;
+ expect(a.provenance).toBe("stated");
+ expect(b.contradicts).toContain("pref-a");
+});
+
+test("currentTruth excludes tombstoned claims but keeps live tips", () => {
+ writeFact("live");
+ const doomed = writeFact("doomed");
+ tombstone({ vault, path: doomed, reason: "wrong", now: new Date("2026-07-18T00:00:00Z") });
+
+ const graph = buildClaimGraph(vault);
+ const truth = currentTruth(graph);
+ const ids = truth.map((n) => n.id);
+ expect(ids).toContain("pref-live");
+ expect(ids).not.toContain("pref-doomed");
+});
+
+test("history (allClaims) includes tombstoned claims for audit", () => {
+ const doomed = writeFact("doomed");
+ tombstone({ vault, path: doomed, reason: "wrong", now: new Date("2026-07-18T00:00:00Z") });
+
+ const graph = buildClaimGraph(vault);
+ expect(allClaims(graph).map((n) => n.id)).toContain("pref-doomed");
+});
+
+test("truthAt returns the historically-valid claim at a past instant", () => {
+ const pred = writeFact("v1", { valid_from: "2026-01-01T00:00:00Z" });
+ const succ = writeFact("v2");
+ temporalReplace({ vault, predecessor: pred, successor: succ, at: "2026-06-01T00:00:00Z" });
+
+ const graph = buildClaimGraph(vault);
+ // Before the switch: v1 is the truth (temporal-replace does not tombstone).
+ const past = truthAt(graph, Date.parse("2026-03-01T00:00:00Z")).map((n) => n.id);
+ expect(past).toContain("pref-v1");
+ expect(past).not.toContain("pref-v2");
+ // After the switch: v2 is the truth.
+ const now = truthAt(graph, Date.parse("2026-09-01T00:00:00Z")).map((n) => n.id);
+ expect(now).toContain("pref-v2");
+ expect(now).not.toContain("pref-v1");
+});
+
+test("whatReplaced follows the supersede chain to the live tip", () => {
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+ temporalReplace({ vault, predecessor: pred, successor: succ, at: "2026-06-01T00:00:00Z" });
+
+ const graph = buildClaimGraph(vault);
+ const tip = whatReplaced(graph, "pref-old");
+ expect(tip?.id).toBe("pref-new");
+});
+
+test("whatContests returns claims on either side of a contradiction", () => {
+ writeFact("x");
+ writeFact("y", { contradicts: ["[[pref-x]]"] });
+
+ const graph = buildClaimGraph(vault);
+ expect(whatContests(graph, "pref-x").map((n) => n.id)).toContain("pref-y");
+ expect(whatContests(graph, "pref-y").map((n) => n.id)).toContain("pref-x");
+});
+
+test("rebuild persists a JSON artifact and loadClaimGraph reads it back", () => {
+ writeFact("a");
+ const built = rebuildClaimGraph(vault);
+ const loaded = loadClaimGraph(vault);
+ expect(loaded).not.toBeNull();
+ expect(loaded!.nodes.map((n) => n.id)).toEqual(built.nodes.map((n) => n.id));
+});
+
+test("rebuild is deterministic: identical vault state yields identical nodes", () => {
+ writeFact("b");
+ writeFact("a");
+ writeFact("c");
+ const g1 = buildClaimGraph(vault);
+ const g2 = buildClaimGraph(vault);
+ expect(g2.nodes).toEqual(g1.nodes);
+ // Sorted by a stable key so the projection is byte-stable across rebuilds.
+ const paths = g1.nodes.map((n) => n.path);
+ expect(paths).toEqual([...paths].toSorted());
+});
+
+test("the projection is bounded by a node cap", () => {
+ for (let i = 0; i < 5; i++) writeFact(`n${i}`);
+ const graph = buildClaimGraph(vault, { maxNodes: 3 });
+ expect(graph.nodes.length).toBe(3);
+ expect(graph.truncated).toBe(true);
+ expect(CLAIM_GRAPH_MAX_NODES).toBeGreaterThan(0);
+});
+
+test("loadClaimGraph returns null when no projection has been built", () => {
+ expect(loadClaimGraph(vault)).toBeNull();
+});
diff --git a/tests/core/brain/commitment.test.ts b/tests/core/brain/commitment.test.ts
new file mode 100644
index 00000000..d7a0cfb0
--- /dev/null
+++ b/tests/core/brain/commitment.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ BRAIN_COMMITMENT_TIER,
+ CommitmentError,
+ isCommitmentTier,
+ readCommitmentTier,
+ validateCommitmentTier,
+} from "../../../src/core/brain/commitment.ts";
+import { regenerateActive } from "../../../src/core/brain/active.ts";
+import { brainActivePath } from "../../../src/core/brain/paths.ts";
+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";
+import { recordThesis, showThesis } from "../../../src/core/brain/health/thesis.ts";
+import { recordDecision, showDecision } from "../../../src/core/brain/decisions/record.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-commitment-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("commitment vocabulary", () => {
+ test("validateCommitmentTier accepts the four tiers and rejects junk", () => {
+ for (const tier of Object.values(BRAIN_COMMITMENT_TIER)) {
+ expect(validateCommitmentTier(tier)).toBe(tier);
+ }
+ expect(validateCommitmentTier(undefined)).toBeNull();
+ expect(validateCommitmentTier("")).toBeNull();
+ expect(() => validateCommitmentTier("committed")).toThrow(CommitmentError);
+ expect(() => validateCommitmentTier(3)).toThrow(CommitmentError);
+ });
+
+ test("readCommitmentTier tolerates junk", () => {
+ expect(readCommitmentTier({ commitment: "locked" })).toBe("locked");
+ expect(readCommitmentTier({ commitment: "nonsense" })).toBeNull();
+ expect(readCommitmentTier({})).toBeNull();
+ expect(isCommitmentTier("decided")).toBe(true);
+ expect(isCommitmentTier("x")).toBe(false);
+ });
+});
+
+function seedPref(slug: string, extra: Record<string, unknown> = {}): string {
+ return writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `principle ${slug}`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 5,
+ violated_count: 0,
+ last_evidence_at: "2026-05-09T00:00:00Z",
+ confidence: "high",
+ confidence_value: 0.87,
+ ...extra,
+ }).path;
+}
+
+describe("commitment round-trip on preferences", () => {
+ test("preference frontmatter round-trips a commitment tier", () => {
+ const path = seedPref("alpha", { commitment: "locked" });
+ const parsed = parsePreference(path);
+ expect(parsed.commitment).toBe("locked");
+ expect(readFileSync(path, "utf8")).toContain("commitment: locked");
+ });
+
+ test("invalid commitment on write rejects with a typed error", () => {
+ expect(() => seedPref("beta", { commitment: "committed" })).toThrow(CommitmentError);
+ });
+
+ test("unset commitment omits the frontmatter key", () => {
+ const path = seedPref("gamma");
+ expect(readFileSync(path, "utf8")).not.toContain("commitment:");
+ expect(parsePreference(path).commitment).toBeUndefined();
+ });
+});
+
+describe("active.md renders the tier in place of the confidence float", () => {
+ test("tier label replaces the numeric float when set", () => {
+ seedPref("locked-one", { commitment: "locked" });
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+ const body = readFileSync(brainActivePath(vault), "utf8");
+ expect(body).toContain("confidence: high (locked)");
+ expect(body).not.toContain("(0.87)");
+ });
+
+ test("byte-identical to today when unset (regression)", () => {
+ seedPref("plain-one");
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+ const withoutTier = readFileSync(brainActivePath(vault), "utf8");
+ expect(withoutTier).toContain("confidence: high (0.87)");
+ expect(withoutTier).not.toContain("(locked)");
+ });
+});
+
+describe("commitment round-trip on theses and decisions", () => {
+ test("thesis frontmatter round-trips a commitment tier", () => {
+ const page = recordThesis(vault, {
+ statement: "Bun is the right runtime",
+ agent: "tester",
+ commitment: "decided",
+ });
+ expect(showThesis(vault, page.slug)!.commitment).toBe("decided");
+ expect(readFileSync(page.path, "utf8")).toContain("commitment: decided");
+ });
+
+ test("thesis without commitment omits the key", () => {
+ const page = recordThesis(vault, { statement: "No tier here", agent: "tester" });
+ expect(readFileSync(page.path, "utf8")).not.toContain("commitment:");
+ expect(showThesis(vault, page.slug)!.commitment).toBeNull();
+ });
+
+ test("decision frontmatter round-trips a commitment tier", () => {
+ const res = recordDecision(vault, {
+ title: "Adopt Bun",
+ chosen: "Bun",
+ assumption: "compat",
+ reviewDate: "2026-12-01",
+ agent: "tester",
+ commitment: "leaning",
+ });
+ expect(showDecision(vault, res.record.slug)!.commitment).toBe("leaning");
+ expect(readFileSync(res.record.path, "utf8")).toContain("commitment: leaning");
+ });
+
+ test("invalid commitment on a decision rejects", () => {
+ expect(() =>
+ recordDecision(vault, {
+ title: "Bad tier",
+ chosen: "x",
+ assumption: "y",
+ reviewDate: "2026-12-01",
+ agent: "tester",
+ commitment: "committed" as never,
+ }),
+ ).toThrow(CommitmentError);
+ });
+});
diff --git a/tests/core/brain/context-pack-tensions.test.ts b/tests/core/brain/context-pack-tensions.test.ts
new file mode 100644
index 00000000..22967cea
--- /dev/null
+++ b/tests/core/brain/context-pack-tensions.test.ts
@@ -0,0 +1,102 @@
+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 { packContext } from "../../../src/core/brain/context-pack.ts";
+import {
+ dismissTension,
+ persistTension,
+ resolveTension,
+} from "../../../src/core/brain/tensions.ts";
+import type { NoteContradictionFinding } from "../../../src/core/brain/health/contradiction.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-cp-tensions-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, principle: string, body: string) {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ [
+ "---",
+ `id: pref-${slug}`,
+ "topic: t",
+ `principle: ${principle}`,
+ "tier: core",
+ "---",
+ "",
+ body,
+ ].join("\n"),
+ );
+}
+
+function finding(): NoteContradictionFinding {
+ return {
+ aId: "pref-tabs",
+ bId: "pref-spaces",
+ subject: "for indentation tabs use",
+ jaccard: 0.6,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "Always use tabs.",
+ bQuote: "Never use tabs.",
+ action: "ask_user",
+ };
+}
+
+describe("packContext tension warnings", () => {
+ test("a tension-free vault produces no warnings key (byte-identical)", () => {
+ writePref("tabs", "always use tabs", "Always use tabs.");
+ const report = packContext(vault, { maxTokens: 1000 });
+ expect(report.warnings).toBeUndefined();
+ });
+
+ test("injecting a subject note of an unresolved tension emits a warning naming it", () => {
+ writePref("tabs", "always use tabs", "Always use tabs.");
+ writePref("spaces", "never use tabs", "Never use tabs.");
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+
+ const report = packContext(vault, { maxTokens: 1000 });
+ expect(report.warnings).toBeDefined();
+ expect(report.warnings!.length).toBeGreaterThanOrEqual(1);
+ expect(report.warnings!.some((w) => w.includes(record.id))).toBe(true);
+ });
+
+ test("a dismissed tension emits no warning", () => {
+ writePref("tabs", "always use tabs", "Always use tabs.");
+ writePref("spaces", "never use tabs", "Never use tabs.");
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ dismissTension(vault, record.slug, { agent: "tester" });
+
+ const report = packContext(vault, { maxTokens: 1000 });
+ expect(report.warnings).toBeUndefined();
+ });
+
+ test("a resolved tension emits no warning", () => {
+ writePref("tabs", "always use tabs", "Always use tabs.");
+ writePref("spaces", "never use tabs", "Never use tabs.");
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ resolveTension(vault, record.slug, { agent: "tester" });
+
+ const report = packContext(vault, { maxTokens: 1000 });
+ expect(report.warnings).toBeUndefined();
+ });
+
+ test("a confirmed (still unresolved) tension still warns", () => {
+ writePref("tabs", "always use tabs", "Always use tabs.");
+ writePref("spaces", "never use tabs", "Never use tabs.");
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ // confirm keeps it unresolved
+ const cp = packContext(vault, { maxTokens: 1000 });
+ expect(cp.warnings).toBeDefined();
+ expect(record.status).toBe("open");
+ });
+});
diff --git a/tests/core/brain/decisions/recall.test.ts b/tests/core/brain/decisions/recall.test.ts
new file mode 100644
index 00000000..5a4fa8dc
--- /dev/null
+++ b/tests/core/brain/decisions/recall.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ EMPTY_DECISION_RECALL_STATE,
+ governDecisionRecall,
+ matchRatedDecisions,
+ type DecisionRecallState,
+} from "../../../../src/core/brain/inject-governor.ts";
+import { recallRatedDecisions } from "../../../../src/core/brain/decisions/recall.ts";
+import { recordDecision } from "../../../../src/core/brain/decisions/record.ts";
+
+describe("matchRatedDecisions (deterministic, language-agnostic)", () => {
+ const candidates = [
+ { id: "decision-adopt-bun", rating: 5, text: "Adopt Bun runtime for the CLI" },
+ { id: "decision-use-postgres", rating: 3, text: "Use Postgres for the ledger store" },
+ ];
+
+ test("matches on structural token overlap and ranks by overlap then rating", () => {
+ const hits = matchRatedDecisions("should we adopt Bun runtime for the server", candidates);
+ expect(hits.length).toBeGreaterThanOrEqual(1);
+ expect(hits[0]!.id).toBe("decision-adopt-bun");
+ });
+
+ test("no match below the overlap floor", () => {
+ expect(matchRatedDecisions("totally unrelated weather report", candidates)).toEqual([]);
+ });
+
+ test("empty prompt never matches", () => {
+ expect(matchRatedDecisions("", candidates)).toEqual([]);
+ });
+});
+
+describe("governDecisionRecall caps and spacing", () => {
+ const matches = [
+ { id: "a", rating: 5, overlap: 0.9 },
+ { id: "b", rating: 4, overlap: 0.8 },
+ ];
+
+ test("disabled when maxPerSession is null (byte-identical)", () => {
+ const res = governDecisionRecall({
+ matches,
+ state: EMPTY_DECISION_RECALL_STATE,
+ turn: 0,
+ config: { maxPerSession: null, minSpacingTurns: 0 },
+ });
+ expect(res.surface).toBeNull();
+ expect(res.state).toBe(EMPTY_DECISION_RECALL_STATE);
+ });
+
+ test("surfaces the top match and advances state", () => {
+ const res = governDecisionRecall({
+ matches,
+ state: EMPTY_DECISION_RECALL_STATE,
+ turn: 0,
+ config: { maxPerSession: 2, minSpacingTurns: 0 },
+ });
+ expect(res.surface!.id).toBe("a");
+ expect(res.state.count).toBe(1);
+ expect(res.state.surfacedIds).toEqual(["a"]);
+ });
+
+ test("per-session cap prevents further recalls", () => {
+ const state: DecisionRecallState = { surfacedIds: ["a"], lastTurn: 0, count: 1 };
+ const res = governDecisionRecall({
+ matches,
+ state,
+ turn: 5,
+ config: { maxPerSession: 1, minSpacingTurns: 0 },
+ });
+ expect(res.surface).toBeNull();
+ });
+
+ test("spacing prevents a recall too soon after the last", () => {
+ const state: DecisionRecallState = { surfacedIds: ["a"], lastTurn: 3, count: 1 };
+ const gated = governDecisionRecall({
+ matches,
+ state,
+ turn: 4,
+ config: { maxPerSession: 5, minSpacingTurns: 3 },
+ });
+ expect(gated.surface).toBeNull();
+
+ const allowed = governDecisionRecall({
+ matches,
+ state,
+ turn: 6,
+ config: { maxPerSession: 5, minSpacingTurns: 3 },
+ });
+ expect(allowed.surface!.id).toBe("b"); // "a" already surfaced, so next best
+ });
+
+ test("never re-surfaces an already-surfaced decision", () => {
+ const state: DecisionRecallState = { surfacedIds: ["a", "b"], lastTurn: 0, count: 2 };
+ const res = governDecisionRecall({
+ matches,
+ state,
+ turn: 10,
+ config: { maxPerSession: 5, minSpacingTurns: 0 },
+ });
+ expect(res.surface).toBeNull();
+ });
+});
+
+describe("recallRatedDecisions orchestrator", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-recall-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ recordDecision(vault, {
+ title: "Adopt Bun runtime for the CLI",
+ chosen: "Bun",
+ assumption: "compat",
+ reviewDate: "2026-12-01",
+ agent: "tester",
+ rating: 5,
+ });
+ });
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("unconfigured => disabled, nothing surfaced (byte-identical)", () => {
+ const res = recallRatedDecisions(vault, { prompt: "adopt Bun runtime again" });
+ expect(res.enabled).toBe(false);
+ expect(res.surfaced).toBeNull();
+ expect(res.text).toBe("");
+ });
+
+ test("configured => resurfaces the matching rated decision verbatim", () => {
+ process.env["OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION"] = "3";
+ try {
+ const res = recallRatedDecisions(vault, {
+ prompt: "should we adopt Bun runtime for the API",
+ });
+ expect(res.enabled).toBe(true);
+ expect(res.surfaced?.slug).toBe("adopt-bun-runtime-for-the-cli");
+ expect(res.text).toContain("Recalled decision");
+ expect(res.text).toContain("Bun");
+ expect(res.state.count).toBe(1);
+ } finally {
+ delete process.env["OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION"];
+ }
+ });
+});
diff --git a/tests/core/brain/decisions/receipts.test.ts b/tests/core/brain/decisions/receipts.test.ts
new file mode 100644
index 00000000..ed4dd7a8
--- /dev/null
+++ b/tests/core/brain/decisions/receipts.test.ts
@@ -0,0 +1,242 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ DECISION_CHANGE_SCHEMA_VERSION,
+ ReceiptError,
+ appendDecisionChangeReceipt,
+ normalizeDecisionSubject,
+ queryDecisionChangeHistory,
+ readDecisionChangeReceipts,
+} from "../../../../src/core/brain/decisions/receipts.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-receipts-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function baseInput(overrides: Record<string, unknown> = {}) {
+ return {
+ ts: "2026-07-18T12:00:00Z",
+ subject: "pref-no-abbrev",
+ before: "confidence:medium(0.55)",
+ after: "confidence:high(0.88)",
+ evidenceTriggers: ["[[sig-2026-07-01-x]]"],
+ confidenceDelta: 0.33,
+ alternatives: ["keep as medium"],
+ actor: "tester",
+ rationale: "accumulated applied evidence",
+ reasonCode: "confidence-refresh",
+ ...overrides,
+ };
+}
+
+describe("appendDecisionChangeReceipt", () => {
+ test("appends a decision_change.v1 receipt with all accountable fields", () => {
+ const res = appendDecisionChangeReceipt(vault, baseInput());
+ expect(res.appended).toBe(true);
+ expect(res.receipt.v).toBe(DECISION_CHANGE_SCHEMA_VERSION);
+ expect(res.receipt.subject).toBe("pref-no-abbrev");
+ expect(res.receipt.confidence_delta).toBe(0.33);
+ expect(res.receipt.reason_code).toBe("confidence-refresh");
+ expect(res.receipt.idempotency_key).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("replays are no-ops via the durable idempotency key", () => {
+ const first = appendDecisionChangeReceipt(vault, baseInput());
+ const second = appendDecisionChangeReceipt(vault, baseInput());
+ expect(second.appended).toBe(false);
+ expect(second.receipt.idempotency_key).toBe(first.receipt.idempotency_key);
+ expect(readDecisionChangeReceipts(vault).receipts.length).toBe(1);
+ });
+
+ test("a different before/after produces a distinct key and a new receipt", () => {
+ appendDecisionChangeReceipt(vault, baseInput());
+ appendDecisionChangeReceipt(vault, baseInput({ after: "confidence:high(0.90)" }));
+ expect(readDecisionChangeReceipts(vault).receipts.length).toBe(2);
+ });
+
+ test("rejects unexpected free-text reasoning fields", () => {
+ expect(() =>
+ appendDecisionChangeReceipt(vault, baseInput({ chain_of_thought: "secret reasoning" })),
+ ).toThrow(ReceiptError);
+ });
+
+ test("rejects a missing required field", () => {
+ const input = baseInput();
+ delete (input as Record<string, unknown>)["subject"];
+ expect(() => appendDecisionChangeReceipt(vault, input)).toThrow(ReceiptError);
+ });
+});
+
+describe("queryDecisionChangeHistory", () => {
+ function seed(n: number): void {
+ for (let i = 0; i < n; i++) {
+ appendDecisionChangeReceipt(
+ vault,
+ baseInput({
+ ts: `2026-07-${String(10 + i).padStart(2, "0")}T00:00:00Z`,
+ after: `confidence:high(0.${80 + i})`,
+ }),
+ );
+ }
+ }
+
+ test("paginates with an opaque cursor and reports exact counts", () => {
+ seed(5);
+ const page1 = queryDecisionChangeHistory(vault, { limit: 2 });
+ expect(page1.total).toBe(5);
+ expect(page1.receipts.length).toBe(2);
+ expect(page1.nextCursor).not.toBeNull();
+
+ const page2 = queryDecisionChangeHistory(vault, { limit: 2, cursor: page1.nextCursor! });
+ expect(page2.receipts.length).toBe(2);
+ const page3 = queryDecisionChangeHistory(vault, { limit: 2, cursor: page2.nextCursor! });
+ expect(page3.receipts.length).toBe(1);
+ expect(page3.nextCursor).toBeNull();
+
+ // No overlap across pages.
+ const keys = new Set(
+ [...page1.receipts, ...page2.receipts, ...page3.receipts].map((r) => r.idempotency_key),
+ );
+ expect(keys.size).toBe(5);
+ });
+
+ test("filters by subject", () => {
+ appendDecisionChangeReceipt(vault, baseInput({ subject: "pref-a" }));
+ appendDecisionChangeReceipt(vault, baseInput({ subject: "pref-b" }));
+ const page = queryDecisionChangeHistory(vault, { subject: "pref-a" });
+ expect(page.total).toBe(1);
+ expect(page.receipts[0]!.subject).toBe("pref-a");
+ });
+
+ test("a malformed cursor is rejected", () => {
+ seed(1);
+ expect(() => queryDecisionChangeHistory(vault, { cursor: "!!!not-base64!!!" })).toThrow(
+ ReceiptError,
+ );
+ });
+});
+
+describe("lifecycle hook", () => {
+ test("tombstone/supersede emits one decision-change receipt", async () => {
+ const { writeFrontmatter } = await import("../../../../src/core/vault.ts");
+ const { supersede } = await import("../../../../src/core/brain/lifecycle/tombstone.ts");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ writeFrontmatter(
+ join(vault, "Brain", "preferences", "pref-old.md"),
+ {
+ kind: "brain-preference",
+ id: "pref-old",
+ _status: "confirmed",
+ topic: "t",
+ principle: "p",
+ },
+ "body",
+ );
+ supersede({
+ vault,
+ predecessor: "Brain/preferences/pref-old.md",
+ successor: "pref-new",
+ agent: "tester",
+ });
+ const { receipts } = readDecisionChangeReceipts(vault);
+ expect(receipts.length).toBe(1);
+ expect(receipts[0]!.reason_code).toBe("supersede");
+ expect(receipts[0]!.after).toContain("superseded_by");
+ });
+});
+
+describe("normalizeDecisionSubject", () => {
+ test("bare id is unchanged", () => {
+ expect(normalizeDecisionSubject("decision-adopt-bun")).toBe("decision-adopt-bun");
+ });
+
+ test("strips wikilink fencing", () => {
+ expect(normalizeDecisionSubject("[[decision-adopt-bun]]")).toBe("decision-adopt-bun");
+ });
+
+ test("strips a vault-relative directory prefix and .md extension", () => {
+ expect(normalizeDecisionSubject("Brain/decisions/decision-adopt-bun.md")).toBe(
+ "decision-adopt-bun",
+ );
+ });
+
+ test("mixed form (wikilinked path) reduces to the same bare id", () => {
+ expect(normalizeDecisionSubject("[[Brain/decisions/decision-adopt-bun.md]]")).toBe(
+ "decision-adopt-bun",
+ );
+ });
+
+ test("distinct subjects stay distinct after normalization", () => {
+ expect(normalizeDecisionSubject("decision-adopt-bun")).not.toBe(
+ normalizeDecisionSubject("decision-adopt-deno"),
+ );
+ });
+});
+
+describe("queryDecisionChangeHistory subject matching (bare/wikilink/path forms)", () => {
+ test("a bare-path-stored subject (lifecycle receipt) matches a bare id query", () => {
+ appendDecisionChangeReceipt(
+ vault,
+ baseInput({ subject: "Brain/decisions/decision-adopt-bun.md" }),
+ );
+ const page = queryDecisionChangeHistory(vault, { subject: "decision-adopt-bun" });
+ expect(page.total).toBe(1);
+ });
+
+ test("a bare-path-stored subject matches a wikilinked query", () => {
+ appendDecisionChangeReceipt(
+ vault,
+ baseInput({ subject: "Brain/decisions/decision-adopt-bun.md" }),
+ );
+ const page = queryDecisionChangeHistory(vault, { subject: "[[decision-adopt-bun]]" });
+ expect(page.total).toBe(1);
+ });
+
+ test("a wikilink-stored subject (decision record receipt) matches a bare id query", () => {
+ appendDecisionChangeReceipt(vault, baseInput({ subject: "[[decision-adopt-bun]]" }));
+ const page = queryDecisionChangeHistory(vault, { subject: "decision-adopt-bun" });
+ expect(page.total).toBe(1);
+ });
+
+ test("--subject bare id and --subject wikilink return identical results", () => {
+ appendDecisionChangeReceipt(vault, baseInput({ subject: "[[decision-adopt-bun]]" }));
+ appendDecisionChangeReceipt(
+ vault,
+ baseInput({ subject: "[[decision-adopt-bun]]", after: "confidence:high(0.91)" }),
+ );
+ const byBareId = queryDecisionChangeHistory(vault, { subject: "decision-adopt-bun" });
+ const byWikilink = queryDecisionChangeHistory(vault, { subject: "[[decision-adopt-bun]]" });
+ expect(byBareId.total).toBe(2);
+ expect(byWikilink.total).toBe(2);
+ expect(byBareId.receipts.map((r) => r.idempotency_key)).toEqual(
+ byWikilink.receipts.map((r) => r.idempotency_key),
+ );
+ });
+
+ test("distinct subjects remain distinct: no cross-match", () => {
+ appendDecisionChangeReceipt(vault, baseInput({ subject: "[[decision-adopt-bun]]" }));
+ appendDecisionChangeReceipt(vault, baseInput({ subject: "[[decision-adopt-deno]]" }));
+ const page = queryDecisionChangeHistory(vault, { subject: "decision-adopt-bun" });
+ expect(page.total).toBe(1);
+ expect(page.receipts[0]!.subject).toBe("[[decision-adopt-bun]]");
+ });
+});
+
+describe("no receipt on reads", () => {
+ test("reading history never creates a receipt file", () => {
+ readDecisionChangeReceipts(vault);
+ queryDecisionChangeHistory(vault, {});
+ const truthDir = join(vault, "Brain", "truth");
+ const files = existsSync(truthDir) ? readdirSync(truthDir) : [];
+ expect(files.filter((f) => f.startsWith("decision-change")).length).toBe(0);
+ });
+});
diff --git a/tests/core/brain/decisions/record.test.ts b/tests/core/brain/decisions/record.test.ts
new file mode 100644
index 00000000..8c8f9bb6
--- /dev/null
+++ b/tests/core/brain/decisions/record.test.ts
@@ -0,0 +1,316 @@
+import { test, expect, beforeEach, afterEach, describe } from "bun:test";
+import { mkdirSync, mkdtempSync, existsSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../../../../src/core/vault.ts";
+import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import { listObligations } from "../../../../src/core/brain/obligations.ts";
+import { queryByTopic } from "../../../../src/core/brain/query.ts";
+import {
+ DECISION_TYPE,
+ DecisionError,
+ backfillOutcome,
+ compareDecisions,
+ findSimilarDecisions,
+ listDecisions,
+ listRatedDecisions,
+ recordDecision,
+ showDecision,
+ updateRating,
+} from "../../../../src/core/brain/decisions/record.ts";
+import {
+ DECISION_CHANGE_REASON,
+ queryDecisionChangeHistory,
+} from "../../../../src/core/brain/decisions/receipts.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-decision-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const NOW = new Date("2026-07-18T12:00:00Z");
+
+function baseInput(overrides: Record<string, unknown> = {}) {
+ return {
+ title: "Adopt Bun as the primary runtime",
+ chosen: "Bun",
+ assumption: "Bun stays API-compatible with our Node usage",
+ reviewDate: "2026-10-01",
+ agent: "tester",
+ now: NOW,
+ ...overrides,
+ };
+}
+
+describe("recordDecision", () => {
+ test("writes a type: decision note with the captured fields and empty outcome", () => {
+ const res = recordDecision(vault, baseInput({ premortem: "Bun ships a breaking change" }));
+ expect(res.record.type).toBe(DECISION_TYPE);
+ expect(res.record.chosen).toBe("Bun");
+ expect(res.record.assumption).toBe("Bun stays API-compatible with our Node usage");
+ expect(res.record.reviewDate).toBe("2026-10-01");
+ expect(res.record.outcome).toBe("");
+ expect(res.record.premortem).toBe("Bun ships a breaking change");
+ expect(existsSync(res.record.path)).toBe(true);
+
+ const [meta] = parseFrontmatter(res.record.path);
+ expect(meta["type"]).toBe("decision");
+ expect(meta["chosen"]).toBe("Bun");
+ expect(meta["review_date"]).toBe("2026-10-01");
+ expect(meta["outcome"]).toBe("");
+ });
+
+ test("premortem is optional", () => {
+ const res = recordDecision(vault, baseInput());
+ expect(res.record.premortem).toBeNull();
+ });
+
+ test("review_date opens exactly one obligation, idempotently", () => {
+ const res = recordDecision(vault, baseInput());
+ expect(res.obligationCreated).toBe(true);
+ const obligations = listObligations(vault);
+ expect(obligations.length).toBe(1);
+ expect(obligations[0]!.nextDue).toBe("2026-10-01");
+ });
+
+ test("logs a decision-record event", () => {
+ const res = recordDecision(vault, baseInput());
+ const { entries } = readLogDay(vault, "2026-07-18");
+ const recorded = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.decisionRecord);
+ expect(recorded.length).toBe(1);
+ expect(recorded[0]!.body["decision"]).toContain(res.record.id);
+ });
+
+ test("refuses to clobber an existing decision", () => {
+ recordDecision(vault, baseInput());
+ expect(() => recordDecision(vault, baseInput())).toThrow(DecisionError);
+ });
+
+ test("rejects malformed input with a typed error", () => {
+ expect(() => recordDecision(vault, baseInput({ title: " " }))).toThrow(DecisionError);
+ expect(() => recordDecision(vault, baseInput({ chosen: "" }))).toThrow(DecisionError);
+ expect(() => recordDecision(vault, baseInput({ reviewDate: "not-a-date" }))).toThrow(
+ DecisionError,
+ );
+ });
+});
+
+describe("backfillOutcome", () => {
+ test("mutates the note outcome and logs the mutation", () => {
+ const res = recordDecision(vault, baseInput());
+ const updated = backfillOutcome(vault, {
+ slug: res.record.slug,
+ outcome: "Bun worked out; kept it",
+ agent: "tester",
+ now: new Date("2026-11-01T09:00:00Z"),
+ });
+ expect(updated.outcome).toBe("Bun worked out; kept it");
+ const [meta] = parseFrontmatter(res.record.path);
+ expect(meta["outcome"]).toBe("Bun worked out; kept it");
+
+ const { entries } = readLogDay(vault, "2026-11-01");
+ const outcomes = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.decisionOutcome);
+ expect(outcomes.length).toBe(1);
+ });
+
+ test("rejects an unknown decision", () => {
+ expect(() => backfillOutcome(vault, { slug: "nope", outcome: "x", agent: "tester" })).toThrow(
+ DecisionError,
+ );
+ });
+
+ test("rejects an empty outcome", () => {
+ const res = recordDecision(vault, baseInput());
+ expect(() =>
+ backfillOutcome(vault, { slug: res.record.slug, outcome: " ", agent: "tester" }),
+ ).toThrow(DecisionError);
+ });
+});
+
+describe("showDecision / listDecisions", () => {
+ test("round-trips a stored decision", () => {
+ const res = recordDecision(vault, baseInput({ premortem: "risk" }));
+ const shown = showDecision(vault, res.record.slug);
+ expect(shown).not.toBeNull();
+ expect(shown!.title).toBe("Adopt Bun as the primary runtime");
+ expect(shown!.premortem).toBe("risk");
+ });
+
+ test("lists decisions sorted by slug", () => {
+ recordDecision(vault, baseInput({ title: "Zeta choice", chosen: "z" }));
+ recordDecision(vault, baseInput({ title: "Alpha choice", chosen: "a" }));
+ const all = listDecisions(vault);
+ expect(all.map((d) => d.slug)).toEqual(["alpha-choice", "zeta-choice"]);
+ });
+
+ test("returns empty when no decisions dir exists", () => {
+ expect(listDecisions(vault)).toEqual([]);
+ expect(showDecision(vault, "missing")).toBeNull();
+ });
+});
+
+describe("rating and rationale (B2)", () => {
+ test("captures rating and rationale at record time", () => {
+ const res = recordDecision(vault, baseInput({ rating: 4, rationale: "worked well" }));
+ expect(res.record.rating).toBe(4);
+ expect(res.record.rationale).toBe("worked well");
+ const [meta] = parseFrontmatter(res.record.path);
+ // The flat frontmatter parser returns scalars as strings.
+ expect(meta["rating"]).toBe("4");
+ expect(meta["rationale"]).toBe("worked well");
+ });
+
+ test("unrated decisions render without rating fields (byte-identical shape)", () => {
+ const res = recordDecision(vault, baseInput());
+ expect(res.record.rating).toBeNull();
+ expect(res.record.rationale).toBe("");
+ const raw = readFileSync(res.record.path, "utf8");
+ expect(raw).not.toContain("rating:");
+ expect(raw).not.toContain("rationale:");
+ });
+
+ test("updateRating sets the rating, logs it, and rejects out-of-range values", () => {
+ const res = recordDecision(vault, baseInput());
+ const updated = updateRating(vault, {
+ slug: res.record.slug,
+ rating: 5,
+ rationale: "great in hindsight",
+ agent: "tester",
+ now: new Date("2026-11-02T09:00:00Z"),
+ });
+ expect(updated.rating).toBe(5);
+ expect(updated.rationale).toBe("great in hindsight");
+
+ const { entries } = readLogDay(vault, "2026-11-02");
+ const rated = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.decisionRating);
+ expect(rated.length).toBe(1);
+
+ expect(() =>
+ updateRating(vault, { slug: res.record.slug, rating: 6, agent: "tester" }),
+ ).toThrow(DecisionError);
+ expect(() =>
+ updateRating(vault, { slug: res.record.slug, rating: 0, agent: "tester" }),
+ ).toThrow(DecisionError);
+ });
+
+ test("listRatedDecisions returns only rated decisions, sorted by rating desc", () => {
+ recordDecision(vault, baseInput({ title: "low one", chosen: "a", rating: 2 }));
+ recordDecision(vault, baseInput({ title: "high one", chosen: "b", rating: 5 }));
+ recordDecision(vault, baseInput({ title: "unrated one", chosen: "c" }));
+ const rated = listRatedDecisions(vault);
+ expect(rated.map((d) => d.rating)).toEqual([5, 2]);
+ });
+
+ test("compareDecisions returns the requested decisions side by side", () => {
+ const a = recordDecision(vault, baseInput({ title: "opt a", chosen: "a", rating: 3 }));
+ const b = recordDecision(vault, baseInput({ title: "opt b", chosen: "b", rating: 4 }));
+ const compared = compareDecisions(vault, [a.record.slug, b.record.slug]);
+ expect(compared.map((d) => d.slug)).toEqual([a.record.slug, b.record.slug]);
+ expect(compared[1]!.rating).toBe(4);
+ });
+
+ test("rated decisions do not pollute signal/preference recall", () => {
+ recordDecision(vault, baseInput({ title: "deploy runtime choice", chosen: "Bun", rating: 5 }));
+ const recall = queryByTopic(vault, "deploy");
+ expect(recall.signals.length).toBe(0);
+ expect(recall.preference).toBeNull();
+ });
+});
+
+describe("findSimilarDecisions", () => {
+ test("surfaces historically similar decisions with their outcomes", () => {
+ const prior = recordDecision(
+ vault,
+ baseInput({ title: "Adopt Bun runtime for the CLI", chosen: "Bun" }),
+ );
+ backfillOutcome(vault, {
+ slug: prior.record.slug,
+ outcome: "Great decision",
+ agent: "tester",
+ now: NOW,
+ });
+ const hits = findSimilarDecisions(vault, {
+ title: "Adopt Bun runtime for the server",
+ chosen: "Bun",
+ });
+ expect(hits.length).toBeGreaterThanOrEqual(1);
+ expect(hits[0]!.slug).toBe(prior.record.slug);
+ expect(hits[0]!.outcome).toBe("Great decision");
+ });
+
+ test("excludes an exact-slug self match", () => {
+ const res = recordDecision(vault, baseInput());
+ const hits = findSimilarDecisions(vault, {
+ title: res.record.title,
+ chosen: res.record.chosen,
+ excludeSlug: res.record.slug,
+ });
+ expect(hits.find((h) => h.slug === res.record.slug)).toBeUndefined();
+ });
+});
+
+describe("decision-change receipts (B4 trail)", () => {
+ test("record -> outcome -> rate emits one receipt per mutation in order", () => {
+ const rec = recordDecision(vault, baseInput({ now: new Date("2026-07-18T12:00:00Z") }));
+ const subject = `[[${rec.record.id}]]`;
+
+ backfillOutcome(vault, {
+ slug: rec.record.slug,
+ outcome: "held up",
+ agent: "tester",
+ now: new Date("2026-07-18T12:00:01Z"),
+ });
+ updateRating(vault, {
+ slug: rec.record.slug,
+ rating: 5,
+ rationale: "worked well",
+ agent: "tester",
+ now: new Date("2026-07-18T12:00:02Z"),
+ });
+
+ const page = queryDecisionChangeHistory(vault, { subject });
+ expect(page.total).toBe(3);
+ expect(page.receipts.map((r) => r.reason_code)).toEqual([
+ DECISION_CHANGE_REASON.record,
+ DECISION_CHANGE_REASON.outcome,
+ DECISION_CHANGE_REASON.rating,
+ ]);
+
+ // The creation receipt carries an explicit absent before-state.
+ const [created, outcome, rated] = page.receipts;
+ expect(created!.before).toBe("(absent)");
+ expect(created!.after).toContain("Bun");
+ expect(outcome!.after).toContain("held up");
+ expect(rated!.after).toContain("5");
+ // Every receipt in the trail shares the one decision subject.
+ expect(page.receipts.every((r) => r.subject === subject)).toBe(true);
+ });
+
+ test("replaying an identical mutation is idempotent (no duplicate receipt)", () => {
+ const rec = recordDecision(vault, baseInput({ now: new Date("2026-07-18T12:00:00Z") }));
+ backfillOutcome(vault, {
+ slug: rec.record.slug,
+ outcome: "held up",
+ agent: "tester",
+ now: new Date("2026-07-18T12:00:01Z"),
+ });
+ // Same before/after -> same idempotency key -> no new receipt.
+ backfillOutcome(vault, {
+ slug: rec.record.slug,
+ outcome: "held up",
+ agent: "tester",
+ now: new Date("2026-07-18T12:00:05Z"),
+ });
+ const page = queryDecisionChangeHistory(vault, { subject: `[[${rec.record.id}]]` });
+ expect(
+ page.receipts.filter((r) => r.reason_code === DECISION_CHANGE_REASON.outcome).length,
+ ).toBe(1);
+ });
+});
diff --git a/tests/core/brain/inject-governor.test.ts b/tests/core/brain/inject-governor.test.ts
new file mode 100644
index 00000000..c46f7b53
--- /dev/null
+++ b/tests/core/brain/inject-governor.test.ts
@@ -0,0 +1,65 @@
+import { test, expect } from "bun:test";
+
+import {
+ CHAIN_DECAY_LOW_RECALL_MAX_APPLIED,
+ CHAIN_DECAY_STALE_DAYS,
+ effectiveStaleThresholdDays,
+ isLowRecallSupersededAncestor,
+ isSuperseded,
+ preferChainTips,
+} from "../../../src/core/brain/inject-governor.ts";
+
+test("preferChainTips keeps only chain tips by default", () => {
+ const cands = [
+ { id: "a", supersededBy: "[[b]]" },
+ { id: "b", supersededBy: "[[c]]" },
+ { id: "c", supersededBy: null },
+ ];
+ const res = preferChainTips(cands);
+ expect(res.kept.map((c) => c.id)).toEqual(["c"]);
+ expect(res.dropped.map((c) => c.id).toSorted()).toEqual(["a", "b"]);
+});
+
+test("preferChainTips with historical keeps the whole chain", () => {
+ const cands = [
+ { id: "a", supersededBy: "[[b]]" },
+ { id: "b", supersededBy: null },
+ ];
+ const res = preferChainTips(cands, { historical: true });
+ expect(res.kept.map((c) => c.id)).toEqual(["a", "b"]);
+ expect(res.dropped).toEqual([]);
+});
+
+test("preferChainTips leaves non-chain memories byte-identical", () => {
+ const cands = [
+ { id: "x", supersededBy: null },
+ { id: "y", supersededBy: undefined },
+ { id: "z" },
+ ];
+ const res = preferChainTips(cands);
+ expect(res.kept.map((c) => c.id)).toEqual(["x", "y", "z"]);
+ expect(res.dropped).toEqual([]);
+});
+
+test("isSuperseded detects a non-empty successor pointer", () => {
+ expect(isSuperseded({ supersededBy: "[[b]]" })).toBe(true);
+ expect(isSuperseded({ supersededBy: "" })).toBe(false);
+ expect(isSuperseded({ supersededBy: null })).toBe(false);
+ expect(isSuperseded({})).toBe(false);
+});
+
+test("isLowRecallSupersededAncestor requires both supersession and low recall", () => {
+ expect(isLowRecallSupersededAncestor({ supersededBy: "[[b]]", appliedCount: 0 })).toBe(true);
+ // High recall: not accelerated even though superseded.
+ expect(isLowRecallSupersededAncestor({ supersededBy: "[[b]]", appliedCount: 5 })).toBe(false);
+ // Not superseded: never accelerated.
+ expect(isLowRecallSupersededAncestor({ supersededBy: null, appliedCount: 0 })).toBe(false);
+ expect(CHAIN_DECAY_LOW_RECALL_MAX_APPLIED).toBeGreaterThanOrEqual(0);
+});
+
+test("effectiveStaleThresholdDays accelerates but is never slower than the normal window", () => {
+ expect(effectiveStaleThresholdDays(true, 90)).toBe(CHAIN_DECAY_STALE_DAYS);
+ expect(effectiveStaleThresholdDays(false, 90)).toBe(90);
+ // Never slower than the normal window when the normal window is short.
+ expect(effectiveStaleThresholdDays(true, 3)).toBe(3);
+});
diff --git a/tests/core/brain/lifecycle/chain-consumer.test.ts b/tests/core/brain/lifecycle/chain-consumer.test.ts
new file mode 100644
index 00000000..161557e9
--- /dev/null
+++ b/tests/core/brain/lifecycle/chain-consumer.test.ts
@@ -0,0 +1,89 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeFrontmatter } from "../../../../src/core/vault.ts";
+import { packContext } from "../../../../src/core/brain/context-pack.ts";
+import { deriveTrust } from "../../../../src/core/search/enrich.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-chain-consumer-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, extra: Record<string, string> = {}): void {
+ writeFrontmatter(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `principle ${slug}`,
+ tags: ["brain"],
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-02-01T00:00:00Z",
+ _confidence: "high",
+ ...extra,
+ },
+ `Body for ${slug}.`,
+ );
+}
+
+test("a chain of three superseding memories injects only the tip by default", () => {
+ writePref("a", { superseded_by: "[[pref-b]]" });
+ writePref("b", { superseded_by: "[[pref-c]]" });
+ writePref("c");
+
+ const report = packContext(vault, { maxTokens: 5000 });
+ const ids = report.items.map((i) => i.id);
+ expect(ids).toContain("pref-c");
+ expect(ids).not.toContain("pref-a");
+ expect(ids).not.toContain("pref-b");
+});
+
+test("the explicit historical flag keeps the whole chain", () => {
+ writePref("a", { superseded_by: "[[pref-b]]" });
+ writePref("b", { superseded_by: "[[pref-c]]" });
+ writePref("c");
+
+ const report = packContext(vault, { maxTokens: 5000, includeHistorical: true });
+ const ids = report.items.map((i) => i.id).toSorted();
+ expect(ids).toEqual(["pref-a", "pref-b", "pref-c"]);
+});
+
+test("non-chain memories inject byte-identically with and without tip preference", () => {
+ writePref("x");
+ writePref("y");
+
+ const def = packContext(vault, { maxTokens: 5000 })
+ .items.map((i) => i.id)
+ .toSorted();
+ const hist = packContext(vault, { maxTokens: 5000, includeHistorical: true })
+ .items.map((i) => i.id)
+ .toSorted();
+ expect(def).toEqual(["pref-x", "pref-y"]);
+ expect(hist).toEqual(def);
+});
+
+test("recall trust carries a pointer to the replacement for a superseded hit", () => {
+ const trust = deriveTrust({
+ mtimeMs: 0,
+ nowMs: 0,
+ relations: [{ relation: "superseded_by", target: "pref-new" }],
+ });
+ expect(trust.superseded).toBe(true);
+ expect(trust.replacement).toBe("pref-new");
+});
+
+test("recall trust replacement is null for a non-superseded hit", () => {
+ const trust = deriveTrust({ mtimeMs: 0, nowMs: 0 });
+ expect(trust.superseded).toBe(false);
+ expect(trust.replacement).toBeNull();
+});
diff --git a/tests/core/brain/lifecycle/chain-decay.test.ts b/tests/core/brain/lifecycle/chain-decay.test.ts
new file mode 100644
index 00000000..fa2a5f92
--- /dev/null
+++ b/tests/core/brain/lifecycle/chain-decay.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { dream } from "../../../../src/core/brain/dream.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { writeFrontmatter } from "../../../../src/core/vault.ts";
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-chain-decay-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-chain-decay-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 });
+});
+
+function writeConfirmedPref(slug: string, extra: Record<string, string> = {}): void {
+ writeFrontmatter(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `principle ${slug}`,
+ tags: ["brain"],
+ created_at: "2026-01-01T00:00:00Z",
+ // Confirmed 30 days before the dream run: inside the normal 90-day
+ // stale window, past the accelerated 7-day chain-decay window. The
+ // dream refresh finds no apply-evidence in the log, so staleness is
+ // measured from confirmation.
+ _confirmed_at: "2026-05-02T00:00:00Z",
+ unconfirmed_until: "2026-01-08T00:00:00Z",
+ _applied_count: "0",
+ _confidence: "high",
+ ...extra,
+ },
+ `Body ${slug}.`,
+ );
+}
+
+test("dream retires a low-recall superseded ancestor faster than a live memory", () => {
+ // Both are 30 days stale - inside the normal 90-day window, but past the
+ // accelerated 7-day chain-decay window.
+ writeConfirmedPref("ancestor", { superseded_by: "[[pref-tip]]" });
+ writeConfirmedPref("live");
+
+ dream(vault, { now: new Date("2026-06-01T12:00:00Z") });
+
+ // The superseded ancestor retired on the accelerated window.
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-ancestor.md"))).toBe(false);
+ // The non-superseded memory is still live (normal window not reached).
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-live.md"))).toBe(true);
+
+ // The accelerated retirement emitted a chain-decay event.
+ const { entries } = readLogDay(vault, "2026-06-01");
+ const decay = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.chainDecay);
+ expect(decay.length).toBe(1);
+ expect(decay[0]!.body["preference"]).toBe("[[ret-ancestor]]");
+});
diff --git a/tests/core/brain/lifecycle/curator.test.ts b/tests/core/brain/lifecycle/curator.test.ts
new file mode 100644
index 00000000..9deec15b
--- /dev/null
+++ b/tests/core/brain/lifecycle/curator.test.ts
@@ -0,0 +1,71 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { emitObservedUse } from "../../../../src/core/brain/observed-use.ts";
+import {
+ CURATOR_HIGH_USE_MIN_DEFAULT,
+ curatorSlices,
+} from "../../../../src/core/brain/lifecycle/curator.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-curator-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function record(
+ entries: Array<{ path: string; verdict: "USED" | "IGNORED" | "CONTRADICTED" }>,
+): void {
+ emitObservedUse(vault, {
+ host: "test",
+ entries: entries.map((e) => ({ id: e.path, path: e.path, verdict: e.verdict })),
+ });
+}
+
+test("curatorSlices reports injected-never-used memories", () => {
+ record([{ path: "a.md", verdict: "IGNORED" }]);
+ record([{ path: "a.md", verdict: "IGNORED" }]);
+ record([{ path: "b.md", verdict: "USED" }]);
+
+ const slices = curatorSlices(vault);
+ const neverUsed = slices.injectedNeverUsed.map((e) => e.key);
+ expect(neverUsed).toContain("a.md");
+ expect(neverUsed).not.toContain("b.md");
+});
+
+test("curatorSlices reports contradicted memories", () => {
+ record([{ path: "c.md", verdict: "CONTRADICTED" }]);
+ record([{ path: "d.md", verdict: "USED" }]);
+
+ const slices = curatorSlices(vault);
+ expect(slices.contradicted.map((e) => e.key)).toEqual(["c.md"]);
+});
+
+test("curatorSlices reports high-used memories above the threshold", () => {
+ for (let i = 0; i < CURATOR_HIGH_USE_MIN_DEFAULT; i++)
+ record([{ path: "hot.md", verdict: "USED" }]);
+ record([{ path: "cold.md", verdict: "USED" }]);
+
+ const slices = curatorSlices(vault);
+ expect(slices.highUsed.map((e) => e.key)).toContain("hot.md");
+ expect(slices.highUsed.map((e) => e.key)).not.toContain("cold.md");
+});
+
+test("curatorSlices honours an explicit high-use minimum", () => {
+ record([{ path: "one.md", verdict: "USED" }]);
+ const slices = curatorSlices(vault, { highUseMin: 1 });
+ expect(slices.highUsed.map((e) => e.key)).toContain("one.md");
+});
+
+test("curatorSlices returns empty slices for an empty vault", () => {
+ const slices = curatorSlices(vault);
+ expect(slices.injectedNeverUsed).toEqual([]);
+ expect(slices.contradicted).toEqual([]);
+ expect(slices.highUsed).toEqual([]);
+});
diff --git a/tests/core/brain/lifecycle/exclusion.test.ts b/tests/core/brain/lifecycle/exclusion.test.ts
new file mode 100644
index 00000000..4703bf31
--- /dev/null
+++ b/tests/core/brain/lifecycle/exclusion.test.ts
@@ -0,0 +1,59 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeFrontmatter } from "../../../../src/core/vault.ts";
+import { regenerateActive } from "../../../../src/core/brain/active.ts";
+import { brainActivePath } from "../../../../src/core/brain/paths.ts";
+import { tombstone } from "../../../../src/core/brain/lifecycle/tombstone.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-lifecycle-excl-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfirmedPref(slug: string): string {
+ const rel = join("Brain", "preferences", `pref-${slug}.md`);
+ writeFrontmatter(
+ join(vault, rel),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `always ${slug}`,
+ tags: ["brain"],
+ created_at: "2026-01-01T00:00:00Z",
+ _confirmed_at: "2026-01-02T00:00:00Z",
+ unconfirmed_until: "2026-02-01T00:00:00Z",
+ _confidence: "high",
+ },
+ "Prose.",
+ );
+ return rel;
+}
+
+test("a tombstoned preference is excluded from active.md but stays on disk for audit", () => {
+ const rel = writeConfirmedPref("keep-this");
+ writeConfirmedPref("also-keep");
+
+ regenerateActive(vault);
+ let active = readFileSync(brainActivePath(vault), "utf8");
+ expect(active).toContain("always keep-this");
+
+ tombstone({ vault, path: rel, reason: "belief reversed", now: new Date("2026-07-18T00:00:00Z") });
+
+ regenerateActive(vault);
+ active = readFileSync(brainActivePath(vault), "utf8");
+ expect(active).not.toContain("always keep-this");
+ expect(active).toContain("always also-keep");
+
+ // Audit: the tombstoned file is not deleted.
+ expect(existsSync(join(vault, rel))).toBe(true);
+});
diff --git a/tests/core/brain/lifecycle/temporal-replace.test.ts b/tests/core/brain/lifecycle/temporal-replace.test.ts
new file mode 100644
index 00000000..e80c6f17
--- /dev/null
+++ b/tests/core/brain/lifecycle/temporal-replace.test.ts
@@ -0,0 +1,163 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { parseFrontmatter, writeFrontmatter } from "../../../../src/core/vault.ts";
+import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import {
+ TemporalReplaceError,
+ isValidAt,
+ temporalReplace,
+} from "../../../../src/core/brain/lifecycle/temporal-replace.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-temporal-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeFact(slug: string, meta: Record<string, string> = {}): string {
+ const rel = join("Brain", "preferences", `pref-${slug}.md`);
+ writeFrontmatter(
+ join(vault, rel),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `fact ${slug}`,
+ tags: ["brain"],
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-02-01T00:00:00Z",
+ ...meta,
+ },
+ "Prose.",
+ );
+ return rel;
+}
+
+const AT = "2026-07-18T12:00:00Z";
+
+test("temporalReplace closes the predecessor and opens the successor at one shared instant", () => {
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+
+ const res = temporalReplace({ vault, predecessor: pred, successor: succ, at: AT, agent: "t" });
+
+ expect(res.at).toBe(AT);
+ const [predMeta] = parseFrontmatter(join(vault, pred));
+ const [succMeta] = parseFrontmatter(join(vault, succ));
+ expect(predMeta["valid_until"]).toBe(AT);
+ expect(predMeta["superseded_by"]).toBe("[[pref-new]]");
+ expect(succMeta["valid_from"]).toBe(AT);
+});
+
+test("the interval is half-open: at the shared instant only the successor is valid", () => {
+ const pred = writeFact("p", { valid_from: "2026-01-01T00:00:00Z" });
+ const succ = writeFact("s");
+ temporalReplace({ vault, predecessor: pred, successor: succ, at: AT });
+
+ const [predMeta] = parseFrontmatter(join(vault, pred));
+ const [succMeta] = parseFrontmatter(join(vault, succ));
+ const tMs = Date.parse(AT);
+
+ // Just before T: predecessor valid, successor not.
+ expect(isValidAt(predMeta, tMs - 1)).toBe(true);
+ expect(isValidAt(succMeta, tMs - 1)).toBe(false);
+ // Exactly at T (half-open [from, until)): successor valid, predecessor not.
+ expect(isValidAt(predMeta, tMs)).toBe(false);
+ expect(isValidAt(succMeta, tMs)).toBe(true);
+});
+
+test("point-in-time evaluation of the pair has no gap and no overlap (property)", () => {
+ const pred = writeFact("p", { valid_from: "2026-01-01T00:00:00Z" });
+ const succ = writeFact("s", { valid_until: "2027-01-01T00:00:00Z" });
+ temporalReplace({ vault, predecessor: pred, successor: succ, at: AT });
+
+ const [predMeta] = parseFrontmatter(join(vault, pred));
+ const [succMeta] = parseFrontmatter(join(vault, succ));
+
+ const spanStart = Date.parse("2026-01-01T00:00:00Z");
+ const spanEnd = Date.parse("2027-01-01T00:00:00Z");
+ const step = Math.floor((spanEnd - spanStart) / 4000);
+ for (let t = spanStart; t < spanEnd; t += step) {
+ const p = isValidAt(predMeta, t);
+ const s = isValidAt(succMeta, t);
+ // Exactly one is valid across the whole span: no gap, no overlap.
+ expect(p !== s).toBe(true);
+ }
+ // The shared boundary specifically.
+ const tMs = Date.parse(AT);
+ expect(isValidAt(predMeta, tMs - 1) && !isValidAt(succMeta, tMs - 1)).toBe(true);
+ expect(!isValidAt(predMeta, tMs) && isValidAt(succMeta, tMs)).toBe(true);
+});
+
+test("date-only facts keep whole-day semantics", () => {
+ const pred = writeFact("p", { valid_from: "2026-01-01" });
+ const succ = writeFact("s");
+ const res = temporalReplace({ vault, predecessor: pred, successor: succ, at: "2026-07-18" });
+
+ expect(res.at).toBe("2026-07-18");
+ const [predMeta] = parseFrontmatter(join(vault, pred));
+ const [succMeta] = parseFrontmatter(join(vault, succ));
+ expect(predMeta["valid_until"]).toBe("2026-07-18");
+ expect(succMeta["valid_from"]).toBe("2026-07-18");
+
+ // Any instant on 2026-07-17 -> predecessor; any instant on/after
+ // 2026-07-18 00:00 -> successor.
+ expect(isValidAt(predMeta, Date.parse("2026-07-17T23:59:59Z"))).toBe(true);
+ expect(isValidAt(succMeta, Date.parse("2026-07-17T23:59:59Z"))).toBe(false);
+ expect(isValidAt(predMeta, Date.parse("2026-07-18T00:00:00Z"))).toBe(false);
+ expect(isValidAt(succMeta, Date.parse("2026-07-18T09:00:00Z"))).toBe(true);
+});
+
+test("temporalReplace logs a temporal-replace event", () => {
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+ temporalReplace({ vault, predecessor: pred, successor: succ, at: AT });
+
+ const { entries } = readLogDay(vault, "2026-07-18");
+ const events = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.temporalReplace);
+ expect(events.length).toBe(1);
+ expect(events[0]!.body["at"]).toBe(AT);
+});
+
+test("both files are written or neither: a bad successor path leaves the predecessor untouched", () => {
+ const pred = writeFact("old");
+ const before = readFileSync(join(vault, pred), "utf8");
+
+ expect(() =>
+ temporalReplace({
+ vault,
+ predecessor: pred,
+ successor: "Brain/preferences/pref-missing.md",
+ at: AT,
+ }),
+ ).toThrow(TemporalReplaceError);
+
+ const after = readFileSync(join(vault, pred), "utf8");
+ expect(after).toBe(before);
+});
+
+test("temporalReplace rejects replacing a fact with itself", () => {
+ const pred = writeFact("self");
+ expect(() => temporalReplace({ vault, predecessor: pred, successor: pred, at: AT })).toThrow(
+ TemporalReplaceError,
+ );
+});
+
+test("isValidAt treats absent bounds as unbounded on that side", () => {
+ expect(isValidAt({}, Date.now())).toBe(true);
+ expect(
+ isValidAt({ valid_from: "2026-01-01T00:00:00Z" }, Date.parse("2025-01-01T00:00:00Z")),
+ ).toBe(false);
+ expect(
+ isValidAt({ valid_until: "2026-01-01T00:00:00Z" }, Date.parse("2027-01-01T00:00:00Z")),
+ ).toBe(false);
+});
diff --git a/tests/core/brain/lifecycle/tombstone.test.ts b/tests/core/brain/lifecycle/tombstone.test.ts
new file mode 100644
index 00000000..88ba5302
--- /dev/null
+++ b/tests/core/brain/lifecycle/tombstone.test.ts
@@ -0,0 +1,196 @@
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { parseFrontmatter, writeFrontmatter } from "../../../../src/core/vault.ts";
+import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import {
+ TombstoneError,
+ isTombstoned,
+ readLifecycleState,
+ resolveChainTip,
+ resolveChainTipInVault,
+ supersede,
+ tombstone,
+} from "../../../../src/core/brain/lifecycle/tombstone.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-tombstone-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, extra: Record<string, string> = {}, body = "Prose."): string {
+ const rel = join("Brain", "preferences", `pref-${slug}.md`);
+ writeFrontmatter(
+ join(vault, rel),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `principle for ${slug}`,
+ tags: ["brain"],
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-02-01T00:00:00Z",
+ ...extra,
+ },
+ body,
+ );
+ return rel;
+}
+
+const NOW = new Date("2026-07-18T12:00:00Z");
+
+test("tombstone sets lifecycle frontmatter without deleting the file and preserves the body", () => {
+ const rel = writePref("alpha", {}, "This is the human prose body.");
+ const res = tombstone({ vault, path: rel, reason: "wrong belief", agent: "tester", now: NOW });
+
+ expect(res.changed).toBe(true);
+ expect(res.state.tombstoned).toBe(true);
+ expect(res.state.tombstoneReason).toBe("wrong belief");
+ expect(res.state.tombstonedAt).toBe("2026-07-18T12:00:00Z");
+
+ const [meta, body] = parseFrontmatter(join(vault, rel));
+ expect(meta["_status"]).toBe("tombstoned");
+ expect(meta["tombstoned_at"]).toBe("2026-07-18T12:00:00Z");
+ expect(meta["tombstone_reason"]).toBe("wrong belief");
+ expect(body).toBe("This is the human prose body.");
+});
+
+test("re-issuing a tombstone is a byte-identical no-op returning the existing state", () => {
+ const rel = writePref("beta");
+ tombstone({ vault, path: rel, reason: "first", agent: "tester", now: NOW });
+ const after1 = readFileSync(join(vault, rel), "utf8");
+
+ const res2 = tombstone({
+ vault,
+ path: rel,
+ reason: "different reason",
+ agent: "tester",
+ now: new Date("2026-07-19T00:00:00Z"),
+ });
+ const after2 = readFileSync(join(vault, rel), "utf8");
+
+ expect(res2.changed).toBe(false);
+ expect(res2.state.tombstoneReason).toBe("first");
+ expect(after2).toBe(after1);
+});
+
+test("tombstone logs exactly one tombstone event on the changing write and none on the no-op", () => {
+ const rel = writePref("gamma");
+ tombstone({ vault, path: rel, reason: "obsolete", agent: "tester", now: NOW });
+ tombstone({ vault, path: rel, reason: "obsolete", agent: "tester", now: NOW });
+
+ const { entries } = readLogDay(vault, "2026-07-18");
+ const tombstones = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.tombstone);
+ expect(tombstones.length).toBe(1);
+ expect(tombstones[0]!.body["reason"]).toBe("obsolete");
+ expect(tombstones[0]!.body["prior_status"]).toBe("confirmed");
+});
+
+test("tombstone throws a typed error when the target does not exist", () => {
+ expect(() =>
+ tombstone({ vault, path: "Brain/preferences/pref-missing.md", reason: "x", now: NOW }),
+ ).toThrow(TombstoneError);
+});
+
+test("tombstone throws a typed error on an empty reason", () => {
+ const rel = writePref("delta");
+ expect(() => tombstone({ vault, path: rel, reason: " ", now: NOW })).toThrow(TombstoneError);
+});
+
+test("supersede tombstones the predecessor and records the replacement pointer", () => {
+ const oldRel = writePref("old-fact");
+ writePref("new-fact");
+
+ const res = supersede({
+ vault,
+ predecessor: oldRel,
+ successor: "pref-new-fact",
+ agent: "tester",
+ now: NOW,
+ });
+
+ expect(res.changed).toBe(true);
+ expect(res.state.tombstoned).toBe(true);
+ expect(res.state.supersededBy).toBe("[[pref-new-fact]]");
+
+ const [meta] = parseFrontmatter(join(vault, oldRel));
+ expect(meta["_status"]).toBe("tombstoned");
+ expect(meta["superseded_by"]).toBe("[[pref-new-fact]]");
+});
+
+test("isTombstoned reads both the prefixed and normalized status key", () => {
+ expect(isTombstoned({ _status: "tombstoned" })).toBe(true);
+ expect(isTombstoned({ status: "tombstoned" })).toBe(true);
+ expect(isTombstoned({ _status: "confirmed" })).toBe(false);
+ expect(isTombstoned({})).toBe(false);
+});
+
+test("readLifecycleState reports the superseded_by pointer normalized", () => {
+ const state = readLifecycleState({ _status: "tombstoned", superseded_by: "[[pref-x]]" });
+ expect(state.tombstoned).toBe(true);
+ expect(state.supersededBy).toBe("[[pref-x]]");
+});
+
+function mapLookup(
+ map: Record<string, string | null>,
+): (link: string) => { supersededBy: string | null } | null {
+ return (link) => (link in map ? { supersededBy: map[link]! } : null);
+}
+
+test("resolveChainTip walks a chain of superseded_by links to the live tip", () => {
+ const res = resolveChainTip(
+ "[[pref-a]]",
+ mapLookup({ "pref-a": "[[pref-b]]", "pref-b": "[[pref-c]]", "pref-c": null }),
+ );
+ expect(res.tip).toBe("pref-c");
+ expect(res.steps).toBe(2);
+ expect(res.cycle).toBe(false);
+ expect(res.resolvedAll).toBe(true);
+});
+
+test("resolveChainTip detects a cycle instead of looping forever", () => {
+ const res = resolveChainTip(
+ "pref-a",
+ mapLookup({ "pref-a": "[[pref-b]]", "pref-b": "[[pref-a]]" }),
+ );
+ expect(res.cycle).toBe(true);
+});
+
+test("resolveChainTip returns the start unchanged when it has no successor", () => {
+ const res = resolveChainTip("pref-solo", () => ({ supersededBy: null }));
+ expect(res.tip).toBe("pref-solo");
+ expect(res.steps).toBe(0);
+});
+
+test("resolveChainTipInVault follows real supersede chains on disk", () => {
+ const oldRel = writePref("v1");
+ writePref("v2");
+ supersede({ vault, predecessor: oldRel, successor: "pref-v2", now: NOW });
+
+ const res = resolveChainTipInVault(vault, "pref-v1");
+ expect(res.tip).toBe("pref-v2");
+});
+
+test("tombstone works cross-type on a signal file", () => {
+ const rel = join("Brain", "inbox", "sig-2026-01-01-note.md");
+ writeFrontmatter(
+ join(vault, rel),
+ { kind: "brain-signal", id: "sig-2026-01-01-note", topic: "note", signal: "positive" },
+ "signal body",
+ );
+ const res = tombstone({ vault, path: rel, reason: "captured in error", now: NOW });
+ expect(res.changed).toBe(true);
+ const [meta, body] = parseFrontmatter(join(vault, rel));
+ expect(meta["_status"]).toBe("tombstoned");
+ expect(body).toBe("signal body");
+});
diff --git a/tests/core/brain/session-recall.test.ts b/tests/core/brain/session-recall.test.ts
index 73335dee..bbbf1280 100644
--- a/tests/core/brain/session-recall.test.ts
+++ b/tests/core/brain/session-recall.test.ts
@@ -137,3 +137,65 @@ describe("session recall DAG", () => {
expect(hit?.line_end).toBe(2);
});
});
+
+function turnAt(turnId: string, text: string, timestamp: string): SessionTurn {
+ return { turnId, role: "user", text, timestamp };
+}
+
+const parseMs = (iso: string): number => Date.parse(iso);
+
+const byString = (a: string, b: string): number => a.localeCompare(b);
+
+describe("session recall β€” since/before time bounds (S1 / t_347e8224)", () => {
+ function seed(): void {
+ importSessionRecall(vault, {
+ sessionId: "session-time",
+ turns: [
+ turnAt("t1", "chronology alpha needle", "2026-01-10T09:00:00.000Z"),
+ turnAt("t2", "chronology beta needle", "2026-03-15T09:00:00.000Z"),
+ turnAt("t3", "chronology gamma needle", "2026-06-20T09:00:00.000Z"),
+ ],
+ summaryGroupSize: 8,
+ createdAt: "2026-06-20T09:00:00.000Z",
+ });
+ }
+
+ function turnIdsFor(input: { sinceMs?: number; untilMs?: number }): string[] {
+ return searchSessionRecall(vault, {
+ query: "needle",
+ sessionId: "session-time",
+ ...input,
+ })
+ .hits.filter((h) => h.kind === "session_turn")
+ .map((h) => h.turn_id ?? "");
+ }
+
+ test("sinceMs excludes turns before the lower bound", () => {
+ seed();
+ expect(turnIdsFor({ sinceMs: parseMs("2026-03-01T00:00:00.000Z") }).toSorted(byString)).toEqual(
+ ["t2", "t3"],
+ );
+ });
+
+ test("untilMs excludes turns after the upper bound", () => {
+ seed();
+ expect(turnIdsFor({ untilMs: parseMs("2026-04-01T00:00:00.000Z") }).toSorted(byString)).toEqual(
+ ["t1", "t2"],
+ );
+ });
+
+ test("since + until keep only turns inside the window", () => {
+ seed();
+ expect(
+ turnIdsFor({
+ sinceMs: parseMs("2026-02-01T00:00:00.000Z"),
+ untilMs: parseMs("2026-04-01T00:00:00.000Z"),
+ }),
+ ).toEqual(["t2"]);
+ });
+
+ test("no bounds is byte-identical to the unbounded search (all three turns)", () => {
+ seed();
+ expect(turnIdsFor({}).toSorted(byString)).toEqual(["t1", "t2", "t3"]);
+ });
+});
diff --git a/tests/core/brain/sessions/import-event-time.test.ts b/tests/core/brain/sessions/import-event-time.test.ts
index ae241f38..ff9a17ce 100644
--- a/tests/core/brain/sessions/import-event-time.test.ts
+++ b/tests/core/brain/sessions/import-event-time.test.ts
@@ -21,6 +21,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../../../src/core/brain/paths.ts";
+import { parseFrontmatter } from "../../../../src/core/vault.ts";
import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/policy.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import { importSession } from "../../../../src/core/brain/sessions/import.ts";
@@ -115,6 +116,46 @@ describe("importSession β€” per-row event-time (preserveEventTime)", () => {
expect(file.startsWith("sig-2020-03-15")).toBe(true);
});
+ test("stamps authored_at with the turn's ORIGINAL timestamp (conversation chronology, S1)", async () => {
+ const fixture = writeFixture(
+ "chronology.jsonl",
+ claudeSession({
+ topic: "evttime",
+ principle: "carry the authoring instant",
+ timestamp: "2020-03-15T08:30:00Z",
+ }),
+ );
+
+ const res = await importSession(tmp, fixture, {
+ agent: "test",
+ now: NOW,
+ preserveEventTime: true,
+ });
+ expect(res.signals_created).toBe(1);
+
+ const { file } = onlySignal(tmp);
+ const meta = parseFrontmatter(join(brainDirs(tmp).inbox, file))[0] as Record<string, unknown>;
+ expect(meta["authored_at"]).toBe("2020-03-15T08:30:00Z");
+ });
+
+ test("without preserveEventTime, no authored_at is written (byte-identity guard)", async () => {
+ const fixture = writeFixture(
+ "no-chronology.jsonl",
+ claudeSession({
+ topic: "evttime",
+ principle: "no authoring instant on the wall-clock path",
+ timestamp: "2020-03-15T08:30:00Z",
+ }),
+ );
+
+ const res = await importSession(tmp, fixture, { agent: "test", now: NOW });
+ expect(res.signals_created).toBe(1);
+
+ const { file } = onlySignal(tmp);
+ const meta = parseFrontmatter(join(brainDirs(tmp).inbox, file))[0] as Record<string, unknown>;
+ expect(meta["authored_at"]).toBeUndefined();
+ });
+
test("a turn with NO timestamp falls back to now (backward-compatible)", async () => {
const fixture = writeFixture(
"no-ts.jsonl",
diff --git a/tests/core/brain/tension-detect.test.ts b/tests/core/brain/tension-detect.test.ts
new file mode 100644
index 00000000..763de2c7
--- /dev/null
+++ b/tests/core/brain/tension-detect.test.ts
@@ -0,0 +1,122 @@
+/**
+ * Tests for `detectTensionsInVault` - the production entry point that
+ * scans the configured note corpus (`notes.read_paths`) and persists
+ * detected contradictions as tensions (Belief lifecycle suite, S2,
+ * t_0e3f2bee). Before this wiring the detector had no production caller.
+ */
+
+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 { brainDirs } from "../../../src/core/brain/paths.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import {
+ detectTensionsInVault,
+ listTensions,
+ TENSION_STATUS,
+} from "../../../src/core/brain/tensions.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-tension-detect-"));
+ mkdirSync(brainDirs(vault).brain, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfig(extra: string): void {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}${extra}`,
+ );
+}
+
+function writeMd(rel: string, content: string): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+}
+
+/** A high-overlap, opposite-stance pair the note detector flags. */
+function seedContradictoryCorpus(): void {
+ writeConfig("\nnotes:\n read_paths:\n - Notes\n");
+ writeMd(
+ "Notes/tabs.md",
+ "---\nid: note-tabs\n---\nAlways use tabs for indentation in source files.\n",
+ );
+ writeMd(
+ "Notes/spaces.md",
+ "---\nid: note-spaces\n---\nNever use tabs for indentation in source files.\n",
+ );
+}
+
+describe("detectTensionsInVault", () => {
+ test("scans the configured note corpus and persists a tension", () => {
+ seedContradictoryCorpus();
+ const res = detectTensionsInVault(vault, { agent: "tester" });
+ expect(res.scannedFiles).toBe(2);
+ expect(res.created).toBe(1);
+ expect(res.updated).toBe(0);
+ expect(res.records.length).toBe(1);
+
+ const persisted = listTensions(vault);
+ expect(persisted.length).toBe(1);
+ expect(persisted[0]!.status).toBe(TENSION_STATUS.open);
+ // Subjects are the note ids, sorted.
+ expect([persisted[0]!.subjectA, persisted[0]!.subjectB].toSorted()).toEqual([
+ "note-spaces",
+ "note-tabs",
+ ]);
+ });
+
+ test("re-detection refreshes the existing tension instead of duplicating", () => {
+ seedContradictoryCorpus();
+ detectTensionsInVault(vault, { agent: "tester" });
+ const second = detectTensionsInVault(vault, { agent: "tester" });
+ expect(second.created).toBe(0);
+ expect(second.updated).toBe(1);
+ expect(listTensions(vault).length).toBe(1);
+ expect(listTensions(vault)[0]!.detectedCount).toBe(2);
+ });
+
+ test("an unconfigured vault (no read_paths) scans nothing and creates nothing", () => {
+ // No notes block at all: default read_paths is empty.
+ writeConfig("");
+ writeMd("Notes/tabs.md", "Always use tabs.\n");
+ writeMd("Notes/spaces.md", "Never use tabs.\n");
+ const res = detectTensionsInVault(vault, { agent: "tester" });
+ expect(res.scannedFiles).toBe(0);
+ expect(res.created).toBe(0);
+ expect(listTensions(vault).length).toBe(0);
+ });
+
+ test("agreeing notes produce no tension", () => {
+ writeConfig("\nnotes:\n read_paths:\n - Notes\n");
+ writeMd("Notes/a.md", "---\nid: note-a\n---\nAlways use tabs for indentation here.\n");
+ writeMd("Notes/b.md", "---\nid: note-b\n---\nAlways use tabs for indentation here too.\n");
+ const res = detectTensionsInVault(vault, { agent: "tester" });
+ expect(res.scannedFiles).toBe(2);
+ expect(res.created).toBe(0);
+ expect(listTensions(vault).length).toBe(0);
+ });
+
+ test("the Brain machinery root is never scanned as note content", () => {
+ // read_paths points at the vault root; the walker still hard-skips Brain/.
+ writeConfig("\nnotes:\n read_paths:\n - Notes\n");
+ writeMd("Notes/tabs.md", "---\nid: note-tabs\n---\nAlways use tabs for indentation.\n");
+ // A decoy under Brain/ that would contradict if it were scanned.
+ writeMd(
+ "Brain/preferences/pref-spaces.md",
+ "---\nid: pref-spaces\n---\nNever use tabs for indentation.\n",
+ );
+ const res = detectTensionsInVault(vault, { agent: "tester" });
+ expect(res.scannedFiles).toBe(1);
+ expect(res.created).toBe(0);
+ });
+});
diff --git a/tests/core/brain/tensions.test.ts b/tests/core/brain/tensions.test.ts
new file mode 100644
index 00000000..d701dd48
--- /dev/null
+++ b/tests/core/brain/tensions.test.ts
@@ -0,0 +1,203 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import type { NoteContradictionFinding } from "../../../src/core/brain/health/contradiction.ts";
+import { parseLogDay } from "../../../src/core/brain/log.ts";
+import { tensionsDir } from "../../../src/core/brain/paths.ts";
+import {
+ confirmTension,
+ detectTensions,
+ dismissTension,
+ listTensions,
+ listUnresolvedTensions,
+ persistTension,
+ resolveTension,
+ showTension,
+ TENSION_STATUS,
+ TENSION_TYPE,
+ TensionError,
+ tensionDedupKey,
+ tensionWarningsForContextItems,
+} from "../../../src/core/brain/tensions.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-tensions-"));
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+/** Two notes with high token overlap and opposite stance (a negation particle). */
+const TABS: ReadonlyArray<{ id: string; text: string }> = [
+ { id: "pref-tabs", text: "Always use tabs for indentation in source files." },
+ { id: "pref-spaces", text: "Never use tabs for indentation in source files." },
+];
+
+function today(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+function finding(): NoteContradictionFinding {
+ return {
+ aId: "pref-tabs",
+ bId: "pref-spaces",
+ subject: "for indentation source tabs use",
+ jaccard: 0.6,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "Always use tabs for indentation in source files.",
+ bQuote: "Never use tabs for indentation in source files.",
+ action: "ask_user",
+ };
+}
+
+describe("tensionDedupKey", () => {
+ test("is stable and pair-order independent", () => {
+ const f = finding();
+ const swapped: NoteContradictionFinding = {
+ ...f,
+ aId: f.bId,
+ bId: f.aId,
+ aSign: f.bSign,
+ bSign: f.aSign,
+ aQuote: f.bQuote,
+ bQuote: f.aQuote,
+ };
+ expect(tensionDedupKey(f)).toBe(tensionDedupKey(swapped));
+ });
+
+ test("changes when the stance signature changes", () => {
+ const f = finding();
+ const flipped: NoteContradictionFinding = { ...f, aSign: "negative", bSign: "positive" };
+ expect(tensionDedupKey(f)).not.toBe(tensionDedupKey(flipped));
+ });
+
+ test("uses printable space separators and no control bytes", () => {
+ // Guards against control characters (e.g. NUL) leaking into the
+ // dedup_key that is written verbatim into tension note frontmatter -
+ // such bytes make the Markdown note binary to grep/git and break the
+ // Syncthing-safe, human-readable contract.
+ const key = tensionDedupKey(finding());
+ expect(key).toBe("pref-spaces pref-tabs negative-positive");
+ });
+});
+
+describe("persistTension", () => {
+ test("creates a tension note in open state with subjects and stances", () => {
+ const res = persistTension(vault, finding(), { agent: "tester" });
+ expect(res.created).toBe(true);
+ expect(res.record.type).toBe(TENSION_TYPE);
+ expect(res.record.status).toBe(TENSION_STATUS.open);
+ expect(res.record.subjectA).toBe("pref-spaces");
+ expect(res.record.subjectB).toBe("pref-tabs");
+ expect(existsSync(res.record.path)).toBe(true);
+
+ const raw = readFileSync(res.record.path, "utf8");
+ expect(raw).toContain("_status: open");
+ expect(raw).toContain(`type: ${TENSION_TYPE}`);
+ });
+
+ test("logs a tension event on creation", () => {
+ persistTension(vault, finding(), { agent: "tester" });
+ const events = parseLogDay(vault, today()).entries.filter((e) => e.eventType === "tension");
+ expect(events.length).toBe(1);
+ });
+
+ test("re-detection of the same pair updates the existing note instead of duplicating", () => {
+ const first = persistTension(vault, finding(), { agent: "tester" });
+ const second = persistTension(vault, finding(), { agent: "tester" });
+ expect(second.created).toBe(false);
+ expect(second.record.slug).toBe(first.record.slug);
+ expect(second.record.detectedCount).toBe(2);
+
+ const files = readdirSync(tensionsDir(vault)).filter((n) => n.endsWith(".md"));
+ expect(files.length).toBe(1);
+ });
+
+ test("re-detection preserves a manual status transition", () => {
+ const first = persistTension(vault, finding(), { agent: "tester" });
+ confirmTension(vault, first.record.slug, { agent: "tester" });
+ const again = persistTension(vault, finding(), { agent: "tester" });
+ expect(again.record.status).toBe(TENSION_STATUS.confirmed);
+ });
+});
+
+describe("detectTensions", () => {
+ test("consumes the contradiction detector and persists one tension", () => {
+ const res = detectTensions(vault, TABS, { jaccard: 0.3, agent: "tester" });
+ expect(res.created).toBe(1);
+ expect(res.records.length).toBe(1);
+ expect(listTensions(vault).length).toBe(1);
+ });
+
+ test("re-running detection does not duplicate", () => {
+ detectTensions(vault, TABS, { jaccard: 0.3, agent: "tester" });
+ const second = detectTensions(vault, TABS, { jaccard: 0.3, agent: "tester" });
+ expect(second.created).toBe(0);
+ expect(second.updated).toBe(1);
+ expect(listTensions(vault).length).toBe(1);
+ });
+});
+
+describe("state machine transitions", () => {
+ test("open -> confirmed logs an event and stays unresolved", () => {
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ const confirmed = confirmTension(vault, record.slug, { agent: "tester" });
+ expect(confirmed.status).toBe(TENSION_STATUS.confirmed);
+ const events = parseLogDay(vault, today()).entries.filter((e) => e.eventType === "tension");
+ // one on create + one on confirm
+ expect(events.length).toBe(2);
+ expect(listUnresolvedTensions(vault).length).toBe(1);
+ });
+
+ test("open -> dismissed drops it from the unresolved set", () => {
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ dismissTension(vault, record.slug, { agent: "tester", reason: "not a real conflict" });
+ expect(showTension(vault, record.slug)!.status).toBe(TENSION_STATUS.dismissed);
+ expect(listUnresolvedTensions(vault).length).toBe(0);
+ });
+
+ test("open -> resolved drops it from the unresolved set", () => {
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ resolveTension(vault, record.slug, { agent: "tester", reason: "merged the two rules" });
+ expect(showTension(vault, record.slug)!.status).toBe(TENSION_STATUS.resolved);
+ expect(listUnresolvedTensions(vault).length).toBe(0);
+ });
+
+ test("an invalid transition raises a typed error", () => {
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ resolveTension(vault, record.slug, { agent: "tester" });
+ expect(() => confirmTension(vault, record.slug, { agent: "tester" })).toThrow(TensionError);
+ expect(() => resolveTension(vault, record.slug, { agent: "tester" })).toThrow(TensionError);
+ });
+
+ test("a transition on an unknown slug raises a typed error", () => {
+ expect(() => confirmTension(vault, "does-not-exist", { agent: "tester" })).toThrow(
+ TensionError,
+ );
+ });
+});
+
+describe("tensionWarningsForContextItems", () => {
+ test("warns for an included subject of an unresolved tension", () => {
+ persistTension(vault, finding(), { agent: "tester" });
+ const warnings = tensionWarningsForContextItems(vault, ["pref-tabs", "pref-unrelated"]);
+ expect(warnings.length).toBe(1);
+ expect(warnings[0]).toContain("pref-tabs");
+ });
+
+ test("emits nothing when no included item is a tension subject", () => {
+ persistTension(vault, finding(), { agent: "tester" });
+ expect(tensionWarningsForContextItems(vault, ["pref-unrelated"]).length).toBe(0);
+ });
+
+ test("emits nothing for a dismissed or resolved tension", () => {
+ const { record } = persistTension(vault, finding(), { agent: "tester" });
+ dismissTension(vault, record.slug, { agent: "tester" });
+ expect(tensionWarningsForContextItems(vault, ["pref-tabs", "pref-spaces"]).length).toBe(0);
+ });
+});
diff --git a/tests/core/config.test.ts b/tests/core/config.test.ts
index 189715c5..e801da61 100644
--- a/tests/core/config.test.ts
+++ b/tests/core/config.test.ts
@@ -11,6 +11,8 @@ import {
resolveAgentName,
resolveExposeHostPaths,
resolveLinkOutputFormat,
+ resolveDecisionRecallMaxPerSession,
+ resolveDecisionRecallMinSpacingTurns,
resolveRecallAdequacyThresholds,
resolveSkillsAttachTriggers,
resolveSkillsDir,
@@ -40,6 +42,8 @@ beforeEach(() => {
"OPEN_SECOND_BRAIN_RECALL_ADEQUACY_WEAK",
"OPEN_SECOND_BRAIN_RECALL_ADEQUACY_MIN_RESULTS",
"OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS",
+ "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION",
+ "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS",
]) {
savedEnv[k] = process.env[k];
delete process.env[k];
@@ -286,6 +290,37 @@ describe("resolveTimezone", () => {
});
});
+describe("resolveDecisionRecall config (B5)", () => {
+ test("returns null when unset (feature disabled, byte-identical)", () => {
+ const cfg = join(tmp, "missing.yaml");
+ expect(resolveDecisionRecallMaxPerSession(cfg)).toBeNull();
+ expect(resolveDecisionRecallMinSpacingTurns(cfg)).toBeNull();
+ });
+
+ test("reads non-negative integers from config", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(
+ cfg,
+ "decision_recall.max_per_session: 3\ndecision_recall.min_spacing_turns: 5\n",
+ );
+ expect(resolveDecisionRecallMaxPerSession(cfg)).toBe(3);
+ expect(resolveDecisionRecallMinSpacingTurns(cfg)).toBe(5);
+ });
+
+ test("rejects non-integer / negative values as null", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, "decision_recall.max_per_session: -1\n");
+ expect(resolveDecisionRecallMaxPerSession(cfg)).toBeNull();
+ });
+
+ test("env wins over config", () => {
+ process.env["OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION"] = "7";
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, "decision_recall.max_per_session: 2\n");
+ expect(resolveDecisionRecallMaxPerSession(cfg)).toBe(7);
+ });
+});
+
describe("resolveSkillsDir", () => {
test("returns null when neither env nor config", () => {
expect(resolveSkillsDir(join(tmp, "missing.yaml"))).toBeNull();
diff --git a/tests/core/search/authored-at.test.ts b/tests/core/search/authored-at.test.ts
new file mode 100644
index 00000000..1fd013e0
--- /dev/null
+++ b/tests/core/search/authored-at.test.ts
@@ -0,0 +1,88 @@
+/**
+ * Conversation chronology (S1 / t_347e8224): the `authored_at` frontmatter
+ * instant is carried into the indexed document and exposed on search
+ * results, and drives the exact hybrid-score recency tie-break end to end.
+ * A document with no `authored_at` is unchanged (no field on its result).
+ */
+
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { utimesSync } from "node:fs";
+import { join } from "node:path";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { search } from "../../../src/core/search/search.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+beforeEach(() => {
+ const v = createTempVault("authored-at");
+ vault = v.vault;
+ dbPath = v.dbPath;
+ cleanup = v.cleanup;
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+function signalMd(authoredAt: string | null, marker: string): string {
+ const fm = [
+ "---",
+ "kind: brain-signal",
+ "source_type: session",
+ ...(authoredAt !== null ? [`authored_at: ${authoredAt}`] : []),
+ "---",
+ "",
+ `# Turn ${marker}`,
+ "",
+ `The operator discussed chronology token ${marker} in this turn.`,
+ "",
+ ];
+ return fm.join("\n");
+}
+
+test("authored_at is carried into the index and exposed on search results", async () => {
+ writeMd(vault, "Brain/inbox/sig-a.md", signalMd("2026-05-20T10:00:00Z", "alpha"));
+ const config = makeConfig({ vault, dbPath });
+ await indexVault(config, { embeddings: false });
+
+ const outcome = await search(config, { query: "chronology token alpha", limit: 5 });
+ const hit = outcome.results.find((r) => r.path === "Brain/inbox/sig-a.md");
+ expect(hit).toBeDefined();
+ expect(hit!.authoredAt).toBe(Math.floor(Date.parse("2026-05-20T10:00:00Z") / 1000));
+});
+
+test("a document without authored_at exposes no authoredAt field (byte-identical shape)", async () => {
+ writeMd(vault, "Brain/inbox/sig-plain.md", signalMd(null, "beta"));
+ const config = makeConfig({ vault, dbPath });
+ await indexVault(config, { embeddings: false });
+
+ const outcome = await search(config, { query: "chronology token beta", limit: 5 });
+ const hit = outcome.results.find((r) => r.path === "Brain/inbox/sig-plain.md");
+ expect(hit).toBeDefined();
+ expect(hit!.authoredAt).toBeUndefined();
+ expect("authoredAt" in hit!).toBe(false);
+});
+
+test("exact-score ties surface the more recent authored_at first end to end", async () => {
+ // Two documents with identical searchable content β†’ tied relevance; only
+ // authored_at distinguishes them. The newer one must lead.
+ writeMd(vault, "Brain/inbox/sig-old.md", signalMd("2026-01-01T00:00:00Z", "tie"));
+ writeMd(vault, "Brain/inbox/sig-new.md", signalMd("2026-06-01T00:00:00Z", "tie"));
+ // Pin identical storage mtimes so the recency boost is equal and the
+ // only distinguishing signal on the exact tie is authored_at.
+ const when = new Date("2026-06-15T00:00:00Z");
+ utimesSync(join(vault, "Brain/inbox/sig-old.md"), when, when);
+ utimesSync(join(vault, "Brain/inbox/sig-new.md"), when, when);
+ const config = makeConfig({ vault, dbPath });
+ await indexVault(config, { embeddings: false });
+
+ const outcome = await search(config, { query: "chronology token tie", limit: 5 });
+ const tied = outcome.results.filter((r) => r.path.startsWith("Brain/inbox/sig-"));
+ expect(tied.length).toBe(2);
+ expect(tied[0]!.score).toBeCloseTo(tied[1]!.score, 6);
+ expect(tied[0]!.path).toBe("Brain/inbox/sig-new.md");
+});
diff --git a/tests/core/search/ranker.test.ts b/tests/core/search/ranker.test.ts
index 1d747635..300b9649 100644
--- a/tests/core/search/ranker.test.ts
+++ b/tests/core/search/ranker.test.ts
@@ -326,3 +326,103 @@ test("limit truncates after ranking", () => {
);
expect(ranked.length).toBe(5);
});
+
+// ── conversation chronology: exact-score recency tie-break (S1 / t_347e8224) ──
+
+/** Like `hyd`, but with an explicit `authored_at` (unix seconds) or null. */
+function hydAuthored(
+ chunkId: number,
+ docId: number,
+ mtime: number,
+ authoredAt: number | null,
+): HydratedChunk {
+ return Object.freeze({
+ chunkId,
+ documentId: docId,
+ path: `doc${docId}.md`,
+ title: `Doc ${docId}`,
+ content: `chunk ${chunkId}`,
+ startLine: 1,
+ endLine: 1,
+ mtime,
+ authoredAt,
+ });
+}
+
+const T_OLD = 1_700_000_000; // unix seconds
+const T_NEW = 1_700_100_000;
+
+test("exact hybrid-score tie orders the more recent authored_at first (S1)", () => {
+ // Equal bm25 + no boosts β†’ an EXACT score tie between the two chunks.
+ const kw: KeywordHit[] = [
+ { chunkId: 1, documentId: 10, bm25: -3 },
+ { chunkId: 2, documentId: 11, bm25: -3 },
+ ];
+ const hydrated = new Map<number, HydratedChunk>([
+ // chunk 1 is OLDER, chunk 2 is NEWER; identical mtime so only authored_at differs.
+ [1, hydAuthored(1, 10, OLD_MTIME, T_OLD)],
+ [2, hydAuthored(2, 11, OLD_MTIME, T_NEW)],
+ ]);
+ const ranked = rankResults(
+ { keyword: kw, semantic: [], hydrated, inboundLinkSources: new Map(), tagsByDoc: new Map() },
+ { keywordWeight: 1, semanticWeight: 0, limit: 10, nowMs: NOW },
+ );
+ expect(ranked[0]!.score).toBeCloseTo(ranked[1]!.score, 6);
+ expect(ranked[0]!.chunkId).toBe(2); // newer first
+ expect(ranked[0]!.authoredAt).toBe(T_NEW);
+ expect(ranked[1]!.authoredAt).toBe(T_OLD);
+});
+
+test("a non-tied pair keeps today's order regardless of authored_at (S1 regression)", () => {
+ // chunk 1 has the STRONGER bm25 (higher score) but the OLDER authored_at;
+ // chunk 2 is weaker but newer. Different scores β†’ recency must NOT reorder.
+ const kw: KeywordHit[] = [
+ { chunkId: 1, documentId: 10, bm25: -10 },
+ { chunkId: 2, documentId: 11, bm25: -1 },
+ ];
+ const hydrated = new Map<number, HydratedChunk>([
+ [1, hydAuthored(1, 10, OLD_MTIME, T_OLD)],
+ [2, hydAuthored(2, 11, OLD_MTIME, T_NEW)],
+ ]);
+ const ranked = rankResults(
+ { keyword: kw, semantic: [], hydrated, inboundLinkSources: new Map(), tagsByDoc: new Map() },
+ { keywordWeight: 1, semanticWeight: 0, limit: 10, nowMs: NOW },
+ );
+ expect(ranked[0]!.score).toBeGreaterThan(ranked[1]!.score);
+ expect(ranked[0]!.chunkId).toBe(1); // stronger score wins despite older authored_at
+});
+
+test("an exact tie where neither side carries authored_at keeps the historical order (S1)", () => {
+ const kw: KeywordHit[] = [
+ { chunkId: 1, documentId: 10, bm25: -3 },
+ { chunkId: 2, documentId: 11, bm25: -3 },
+ ];
+ const hydrated = new Map<number, HydratedChunk>([
+ [1, hydAuthored(1, 10, OLD_MTIME, null)],
+ [2, hydAuthored(2, 11, OLD_MTIME, null)],
+ ]);
+ const ranked = rankResults(
+ { keyword: kw, semantic: [], hydrated, inboundLinkSources: new Map(), tagsByDoc: new Map() },
+ { keywordWeight: 1, semanticWeight: 0, limit: 10, nowMs: NOW },
+ );
+ // Equal keywordScore + mtime β†’ chunkId asc (the historical final tie-break).
+ expect(ranked.map((r) => r.chunkId)).toEqual([1, 2]);
+ expect(ranked[0]!.authoredAt).toBeUndefined();
+});
+
+test("an exact tie with only one authored_at falls through to the historical tie-break (S1)", () => {
+ const kw: KeywordHit[] = [
+ { chunkId: 1, documentId: 10, bm25: -3 },
+ { chunkId: 2, documentId: 11, bm25: -3 },
+ ];
+ const hydrated = new Map<number, HydratedChunk>([
+ // Only chunk 2 has an instant; a mixed pair must not be reordered by it.
+ [1, hydAuthored(1, 10, OLD_MTIME, null)],
+ [2, hydAuthored(2, 11, OLD_MTIME, T_NEW)],
+ ]);
+ const ranked = rankResults(
+ { keyword: kw, semantic: [], hydrated, inboundLinkSources: new Map(), tagsByDoc: new Map() },
+ { keywordWeight: 1, semanticWeight: 0, limit: 10, nowMs: NOW },
+ );
+ expect(ranked.map((r) => r.chunkId)).toEqual([1, 2]); // chunkId asc, unchanged
+});
diff --git a/tests/core/search/schema-migration-v10.test.ts b/tests/core/search/schema-migration-v10.test.ts
new file mode 100644
index 00000000..efbf9cd5
--- /dev/null
+++ b/tests/core/search/schema-migration-v10.test.ts
@@ -0,0 +1,72 @@
+/**
+ * Schema migration v9 -> v10: the `documents.authored_at` column
+ * (conversation chronology, t_347e8224). v10 adds a nullable
+ * `authored_at INTEGER` column carrying the transcript turn instant a
+ * session-imported note was authored at. Additive and reindex-safe:
+ * existing rows default to NULL until a reindex repopulates it from the
+ * `authored_at` frontmatter field.
+ */
+
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { Database } from "bun:sqlite";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ applyMigrations,
+ LATEST_SCHEMA_VERSION,
+ readSchemaVersion,
+} from "../../../src/core/search/schema.ts";
+
+let tmp: string;
+let dbPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-mig-v10-"));
+ dbPath = join(tmp, "test.sqlite");
+});
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function hasColumn(db: Database, table: string, name: string): boolean {
+ return db
+ .query<{ name: string }, []>(`PRAGMA table_info(${table})`)
+ .all()
+ .some((c) => c.name === name);
+}
+
+test("latest schema version is 10", () => {
+ expect(LATEST_SCHEMA_VERSION).toBe(10);
+});
+
+test("fresh migration reaches latest with the authored_at column", () => {
+ const db = new Database(dbPath);
+ expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
+ expect(hasColumn(db, "documents", "authored_at")).toBe(true);
+ db.close();
+});
+
+test("a v9 index upgrades to v10 and preserves existing rows (authored_at NULL)", () => {
+ const db = new Database(dbPath);
+ applyMigrations(db); // -> latest
+ db.run(
+ "INSERT INTO documents(id, path, basename, title, content_hash, mtime, size, created_at, updated_at, indexed_at) " +
+ "VALUES (1, 'notes/alpha.md', 'alpha', 'A', 'h', 1, 1, 't', 't', 't')",
+ );
+ // Simulate an older v9 index: drop the column and rewind the version.
+ db.run("ALTER TABLE documents DROP COLUMN authored_at");
+ db.run("UPDATE index_state SET value = '9' WHERE key = 'schema_version'");
+ expect(readSchemaVersion(db)).toBe(9);
+
+ expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
+ expect(hasColumn(db, "documents", "authored_at")).toBe(true);
+ const row = db
+ .query<{ id: number; authored_at: number | null }, []>(
+ "SELECT id, authored_at FROM documents WHERE id = 1",
+ )
+ .get();
+ expect(row).toEqual({ id: 1, authored_at: null });
+ db.close();
+});
diff --git a/tests/core/search/store-aliases.test.ts b/tests/core/search/store-aliases.test.ts
index 42411845..b9205889 100644
--- a/tests/core/search/store-aliases.test.ts
+++ b/tests/core/search/store-aliases.test.ts
@@ -53,8 +53,8 @@ function targetDocId(store: Store, sourceId: number): number | null {
return row?.target_document_id ?? null;
}
-test("schema version is 9", () => {
- expect(LATEST_SCHEMA_VERSION).toBe(9);
+test("schema version is 10", () => {
+ expect(LATEST_SCHEMA_VERSION).toBe(10);
});
test("normalizeAlias lower-cases, trims, and NFC-normalises", () => {
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index 099b2224..8247660b 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -53,6 +53,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_benchmark",
"brain_bridges",
"brain_brief",
+ "brain_claims",
"brain_clusters",
"brain_codegraph_report",
"brain_context",
@@ -62,6 +63,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_context_receipts",
"brain_create_note",
"brain_dead_ends",
+ "brain_decision",
"brain_deep_synthesis",
"brain_delete_by_source",
"brain_derive_fact",
@@ -84,6 +86,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_intention",
"brain_knowledge_gaps",
"brain_labels",
+ "brain_lifecycle",
"brain_maintenance",
"brain_mcp_landscape",
"brain_memory_bridge",
@@ -115,6 +118,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_sources",
"brain_stale_scan",
"brain_switch_vault",
+ "brain_tension",
"brain_tiers",
"brain_token_impact",
"brain_trigger",
diff --git a/tests/mcp/decision-tool.test.ts b/tests/mcp/decision-tool.test.ts
new file mode 100644
index 00000000..8ef69c2e
--- /dev/null
+++ b/tests/mcp/decision-tool.test.ts
@@ -0,0 +1,265 @@
+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 { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-decision-tool-"));
+});
+afterEach(() => {
+ rmSync(vault, { 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: "decision-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+async function call(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<{ result?: unknown; error?: unknown }> {
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_decision", arguments: args },
+ })) as { result?: unknown; error?: unknown };
+}
+
+function payload(response: { result?: unknown }): Record<string, unknown> {
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ return JSON.parse(result.content[0]!.text);
+}
+
+describe("brain_decision tool", () => {
+ test("registered in the full tool table", () => {
+ expect(buildToolTable("full").find((t) => t.name === "brain_decision")).toBeDefined();
+ });
+
+ test("records a decision and reads it back with its outcome", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const recorded = payload(
+ await call(server, {
+ action: "record",
+ title: "Adopt Bun runtime",
+ chosen: "Bun",
+ assumption: "Bun stays compatible",
+ review_date: "2026-12-01",
+ }),
+ );
+ expect(recorded["id"]).toBe("decision-adopt-bun-runtime");
+ expect(recorded["obligation_created"]).toBe(true);
+
+ const outcome = payload(
+ await call(server, { action: "outcome", slug: "adopt-bun-runtime", outcome: "held up" }),
+ );
+ expect(outcome["outcome"]).toBe("held up");
+
+ const shown = payload(await call(server, { action: "show", slug: "adopt-bun-runtime" }));
+ expect(shown["outcome"]).toBe("held up");
+ });
+
+ test("similar surfaces a prior decision", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, {
+ action: "record",
+ title: "Adopt Bun runtime for CLI",
+ chosen: "Bun",
+ assumption: "x",
+ review_date: "2026-12-01",
+ });
+ const similar = payload(
+ await call(server, {
+ action: "similar",
+ title: "Adopt Bun runtime for server",
+ chosen: "Bun",
+ }),
+ );
+ expect((similar["similar"] as unknown[]).length).toBeGreaterThanOrEqual(1);
+ });
+
+ test("show surfaces commitment when set and omits it when unset (B3)", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, {
+ action: "record",
+ title: "Committed choice",
+ chosen: "X",
+ assumption: "a",
+ review_date: "2026-12-01",
+ commitment: "decided",
+ });
+ await call(server, {
+ action: "record",
+ title: "Loose choice",
+ chosen: "Y",
+ assumption: "b",
+ review_date: "2026-12-01",
+ });
+ const withCommitment = payload(
+ await call(server, { action: "show", slug: "committed-choice" }),
+ );
+ expect(withCommitment["commitment"]).toBe("decided");
+ const without = payload(await call(server, { action: "show", slug: "loose-choice" }));
+ expect("commitment" in without).toBe(false);
+ });
+
+ test("rate, list rated, and compare (B2)", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, {
+ action: "record",
+ title: "Option A",
+ chosen: "A",
+ assumption: "x",
+ review_date: "2026-12-01",
+ rating: 4,
+ });
+ await call(server, {
+ action: "record",
+ title: "Option B",
+ chosen: "B",
+ assumption: "y",
+ review_date: "2026-12-01",
+ });
+ const rated = payload(await call(server, { action: "rate", slug: "option-b", rating: 5 }));
+ expect(rated["rating"]).toBe(5);
+
+ const list = payload(await call(server, { action: "list", rated: true }));
+ const decisions = list["decisions"] as Array<{ rating: number }>;
+ expect(decisions.map((d) => d.rating)).toEqual([5, 4]);
+
+ const compared = payload(
+ await call(server, { action: "compare", slugs: ["option-a", "option-b"] }),
+ );
+ expect((compared["decisions"] as unknown[]).length).toBe(2);
+ });
+
+ test("out-of-range rating returns an error", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, {
+ action: "record",
+ title: "Option C",
+ chosen: "C",
+ assumption: "z",
+ review_date: "2026-12-01",
+ });
+ const res = await call(server, { action: "rate", slug: "option-c", rating: 9 });
+ expect(res.error).toBeDefined();
+ });
+
+ test("history reads decision-change receipts (B4)", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ // A supersede/tombstone emits a decision-change receipt via the hook.
+ await call(server, {
+ action: "record",
+ title: "Old choice",
+ chosen: "old",
+ assumption: "x",
+ review_date: "2026-12-01",
+ });
+ await call(server, {
+ action: "record",
+ title: "New choice",
+ chosen: "new",
+ assumption: "y",
+ review_date: "2026-12-01",
+ });
+ const supersede = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 20,
+ method: "tools/call",
+ params: {
+ name: "brain_lifecycle",
+ arguments: {
+ action: "supersede",
+ predecessor: "Brain/decisions/decision-old-choice.md",
+ successor: "decision-new-choice",
+ },
+ },
+ })) as { result?: unknown };
+ expect(supersede.result).toBeDefined();
+
+ const history = payload(await call(server, { action: "history" }));
+ // Two record creations each emit a decision-record receipt (B4), plus
+ // the supersede receipt from the lifecycle hook.
+ expect(history["total"]).toBe(3);
+ const receipts = history["receipts"] as Array<{ reason_code: string }>;
+ const codes = receipts.map((r) => r.reason_code);
+ expect(codes.filter((c) => c === "decision-record").length).toBe(2);
+ expect(codes).toContain("supersede");
+ });
+
+ test("recall is disabled (byte-identical) when unconfigured (B5)", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, {
+ action: "record",
+ title: "Adopt Bun runtime",
+ chosen: "Bun",
+ assumption: "x",
+ review_date: "2026-12-01",
+ rating: 5,
+ });
+ const res = payload(await call(server, { action: "recall", prompt: "adopt Bun runtime" }));
+ expect(res["enabled"]).toBe(false);
+ expect(res["surfaced"]).toBeNull();
+ expect(res["text"]).toBe("");
+ });
+
+ test("recall resurfaces a rated decision when configured (B5)", async () => {
+ process.env["OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION"] = "3";
+ try {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, {
+ action: "record",
+ title: "Adopt Bun runtime for the CLI",
+ chosen: "Bun",
+ assumption: "x",
+ review_date: "2026-12-01",
+ rating: 5,
+ });
+ const res = payload(
+ await call(server, { action: "recall", prompt: "should we adopt Bun runtime for the API" }),
+ );
+ expect(res["enabled"]).toBe(true);
+ expect((res["surfaced"] as { slug: string }).slug).toBe("adopt-bun-runtime-for-the-cli");
+ expect(res["text"]).toContain("Recalled decision");
+ } finally {
+ delete process.env["OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION"];
+ }
+ });
+
+ test("malformed input returns an error result", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const res = await call(server, {
+ action: "record",
+ title: "x",
+ chosen: "y",
+ assumption: "z",
+ review_date: "not-a-date",
+ });
+ expect(res.error).toBeDefined();
+ });
+});
diff --git a/tests/mcp/lifecycle-tool.test.ts b/tests/mcp/lifecycle-tool.test.ts
new file mode 100644
index 00000000..cffce2bb
--- /dev/null
+++ b/tests/mcp/lifecycle-tool.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Tests for the `brain_lifecycle` MCP tool's temporal-replace action
+ * (Belief lifecycle suite, A2, t_3ba9c404).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } 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, writeFrontmatter } from "../../src/core/vault.ts";
+
+let vault: string;
+const AT = "2026-07-18T12:00:00Z";
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-lifecycle-tool-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { 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-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+async function call(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<{ result?: unknown; error?: unknown }> {
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_lifecycle", arguments: args },
+ })) as { result?: unknown; error?: unknown };
+}
+
+function payload(response: { result?: unknown }): Record<string, unknown> {
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ return JSON.parse(result.content[0]!.text);
+}
+
+function writeFact(slug: string): string {
+ const rel = join("Brain", "preferences", `pref-${slug}.md`);
+ writeFrontmatter(
+ join(vault, rel),
+ {
+ kind: "brain-preference",
+ id: `pref-${slug}`,
+ _status: "confirmed",
+ topic: slug,
+ principle: `fact ${slug}`,
+ },
+ "Prose.",
+ );
+ return rel;
+}
+
+describe("brain_lifecycle temporal-replace", () => {
+ test("closes predecessor and opens successor at a shared instant", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+ const res = payload(
+ await call(server, {
+ action: "temporal-replace",
+ predecessor: pred,
+ successor: succ,
+ at: AT,
+ }),
+ );
+ expect(res["action"]).toBe("temporal-replace");
+ expect(res["at"]).toBe(AT);
+ expect(res["predecessor"]).toBe("Brain/preferences/pref-old.md");
+ expect(res["successor"]).toBe("Brain/preferences/pref-new.md");
+
+ const [predMeta] = parseFrontmatter(join(vault, pred));
+ const [succMeta] = parseFrontmatter(join(vault, succ));
+ expect(predMeta["valid_until"]).toBe(AT);
+ expect(succMeta["valid_from"]).toBe(AT);
+ });
+
+ test("missing 'at' is an INVALID_PARAMS error", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const pred = writeFact("old");
+ const succ = writeFact("new");
+ const response = await call(server, {
+ action: "temporal-replace",
+ predecessor: pred,
+ successor: succ,
+ });
+ expect(response.error).toBeDefined();
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 61bb73f7..42a4074e 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -279,6 +279,8 @@ describe("tool listing", () => {
"brain_tiers",
"brain_secrets",
"brain_maintenance",
+ // Belief lifecycle suite (t_7d5a3589): cross-type tombstone + supersede.
+ "brain_lifecycle",
// Link & Recall Intelligence Suite (v0.45.0).
"brain_bridges",
"brain_clusters",
@@ -286,6 +288,12 @@ describe("tool listing", () => {
"brain_tune",
// CodeGraph & MCP Operational Readability (v1.12.0).
"brain_codegraph_report",
+ // Belief lifecycle suite (t_6916369f): claim-graph query surface.
+ "brain_claims",
+ // Belief lifecycle suite (t_ac03214d): decision-record note family.
+ "brain_decision",
+ // Belief lifecycle suite (t_0e3f2bee): persisted-contradiction lifecycle.
+ "brain_tension",
// Agent Write Contract Suite: provider-agnostic write sessions.
"brain_write_session",
// Knowledge Provenance Suite (v1.7.0).
@@ -627,7 +635,15 @@ describe("stdio loop", () => {
// ingestion-import-robustness t_2e2e959f) = 97.
// + brain_observed_use (session-end observed-use verdict feeding recall
// ranking, retrieval-ranking-quality t_65588d8b) = 98.
- expect(list.result.tools.length).toBe(98);
+ // + brain_lifecycle (cross-type tombstone + supersede lifecycle,
+ // belief-lifecycle-decision-memory t_7d5a3589) = 99.
+ // + brain_claims (claim-graph query surface,
+ // belief-lifecycle-decision-memory t_6916369f) = 100.
+ // + brain_decision (decision-record note family,
+ // belief-lifecycle-decision-memory t_ac03214d) = 101.
+ // + brain_tension (persisted-contradiction lifecycle,
+ // belief-lifecycle-decision-memory t_0e3f2bee) = 102.
+ expect(list.result.tools.length).toBe(102);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index 7f71b04c..efbe1032 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -161,5 +161,13 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
// ingestion-import-robustness t_2e2e959f) = 97.
// + brain_observed_use (observed-use verdict feeding recall ranking,
// retrieval-ranking-quality t_65588d8b) = 98.
- expect(list.result.tools.length).toBe(98);
+ // + brain_lifecycle (cross-type tombstone + supersede lifecycle,
+ // belief-lifecycle-decision-memory t_7d5a3589) = 99.
+ // + brain_claims (claim-graph query surface,
+ // belief-lifecycle-decision-memory t_6916369f) = 100.
+ // + brain_decision (decision-record note family,
+ // belief-lifecycle-decision-memory t_ac03214d) = 101.
+ // + brain_tension (persisted-contradiction lifecycle,
+ // belief-lifecycle-decision-memory t_0e3f2bee) = 102.
+ expect(list.result.tools.length).toBe(102);
});
diff --git a/tests/mcp/search.test.ts b/tests/mcp/search.test.ts
index 5f2d532d..b0aac26e 100644
--- a/tests/mcp/search.test.ts
+++ b/tests/mcp/search.test.ts
@@ -335,3 +335,28 @@ test("second_brain_status reports search.exists=false when index missing", async
expect(search!["exists"]).toBe(false);
expect(search!["hint"]).toMatch(/o2b search index/);
});
+
+test("brain_search surfaces authoredAt when present and omits it otherwise", async () => {
+ writeMd(
+ "Brain/inbox/sig-dated.md",
+ "---\nkind: brain-signal\nsource_type: session\nauthored_at: 2026-05-20T10:00:00Z\n---\n\n# Turn\n\nchronology alpha token discussed here.",
+ );
+ writeMd(
+ "Brain/inbox/sig-plain.md",
+ "---\nkind: brain-signal\nsource_type: session\n---\n\n# Turn\n\nchronology alpha token discussed here.",
+ );
+ const cfg = resolveSearchConfig({ vault, configPath });
+ await indexVault(cfg);
+
+ const server = makeServer();
+ await initialize(server);
+ const resp = await call(server, "brain_search", { query: "chronology alpha token", limit: 10 });
+ const body = extractToolResult(resp);
+ const results = body["results"] as Array<Record<string, unknown>>;
+ const dated = results.find((r) => r["path"] === "Brain/inbox/sig-dated.md");
+ const plain = results.find((r) => r["path"] === "Brain/inbox/sig-plain.md");
+ expect(dated).toBeDefined();
+ expect(plain).toBeDefined();
+ expect(dated!["authoredAt"]).toBe(Math.floor(Date.parse("2026-05-20T10:00:00Z") / 1000));
+ expect("authoredAt" in plain!).toBe(false);
+});
diff --git a/tests/mcp/session-recall-tool.test.ts b/tests/mcp/session-recall-tool.test.ts
index ec675426..c01f0d73 100644
--- a/tests/mcp/session-recall-tool.test.ts
+++ b/tests/mcp/session-recall-tool.test.ts
@@ -126,4 +126,42 @@ describe("session recall MCP tools", () => {
expect(expanded).toMatchObject({ next_cursor: "1" });
expect(expanded.raw_content).toHaveLength(1);
});
+
+ test("since/before bound grep to a time window (S1)", async () => {
+ // Both turns are at 2026-05-20T17:00:0Xz; a before-bound in the past
+ // drops them, an enclosing window keeps them.
+ const before = await callTool("brain_session_grep", {
+ query: "receipt",
+ session_id: "session-mcp",
+ before: "2026-05-19",
+ });
+ expect((before.hits as Array<unknown>).length).toBe(0);
+
+ const windowed = await callTool("brain_session_grep", {
+ query: "receipt",
+ session_id: "session-mcp",
+ since: "2026-05-20",
+ before: "2026-05-21",
+ });
+ expect(
+ (windowed.hits as Array<{ kind: string }>).some((hit) => hit.kind === "session_turn"),
+ ).toBe(true);
+ });
+
+ test("an unparseable time bound rejects with an MCP error (S1)", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: {
+ name: "brain_session_grep",
+ arguments: { query: "receipt", since: "not-a-date" },
+ },
+ })) as { error?: { message: string }; result?: { isError?: boolean } };
+ // The invalid-input surfaces as an error (either JSON-RPC error or an
+ // isError tool result), never a silently ignored filter.
+ expect(response.error !== undefined || response.result?.isError === true).toBe(true);
+ });
});
diff --git a/tests/mcp/tension-tool.test.ts b/tests/mcp/tension-tool.test.ts
new file mode 100644
index 00000000..558090c4
--- /dev/null
+++ b/tests/mcp/tension-tool.test.ts
@@ -0,0 +1,131 @@
+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 { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+import { persistTension } from "../../src/core/brain/tensions.ts";
+import type { NoteContradictionFinding } from "../../src/core/brain/health/contradiction.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-tension-tool-"));
+});
+afterEach(() => {
+ rmSync(vault, { 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: "tension-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+async function call(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<{ result?: unknown; error?: unknown }> {
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_tension", arguments: args },
+ })) as { result?: unknown; error?: unknown };
+}
+
+function payload(response: { result?: unknown }): Record<string, unknown> {
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ return JSON.parse(result.content[0]!.text);
+}
+
+function seed(): string {
+ const finding: NoteContradictionFinding = {
+ aId: "pref-tabs",
+ bId: "pref-spaces",
+ subject: "tabs use",
+ jaccard: 0.6,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "Always use tabs.",
+ bQuote: "Never use tabs.",
+ action: "ask_user",
+ };
+ return persistTension(vault, finding, { agent: "tester" }).record.slug;
+}
+
+describe("brain_tension tool", () => {
+ test("registered in the full tool table", () => {
+ expect(buildToolTable("full").find((t) => t.name === "brain_tension")).toBeDefined();
+ });
+
+ test("lists and transitions a tension", async () => {
+ const slug = seed();
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+
+ const listed = payload(await call(server, { action: "list" }));
+ expect((listed["tensions"] as unknown[]).length).toBe(1);
+
+ const confirmed = payload(await call(server, { action: "confirm", slug }));
+ expect(confirmed["status"]).toBe("confirmed");
+
+ const resolved = payload(await call(server, { action: "resolve", slug, reason: "merged" }));
+ expect(resolved["status"]).toBe("resolved");
+ });
+
+ test("detect scans the note corpus and persists a tension", async () => {
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nnotes:\n read_paths:\n - Notes\n",
+ "utf8",
+ );
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Notes", "tabs.md"),
+ "---\nid: note-tabs\n---\nAlways use tabs for indentation in source files.\n",
+ "utf8",
+ );
+ writeFileSync(
+ join(vault, "Notes", "spaces.md"),
+ "---\nid: note-spaces\n---\nNever use tabs for indentation in source files.\n",
+ "utf8",
+ );
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+
+ const detected = payload(await call(server, { action: "detect" }));
+ expect(detected["created"]).toBe(1);
+ expect(detected["scanned_files"]).toBe(2);
+ expect((detected["tensions"] as unknown[]).length).toBe(1);
+
+ const listed = payload(await call(server, { action: "list" }));
+ expect((listed["tensions"] as unknown[]).length).toBe(1);
+ });
+
+ test("detect rejects an out-of-range jaccard", async () => {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ const bad = await call(server, { action: "detect", jaccard: 2 });
+ expect(bad.error).toBeDefined();
+ });
+
+ test("an invalid transition returns an error", async () => {
+ const slug = seed();
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ await call(server, { action: "dismiss", slug });
+ const bad = await call(server, { action: "confirm", slug });
+ expect(bad.error).toBeDefined();
+ });
+});