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: brain lifecycle suite - mutation audit, multi-phase dream, reconcile domains, morning brief, temporal extraction, heal enrichment (#48)

Sol Aitken73e4a28a8fbf
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index fab2aa69..aee84987 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.20.0",
+ "version": "0.21.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 ab12e4c1..914773a6 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.20.0",
+ "version": "0.21.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 ace3bc1f..88abf55a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,69 @@ 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).
+## [0.21.0] - 2026-05-29
+
+Brain lifecycle suite. The nightly `dream` consolidation becomes an
+explicit ordered pipeline, every preference gains an authoritative
+mutation trail, contradictions are classified by domain instead of a
+flat list, a budgeted session-start brief surfaces what matters, and
+formal temporal constraints are lifted from signal text - all
+deterministic and language-agnostic, with each new layer a no-op until
+it applies or is opted in.
+
+### Added
+
+- Per-preference mutation audit log (`src/core/brain/pref-audit.ts`).
+ An append-only JSONL trail under `Brain/log/pref-audit/<pref-id>.jsonl`
+ captures every mutation (create / promote / update / retire / merge)
+ with agent, reason, and revision + content-hash before/after, written
+ at the mutation chokepoints (`writePreferenceTxn`, `moveToRetired`,
+ `mergePreferences`) so it is authoritative and also records manual
+ edits. Counter-only `update` churn is suppressed, so a no-op dream run
+ writes no audit line. Read surface: `o2b brain audit <pref-id>` and
+ the `brain_audit` MCP tool.
+- Multi-phase dream pipeline (`src/core/brain/dream-phases.ts`). The
+ proven `dream()` internals are unchanged; the existing seams are named
+ as ordered phases (close -> reconcile -> synthesize -> heal -> log),
+ each emitting a workrun checkpoint and a structured
+ `DreamRunSummary.phases` summary. A no-op run returns `phases: []`.
+- Reconcile-phase domain classification
+ (`src/core/brain/reconcile-domains.ts`). Each contradiction is bucketed
+ by structural signal shape into claims / entity / decisions /
+ source-freshness. Only source-freshness with a decisive recency gap
+ auto-resolves (recorded as a `reconcile` log event, never a
+ sub-threshold mutation); the rest surface as `DreamRunSummary.open_questions`.
+ The legacy `contradictions` field stays a derived view. No forced merge,
+ no LLM fan-out.
+- Morning brief (`src/core/brain/morning-brief.ts`). A read-only,
+ character-budgeted session-start summary of the top confirmed
+ preferences (confidence then recency), recent reconcile open questions,
+ and recent notes. Exposed as `o2b brain morning-brief` and the
+ `brain_morning_brief` MCP tool.
+- Language-agnostic temporal extraction
+ (`src/core/brain/temporal-extract.ts`). On promotion, an empty
+ `valid_from` / `valid_until` is filled from the source signal - explicit
+ bi-temporal fields preferred, else formal ISO-8601 tokens (date,
+ interval, duration anchored to a co-occurring date or `now`) parsed from
+ the signal text. No localized month/day names; the preference writer now
+ emits the bi-temporal fields.
+- Opt-in heal-phase vault enrichment (`src/core/brain/heal-enrich.ts` +
+ `heal-run.ts`). When `dream.heal_enrich_enabled` is true, the heal phase
+ completes a missing `title` from the first H1 and inserts wikilinks for
+ exact title/alias matches across user pages, excluding the Brain root and
+ the standard ignored dirs, never self-linking, via atomic writes.
+ Default false, so a default install stays byte-identical.
+
+### Notes
+
+- New config key `dream.heal_enrich_enabled` (default `false`). New MCP
+ tools `brain_audit` and `brain_morning_brief` (tool count 42 -> 44). New
+ `reconcile` log event kind (additive; tolerated by the JSONL reader).
+- Default-install behaviour is byte-identical: the audit is mutation- and
+ content-gated, phases and open questions are additive, temporal fields
+ fill only when empty, and heal enrichment is opt-in.
+- Full suite green on merge: 2771 tests passing.
+
## [0.20.0] - 2026-05-29
Recall and ranking quality. The retrieval layer gains a tunable recency
@@ -3327,6 +3390,8 @@ 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.
+[0.21.0]: https://github.com/itechmeat/open-second-brain/compare/v0.20.0...v0.21.0
+[0.20.0]: https://github.com/itechmeat/open-second-brain/compare/v0.19.0...v0.20.0
[0.19.0]: https://github.com/itechmeat/open-second-brain/compare/v0.18.0...v0.19.0
[0.18.0]: https://github.com/itechmeat/open-second-brain/compare/v0.17.0...v0.18.0
[0.17.0]: https://github.com/itechmeat/open-second-brain/compare/v0.16.0...v0.17.0
diff --git a/README.md b/README.md
index afaad607..dc5ed4fb 100644
--- a/README.md
+++ b/README.md
@@ -112,7 +112,7 @@ The capabilities you actually feel day to day:
| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` β€” SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |
| 10 | Pay Memory β€” audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |
-These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
+These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
## CLI
@@ -125,6 +125,8 @@ o2b brain digest # Recent transitions, markdown or JSON
o2b brain intent-review --json # Pre-dream signal readiness audit
o2b brain retention --json # Recommendation-only lifecycle review
o2b brain monthly --month 2026-05 --json # Month-level Brain synthesis
+o2b brain audit pref-foo --json # Full mutation trail for one preference
+o2b brain morning-brief --json # Session-start summary (prefs, open questions, notes)
o2b brain agent-query --agent claude --json # Source-agent provenance query
o2b brain agent-diff --mode diff --agent claude --agent codex
o2b search "<query>" # FTS5 over the vault
diff --git a/docs/brainstorm/brain-lifecycle-suite/cli-output/claude.md b/docs/brainstorm/brain-lifecycle-suite/cli-output/claude.md
new file mode 100644
index 00000000..fc14da51
--- /dev/null
+++ b/docs/brainstorm/brain-lifecycle-suite/cli-output/claude.md
@@ -0,0 +1,33 @@
+### Variant 1: Orchestration wrapper with chokepoint audit
+- **Approach**: Leave the proven `dream()` plan/execute internals untouched but wrap them in a thin phase orchestrator that names the existing seams (`close` β†’ `reconcile` β†’ `synthesize` β†’ `heal` β†’ `log`) and emits one checkpoint per phase into the existing `dream-workrun` JSONL. The domain classifier, temporal extractor, and heal enrichment slot in as pure functions called *inside* the relevant phase; the per-preference audit is captured at the mutation chokepoints (`writePreferenceTxn`, `moveToRetired`, `mergePreferences`) so it records authoritative before/after content hashes and also catches manual edits. Morning brief and reconcile open-questions become read-only projections plus one small open-questions artifact.
+- **Trade-offs**:
+ - Pro: phases are genuinely explicit and ordered (satisfies feature 2's intent) without moving any proven logic β€” every dream invariant is preserved by construction.
+ - Pro: audit instrumented at the write primitive is the most faithful trail (single source of truth, captures non-dream edits too) and reuses the existing `_revision`/`_content_hash` stamping.
+ - Pro: ordering guarantee (reconcile-before-synthesize, heal-after-mutations) is enforced by the orchestrator, not by reasoning about a 1974-line function.
+ - Con: audit writes are new on-disk state β€” must be gated so a no-mutation run stays a true no-op and byte-identical.
+ - Con: the orchestrator straddles the existing `scanBrain`/`planTopics`/execute boundaries, so it must thread the same in-memory plan objects carefully to avoid double-execution.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Pure phase-module pipeline + dedicated per-pref ledger
+- **Approach**: Refactor `dream()` into an explicit pipeline where each phase is its own pure module (`close.ts`, `reconcile.ts`, `synthesize.ts`, `heal.ts`) consuming a shared immutable `DreamContext` and returning a phase result + checkpoint; the proven `planTopics`/`planRefresh`/retire logic is *relocated behind unchanged signatures* into those modules. The audit gets a first-class append-only ledger (`Brain/log/pref-audit/<pref-id>.jsonl`) written transactionally with each preference mutation, and reconcile/temporal/heal are each standalone deterministic modules with their own test suites.
+- **Trade-offs**:
+ - Pro: cleanest separation of concerns, maximally testable phase-by-phase, and the per-pref ledger gives the operator a directly greppable lifecycle file with no projection step.
+ - Pro: best long-term foundation if more phases are added later.
+ - Con: relocating proven logic β€” even behind identical signatures β€” is exactly the "rewrite the core" risk the constraints warn against; high chance of perturbing a subtle invariant (pinned-rebut retain, signal suppression, gated retires).
+ - Con: largest diff by far, straining the one-PR-per-version rule; many new files and a new directory layout to keep no-op-safe.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Checkpoint-extension decorator with projected audit
+- **Approach**: Don't change dream's control flow at all β€” extend the `dream-workrun` checkpoint enum with the new phase names and emit richer phase summaries at the *existing* checkpoint seams (`cluster_complete` β‰ˆ reconcile, `promote_complete` β‰ˆ synthesize), so phases are virtual labels over the current pipeline. New behaviors (classifier, temporal, heal enrichment) ship as flag-gated decorators, and the per-pref audit is a read-time projection over existing log events keyed by pref id (Γ  la `timeline.ts`), with the morning brief composed from existing `brain_digest`/`brain_daily_brief` output.
+- **Trade-offs**:
+ - Pro: lowest possible churn to the dream core; control flow is provably untouched, and the audit projection adds zero new on-disk state (byte-identical by default for free).
+ - Pro: naturally incremental β€” pieces could even be staged.
+ - Con: phases are mapped onto existing checkpoints rather than truly explicit ordered phases, which only partially honors feature 2's "explicit ordered phases each emitting a checkpoint."
+ - Con: a projected audit can only report what was already logged β€” it cannot reconstruct before/after hashes that weren't emitted, and it misses manual edits made outside the log path, weakening the "trace the full lifecycle" goal.
+- **Complexity**: small
+- **Risk**: medium
+
+### Recommended: Variant 1
+**Rationale**: It is the only variant that makes the dream phases genuinely explicit and ordered (feature 2's core intent) while preserving the proven `dream()` internals verbatim, directly honoring the "wrap/extend, don't rewrite" and invariant-preservation constraints that make Variant 2 too risky. Capturing the audit at the mutation chokepoints β€” rather than Variant 3's projection β€” yields an authoritative before/after trail that also catches manual edits, satisfying feature 1's "trace the full lifecycle" requirement, and the new audit state is easy to gate so a no-mutation dream run stays a true byte-identical no-op.
diff --git a/docs/brainstorm/brain-lifecycle-suite/cli-output/prompt.md b/docs/brainstorm/brain-lifecycle-suite/cli-output/prompt.md
new file mode 100644
index 00000000..661c341a
--- /dev/null
+++ b/docs/brainstorm/brain-lifecycle-suite/cli-output/prompt.md
@@ -0,0 +1,73 @@
+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
+
+Ship a "Brain lifecycle suite" β€” a cohesive set of 6 deterministic features that deepen Open Second Brain's nightly consolidation (`dream` pass), make preference mutations auditable, and surface a session-start brief. All features must be DETERMINISTIC (no LLM fan-out, injectable clock, byte-identical given inputs) and LANGUAGE-AGNOSTIC (no hardcoded natural-language word lists, month names, or per-language phrases β€” handle multilingual input structurally/abstractly).
+
+The 6 features:
+
+1. **Per-preference mutation audit log.** An append-only, structured trail of every mutation to a preference (status change, body edit, promotion, retirement, merge) with: who (agent), what (before/after or a content hash), when (ISO ts), why (reason code). Lets an operator trace the full lifecycle of one preference across dream passes and manual edits. OSB already has `Brain/log/<day>.md` + a JSONL sidecar for narrative events and a timeline projection, but no per-preference mutation audit keyed by pref id.
+
+2. **Multi-phase dream pipeline.** Restructure the single-pass `dream()` into explicit ordered phases β€” close (day summary) β†’ reconcile (contradictions) β†’ synthesize (promote/confirm) β†’ heal (link orphans, complete metadata, close stale) β†’ log β€” each emitting a checkpoint summary. Phase ordering must guarantee reconcile-before-synthesize and heal-after-mutations. The existing proven planning/execution logic must be preserved, not rewritten.
+
+3. **Reconcile phase: domain contradiction classification (deterministic).** Replace the current binary same/opposite-sign contradiction handling with a domain-tagged classifier that buckets contradictions into domains (claims / entity / decisions / source-freshness), auto-resolves unambiguous conflicts with a domain-appropriate strategy, and flags ambiguous ones as open questions instead of force-merging. STRICTLY deterministic β€” NO parallel LLM agents (the upstream inspiration used 4 concurrent LLM agents; we explicitly do not).
+
+4. **Morning brief / day-close summary (deterministic).** A read-only, budgeted summary surfaced at session start: recent digest signals + active preferences + open questions raised by reconcile. Complements the existing on-demand `brain_digest`. The generic external "memory ingest pipeline" from the upstream inspiration is OUT of scope β€” only the brief.
+
+5. **Temporal extraction from signal text (abstract).** A parser that extracts time constraints from a signal's raw/principle text and attaches them to the EXISTING bi-temporal frontmatter fields (`valid_from` / `valid_until`). Must be abstract: recognise ISO-8601 dates and formal relative offsets (e.g. ISO-8601 durations like `P7D`), NOT localized month/day names or natural-language phrases in any specific language.
+
+6. **Heal phase: deterministic vault enrichment.** In the dream heal phase, complete incomplete frontmatter from content and auto-link orphan pages to existing pages by EXACT title/alias match. LLM-based inference (due-date guessing, workload reasoning) is OUT of scope.
+
+# Project context
+
+Open Second Brain (OSB) β€” TypeScript on Bun. A single-user, file-based "second brain": a vault of markdown files under `Brain/` (preferences, signals/inbox, retired, log) operated by AI agents through an `o2b` CLI and an MCP server. Byte-identical determinism matters because the vault is synced across devices via Syncthing.
+
+Recent releases (newest first):
+- v0.20.0 Recall and ranking quality (Weibull recency, query intent, synonym expansion, recall budgets, query cache, pre-compress pack)
+- v0.17.0 Brain Lifecycle Review Suite (intent review, retention, monthly synthesis, complexity warning)
+- v0.14.0 Semantic Brain Health and Self-Maintenance (contradiction detection, concept gaps, stale claims, edit-history, remediation)
+- v0.12.0 Brain Integrity Suite (typed collision detection, content-hash drift, durable dream workruns)
+
+Related files (current architecture):
+- `src/core/brain/dream.ts` (1974 lines) β€” the only mutating batch op. Single-pass: `scanBrain` β†’ `planTopics` (same/opposite-sign contradiction handling) β†’ `planRefresh` (counters/confidence/promotion) β†’ `planAutoRetires` β†’ `planSignalMoves` β†’ execute (snapshot β†’ write prefs via `writePreferenceTxn` β†’ `moveToRetired` β†’ move signals to processed/) β†’ emit log events via `writeEvent` β†’ `pruneSnapshots`. Already deterministic on an injected `now`.
+- `src/core/brain/dream-workrun.ts` β€” durable JSONL workrun with `WORKRUN_PHASE` checkpoints (started / cluster_complete / promote_complete / retire_complete / finalized / interrupted) under `Brain/log/dream-runs/<run-id>.jsonl`. Readers must tolerate unknown future phases.
+- `src/core/brain/merge.ts` β€” `mergePreferences(keep, drop)` binary merge with a `MergePlan`.
+- `src/core/brain/signal.ts` β€” `parseSignal`; `BrainSignal` already carries optional bi-temporal `valid_from` / `valid_until` / `recorded_at` fields (added v0.10.18).
+- `src/core/brain/preference.ts`, `preference-txn.ts` (`writePreferenceTxn` auto-stamps `_revision` + `_content_hash`), `status.ts`.
+- `src/core/brain/log.ts` (`appendLogEvent`, `parseLogDay`), `log-jsonl.ts` (`readLogDay`, JSONL sidecar reader), `types.ts` (`BRAIN_LOG_EVENT_KIND` closed enum + `BRAIN_LOG_EVENT_KIND_SET`).
+- `src/core/brain/digest.ts` (1099 lines) β€” `brain_digest` summary builder.
+- `src/core/brain/intent-review.ts` β€” deterministic pre-dream intent review over signal clusters (two-stage gate, v0.17.0).
+- `src/core/brain/timeline.ts` β€” timeline projection over log events.
+- MCP surface: `src/mcp/brain-tools.ts`, `src/mcp/tools.ts`, `src/mcp/instructions.ts`. CLI verbs: `src/cli/brain/verbs/*.ts` (one file per verb, ~45 verbs), dispatched from `src/cli/brain.ts`; shared output helpers in `src/cli/output.ts`.
+
+Conventions:
+- TDD with Bun's test runner; tests under `tests/core/brain/` and `tests/mcp/`. Watch RED before GREEN.
+- Pure deterministic modules: inject the clock (`now: Date` / `nowMs`), never call `Date.now()` / `Math.random()` in pure code. Byte-identical output for the Syncthing contract.
+- New behaviour OFF or no-op by default where it could change existing on-disk output, so a default install stays byte-identical. The dream pass's `changed: false` no-op path must stay a true no-op.
+- Additive schema migrations only; tolerate unknown future enum values / phases on read.
+- `BRAIN_LOG_EVENT_KIND` is a closed enum β€” new event kinds extend it and must be added to the validating set.
+- One PR = one CHANGELOG version; full project name in public artifacts.
+
+Constraints:
+- Do NOT rewrite the proven `dream()` core algorithm β€” wrap/extend it. Preserve every existing dream invariant (no-op idempotence, pinned-rebut retain, signal suppression, gated retires, guardrail quarantine, workrun checkpoints).
+- STRICTLY deterministic β€” no parallel LLM agents, no network calls, injectable clock everywhere.
+- NO hardcoded natural-language word lists / month names / per-language phrases. Multilingual handling must be structural (ISO formats, exact title/alias match, content-shape signals).
+- No new external runtime dependencies unless unavoidable.
+- Must not duplicate features already shipped (intent review, retention, contradiction *detection*, edit-history `_revision`/`_content_hash`, durable workruns, temporal *storage*).
+
+# 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/brain-lifecycle-suite/design.md b/docs/brainstorm/brain-lifecycle-suite/design.md
new file mode 100644
index 00000000..ba67df03
--- /dev/null
+++ b/docs/brainstorm/brain-lifecycle-suite/design.md
@@ -0,0 +1,124 @@
+# Brain lifecycle suite - deterministic consolidation, audit, and brief
+
+**Status:** draft
+**Author:** claude-vps-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain's nightly consolidation (`dream`) is a single opaque pass,
+preference mutations leave no per-preference trail, contradictions collapse to
+one flat topic list, and there is no session-start brief. This suite makes the
+dream pass an explicit ordered pipeline, gives every preference an authoritative
+mutation history, classifies contradictions by domain, surfaces a budgeted
+brief, and extracts formal temporal constraints from signal text - all
+deterministically and without any hardcoded natural language.
+
+## Scope
+
+Six deterministic, language-agnostic features (chosen set, implemented one-by-one via TDD):
+
+1. **Per-preference mutation audit log** - append-only JSONL per pref id, captured at the mutation chokepoints (`writePreferenceTxn`, `moveToRetired`, `mergePreferences`), recording op / agent / reason / revision + content-hash before-after. Read surface: `brain_audit` (MCP) + `o2b brain audit <pref-id>` (CLI).
+2. **Multi-phase dream pipeline** - the proven `dream()` internals stay verbatim; a thin orchestration layer names the existing seams as ordered phases (close -> reconcile -> synthesize -> heal -> log), emits one workrun checkpoint + one structured summary per phase, and exposes `DreamRunSummary.phases`.
+3. **Reconcile domain classification** - a deterministic classifier buckets the run's contradictions into domains (claims / entity / decisions / source-freshness) from structural signals only, auto-resolves the unambiguous source-freshness case, and flags the rest as `open_questions` instead of force-merging. Replaces the flat `contradictions` topic list (kept as a derived view for back-compat).
+4. **Morning brief / day-close** - a read-only, budgeted summary (recent activity + top confirmed preferences + open questions from the last reconcile). Read surface: `brain_morning_brief` (MCP) + `o2b brain morning-brief` (CLI). Reuses the v0.20.0 `recall-budget` char primitive.
+5. **Temporal extraction from signal text** - a pure parser that recognises ISO-8601 dates, intervals, and durations (relative to an injected `now`) in a signal's text and fills the EXISTING bi-temporal `valid_from` / `valid_until` fields on the promoted preference when empty. ISO tokens only - no localized month/day names.
+6. **Heal-phase vault enrichment** - in the dream heal phase, complete a missing `title` from the page's first H1 and insert wikilinks for exact title/alias matches to existing pages. Opt-in (`dream.heal_enrich_enabled`, default false) because it rewrites user files; disabled = no-op.
+
+## Out of scope
+
+- Rewriting or relocating the proven `dream()` plan/execute logic (Variant 2 rejected).
+- Any LLM fan-out / parallel reconciliation agents (the upstream inspiration's 4-agent design is explicitly NOT adopted).
+- Generic external "memory ingest pipeline" beyond the brief.
+- LLM-based enrichment inference (due-date guessing, workload reasoning).
+- Localized natural-language temporal parsing (only formal ISO tokens).
+- A frontend / UI for reviewing open questions.
+
+## Chosen approach
+
+**Variant 1 - orchestration wrapper with chokepoint audit.** The phase
+pipeline is a thin orchestrator over the existing `scanBrain` -> `planTopics`
+-> `planRefresh` -> `planAutoRetires` -> execute seams: each seam is labelled a
+phase, emits a `WORKRUN_PHASE` checkpoint, and contributes a structured
+`DreamPhaseSummary`. No proven logic moves. The new deterministic capabilities
+(domain classifier, temporal extractor, heal enrichment) are pure functions
+called inside their owning phase. The audit trail is captured at the write
+primitives so it is authoritative (true before/after content hashes) and also
+catches non-dream manual edits.
+
+## Design decisions
+
+- **Audit at the chokepoint, not by projection.** `writePreferenceTxn` /
+ `moveToRetired` / `mergePreferences` already compute `_revision` and
+ `_content_hash`; they gain an optional audit sink and append one record
+ **only when the content hash actually changes** (before != after). A no-op
+ dream run touches no preference content, so it writes no audit line -> the
+ default byte-identical contract holds.
+- **Per-pref-id JSONL file** (`Brain/log/pref-audit/<pref-id>.jsonl`) so an
+ operator can `cat` one preference's whole lifecycle. Append-only, same
+ atomic-append assumption as `dream-workrun`. The op kind is a small closed
+ enum tolerant of unknown values on read.
+- **Phases are additive labels, not control-flow surgery.** `WORKRUN_PHASE`
+ gains `close_complete` / `reconcile_complete` / `synthesize_complete` /
+ `heal_complete`; readers already must tolerate unknown phases.
+ `DreamRunSummary.phases` is a new optional-shaped array; existing fields are
+ unchanged and the no-op path returns `phases: []`.
+- **Domain classification is structural.** Domain is derived from signal shape:
+ `source-freshness` when the contradiction is resolvable by `recorded_at` /
+ `created_at` recency beyond a margin; `entity` when signals carry entity
+ wikilinks in `source`; `decisions` when scope marks a decision; else
+ `claims`. Only `source-freshness` auto-resolves (toward the strictly fresher
+ side); everything else becomes an open question. No language inspection.
+- **Temporal extraction is ISO-only and additive.** Recognises `YYYY-MM-DD`,
+ `YYYY-MM-DD/YYYY-MM-DD`, and ISO-8601 durations (`P7D`, `P2W`, `P1M`, `P1Y`)
+ computed against the injected `now`. Fills `valid_from`/`valid_until` on a
+ promoted preference only when the field is empty; never overwrites.
+- **Heal enrichment is opt-in.** It rewrites user vault files, so it is gated
+ behind `dream.heal_enrich_enabled` (default false). Disabled = the heal phase
+ is a checkpoint-only no-op. Linking is exact title/alias match only.
+- **Morning brief reuses primitives.** Char budgeting via the existing
+ `applyCharBudget` (recall-budget.ts); preference ordering by confidence then
+ recency (same comparator family as `pre-compress-pack.ts`).
+
+## File changes
+
+New core modules:
+- `src/core/brain/pref-audit.ts` - audit record type, `appendPrefAudit`, `readPrefAudit`.
+- `src/core/brain/dream-phases.ts` - `DREAM_PHASE` order, `DreamPhaseSummary`, phase-summary builders.
+- `src/core/brain/reconcile-domains.ts` - `classifyContradiction`, `resolveContradiction`, `DreamOpenQuestion`.
+- `src/core/brain/morning-brief.ts` - `buildMorningBrief`.
+- `src/core/brain/temporal-extract.ts` - `extractTemporalConstraints`.
+- `src/core/brain/heal-enrich.ts` - `deriveTitleFromContent`, `linkExactMentions`, `planHealEnrichment`.
+
+Modified core:
+- `src/core/brain/dream.ts` - phase checkpoints + summaries; call classifier in reconcile, temporal-extract in synthesize promote, heal-enrich in heal; thread audit sink.
+- `src/core/brain/preference-txn.ts`, `merge.ts`, `preference.ts` (`moveToRetired`) - optional audit sink param.
+- `src/core/brain/dream-workrun.ts` - new phase constants.
+- `src/core/brain/types.ts` - `DreamRunSummary.phases`, `open_questions`; new `BRAIN_LOG_EVENT_KIND.reconcile`; audit op enum; config fields.
+- `src/core/brain/paths.ts` - `prefAuditDir` / `prefAuditPath`.
+- `src/core/brain/policy.ts` - `dream.heal_enrich_enabled` config resolution.
+- `src/core/brain/morning-brief.ts` (new, self-contained) - composes the brief from existing read helpers (`readLogDay`, confirmed-preference scan, `open_questions`); does NOT modify `digest.ts`.
+
+Note: `BrainPreference` already carries optional `valid_from` / `valid_until` /
+`recorded_at` (added v0.10.18), so feature 5 only fills those existing fields on
+the promoted preference - no schema change, no migration.
+
+MCP + CLI surface:
+- `src/mcp/brain-tools.ts` (+ `instructions.ts`, `tools.ts`) - `brain_audit`, `brain_morning_brief` (tool count 42 -> 44).
+- `src/cli/brain/verbs/audit.ts`, `morning-brief.ts` + `src/cli/brain.ts`, `help-text.ts`.
+
+Docs:
+- `README.md`, `docs/how-it-works.md`, `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md`.
+
+## Risks and open questions
+
+- **Byte-identical default.** Audit (mutation-gated), phases (additive), open
+ questions (replace a derived list), temporal (fill-when-empty), heal (opt-in)
+ are each designed to leave a default no-op dream run byte-identical. The QA
+ phase must assert a no-op run produces zero new files.
+- **Concurrent-device audit appends.** Per-pref JSONL append from two devices
+ could interleave; acceptable under the single-primary-agent dream convention
+ (same assumption as `dream-runs/`). Documented, not solved here.
+- **Domain classifier conservatism.** Auto-resolving only source-freshness
+ keeps false auto-merges at zero; all judgemental domains stay operator-facing
+ open questions. This is intentional under the "no cheap wins" rule.
diff --git a/docs/brainstorm/brain-lifecycle-suite/plan.md b/docs/brainstorm/brain-lifecycle-suite/plan.md
new file mode 100644
index 00000000..1ec1f758
--- /dev/null
+++ b/docs/brainstorm/brain-lifecycle-suite/plan.md
@@ -0,0 +1,61 @@
+# Brain lifecycle suite - implementation plan
+
+Each task is one atomic unit, implemented RED -> GREEN -> REFACTOR with its own
+commit. Tasks are ordered so foundational primitives land before the dream
+integration that consumes them. Every task keeps a default no-op dream run
+byte-identical.
+
+## Task 1: Per-preference mutation audit primitive
+- **Files**: `src/core/brain/pref-audit.ts`, `src/core/brain/paths.ts` (+ `prefAuditDir`/`prefAuditPath`), `src/core/brain/types.ts` (`PrefAuditOp` enum, `PrefAuditRecord`), `tests/core/brain/pref-audit.test.ts`
+- **Acceptance**: pure `renderPrefAuditLine` + `appendPrefAudit({pref_id, op, agent, reason, revision_before/after, hash_before/after}, {now})` writes one JSONL line under `Brain/log/pref-audit/<pref-id>.jsonl`; `readPrefAudit(vault, prefId)` round-trips records and tolerates unknown op kinds; appending with `hash_before === hash_after` is a no-op (returns false, writes nothing).
+- **Depends on**: none
+
+## Task 2: Wire audit into mutation chokepoints
+- **Files**: `src/core/brain/preference-txn.ts`, `src/core/brain/preference.ts` (`moveToRetired`), `src/core/brain/merge.ts`, tests `tests/core/brain/pref-audit-chokepoints.test.ts`
+- **Acceptance**: each chokepoint accepts an optional `audit?: { agent, reason }` sink; when provided AND content hash changed, it appends exactly one audit record with correct before/after; when content unchanged, zero records; existing call sites without the sink are unaffected (back-compat).
+- **Depends on**: Task 1
+
+## Task 3: Audit read surface (CLI + MCP)
+- **Files**: `src/cli/brain/verbs/audit.ts`, `src/cli/brain.ts`, `src/cli/brain/help-text.ts`, `src/mcp/brain-tools.ts`, `src/mcp/instructions.ts`, tests `tests/mcp/mcp.test.ts` (tool count), `tests/cli/brain-audit.test.ts`
+- **Acceptance**: `o2b brain audit <pref-id> [--json]` prints the lifecycle; `brain_audit` MCP tool returns the same; tool count 42 -> 43.
+- **Depends on**: Task 1
+
+## Task 4: Temporal extraction primitive
+- **Files**: `src/core/brain/temporal-extract.ts`, `tests/core/brain/temporal-extract.test.ts`
+- **Acceptance**: `extractTemporalConstraints(text, {now})` returns `{valid_from?, valid_until?}` for ISO date `YYYY-MM-DD`, interval `A/B`, and ISO-8601 duration (`P7D`/`P2W`/`P1M`/`P1Y`, relative to `now`); returns `{}` for text with no ISO token (incl. localized month names); never throws; deterministic on injected `now`.
+- **Depends on**: none
+
+## Task 5: Reconcile domain classifier
+- **Files**: `src/core/brain/reconcile-domains.ts`, `src/core/brain/types.ts` (`RECONCILE_DOMAIN`, `DreamOpenQuestion`), `tests/core/brain/reconcile-domains.test.ts`
+- **Acceptance**: `classifyContradiction({topic, scope, positives, negatives})` returns a domain from structural signals only; `resolveContradiction(...)` auto-resolves the source-freshness case (strictly fresher side wins beyond a margin) and returns an open question for every other domain; no language inspection anywhere; pure + deterministic.
+- **Depends on**: none
+
+## Task 6: Heal-enrichment primitive
+- **Files**: `src/core/brain/heal-enrich.ts`, `src/core/brain/policy.ts` (`dream.heal_enrich_enabled`, default false), `src/core/brain/types.ts` (config field), `tests/core/brain/heal-enrich.test.ts`
+- **Acceptance**: `deriveTitleFromContent(md)` returns the first H1 text or null; `linkExactMentions(body, knownTitlesAndAliases)` wraps only exact whole-token title/alias matches in `[[...]]` (idempotent, skips already-linked, skips code spans); `planHealEnrichment(page, known)` returns a pure plan; nothing runs unless the config flag is on.
+- **Depends on**: none
+
+## Task 7: Dream phase orchestration
+- **Files**: `src/core/brain/dream-phases.ts`, `src/core/brain/dream-workrun.ts` (new phase constants), `src/core/brain/dream.ts`, `src/core/brain/types.ts` (`DreamRunSummary.phases`), tests `tests/core/brain.dream.phases.test.ts` + existing dream tests stay green
+- **Acceptance**: a changed dream run emits ordered checkpoints `close_complete` -> `reconcile_complete` -> `synthesize_complete` -> `heal_complete` in the workrun and returns a `phases` array with one summary each; a no-op run returns `phases: []` and writes no workrun; ALL existing dream invariants/tests unchanged.
+- **Depends on**: Tasks 1-2 (audit sink available to thread)
+
+## Task 8: Reconcile integration (domains + open questions)
+- **Files**: `src/core/brain/dream.ts`, `src/core/brain/types.ts` (`DreamRunSummary.open_questions`, `BRAIN_LOG_EVENT_KIND.reconcile`), `tests/core/brain.dream.reconcile.test.ts`
+- **Acceptance**: the reconcile phase classifies the run's contradictions, auto-resolves source-freshness, emits `reconcile` open-question log events, and populates `open_questions`; the legacy `contradictions` field stays a derived view (back-compat); no force-merge ever happens.
+- **Depends on**: Tasks 5, 7
+
+## Task 9: Temporal + heal integration into dream
+- **Files**: `src/core/brain/dream.ts`, `tests/core/brain.dream.temporal.test.ts`, `tests/core/brain.dream.heal.test.ts`
+- **Acceptance**: on promotion, an empty `valid_from`/`valid_until` is filled from the source signal's text via Task 4 (never overwrites); the heal phase, when `dream.heal_enrich_enabled` is on, applies Task 6 enrichment and records it; with the flag off (default) the dream output is byte-identical to pre-suite.
+- **Depends on**: Tasks 4, 6, 7
+
+## Task 10: Morning brief
+- **Files**: `src/core/brain/morning-brief.ts`, `src/cli/brain/verbs/morning-brief.ts`, `src/cli/brain.ts`, `src/cli/brain/help-text.ts`, `src/mcp/brain-tools.ts`, `src/mcp/instructions.ts`, tests `tests/core/brain/morning-brief.test.ts` + `tests/mcp/mcp.test.ts` (count -> 44)
+- **Acceptance**: `buildMorningBrief(vault, {now, topK, maxChars})` composes recent activity + top confirmed preferences (confidence then recency) + open questions, char-budgeted via `applyCharBudget`; read-only; `o2b brain morning-brief [--json]` + `brain_morning_brief` expose it; tool count -> 44.
+- **Depends on**: Task 8 (open questions source)
+
+## Task 11: QA, docs, version bump, release prep
+- **Files**: `README.md`, `docs/how-it-works.md`, `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md`, `package.json` + manifests (via sync-version), tests for config parsing
+- **Acceptance**: full `bun run validate` green; a no-op dream run asserted byte-identical; docs describe all 6 features; one `[0.21.0]` CHANGELOG entry; version synced across manifests.
+- **Depends on**: Tasks 1-10
diff --git a/docs/brainstorm/brain-lifecycle-suite/variants.md b/docs/brainstorm/brain-lifecycle-suite/variants.md
new file mode 100644
index 00000000..49480a42
--- /dev/null
+++ b/docs/brainstorm/brain-lifecycle-suite/variants.md
@@ -0,0 +1,45 @@
+# Brain lifecycle suite - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), primary. Exit 0, three parseable
+variants returned; the Codex fallback was therefore not run. Raw output is
+preserved at `cli-output/claude.md`; the filled prompt at `cli-output/prompt.md`.
+
+## Variants (verbatim)
+
+### Variant 1: Orchestration wrapper with chokepoint audit
+- **Approach**: Leave the proven `dream()` plan/execute internals untouched but wrap them in a thin phase orchestrator that names the existing seams (`close` -> `reconcile` -> `synthesize` -> `heal` -> `log`) and emits one checkpoint per phase into the existing `dream-workrun` JSONL. The domain classifier, temporal extractor, and heal enrichment slot in as pure functions called inside the relevant phase; the per-preference audit is captured at the mutation chokepoints (`writePreferenceTxn`, `moveToRetired`, `mergePreferences`) so it records authoritative before/after content hashes and also catches manual edits. Morning brief and reconcile open-questions become read-only projections plus one small open-questions artifact.
+- **Trade-offs**: Pro - phases genuinely explicit and ordered without moving proven logic; every invariant preserved by construction. Pro - audit at the write primitive is the most faithful trail (single source of truth, catches non-dream edits) and reuses existing `_revision`/`_content_hash`. Pro - ordering guarantee enforced by the orchestrator, not by reasoning about a 1974-line function. Con - audit writes are new on-disk state, must be gated so a no-mutation run stays byte-identical. Con - the orchestrator straddles existing seams and must thread the same in-memory plan objects carefully.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Pure phase-module pipeline + dedicated per-pref ledger
+- **Approach**: Refactor `dream()` into an explicit pipeline where each phase is its own pure module (`close.ts`, `reconcile.ts`, `synthesize.ts`, `heal.ts`) consuming a shared immutable `DreamContext` and returning a phase result + checkpoint; the proven `planTopics`/`planRefresh`/retire logic is relocated behind unchanged signatures into those modules. The audit gets a first-class append-only ledger (`Brain/log/pref-audit/<pref-id>.jsonl`) written transactionally with each preference mutation, and reconcile/temporal/heal are standalone deterministic modules with their own test suites.
+- **Trade-offs**: Pro - cleanest separation of concerns, maximally testable phase-by-phase; per-pref ledger is directly greppable with no projection step. Pro - best long-term foundation for more phases. Con - relocating proven logic (even behind identical signatures) is exactly the "rewrite the core" risk the constraints warn against; high chance of perturbing a subtle invariant. Con - largest diff by far, straining one-PR-per-version; many new files and a new layout to keep no-op-safe.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Checkpoint-extension decorator with projected audit
+- **Approach**: Don't change dream's control flow at all - extend the `dream-workrun` checkpoint enum with the new phase names and emit richer phase summaries at the existing checkpoint seams (`cluster_complete` ~ reconcile, `promote_complete` ~ synthesize), so phases are virtual labels over the current pipeline. New behaviours ship as flag-gated decorators, and the per-pref audit is a read-time projection over existing log events keyed by pref id (like `timeline.ts`), with the morning brief composed from existing digest output.
+- **Trade-offs**: Pro - lowest churn; control flow provably untouched; audit projection adds zero new on-disk state (byte-identical by default for free). Pro - naturally incremental. Con - phases mapped onto existing checkpoints rather than truly explicit ordered phases, only partially honouring feature 2. Con - a projected audit can only report what was already logged; cannot reconstruct before/after hashes that were not emitted, and misses manual edits made outside the log path, weakening the lifecycle-trace goal.
+- **Complexity**: small
+- **Risk**: medium
+
+### Consultant recommendation: Variant 1
+Only variant that makes the dream phases genuinely explicit and ordered while
+preserving the proven internals verbatim, honouring "wrap/extend, don't
+rewrite". Chokepoint audit (vs Variant 3's projection) yields an authoritative
+before/after trail that also catches manual edits; the new audit state is easy
+to gate so a no-mutation run stays byte-identical.
+
+## Orchestrator decision: Variant 1 (agree with consultant)
+
+Adopted without override. Variant 1 is the only option that satisfies the hard
+"do not rewrite the proven `dream()` core" constraint while still delivering
+genuinely explicit ordered phases. Variant 2's relocation of battle-tested
+planning logic (pinned-rebut retain, signal suppression, gated retires,
+guardrail quarantine) is the precise risk the constraints forbid, and its diff
+size strains the one-PR-per-version rule. Variant 3's projected audit cannot
+reconstruct authoritative before/after content hashes and misses manual edits,
+failing feature 1's "trace the full lifecycle" goal. Variant 1's only cost -
+new audit on-disk state - is neutralised by gating the append on an actual
+content-hash change, preserving the byte-identical default-install contract.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 3afe0569..ee4bacb0 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -49,6 +49,8 @@ o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/pref
o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...). --remediate [--dry-run] plans a dependency-ordered repair and applies auto-safe content-hash re-stamps
o2b brain health Semantic-health report (since v0.14.0): contradictory confirmed preferences, recurring concepts with no dedicated preference, stale claims, plus a clean | watch | investigate verdict
o2b brain history Render a preference's edit-history timeline (since v0.14.0): one entry per content mutation (principle / scope / status before -> after)
+o2b brain audit Render a preference's full mutation audit trail (since v0.21.0): create / promote / update / retire / merge with agent, reason, revision + content-hash before/after. ret- or bare-slug arg resolves to the same trail
+o2b brain morning-brief Read-only session-start summary (since v0.21.0): top confirmed preferences, recent reconcile open questions, recent notes; bounded by --max-chars-per-memory / --max-total-chars; --top-k / --lookback-days
o2b brain backlinks List inbound references to a Brain artifact id
o2b brain mcp-landscape List MCP servers configured across the vault (since v0.19.0): name, source file, packages, required env-var names (values never read)
o2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yaml
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 0d43aeae..2be55262 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -281,6 +281,34 @@ Key rules baked into the pipeline:
preference is logged as a `skip-corrupted-frontmatter` event; the
rest of the run proceeds.
+### Lifecycle suite (v0.21.0)
+
+The same pipeline is named as five explicit ordered phases - **close**
+(scan) -> **reconcile** (contradictions) -> **synthesize** (promote /
+confirm) -> **heal** (auto-retire stale, optional enrichment) -> **log**
+- each emitting a workrun checkpoint and a structured entry in
+`DreamRunSummary.phases`. The internals are unchanged; the phases are
+labels over the existing seams, so every invariant above still holds.
+
+- **Reconcile classification.** Each contradiction is bucketed by
+ structural signal shape (claims / entity / decisions / source-freshness).
+ Only source-freshness with a decisive recency gap auto-resolves - and
+ even then it is *recorded* as a `reconcile` log event, never a
+ sub-threshold state mutation. Everything else surfaces in
+ `open_questions` for operator review rather than being force-merged.
+- **Per-preference audit.** Every mutation (create / promote / update /
+ retire / merge) appends one line to `Brain/log/pref-audit/<pref-id>.jsonl`
+ with the agent, reason, and revision + content-hash before/after.
+ Counter-only churn is suppressed, so a no-op run writes no audit line.
+- **Temporal extraction.** On promotion an empty `valid_from` /
+ `valid_until` is filled from the source signal - explicit bi-temporal
+ fields first, else formal ISO-8601 tokens parsed from the signal text
+ (no localized month/day names).
+- **Heal enrichment** (opt-in via `dream.heal_enrich_enabled`, default
+ off). The heal phase links exact title/alias mentions across user vault
+ pages outside the Brain root. Disabled by default so the install stays
+ byte-identical.
+
## Confidence formula
Confidence is computed for every active preference on every dream
diff --git a/docs/mcp.md b/docs/mcp.md
index 16723f75..cf2174b8 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -18,7 +18,7 @@ in Open Second Brain depends on the MCP server being running.
## Tool Highlights
-The full server currently advertises 35 tools. The table below highlights the
+The full server currently advertises 44 tools. The table below highlights the
operator-facing core, agent-source, health, and Pay Memory tools; the full
surface also includes Brain writer, review, query, temporal, link-graph, and
search tools. In Claude Code, that full schema can push MCP definitions beyond
@@ -34,6 +34,8 @@ writer split below for the always-loaded writer subset.
| `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | β€” |
| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | β€” |
| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | β€” |
+| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
+| `brain_morning_brief` | Read-only session-start summary: top confirmed preferences, recent reconcile open questions, recent notes; character-budgeted. | β€” |
| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | β€” |
| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |
| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |
@@ -259,7 +261,7 @@ server to your Codex MCP config the same way as Hermes.
The plugin's `.mcp.json` ships **two** MCP-server entries:
-- `open-second-brain` - the full surface (42 tools, including `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_pinned_context`, and `brain_pre_compress_pack`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
+- `open-second-brain` - the full surface (44 tools, including `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_pinned_context`, `brain_pre_compress_pack`, `brain_audit`, and `brain_morning_brief`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.
Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index cb790c42..0090646a 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": "0.20.0",
+ "version": "0.21.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 24004a22..31c214f5 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.20.0",
+ "version": "0.21.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 434acd94..b47e9835 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.20.0"
+version: "0.21.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index e6a95493..3d0fd5ec 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.20.0",
+ "version": "0.21.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 b195fae8..9a4b292a 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.20.0"
+version: "0.21.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 8d41e1cc..a0bc7bbc 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 = "0.20.0"
+version = "0.21.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 7158bb12..36537a49 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -31,6 +31,8 @@ import {
cmdBrainDoctor,
cmdBrainHealth,
cmdBrainHistory,
+ cmdBrainAudit,
+ cmdBrainMorningBrief,
cmdBrainBacklinks,
cmdBrainMcpLandscape,
cmdBrainMerge,
@@ -125,6 +127,10 @@ export async function handleBrainSubcommand(
return await cmdBrainHealth(rest);
case "history":
return await cmdBrainHistory(rest);
+ case "audit":
+ return await cmdBrainAudit(rest);
+ case "morning-brief":
+ return await cmdBrainMorningBrief(rest);
case "backlinks":
return await cmdBrainBacklinks(rest);
case "mcp-landscape":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 8e6e9a91..2cc8e969 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -38,6 +38,8 @@ Brain verbs (observing memory):
doctor Validate Brain invariants (--strict; --remediate [--dry-run])
health Semantic-health report: contradictions, concept gaps, stale claims
history Render a preference's edit-history timeline
+ audit Render a preference's full mutation audit trail
+ morning-brief Session-start summary: top prefs, open questions, recent notes
backlinks List inbound references to a Brain artifact id
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
@@ -165,6 +167,18 @@ export const VERB_HELP: Record<string, string> = {
"usage: o2b brain history <slug> [--vault <path>] [--json]\n" +
"Render a preference's edit-history timeline (one entry per content\n" +
"mutation: principle/scope/status before -> after). Read-only.\n",
+ audit:
+ "usage: o2b brain audit <pref-id> [--vault <path>] [--json]\n" +
+ "Render a preference's full mutation audit trail (create / promote /\n" +
+ "update / retire / merge) with agent, reason, and revision + content-hash\n" +
+ "before/after. A ret- or bare-slug argument resolves to the same trail.\n" +
+ "Read-only.\n",
+ "morning-brief":
+ "usage: o2b brain morning-brief [--vault <path>] [--json] [--top-k <n>]\n" +
+ " [--lookback-days <n>] [--max-chars-per-memory <n>] [--max-total-chars <n>]\n" +
+ "Render a read-only session-start summary: top confirmed preferences\n" +
+ "(confidence then recency), recent reconcile open questions, and recent\n" +
+ "notes, bounded by the shared recall char budget. Read-only.\n",
backlinks:
"usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +
"List inbound references to the given Brain artifact id (preference, retired, signal).\n",
diff --git a/src/cli/brain/verbs/audit.ts b/src/cli/brain/verbs/audit.ts
new file mode 100644
index 00000000..98e133c3
--- /dev/null
+++ b/src/cli/brain/verbs/audit.ts
@@ -0,0 +1,42 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { readPrefAudit, renderPrefAudit } from "../../../core/brain/pref-audit.ts";
+import { fail, parse, resolveBrainVault } from "../helpers.ts";
+
+/**
+ * `o2b brain audit <pref-id>` - render a preference's full mutation
+ * audit trail (create / promote / update / retire / merge). The trail
+ * is keyed by the original `pref-<slug>` id, so a `ret-<slug>` or bare
+ * `<slug>` argument is normalised to the same file. Read-only.
+ */
+export async function cmdBrainAudit(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const raw = positional[0];
+ if (!raw) return fail("usage: o2b brain audit <pref-id>");
+ const slug = raw.replace(/^(?:pref-|ret-)/, "").trim();
+ if (slug.length === 0) {
+ return fail(`audit: empty preference slug after stripping prefix from '${raw}'`);
+ }
+ const prefId = `pref-${slug}`;
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ let result;
+ try {
+ result = readPrefAudit(vault, prefId);
+ } catch (exc) {
+ return fail(`audit failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ pref_id: prefId, ...result }, null, 2) + "\n",
+ );
+ } else {
+ process.stdout.write(renderPrefAudit(prefId, result.records) + "\n");
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 48fea059..18627781 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -18,6 +18,8 @@ export { cmdBrainRollback } from "./rollback.ts";
export { cmdBrainDoctor } from "./doctor.ts";
export { cmdBrainHealth } from "./health.ts";
export { cmdBrainHistory } from "./history.ts";
+export { cmdBrainAudit } from "./audit.ts";
+export { cmdBrainMorningBrief } from "./morning-brief.ts";
export { cmdBrainBacklinks } from "./backlinks.ts";
export { cmdBrainMcpLandscape } from "./mcp-landscape.ts";
export { cmdBrainMerge } from "./merge.ts";
diff --git a/src/cli/brain/verbs/morning-brief.ts b/src/cli/brain/verbs/morning-brief.ts
new file mode 100644
index 00000000..a2c44610
--- /dev/null
+++ b/src/cli/brain/verbs/morning-brief.ts
@@ -0,0 +1,63 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { buildMorningBrief } from "../../../core/brain/morning-brief.ts";
+import { parseOptionalNumberFlag } from "../../coerce.ts";
+import { fail, parse, resolveBrainVault } from "../helpers.ts";
+
+/**
+ * `o2b brain morning-brief` - render a read-only session-start summary:
+ * top confirmed preferences, recent reconcile open questions, and recent
+ * notes. Bounded by the shared recall char budget.
+ */
+export async function cmdBrainMorningBrief(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "top-k": { type: "string" },
+ "lookback-days": { type: "string" },
+ "max-chars-per-memory": { type: "string" },
+ "max-total-chars": { type: "string" },
+ });
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ // Positive-integer validation mirroring the MCP tool's
+ // optionalPositiveInt, so the CLI and MCP surfaces share semantics.
+ const positiveInt = (name: string): { value: number | null; error: string | null } => {
+ const parsed = parseOptionalNumberFlag(flags, name);
+ if (parsed.error) return parsed;
+ if (parsed.value !== null && (!Number.isInteger(parsed.value) || parsed.value < 1)) {
+ return { value: null, error: `--${name} must be a positive integer` };
+ }
+ return parsed;
+ };
+
+ const topKFlag = positiveInt("top-k");
+ if (topKFlag.error) return fail(topKFlag.error);
+ const lookbackFlag = positiveInt("lookback-days");
+ if (lookbackFlag.error) return fail(lookbackFlag.error);
+ const perMemFlag = positiveInt("max-chars-per-memory");
+ if (perMemFlag.error) return fail(perMemFlag.error);
+ const totalFlag = positiveInt("max-total-chars");
+ if (totalFlag.error) return fail(totalFlag.error);
+
+ let brief;
+ try {
+ brief = buildMorningBrief(vault, {
+ now: new Date(),
+ topK: topKFlag.value ?? 10,
+ lookbackDays: lookbackFlag.value ?? 7,
+ ...(perMemFlag.value !== null ? { maxCharsPerMemory: perMemFlag.value } : {}),
+ ...(totalFlag.value !== null ? { maxTotalChars: totalFlag.value } : {}),
+ });
+ } catch (exc) {
+ return fail(`morning-brief failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(brief, null, 2) + "\n");
+ } else {
+ process.stdout.write((brief.text.length > 0 ? brief.text : "(nothing to surface)") + "\n");
+ }
+ return 0;
+}
diff --git a/src/core/brain/dream-phases.ts b/src/core/brain/dream-phases.ts
new file mode 100644
index 00000000..b4ce2719
--- /dev/null
+++ b/src/core/brain/dream-phases.ts
@@ -0,0 +1,45 @@
+/**
+ * Multi-phase dream pipeline labels (Brain lifecycle suite, Feature 2).
+ *
+ * The proven `dream()` internals are NOT rewritten. This module only
+ * names the existing seams as explicit ordered phases so the pass emits
+ * one workrun checkpoint and one structured summary per phase:
+ *
+ * close - scan the tree, snapshot the starting counts
+ * reconcile - contradiction handling + domain classification (F3)
+ * synthesize - promote / confirm / refresh preferences
+ * heal - auto-retire stale, optional vault enrichment (F6)
+ * log - emit events + audit, finalise
+ *
+ * Ordering guarantees reconcile-before-synthesize and heal-after the
+ * mutating writes. The phase list is the contract; `DreamPhaseSummary`
+ * carries integer metrics so a run is auditable without re-deriving.
+ */
+
+export const DREAM_PHASE = {
+ close: "close",
+ reconcile: "reconcile",
+ synthesize: "synthesize",
+ heal: "heal",
+ log: "log",
+} as const;
+export type DreamPhase = (typeof DREAM_PHASE)[keyof typeof DREAM_PHASE];
+
+/** Canonical phase order. Readers MUST tolerate unknown future phases. */
+export const DREAM_PHASE_ORDER: ReadonlyArray<DreamPhase> = Object.freeze([
+ DREAM_PHASE.close,
+ DREAM_PHASE.reconcile,
+ DREAM_PHASE.synthesize,
+ DREAM_PHASE.heal,
+ DREAM_PHASE.log,
+]);
+
+/**
+ * One phase's structured summary. `metrics` holds integer counters
+ * describing what the phase observed or did; the keys are phase-specific
+ * and additive (new keys may appear in future versions).
+ */
+export interface DreamPhaseSummary {
+ readonly phase: DreamPhase;
+ readonly metrics: Readonly<Record<string, number>>;
+}
diff --git a/src/core/brain/dream-workrun.ts b/src/core/brain/dream-workrun.ts
index 3b3f64ff..195e0ca6 100644
--- a/src/core/brain/dream-workrun.ts
+++ b/src/core/brain/dream-workrun.ts
@@ -46,6 +46,13 @@ export const WORKRUN_PHASE = Object.freeze({
retireComplete: "retire_complete",
finalized: "finalized",
interrupted: "interrupted",
+ // Brain lifecycle suite (Feature 2): multi-phase dream checkpoints.
+ // Emitted in order between `started` and `finalized`. Readers tolerate
+ // unknown phases, so adding these is backward-compatible.
+ closeComplete: "close_complete",
+ reconcileComplete: "reconcile_complete",
+ synthesizeComplete: "synthesize_complete",
+ healComplete: "heal_complete",
} as const);
export type WorkrunPhase = (typeof WORKRUN_PHASE)[keyof typeof WORKRUN_PHASE];
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 53a69efe..209ac2ba 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -44,6 +44,18 @@ import {
WORKRUN_PHASE,
type WorkrunHandle,
} from "./dream-workrun.ts";
+import {
+ DREAM_PHASE,
+ type DreamPhase,
+ type DreamPhaseSummary,
+} from "./dream-phases.ts";
+import {
+ resolveContradiction,
+ type ContradictionInput,
+ type ReconcileSignal,
+} from "./reconcile-domains.ts";
+import { extractTemporalConstraints } from "./temporal-extract.ts";
+import { runHealEnrichment } from "./heal-run.ts";
import { collectEvidenceForSlug } from "./evidence.ts";
import {
buildIntentReview,
@@ -85,6 +97,7 @@ import {
type BrainRetiredReason,
type BrainSignal,
type BrainSignalSign,
+ type DreamOpenQuestion,
} from "./types.ts";
// ----- Public types --------------------------------------------------------
@@ -215,6 +228,22 @@ export interface DreamRunSummary {
* when the config field is absent (the default).
*/
readonly gated_retires: ReadonlyArray<DreamGatedRetireEntry>;
+ /**
+ * Multi-phase dream pipeline (Brain lifecycle suite, Feature 2).
+ * Ordered per-phase summaries (close, reconcile, synthesize, heal,
+ * log) for a changed run; empty on a no-op run. Additive: existing
+ * fields are unchanged.
+ */
+ readonly phases: ReadonlyArray<DreamPhaseSummary>;
+ /**
+ * Reconcile-phase domain classification (Brain lifecycle suite,
+ * Feature 3). Contradictions that stayed unresolved, each tagged with
+ * a domain. Source-freshness contradictions that auto-resolved are
+ * NOT listed here (they are recorded as `reconcile` log events on a
+ * changed run). The legacy `contradictions` field remains a derived
+ * topic-only view for back-compat.
+ */
+ readonly open_questions: ReadonlyArray<DreamOpenQuestion>;
/** Snapshot file (absent on a no-op run). */
readonly snapshot_path?: string;
/** Log file the run summary landed in (absent on a no-op run). */
@@ -334,6 +363,14 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// 5. Plan signal moves (inbox/ β†’ processed/).
planSignalMoves(scan, plan);
+ // Reconcile phase (F3): classify each contradiction topic into a
+ // domain. Source-freshness with a clear gap auto-resolves (recorded,
+ // never a sub-threshold mutation); everything else becomes an open
+ // question. Computed in-memory before the `changed` gate so the
+ // summary carries open_questions on both the no-op and changed paths;
+ // the `reconcile` log events below are emitted only on a changed run.
+ const reconcile = buildReconcileOutcomes(scan, plan, cfg, now);
+
// Decide if anything is going to change. We treat any of the
// following as a state change:
// - a new unconfirmed pref
@@ -373,6 +410,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
quarantined: Object.freeze([...plan.quarantined]),
intent_reviews: Object.freeze([...intentReview.reviews]),
gated_retires: Object.freeze([] as ReadonlyArray<DreamGatedRetireEntry>),
+ phases: Object.freeze([] as ReadonlyArray<DreamPhaseSummary>),
+ open_questions: Object.freeze([...reconcile.openQuestions]),
...(dryRun ? { dry_run: true } : {}),
} satisfies DreamRunSummary);
}
@@ -400,6 +439,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// 5. Emit log entries (noted-redundant, retain-pinned,
// skip-corrupted-frontmatter, dream summary).
const moved: string[] = [];
+ // F6: count of user pages the opt-in heal phase enriched (0 unless
+ // dream.heal_enrich_enabled).
+ let healEnriched = 0;
// v0.12.0 Brain Integrity Suite: declined retires accumulate here.
// Always declared (even when no gate is configured) so the eventual
// DreamRunSummary.gated_retires field is consistently an array.
@@ -413,6 +455,12 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
if (!dryRun) {
workrun = openWorkrun(vault, runId);
workrun.checkpoint(WORKRUN_PHASE.clusterComplete);
+ // Multi-phase dream (F2): close + reconcile are complete by the time
+ // we reach the mutation path - the scan and contradiction planning
+ // both ran before the `changed` gate. Emit their checkpoints here in
+ // order; synthesize + heal follow the write loops below.
+ workrun.checkpoint(WORKRUN_PHASE.closeComplete);
+ workrun.checkpoint(WORKRUN_PHASE.reconcileComplete);
}
if (!dryRun) {
@@ -450,6 +498,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
recentViolated: [],
...(np.scope ? { scope: np.scope } : {}),
...(np.supersedes ? { supersedes: np.supersedes } : {}),
+ // F5: bi-temporal validity extracted from the source signal.
+ ...(np.valid_from ? { valid_from: np.valid_from } : {}),
+ ...(np.valid_until ? { valid_until: np.valid_until } : {}),
},
[],
{ overwrite: false },
@@ -555,6 +606,20 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
);
}
}
+
+ // Heal phase (F6): opt-in deterministic vault enrichment, run after
+ // the retire/move mutations (heal-after-mutations). Off by default so
+ // the default install stays byte-identical; a failure is a warning,
+ // never fatal to the dream pass.
+ if (cfg.dream.heal_enrich_enabled === true) {
+ try {
+ healEnriched = runHealEnrichment(vault).enriched;
+ } catch (err) {
+ process.stderr.write(
+ `warning: heal enrichment failed: ${(err as Error).message}\n`,
+ );
+ }
+ }
} else {
// Dry-run still reports the move list so the caller's summary is
// accurate, but it does not touch disk.
@@ -567,7 +632,13 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// mutations so the workrun stays compact yet recovery-meaningful.
if (workrun !== null) {
workrun.checkpoint(WORKRUN_PHASE.promoteComplete);
+ // Multi-phase dream (F2): synthesize = the promote/confirm writes
+ // just completed; heal = the retire (and, when enabled, enrichment)
+ // writes. Emit the phase checkpoints in order alongside the legacy
+ // promote/retire markers (readers tolerate the extra phases).
+ workrun.checkpoint(WORKRUN_PHASE.synthesizeComplete);
workrun.checkpoint(WORKRUN_PHASE.retireComplete);
+ workrun.checkpoint(WORKRUN_PHASE.healComplete);
}
// v0.12.0 Brain Integrity Suite: build the gated-slug set once so the
@@ -611,6 +682,37 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
});
}
+ // Reconcile phase (F3): one event per open question + per
+ // auto-resolution. Persisted only on this changed path so a no-op
+ // run stays byte-identical.
+ for (const q of reconcile.openQuestions) {
+ writeEvent(vault, {
+ timestamp: nextStamp(),
+ eventType: BRAIN_LOG_EVENT_KIND.reconcile,
+ body: {
+ topic: q.topic,
+ domain: q.domain,
+ reason: q.reason,
+ ...(q.scope ? { scope: q.scope } : {}),
+ positives: String(q.positive_count),
+ negatives: String(q.negative_count),
+ },
+ });
+ }
+ for (const r of reconcile.autoResolved) {
+ writeEvent(vault, {
+ timestamp: nextStamp(),
+ eventType: BRAIN_LOG_EVENT_KIND.reconcile,
+ body: {
+ topic: r.topic,
+ domain: r.domain,
+ resolution: "auto-resolved",
+ winner_sign: r.winner_sign,
+ margin_days: String(r.margin_days),
+ },
+ });
+ }
+
for (const suppressed of plan.signalsSuppressed) {
writeEvent(vault, {
timestamp: nextStamp(),
@@ -735,9 +837,41 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// spot. `workrun` is null on dry-run / pre-mutation paths.
workrun?.finalize();
+ // Multi-phase dream (F2): structured per-phase summaries for a changed
+ // run. Metrics are integer counters derived from the plan/refresh that
+ // already ran; additive keys may appear in later versions.
+ const activeSignalCount = scan.signals.filter((s) => s.active).length;
+ const retiredThisRun = plan.retires.filter((r) => !gatedSlugs.has(r.slug)).length;
+ const phases: ReadonlyArray<DreamPhaseSummary> = Object.freeze([
+ phaseSummary(DREAM_PHASE.close, {
+ active_signals: activeSignalCount,
+ preferences: scan.preferences.length,
+ retired_files: scan.retired.length,
+ }),
+ phaseSummary(DREAM_PHASE.reconcile, {
+ contradictions: plan.contradictionTopics.size,
+ open_questions: reconcile.openQuestions.length,
+ auto_resolved: reconcile.autoResolved.length,
+ }),
+ phaseSummary(DREAM_PHASE.synthesize, {
+ new_unconfirmed: plan.newUnconfirmed.length,
+ confirmed: refresh.confirmed.size,
+ }),
+ phaseSummary(DREAM_PHASE.heal, {
+ retired: retiredThisRun,
+ enriched: healEnriched,
+ }),
+ phaseSummary(DREAM_PHASE.log, {
+ moved: moved.length,
+ suppressed: plan.signalsSuppressed.length,
+ }),
+ ]);
+
return Object.freeze({
run_id: runId,
changed: true,
+ phases,
+ open_questions: Object.freeze([...reconcile.openQuestions]),
new_unconfirmed: plan.newUnconfirmed.map((p) => `pref-${p.slug}`),
confirmed: Array.from(refresh.confirmed.values()).map((s) => `pref-${s}`),
retired: plan.retires
@@ -923,6 +1057,14 @@ interface NewUnconfirmedPlan {
* `supersedes:` for audit-trail continuity across rebuttals.
*/
readonly supersedes?: string;
+ /**
+ * Brain lifecycle suite (F5). Bi-temporal validity derived from the
+ * source signal at plan time (explicit signal fields preferred, else
+ * extracted from the signal's ISO temporal text). Threaded to the
+ * preference writer on promotion.
+ */
+ readonly valid_from?: string;
+ readonly valid_until?: string;
}
interface RetirePlan {
@@ -1157,6 +1299,7 @@ function planTopics(
principle,
evidencedBy,
sign,
+ ...deriveSignalTemporal(dominant[0]!.signal, now),
...(supersedesRecord
? {
supersedes: renderPrefLink({
@@ -1310,6 +1453,7 @@ function handleSignalsOnActivePref(
principle,
evidencedBy,
sign: oppositeSign,
+ ...deriveSignalTemporal(opposing[0]!.signal, now),
supersedes: renderPrefLink({
id: active.pref.id,
principle: active.pref.principle,
@@ -1384,6 +1528,118 @@ function filterWithinWindow(
});
}
+/**
+ * Brain lifecycle suite (F5). Derive a preference's bi-temporal validity
+ * from the source signal: prefer the signal's explicit `valid_from` /
+ * `valid_until`, otherwise extract formal ISO temporal tokens from the
+ * signal's principle + raw text. Returns `{}` when neither yields a
+ * constraint, so callers spread it without changing byte output.
+ */
+function deriveSignalTemporal(
+ sig: BrainSignal,
+ now: Date,
+): { valid_from?: string; valid_until?: string } {
+ if (sig.valid_from || sig.valid_until) {
+ return {
+ ...(sig.valid_from ? { valid_from: sig.valid_from } : {}),
+ ...(sig.valid_until ? { valid_until: sig.valid_until } : {}),
+ };
+ }
+ const text = `${sig.principle ?? ""}\n${sig.raw ?? ""}`;
+ return extractTemporalConstraints(text, { now });
+}
+
+/** Build one phase summary (module-scoped: captures nothing). */
+function phaseSummary(
+ phase: DreamPhase,
+ metrics: Record<string, number>,
+): DreamPhaseSummary {
+ return { phase, metrics };
+}
+
+/** Project a scanned signal onto the minimal reconcile view. */
+function toReconcileSignal(r: SignalRecord): ReconcileSignal {
+ return {
+ created_at: r.signal.created_at,
+ ...(r.signal.recorded_at ? { recorded_at: r.signal.recorded_at } : {}),
+ ...(r.signal.source ? { source: r.signal.source } : {}),
+ };
+}
+
+// ----- Reconcile (F3) ------------------------------------------------------
+
+interface ReconcileAutoResolved {
+ readonly topic: string;
+ readonly domain: "source-freshness";
+ readonly winner_sign: "positive" | "negative";
+ readonly margin_days: number;
+}
+
+interface ReconcileOutcomes {
+ readonly openQuestions: DreamOpenQuestion[];
+ readonly autoResolved: ReconcileAutoResolved[];
+}
+
+/**
+ * Classify every contradiction topic the plan flagged into a domain and
+ * decide its outcome. Source-freshness contradictions where the fresher
+ * side leads by at least half the contradiction window auto-resolve
+ * (recorded only - never a sub-threshold mutation); the rest become
+ * operator-facing open questions. Pure; emits nothing.
+ */
+function buildReconcileOutcomes(
+ scan: ScanResult,
+ plan: PlanState,
+ cfg: BrainConfig,
+ now: Date,
+): ReconcileOutcomes {
+ const openQuestions: DreamOpenQuestion[] = [];
+ const autoResolved: ReconcileAutoResolved[] = [];
+ if (plan.contradictionTopics.size === 0) return { openQuestions, autoResolved };
+
+ const windowDays = cfg.dream.contradiction_window_days;
+ // Freshness must be decisive WITHIN the contradiction window, so the
+ // margin is half the window (a gap larger than the window would have
+ // excluded the older signal from the contradiction in the first place).
+ const freshnessMarginDays = Math.max(1, Math.ceil(windowDays / 2));
+
+ const byTopic = new Map<string, SignalRecord[]>();
+ for (const rec of scan.signals) {
+ const arr = byTopic.get(rec.signal.topic);
+ if (arr) arr.push(rec);
+ else byTopic.set(rec.signal.topic, [rec]);
+ }
+
+ for (const topic of plan.contradictionTopics) {
+ const sigs = filterWithinWindow(byTopic.get(topic) ?? [], windowDays, now);
+ const positives = sigs
+ .filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive)
+ .map(toReconcileSignal);
+ const negatives = sigs
+ .filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative)
+ .map(toReconcileSignal);
+ const scope = sigs.find((s) => s.signal.scope)?.signal.scope;
+ const input: ContradictionInput = {
+ topic,
+ ...(scope ? { scope } : {}),
+ positives,
+ negatives,
+ };
+ const outcome = resolveContradiction(input, { now, freshnessMarginDays });
+ if (outcome.kind === "auto-resolved") {
+ autoResolved.push({
+ topic,
+ domain: outcome.domain,
+ winner_sign: outcome.winner_sign,
+ margin_days: outcome.margin_days,
+ });
+ } else {
+ openQuestions.push(outcome.question);
+ }
+ }
+ return { openQuestions, autoResolved };
+}
+
// ----- Refresh + promote --------------------------------------------------
interface RefreshUpdate {
diff --git a/src/core/brain/heal-enrich.ts b/src/core/brain/heal-enrich.ts
new file mode 100644
index 00000000..81773815
--- /dev/null
+++ b/src/core/brain/heal-enrich.ts
@@ -0,0 +1,112 @@
+/**
+ * Heal-phase vault enrichment (Brain lifecycle suite, Feature 6).
+ *
+ * Deterministic, structural enrichment for the dream heal phase. Two
+ * narrow operations, both safe to re-run:
+ *
+ * - {@link deriveTitleFromContent}: a missing `title` is filled from
+ * the page's first H1. No inference beyond reading the heading.
+ * - {@link linkExactMentions}: insert wikilinks for EXACT, whole-token
+ * title/alias matches to known pages. Case-sensitive, longest-match
+ * first, idempotent (existing `[[...]]` and inline `code` spans are
+ * never re-linked). No fuzzy matching, no language heuristics.
+ *
+ * The whole feature is gated off by default in the dream pass
+ * (`dream.heal_enrich_enabled`), because it rewrites user files; these
+ * functions are pure and side-effect free regardless.
+ */
+
+const H1_RE = /^#[ \t]+(.+?)[ \t]*$/m;
+// Existing wikilinks, fenced code blocks, and inline code spans are
+// protected from linking. The fenced-block alternation comes first so a
+// multi-line ``` block is captured whole before the inline-code branch
+// can match a backtick pair inside it.
+const PROTECTED_RE = /(```[\s\S]*?```|\[\[[^\]]*\]\]|`[^`]*`)/g;
+
+/** First H1 heading text, or null when the page has no H1. */
+export function deriveTitleFromContent(markdown: string): string | null {
+ const m = H1_RE.exec(markdown);
+ if (!m) return null;
+ const title = m[1]!.trim();
+ return title.length > 0 ? title : null;
+}
+
+function escapeRegExp(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * Wrap exact whole-token occurrences of any `known` title/alias in a
+ * wikilink. Text inside existing wikilinks or inline code is left
+ * untouched, so the function is idempotent. Returns the input unchanged
+ * when `known` is empty.
+ */
+export function linkExactMentions(
+ body: string,
+ known: ReadonlyArray<string>,
+): string {
+ const phrases = known
+ .map((k) => k.trim())
+ .filter((k) => k.length > 0)
+ // Longest first so a multi-word title wins over a contained shorter
+ // one at the same position; lexicographic tie-break for determinism.
+ .toSorted((a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0));
+ if (phrases.length === 0) return body;
+
+ const alternation = phrases.map(escapeRegExp).join("|");
+ // Whole-token boundaries via Unicode letter/number lookarounds so the
+ // match is language-agnostic (works for any script).
+ const linkRe = new RegExp(`(?<![\\p{L}\\p{N}])(?:${alternation})(?![\\p{L}\\p{N}])`, "gu");
+
+ // Split on protected spans (captured, so they land at odd indices) and
+ // only link in the free text at even indices.
+ const parts = body.split(PROTECTED_RE);
+ for (let i = 0; i < parts.length; i += 2) {
+ parts[i] = parts[i]!.replace(linkRe, (match) => `[[${match}]]`);
+ }
+ return parts.join("");
+}
+
+/** A page view the heal planner reads. */
+export interface HealPageInput {
+ readonly frontmatter: Record<string, unknown>;
+ readonly body: string;
+}
+
+/** Pure, additive enrichment plan. `changed` is true iff anything applies. */
+export interface HealPlan {
+ readonly changed: boolean;
+ /** Title to add when the page has none and an H1 exists. */
+ readonly title?: string;
+ /** Rewritten body when new wikilinks were inserted. */
+ readonly body?: string;
+}
+
+/**
+ * Compute a pure enrichment plan for one page. Fills a missing title
+ * from the first H1 and links exact mentions of `knownTitlesAndAliases`.
+ * Never overwrites an existing title; returns `changed: false` when
+ * there is nothing to do.
+ */
+export function planHealEnrichment(
+ page: HealPageInput,
+ knownTitlesAndAliases: ReadonlyArray<string>,
+): HealPlan {
+ const existingTitle = page.frontmatter["title"];
+ const hasTitle = typeof existingTitle === "string" && existingTitle.trim().length > 0;
+
+ let title: string | undefined;
+ if (!hasTitle) {
+ const derived = deriveTitleFromContent(page.body);
+ if (derived !== null) title = derived;
+ }
+
+ const linked = linkExactMentions(page.body, knownTitlesAndAliases);
+ const body = linked !== page.body ? linked : undefined;
+
+ return {
+ changed: title !== undefined || body !== undefined,
+ ...(title !== undefined ? { title } : {}),
+ ...(body !== undefined ? { body } : {}),
+ };
+}
diff --git a/src/core/brain/heal-run.ts b/src/core/brain/heal-run.ts
new file mode 100644
index 00000000..4cf897df
--- /dev/null
+++ b/src/core/brain/heal-run.ts
@@ -0,0 +1,107 @@
+/**
+ * Heal-phase enrichment runner (Brain lifecycle suite, Feature 6).
+ *
+ * Drives the pure {@link planHealEnrichment} primitive over the user's
+ * vault pages during the dream heal phase. Opt-in only: the dream pass
+ * calls this exclusively when `dream.heal_enrich_enabled` is true.
+ *
+ * Safety:
+ * - The Brain root (`Brain/`) is excluded - preference / signal /
+ * retired frontmatter is owned by the transactional writer and must
+ * never be rewritten here.
+ * - A page is never linked to its own title (no self-links).
+ * - Only changed pages are rewritten, via the same atomic writer the
+ * rest of the Brain layer uses.
+ *
+ * Deterministic: the known-title index is derived from the vault's own
+ * page titles + aliases; no clock, no network, no language heuristics.
+ */
+
+import {
+ EXCLUDED_DIRS,
+ listVaultPages,
+ parseFrontmatter,
+ writeFrontmatterAtomic,
+} from "../vault.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
+import { planHealEnrichment } from "./heal-enrich.ts";
+
+export interface HealRunResult {
+ /** Pages scanned (outside the Brain root). */
+ readonly scanned: number;
+ /** Pages actually rewritten. */
+ readonly enriched: number;
+ /** Vault-relative-ish paths of the rewritten pages, sorted. */
+ readonly pages: ReadonlyArray<string>;
+}
+
+/**
+ * Run deterministic enrichment over the vault's user pages. Returns the
+ * scan/enrich counts. Writes only changed pages.
+ */
+export function runHealEnrichment(vault: string): HealRunResult {
+ // BRAIN_ROOT_REL is the Brain dir name relative to the vault (its
+ // first path segment is the dir to skip). The skipDirs option REPLACES
+ // the default exclusions, so the Brain root is added to the standard
+ // set (.git / .obsidian / .trash / .stversions) rather than replacing
+ // it - heal must never rewrite Syncthing version history, Obsidian
+ // config, or the trash.
+ const brainDir = BRAIN_ROOT_REL.split("/")[0] ?? "Brain";
+ const pages = listVaultPages(vault, { skipDirs: [...EXCLUDED_DIRS, brainDir] });
+
+ // Build the known title/alias index from every page once, plus a
+ // per-page exclusion map so a page is never linked to its own title
+ // OR its own aliases.
+ const known = new Set<string>();
+ const ownTokens = new Map<string, Set<string>>();
+ for (const p of pages) {
+ const own = new Set<string>();
+ if (p.title.trim().length > 0) {
+ known.add(p.title);
+ own.add(p.title);
+ }
+ const aliases = p.metadata["aliases"];
+ if (Array.isArray(aliases)) {
+ for (const a of aliases) {
+ if (typeof a === "string" && a.trim()) {
+ known.add(a);
+ own.add(a);
+ }
+ }
+ }
+ ownTokens.set(p.path, own);
+ }
+
+ const changed: string[] = [];
+ for (const p of pages) {
+ let meta;
+ let body;
+ try {
+ [meta, body] = parseFrontmatter(p.path);
+ } catch {
+ // A page we cannot parse is skipped, not aborted - heal is hygiene.
+ continue;
+ }
+ // Never link a page to its own title or aliases.
+ const own = ownTokens.get(p.path) ?? new Set<string>();
+ const others = [...known].filter((k) => !own.has(k));
+ const plan = planHealEnrichment({ frontmatter: meta, body }, others);
+ if (!plan.changed) continue;
+
+ const newMeta = plan.title !== undefined ? { ...meta, title: plan.title } : meta;
+ const newBody = plan.body ?? body;
+ try {
+ writeFrontmatterAtomic(p.path, newMeta, newBody, {
+ overwrite: true,
+ vaultForRelativePath: vault,
+ });
+ changed.push(p.path);
+ } catch {
+ // Best-effort: a write failure on one page must not fail the run.
+ continue;
+ }
+ }
+
+ changed.sort();
+ return { scanned: pages.length, enriched: changed.length, pages: changed };
+}
diff --git a/src/core/brain/merge.ts b/src/core/brain/merge.ts
index 2ec686ba..da17ea8b 100644
--- a/src/core/brain/merge.ts
+++ b/src/core/brain/merge.ts
@@ -26,11 +26,13 @@ import { existsSync } from "node:fs";
import { join } from "node:path";
import { regenerateActiveQuiet } from "./active.ts";
+import { computeContentHash } from "./content-hash.ts";
import { appendLogEvent } from "./log.ts";
import { brainDirs, preferencePath } from "./paths.ts";
+import { appendPrefAudit } from "./pref-audit.ts";
import { moveToRetired, parsePreference, writePreference } from "./preference.ts";
import { isoDate, isoSecond } from "./time.ts";
-import { BRAIN_LOG_EVENT_KIND, BRAIN_RETIRED_REASON } from "./types.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_RETIRED_REASON, PREF_AUDIT_OP } from "./types.ts";
import { renderPrefLink } from "./wikilink.ts";
export type BrainMergeErrorCode =
@@ -214,8 +216,32 @@ export function mergePreferences(
now,
retired_by: `[[Brain/log/${isoDate(now)}]]`,
superseded_by: supersededBy,
+ audit: { agent: opts.agentName ?? "merge" },
});
+ // Per-preference mutation audit (Brain lifecycle suite F1). The keep
+ // pref absorbed evidence + counters; record a `merge` op on its trail.
+ // A merge is a lifecycle event, so it records even though keep's
+ // principle/scope fingerprint is unchanged. The drop's retire(merged-
+ // into) record is written by moveToRetired above.
+ {
+ const keepHash = computeContentHash(keep.principle, keep.scope);
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: keep.id,
+ op: PREF_AUDIT_OP.merge,
+ agent: opts.agentName ?? "merge",
+ reason: `merged-in ${drop.id}`,
+ revision_before: keep.revision ?? null,
+ revision_after: keep.revision ?? null,
+ hash_before: keepHash,
+ hash_after: keepHash,
+ },
+ { now },
+ );
+ }
+
// 3. Append a `merge` log event with audit-grade payload.
appendLogEvent(vault, {
timestamp: isoSecond(now),
diff --git a/src/core/brain/morning-brief.ts b/src/core/brain/morning-brief.ts
new file mode 100644
index 00000000..8107a329
--- /dev/null
+++ b/src/core/brain/morning-brief.ts
@@ -0,0 +1,200 @@
+/**
+ * Morning brief / day-close summary (Brain lifecycle suite, Feature 4).
+ *
+ * A read-only, budgeted session-start bundle composed from three
+ * existing sources: the highest-confidence confirmed preferences, the
+ * open questions the recent reconcile phase raised, and recent narrative
+ * notes. It complements the on-demand `brain_digest` by giving a host
+ * runtime one compact thing to surface at session start.
+ *
+ * Deterministic given the vault + injected clock: preference ordering is
+ * confidence -> recency -> id; the log lookback iterates a fixed day
+ * range; nothing calls the wall clock. Bounded by the shared
+ * recall-budget primitive so one oversized entry cannot dominate.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "./paths.ts";
+import { parsePreference } from "./preference.ts";
+import { applyCharBudget } from "./recall-budget.ts";
+import { readLogDay } from "./log-jsonl.ts";
+import { isoDate } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "./types.ts";
+
+export interface MorningBriefPreference {
+ readonly id: string;
+ readonly principle: string;
+ readonly trimmed: boolean;
+}
+
+export interface MorningBriefOpenQuestion {
+ readonly topic: string;
+ readonly domain: string;
+}
+
+export interface MorningBrief {
+ /** Rendered Markdown summary (empty string when nothing fits). */
+ readonly text: string;
+ readonly preferences: ReadonlyArray<MorningBriefPreference>;
+ readonly openQuestions: ReadonlyArray<MorningBriefOpenQuestion>;
+ readonly recentNotes: ReadonlyArray<string>;
+ readonly totalChars: number;
+}
+
+export interface MorningBriefOptions {
+ readonly now: Date;
+ /** Max confirmed preferences to consider (highest-confidence first). */
+ readonly topK: number;
+ /** Days of log history to scan for open questions + notes. Default 7. */
+ readonly lookbackDays?: number;
+ /** Per-entry character cap (code points); <= 0 / undefined disables. */
+ readonly maxCharsPerMemory?: number;
+ /** Total character cap across the brief; <= 0 / undefined disables. */
+ readonly maxTotalChars?: number;
+}
+
+interface ConfirmedPref {
+ readonly id: string;
+ readonly principle: string;
+ readonly confidence: number;
+ readonly createdAt: string;
+}
+
+function collectConfirmed(vault: string): ConfirmedPref[] {
+ const dir = brainDirs(vault).preferences;
+ if (!existsSync(dir)) return [];
+ const out: ConfirmedPref[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md")) continue;
+ let pref;
+ try {
+ pref = parsePreference(join(dir, name));
+ } catch {
+ continue;
+ }
+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;
+ out.push({
+ id: pref.id,
+ principle: pref.principle,
+ confidence: pref.confidence_value ?? Number.NEGATIVE_INFINITY,
+ createdAt: pref.created_at,
+ });
+ }
+ return out;
+}
+
+interface LogScan {
+ readonly openQuestions: MorningBriefOpenQuestion[];
+ readonly notes: string[];
+}
+
+function scanRecentLog(vault: string, now: Date, lookbackDays: number): LogScan {
+ const openQuestions: MorningBriefOpenQuestion[] = [];
+ const notes: string[] = [];
+ const seenTopics = new Set<string>();
+ const dayMs = 24 * 60 * 60 * 1000;
+ // Newest day first so dedup keeps the most recent open question per topic.
+ for (let i = 0; i <= lookbackDays; i++) {
+ const date = isoDate(new Date(now.getTime() - i * dayMs));
+ const entries = readLogDay(vault, date).entries;
+ for (const e of entries) {
+ if (e.eventType === BRAIN_LOG_EVENT_KIND.reconcile) {
+ // Auto-resolutions carry a `resolution` field; only open
+ // questions (no resolution) are surfaced to the operator.
+ if (typeof e.body["resolution"] === "string") continue;
+ const topic = typeof e.body["topic"] === "string" ? e.body["topic"] : "";
+ const domain = typeof e.body["domain"] === "string" ? e.body["domain"] : "";
+ if (topic && !seenTopics.has(topic)) {
+ seenTopics.add(topic);
+ openQuestions.push({ topic, domain });
+ }
+ } else if (e.eventType === BRAIN_LOG_EVENT_KIND.note) {
+ const text = typeof e.body["text"] === "string" ? e.body["text"] : "";
+ if (text) notes.push(text);
+ }
+ }
+ }
+ return { openQuestions, notes };
+}
+
+const PREF_PREFIX = "pref:";
+const OQ_PREFIX = "oq:";
+const NOTE_PREFIX = "note:";
+
+/**
+ * Build the morning brief for a vault. Read-only; deterministic given
+ * the vault and `opts.now`.
+ */
+export function buildMorningBrief(vault: string, opts: MorningBriefOptions): MorningBrief {
+ const lookbackDays = opts.lookbackDays ?? 7;
+
+ const ranked = collectConfirmed(vault).toSorted((a, b) => {
+ if (b.confidence !== a.confidence) return b.confidence - a.confidence;
+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+ });
+ const topPrefs = ranked.slice(0, Math.max(0, opts.topK));
+
+ const { openQuestions, notes } = scanRecentLog(vault, opts.now, lookbackDays);
+
+ // Budget all variable-length entries together so one oversized entry
+ // cannot crowd out the rest. Items are tagged by kind so the result
+ // can be partitioned back.
+ const entries: Array<{ item: string; text: string }> = [];
+ for (const p of topPrefs) entries.push({ item: `${PREF_PREFIX}${p.id}`, text: p.principle });
+ for (const q of openQuestions) {
+ entries.push({ item: `${OQ_PREFIX}${q.topic}`, text: `${q.topic} (${q.domain})` });
+ }
+ for (let i = 0; i < notes.length; i++) {
+ entries.push({ item: `${NOTE_PREFIX}${i}`, text: notes[i]! });
+ }
+
+ const budgeted = applyCharBudget(entries, {
+ maxCharsPerEntry: opts.maxCharsPerMemory,
+ maxTotalChars: opts.maxTotalChars,
+ });
+
+ const preferences: MorningBriefPreference[] = [];
+ const keptQuestions: MorningBriefOpenQuestion[] = [];
+ const keptNotes: string[] = [];
+ for (const kept of budgeted.kept) {
+ if (kept.item.startsWith(PREF_PREFIX)) {
+ preferences.push({
+ id: kept.item.slice(PREF_PREFIX.length),
+ principle: kept.text,
+ trimmed: kept.trimmed,
+ });
+ } else if (kept.item.startsWith(OQ_PREFIX)) {
+ const topic = kept.item.slice(OQ_PREFIX.length);
+ const found = openQuestions.find((q) => q.topic === topic);
+ keptQuestions.push({ topic, domain: found?.domain ?? "" });
+ } else if (kept.item.startsWith(NOTE_PREFIX)) {
+ keptNotes.push(kept.text);
+ }
+ }
+
+ const sections: string[] = [];
+ if (preferences.length > 0) {
+ sections.push(
+ ["## Top preferences", ...preferences.map((p) => `- ${p.principle}`)].join("\n"),
+ );
+ }
+ if (keptQuestions.length > 0) {
+ sections.push(
+ ["## Open questions", ...keptQuestions.map((q) => `- ${q.topic} (${q.domain})`)].join("\n"),
+ );
+ }
+ if (keptNotes.length > 0) {
+ sections.push(["## Recent notes", ...keptNotes.map((n) => `- ${n}`)].join("\n"));
+ }
+
+ return Object.freeze({
+ text: sections.join("\n\n"),
+ preferences: Object.freeze(preferences),
+ openQuestions: Object.freeze(keptQuestions),
+ recentNotes: Object.freeze(keptNotes),
+ totalChars: budgeted.totalChars,
+ });
+}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 10281bcf..863c7d49 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -202,6 +202,26 @@ export function dreamWorkrunPath(vault: string, runId: string): string {
return ensureInsideVault(join(dreamRunsDir(vault), `${id}.jsonl`), vault);
}
+/**
+ * Brain lifecycle suite (Feature 1). Per-preference mutation audit
+ * directory: `Brain/log/pref-audit/`. Lives under the log dir so
+ * backups already include it.
+ */
+export function prefAuditDir(vault: string): string {
+ return join(brainDirs(vault).log, "pref-audit");
+}
+
+/**
+ * Brain lifecycle suite (Feature 1). Append-only audit JSONL for a
+ * single preference: `Brain/log/pref-audit/<pref-id>.jsonl`. The pref
+ * id (`pref-<slug>` / `ret-<slug>`) is validated through
+ * {@link validateSlug} so it cannot escape the canonical directory.
+ */
+export function prefAuditPath(vault: string, prefId: string): string {
+ const id = validateSlug(prefId);
+ return ensureInsideVault(join(prefAuditDir(vault), `${id}.jsonl`), vault);
+}
+
/** Snapshots directory: `Brain/.snapshots/`. */
export function snapshotsDir(vault: string): string {
return brainDirs(vault).snapshots;
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index ff091c47..30440fcf 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -303,6 +303,7 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
candidate_threshold: 3,
unconfirmed_window_days: 14,
contradiction_window_days: 14,
+ heal_enrich_enabled: false,
}),
retire: Object.freeze({
stale_evidence_days: 90,
@@ -1276,6 +1277,10 @@ export function validateBrainConfigDetailed(
candidate_threshold: dream.candidate_threshold as number,
unconfirmed_window_days: dream.unconfirmed_window_days as number,
contradiction_window_days: dream.contradiction_window_days as number,
+ // Brain lifecycle suite F6: opt-in heal-phase enrichment. Absent
+ // or non-boolean coerces to false so the default install stays
+ // byte-identical (the heal phase becomes a checkpoint-only no-op).
+ heal_enrich_enabled: dream.heal_enrich_enabled === true,
},
retire: {
stale_evidence_days: retire.stale_evidence_days as number,
diff --git a/src/core/brain/pref-audit.ts b/src/core/brain/pref-audit.ts
new file mode 100644
index 00000000..e708b93a
--- /dev/null
+++ b/src/core/brain/pref-audit.ts
@@ -0,0 +1,240 @@
+/**
+ * Per-preference mutation audit log (Brain lifecycle suite, Feature 1).
+ *
+ * Every mutation to a preference is captured at the mutation chokepoint
+ * (`writePreferenceTxn`, `moveToRetired`, `mergePreferences`) as one
+ * append-only JSONL line under `Brain/log/pref-audit/<pref-id>.jsonl`.
+ * Because the trail is written where the content hash is computed, it is
+ * authoritative (true before/after) and also catches manual edits routed
+ * through the same primitives.
+ *
+ * No-op contract: for an `update` op, {@link appendPrefAudit} writes
+ * nothing and returns `false` when `hash_before === hash_after` (both
+ * present and equal), i.e. the write did not change the preference
+ * content - so counter-only refresh churn leaves no audit line and the
+ * byte-identical default-install contract holds. Lifecycle ops
+ * (`create` / `promote` / `retire` / `merge`) always record: they are
+ * meaningful transitions even when the principle/scope fingerprint is
+ * unchanged (e.g. a merge that only absorbs evidence).
+ *
+ * Append uses `appendFileSync` (the same `O_APPEND` atomicity assumption
+ * as `dream-workrun.ts`); each line is small. The reader tolerates
+ * malformed lines (surfaced as warnings) and unknown future op kinds
+ * (kept as the raw string), matching the log-reader tolerance contract.
+ */
+
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname } from "node:path";
+
+import { prefAuditPath } from "./paths.ts";
+import { isoSecond } from "./time.ts";
+import { PREF_AUDIT_OP, type PrefAuditOp, type PrefAuditRecord } from "./types.ts";
+
+/**
+ * Opt-in audit sink threaded through a mutation chokepoint. When
+ * supplied, the chokepoint appends one audit record (subject to the
+ * per-op no-op rule). Omitting it preserves pre-suite behaviour - no
+ * audit file is created.
+ */
+export interface PrefAuditSink {
+ /** Agent identity recorded on the audit line. */
+ readonly agent: string;
+ /** Optional machine-readable reason code. */
+ readonly reason?: string;
+ /** Clock for the audit timestamp; defaults to `new Date()`. */
+ readonly now?: () => Date;
+}
+
+/** Input for {@link appendPrefAudit}. `reason` is optional. */
+export interface AppendPrefAuditInput {
+ readonly pref_id: string;
+ readonly op: PrefAuditOp;
+ readonly agent: string;
+ readonly reason?: string;
+ readonly revision_before: number | null;
+ readonly revision_after: number | null;
+ readonly hash_before: string | null;
+ readonly hash_after: string | null;
+}
+
+/** One warning raised while reading an audit JSONL file. */
+export interface PrefAuditParseWarning {
+ readonly path: string;
+ readonly lineNumber: number;
+ readonly message: string;
+}
+
+export interface ReadPrefAuditResult {
+ readonly records: ReadonlyArray<PrefAuditRecord>;
+ readonly warnings: ReadonlyArray<PrefAuditParseWarning>;
+}
+
+/**
+ * Render one audit record as a canonical JSON line (trailing newline).
+ * Field order is fixed so the on-disk line stays stable across writes -
+ * important for the Syncthing byte-identical contract.
+ */
+export function renderPrefAuditLine(rec: PrefAuditRecord): string {
+ const ordered: Record<string, unknown> = {
+ ts: rec.ts,
+ pref_id: rec.pref_id,
+ op: rec.op,
+ agent: rec.agent,
+ ...(rec.reason !== undefined ? { reason: rec.reason } : {}),
+ revision_before: rec.revision_before,
+ revision_after: rec.revision_after,
+ hash_before: rec.hash_before,
+ hash_after: rec.hash_after,
+ };
+ return JSON.stringify(ordered) + "\n";
+}
+
+/**
+ * Append one audit line for `input`. Returns `true` when a line was
+ * written, `false` on the no-op path (unchanged content hash). The
+ * audit directory is created on demand.
+ */
+export function appendPrefAudit(
+ vault: string,
+ input: AppendPrefAuditInput,
+ opts: { now?: Date } = {},
+): boolean {
+ // No-op when an `update` did not change the preference content. Both
+ // hashes present and equal => counter-only churn, nothing meaningful
+ // to record. Lifecycle ops always record (see module docstring).
+ if (
+ input.op === PREF_AUDIT_OP.update &&
+ input.hash_before !== null &&
+ input.hash_after !== null &&
+ input.hash_before === input.hash_after
+ ) {
+ return false;
+ }
+
+ const now = opts.now ?? new Date();
+ const record: PrefAuditRecord = {
+ ts: isoSecond(now),
+ pref_id: input.pref_id,
+ op: input.op,
+ agent: input.agent,
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
+ revision_before: input.revision_before,
+ revision_after: input.revision_after,
+ hash_before: input.hash_before,
+ hash_after: input.hash_after,
+ };
+
+ const path = prefAuditPath(vault, input.pref_id);
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(path, renderPrefAuditLine(record), "utf8");
+ return true;
+}
+
+/**
+ * Read the full mutation history for one preference id, oldest first.
+ * Returns empty records (no warnings) when the file does not exist.
+ * Malformed lines and rows missing required fields become warnings;
+ * unknown op kinds are preserved verbatim.
+ */
+export function readPrefAudit(vault: string, prefId: string): ReadPrefAuditResult {
+ const path = prefAuditPath(vault, prefId);
+ if (!existsSync(path)) return { records: [], warnings: [] };
+
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (err) {
+ const message = (err as NodeJS.ErrnoException).message ?? String(err);
+ return {
+ records: [],
+ warnings: [{ path, lineNumber: 0, message: `failed to read audit file: ${message}` }],
+ };
+ }
+
+ const records: PrefAuditRecord[] = [];
+ const warnings: PrefAuditParseWarning[] = [];
+ 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: ${line.slice(0, 80)}`,
+ });
+ continue;
+ }
+ const rec = coerceRecord(parsed, path, i + 1, warnings);
+ if (rec !== null) records.push(rec);
+ }
+ return { records, warnings };
+}
+
+/**
+ * Render an audit trail as a compact, locale-free text table (oldest
+ * first). One header line plus one line per record. Used by the
+ * `o2b brain audit` CLI verb; the MCP tool returns the structured
+ * records directly.
+ */
+export function renderPrefAudit(prefId: string, records: ReadonlyArray<PrefAuditRecord>): string {
+ if (records.length === 0) {
+ return `${prefId}: no audit records`;
+ }
+ const lines = [`${prefId} - ${records.length} event${records.length === 1 ? "" : "s"}`];
+ for (const r of records) {
+ const rev = `${r.revision_before ?? "-"}->${r.revision_after ?? "-"}`;
+ const reason = r.reason ? ` (${r.reason})` : "";
+ lines.push(`${r.ts} ${r.op.padEnd(8)} ${r.agent.padEnd(12)} rev ${rev}${reason}`);
+ }
+ return lines.join("\n");
+}
+
+function coerceRecord(
+ raw: unknown,
+ path: string,
+ lineNumber: number,
+ warnings: PrefAuditParseWarning[],
+): PrefAuditRecord | null {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ warnings.push({ path, lineNumber, message: "audit row is not an object" });
+ return null;
+ }
+ const obj = raw as Record<string, unknown>;
+ const ts = obj["ts"];
+ const prefId = obj["pref_id"];
+ const op = obj["op"];
+ const agent = obj["agent"];
+ if (
+ typeof ts !== "string" ||
+ typeof prefId !== "string" ||
+ typeof op !== "string" ||
+ typeof agent !== "string"
+ ) {
+ warnings.push({ path, lineNumber, message: "audit row missing ts/pref_id/op/agent" });
+ return null;
+ }
+ const reason = obj["reason"];
+ return {
+ ts,
+ pref_id: prefId,
+ op,
+ agent,
+ ...(typeof reason === "string" ? { reason } : {}),
+ revision_before: coerceNullableNumber(obj["revision_before"]),
+ revision_after: coerceNullableNumber(obj["revision_after"]),
+ hash_before: coerceNullableString(obj["hash_before"]),
+ hash_after: coerceNullableString(obj["hash_after"]),
+ };
+}
+
+function coerceNullableNumber(v: unknown): number | null {
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
+}
+
+function coerceNullableString(v: unknown): string | null {
+ return typeof v === "string" ? v : null;
+}
diff --git a/src/core/brain/preference-txn.ts b/src/core/brain/preference-txn.ts
index 7ec5cfd8..2f2aedc3 100644
--- a/src/core/brain/preference-txn.ts
+++ b/src/core/brain/preference-txn.ts
@@ -31,6 +31,8 @@ import { existsSync } from "node:fs";
import { computeContentHash } from "./content-hash.ts";
import { appendEditHistory, type EditHistoryEntry } from "./health/edit-history.ts";
+import { appendPrefAudit, type PrefAuditSink } from "./pref-audit.ts";
+import { PREF_AUDIT_OP } from "./types.ts";
import { preferencePath, validateSlug } from "./paths.ts";
import {
parsePreference,
@@ -170,6 +172,7 @@ export function writePreferenceTxn(
expectations: ReadonlyArray<WritePreferenceExpectation>,
options: WritePreferenceOptions = {},
history?: EditHistoryOptions,
+ audit?: PrefAuditSink,
): WritePreferenceResult {
const slug = validateSlug(input.slug);
const path = preferencePath(vault, slug);
@@ -244,6 +247,33 @@ export function writePreferenceTxn(
);
appendEditHistory(vault, slug, entries);
}
+ // Per-preference mutation audit (opt-in, Brain lifecycle suite F1).
+ // Recorded only when the write actually changed bytes; the op is the
+ // lifecycle transition. The audit's own per-op no-op rule then drops
+ // counter-only `update` churn so the byte-identical default holds.
+ if (audit && willChange) {
+ const op =
+ existing === null
+ ? PREF_AUDIT_OP.create
+ : existing.status !== BRAIN_PREFERENCE_STATUS.confirmed &&
+ inputWithDefaults.status === BRAIN_PREFERENCE_STATUS.confirmed
+ ? PREF_AUDIT_OP.promote
+ : PREF_AUDIT_OP.update;
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: `pref-${slug}`,
+ op,
+ agent: audit.agent,
+ ...(audit.reason !== undefined ? { reason: audit.reason } : {}),
+ revision_before: existing?.revision ?? null,
+ revision_after: inputWithDefaults.revision ?? null,
+ hash_before: existing ? computeContentHash(existing.principle, existing.scope) : null,
+ hash_after: computeContentHash(inputWithDefaults.principle, inputWithDefaults.scope),
+ },
+ { now: audit.now?.() ?? new Date() },
+ );
+ }
return result;
} finally {
handle.release();
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index cfbf449d..a5584b08 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -52,6 +52,9 @@ import {
} from "./types.ts";
import type { PageLifecycle } from "./page-meta/lifecycle.ts";
import type { PageTier } from "./page-meta/tier.ts";
+import { computeContentHash } from "./content-hash.ts";
+import { appendPrefAudit } from "./pref-audit.ts";
+import { PREF_AUDIT_OP } from "./types.ts";
// ----- Errors ---------------------------------------------------------------
@@ -131,6 +134,13 @@ export interface WritePreferenceInput {
readonly content_hash?: string;
readonly supersedes?: string;
readonly aliases?: ReadonlyArray<string>;
+ /**
+ * Brain lifecycle suite (F5). Bi-temporal validity window, filled by
+ * the dream promotion path from the source signal's ISO temporal
+ * text. Emitted verbatim when supplied; absent leaves the field off.
+ */
+ readonly valid_from?: string;
+ readonly valid_until?: string;
/** Optional extra tags merged after the canonical set. */
readonly extraTags?: ReadonlyArray<string>;
/** Free-form "How to apply" prose (rendered as a section). */
@@ -178,6 +188,15 @@ export interface MoveToRetiredOptions {
*/
readonly evidenceApplied?: ReadonlyArray<BrainEvidenceSummary>;
readonly evidenceViolated?: ReadonlyArray<BrainEvidenceSummary>;
+ /**
+ * Opt-in per-preference audit (Brain lifecycle suite F1). When
+ * supplied, a `retire` record is appended to the original
+ * preference's audit trail (`pref-<slug>.jsonl`) so the whole
+ * lifecycle stays in one file. The retire reason is taken from the
+ * `reason` argument, not from the sink. Omitting it preserves
+ * pre-suite behaviour (no audit file).
+ */
+ readonly audit?: { readonly agent: string };
}
export interface MoveToRetiredResult {
@@ -351,6 +370,12 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma
if (input.tier !== undefined) {
metadata["tier"] = input.tier;
}
+ // 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
+ // callers stay byte-identical.
+ if (input.valid_from?.trim()) metadata["valid_from"] = input.valid_from.trim();
+ if (input.valid_until?.trim()) metadata["valid_until"] = input.valid_until.trim();
return metadata;
}
@@ -835,6 +860,31 @@ export function moveToRetired(
}
unlinkSync(prefPath);
+ // Per-preference mutation audit (opt-in, Brain lifecycle suite F1).
+ // Keyed by the ORIGINAL `pref-<slug>` id so create -> ... -> retire
+ // all land in one trail. A retire is a lifecycle transition, so it
+ // always records (the audit's no-op rule only suppresses `update`).
+ if (opts.audit) {
+ const principle = requireString(meta, "principle", prefPath);
+ const scope = typeof meta["scope"] === "string" ? (meta["scope"] as string) : undefined;
+ const revRaw = meta["_revision"];
+ const contentHash = computeContentHash(principle, scope);
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: oldId,
+ op: PREF_AUDIT_OP.retire,
+ agent: opts.audit.agent,
+ reason,
+ revision_before: typeof revRaw === "number" ? revRaw : null,
+ revision_after: null,
+ hash_before: contentHash,
+ hash_after: contentHash,
+ },
+ { now: opts.now },
+ );
+ }
+
return { path: newPath, id: newId };
}
diff --git a/src/core/brain/reconcile-domains.ts b/src/core/brain/reconcile-domains.ts
new file mode 100644
index 00000000..a03c8fad
--- /dev/null
+++ b/src/core/brain/reconcile-domains.ts
@@ -0,0 +1,154 @@
+/**
+ * Reconcile-phase domain classification (Brain lifecycle suite,
+ * Feature 3).
+ *
+ * Replaces the dream pass's flat "contradiction topic" list with a
+ * deterministic, STRUCTURAL classifier. A contradiction (positive vs
+ * negative signals on one topic) is bucketed into one of four domains
+ * from signal shape only - never from language. The resolver then
+ * auto-resolves ONLY the `source-freshness` domain, and only when one
+ * side is materially fresher than the other (beyond a margin); every
+ * judgement domain - claims, entity, decisions - and an ambiguous
+ * freshness case become operator-facing open questions rather than a
+ * forced merge.
+ *
+ * This is the deterministic subset of the "parallel-agent truth
+ * reconciliation" idea: no LLM fan-out, no network, injectable clock.
+ */
+
+import {
+ RECONCILE_DOMAIN,
+ type DreamOpenQuestion,
+ type ReconcileDomain,
+} from "./types.ts";
+
+// Re-export so callers can reach the domain enum + type from the
+// reconciler module without also importing types.ts.
+export { RECONCILE_DOMAIN, type ReconcileDomain } from "./types.ts";
+
+/** Minimal signal view the reconciler needs. Decoupled from BrainSignal. */
+export interface ReconcileSignal {
+ /** ISO-8601 transaction/creation time. */
+ readonly created_at: string;
+ /** Optional bi-temporal record time; preferred over created_at when set. */
+ readonly recorded_at?: string;
+ /** Optional context wikilinks; a non-empty list marks an entity contradiction. */
+ readonly source?: ReadonlyArray<string>;
+}
+
+export interface ContradictionInput {
+ readonly topic: string;
+ readonly scope?: string;
+ readonly positives: ReadonlyArray<ReconcileSignal>;
+ readonly negatives: ReadonlyArray<ReconcileSignal>;
+}
+
+export type ReconcileOutcome =
+ | {
+ readonly kind: "auto-resolved";
+ readonly domain: typeof RECONCILE_DOMAIN.sourceFreshness;
+ /** Sign of the side that wins (the materially fresher one). */
+ readonly winner_sign: "positive" | "negative";
+ readonly margin_days: number;
+ }
+ | {
+ readonly kind: "open-question";
+ readonly question: DreamOpenQuestion;
+ };
+
+/** Conventional scope value marking a judgement/decision contradiction. */
+const DECISIONS_SCOPE = "decisions";
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+
+/** Effective recency anchor for a signal: recorded_at if present, else created_at. */
+function signalTimeMs(s: ReconcileSignal): number {
+ const raw = s.recorded_at ?? s.created_at;
+ const t = Date.parse(raw);
+ return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY;
+}
+
+/** Newest effective time across a set of signals, or -Infinity if empty. */
+function newestMs(signals: ReadonlyArray<ReconcileSignal>): number {
+ let max = Number.NEGATIVE_INFINITY;
+ for (const s of signals) {
+ const t = signalTimeMs(s);
+ if (t > max) max = t;
+ }
+ return max;
+}
+
+function hasEntityReference(signals: ReadonlyArray<ReconcileSignal>): boolean {
+ return signals.some((s) => (s.source?.length ?? 0) > 0);
+}
+
+/**
+ * Classify a contradiction into a domain from structural signal shape.
+ * Priority: decisions (scope marker) > entity (wikilink sources) >
+ * source-freshness (a recency separation) > claims (default).
+ */
+export function classifyContradiction(input: ContradictionInput): ReconcileDomain {
+ if (input.scope === DECISIONS_SCOPE) return RECONCILE_DOMAIN.decisions;
+ if (
+ hasEntityReference(input.positives) ||
+ hasEntityReference(input.negatives)
+ ) {
+ return RECONCILE_DOMAIN.entity;
+ }
+ const posNewest = newestMs(input.positives);
+ const negNewest = newestMs(input.negatives);
+ if (
+ Number.isFinite(posNewest) &&
+ Number.isFinite(negNewest) &&
+ posNewest !== negNewest
+ ) {
+ return RECONCILE_DOMAIN.sourceFreshness;
+ }
+ return RECONCILE_DOMAIN.claims;
+}
+
+/**
+ * Resolve a contradiction. Auto-resolves only the source-freshness
+ * domain when the fresher side leads by at least `freshnessMarginDays`;
+ * otherwise returns an open question carrying the classified domain.
+ */
+export function resolveContradiction(
+ input: ContradictionInput,
+ opts: { now: Date; freshnessMarginDays: number },
+): ReconcileOutcome {
+ const domain = classifyContradiction(input);
+
+ if (domain === RECONCILE_DOMAIN.sourceFreshness) {
+ const posNewest = newestMs(input.positives);
+ const negNewest = newestMs(input.negatives);
+ const gapDays = Math.abs(posNewest - negNewest) / MS_PER_DAY;
+ if (gapDays >= opts.freshnessMarginDays) {
+ return {
+ kind: "auto-resolved",
+ domain: RECONCILE_DOMAIN.sourceFreshness,
+ winner_sign: negNewest > posNewest ? "negative" : "positive",
+ margin_days: Math.floor(gapDays),
+ };
+ }
+ return openQuestion(input, domain, "freshness-gap-below-margin");
+ }
+
+ return openQuestion(input, domain, `${domain}-needs-operator`);
+}
+
+function openQuestion(
+ input: ContradictionInput,
+ domain: ReconcileDomain,
+ reason: string,
+): ReconcileOutcome {
+ return {
+ kind: "open-question",
+ question: {
+ topic: input.topic,
+ ...(input.scope ? { scope: input.scope } : {}),
+ domain,
+ positive_count: input.positives.length,
+ negative_count: input.negatives.length,
+ reason,
+ },
+ };
+}
diff --git a/src/core/brain/temporal-extract.ts b/src/core/brain/temporal-extract.ts
new file mode 100644
index 00000000..889e6421
--- /dev/null
+++ b/src/core/brain/temporal-extract.ts
@@ -0,0 +1,112 @@
+/**
+ * Temporal extraction from signal text (Brain lifecycle suite,
+ * Feature 5).
+ *
+ * A pure, deterministic, LANGUAGE-AGNOSTIC parser. It recognises only
+ * formal ISO-8601 tokens, never localized month/day names or
+ * natural-language phrases in any specific language - so a vault in any
+ * language behaves identically and we never bake a per-language word
+ * list into the engine. The extracted constraints map onto the existing
+ * bi-temporal `valid_from` / `valid_until` preference fields.
+ *
+ * Recognised forms, in precedence order (first match wins):
+ *
+ * 1. ISO interval `YYYY-MM-DD/YYYY-MM-DD`
+ * -> { valid_from: <A>T00:00:00Z, valid_until: <B>T00:00:00Z }
+ * 2. ISO-8601 duration `P[n]Y[n]M[n]W[n]D`, anchored to a co-occurring
+ * lone ISO date when present, else to `now`
+ * -> { valid_from: <anchor>, valid_until: <anchor> + duration }
+ * 3. Lone ISO date `YYYY-MM-DD`
+ * -> { valid_from: <date>T00:00:00Z }
+ *
+ * No ISO token -> `{}`. The function never throws.
+ */
+
+import { isoSecond } from "./time.ts";
+
+export interface TemporalConstraints {
+ readonly valid_from?: string;
+ readonly valid_until?: string;
+}
+
+const ISO_DATE = String.raw`\d{4}-\d{2}-\d{2}`;
+const INTERVAL_RE = new RegExp(`\\b(${ISO_DATE})/(${ISO_DATE})\\b`);
+const LONE_DATE_RE = new RegExp(`\\b(${ISO_DATE})\\b`);
+// ISO-8601 duration, date components only (time part intentionally
+// unsupported - signals express coarse validity windows, not seconds).
+// At least one component is required; the all-empty `P` is rejected by
+// the post-match guard.
+const DURATION_RE = /\bP(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?\b/;
+
+/**
+ * Extract bi-temporal constraints from `text` against the injected
+ * clock. Returns `{}` when no ISO token is present.
+ */
+export function extractTemporalConstraints(
+ text: string,
+ opts: { now: Date },
+): TemporalConstraints {
+ if (typeof text !== "string" || text.length === 0) return {};
+
+ const interval = INTERVAL_RE.exec(text);
+ if (interval) {
+ return {
+ valid_from: `${interval[1]}T00:00:00Z`,
+ valid_until: `${interval[2]}T00:00:00Z`,
+ };
+ }
+
+ const lone = LONE_DATE_RE.exec(text);
+ const duration = parseDuration(text);
+ if (duration) {
+ // Anchor the window to a co-occurring explicit start date when
+ // present (so "from 2026-06-01 for P1Y" keeps June 1 as the start),
+ // otherwise to `now`.
+ if (lone) {
+ const startIso = `${lone[1]}T00:00:00Z`;
+ return {
+ valid_from: startIso,
+ valid_until: isoSecond(addDuration(new Date(startIso), duration)),
+ };
+ }
+ return {
+ valid_from: isoSecond(opts.now),
+ valid_until: isoSecond(addDuration(opts.now, duration)),
+ };
+ }
+
+ if (lone) {
+ return { valid_from: `${lone[1]}T00:00:00Z` };
+ }
+
+ return {};
+}
+
+interface DurationParts {
+ readonly years: number;
+ readonly months: number;
+ readonly weeks: number;
+ readonly days: number;
+}
+
+/** Parse an ISO-8601 date-component duration, or null when none/bare `P`. */
+function parseDuration(text: string): DurationParts | null {
+ const m = DURATION_RE.exec(text);
+ if (!m) return null;
+ const years = m[1] ? Number(m[1]) : 0;
+ const months = m[2] ? Number(m[2]) : 0;
+ const weeks = m[3] ? Number(m[3]) : 0;
+ const days = m[4] ? Number(m[4]) : 0;
+ if (years === 0 && months === 0 && weeks === 0 && days === 0) return null;
+ return { years, months, weeks, days };
+}
+
+/** Add a duration to an anchor instant via UTC calendar arithmetic. */
+function addDuration(anchor: Date, d: DurationParts): Date {
+ const end = new Date(anchor.getTime());
+ if (d.years) end.setUTCFullYear(end.getUTCFullYear() + d.years);
+ if (d.months) end.setUTCMonth(end.getUTCMonth() + d.months);
+ const extraDays = d.weeks * 7 + d.days;
+ if (extraDays) end.setUTCDate(end.getUTCDate() + extraDays);
+ return end;
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 16dfc379..5086d43f 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -186,6 +186,14 @@ export const BRAIN_LOG_EVENT_KIND = {
* surface.
*/
note: "note",
+ /**
+ * `reconcile` (Brain lifecycle suite, Feature 3) - the dream reconcile
+ * phase recorded a domain-classified contradiction. Payload carries
+ * `topic`, `domain`, and either a `reason` (open question) or a
+ * `resolution` + `winner_sign` (source-freshness auto-resolution).
+ * Emitted only on a changed run, so a no-op stays byte-identical.
+ */
+ reconcile: "reconcile",
} as const;
export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -209,6 +217,75 @@ export function isBrainLogEventKind(value: string): value is BrainLogEventKind {
return BRAIN_LOG_EVENT_KIND_SET.has(value);
}
+/**
+ * Per-preference mutation audit op kinds (Brain lifecycle suite,
+ * Feature 1). Captured at the mutation chokepoints. The reader
+ * tolerates unknown op strings (forward-compat), so this is the
+ * canonical set the writers emit, not a closed validation gate.
+ */
+export const PREF_AUDIT_OP = {
+ create: "create",
+ update: "update",
+ promote: "promote",
+ retire: "retire",
+ merge: "merge",
+} as const;
+export type PrefAuditOp = (typeof PREF_AUDIT_OP)[keyof typeof PREF_AUDIT_OP];
+
+/**
+ * One append-only audit line for a single preference mutation. Stored
+ * as JSONL under `Brain/log/pref-audit/<pref-id>.jsonl`. `op` is widened
+ * to `string` on read so an unknown future op kind round-trips without
+ * loss. Revision/hash before-after are `null` where not applicable
+ * (e.g. `hash_before` is `null` on a `create`).
+ */
+export interface PrefAuditRecord {
+ readonly ts: string;
+ readonly pref_id: string;
+ readonly op: PrefAuditOp | string;
+ readonly agent: string;
+ readonly reason?: string;
+ readonly revision_before: number | null;
+ readonly revision_after: number | null;
+ readonly hash_before: string | null;
+ readonly hash_after: string | null;
+}
+
+/**
+ * Reconcile-phase contradiction domains (Brain lifecycle suite,
+ * Feature 3). A contradiction is bucketed by STRUCTURAL signal shape
+ * only - never by language. Only `source-freshness` is eligible for
+ * deterministic auto-resolution; the judgement domains always surface
+ * as operator-facing open questions.
+ */
+export const RECONCILE_DOMAIN = {
+ /** Generic competing assertions; default bucket. Never auto-resolved. */
+ claims: "claims",
+ /** Signals reference named entities (wikilinks). Never auto-resolved. */
+ entity: "entity",
+ /** Signals scoped as decisions/judgement calls. Never auto-resolved. */
+ decisions: "decisions",
+ /** Resolvable by recency: one side is materially fresher. */
+ sourceFreshness: "source-freshness",
+} as const;
+export type ReconcileDomain = (typeof RECONCILE_DOMAIN)[keyof typeof RECONCILE_DOMAIN];
+
+/**
+ * An unresolved contradiction the reconcile phase surfaced for operator
+ * review instead of force-merging. Carried on {@link DreamRunSummary}
+ * and emitted as a `reconcile` log event. The counts are integers so
+ * the question is auditable without re-reading signals.
+ */
+export interface DreamOpenQuestion {
+ readonly topic: string;
+ readonly scope?: string;
+ readonly domain: ReconcileDomain;
+ readonly positive_count: number;
+ readonly negative_count: number;
+ /** Machine-readable reason the contradiction stayed open. */
+ readonly reason: string;
+}
+
// ----- File-frontmatter shapes ----------------------------------------------
/**
@@ -638,6 +715,14 @@ export interface BrainDreamConfig {
readonly unconfirmed_window_days: number;
/** Window in which positive/negative signals cancel each other. */
readonly contradiction_window_days: number;
+ /**
+ * Brain lifecycle suite (Feature 6). When `true`, the dream heal
+ * phase performs deterministic vault enrichment (fill a missing
+ * title from the first H1, link exact title/alias mentions). Default
+ * `false` because it rewrites user files - a default install stays
+ * byte-identical. Absent is treated as `false`.
+ */
+ readonly heal_enrich_enabled?: boolean;
}
export interface BrainRetireConfig {
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 991f67d0..9dd62259 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -50,6 +50,8 @@ import {
type AppendApplyEvidenceInput,
} from "../core/brain/apply-evidence.ts";
import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
+import { readPrefAudit } from "../core/brain/pref-audit.ts";
+import { buildMorningBrief } from "../core/brain/morning-brief.ts";
import { findUnlinkedMentions } from "../core/brain/link-graph/unlinked-mentions.ts";
import { buildConceptCluster } from "../core/brain/link-graph/concept-cluster.ts";
import { auditMoc, MocAuditError } from "../core/brain/link-graph/moc-audit.ts";
@@ -875,6 +877,53 @@ async function toolBrainBacklinks(
};
}
+async function toolBrainAudit(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const raw = coerceStr(args, "pref_id", true)!;
+ // The trail is keyed by the original `pref-<slug>` id. Run the input
+ // through the shared wikilink normaliser first (handles `[[id]]`,
+ // `[[id|Alias]]`, and `Brain/.../id.md` forms), then strip the
+ // pref-/ret- prefix so every reference resolves to one trail.
+ const slug = normaliseWikilinkTarget(raw).replace(/^(?:pref-|ret-)/, "").trim();
+ if (slug.length === 0) {
+ throw new Error(`brain_audit: empty preference slug after normalising '${raw}'`);
+ }
+ const prefId = `pref-${slug}`;
+ const { records, warnings } = readPrefAudit(ctx.vault, prefId);
+ return {
+ pref_id: prefId,
+ count: records.length,
+ records,
+ warnings: warnings.map((w) => w.message),
+ };
+}
+
+async function toolBrainMorningBrief(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topK = optionalPositiveInt(args, "top_k", "brain_morning_brief") ?? 10;
+ const lookbackDays = optionalPositiveInt(args, "lookback_days", "brain_morning_brief") ?? 7;
+ const maxCharsPerMemory = optionalPositiveInt(args, "max_chars_per_memory", "brain_morning_brief");
+ const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_morning_brief");
+ const brief = buildMorningBrief(ctx.vault, {
+ now: new Date(),
+ topK,
+ lookbackDays,
+ ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
+ ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ });
+ return {
+ text: brief.text,
+ preferences: brief.preferences,
+ open_questions: brief.openQuestions,
+ recent_notes: brief.recentNotes,
+ total_chars: brief.totalChars,
+ };
+}
+
// ----- brain_doctor --------------------------------------------------------
async function toolBrainDoctor(
@@ -2160,6 +2209,56 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainBacklinks,
},
+ {
+ name: "brain_audit",
+ description:
+ "Return a preference's full mutation audit trail (create / promote / update / retire / merge), oldest first, with agent, reason, and revision + content-hash before/after. The trail is keyed by the original `pref-<slug>` id; a `ret-<slug>`, bare `<slug>`, or wikilink-decorated argument resolves to the same trail. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ pref_id: {
+ type: "string",
+ description:
+ "Preference id (e.g. `pref-foo`). `ret-foo`, bare `foo`, and `[[pref-foo]]` all resolve to the same trail.",
+ },
+ },
+ required: ["pref_id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainAudit,
+ },
+ {
+ name: "brain_morning_brief",
+ description:
+ "Return a read-only session-start summary: top confirmed preferences (confidence then recency), open questions raised by the recent reconcile phase, and recent narrative notes. Bounded by per-entry and total character caps. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ top_k: {
+ type: "integer",
+ minimum: 1,
+ description: "Max confirmed preferences to consider (default 10).",
+ },
+ lookback_days: {
+ type: "integer",
+ minimum: 1,
+ description: "Days of log history scanned for open questions + notes (default 7).",
+ },
+ max_chars_per_memory: {
+ type: "integer",
+ minimum: 1,
+ description: "Per-entry character cap (code points).",
+ },
+ max_total_chars: {
+ type: "integer",
+ minimum: 1,
+ description: "Total character cap across the brief.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainMorningBrief,
+ },
{
name: "brain_context_pack",
previewBudget: MCP_PREVIEW_BUDGET,
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 4024ed7c..9e1a9897 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -102,7 +102,13 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string
"or `since` (exactly one). Use this to discover applicable rules " +
"before calling `brain_apply_evidence`.\n" +
" - brain_doctor β€” invariant / schema health check. With " +
- "`strict: true`, warnings demote the `ok` flag.\n\n" +
+ "`strict: true`, warnings demote the `ok` flag.\n" +
+ " - brain_audit β€” read-only mutation trail for one preference " +
+ "(create / promote / update / retire / merge), with agent, reason, " +
+ "and revision + content-hash before/after.\n" +
+ " - brain_morning_brief β€” read-only session-start summary: top " +
+ "confirmed preferences, recent reconcile open questions, and recent " +
+ "notes, bounded by a character budget.\n\n" +
"Skip Brain calls for casual chat, exploration without a stated " +
"rule, read-only inspection, and trivial edits. A misrecorded " +
"signal is worse than a missed one β€” the dream pass surfaces " +
diff --git a/tests/cli/brain-audit.test.ts b/tests/cli/brain-audit.test.ts
new file mode 100644
index 00000000..18118cee
--- /dev/null
+++ b/tests/cli/brain-audit.test.ts
@@ -0,0 +1,109 @@
+/**
+ * CLI tests for `o2b brain audit`.
+ *
+ * The verb wraps `readPrefAudit` / `renderPrefAudit`. Here we lock the
+ * CLI surface: argument normalisation (pref- / ret- / bare slug all
+ * resolve to one trail), `--json`, the empty-trail path, and exit code.
+ * The audit trail itself is produced by the merge chokepoint, which has
+ * its own unit coverage.
+ */
+
+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 { writePreference } from "../../src/core/brain/preference.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-audit-cli-test-"));
+ 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);
+}
+
+function makePref(slug: string): void {
+ writePreference(vault, {
+ slug,
+ topic: "commits",
+ principle: `Principle for ${slug}`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],
+ });
+}
+
+describe("o2b brain audit", () => {
+ test("usage error with no argument", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "audit"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).not.toBe(0);
+ });
+
+ test("reports no records for a preference with no audit trail", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "audit", "pref-nothing"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("no audit records");
+ });
+
+ test("renders the merge audit trail (text + json, bare-slug normalised)", async () => {
+ await bootstrap();
+ makePref("keep");
+ makePref("drop");
+ const merge = await runCli(["brain", "merge", "pref-keep", "pref-drop", "--force"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(merge.returncode).toBe(0);
+
+ // Bare slug resolves to the same `pref-keep` trail.
+ const text = await runCli(["brain", "audit", "keep"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(text.returncode).toBe(0);
+ expect(text.stdout).toContain("pref-keep");
+ expect(text.stdout).toContain("merge");
+
+ const json = await runCli(["brain", "audit", "pref-keep", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(json.returncode).toBe(0);
+ const parsed = JSON.parse(json.stdout) as {
+ pref_id: string;
+ records: Array<{ op: string }>;
+ };
+ expect(parsed.pref_id).toBe("pref-keep");
+ expect(parsed.records.some((r) => r.op === "merge")).toBe(true);
+
+ // The dropped pref's trail shows the retire(merged-into).
+ const drop = await runCli(["brain", "audit", "ret-drop", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ const dropParsed = JSON.parse(drop.stdout) as { records: Array<{ op: string }> };
+ expect(dropParsed.records.some((r) => r.op === "retire")).toBe(true);
+ });
+});
diff --git a/tests/core/brain.dream.heal.test.ts b/tests/core/brain.dream.heal.test.ts
new file mode 100644
index 00000000..f5ba2833
--- /dev/null
+++ b/tests/core/brain.dream.heal.test.ts
@@ -0,0 +1,112 @@
+/**
+ * Heal-phase vault enrichment wired into the dream pass (Brain lifecycle
+ * suite, Feature 6). When `dream.heal_enrich_enabled` is on, a changed
+ * dream run links exact title mentions across the user's vault pages
+ * (outside the Brain root). Off by default: the heal phase is a
+ * checkpoint-only no-op and user files are byte-identical.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { dream } from "../../src/core/brain/dream.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-heal-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-heal-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function enableHeal(): void {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\ndream:\n heal_enrich_enabled: true\n",
+ "utf8",
+ );
+}
+
+function seedPromotion(): void {
+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {
+ writeSignal(vault, {
+ topic: "heal-topic",
+ signal: "positive",
+ agent: "claude",
+ principle: "Prefer the healed approach",
+ created_at: `${date}T10:00:00Z`,
+ date,
+ slug: `h${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+function makeNotes(): { refPath: string } {
+ const notes = join(vault, "Notes");
+ mkdirSync(notes, { recursive: true });
+ writeFileSync(join(notes, "Acme.md"), "---\ntitle: Acme\n---\nThe Acme page.\n", "utf8");
+ const refPath = join(notes, "ref.md");
+ writeFileSync(refPath, "---\ntitle: Ref\n---\nwe rely on Acme daily\n", "utf8");
+ return { refPath };
+}
+
+const now = new Date("2026-05-23T12:00:00Z");
+
+describe("dream heal phase enrichment", () => {
+ test("links exact title mentions in user pages when enabled", () => {
+ enableHeal();
+ const { refPath } = makeNotes();
+ seedPromotion();
+
+ const summary = dream(vault, { now });
+ expect(summary.changed).toBe(true);
+ expect(readFileSync(refPath, "utf8")).toContain("[[Acme]]");
+ const heal = summary.phases.find((p) => p.phase === "heal")?.metrics;
+ expect(heal?.["enriched"]).toBeGreaterThanOrEqual(1);
+ });
+
+ test("leaves user pages untouched when disabled (default)", () => {
+ // Note: heal flag NOT enabled (default _brain.yaml from bootstrap).
+ const { refPath } = makeNotes();
+ seedPromotion();
+
+ const before = readFileSync(refPath, "utf8");
+ const summary = dream(vault, { now });
+ expect(summary.changed).toBe(true);
+ expect(readFileSync(refPath, "utf8")).toBe(before);
+ const heal = summary.phases.find((p) => p.phase === "heal")?.metrics;
+ expect(heal?.["enriched"]).toBe(0);
+ });
+
+ test("never rewrites Brain-root pages (preferences stay txn-owned)", () => {
+ enableHeal();
+ // A Brain preference whose principle literally names a known page
+ // title; heal must NOT inject a wikilink into it (Brain root is
+ // excluded - preference frontmatter is owned by the txn writer).
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(join(vault, "Notes", "Acme.md"), "---\ntitle: Acme\n---\nx\n");
+ const prefPath = join(vault, "Brain", "preferences", "pref-mentions.md");
+ writeFileSync(
+ prefPath,
+ "---\nkind: brain-preference\nid: pref-mentions\n_status: confirmed\ncreated_at: 2026-05-01T00:00:00Z\nunconfirmed_until: 2026-05-08T00:00:00Z\ntopic: mentions\nprinciple: Always cite Acme in reviews\ntags:\n - brain\n - brain/preference\npinned: false\n---\nbody mentions Acme here\n",
+ "utf8",
+ );
+ seedPromotion();
+ dream(vault, { now });
+ expect(readFileSync(prefPath, "utf8")).not.toContain("[[Acme]]");
+ });
+});
diff --git a/tests/core/brain.dream.phases.test.ts b/tests/core/brain.dream.phases.test.ts
new file mode 100644
index 00000000..2b0dd87b
--- /dev/null
+++ b/tests/core/brain.dream.phases.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Multi-phase dream pipeline (Brain lifecycle suite, Feature 2).
+ *
+ * A changed dream run names its seams as ordered phases - close,
+ * reconcile, synthesize, heal, log - emitting one workrun checkpoint
+ * per phase and a structured `phases` summary. A no-op run stays a true
+ * no-op: empty `phases`, no workrun. The proven dream internals are
+ * unchanged; this only adds observable phase structure.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { dream } from "../../src/core/brain/dream.ts";
+import { dreamRunsDir } from "../../src/core/brain/paths.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-phases-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-phases-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function seed(slug: string, date: string): void {
+ writeSignal(vault, {
+ topic: "phase-topic",
+ signal: "positive",
+ agent: "claude",
+ principle: "Prefer the phased approach",
+ created_at: `${date}T10:00:00Z`,
+ date,
+ slug,
+ scope: "writing",
+ });
+}
+
+function workrunPhases(): string[] {
+ const dir = dreamRunsDir(vault);
+ if (!existsSync(dir)) return [];
+ const files = readdirSync(dir).filter((n) => n.endsWith(".jsonl"));
+ if (files.length === 0) return [];
+ const text = readFileSync(join(dir, files[0]!), "utf8");
+ return text
+ .split("\n")
+ .filter((l) => l.trim().length > 0)
+ .map((l) => (JSON.parse(l) as { phase: string }).phase);
+}
+
+describe("dream multi-phase pipeline", () => {
+ test("a changed run returns the ordered phase summaries", () => {
+ seed("phase-topic-a", "2026-05-20");
+ seed("phase-topic-b", "2026-05-21");
+ seed("phase-topic-c", "2026-05-22");
+ const summary = dream(vault, { now: new Date("2026-05-23T12:00:00Z") });
+ expect(summary.changed).toBe(true);
+ expect(summary.phases.map((p) => p.phase)).toEqual([
+ "close",
+ "reconcile",
+ "synthesize",
+ "heal",
+ "log",
+ ]);
+ const synth = summary.phases.find((p) => p.phase === "synthesize");
+ expect(synth?.metrics["new_unconfirmed"]).toBe(1);
+ });
+
+ test("a changed run emits ordered phase checkpoints in the workrun", () => {
+ seed("phase-topic-a", "2026-05-20");
+ seed("phase-topic-b", "2026-05-21");
+ seed("phase-topic-c", "2026-05-22");
+ dream(vault, { now: new Date("2026-05-23T12:00:00Z") });
+ const phases = workrunPhases();
+ // The new phase checkpoints appear in order between started/finalized.
+ const ordered = phases.filter((p) =>
+ ["close_complete", "reconcile_complete", "synthesize_complete", "heal_complete"].includes(p),
+ );
+ expect(ordered).toEqual([
+ "close_complete",
+ "reconcile_complete",
+ "synthesize_complete",
+ "heal_complete",
+ ]);
+ });
+
+ test("a no-op run returns empty phases and writes no workrun", () => {
+ const summary = dream(vault, { now: new Date("2026-05-23T12:00:00Z") });
+ expect(summary.changed).toBe(false);
+ expect(summary.phases).toEqual([]);
+ expect(existsSync(dreamRunsDir(vault))).toBe(false);
+ });
+});
diff --git a/tests/core/brain.dream.reconcile.test.ts b/tests/core/brain.dream.reconcile.test.ts
new file mode 100644
index 00000000..0d394b02
--- /dev/null
+++ b/tests/core/brain.dream.reconcile.test.ts
@@ -0,0 +1,112 @@
+/**
+ * Reconcile-phase domain classification in the dream pass (Brain
+ * lifecycle suite, Feature 3). The flat contradiction-topic list gains
+ * a structured `open_questions` view: each contradiction is classified
+ * by domain, source-freshness is auto-resolved (recorded, never a
+ * sub-threshold mutation), and the rest surface as operator-facing open
+ * questions. The legacy `contradictions` field stays a derived view.
+ * No forced merge ever happens.
+ */
+
+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 { dream } from "../../src/core/brain/dream.ts";
+import { readLogDay } from "../../src/core/brain/log-jsonl.ts";
+import { isoDate } from "../../src/core/brain/time.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-reconcile-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-reconcile-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function sig(opts: {
+ topic: string;
+ slug: string;
+ signal: "positive" | "negative";
+ date: string;
+ scope?: string;
+}): void {
+ writeSignal(vault, {
+ topic: opts.topic,
+ signal: opts.signal,
+ agent: "claude",
+ principle: `Rule for ${opts.topic}`,
+ created_at: `${opts.date}T10:00:00Z`,
+ date: opts.date,
+ slug: opts.slug,
+ ...(opts.scope ? { scope: opts.scope } : {}),
+ });
+}
+
+const now = new Date("2026-05-29T12:00:00Z");
+
+describe("dream reconcile phase", () => {
+ test("a same-window contradiction surfaces as a claims open question", () => {
+ // topic A promotes (3 positives) so the run is changed; topic B is a
+ // 1v1 contradiction in the same window -> claims open question.
+ sig({ topic: "topic-a", slug: "a1", signal: "positive", date: "2026-05-20" });
+ sig({ topic: "topic-a", slug: "a2", signal: "positive", date: "2026-05-21" });
+ sig({ topic: "topic-a", slug: "a3", signal: "positive", date: "2026-05-22" });
+ // Same-instant pos + neg -> no recency separation -> claims domain.
+ sig({ topic: "topic-b", slug: "b1", signal: "positive", date: "2026-05-25" });
+ sig({ topic: "topic-b", slug: "b2", signal: "negative", date: "2026-05-25" });
+
+ const summary = dream(vault, { now });
+ expect(summary.changed).toBe(true);
+ const q = summary.open_questions.find((x) => x.topic === "topic-b");
+ expect(q).toBeDefined();
+ expect(q!.domain).toBe("claims");
+ // Legacy derived view still lists the topic.
+ expect(summary.contradictions).toContain("topic-b");
+
+ const reconcileMetrics = summary.phases.find((p) => p.phase === "reconcile")?.metrics;
+ expect(reconcileMetrics?.["open_questions"]).toBe(1);
+
+ // A reconcile log event was emitted for the open question.
+ const events = readLogDay(vault, isoDate(now)).entries;
+ expect(events.some((e) => e.eventType === "reconcile")).toBe(true);
+ });
+
+ test("a wide recency gap is auto-resolved, not surfaced as an open question", () => {
+ sig({ topic: "topic-a", slug: "a1", signal: "positive", date: "2026-05-20" });
+ sig({ topic: "topic-a", slug: "a2", signal: "positive", date: "2026-05-21" });
+ sig({ topic: "topic-a", slug: "a3", signal: "positive", date: "2026-05-22" });
+ // topic-c: both within the 14d contradiction window, but the gap
+ // (11d) exceeds half the window -> source-freshness auto-resolved.
+ sig({ topic: "topic-c", slug: "c1", signal: "positive", date: "2026-05-16" });
+ sig({ topic: "topic-c", slug: "c2", signal: "negative", date: "2026-05-27" });
+
+ const summary = dream(vault, { now });
+ const open = summary.open_questions.find((x) => x.topic === "topic-c");
+ expect(open).toBeUndefined(); // auto-resolved, not an open question
+ });
+
+ test("a pure-contradiction no-op run still reports open_questions in-memory but writes no log", () => {
+ sig({ topic: "topic-b", slug: "b1", signal: "positive", date: "2026-05-25" });
+ sig({ topic: "topic-b", slug: "b2", signal: "negative", date: "2026-05-26" });
+
+ const summary = dream(vault, { now });
+ expect(summary.changed).toBe(false);
+ expect(summary.open_questions.some((x) => x.topic === "topic-b")).toBe(true);
+ // No reconcile event persisted on a no-op run (byte-identical hold).
+ const events = readLogDay(vault, isoDate(now)).entries;
+ expect(events.some((e) => e.eventType === "reconcile")).toBe(false);
+ });
+});
diff --git a/tests/core/brain.dream.temporal.test.ts b/tests/core/brain.dream.temporal.test.ts
new file mode 100644
index 00000000..79728992
--- /dev/null
+++ b/tests/core/brain.dream.temporal.test.ts
@@ -0,0 +1,76 @@
+/**
+ * Temporal extraction wired into dream promotion (Brain lifecycle
+ * suite, Feature 5). When a promoted cluster's source signal carries a
+ * formal ISO temporal token, the new preference's bi-temporal
+ * valid_from/valid_until fields are filled. Signals without an ISO token
+ * promote with no temporal fields (byte-identical to pre-suite).
+ */
+
+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 { dream } from "../../src/core/brain/dream.ts";
+import { parsePreference } from "../../src/core/brain/preference.ts";
+import { preferencePath } from "../../src/core/brain/paths.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-temporal-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-temporal-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function seed(topic: string, slug: string, date: string, principle: string): void {
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle,
+ created_at: `${date}T10:00:00Z`,
+ date,
+ slug,
+ scope: "writing",
+ });
+}
+
+const now = new Date("2026-05-29T12:00:00Z");
+
+describe("dream temporal extraction on promotion", () => {
+ test("fills valid_from/valid_until from an ISO duration in the signal", () => {
+ seed("temporal-topic", "t1", "2026-05-20", "Rule expires P30D");
+ seed("temporal-topic", "t2", "2026-05-21", "Rule expires P30D");
+ seed("temporal-topic", "t3", "2026-05-22", "Rule expires P30D");
+
+ const summary = dream(vault, { now });
+ expect(summary.new_unconfirmed).toContain("pref-temporal-topic");
+
+ const pref = parsePreference(preferencePath(vault, "temporal-topic"));
+ expect(pref.valid_from).toBe("2026-05-29T12:00:00Z");
+ expect(pref.valid_until).toBe("2026-06-28T12:00:00Z");
+ });
+
+ test("promotes without temporal fields when the signal has no ISO token", () => {
+ seed("plain-topic", "p1", "2026-05-20", "Prefer the plain approach");
+ seed("plain-topic", "p2", "2026-05-21", "Prefer the plain approach");
+ seed("plain-topic", "p3", "2026-05-22", "Prefer the plain approach");
+
+ dream(vault, { now });
+ const pref = parsePreference(preferencePath(vault, "plain-topic"));
+ expect(pref.valid_from).toBeUndefined();
+ expect(pref.valid_until).toBeUndefined();
+ });
+});
diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.ts
index 0f047229..f4a0ddd7 100644
--- a/tests/core/brain.policy.test.ts
+++ b/tests/core/brain.policy.test.ts
@@ -399,6 +399,19 @@ describe("loadBrainConfig β€” filesystem integration", () => {
writeBrainYaml(tmp, "schema_version: 1\ndream: 5\n");
expect(() => loadBrainConfig(tmp)).toThrow(/dream/);
});
+
+ test("dream.heal_enrich_enabled defaults to false", () => {
+ writeBrainYaml(tmp, DEFAULT_BRAIN_CONFIG_YAML);
+ expect(loadBrainConfig(tmp).dream.heal_enrich_enabled).toBe(false);
+ });
+
+ test("dream.heal_enrich_enabled can be opted in via YAML", () => {
+ writeBrainYaml(
+ tmp,
+ "schema_version: 1\ndream:\n candidate_threshold: 3\n unconfirmed_window_days: 14\n contradiction_window_days: 14\n heal_enrich_enabled: true\n",
+ );
+ expect(loadBrainConfig(tmp).dream.heal_enrich_enabled).toBe(true);
+ });
});
describe("parseBrainYaml", () => {
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 978a77e3..be205577 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -81,6 +81,8 @@ describe("BRAIN_* const enums", () => {
"import-claude-memory",
// Β§32B (v0.10.8) brain_note narrative milestones
"note",
+ // Brain lifecycle suite (v0.21.0) reconcile-phase open questions
+ "reconcile",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
diff --git a/tests/core/brain/heal-enrich.test.ts b/tests/core/brain/heal-enrich.test.ts
new file mode 100644
index 00000000..088bf8ef
--- /dev/null
+++ b/tests/core/brain/heal-enrich.test.ts
@@ -0,0 +1,117 @@
+/**
+ * Heal-phase vault enrichment (Brain lifecycle suite, Feature 6).
+ *
+ * Deterministic, structural enrichment used in the dream heal phase:
+ * derive a missing `title` from the page's first H1, and insert
+ * wikilinks for EXACT whole-token title/alias matches to existing
+ * pages. No inference, no language heuristics. Idempotent: existing
+ * links and inline code are never re-linked. The whole feature is
+ * gated off by default (`dream.heal_enrich_enabled`).
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ deriveTitleFromContent,
+ linkExactMentions,
+ planHealEnrichment,
+} from "../../../src/core/brain/heal-enrich.ts";
+
+describe("deriveTitleFromContent", () => {
+ test("returns the first H1 text", () => {
+ expect(deriveTitleFromContent("# Hello World\n\nbody")).toBe("Hello World");
+ });
+ test("ignores deeper headings and returns null when no H1", () => {
+ expect(deriveTitleFromContent("## Sub\n\nbody")).toBeNull();
+ expect(deriveTitleFromContent("plain body only")).toBeNull();
+ });
+ test("trims surrounding whitespace of the H1", () => {
+ expect(deriveTitleFromContent("# Spaced \nx")).toBe("Spaced");
+ });
+});
+
+describe("linkExactMentions", () => {
+ const known = ["Acme Corp", "Widget"];
+
+ test("wraps an exact whole-phrase match in a wikilink", () => {
+ expect(linkExactMentions("We use Acme Corp daily", known)).toBe(
+ "We use [[Acme Corp]] daily",
+ );
+ });
+
+ test("is idempotent - never re-links an existing wikilink", () => {
+ expect(linkExactMentions("We use [[Acme Corp]] daily", known)).toBe(
+ "We use [[Acme Corp]] daily",
+ );
+ });
+
+ test("does not link inside inline code spans", () => {
+ expect(linkExactMentions("run `Widget` now", known)).toBe("run `Widget` now");
+ });
+
+ test("does not link inside fenced code blocks", () => {
+ const body = "intro\n\n```\nuse Widget here\n```\n\nWidget outside";
+ expect(linkExactMentions(body, known)).toBe(
+ "intro\n\n```\nuse Widget here\n```\n\n[[Widget]] outside",
+ );
+ });
+
+ test("does not link a partial token (Acme Corporation)", () => {
+ expect(linkExactMentions("Acme Corporation rocks", known)).toBe(
+ "Acme Corporation rocks",
+ );
+ });
+
+ test("prefers the longest phrase at a position", () => {
+ // "Acme Corp" should win over a hypothetical "Acme" entry.
+ expect(linkExactMentions("Acme Corp ships", ["Acme", "Acme Corp"])).toBe(
+ "[[Acme Corp]] ships",
+ );
+ });
+
+ test("returns body unchanged with no known titles", () => {
+ expect(linkExactMentions("Acme Corp", [])).toBe("Acme Corp");
+ });
+
+ test("is case-sensitive (exact match only)", () => {
+ expect(linkExactMentions("acme corp lower", known)).toBe("acme corp lower");
+ });
+});
+
+describe("planHealEnrichment", () => {
+ test("plans a title completion when frontmatter has no title", () => {
+ const plan = planHealEnrichment(
+ { frontmatter: {}, body: "# Derived Title\n\ncontent" },
+ [],
+ );
+ expect(plan.changed).toBe(true);
+ expect(plan.title).toBe("Derived Title");
+ });
+
+ test("does not overwrite an existing title", () => {
+ const plan = planHealEnrichment(
+ { frontmatter: { title: "Kept" }, body: "# Other\n\nx" },
+ [],
+ );
+ expect(plan.title).toBeUndefined();
+ });
+
+ test("plans a body rewrite when an exact mention can be linked", () => {
+ const plan = planHealEnrichment(
+ { frontmatter: { title: "Note" }, body: "see Widget here" },
+ ["Widget"],
+ );
+ expect(plan.changed).toBe(true);
+ expect(plan.body).toBe("see [[Widget]] here");
+ });
+
+ test("is a no-op (changed=false) when nothing to do", () => {
+ const plan = planHealEnrichment(
+ { frontmatter: { title: "Note" }, body: "nothing to link" },
+ ["Widget"],
+ );
+ expect(plan.changed).toBe(false);
+ expect(plan.title).toBeUndefined();
+ expect(plan.body).toBeUndefined();
+ });
+});
diff --git a/tests/core/brain/heal-run.test.ts b/tests/core/brain/heal-run.test.ts
new file mode 100644
index 00000000..9a2af58a
--- /dev/null
+++ b/tests/core/brain/heal-run.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Heal-enrichment runner (Brain lifecycle suite, Feature 6) - safety
+ * properties: the Brain root AND the standard excluded dirs (.git /
+ * .obsidian / .trash / .stversions) are never rewritten, and a page is
+ * never linked to its own title or aliases.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runHealEnrichment } from "../../../src/core/brain/heal-run.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-heal-run-"));
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function note(rel: string, content: string): string {
+ const p = join(vault, rel);
+ mkdirSync(join(p, ".."), { recursive: true });
+ writeFileSync(p, content, "utf8");
+ return p;
+}
+
+describe("runHealEnrichment safety", () => {
+ test("links exact mentions in ordinary user pages", () => {
+ note("Notes/Acme.md", "---\ntitle: Acme\n---\nThe Acme page.\n");
+ const ref = note("Notes/ref.md", "---\ntitle: Ref\n---\nwe rely on Acme daily\n");
+ const result = runHealEnrichment(vault);
+ expect(result.enriched).toBeGreaterThanOrEqual(1);
+ expect(readFileSync(ref, "utf8")).toContain("[[Acme]]");
+ });
+
+ test("never rewrites pages under .obsidian / .stversions / .trash", () => {
+ note("Notes/Acme.md", "---\ntitle: Acme\n---\nThe Acme page.\n");
+ const obsidian = note(".obsidian/snippets/note.md", "mentions Acme here");
+ const stversion = note(".stversions/old.md", "mentions Acme here");
+ const trash = note(".trash/gone.md", "mentions Acme here");
+ runHealEnrichment(vault);
+ expect(readFileSync(obsidian, "utf8")).not.toContain("[[Acme]]");
+ expect(readFileSync(stversion, "utf8")).not.toContain("[[Acme]]");
+ expect(readFileSync(trash, "utf8")).not.toContain("[[Acme]]");
+ });
+
+ test("never rewrites pages under the Brain root", () => {
+ note("Notes/Acme.md", "---\ntitle: Acme\n---\nx\n");
+ const brainPage = note("Brain/preferences/pref-x.md", "mentions Acme here");
+ runHealEnrichment(vault);
+ expect(readFileSync(brainPage, "utf8")).not.toContain("[[Acme]]");
+ });
+
+ test("does not link a page to its own alias", () => {
+ // ego.md has title Ego and an alias "Acme"; it must not link its own
+ // alias even though another page also references "Acme".
+ const ego = note(
+ "Notes/ego.md",
+ "---\ntitle: Ego\naliases:\n - Acme\n---\nThis Acme note is mine.\n",
+ );
+ runHealEnrichment(vault);
+ expect(readFileSync(ego, "utf8")).not.toContain("[[Acme]]");
+ });
+});
diff --git a/tests/core/brain/morning-brief.test.ts b/tests/core/brain/morning-brief.test.ts
new file mode 100644
index 00000000..be4c838e
--- /dev/null
+++ b/tests/core/brain/morning-brief.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Morning brief / day-close summary (Brain lifecycle suite, Feature 4).
+ *
+ * A read-only, budgeted session-start summary: top confirmed
+ * preferences (confidence then recency), open questions raised by the
+ * recent reconcile phase, and recent narrative notes. Deterministic on
+ * an injected clock; character-bounded via the shared recall budget.
+ */
+
+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 { buildMorningBrief } from "../../../src/core/brain/morning-brief.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+const now = new Date("2026-05-29T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-morning-brief-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-morning-brief-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function confirmedPref(slug: string, confidence: number): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `Principle ${slug}`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],
+ confidence_value: confidence,
+ });
+}
+
+describe("buildMorningBrief", () => {
+ test("returns an empty brief for a fresh vault", () => {
+ const brief = buildMorningBrief(vault, { now, topK: 5 });
+ expect(brief.preferences).toHaveLength(0);
+ expect(brief.openQuestions).toHaveLength(0);
+ expect(brief.text).toBe("");
+ });
+
+ test("ranks confirmed preferences by confidence (desc)", () => {
+ confirmedPref("low", 0.2);
+ confirmedPref("high", 0.9);
+ const brief = buildMorningBrief(vault, { now, topK: 5 });
+ expect(brief.preferences.map((p) => p.id)).toEqual(["pref-high", "pref-low"]);
+ expect(brief.text).toContain("Principle high");
+ });
+
+ test("surfaces recent reconcile open questions but not auto-resolutions", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-28T09:00:00Z",
+ eventType: "reconcile",
+ body: { topic: "commit-style", domain: "claims", reason: "claims-needs-operator" },
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-28T09:01:00Z",
+ eventType: "reconcile",
+ body: { topic: "freshness-one", domain: "source-freshness", resolution: "auto-resolved", winner_sign: "negative" },
+ });
+ const brief = buildMorningBrief(vault, { now, topK: 5, lookbackDays: 7 });
+ expect(brief.openQuestions.map((q) => q.topic)).toEqual(["commit-style"]);
+ expect(brief.text).toContain("commit-style");
+ });
+
+ test("includes recent notes within the lookback window", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-28T08:00:00Z",
+ eventType: "note",
+ body: { text: "Shipped the lifecycle suite", agent: "claude" },
+ });
+ const brief = buildMorningBrief(vault, { now, topK: 5, lookbackDays: 7 });
+ expect(brief.recentNotes.some((n) => n.includes("lifecycle suite"))).toBe(true);
+ });
+
+ test("honours the total character budget", () => {
+ confirmedPref("a", 0.9);
+ confirmedPref("b", 0.8);
+ const tiny = buildMorningBrief(vault, { now, topK: 5, maxTotalChars: 12 });
+ expect(tiny.totalChars).toBeLessThanOrEqual(12);
+ });
+
+ test("is deterministic on the injected clock", () => {
+ confirmedPref("a", 0.9);
+ const a = buildMorningBrief(vault, { now, topK: 5 });
+ const b = buildMorningBrief(vault, { now, topK: 5 });
+ expect(a.text).toBe(b.text);
+ });
+});
diff --git a/tests/core/brain/pref-audit-chokepoints.test.ts b/tests/core/brain/pref-audit-chokepoints.test.ts
new file mode 100644
index 00000000..700b7cf5
--- /dev/null
+++ b/tests/core/brain/pref-audit-chokepoints.test.ts
@@ -0,0 +1,168 @@
+/**
+ * Audit capture at the mutation chokepoints (Brain lifecycle suite,
+ * Feature 1, Task 2). `writePreferenceTxn`, `moveToRetired`, and
+ * `mergePreferences` each append an authoritative audit record when a
+ * mutation actually changes the preference. Callers that omit the audit
+ * sink are unaffected (back-compat).
+ */
+
+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 { writePreferenceTxn } from "../../../src/core/brain/preference-txn.ts";
+import { moveToRetired } from "../../../src/core/brain/preference.ts";
+import { mergePreferences } from "../../../src/core/brain/merge.ts";
+import { readPrefAudit } from "../../../src/core/brain/pref-audit.ts";
+import { preferencePath } from "../../../src/core/brain/paths.ts";
+import {
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+} from "../../../src/core/brain/types.ts";
+import type { WritePreferenceInput } from "../../../src/core/brain/preference.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-audit-choke-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox", "processed"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function baseInput(over: Partial<WritePreferenceInput> = {}): WritePreferenceInput {
+ return {
+ slug: "foo",
+ topic: "foo",
+ principle: "Prefer foo over bar",
+ created_at: "2026-05-29T10:00:00Z",
+ unconfirmed_until: "2026-06-12T10:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ evidenced_by: ["[[sig-2026-05-29-foo]]"],
+ confidence_value: 0,
+ ...over,
+ };
+}
+
+const audit = (agent = "dream", reason?: string) => ({
+ agent,
+ ...(reason ? { reason } : {}),
+ now: () => new Date("2026-05-29T12:00:00Z"),
+});
+
+describe("writePreferenceTxn audit sink", () => {
+ test("records a create on the first write", () => {
+ writePreferenceTxn(vault, baseInput(), [], { overwrite: false }, undefined, audit("dream", "promoted from cluster"));
+ const { records } = readPrefAudit(vault, "pref-foo");
+ expect(records).toHaveLength(1);
+ expect(records[0]!.op).toBe("create");
+ expect(records[0]!.agent).toBe("dream");
+ expect(records[0]!.reason).toBe("promoted from cluster");
+ expect(records[0]!.hash_before).toBeNull();
+ expect(records[0]!.hash_after).not.toBeNull();
+ });
+
+ test("records a promote when status crosses to confirmed", () => {
+ writePreferenceTxn(vault, baseInput(), [], { overwrite: false }, undefined, audit());
+ writePreferenceTxn(
+ vault,
+ baseInput({ status: BRAIN_PREFERENCE_STATUS.confirmed, confirmed_at: "2026-05-29T12:00:00Z" }),
+ [],
+ { overwrite: true },
+ undefined,
+ audit(),
+ );
+ const { records } = readPrefAudit(vault, "pref-foo");
+ expect(records.map((r) => r.op)).toEqual(["create", "promote"]);
+ });
+
+ test("does NOT record a counter-only update (content unchanged)", () => {
+ writePreferenceTxn(
+ vault,
+ baseInput({ status: BRAIN_PREFERENCE_STATUS.confirmed, confirmed_at: "2026-05-29T12:00:00Z" }),
+ [],
+ { overwrite: false },
+ undefined,
+ audit(),
+ );
+ // Same principle/scope, only a counter moves -> update op, suppressed.
+ writePreferenceTxn(
+ vault,
+ baseInput({
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ confirmed_at: "2026-05-29T12:00:00Z",
+ applied_count: 5,
+ }),
+ [],
+ { overwrite: true },
+ undefined,
+ audit(),
+ );
+ const { records } = readPrefAudit(vault, "pref-foo");
+ expect(records.map((r) => r.op)).toEqual(["create"]);
+ });
+
+ test("writes no audit file when the sink is omitted (back-compat)", () => {
+ writePreferenceTxn(vault, baseInput(), [], { overwrite: false });
+ const { records } = readPrefAudit(vault, "pref-foo");
+ expect(records).toHaveLength(0);
+ });
+});
+
+describe("moveToRetired audit sink", () => {
+ test("records a retire keyed by the original pref id", () => {
+ writePreferenceTxn(
+ vault,
+ baseInput({ status: BRAIN_PREFERENCE_STATUS.confirmed, confirmed_at: "2026-05-29T12:00:00Z" }),
+ [],
+ { overwrite: false },
+ undefined,
+ audit(),
+ );
+ moveToRetired(vault, preferencePath(vault, "foo"), BRAIN_RETIRED_REASON.rebutted, {
+ now: new Date("2026-05-30T09:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-30]]",
+ audit: { agent: "operator" },
+ });
+ const { records } = readPrefAudit(vault, "pref-foo");
+ expect(records.map((r) => r.op)).toEqual(["create", "retire"]);
+ expect(records[1]!.agent).toBe("operator");
+ expect(records[1]!.reason).toBe(BRAIN_RETIRED_REASON.rebutted);
+ });
+});
+
+describe("mergePreferences audit", () => {
+ test("records merge on keep and retire(merged-into) on drop", () => {
+ for (const slug of ["keep", "drop"]) {
+ writePreferenceTxn(
+ vault,
+ baseInput({
+ slug,
+ topic: "shared",
+ principle: `Principle ${slug}`,
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ confirmed_at: "2026-05-29T12:00:00Z",
+ evidenced_by: [`[[sig-2026-05-29-${slug}]]`],
+ }),
+ [],
+ { overwrite: false },
+ undefined,
+ audit(),
+ );
+ }
+ mergePreferences(vault, "pref-keep", "pref-drop", {
+ now: new Date("2026-05-31T09:00:00Z"),
+ agentName: "operator",
+ });
+ const keep = readPrefAudit(vault, "pref-keep");
+ const drop = readPrefAudit(vault, "pref-drop");
+ expect(keep.records.map((r) => r.op)).toEqual(["create", "merge"]);
+ expect(drop.records.map((r) => r.op)).toEqual(["create", "retire"]);
+ expect(drop.records[1]!.reason).toBe(BRAIN_RETIRED_REASON.mergedInto);
+ });
+});
diff --git a/tests/core/brain/pref-audit.test.ts b/tests/core/brain/pref-audit.test.ts
new file mode 100644
index 00000000..99ed4adc
--- /dev/null
+++ b/tests/core/brain/pref-audit.test.ts
@@ -0,0 +1,199 @@
+/**
+ * Per-preference mutation audit log (Brain lifecycle suite, Feature 1).
+ *
+ * An append-only JSONL trail under `Brain/log/pref-audit/<pref-id>.jsonl`
+ * captures every mutation to a preference (create / update / promote /
+ * retire / merge) with the agent, reason, and revision + content-hash
+ * before/after. The trail is authoritative because it is written at the
+ * mutation chokepoints, and it stays a true no-op when a write does not
+ * actually change the preference content (hash_before === hash_after).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ appendPrefAudit,
+ readPrefAudit,
+ renderPrefAuditLine,
+} from "../../../src/core/brain/pref-audit.ts";
+import { prefAuditPath } from "../../../src/core/brain/paths.ts";
+import { PREF_AUDIT_OP } from "../../../src/core/brain/types.ts";
+
+let vault: string;
+const now = new Date("2026-05-29T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pref-audit-"));
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("PREF_AUDIT_OP", () => {
+ test("exposes the five canonical op strings", () => {
+ expect(PREF_AUDIT_OP.create).toBe("create");
+ expect(PREF_AUDIT_OP.update).toBe("update");
+ expect(PREF_AUDIT_OP.promote).toBe("promote");
+ expect(PREF_AUDIT_OP.retire).toBe("retire");
+ expect(PREF_AUDIT_OP.merge).toBe("merge");
+ });
+});
+
+describe("renderPrefAuditLine", () => {
+ test("emits one canonical JSON object with a trailing newline", () => {
+ const line = renderPrefAuditLine({
+ ts: "2026-05-29T12:00:00Z",
+ pref_id: "pref-foo",
+ op: PREF_AUDIT_OP.promote,
+ agent: "dream",
+ reason: "threshold met",
+ revision_before: 1,
+ revision_after: 2,
+ hash_before: "aaa",
+ hash_after: "bbb",
+ });
+ expect(line.endsWith("\n")).toBe(true);
+ const parsed = JSON.parse(line) as Record<string, unknown>;
+ expect(parsed["pref_id"]).toBe("pref-foo");
+ expect(parsed["op"]).toBe("promote");
+ expect(parsed["agent"]).toBe("dream");
+ expect(parsed["revision_after"]).toBe(2);
+ });
+});
+
+describe("appendPrefAudit", () => {
+ test("appends a record on a real content change and returns true", () => {
+ const wrote = appendPrefAudit(
+ vault,
+ {
+ pref_id: "pref-foo",
+ op: PREF_AUDIT_OP.create,
+ agent: "dream",
+ reason: "promoted from 2 signals",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "abc123",
+ },
+ { now },
+ );
+ expect(wrote).toBe(true);
+ const path = prefAuditPath(vault, "pref-foo");
+ expect(existsSync(path)).toBe(true);
+ const { records, warnings } = readPrefAudit(vault, "pref-foo");
+ expect(warnings).toHaveLength(0);
+ expect(records).toHaveLength(1);
+ expect(records[0]!.op).toBe("create");
+ expect(records[0]!.ts).toBe("2026-05-29T12:00:00Z");
+ expect(records[0]!.hash_after).toBe("abc123");
+ });
+
+ test("is a no-op when hash_before === hash_after (unchanged content)", () => {
+ const wrote = appendPrefAudit(
+ vault,
+ {
+ pref_id: "pref-foo",
+ op: PREF_AUDIT_OP.update,
+ agent: "dream",
+ revision_before: 3,
+ revision_after: 4,
+ hash_before: "same",
+ hash_after: "same",
+ },
+ { now },
+ );
+ expect(wrote).toBe(false);
+ expect(existsSync(prefAuditPath(vault, "pref-foo"))).toBe(false);
+ });
+
+ test("accumulates records across calls in chronological order", () => {
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: "pref-bar",
+ op: PREF_AUDIT_OP.create,
+ agent: "dream",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "h1",
+ },
+ { now: new Date("2026-05-29T12:00:00Z") },
+ );
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: "pref-bar",
+ op: PREF_AUDIT_OP.retire,
+ agent: "operator",
+ reason: "rebutted",
+ revision_before: 1,
+ revision_after: 2,
+ hash_before: "h1",
+ hash_after: "h2",
+ },
+ { now: new Date("2026-05-30T09:00:00Z") },
+ );
+ const { records } = readPrefAudit(vault, "pref-bar");
+ expect(records.map((r) => r.op)).toEqual(["create", "retire"]);
+ expect(records[1]!.agent).toBe("operator");
+ });
+});
+
+describe("readPrefAudit", () => {
+ test("returns empty records (no warnings) for a preference with no audit file", () => {
+ const { records, warnings } = readPrefAudit(vault, "pref-missing");
+ expect(records).toHaveLength(0);
+ expect(warnings).toHaveLength(0);
+ });
+
+ test("tolerates an unknown op kind, keeping the raw string", () => {
+ const path = prefAuditPath(vault, "pref-future");
+ mkdirSync(join(vault, "Brain", "log", "pref-audit"), { recursive: true });
+ appendFileSync(
+ path,
+ JSON.stringify({
+ ts: "2026-05-29T12:00:00Z",
+ pref_id: "pref-future",
+ op: "quantum-entangle",
+ agent: "dream",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "z",
+ }) + "\n",
+ "utf8",
+ );
+ const { records, warnings } = readPrefAudit(vault, "pref-future");
+ expect(warnings).toHaveLength(0);
+ expect(records).toHaveLength(1);
+ expect(records[0]!.op).toBe("quantum-entangle");
+ });
+
+ test("surfaces a malformed JSONL line as a warning without aborting", () => {
+ const path = prefAuditPath(vault, "pref-mixed");
+ mkdirSync(join(vault, "Brain", "log", "pref-audit"), { recursive: true });
+ appendFileSync(path, "{ not json\n", "utf8");
+ appendFileSync(
+ path,
+ JSON.stringify({
+ ts: "2026-05-29T12:00:00Z",
+ pref_id: "pref-mixed",
+ op: "create",
+ agent: "dream",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "ok",
+ }) + "\n",
+ "utf8",
+ );
+ const { records, warnings } = readPrefAudit(vault, "pref-mixed");
+ expect(records).toHaveLength(1);
+ expect(warnings.length).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/tests/core/brain/reconcile-domains.test.ts b/tests/core/brain/reconcile-domains.test.ts
new file mode 100644
index 00000000..a7c95725
--- /dev/null
+++ b/tests/core/brain/reconcile-domains.test.ts
@@ -0,0 +1,140 @@
+/**
+ * Reconcile domain classification (Brain lifecycle suite, Feature 3).
+ *
+ * Deterministic, structural-only classification of a contradiction into
+ * one of four domains, plus a conservative resolver: ONLY the
+ * source-freshness domain auto-resolves (toward the strictly fresher
+ * side, beyond a margin); every other domain - and an ambiguous
+ * freshness case - becomes an operator-facing open question. No
+ * language inspection, no LLM fan-out.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ classifyContradiction,
+ resolveContradiction,
+ RECONCILE_DOMAIN,
+ type ContradictionInput,
+} from "../../../src/core/brain/reconcile-domains.ts";
+
+const now = new Date("2026-05-29T12:00:00Z");
+
+function input(over: Partial<ContradictionInput> = {}): ContradictionInput {
+ return {
+ topic: "commit-style",
+ positives: [{ created_at: "2026-05-20T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-21T00:00:00Z" }],
+ ...over,
+ };
+}
+
+describe("RECONCILE_DOMAIN", () => {
+ test("exposes the four canonical domains", () => {
+ expect(RECONCILE_DOMAIN.claims).toBe("claims");
+ expect(RECONCILE_DOMAIN.entity).toBe("entity");
+ expect(RECONCILE_DOMAIN.decisions).toBe("decisions");
+ expect(RECONCILE_DOMAIN.sourceFreshness).toBe("source-freshness");
+ });
+});
+
+describe("classifyContradiction", () => {
+ test("scope 'decisions' classifies as the decisions domain", () => {
+ expect(classifyContradiction(input({ scope: "decisions" }))).toBe("decisions");
+ });
+
+ test("entity wikilinks in a signal source classify as the entity domain", () => {
+ const out = classifyContradiction(
+ input({
+ positives: [{ created_at: "2026-05-20T00:00:00Z", source: ["[[Acme Corp]]"] }],
+ }),
+ );
+ expect(out).toBe("entity");
+ });
+
+ test("a recency separation with no entity/decisions marker is source-freshness", () => {
+ const out = classifyContradiction(
+ input({
+ positives: [{ created_at: "2026-05-01T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-28T00:00:00Z" }],
+ }),
+ );
+ expect(out).toBe("source-freshness");
+ });
+
+ test("same-day signals with no markers fall back to claims", () => {
+ const out = classifyContradiction(
+ input({
+ positives: [{ created_at: "2026-05-20T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-20T00:00:00Z" }],
+ }),
+ );
+ expect(out).toBe("claims");
+ });
+});
+
+describe("resolveContradiction", () => {
+ test("auto-resolves source-freshness toward the fresher side beyond the margin", () => {
+ const out = resolveContradiction(
+ input({
+ positives: [{ created_at: "2026-05-01T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-28T00:00:00Z" }],
+ }),
+ { now, freshnessMarginDays: 7 },
+ );
+ expect(out.kind).toBe("auto-resolved");
+ if (out.kind === "auto-resolved") {
+ expect(out.domain).toBe("source-freshness");
+ expect(out.winner_sign).toBe("negative"); // the newer side
+ }
+ });
+
+ test("source-freshness within the margin stays an open question", () => {
+ const out = resolveContradiction(
+ input({
+ positives: [{ created_at: "2026-05-26T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-28T00:00:00Z" }],
+ }),
+ { now, freshnessMarginDays: 7 },
+ );
+ expect(out.kind).toBe("open-question");
+ });
+
+ test("a claims contradiction is never auto-resolved", () => {
+ const out = resolveContradiction(
+ input({
+ positives: [{ created_at: "2026-05-20T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-20T00:00:00Z" }],
+ }),
+ { now, freshnessMarginDays: 7 },
+ );
+ expect(out.kind).toBe("open-question");
+ if (out.kind === "open-question") {
+ expect(out.question.domain).toBe("claims");
+ expect(out.question.topic).toBe("commit-style");
+ }
+ });
+
+ test("a decisions contradiction is never auto-resolved even with a recency gap", () => {
+ const out = resolveContradiction(
+ input({
+ scope: "decisions",
+ positives: [{ created_at: "2026-05-01T00:00:00Z" }],
+ negatives: [{ created_at: "2026-05-28T00:00:00Z" }],
+ }),
+ { now, freshnessMarginDays: 7 },
+ );
+ expect(out.kind).toBe("open-question");
+ if (out.kind === "open-question") {
+ expect(out.question.domain).toBe("decisions");
+ }
+ });
+
+ test("is deterministic and never throws on empty sides", () => {
+ const empty = resolveContradiction(
+ { topic: "x", positives: [], negatives: [] },
+ { now, freshnessMarginDays: 7 },
+ );
+ expect(empty.kind).toBe("open-question");
+ });
+});
diff --git a/tests/core/brain/temporal-extract.test.ts b/tests/core/brain/temporal-extract.test.ts
new file mode 100644
index 00000000..c6b419a4
--- /dev/null
+++ b/tests/core/brain/temporal-extract.test.ts
@@ -0,0 +1,80 @@
+/**
+ * Temporal extraction from signal text (Brain lifecycle suite,
+ * Feature 5). A pure, language-agnostic parser that recognises formal
+ * ISO-8601 tokens only - dates, intervals, and durations - and maps
+ * them onto the bi-temporal `valid_from` / `valid_until` shape. Text
+ * carrying no ISO token (including localized month/day names in any
+ * language) yields `{}`.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { extractTemporalConstraints } from "../../../src/core/brain/temporal-extract.ts";
+
+const now = new Date("2026-05-29T12:00:00Z");
+
+describe("extractTemporalConstraints", () => {
+ test("returns {} for text with no ISO token", () => {
+ expect(extractTemporalConstraints("just a plain note", { now })).toEqual({});
+ });
+
+ test("ignores localized month names (language-agnostic)", () => {
+ // Russian, Spanish, Chinese month/day phrases - no ISO token.
+ expect(extractTemporalConstraints("ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ понСдСльник Π² ΠΌΠ°Π΅", { now })).toEqual({});
+ expect(extractTemporalConstraints("revisar el 5 de mayo", { now })).toEqual({});
+ expect(extractTemporalConstraints("δΊ”ζœˆζ―ε‘¨δΈ€ε€δΉ ", { now })).toEqual({});
+ });
+
+ test("maps an ISO interval A/B to valid_from + valid_until", () => {
+ const out = extractTemporalConstraints("active 2026-06-01/2026-06-30 only", { now });
+ expect(out.valid_from).toBe("2026-06-01T00:00:00Z");
+ expect(out.valid_until).toBe("2026-06-30T00:00:00Z");
+ });
+
+ test("maps an ISO-8601 day duration relative to now", () => {
+ const out = extractTemporalConstraints("keep this for P7D then drop", { now });
+ expect(out.valid_from).toBe("2026-05-29T12:00:00Z");
+ expect(out.valid_until).toBe("2026-06-05T12:00:00Z");
+ });
+
+ test("maps a week duration", () => {
+ const out = extractTemporalConstraints("valid P2W", { now });
+ expect(out.valid_until).toBe("2026-06-12T12:00:00Z");
+ });
+
+ test("maps a month duration via calendar arithmetic", () => {
+ const out = extractTemporalConstraints("expires in P1M", { now });
+ expect(out.valid_until).toBe("2026-06-29T12:00:00Z");
+ });
+
+ test("maps a year duration", () => {
+ const out = extractTemporalConstraints("renew P1Y", { now });
+ expect(out.valid_until).toBe("2027-05-29T12:00:00Z");
+ });
+
+ test("anchors a duration to a co-occurring explicit start date", () => {
+ const out = extractTemporalConstraints("from 2026-06-01 for P1Y", { now });
+ expect(out.valid_from).toBe("2026-06-01T00:00:00Z");
+ expect(out.valid_until).toBe("2027-06-01T00:00:00Z");
+ });
+
+ test("treats a lone ISO date as valid_from", () => {
+ const out = extractTemporalConstraints("starting 2026-07-01", { now });
+ expect(out.valid_from).toBe("2026-07-01T00:00:00Z");
+ expect(out.valid_until).toBeUndefined();
+ });
+
+ test("prefers the interval form over a lone date when both could match", () => {
+ const out = extractTemporalConstraints("window 2026-06-01/2026-06-30", { now });
+ expect(out.valid_from).toBe("2026-06-01T00:00:00Z");
+ expect(out.valid_until).toBe("2026-06-30T00:00:00Z");
+ });
+
+ test("is deterministic on the injected clock and never throws", () => {
+ const a = extractTemporalConstraints("P30D", { now });
+ const b = extractTemporalConstraints("P30D", { now });
+ expect(a).toEqual(b);
+ expect(() => extractTemporalConstraints("PXYZ garbage", { now })).not.toThrow();
+ expect(extractTemporalConstraints("PXYZ garbage", { now })).toEqual({});
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 6d4ae632..8adcd038 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -207,6 +207,9 @@ describe("tool listing", () => {
"brain_health",
"brain_mcp_landscape",
"brain_backlinks",
+ // Per-preference mutation audit + morning brief (added in v0.21.0).
+ "brain_audit",
+ "brain_morning_brief",
"brain_context_pack",
"brain_unlinked_mentions",
"brain_concept_synthesis",
@@ -469,7 +472,9 @@ describe("stdio loop", () => {
// + brain_artifact_get (v0.18.0) = 40.
// + brain_mcp_landscape (typed graph semantics) = 41.
// + brain_pre_compress_pack (v0.20.0) = 42.
- expect(list.result.tools.length).toBe(42);
+ // + brain_audit (v0.21.0) = 43.
+ // + brain_morning_brief (v0.21.0) = 44.
+ expect(list.result.tools.length).toBe(44);
});
test("returns parse error for invalid JSON", async () => {