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
v0.14.0 - Semantic Brain Health and Self-Maintenance: contradiction detection, concept gaps, stale claims, edit-history, remediation (#38)
Sol Aitkenb76199a02579
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5e0c2874..2eae7f7f 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.13.0",+ "version": "0.14.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.jsonindex af428298..fd48d81c 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.13.0",+ "version": "0.14.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.mdindex 2b261859..5fb3c199 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,64 @@ 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.14.0] - 2026-05-27++Semantic Brain Health and Self-Maintenance suite: `brain_doctor` grows+from a structural well-formedness checker into a semantic quality gate,+and gains a bounded, deterministic self-maintenance path. It now surfaces+confirmed preferences that contradict each other (same subject, opposite+sign of record), concepts that recur across the vault with no dedicated+preference, and confirmed rules running on stale evidence. Every+preference write through the dream pass leaves an append-only edit-history+trail, so a rule's wording can be replayed from first signal to current+form. A new reconciliation surface folds the three detectors into one+clean/watch/investigate verdict, and `doctor --remediate` plans a+dependency-ordered repair and applies the auto-safe fixes (with a+dry-run preview). Every detector is dependency-free, deterministic,+language-agnostic, and config-tunable.++### Added++- `src/core/brain/health/contradiction.ts` (`detectContradictions`) -+ pairs confirmed preferences by principle token overlap and keeps only+ opposite-sign pairs. Polarity comes from the shared sign-of-record+ helper; no negation word list.+- `src/core/brain/health/concept-gap.ts` (`detectConceptGaps`) -+ recurring entities (via the v0.13.0 entity extractor) with no covering+ preference topic. Frequency-only, language-agnostic.+- `src/core/brain/health/stale-claim.ts` (`detectStaleClaims`) -+ confirmed preferences whose newest evidence is older than a window+ (injected clock).+- `src/core/brain/health/edit-history.ts` - append-only+ `pref-<slug>.history.jsonl` sidecar (`appendEditHistory` /+ `readEditHistory` / `renderEditHistory`), idempotent on+ `(revision, field, after)` so Syncthing peers converge. Recorded from+ the `writePreferenceTxn` chokepoint (opt-in); the dream pass threads it.+- `src/core/brain/health/remediation.ts` - `planRemediation` (ordered,+ auto-safe vs needs-review classification) and `applyRemediation`+ (dry-run safe, applies only auto-safe content-hash re-stamps under the+ sync lock, bounded by a step cap).+- `src/core/brain/health/reconcile.ts` (`reconcileSemanticHealth`) -+ runs the three detectors as domains in one deterministic pass and+ returns a `clean | watch | investigate` verdict.+- `src/core/brain/sign.ts` - shared sign-of-record helper extracted from+ `dream.ts` (behaviour-preserving).+- `brain_health` MCP tool; `o2b brain health`, `o2b brain history <slug>`,+ and `o2b brain doctor --remediate [--dry-run]` CLI surfaces.+- Optional `health:` config block (`contradiction_jaccard`,+ `concept_gap_min_frequency`, `stale_claim_max_age_days`,+ `remediation_step_cap`) with `BRAIN_HEALTH_DEFAULTS` + `resolveHealth`.++### Changed++- `runDoctor` now runs the semantic-health reconciliation best-effort,+ merges findings as warnings (`contradictory-preferences`,+ `concept-gap`, `stale-claim`), and attaches a `semantic_health` report+ to `RunDoctorResult`. The doctor remains non-mutating.+- `writePreferenceTxn` accepts an optional edit-history option; the dream+ pass passes its agent + run clock so promotions, refreshes, and+ retirements are recorded.+## [0.13.0] - 2026-05-26Hybrid Search and Recall Quality suite: the fused FTS5 + semantic@@ -3001,6 +3059,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.14.0]: https://github.com/itechmeat/open-second-brain/compare/v0.13.0...v0.14.0[0.13.0]: https://github.com/itechmeat/open-second-brain/compare/v0.12.0...v0.13.0[0.12.0]: https://github.com/itechmeat/open-second-brain/compare/v0.11.0...v0.12.0[0.10.9]: https://github.com/itechmeat/open-second-brain/compare/v0.10.8...v0.10.9diff --git a/README.md b/README.mdindex e326d1cf..f427355d 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, cross-project pointers for shared vaults, the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, 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), and the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking). 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, cross-project pointers for shared vaults, the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, 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), and 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`). 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.## CLIdiff --git a/docs/brainstorm/semantic-brain-health/cli-output/claude.md b/docs/brainstorm/semantic-brain-health/cli-output/claude.mdnew file mode 100644index 00000000..c1a17333--- /dev/null+++ b/docs/brainstorm/semantic-brain-health/cli-output/claude.md@@ -0,0 +1,37 @@+### Variant 1: In-place extension of doctor.ts+- **Approach**: Add each semantic detector as a new private `check*` helper appended to `doctor.ts`, reusing the existing `readAllPreferenceRecords`/`readAllLogRecords`/`similarity.ts` plumbing and pushing `DoctorIssue`s onto the same array. Reconciliation becomes a grouping pass over the issues the new checks emit; the edit-history sidecar and a `remediate()` entry point are added as further exports in (or directly beside) `doctor.ts`.+- **Trade-offs**:+ - Pro: maximal DRY — reuses already-present record readers, similarity, and verdict assembly with zero new wiring.+ - Pro: matches the "in-place-extension-of-pure-modules" style the project just used for v0.12/v0.13.+ - Pro: fastest path; least new surface area to test and document.+ - Con: `doctor.ts` is already 1088 lines and would approach ~2000, mixing structural and semantic concerns in one file.+ - Con: putting mutation (`remediate`) next to a module whose invariant is "never mutates today" blurs the non-mutating contract and invites accidental coupling.+ - Con: per-detector config-gating and independent testing get awkward when everything shares one function body and one issues array.+- **Complexity**: medium+- **Risk**: medium++### Variant 2: Semantic-health module layer with a separate remediation engine+- **Approach**: Introduce `src/core/brain/health/` with one pure detector module per concern (`contradiction.ts`, `concept-gap.ts`, `stale-claim.ts`), a `reconcile.ts` aggregator that runs them as partitioned domains (preferences / evidence / retirement) in a single deterministic pass, an append-only `edit-history.ts` sidecar reader/writer, and a standalone `remediation.ts` planner+executor. `doctor.ts` calls the detectors and merges their findings into its `issues`+`trustVerdict`, staying non-mutating; remediation is a distinct opt-in path that routes auto-safe fixes through the `preference-txn` chokepoint.+- **Trade-offs**:+ - Pro: clean separation of structural vs semantic; each detector is independently skippable, config-gated, and unit-testable.+ - Pro: mirrors the existing `assess-rule-quality.ts` pure-gate pattern and the "pure core + thin shell" convention.+ - Pro: remediation isolation preserves the doctor non-mutating contract by construction; mutations funnel through `writePreferenceTxn` (revision bump, content-hash, edit-history hook in one place).+ - Pro: reconciliation as domain-partitioned single pass falls out naturally from per-domain detector modules — no sub-agents.+ - Con: more files and a shared "finding" type that both doctor and the remediation planner consume.+ - Con: slightly more upfront wiring than Variant 1.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Unified findings-as-data detector/repair registry+- **Approach**: Model every detector — existing structural `check*` plus the six new ones — as a uniform `Finding` producer registered in an ordered registry; `doctor.ts` becomes a thin runner that executes registered detectors and collects a single `Finding` stream. Remediation is a separate consumer mapping `Finding.kind` → deterministic repair handlers via a second registry, and reconciliation/verdict become group-by projections over the same stream.+- **Trade-offs**:+ - Pro: maximally extensible and uniform — future detectors, remediation, and reconciliation are all projections over one data contract.+ - Pro: dry-run, step-cap, and auto-safe/needs-review classification become clean filters over the planned `Finding`→repair mapping.+ - Con: requires retrofitting the already-shipped structural `check*` helpers into the `Finding` contract — real regression risk to v0.12 integrity checks for no functional gain.+ - Con: introduces a registry/abstraction layer heavier than anything currently in the codebase (over-engineering for six features).+ - Con: registry iteration order must be explicitly pinned or determinism across peers breaks.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 2+**Rationale**: It matches the project's established "pure core modules + thin MCP/CLI shell" convention and directly mirrors the `assess-rule-quality.ts` gate pattern, while keeping `brain_doctor` non-mutating by isolating the remediation engine and funneling every write through the existing `preference-txn` chokepoint. The per-domain detector modules give free independent gating and make the single-pass partitioned reconciliation natural, without the regression risk of retrofitting shipped structural checks (Variant 3) or the file-size and contract-blur problems of cramming mutation into `doctor.ts` (Variant 1).diff --git a/docs/brainstorm/semantic-brain-health/cli-output/prompt.md b/docs/brainstorm/semantic-brain-health/cli-output/prompt.mdnew file mode 100644index 00000000..3f37e966--- /dev/null+++ b/docs/brainstorm/semantic-brain-health/cli-output/prompt.md@@ -0,0 +1,65 @@+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++Build a "Semantic Brain Health & Self-Maintenance" bundle for Open Second Brain. Today `brain_doctor` validates only structural vault invariants (frontmatter validity, duplicate IDs, ISO parsing, dangling wikilinks, duplicate-preference near-dupes, content-hash drift). It does NO semantic-level auditing, and it cannot fix anything it finds. The bundle adds a semantic quality gate plus deterministic self-maintenance:++1. Cross-preference contradiction detection: surface pairs of CONFIRMED preferences that are about the same subject but carry an opposite "sign of record" (positive vs negative). Must be language-agnostic — no negation word lists.+2. Concept-gap detection: terms that recur across the signal+preference corpus (frequency >= N) yet have no dedicated preference/page.+3. Stale-claim flagging: confirmed preferences whose newest supporting evidence is older than a configurable window.+4. Per-preference edit-history audit trail: append-only sidecar capturing one entry per content mutation {timestamp, agent, revision, field, before, after}, rendered as a timeline on demand.+5. Dependency-ordered remediation plan with dry-run: doctor computes an ordered repair plan from its own findings, classifies each step auto-safe (deterministic) vs needs-review, applies only auto-safe fixes outside dry-run, and refuses past a bounded step cap. NO paid LLM jobs, NO background worker — purely local deterministic repairs.+6. Semantic-health aggregate surface ("truth reconciliation"): run the semantic detectors as distinct domains (preferences / evidence / retirement) and return one structured verdict in a single deterministic pass (NOT spawning sub-agents).++# Project context++Open Second Brain — TypeScript + Bun, Obsidian-vault-backed agent memory. Vault is plain markdown synced across peers via Syncthing; determinism is load-bearing (same vault must hash/rank/flag identically on every peer). Just shipped v0.13.0 (hybrid search & recall suite) with the same in-place-extension-of-pure-modules style.++Recent commits:+2147640 v0.13.0 - Hybrid Search and Recall Quality+84886d1 v0.12.0 - Brain Integrity Suite: typed collision detection, content-hash drift, durable dream workruns+c002268 v0.11.0 - Brain-centric vault layout+a8d4803 v0.10.18 - temporal axis: timeline, belief evolution, stale watch, daily brief, weekly synthesis+3b7dfe9 v0.10.16 - trust and operator surfaces - verification, verdict, dashboard++Related files (existing primitives to reuse, DRY):+- src/core/brain/doctor.ts (1088 lines): runDoctor() -> RunDoctorResult { issues: DoctorIssue[]{severity:"warning"|"error", kind, message}, trustVerdict, ... }. Lint functions are private `check*` helpers appended to an issues array. Already has checkDuplicatePreferences (jaccard 0.7), checkContentHashDrift, checkLowEvidenceConfirmed, checkPinnedWithoutRecentEvidence, readAllPreferenceRecords, readAllLogRecords. Never mutates state today.+- src/core/brain/similarity.ts (84 lines): tokenise(text) (language-agnostic, no stopwords), jaccard(a,b), findSimilarPairs(entries, {threshold}) bucket-and-pair walk. Already shared by doctor + merge-candidates.+- src/core/brain/dream.ts (1904 lines): the learning pass. Has the "sign of record" derivation — a preference's sign (positive/negative) is the dominant sign of the signals in its evidenced_by; falls back to topic signals. contradictionTopics is tracked when both polarities appear for a topic with no active pref. BRAIN_SIGNAL_SIGN = {positive, negative}.+- src/core/brain/preference-txn.ts (285 lines): writePreferenceTxn() — THE single chokepoint for every preference write (direct + dream). Runs an expectations chain under a sync lock, then computes smart defaults (_content_hash on confirm, monotonic _revision bumped only when wouldRewritePreference says bytes change), then delegates to writePreference. willChange is already computed here.+- src/core/brain/preference.ts (1135 lines): parsePreference, writePreference, wouldRewritePreference. BrainPreference carries principle, scope, topic, status, revision, content_hash, last_evidence_at, _applied_count, _violated_count.+- src/core/brain/temporal/stale-watch.ts (208 lines): file-mtime-based staleness (different axis than evidence-age staleness).+- src/core/brain/trust/assess-rule-quality.ts (129 lines): language-agnostic structural quality gate returning {score, severity: ok|warn|reject, reasons}. Pattern to mirror.+- src/mcp/brain-tools.ts (1880 lines): MCP tool handlers (brain_doctor, brain_query, brain_review_candidates, ...).+- src/cli/brain/verbs/doctor.ts, dream.ts: CLI verb wrappers.++Conventions:+- Language-agnostic by construction: no stopword lists, no negation dictionaries, no per-language vocab. Codepoint-shape and structural signals only (\p{L}, \p{N}, polarity sign, token overlap, counts, ages).+- Determinism: identical vault -> identical output on every peer. No wall-clock except injected `now`. No network in core.+- Pure core modules + a thin store/IO boundary; MCP and CLI are thin shells over core.+- Graceful per-layer degrade; each detector independently skippable/config-gated.+- New artifacts excluded from the search index by default when they are bookkeeping sidecars.++Constraints:+- Do NOT add external dependencies.+- Do NOT introduce a background-job/worker system or any paid LLM call in remediation — repairs must be local and deterministic.+- Do NOT spawn sub-agents for the "reconciliation" feature — single deterministic pass with domain partitioning.+- brain_doctor must remain non-mutating by default; remediation is an explicit opt-in path.+- Reuse similarity.ts and the preference-txn chokepoint rather than re-implementing token/diff/write logic.++# 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/semantic-brain-health/design.md b/docs/brainstorm/semantic-brain-health/design.mdnew file mode 100644index 00000000..caf1c3c3--- /dev/null+++ b/docs/brainstorm/semantic-brain-health/design.md@@ -0,0 +1,70 @@+# Semantic Brain Health & Self-Maintenance - design++**Status:** draft+**Author:** claude-vps-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++`brain_doctor` today validates only structural vault invariants (frontmatter validity, duplicate IDs, ISO parsing, dangling wikilinks, near-duplicate preferences, content-hash drift) and never mutates state. It cannot tell when two confirmed preferences contradict each other, when a recurring concept has no home, or when a confirmed rule is running on stale evidence - and it cannot repair anything it finds. As a vault grows, contradictory preferences and orphaned signals accumulate silently. This bundle turns the doctor into a genuine semantic quality gate and adds a bounded, deterministic self-maintenance path.++## Scope++- **F1 - Cross-preference contradiction detection.** Surface pairs of confirmed preferences about the same subject that carry an opposite sign of record (positive vs negative). Language-agnostic: pairing uses token overlap (`similarity.ts`); polarity uses the sign derived from each preference's `evidenced_by` signals - never a negation word list.+- **F2 - Concept-gap detection.** Entities that recur across the signal + preference corpus at or above a configured frequency yet have no dedicated preference topic. Reuses the v0.13.0 language-agnostic entity extractor so lowercase function words ("the", "use") never surface without needing a stopword list.+- **F3 - Stale-claim flagging.** Confirmed preferences whose newest supporting evidence (`last_evidence_at`) is older than a configured age window relative to the injected clock.+- **F4 - Per-preference edit-history audit trail.** Append-only `Brain/preferences/<slug>.history.jsonl` sidecar capturing one entry per content mutation `{ts, agent, revision, field, before, after}`. Written from the `writePreferenceTxn` chokepoint; rendered as a timeline on demand. Excluded from the search index.+- **F5 - Dependency-ordered remediation with dry-run.** A standalone planner turns doctor findings into an ordered repair plan, classifies each step `auto-safe` (deterministic) vs `needs-review`, applies only auto-safe steps outside dry-run through `writePreferenceTxn`, and refuses past a bounded step cap. No background worker, no paid LLM call.+- **F6 - Semantic-health reconciliation surface.** A single deterministic pass that runs the three detectors partitioned into domains (preferences / evidence / retirement) and returns one structured report plus a verdict. No sub-agent spawning.+- MCP + CLI surfaces for the above (`brain_health` tool, `o2b brain health`, `o2b brain doctor --remediate [--dry-run]`, `o2b brain history <slug>`).++## Out of scope++- Background-job / minion worker systems and any paid LLM remediation (explicitly excluded by the upstream-task constraints).+- Sub-agent spawning for reconciliation (upstream does this; we do a single deterministic pass instead).+- Vector / semantic-embedding contradiction detection - we stay structural and dependency-free.+- Multi-vault or cross-agent reconciliation.++## Chosen approach++Variant 2 (consultant recommendation, adopted): a new pure-core module layer `src/core/brain/health/` with one detector module per concern, a reconciliation aggregator, an edit-history sidecar reader/writer, and a standalone remediation engine. `doctor.ts` stays non-mutating - it calls the detectors best-effort (one `try` boundary each, mirroring the existing hygiene lints) and merges their findings into its `warnings`/`errors` stream and an optional semantic-health report. Every mutation funnels through the existing `writePreferenceTxn` chokepoint, so revision bump, content-hash bookkeeping, and the new edit-history append all happen in one place.++This mirrors the shipped `assess-rule-quality.ts` pure-gate pattern and the "pure core + thin MCP/CLI shell" convention, and avoids both the non-mutating-contract blur of cramming `remediate()` into `doctor.ts` (Variant 1) and the regression risk of retrofitting the v0.12 structural `check*` helpers into a new findings registry (Variant 3).++## Design decisions++- **Polarity without a dictionary.** A confirmed preference's sign is the dominant sign of the signals in its `evidenced_by` (the same "sign of record" derivation `dream.ts` already uses). Contradiction = same `(scope)` bucket + principle jaccard >= threshold + opposite sign. Extract the dominant-sign helper so detector and dream share one definition (DRY); fall back to "unknown" sign when no evidence resolves, and skip unknown-sign preferences rather than guess.+- **Concept-gap is frequency-only.** Count multi-codepoint tokens across signal + preference principles; a term at or above `min_frequency` with no preference whose `topic` or principle contains it is a gap. No notion of "importance" beyond raw recurrence - deterministic and language-blind.+- **Edit-history is convergent under sync.** The sidecar is append-only but `appendEditHistory` is idempotent per `(revision, field, after)`: an entry whose triple already exists is not duplicated. Two Syncthing peers that both replay the same write therefore converge instead of diverging. The `.history.jsonl` sidecar never enters the search index because the walker only yields `.md` files - no extra ignore rule is needed (and the ignore system matches names/paths, not globs).+- **Remediation ordering is explicit and deterministic.** Steps are emitted in a fixed dependency order (bookkeeping fixes before semantic ones) and sorted by a stable key, so the same findings always yield the same plan on every peer. The only `auto-safe` action this release is the content-hash re-stamp - a lossless, reversible re-derivation of bookkeeping from authoritative content that needs no human judgment. Contradictions, stale claims, and concept gaps are always `needs-review`. The auto-safe set is deliberately minimal; widening it later (e.g. orphan-artifact cleanup) is additive.+- **Doctor stays non-mutating; remediation is opt-in.** `runDoctor` never writes. `planRemediation` is pure. `applyRemediation` is the only writer and honors `dryRun` + `stepCap`.+- **Best-effort detector boundaries.** Each detector is wrapped in its own `try` inside `doctor.ts` so one broken scan cannot mask the others, matching the existing hygiene-lint convention.++## File changes++**New (`src/core/brain/health/`):**+- `contradiction.ts` - `detectContradictions(...)`, pure.+- `concept-gap.ts` - `detectConceptGaps(...)`, pure.+- `stale-claim.ts` - `detectStaleClaims(...)`, pure.+- `reconcile.ts` - `reconcileSemanticHealth(...)` domain-partitioned single pass + verdict.+- `edit-history.ts` - `appendEditHistory`, `readEditHistory`, `renderEditHistory`, types.+- `remediation.ts` - `planRemediation` (pure) + `applyRemediation` (writer via txn).+- `sign.ts` - shared dominant-sign-of-record helper extracted from `dream.ts` (or a thin re-export if a helper already exists).++**Modified:**+- `doctor.ts` - call the three detectors best-effort, merge findings, attach optional `semantic_health` to `RunDoctorResult`.+- `preference-txn.ts` - on `willChange`, diff `ctx.existing` vs proposed and append edit-history (idempotent).+- `dream.ts` - use the extracted `sign.ts` helper (no behavior change).+- `types.ts` - finding/report/edit-history types, new `DoctorIssue` codes.+- brain config - a new `health` section on `BrainConfig` (`src/core/brain/types.ts`) with defaults in `DEFAULT_BRAIN_CONFIG` and parsing in the loader (`src/core/brain/policy.ts`): `contradiction_jaccard`, `concept_gap_min_frequency`, `stale_claim_max_age_days`, `remediation_step_cap`.+- `src/mcp/brain-tools.ts` - `brain_health` tool; extend `brain_doctor` output.+- `src/cli/brain/verbs/` - `health.ts`, `history.ts`, `doctor.ts` (`--remediate`, `--dry-run`).+- `src/core/brain/index.ts` / barrel exports.+- README, CHANGELOG, docs/*.++## Risks and open questions++- **Sign derivation cost.** Resolving `evidenced_by` for every confirmed pref means indexing signals once per doctor run; reuse the single snapshot pattern already in `doctor.ts` to avoid re-parsing.+- **Edit-history backfill.** Existing preferences have no history file; the first mutation after upgrade seeds the trail from the current state. No retroactive reconstruction (documented, not a bug).+- **Edit-history coverage is the txn chokepoint.** The trail is recorded by `writePreferenceTxn`, which the dream pass routes every promotion / refresh / retirement through - so the automated lifecycle is fully captured. Operator-forced direct writes that bypass the txn (e.g. `brain feedback --force_confirmed`, the merge writer) do not yet thread the history option and so are not recorded. This is a known limitation of the current write routing, not a defect in the trail; widening coverage is a follow-up once those writers move onto the txn.+- **Auto-safe conservatism.** Initial release keeps the auto-safe set deliberately small; expanding it later is additive. Better to under-fix than to auto-mutate something needing judgment.diff --git a/docs/brainstorm/semantic-brain-health/plan.md b/docs/brainstorm/semantic-brain-health/plan.mdnew file mode 100644index 00000000..41e5f593--- /dev/null+++ b/docs/brainstorm/semantic-brain-health/plan.md@@ -0,0 +1,62 @@+# Semantic Brain Health & Self-Maintenance - implementation plan++Each task is one atomic unit, implemented RED-GREEN-REFACTOR on the+`feat/semantic-brain-health` branch, one conventional commit per task.+Detectors are pure and land before the surfaces that consume them.++## Tasks++### Task 1: Shared sign-of-record helper+- **Files**: `src/core/brain/health/sign.ts`, extract from `src/core/brain/dream.ts`; `tests/core/brain/health/sign.test.ts`+- **Acceptance**: `dominantSign(evidencedBy, signalsById)` returns `positive | negative | unknown` matching dream's existing derivation; dream.ts uses it with no behavior change (existing dream tests stay green).+- **Depends on**: none++### Task 2: Contradiction detector (F1)+- **Files**: `src/core/brain/health/contradiction.ts`; `tests/core/brain/health/contradiction.test.ts`+- **Acceptance**: `detectContradictions(prefs, signalsById, {jaccard})` returns findings for same-scope confirmed pref pairs with principle jaccard >= threshold and opposite resolved sign; skips unknown-sign prefs; deterministic ordering (a.id < b.id).+- **Depends on**: Task 1++### Task 3: Concept-gap detector (F2)+- **Files**: `src/core/brain/health/concept-gap.ts`; `tests/core/brain/health/concept-gap.test.ts`+- **Acceptance**: `detectConceptGaps(corpus, {minFrequency})` counts multi-codepoint tokens across signal + preference principles and returns terms at/above frequency with no covering preference topic/principle; language-agnostic; stable order (frequency desc, then term).+- **Depends on**: none++### Task 4: Stale-claim detector (F3)+- **Files**: `src/core/brain/health/stale-claim.ts`; `tests/core/brain/health/stale-claim.test.ts`+- **Acceptance**: `detectStaleClaims(prefs, {maxAgeDays, now})` flags confirmed prefs whose `last_evidence_at` is older than the window; injectable `now`; prefs without evidence date are skipped (reported elsewhere).+- **Depends on**: none++### Task 5: Edit-history sidecar (F4)+- **Files**: `src/core/brain/health/edit-history.ts`; `tests/core/brain/health/edit-history.test.ts`+- **Acceptance**: `appendEditHistory` writes one JSONL line per `(revision, field)` change and is idempotent (re-append of same revision+field+after is a no-op); `readEditHistory` round-trips; `renderEditHistory` produces a deterministic timeline; malformed lines are skipped.+- **Depends on**: none++### Task 6: Wire edit-history into the write chokepoint (F4)+- **Files**: `src/core/brain/preference-txn.ts`; `tests/core/brain/preference-txn-history.test.ts`+- **Acceptance**: a `writePreferenceTxn` call that changes bytes appends field-level before/after entries; a no-op rewrite appends nothing; first write after upgrade seeds from current state; search-index ignore covers `*.history.jsonl`.+- **Depends on**: Task 5++### Task 7: Reconciliation surface (F6)+- **Files**: `src/core/brain/health/reconcile.ts`; `tests/core/brain/health/reconcile.test.ts`+- **Acceptance**: `reconcileSemanticHealth(...)` runs the three detectors partitioned into domains and returns `{ domains: {...}, verdict }` in a single deterministic pass; verdict escalates clean -> watch -> investigate by finding severity/count.+- **Depends on**: Tasks 2, 3, 4++### Task 8: Doctor integration+- **Files**: `src/core/brain/doctor.ts`, `src/core/brain/types.ts`; `tests/core/brain/doctor-semantic.test.ts`+- **Acceptance**: `runDoctor` calls the three detectors best-effort, merges findings as warnings with new codes (`contradictory-preferences`, `concept-gap`, `stale-claim`), and attaches an optional `semantic_health` report; a broken detector cannot mask others; clean vault stays clean.+- **Depends on**: Tasks 2, 3, 4, 7++### Task 9: Remediation planner + executor (F5)+- **Files**: `src/core/brain/health/remediation.ts`; `tests/core/brain/health/remediation.test.ts`+- **Acceptance**: `planRemediation(findings, {stepCap})` emits a deterministically-ordered plan with `auto-safe | needs-review` classification; `applyRemediation(vault, plan, {dryRun})` mutates nothing under `dryRun`, applies only auto-safe steps through `writePreferenceTxn` otherwise, and stops at `stepCap`.+- **Depends on**: Task 8++### Task 10: MCP + CLI surfaces+- **Files**: `src/mcp/brain-tools.ts`, `src/cli/brain/verbs/health.ts`, `src/cli/brain/verbs/history.ts`, `src/cli/brain/verbs/doctor.ts`, barrel exports; `tests/mcp/brain-health.test.ts`, `tests/cli/brain-health.test.ts`+- **Acceptance**: `brain_health` MCP tool returns the reconcile report; `o2b brain health`, `o2b brain history <slug>`, and `o2b brain doctor --remediate [--dry-run]` work end-to-end against a temp vault.+- **Depends on**: Tasks 7, 8, 9++### Task 11: Config thresholds+- **Files**: brain config schema + loader, defaults; `tests/core/brain/config-health.test.ts`+- **Acceptance**: `contradiction_jaccard`, `concept_gap_min_frequency`, `stale_claim_max_age_days`, `remediation_step_cap` parse with safe defaults and feed the detectors; absent config falls back to defaults without throwing.+- **Depends on**: Tasks 2, 3, 4, 9diff --git a/docs/brainstorm/semantic-brain-health/variants.md b/docs/brainstorm/semantic-brain-health/variants.mdnew file mode 100644index 00000000..ddc8a1db--- /dev/null+++ b/docs/brainstorm/semantic-brain-health/variants.md@@ -0,0 +1,72 @@+# Semantic Brain Health & Self-Maintenance - variant audit trail++Consultant: Claude Code CLI (primary). Codex fallback not invoked - the+primary returned three parseable variants with a recommendation.+Raw output preserved at `cli-output/claude.md`; prompt at+`cli-output/prompt.md`.++## Variants (verbatim from the consultant)++### Variant 1: In-place extension of doctor.ts+Add each semantic detector as a new private `check*` helper appended to+`doctor.ts`, reusing the existing record readers / `similarity.ts` and+pushing `DoctorIssue`s onto the same array; reconciliation is a grouping+pass over those issues; edit-history and `remediate()` added beside it.+- Complexity: medium - Risk: medium+- Pro: maximal DRY; matches recent in-place style; fastest path.+- Con: `doctor.ts` (~1088 lines) would approach ~2000, mixing structural+ and semantic concerns; mutation next to a "never mutates" module blurs+ the contract; per-detector gating/testing awkward in one body.++### Variant 2: Semantic-health module layer with a separate remediation engine+`src/core/brain/health/` with one pure detector per concern, a+`reconcile.ts` domain-partitioned aggregator, an append-only+`edit-history.ts` sidecar, and a standalone `remediation.ts`+planner+executor. `doctor.ts` calls the detectors and merges findings,+staying non-mutating; remediation routes auto-safe fixes through the+`preference-txn` chokepoint.+- Complexity: medium - Risk: low+- Pro: clean structural/semantic separation; each detector independently+ skippable, config-gated, unit-testable; mirrors `assess-rule-quality.ts`+ and the pure-core+thin-shell convention; remediation isolation preserves+ the doctor non-mutating contract by construction; reconciliation falls+ out naturally; no sub-agents.+- Con: more files and a shared finding type; slightly more wiring than V1.++### Variant 3: Unified findings-as-data detector/repair registry+Model every detector (existing structural + the six new) as a uniform+`Finding` producer in an ordered registry; `doctor.ts` becomes a thin+runner; remediation and reconciliation are projections over one stream.+- Complexity: large - Risk: high+- Pro: maximally extensible/uniform; dry-run, step-cap, and+ auto-safe/needs-review classification become clean filters.+- Con: requires retrofitting shipped structural `check*` helpers into the+ contract - real regression risk to v0.12 integrity checks for no+ functional gain; registry abstraction heavier than anything in the+ codebase; iteration order must be pinned or determinism breaks.++## Consultant recommendation++**Variant 2.** Matches the pure-core + thin-shell convention and the+`assess-rule-quality.ts` gate pattern, keeps `brain_doctor` non-mutating+by isolating remediation and funneling writes through `preference-txn`,+gives free per-detector gating and a natural single-pass reconciliation,+and avoids the regression risk of V3 and the contract-blur/file-size+problems of V1.++## Orchestrator decision++**Adopt Variant 2 as recommended.** It is the only option that keeps the+doctor's shipped non-mutating invariant intact while adding mutation, and+it reuses the existing chokepoint (`writePreferenceTxn`) so revision bump,+content-hash, and the new edit-history append all stay in one place. No+override needed.++One refinement layered on top of the consultant's sketch: the new+detectors are still **surfaced through `doctor.ts`** (so `o2b brain+doctor` shows semantic findings alongside structural ones, best-effort+per-detector `try` boundaries) rather than living only behind a separate+command - this matches operator expectations and the existing hygiene-lint+wiring. A shared `sign.ts` helper is extracted from `dream.ts` so the+contradiction detector and the dream pass agree on one polarity+definition (DRY), instead of the detector re-deriving sign independently.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 5b33a9d6..2ec30ae7 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -41,7 +41,9 @@ o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshoo2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yeso2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode).-o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...)+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 backlinks List inbound references to a Brain artifact ido2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yamlo2b brain import-session Replay signals from a Claude / Codex / Hermes session .jsonl (or directory)diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 67425e5d..297f23e3 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -383,7 +383,9 @@ are mirrored in MCP; destructive operations are CLI-only by design.| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections || Inspect state | `o2b brain query` | `brain_query` | read-only || Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |-| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; six lint rules |+| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; structural lints + semantic-health findings; `--remediate [--dry-run]` applies auto-safe content-hash re-stamps |+| Semantic health | `o2b brain health` | `brain_health` | read-only; contradictions, concept gaps, stale claims + clean/watch/investigate verdict |+| Preference edit-history | `o2b brain history <slug>` | — (CLI-only) | read-only; one entry per content mutation (principle / scope / status before -> after) || Full-text search | `o2b search "<query>"` | `brain_search` | read-only; FTS5 + optional semantic || Manage search index | `o2b search index \| reindex \| status \| check` | — (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) || Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | — (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) |@@ -522,8 +524,10 @@ through `src/core/redactor.ts` (promoted from Pay Memory) plus afield" error branch, so the writer never persists a placeholdersignal.-**Doctor lints** (`o2b brain doctor`, `brain_doctor` MCP). All six are-pure functions over the on-disk Brain state — no LLM, no network:+**Doctor lints** (`o2b brain doctor`, `brain_doctor` MCP). All are pure+functions over the on-disk Brain state — no LLM, no network. The first+group are structural; the last three (v0.14.0) are semantic and also+populate the `semantic_health` report (see `brain_health` below):| Code | Triggers when ||---|---|@@ -533,11 +537,17 @@ pure functions over the on-disk Brain state — no LLM, no network:| `pinned-without-recent-evidence` | `pinned: true` with no evidence or evidence older than `stale_evidence_days` || `malformed-evidence-range` | `apply-evidence` `artifact` uses `[[file:…]]` range syntax but fails validation (`:abc-def`, `:120-100`, bare `:`) || `orphan-evidence` | `apply-evidence` `artifact` wikilink does not resolve to any file in the vault |+| `contradictory-preferences` | two confirmed preferences share a subject (principle Jaccard ≥ `health.contradiction_jaccard`) but carry an opposite sign of record |+| `concept-gap` | an entity recurs across ≥ `health.concept_gap_min_frequency` corpus entries with no covering preference topic |+| `stale-claim` | a confirmed preference's newest evidence is older than `health.stale_claim_max_age_days` |With `--strict`, warnings demote `ok` to `false` so CI can gate on-hygiene. The lints are read-only — `brain_doctor --fix` is explicitly-out of scope because auto-modifying state runs against the-"explicit-driven" invariant.+hygiene. `brain_doctor` itself stays read-only — auto-modifying state on+a plain doctor run would break the "explicit-driven" invariant. The+explicit opt-in `o2b brain doctor --remediate [--dry-run]` is the only+writer: it plans a dependency-ordered repair and applies the auto-safe+fixes (currently the lossless content-hash re-stamp), bounded by+`health.remediation_step_cap`.```mermaidflowchart LRdiff --git a/docs/mcp.md b/docs/mcp.mdindex 5c3e434b..998c44c2 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -244,7 +244,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 (31 tools); 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 (33 tools, including `brain_health` since v0.14.0); 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 four tools: `brain_feedback`, `brain_apply_evidence`, `brain_note` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md`, v0.10.10). The agent records taste signals, evidence events, and milestone notes - 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.jsonindex 325d5dd3..5800c310 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.13.0",+ "version": "0.14.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex ad44a945..d15fbb9c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.13.0",+ "version": "0.14.0","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex b62b1ef8..2388074c 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.13.0"+version: "0.14.0"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex d58538e8..02ae7d6d 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.13.0",+ "version": "0.14.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.yamlindex 2730e996..11c923a4 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.13.0"+version: "0.14.0"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 46d192ad..ca0cb9b3 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.13.0"+version = "0.14.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.tsindex 5b576667..cf795508 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -24,6 +24,8 @@ import {cmdBrainUnprotect,cmdBrainRollback,cmdBrainDoctor,+ cmdBrainHealth,+ cmdBrainHistory,cmdBrainBacklinks,cmdBrainMerge,cmdBrainExplorer,@@ -82,6 +84,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promiscase "snapshot": return await handleBrainSnapshotSubcommand(rest);case "rollback": return await cmdBrainRollback(rest);case "doctor": return await cmdBrainDoctor(rest);+ case "health": return await cmdBrainHealth(rest);+ case "history": return await cmdBrainHistory(rest);case "backlinks": return await cmdBrainBacklinks(rest);case "scan-inline": return await cmdBrainScanInline(rest);case "import-session": return await cmdBrainImportSession(rest);diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex c1bc5983..1d9e0486 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -30,7 +30,9 @@ Brain verbs (observing memory):snapshot diff Read-only diff between two snapshots, or snapshot vs liverollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;--dry-run previews via the same diff renderer)- doctor Validate Brain invariants (--strict promotes warnings to exit 2)+ doctor Validate Brain invariants (--strict; --remediate [--dry-run])+ health Semantic-health report: contradictions, concept gaps, stale claims+ history Render a preference's edit-history timelinebacklinks List inbound references to a Brain artifact idscan-inline Capture @osb markers from folders listed under notes.read_paths in _brain.yamlimport-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)@@ -118,7 +120,19 @@ export const VERB_HELP: Record<string, string> = {"the live Brain/ tree (when <run_id_b> is omitted).\n",doctor:"usage: o2b brain doctor [--vault <path>] [--json] [--strict]\n" +- "Validate invariants. Warnings exit 0 (or 2 with --strict). Errors always exit 1.\n",+ " [--remediate [--dry-run]]\n" ++ "Validate invariants. Warnings exit 0 (or 2 with --strict). Errors always exit 1.\n" ++ "--remediate builds a dependency-ordered repair plan and applies the\n" ++ "auto-safe steps (content-hash re-stamp); --dry-run previews without writing.\n",+ health:+ "usage: o2b brain health [--vault <path>] [--json]\n" ++ "Semantic-health report: contradictory confirmed preferences, recurring\n" ++ "concepts with no dedicated preference, and confirmed preferences on stale\n" ++ "evidence, plus a clean/watch/investigate verdict. Read-only.\n",+ history:+ "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",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/doctor.ts b/src/cli/brain/verbs/doctor.tsindex 6b21de46..3da92edf 100644--- a/src/cli/brain/verbs/doctor.ts+++ b/src/cli/brain/verbs/doctor.ts@@ -1,5 +1,11 @@import { defaultConfigPath } from "../../../core/config.ts";import { runDoctor } from "../../../core/brain/doctor.ts";+import {+ applyRemediation,+ collectDriftedSlugs,+ planRemediation,+} from "../../../core/brain/health/remediation.ts";+import { loadBrainConfigDetailed, resolveHealth } from "../../../core/brain/policy.ts";import { parse, fail, ok, resolveBrainVault } from "../helpers.ts";export async function cmdBrainDoctor(argv: string[]): Promise<number> {@@ -7,6 +13,8 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {vault: { type: "string" },strict: { type: "boolean" },json: { type: "boolean" },+ remediate: { type: "boolean" },+ "dry-run": { type: "boolean" },});const config = defaultConfigPath();const vault = resolveBrainVault(flags["vault"] as string | undefined, config);@@ -15,6 +23,22 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {try { result = runDoctor(vault, { strict: Boolean(flags["strict"]) }); }catch (exc) { return fail(`doctor failed: ${(exc as Error).message ?? exc}`); }+ if (flags["remediate"]) {+ // Never auto-repair a vault that has structural errors - those need+ // an operator, and remediation assumes a parseable tree.+ if (result.errors.length > 0) {+ for (const e of result.errors) {+ process.stdout.write(`[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`);+ }+ return fail("doctor found errors; remediation aborted");+ }+ try {+ return runRemediate(vault, Boolean(flags["dry-run"]), Boolean(flags["json"]), result);+ } catch (exc) {+ return fail(`remediation failed: ${(exc as Error).message ?? exc}`);+ }+ }+if (flags["json"]) {process.stdout.write(JSON.stringify({ warnings: result.warnings, errors: result.errors }, null, 2) + "\n");} else {@@ -27,3 +51,51 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {if (result.warnings.length > 0 && flags["strict"]) return 2;return 0;}++/**+ * `--remediate [--dry-run]`: build a dependency-ordered plan from the+ * doctor's semantic findings plus content-hash drift, then apply the+ * auto-safe steps (or preview them under `--dry-run`). Needs-review+ * steps are always listed but never applied.+ */+function runRemediate(+ vault: string,+ dryRun: boolean,+ json: boolean,+ result: ReturnType<typeof runDoctor>,+): number {+ let stepCap = 20;+ try {+ stepCap = resolveHealth(loadBrainConfigDetailed(vault).config).remediation_step_cap;+ } catch { /* fall back to default cap */ }++ const sh = result.semantic_health;+ const plan = planRemediation(+ {+ driftedSlugs: collectDriftedSlugs(vault),+ contradictions: (sh?.contradictions ?? []).map((c) => ({ aId: c.aId, bId: c.bId })),+ staleClaims: (sh?.staleClaims ?? []).map((s) => ({ id: s.id })),+ conceptGaps: (sh?.conceptGaps ?? []).map((g) => ({ term: g.term })),+ },+ { stepCap },+ );+ const outcome = applyRemediation(vault, plan, { dryRun });++ if (json) {+ process.stdout.write(JSON.stringify({ plan: plan.steps, outcome }, null, 2) + "\n");+ return 0;+ }++ const verb = dryRun ? "would apply" : "applied";+ for (const s of outcome.applied) {+ process.stdout.write(`[${verb}] ${s.code}: ${s.detail}\n`);+ }+ for (const s of outcome.skipped) {+ process.stdout.write(`[skip:${s.classification}] ${s.code}: ${s.detail}\n`);+ }+ ok(+ `remediation ${dryRun ? "dry-run" : "complete"}: ` ++ `${outcome.applied.length} ${verb}, ${outcome.skipped.length} skipped`,+ );+ return 0;+}diff --git a/src/cli/brain/verbs/health.ts b/src/cli/brain/verbs/health.tsnew file mode 100644index 00000000..08cf432a--- /dev/null+++ b/src/cli/brain/verbs/health.ts@@ -0,0 +1,68 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { runDoctor } from "../../../core/brain/doctor.ts";+import { fail, ok, parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain health` - print the semantic-health report (contradictory+ * preferences, recurring uncovered concepts, stale claims) plus the+ * clean/watch/investigate verdict. Read-only.+ */+export async function cmdBrainHealth(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ let result;+ try {+ result = runDoctor(vault);+ } catch (exc) {+ return fail(`health failed: ${(exc as Error).message ?? exc}`);+ }++ // Structural errors mean the tree is not trustworthy enough to report+ // a semantic verdict on - surface them and fail rather than print a+ // misleading "clean".+ if (result.errors.length > 0) {+ for (const e of result.errors) {+ process.stdout.write(`[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`);+ }+ return 1;+ }++ const sh = result.semantic_health ?? {+ verdict: "clean" as const,+ contradictions: [],+ conceptGaps: [],+ staleClaims: [],+ };++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(sh, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`verdict: ${sh.verdict}\n`);+ for (const c of sh.contradictions) {+ process.stdout.write(+ `[contradiction] ${c.aId} (${c.aSign}) vs ${c.bId} (${c.bSign})` ++ `${c.scope ? ` scope=${c.scope}` : ""} jaccard=${c.jaccard.toFixed(2)}\n`,+ );+ }+ for (const g of sh.conceptGaps) {+ process.stdout.write(`[concept-gap] ${g.term} (x${g.frequency})\n`);+ }+ for (const s of sh.staleClaims) {+ process.stdout.write(`[stale-claim] ${s.id} (${s.ageDays}d since ${s.lastEvidenceAt})\n`);+ }+ if (+ sh.contradictions.length === 0 &&+ sh.conceptGaps.length === 0 &&+ sh.staleClaims.length === 0+ ) {+ ok("brain health: clean");+ }+ return 0;+}diff --git a/src/cli/brain/verbs/history.ts b/src/cli/brain/verbs/history.tsnew file mode 100644index 00000000..3f04a539--- /dev/null+++ b/src/cli/brain/verbs/history.ts@@ -0,0 +1,38 @@+import { defaultConfigPath } from "../../../core/config.ts";+import {+ readEditHistory,+ renderEditHistory,+} from "../../../core/brain/health/edit-history.ts";+import { fail, parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain history <slug>` - render a preference's edit-history+ * timeline (one entry per content mutation). A leading `pref-` on the+ * argument is tolerated. Read-only.+ */+export async function cmdBrainHistory(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 history <slug>");+ const slug = raw.replace(/^pref-/, "");++ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ let entries;+ try {+ entries = readEditHistory(vault, slug);+ } catch (exc) {+ return fail(`history failed: ${(exc as Error).message ?? exc}`);+ }++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(entries, null, 2) + "\n");+ } else {+ process.stdout.write(renderEditHistory(entries) + "\n");+ }+ return 0;+}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 7bed78f2..99167c4a 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -11,6 +11,8 @@ export { cmdBrainSetPrimary } from "./set-primary.ts";export { cmdBrainProtect, cmdBrainUnprotect } from "./protect.ts";export { cmdBrainRollback } from "./rollback.ts";export { cmdBrainDoctor } from "./doctor.ts";+export { cmdBrainHealth } from "./health.ts";+export { cmdBrainHistory } from "./history.ts";export { cmdBrainBacklinks } from "./backlinks.ts";export { cmdBrainMerge } from "./merge.ts";export { cmdBrainExplorer } from "./explorer.ts";diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 2d01d985..88190d1f 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -48,8 +48,10 @@ import { parseLogDay } from "./log.ts";import {BRAIN_CONFIG_SUPPORTED_VERSIONS,BRAIN_GUARDRAIL_DEFAULTS,+ BRAIN_HEALTH_DEFAULTS,BrainConfigError,loadBrainConfigDetailed,+ resolveHealth,} from "./policy.ts";import { computeTrustVerdict } from "./trust/compute-trust-verdict.ts";import {@@ -63,12 +65,18 @@ import {parsePreference,parseRetired,} from "./preference.ts";+import {+ reconcileSemanticHealth,+ type PreferenceForHealth,+ type SemanticHealthReport,+} from "./health/reconcile.ts";import { parseSignal } from "./signal.ts";import { findSimilarPairs, tokenise } from "./similarity.ts";import {BRAIN_LOG_EVENT_KIND,BRAIN_PREFERENCE_STATUS,type BrainConfig,+ type ResolvedBrainHealthConfig,} from "./types.ts";import { normaliseWikilinkTarget, parseArtifactRef } from "./wikilink.ts";@@ -192,6 +200,13 @@ export interface RunDoctorResult {* helper is invoked.*/readonly uncertain?: ReadonlyArray<DoctorUncertainEntry>;+ /**+ * Semantic-health report (v0.14.0): contradiction / concept-gap /+ * stale-claim findings plus an escalating verdict. Absent only when+ * the vault has no Brain layer; otherwise present even on a clean+ * run (with empty domains and a `clean` verdict).+ */+ readonly semantic_health?: SemanticHealthReport;}// ----- Entry point ----------------------------------------------------------@@ -306,6 +321,17 @@ export function runDoctor(checkOrphanEvidence(vault, logRecords, issues);} catch { /* doctor never throws */ }+ // v0.14.0 semantic-health pass. Best-effort like every other lint:+ // a failure here must not poison the structural warning / error+ // stream. The report is attached to the result even on a clean run+ // (empty domains, `clean` verdict); it stays `undefined` only when+ // the pass threw.+ let semanticReport: SemanticHealthReport | undefined;+ try {+ const health = cfg ? resolveHealth(cfg) : BRAIN_HEALTH_DEFAULTS;+ semanticReport = checkSemanticHealth(vault, prefRecords, issues, health, now);+ } catch { /* doctor never throws */ }+// Partition by severity. Stable sort preserves discovery order which// is convenient for tests asserting on `path`+`code`.const warnings = issues.filter((i) => i.severity === "warning");@@ -349,9 +375,107 @@ export function runDoctor(? { verification_delta_summary: verificationCounts }: {}),instruction_file_warnings: instructionWarnings,+ ...(semanticReport !== undefined ? { semantic_health: semanticReport } : {}),});}+// ----- Semantic health (v0.14.0) --------------------------------------------++/** Minimal signal projection the semantic-health pass needs. */+interface SignalSignRecord {+ readonly id: string;+ readonly sign: import("./types.ts").BrainSignalSign;+ readonly principle: string;+}++/**+ * Read every `sig-*.md` across `inbox/` and `processed/`, projecting+ * each to its id, sign, and principle. Files that fail to parse are+ * skipped (their schema errors surface through {@link checkSignals}).+ */+function readAllSignalRecords(vault: string): ReadonlyArray<SignalSignRecord> {+ const dirs = brainDirs(vault);+ const out: SignalSignRecord[] = [];+ for (const dir of [dirs.inbox, dirs.processed]) {+ if (!existsSync(dir)) continue;+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md") || !name.startsWith("sig-")) continue;+ try {+ const sig = parseSignal(join(dir, name));+ out.push({ id: sig.id, sign: sig.signal, principle: sig.principle });+ } catch {+ // schema error - reported by checkSignals+ }+ }+ }+ return out;+}++/**+ * Run the semantic-health detectors, merge their findings into the+ * shared `issues` array as warnings, and return the structured report.+ * Confirmed preferences feed the contradiction and stale-claim passes;+ * signal + preference principles feed the concept-gap pass.+ */+function checkSemanticHealth(+ vault: string,+ prefRecords: ReadonlyArray<PreferenceRecord>,+ issues: DoctorIssue[],+ health: ResolvedBrainHealthConfig,+ now: Date,+): SemanticHealthReport {+ const signals = readAllSignalRecords(vault);+ const signSignById = new Map(signals.map((s) => [s.id, s.sign]));+ const preferences: PreferenceForHealth[] = prefRecords.map(({ pref }) => pref);+ const corpusPrinciples = [+ ...signals.map((s) => s.principle),+ ...prefRecords.map((r) => r.pref.principle),+ ];+ const coveredTopics = prefRecords.map((r) => r.pref.topic);++ const report = reconcileSemanticHealth(+ { preferences, signSignById, corpusPrinciples, coveredTopics },+ {+ contradictionJaccard: health.contradiction_jaccard,+ conceptGapMinFrequency: health.concept_gap_min_frequency,+ staleClaimMaxAgeDays: health.stale_claim_max_age_days,+ now,+ },+ );++ for (const c of report.contradictions) {+ issues.push({+ severity: "warning",+ code: "contradictory-preferences",+ message:+ `[[${c.aId}]] (${c.aSign}) and [[${c.bId}]] (${c.bSign})` ++ `${c.scope ? ` in scope '${c.scope}'` : ""}` ++ ` look like contradictions (jaccard ${c.jaccard.toFixed(2)} of principle tokens,` ++ " opposite sign of record). Reconcile or retire one.",+ });+ }+ for (const g of report.conceptGaps) {+ issues.push({+ severity: "warning",+ code: "concept-gap",+ message:+ `term '${g.term}' recurs across ${g.frequency} entries but no preference topic covers it.` ++ " Consider capturing a dedicated preference.",+ });+ }+ for (const s of report.staleClaims) {+ issues.push({+ severity: "warning",+ code: "stale-claim",+ message:+ `[[${s.id}]] last saw evidence ${s.ageDays} days ago (${s.lastEvidenceAt}).` ++ " Re-confirm or retire it.",+ });+ }++ return report;+}+// ----- Config check ---------------------------------------------------------function checkConfig(vault: string, issues: DoctorIssue[]): void {diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 13759494..5c4f9937 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -70,6 +70,7 @@ import {processedSignalPath,vaultRelative,} from "./paths.ts";+import { countSigns, dominantSignOf } from "./sign.ts";import { isoDate, isoSecond } from "./time.ts";import { parseWikilink, renderPrefLink } from "./wikilink.ts";import {@@ -406,6 +407,10 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {}if (!dryRun) {+ // Edit-history (F4): every dream-pass write records its content+ // before/after so a preference's evolution stays auditable. The+ // agent of record is whoever invoked the dream run.+ const historyOpts = { agent: opts.agentName ?? "dream", now: () => now };for (const np of plan.newUnconfirmed) {// Fresh pref has no apply-evidence yet; recentApplied/recentViolated// start empty and stay so until the next dream pass after the@@ -439,6 +444,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {},[],{ overwrite: false },+ historyOpts,);}@@ -475,6 +481,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {},[],{ overwrite: true },+ historyOpts,);}@@ -1172,28 +1179,22 @@ function handleSignalsOnActivePref(// conservative, fail-loud choice: the operator gets a clear// rebut/retire signal and can manually intervene if the system// misread their intent.- const signCounts = (records: ReadonlyArray<SignalRecord>): { pos: number; neg: number } => {- let pos = 0;- let neg = 0;- for (const r of records) {- if (r.signal.signal === BRAIN_SIGNAL_SIGN.positive) pos++;- else if (r.signal.signal === BRAIN_SIGNAL_SIGN.negative) neg++;- }- return { pos, neg };- };-- const evidenceIds = new Set(- active.pref.evidenced_by- .map((wl) => parseWikilink(wl))- .filter((s): s is string => !!s),- );- const evidenceRecords = allSignals.filter((r) => evidenceIds.has(r.signal.id));+ const signCounts = (records: ReadonlyArray<SignalRecord>): { pos: number; neg: number } =>+ countSigns(records.map((r) => r.signal.signal));++ // Tier-1 derivation now lives in the shared `sign.ts` helper so the+ // semantic-health contradiction detector and this pass agree on one+ // definition. `dominantSignOf` returning a concrete sign is exactly+ // the old `evidenceRecords.length > 0` branch (every signal carries a+ // polarity, so a resolved evidence link always counts); `"unknown"`+ // is the old "no evidenced signal resolved" fall-through.+ const signSignById = new Map(allSignals.map((r) => [r.signal.id, r.signal.signal]));const topicRecords = allSignals.filter((r) => r.signal.topic === active.pref.topic);+ const evidenceSign = dominantSignOf(active.pref.evidenced_by, signSignById);let activeSign: BrainSignalSign;- if (evidenceRecords.length > 0) {- const c = signCounts(evidenceRecords);- activeSign = c.pos >= c.neg ? BRAIN_SIGNAL_SIGN.positive : BRAIN_SIGNAL_SIGN.negative;+ if (evidenceSign !== "unknown") {+ activeSign = evidenceSign;} else if (topicRecords.length > sigs.length) {// There are processed signals for this topic that are NOT among// the active inbox set — use them.diff --git a/src/core/brain/health/concept-gap.ts b/src/core/brain/health/concept-gap.tsnew file mode 100644index 00000000..fa590fae--- /dev/null+++ b/src/core/brain/health/concept-gap.ts@@ -0,0 +1,68 @@+/**+ * Concept-gap detector (F2).+ *+ * Counts how many distinct corpus entries (document frequency) each+ * *entity* appears in, then reports entities that recur at or above+ * `minFrequency` but are not covered by any preference topic. Entities+ * come from the shared language-agnostic extractor (proper-noun-ish+ * anchors: capitalized runs, CamelCase, ALLCAPS, wikilinks, quoted+ * spans) - so lowercase function words like "the" or "use" never reach+ * the result without needing a stopword list. An entity is "covered"+ * when every word of it appears in some preference topic slug.+ *+ * Frequency + structure only, no vocabulary list. Pure and deterministic.+ */++import { extractEntities } from "../../search/entities.ts";+import { tokenise } from "../similarity.ts";++export interface ConceptGapFinding {+ readonly term: string;+ /** Number of distinct corpus entries the entity appears in. */+ readonly frequency: number;+}++export interface DetectConceptGapsOptions {+ /** Minimum document frequency for an entity to count as recurring. */+ readonly minFrequency: number;+}++/**+ * Detect recurring entities with no covering preference topic.+ *+ * @param principles corpus entries (signal + preference principle text)+ * @param coveredTopics preference topic slugs that already own a concept+ */+export function detectConceptGaps(+ principles: ReadonlyArray<string>,+ coveredTopics: ReadonlyArray<string>,+ opts: DetectConceptGapsOptions,+): ConceptGapFinding[] {+ // Topic slugs are kebab/snake-cased ("kanban-grooming"); the shared+ // tokeniser keeps `-`/`_` inside tokens, so split slug separators+ // into whitespace first to match entity words like "kanban".+ const covered = new Set<string>();+ for (const topic of coveredTopics) {+ for (const t of tokenise(topic.replace(/[-_]+/gu, " "))) covered.add(t);+ }+ const isCovered = (term: string): boolean =>+ term.split(/\s+/u).every((w) => covered.has(w));++ const docFreq = new Map<string, number>();+ for (const principle of principles) {+ // extractEntities dedupes within a single text, so each entity is+ // counted at most once per corpus entry (document frequency).+ for (const entity of extractEntities(principle)) {+ docFreq.set(entity, (docFreq.get(entity) ?? 0) + 1);+ }+ }++ const out: ConceptGapFinding[] = [];+ for (const [term, frequency] of docFreq) {+ if (frequency < opts.minFrequency) continue;+ if (isCovered(term)) continue;+ out.push({ term, frequency });+ }+ out.sort((a, b) => b.frequency - a.frequency || a.term.localeCompare(b.term));+ return out;+}diff --git a/src/core/brain/health/contradiction.ts b/src/core/brain/health/contradiction.tsnew file mode 100644index 00000000..5ae31317--- /dev/null+++ b/src/core/brain/health/contradiction.ts@@ -0,0 +1,97 @@+/**+ * Cross-preference contradiction detector (F1).+ *+ * Surfaces pairs of confirmed preferences that are about the same+ * subject but carry an opposite sign of record. "Same subject" is a+ * structural signal - principle token overlap (jaccard) via the shared+ * `similarity.ts` walker - and the polarity comes from `sign.ts`, which+ * derives each preference's sign from its `evidenced_by` signals. There+ * is no negation dictionary and no per-language vocabulary: a rule and+ * its negation share most of their tokens, so a high-overlap pair with+ * opposite signs is the language-agnostic shape of a contradiction.+ *+ * Pure and deterministic: identical input yields identical findings on+ * every Syncthing peer.+ */++import { dominantSignOf } from "../sign.ts";+import { findSimilarPairs, tokenise } from "../similarity.ts";+import {+ BRAIN_PREFERENCE_STATUS,+ type BrainPreferenceStatus,+ type BrainSignalSign,+} from "../types.ts";++/**+ * Narrow projection of {@link BrainPreference} the detector needs. The+ * full preference type satisfies this structurally, so callers pass+ * parsed preferences directly.+ */+export interface PreferenceForContradiction {+ readonly id: string;+ readonly scope?: string;+ readonly status: BrainPreferenceStatus;+ readonly principle: string;+ readonly evidenced_by: ReadonlyArray<string>;+}++export interface ContradictionFinding {+ readonly aId: string;+ readonly bId: string;+ /** Shared scope of the pair (the bucket key); `null` when unscoped. */+ readonly scope: string | null;+ readonly jaccard: number;+ readonly aSign: BrainSignalSign;+ readonly bSign: BrainSignalSign;+}++export interface DetectContradictionsOptions {+ /** Minimum principle jaccard for two preferences to count as the same subject. */+ readonly jaccard: number;+}++/**+ * Detect contradictory confirmed-preference pairs. Preferences are+ * bucketed by scope (so only same-scope rules are compared), paired by+ * principle token similarity at or above `jaccard`, and kept only when+ * the two resolved signs disagree. Preferences whose sign cannot be+ * resolved from evidence are skipped rather than guessed.+ */+export function detectContradictions(+ prefs: ReadonlyArray<PreferenceForContradiction>,+ signSignById: ReadonlyMap<string, BrainSignalSign>,+ opts: DetectContradictionsOptions,+): ContradictionFinding[] {+ const signById = new Map<string, BrainSignalSign>();+ const entries = [];+ for (const p of prefs) {+ if (p.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;+ const sign = dominantSignOf(p.evidenced_by, signSignById);+ if (sign === "unknown") continue;+ signById.set(p.id, sign);+ entries.push({+ id: p.id,+ bucketKey: p.scope ?? "",+ tokens: tokenise(p.principle),+ source: p,+ });+ }++ const pairs = findSimilarPairs(entries, { threshold: opts.jaccard });+ const out: ContradictionFinding[] = [];+ for (const pair of pairs) {+ const aSign = signById.get(pair.a.id)!;+ const bSign = signById.get(pair.b.id)!;+ if (aSign === bSign) continue;+ out.push({+ aId: pair.a.id,+ bId: pair.b.id,+ scope: pair.a.source.scope ?? null,+ jaccard: pair.jaccard,+ aSign,+ bSign,+ });+ }+ out.sort((x, y) => x.aId.localeCompare(y.aId) || x.bId.localeCompare(y.bId));+ return out;+}diff --git a/src/core/brain/health/edit-history.ts b/src/core/brain/health/edit-history.tsnew file mode 100644index 00000000..4e8921f5--- /dev/null+++ b/src/core/brain/health/edit-history.ts@@ -0,0 +1,116 @@+/**+ * Per-preference edit-history sidecar (F4).+ *+ * Each content mutation of a preference appends one JSONL line to+ * `Brain/preferences/pref-<slug>.history.jsonl` recording the field that+ * changed and its before/after. The trail is append-only but+ * convergent under Syncthing: {@link appendEditHistory} skips any entry+ * whose `(revision, field, after)` triple already exists, so two peers+ * replaying the same write converge instead of duplicating. The sidecar+ * never enters the search index because the walker only yields `.md`+ * files.+ */++import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname } from "node:path";++import { preferenceHistoryPath } from "../paths.ts";++export interface EditHistoryEntry {+ /** ISO timestamp of the mutation. */+ readonly ts: string;+ /** Agent identity that performed the write. */+ readonly agent: string;+ /** The preference `_revision` this entry produced. */+ readonly revision: number;+ /** The frontmatter field that changed (e.g. `principle`, `scope`). */+ readonly field: string;+ /** Prior value, or `null` when the field was absent before. */+ readonly before: string | null;+ /** New value, or `null` when the field was removed. */+ readonly after: string | null;+}++function dedupKey(e: EditHistoryEntry): string {+ return `${e.revision}\x00${e.field}\x00${e.after ?? "\x01"}`;+}++function isEntry(value: unknown): value is EditHistoryEntry {+ if (typeof value !== "object" || value === null) return false;+ const v = value as Record<string, unknown>;+ return (+ typeof v.ts === "string" &&+ typeof v.agent === "string" &&+ typeof v.revision === "number" &&+ typeof v.field === "string" &&+ (typeof v.before === "string" || v.before === null) &&+ (typeof v.after === "string" || v.after === null)+ );+}++/** Read the sidecar, skipping malformed lines. Missing file -> `[]`. */+export function readEditHistory(+ vault: string,+ slug: string,+): EditHistoryEntry[] {+ const path = preferenceHistoryPath(vault, slug);+ if (!existsSync(path)) return [];+ const out: EditHistoryEntry[] = [];+ for (const line of readFileSync(path, "utf8").split("\n")) {+ const trimmed = line.trim();+ if (trimmed.length === 0) continue;+ try {+ const parsed: unknown = JSON.parse(trimmed);+ if (isEntry(parsed)) out.push(parsed);+ } catch {+ // malformed line - skip, do not throw+ }+ }+ return out;+}++/**+ * Append `entries` to the sidecar, skipping any whose+ * `(revision, field, after)` already exists. Returns the number of+ * lines actually written. Creates the parent directory if missing.+ */+export function appendEditHistory(+ vault: string,+ slug: string,+ entries: ReadonlyArray<EditHistoryEntry>,+): number {+ if (entries.length === 0) return 0;+ const path = preferenceHistoryPath(vault, slug);+ const seen = new Set(readEditHistory(vault, slug).map(dedupKey));+ const lines: string[] = [];+ for (const e of entries) {+ const key = dedupKey(e);+ if (seen.has(key)) continue;+ seen.add(key);+ lines.push(JSON.stringify(e));+ }+ if (lines.length === 0) return 0;+ mkdirSync(dirname(path), { recursive: true });+ appendFileSync(path, lines.join("\n") + "\n");+ return lines.length;+}++/**+ * Render a deterministic, human-readable timeline. Entries are sorted+ * by revision then field; values are quoted so empty/whitespace edits+ * stay visible.+ */+export function renderEditHistory(+ entries: ReadonlyArray<EditHistoryEntry>,+): string {+ if (entries.length === 0) return "(no recorded edits)";+ const sorted = entries+ .slice()+ .sort((a, b) => a.revision - b.revision || a.field.localeCompare(b.field));+ const lines = sorted.map((e) => {+ const before = e.before === null ? "(absent)" : `"${e.before}"`;+ const after = e.after === null ? "(removed)" : `"${e.after}"`;+ return `rev ${e.revision} (${e.ts}, ${e.agent}): ${e.field}: ${before} -> ${after}`;+ });+ return lines.join("\n");+}diff --git a/src/core/brain/health/reconcile.ts b/src/core/brain/health/reconcile.tsnew file mode 100644index 00000000..ea4a65f2--- /dev/null+++ b/src/core/brain/health/reconcile.ts@@ -0,0 +1,88 @@+/**+ * Semantic-health reconciliation surface (F6).+ *+ * Runs the three semantic detectors over already-gathered vault data in+ * one deterministic pass and folds their findings into a single+ * verdict. This is the "truth reconciliation" surface, done without+ * sub-agents: each detector owns a domain, and the verdict escalates by+ * the most serious domain that fired.+ *+ * Pure - the caller is responsible for reading preferences, signals,+ * and the corpus; this module never touches the filesystem.+ */++import type { BrainSignalSign } from "../types.ts";+import {+ detectContradictions,+ type ContradictionFinding,+ type PreferenceForContradiction,+} from "./contradiction.ts";+import {+ detectConceptGaps,+ type ConceptGapFinding,+} from "./concept-gap.ts";+import {+ detectStaleClaims,+ type PreferenceForStaleClaim,+ type StaleClaimFinding,+} from "./stale-claim.ts";++/** A preference shape sufficient for every semantic-health detector. */+export type PreferenceForHealth = PreferenceForContradiction &+ PreferenceForStaleClaim;++export interface SemanticHealthInput {+ readonly preferences: ReadonlyArray<PreferenceForHealth>;+ readonly signSignById: ReadonlyMap<string, BrainSignalSign>;+ /** Signal + preference principle text the concept-gap detector counts over. */+ readonly corpusPrinciples: ReadonlyArray<string>;+ /** Preference topic slugs that already own a concept. */+ readonly coveredTopics: ReadonlyArray<string>;+}++export interface SemanticHealthConfig {+ readonly contradictionJaccard: number;+ readonly conceptGapMinFrequency: number;+ readonly staleClaimMaxAgeDays: number;+ readonly now: Date;+}++/** Mirrors the doctor's `TrustVerdict` ladder. */+export type SemanticHealthVerdict = "clean" | "watch" | "investigate";++export interface SemanticHealthReport {+ readonly contradictions: ReadonlyArray<ContradictionFinding>;+ readonly conceptGaps: ReadonlyArray<ConceptGapFinding>;+ readonly staleClaims: ReadonlyArray<StaleClaimFinding>;+ readonly verdict: SemanticHealthVerdict;+}++export function reconcileSemanticHealth(+ input: SemanticHealthInput,+ config: SemanticHealthConfig,+): SemanticHealthReport {+ const contradictions = detectContradictions(+ input.preferences,+ input.signSignById,+ { jaccard: config.contradictionJaccard },+ );+ const conceptGaps = detectConceptGaps(+ input.corpusPrinciples,+ input.coveredTopics,+ { minFrequency: config.conceptGapMinFrequency },+ );+ const staleClaims = detectStaleClaims(input.preferences, {+ maxAgeDays: config.staleClaimMaxAgeDays,+ now: config.now,+ });++ // A contradiction between two confirmed preferences is the most+ // serious finding - two active rules disagree, so an agent will apply+ // a coin-flip. Gaps and stale claims are quality nudges, not active+ // conflicts, so they only raise a watch.+ let verdict: SemanticHealthVerdict = "clean";+ if (contradictions.length > 0) verdict = "investigate";+ else if (conceptGaps.length > 0 || staleClaims.length > 0) verdict = "watch";++ return { contradictions, conceptGaps, staleClaims, verdict };+}diff --git a/src/core/brain/health/remediation.ts b/src/core/brain/health/remediation.tsnew file mode 100644index 00000000..ccb1a41b--- /dev/null+++ b/src/core/brain/health/remediation.ts@@ -0,0 +1,243 @@+/**+ * Dependency-ordered remediation planner + executor (F5).+ *+ * `planRemediation` turns findings into a deterministically-ordered+ * repair plan. Each step is classified `auto-safe` - a deterministic,+ * lossless, reversible repair that needs no human judgment - or+ * `needs-review`. `applyRemediation` mutates nothing under `dryRun`,+ * applies only auto-safe steps otherwise, and refuses past `stepCap`.+ *+ * The brain doctor stays non-mutating: this module is the only writer,+ * and it is invoked through an explicit opt-in path. The single+ * auto-safe action in this release is a content-hash re-stamp - the+ * stored `_content_hash` is bookkeeping derived from the authoritative+ * (principle, scope), so re-deriving it touches one frontmatter field+ * and preserves every byte of body content. Conservative by design:+ * contradictions, stale claims, and concept gaps are always+ * needs-review (better to under-fix than auto-mutate something needing+ * judgment).+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";+import { computeContentHash, verifyContentHash } from "../content-hash.ts";+import { brainDirs, preferencePath } from "../paths.ts";+import { parsePreference } from "../preference.ts";+import { acquireLockSync } from "../sync-lockfile.ts";+import { BRAIN_PREFERENCE_STATUS } from "../types.ts";++export type RemediationClass = "auto-safe" | "needs-review";++export interface RemediationStep {+ /** Finding code this step addresses. */+ readonly code: string;+ /** Machine action discriminant (`restamp-content-hash` | `review`). */+ readonly action: string;+ /** Repair target - a preference slug, id pair, or concept term. */+ readonly target: string;+ readonly classification: RemediationClass;+ /** Human-readable note for the plan preview. */+ readonly detail: string;+}++export interface RemediationPlan {+ readonly steps: ReadonlyArray<RemediationStep>;+ readonly stepCap: number;+}++export interface RemediationFindings {+ /** Confirmed preferences (slug stems) whose `_content_hash` drifted. */+ readonly driftedSlugs: ReadonlyArray<string>;+ readonly contradictions: ReadonlyArray<{ aId: string; bId: string }>;+ readonly staleClaims: ReadonlyArray<{ id: string }>;+ readonly conceptGaps: ReadonlyArray<{ term: string }>;+}++export interface PlanRemediationOptions {+ /** Maximum number of auto-safe steps `applyRemediation` will apply. */+ readonly stepCap: number;+}++export interface ApplyRemediationOptions {+ /** When true, compute the outcome but make no writes. */+ readonly dryRun: boolean;+}++export interface RemediationOutcome {+ readonly applied: ReadonlyArray<RemediationStep>;+ readonly skipped: ReadonlyArray<RemediationStep>;+ readonly dryRun: boolean;+}++// Fixed dependency order: bookkeeping repairs first, then semantic+// review steps. Pinned explicitly so the plan is identical on every+// Syncthing peer.+const CODE_ORDER: ReadonlyMap<string, number> = new Map([+ ["content-hash-drift", 0],+ ["contradictory-preferences", 1],+ ["stale-claim", 2],+ ["concept-gap", 3],+]);++/**+ * Scan `Brain/preferences/` for confirmed preferences whose stored+ * `_content_hash` no longer matches their live (principle, scope) -+ * the auto-safe re-stamp targets. Returns slug stems (no `pref-`+ * prefix), sorted for determinism. Files that fail to parse are+ * skipped (their schema errors surface through the doctor).+ */+export function collectDriftedSlugs(vault: string): string[] {+ const dir = brainDirs(vault).preferences;+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md") || !name.startsWith("pref-")) continue;+ try {+ const pref = parsePreference(join(dir, name));+ // Only confirmed preferences carry a txn-stamped hash; a legacy+ // or unconfirmed pref without one is not a drift target (and+ // verifyContentHash is neutral on absent hashes anyway).+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;+ if (!pref.content_hash) continue;+ const check = verifyContentHash({+ principle: pref.principle,+ scope: pref.scope,+ content_hash: pref.content_hash,+ });+ if (!check.ok) out.push(pref.id.replace(/^pref-/, ""));+ } catch {+ // schema error - reported by the doctor+ }+ }+ return out.sort((a, b) => a.localeCompare(b));+}++export function planRemediation(+ findings: RemediationFindings,+ opts: PlanRemediationOptions,+): RemediationPlan {+ const steps: RemediationStep[] = [];++ for (const slug of findings.driftedSlugs) {+ steps.push({+ code: "content-hash-drift",+ action: "restamp-content-hash",+ target: slug,+ classification: "auto-safe",+ detail: `re-stamp _content_hash for pref-${slug} from its current content`,+ });+ }+ for (const c of findings.contradictions) {+ steps.push({+ code: "contradictory-preferences",+ action: "review",+ target: `${c.aId}|${c.bId}`,+ classification: "needs-review",+ detail: `reconcile or retire one of [[${c.aId}]] / [[${c.bId}]]`,+ });+ }+ for (const s of findings.staleClaims) {+ steps.push({+ code: "stale-claim",+ action: "review",+ target: s.id,+ classification: "needs-review",+ detail: `re-confirm or retire [[${s.id}]]`,+ });+ }+ for (const g of findings.conceptGaps) {+ steps.push({+ code: "concept-gap",+ action: "review",+ target: g.term,+ classification: "needs-review",+ detail: `capture a dedicated preference for '${g.term}'`,+ });+ }++ steps.sort(+ (a, b) =>+ (CODE_ORDER.get(a.code) ?? 99) - (CODE_ORDER.get(b.code) ?? 99) ||+ a.target.localeCompare(b.target),+ );+ return { steps, stepCap: opts.stepCap };+}++/**+ * Re-stamp a preference's `_content_hash` to match its authoritative+ * (principle, scope). The file is round-tripped through+ * `parseFrontmatter` -> `writeFrontmatterAtomic`, preserving field+ * order and body verbatim; only the `_content_hash` value is rewritten.+ * In-scope files are confirmed preferences that previously carried a+ * txn-written (canonical) hash, so re-serialisation is a no-op for+ * every other field. The write goes through the same `.lock` file the+ * txn uses, so it is serialised against concurrent preference writes.+ * It deliberately bypasses the txn (and so does not bump `_revision`+ * or record edit-history): a hash re-stamp is bookkeeping, not a+ * content change.+ *+ * Returns true when a write happened, false when the file is gone, the+ * hash was already correct, or the lock could not be acquired.+ */+function restampContentHash(vault: string, slug: string): boolean {+ const path = preferencePath(vault, slug);+ if (!existsSync(path)) return false;+ let handle: ReturnType<typeof acquireLockSync>;+ try {+ handle = acquireLockSync(path);+ } catch {+ return false; // contended - leave for a later run+ }+ try {+ const pref = parsePreference(path);+ // Defence in depth: only re-stamp confirmed preferences that+ // already carry a hash, so a direct call cannot stamp a hash onto a+ // legacy/unconfirmed record outside the drift path.+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) return false;+ if (!pref.content_hash) return false;+ const correct = computeContentHash(pref.principle, pref.scope);+ if (pref.content_hash === correct) return false;+ const [meta, body] = parseFrontmatter(path);+ meta["_content_hash"] = correct;+ writeFrontmatterAtomic(path, meta, body, { overwrite: true });+ return true;+ } finally {+ handle.release();+ }+}++export function applyRemediation(+ vault: string,+ plan: RemediationPlan,+ opts: ApplyRemediationOptions,+): RemediationOutcome {+ const applied: RemediationStep[] = [];+ const skipped: RemediationStep[] = [];+ let budget = plan.stepCap;++ for (const step of plan.steps) {+ if (step.classification !== "auto-safe" || budget <= 0) {+ skipped.push(step);+ continue;+ }+ if (opts.dryRun) {+ applied.push(step);+ budget--;+ continue;+ }+ const didWrite =+ step.action === "restamp-content-hash"+ ? restampContentHash(vault, step.target)+ : false;+ if (didWrite) {+ applied.push(step);+ budget--;+ } else {+ skipped.push(step);+ }+ }++ return { applied, skipped, dryRun: opts.dryRun };+}diff --git a/src/core/brain/health/stale-claim.ts b/src/core/brain/health/stale-claim.tsnew file mode 100644index 00000000..a170e6af--- /dev/null+++ b/src/core/brain/health/stale-claim.ts@@ -0,0 +1,69 @@+/**+ * Stale-claim detector (F3).+ *+ * Flags confirmed preferences whose newest supporting evidence+ * (`last_evidence_at`) is older than a configured age window. A+ * different axis than `temporal/stale-watch.ts`, which keys off file+ * mtime - this keys off the recorded evidence date. Pure and+ * deterministic with an injected clock; preferences with a missing or+ * unparseable evidence date are skipped (their absence is a separate+ * lint's concern), and a future-dated evidence is never stale.+ */++import {+ BRAIN_PREFERENCE_STATUS,+ type BrainPreferenceStatus,+} from "../types.ts";++const DAY_MS = 24 * 60 * 60 * 1000;++/** Date-only ISO form (`YYYY-MM-DD`), which the doctor's checkIso allows. */+const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;++/**+ * Parse an ISO timestamp deterministically. A date-only value is+ * expanded to UTC midnight before parsing so the millisecond result -+ * and therefore `ageDays` - is identical on every engine and peer,+ * never drifting to a local-midnight interpretation.+ */+function parseIsoUtc(value: string): number {+ const iso = ISO_DATE_ONLY_RE.test(value) ? `${value}T00:00:00Z` : value;+ return Date.parse(iso);+}++/** Narrow projection the detector needs; {@link BrainPreference} satisfies it. */+export interface PreferenceForStaleClaim {+ readonly id: string;+ readonly status: BrainPreferenceStatus;+ readonly last_evidence_at: string | null;+}++export interface StaleClaimFinding {+ readonly id: string;+ readonly lastEvidenceAt: string;+ readonly ageDays: number;+}++export interface DetectStaleClaimsOptions {+ readonly maxAgeDays: number;+ readonly now: Date;+}++export function detectStaleClaims(+ prefs: ReadonlyArray<PreferenceForStaleClaim>,+ opts: DetectStaleClaimsOptions,+): StaleClaimFinding[] {+ const nowMs = opts.now.getTime();+ const out: StaleClaimFinding[] = [];+ for (const p of prefs) {+ if (p.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;+ if (!p.last_evidence_at) continue;+ const evMs = parseIsoUtc(p.last_evidence_at);+ if (!Number.isFinite(evMs)) continue;+ const ageDays = Math.floor((nowMs - evMs) / DAY_MS);+ if (ageDays <= opts.maxAgeDays) continue;+ out.push({ id: p.id, lastEvidenceAt: p.last_evidence_at, ageDays });+ }+ out.sort((a, b) => b.ageDays - a.ageDays || a.id.localeCompare(b.id));+ return out;+}diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex 3ed62421..a410f12e 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -159,6 +159,19 @@ export function preferencePath(vault: string, slug: string): string {);}+/**+ * Per-preference edit-history sidecar: `Brain/preferences/pref-<slug>.history.jsonl`.+ * Lives next to the preference file; never enters the search index+ * because the walker only yields `.md` files.+ */+export function preferenceHistoryPath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(+ join(brainDirs(vault).preferences, `pref-${s}.history.jsonl`),+ vault,+ );+}+/** Retired-preference path: `Brain/retired/ret-<slug>.md`. */export function retiredPath(vault: string, slug: string): string {const s = validateSlug(slug);diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 7c8401b1..6ffc7e05 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -25,6 +25,7 @@ import type {BrainActiveConfig,BrainConfig,BrainGuardrailConfig,+ BrainHealthConfig,BrainLinkGraphConfig,BrainNotesConfig,BrainMostAppliedConfig,@@ -32,6 +33,7 @@ import type {BrainVaultConfig,DisciplineReportConfig,ResolvedBrainGuardrailConfig,+ ResolvedBrainHealthConfig,ResolvedBrainLinkGraphConfig,ResolvedBrainNotesConfig,ResolvedBrainTemporalConfig,@@ -217,6 +219,49 @@ export function resolveTemporal(};}+/**+ * Default `health:` block (v0.14.0). Drives the semantic-health+ * detectors and the remediation step cap. Absent block falls back here+ * via `resolveHealth`:+ *+ * - `contradiction_jaccard: 0.5` - two confirmed preferences must+ * share at least half their principle tokens (and carry opposite+ * signs) to count as a contradiction.+ * - `concept_gap_min_frequency: 3` - an entity must recur across 3+ * distinct corpus entries before an uncovered-concept gap fires.+ * - `stale_claim_max_age_days: 180` - 6 months without fresh+ * evidence before a confirmed preference is flagged stale.+ * - `remediation_step_cap: 20` - a single `doctor --remediate` run+ * applies at most 20 auto-safe repairs.+ */+export const BRAIN_HEALTH_DEFAULTS: ResolvedBrainHealthConfig = Object.freeze({+ contradiction_jaccard: 0.5,+ concept_gap_min_frequency: 3,+ stale_claim_max_age_days: 180,+ remediation_step_cap: 20,+}) as ResolvedBrainHealthConfig;++/**+ * Merge a parsed `health` block (or `undefined`) with+ * `BRAIN_HEALTH_DEFAULTS`.+ */+export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {+ const h = cfg.health;+ if (h === undefined) return BRAIN_HEALTH_DEFAULTS;+ return {+ contradiction_jaccard:+ h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,+ concept_gap_min_frequency:+ h.concept_gap_min_frequency ??+ BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,+ stale_claim_max_age_days:+ h.stale_claim_max_age_days ??+ BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,+ remediation_step_cap:+ h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,+ };+}+/*** Default `notes:` block (v0.11.0). Empty `read_paths` list means* the agent does not scan any user-authored notes. The operator@@ -1148,6 +1193,73 @@ export function validateBrainConfigDetailed(: {};}+ // Optional `health:` block (v0.14.0). Shape:+ // health:+ // contradiction_jaccard: 0.5 # float in (0, 1]+ // concept_gap_min_frequency: 3 # positive integer+ // stale_claim_max_age_days: 180+ // remediation_step_cap: 20+ // Absent block → `cfg.health` undefined; resolveHealth returns the+ // bit-identical defaults.+ let health: BrainHealthConfig | undefined;+ if ("health" in obj) {+ const rawH = obj["health"];+ if (typeof rawH !== "object" || rawH === null || Array.isArray(rawH)) {+ throw new BrainConfigError("health must be a mapping", "health", source);+ }+ const hObj = rawH as Record<string, unknown>;+ const partialH: Record<string, unknown> = {};+ if ("contradiction_jaccard" in hObj) {+ const v = hObj["contradiction_jaccard"];+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) {+ throw new BrainConfigError(+ "must be a finite number in (0, 1]",+ "health.contradiction_jaccard",+ source,+ );+ }+ partialH["contradiction_jaccard"] = v;+ }+ const positiveIntKeys: ReadonlyArray<+ "concept_gap_min_frequency" | "stale_claim_max_age_days" | "remediation_step_cap"+ > = [+ "concept_gap_min_frequency",+ "stale_claim_max_age_days",+ "remediation_step_cap",+ ];+ for (const key of positiveIntKeys) {+ if (key in hObj) {+ const v = hObj[key];+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {+ throw new BrainConfigError(+ "must be a positive integer",+ `health.${key}`,+ source,+ );+ }+ partialH[key] = v;+ }+ }+ const knownH = new Set([+ "contradiction_jaccard",+ "concept_gap_min_frequency",+ "stale_claim_max_age_days",+ "remediation_step_cap",+ ]);+ for (const key of Object.keys(hObj)) {+ if (!knownH.has(key)) {+ warnings.push({+ path: source ?? "<config>",+ message: `health.${key}: unknown field ignored (forward-compat)`,+ });+ }+ }+ health =+ Object.keys(partialH).length > 0+ ? (partialH as BrainHealthConfig)+ : {};+ }+// Optional `notes:` block (v0.11.0). Shape:// notes:// read_paths:@@ -1283,6 +1395,7 @@ export function validateBrainConfigDetailed(...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),...(temporal !== undefined ? { temporal } : {}),...(notes !== undefined ? { notes } : {}),+ ...(health !== undefined ? { health } : {}),};return { config, warnings };diff --git a/src/core/brain/preference-txn.ts b/src/core/brain/preference-txn.tsindex 14fa27a5..74d2cdb7 100644--- a/src/core/brain/preference-txn.ts+++ b/src/core/brain/preference-txn.ts@@ -30,6 +30,7 @@import { existsSync } from "node:fs";import { computeContentHash } from "./content-hash.ts";+import { appendEditHistory, type EditHistoryEntry } from "./health/edit-history.ts";import {preferencePath,validateSlug,@@ -79,6 +80,62 @@ export class BrainCollisionError extends Error {}}+/**+ * Opt-in edit-history recording for the txn (v0.14.0, F4). When+ * supplied AND the write actually changes bytes, the txn appends one+ * {@link EditHistoryEntry} per changed tracked field (`principle`,+ * `scope`, `status`) to the preference's `.history.jsonl` sidecar,+ * keyed by the resulting revision. Callers that omit this leave the+ * pre-v0.14.0 behaviour untouched - no sidecar is created.+ */+export interface EditHistoryOptions {+ /** Agent identity recorded on each entry. */+ readonly agent: string;+ /** Clock for the entry timestamp; defaults to `new Date()`. */+ readonly now?: () => Date;+}++/**+ * Frontmatter fields whose before/after the edit-history trail records.+ * Kept to the content-bearing fields plus lifecycle status; derived+ * counters and timestamps are intentionally excluded so the trail+ * stays a record of meaning, not bookkeeping churn.+ */+const HISTORY_TRACKED_FIELDS = ["principle", "scope", "status"] as const;++function editHistoryEntries(+ existing: BrainPreference | null,+ proposed: WritePreferenceInput,+ revision: number,+ opts: EditHistoryOptions,+): EditHistoryEntry[] {+ const ts = (opts.now?.() ?? new Date()).toISOString();+ const reader: Record<(typeof HISTORY_TRACKED_FIELDS)[number], {+ before: string | null;+ after: string | null;+ }> = {+ principle: {+ before: existing?.principle ?? null,+ after: proposed.principle ?? null,+ },+ scope: {+ before: existing?.scope ?? null,+ after: proposed.scope ?? null,+ },+ status: {+ before: existing?.status ?? null,+ after: proposed.status ?? null,+ },+ };+ const out: EditHistoryEntry[] = [];+ for (const field of HISTORY_TRACKED_FIELDS) {+ const { before, after } = reader[field];+ if (before === after) continue;+ out.push({ ts, agent: opts.agent, revision, field, before, after });+ }+ return out;+}+/*** Context passed to every expectation. Carries the resolved path, the* existing preference (if any), and the proposed input. Expectations@@ -118,6 +175,7 @@ export function writePreferenceTxn(input: WritePreferenceInput,expectations: ReadonlyArray<WritePreferenceExpectation>,options: WritePreferenceOptions = {},+ history?: EditHistoryOptions,): WritePreferenceResult {const slug = validateSlug(input.slug);const path = preferencePath(vault, slug);@@ -182,7 +240,20 @@ export function writePreferenceTxn(revision: input.revision ?? ((existing?.revision ?? 0) + 1),}: candidate;- return writePreference(vault, inputWithDefaults, options);+ const result = writePreference(vault, inputWithDefaults, options);+ // Edit-history (opt-in): record field-level before/after only when+ // the write actually changed bytes, keyed by the resulting+ // revision. Idempotent appends keep Syncthing peers convergent.+ if (history && willChange) {+ const entries = editHistoryEntries(+ existing,+ inputWithDefaults,+ inputWithDefaults.revision ?? 1,+ history,+ );+ appendEditHistory(vault, slug, entries);+ }+ return result;} finally {handle.release();}diff --git a/src/core/brain/sign.ts b/src/core/brain/sign.tsnew file mode 100644index 00000000..398e99f6--- /dev/null+++ b/src/core/brain/sign.ts@@ -0,0 +1,67 @@+/**+ * Shared "sign of record" helper.+ *+ * A taste signal carries a polarity (`positive` / `negative`). A+ * preference inherits a derived sign from the signals it cites in+ * `evidenced_by` - the dominant polarity among them. This module is the+ * single definition of that derivation, lifted out of `dream.ts` so the+ * dream pass and the semantic-health contradiction detector agree on one+ * tie-break and one notion of "unresolved".+ *+ * Language-agnostic by construction: polarity comes from the signal's+ * structured `signal` field, never from inspecting principle text.+ */++import { BRAIN_SIGNAL_SIGN, type BrainSignalSign } from "./types.ts";+import { parseWikilink } from "./wikilink.ts";++/**+ * A resolved sign, or `"unknown"` when no evidence settles the polarity.+ * Callers decide how to treat unknown: the contradiction detector skips+ * such preferences; the dream pass falls back to its topic / heuristic+ * tiers.+ */+export type ResolvedSign = BrainSignalSign | "unknown";++/** Count positive vs negative signs in an iterable of polarities. */+export function countSigns(+ signs: Iterable<BrainSignalSign>,+): { pos: number; neg: number } {+ let pos = 0;+ let neg = 0;+ for (const s of signs) {+ if (s === BRAIN_SIGNAL_SIGN.positive) pos++;+ else if (s === BRAIN_SIGNAL_SIGN.negative) neg++;+ }+ return { pos, neg };+}++/**+ * Reduce a pos/neg tally to a dominant sign. A tie breaks to+ * `positive` - the same `pos >= neg` rule `dream.ts` has always used.+ * An all-zero tally is `"unknown"`.+ */+export function dominantSignFromCounts(pos: number, neg: number): ResolvedSign {+ if (pos === 0 && neg === 0) return "unknown";+ return pos >= neg ? BRAIN_SIGNAL_SIGN.positive : BRAIN_SIGNAL_SIGN.negative;+}++/**+ * Resolve a preference's sign of record from the signals it cites.+ * Wikilinks that do not resolve in `signSignById` are ignored; when no+ * cited signal resolves, the result is `"unknown"`.+ */+export function dominantSignOf(+ evidencedBy: ReadonlyArray<string>,+ signSignById: ReadonlyMap<string, BrainSignalSign>,+): ResolvedSign {+ const signs: BrainSignalSign[] = [];+ for (const wl of evidencedBy) {+ const id = parseWikilink(wl);+ if (!id) continue;+ const s = signSignById.get(id);+ if (s) signs.push(s);+ }+ const { pos, neg } = countSigns(signs);+ return dominantSignFromCounts(pos, neg);+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex a9ca9ded..59432731 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -839,6 +839,12 @@ export interface BrainConfig {* to these paths - the type is `read_paths` for a reason.*/readonly notes?: BrainNotesConfig;+ /**+ * Optional `health:` block (v0.14.0). Tunes the semantic-health+ * detectors and the remediation step cap. Absent: callers fall back+ * to `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.+ */+ readonly health?: BrainHealthConfig;}/**@@ -958,3 +964,31 @@ export interface ResolvedBrainTemporalConfig {readonly weekly_start_dow: number;readonly daily_window_offset_hours: number;}++/**+ * Optional `health:` block (v0.14.0). Tunes the semantic-health+ * detectors (contradiction / concept-gap / stale-claim) and the+ * remediation step cap. Absent: callers fall back to+ * `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.+ */+export interface BrainHealthConfig {+ /** Minimum principle jaccard for a contradiction pair. Float in (0, 1]. */+ readonly contradiction_jaccard?: number;+ /** Minimum document frequency for a concept gap. Positive integer. */+ readonly concept_gap_min_frequency?: number;+ /** Age (days) past which a confirmed preference's evidence is stale. Positive integer. */+ readonly stale_claim_max_age_days?: number;+ /** Maximum auto-safe steps a single remediation run applies. Positive integer. */+ readonly remediation_step_cap?: number;+}++/**+ * Concrete (fully-resolved) health config. Returned by+ * `resolveHealth(cfg)` so consumers do not branch on optionals.+ */+export interface ResolvedBrainHealthConfig {+ readonly contradiction_jaccard: number;+ readonly concept_gap_min_frequency: number;+ readonly stale_claim_max_age_days: number;+ readonly remediation_step_cap: number;+}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex c1ebfcc7..4a24200b 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -722,6 +722,38 @@ async function toolBrainDoctor(};}+// ----- brain_health --------------------------------------------------------++async function toolBrainHealth(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const format = coerceFormat(args);+ const result = runDoctor(ctx.vault);+ const sh = result.semantic_health;+ return {+ format,+ verdict: sh?.verdict ?? "clean",+ contradictions: (sh?.contradictions ?? []).map((c) => ({+ a: c.aId,+ b: c.bId,+ ...(c.scope !== null ? { scope: c.scope } : {}),+ jaccard: c.jaccard,+ a_sign: c.aSign,+ b_sign: c.bSign,+ })),+ concept_gaps: (sh?.conceptGaps ?? []).map((g) => ({+ term: g.term,+ frequency: g.frequency,+ })),+ stale_claims: (sh?.staleClaims ?? []).map((s) => ({+ id: s.id,+ last_evidence_at: s.lastEvidenceAt,+ age_days: s.ageDays,+ })),+ };+}+// ----- Serializers ---------------------------------------------------------function serializeSignal(s: BrainSignal): Record<string, unknown> {@@ -1640,6 +1672,24 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},handler: toolBrainDoctor,},+ {+ name: "brain_health",+ description:+ "Semantic-health report: contradictory confirmed preferences (opposite sign of record, same subject), recurring concepts with no dedicated preference, and confirmed preferences running on stale evidence. Returns the per-domain findings plus a clean/watch/investigate verdict. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ format: {+ type: "string",+ enum: ["markdown", "json"],+ description:+ "Output format hint. Structured result is identical; caller decides rendering.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainHealth,+ },{name: "brain_backlinks",description:diff --git a/tests/cli/brain-health.test.ts b/tests/cli/brain-health.test.tsnew file mode 100644index 00000000..3161eb0b--- /dev/null+++ b/tests/cli/brain-health.test.ts@@ -0,0 +1,116 @@+/**+ * CLI smoke tests for the v0.14.0 semantic-health surfaces:+ * `o2b brain health`, `o2b brain history <slug>`, and+ * `o2b brain doctor --remediate [--dry-run]`.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";+import { appendEditHistory } from "../../src/core/brain/health/edit-history.ts";+import { computeContentHash } from "../../src/core/brain/content-hash.ts";+import { parsePreference, writePreference } from "../../src/core/brain/preference.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";++let tmp: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-health-cli-"));+ vault = join(tmp, "vault");+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {+ mkdirSync(join(vault, "Brain", d), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });++function writeDriftedPref(slug: string): void {+ writePreference(+ vault,+ {+ slug,+ topic: slug,+ principle: "always write tests first in production code",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ content_hash: "0".repeat(64),+ },+ { overwrite: true },+ );+}++describe("o2b brain health", () => {+ test("clean vault prints verdict clean", async () => {+ const r = await runCli(["brain", "health"], { env: env() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("verdict: clean");+ });++ test("--json prints the structured report", async () => {+ const r = await runCli(["brain", "health", "--json"], { env: env() });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as { verdict: string };+ expect(payload.verdict).toBe("clean");+ });+});++describe("o2b brain history", () => {+ test("renders an edit-history timeline", async () => {+ appendEditHistory(vault, "tabs", [+ {+ ts: "2026-05-27T00:00:00Z",+ agent: "tester",+ revision: 1,+ field: "principle",+ before: "use tabs",+ after: "use spaces",+ },+ ]);+ const r = await runCli(["brain", "history", "tabs"], { env: env() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("rev 1");+ expect(r.stdout).toContain("use spaces");+ });++ test("missing slug argument fails", async () => {+ const r = await runCli(["brain", "history"], { env: env() });+ expect(r.returncode).toBe(1);+ });+});++describe("o2b brain doctor --remediate", () => {+ test("--dry-run previews the content-hash re-stamp without writing", async () => {+ writeDriftedPref("a-drift");+ const r = await runCli(["brain", "doctor", "--remediate", "--dry-run"], { env: env() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("would apply");+ expect(r.stdout).toContain("content-hash-drift");+ const pref = parsePreference(join(brainDirs(vault).preferences, "pref-a-drift.md"));+ expect(pref.content_hash).not.toBe(computeContentHash(pref.principle, pref.scope));+ });++ test("applies the re-stamp and fixes the drift", async () => {+ writeDriftedPref("a-drift");+ const r = await runCli(["brain", "doctor", "--remediate"], { env: env() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("applied");+ const pref = parsePreference(join(brainDirs(vault).preferences, "pref-a-drift.md"));+ expect(pref.content_hash).toBe(computeContentHash(pref.principle, pref.scope));+ });+});diff --git a/tests/core/brain/doctor-semantic.test.ts b/tests/core/brain/doctor-semantic.test.tsnew file mode 100644index 00000000..1022867b--- /dev/null+++ b/tests/core/brain/doctor-semantic.test.ts@@ -0,0 +1,113 @@+/**+ * Doctor integration of the semantic-health detectors (F6, Task 8).+ *+ * runDoctor calls the contradiction / concept-gap / stale-claim+ * detectors best-effort, merges their findings into the warning stream+ * with dedicated codes, and attaches a semantic_health report. The+ * doctor stays non-mutating.+ */++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 { runDoctor } from "../../../src/core/brain/doctor.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import {+ BRAIN_PREFERENCE_STATUS,+ BRAIN_SIGNAL_SIGN,+ type BrainSignalSign,+} from "../../../src/core/brain/types.ts";++const NOW = new Date("2026-05-27T00:00:00Z");+let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-doctor-semantic-"));+ const d = brainDirs(vault);+ for (const dir of [d.brain, d.inbox, d.processed, d.preferences, d.retired, d.log]) {+ mkdirSync(dir, { recursive: true });+ }+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function sig(slug: string, sign: BrainSignalSign, principle: string): string {+ return writeSignal(vault, {+ topic: "indentation",+ signal: sign,+ agent: "tester",+ principle,+ created_at: "2026-05-01T00:00:00Z",+ date: "2026-05-01",+ slug,+ }).id;+}++function confirmedPref(+ slug: string,+ topic: string,+ principle: string,+ evidenced_by: ReadonlyArray<string>,+): void {+ writePreference(+ vault,+ {+ slug,+ topic,+ principle,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by,+ },+ { overwrite: true },+ );+}++describe("runDoctor semantic health", () => {+ test("flags contradictory confirmed preferences and escalates the verdict", () => {+ const pos = sig("tabs-pos", BRAIN_SIGNAL_SIGN.positive, "use tabs");+ const neg = sig("tabs-neg", BRAIN_SIGNAL_SIGN.negative, "use spaces");+ confirmedPref("tabs-rule", "tabs-rule", "always indent source with tabs not spaces", [+ `[[${pos}]]`,+ ]);+ confirmedPref("spaces-rule", "spaces-rule", "never indent source with tabs always spaces", [+ `[[${neg}]]`,+ ]);++ const result = runDoctor(vault, { now: NOW });+ const codes = result.warnings.map((w) => w.code);+ expect(codes).toContain("contradictory-preferences");+ expect(result.semantic_health?.verdict).toBe("investigate");+ expect(result.semantic_health?.contradictions.length).toBe(1);+ });++ test("a coherent vault produces no semantic warnings and a clean verdict", () => {+ const pos = sig("tdd-pos", BRAIN_SIGNAL_SIGN.positive, "write tests early");+ confirmedPref(+ "tdd-rule",+ "testing-discipline",+ "write unit tests before merging code",+ [`[[${pos}]]`],+ );++ const result = runDoctor(vault, { now: NOW });+ const semanticCodes = result.warnings+ .map((w) => w.code)+ .filter((c) => ["contradictory-preferences", "concept-gap", "stale-claim"].includes(c));+ expect(semanticCodes).toEqual([]);+ expect(result.semantic_health?.verdict).toBe("clean");+ });++ test("does not throw on a vault and always returns a semantic_health report", () => {+ expect(() => runDoctor(vault, { now: NOW })).not.toThrow();+ expect(runDoctor(vault, { now: NOW }).semantic_health).toBeDefined();+ });+});diff --git a/tests/core/brain/health/concept-gap.test.ts b/tests/core/brain/health/concept-gap.test.tsnew file mode 100644index 00000000..744d2c9f--- /dev/null+++ b/tests/core/brain/health/concept-gap.test.ts@@ -0,0 +1,104 @@+/**+ * Concept-gap detector (F2).+ *+ * A concept gap is a recurring *entity* (a proper-noun-ish anchor, per+ * the shared language-agnostic entity extractor) whose document+ * frequency reaches a threshold yet is not covered by any preference+ * topic. Using entities rather than raw tokens keeps lowercase function+ * words ("the", "use") out of the result without any stopword list -+ * the filter is structural (codepoint case / shape), not lexical.+ */++import { describe, expect, test } from "bun:test";++import { detectConceptGaps } from "../../../../src/core/brain/health/concept-gap.ts";++describe("detectConceptGaps", () => {+ test("flags an entity recurring across enough distinct principles", () => {+ const gaps = detectConceptGaps(+ [+ "Kanban board needs grooming",+ "the Kanban workflow is slow",+ "review Kanban tasks weekly",+ "unrelated note about Coffee",+ ],+ ["coffee-habits"],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([{ term: "kanban", frequency: 3 }]);+ });++ test("an entity covered by a preference topic is not a gap", () => {+ const gaps = detectConceptGaps(+ [+ "Kanban board needs grooming",+ "the Kanban workflow is slow",+ "review Kanban tasks weekly",+ ],+ ["kanban-grooming"],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([]);+ });++ test("a multi-word entity covered by a hyphenated topic is not a gap", () => {+ const gaps = detectConceptGaps(+ [+ "Open Second Brain stores notes",+ "Open Second Brain syncs peers",+ "Open Second Brain ranks results",+ ],+ ["open-second-brain"],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([]);+ });++ test("lowercase function words are never entities", () => {+ const gaps = detectConceptGaps(+ ["use the tool", "use the result", "use the output"],+ [],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([]);+ });++ test("an entity below the frequency threshold is not a gap", () => {+ const gaps = detectConceptGaps(+ ["Kanban once", "Kanban twice"],+ [],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([]);+ });++ test("repeats within one principle count once (document frequency)", () => {+ const gaps = detectConceptGaps(+ ["Kanban Kanban Kanban Kanban"],+ [],+ { minFrequency: 2 },+ );+ expect(gaps).toEqual([]);+ });++ test("findings are ordered by frequency desc then term asc", () => {+ const gaps = detectConceptGaps(+ ["Alpha", "Alpha", "Alpha", "Beta", "Beta", "Beta", "Beta"],+ [],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([+ { term: "beta", frequency: 4 },+ { term: "alpha", frequency: 3 },+ ]);+ });++ test("is language-agnostic", () => {+ const gaps = detectConceptGaps(+ ["Бэклог растёт", "Бэклог завис", "разгрести Бэклог"],+ [],+ { minFrequency: 3 },+ );+ expect(gaps).toEqual([{ term: "бэклог", frequency: 3 }]);+ });+});diff --git a/tests/core/brain/health/contradiction.test.ts b/tests/core/brain/health/contradiction.test.tsnew file mode 100644index 00000000..16453150--- /dev/null+++ b/tests/core/brain/health/contradiction.test.ts@@ -0,0 +1,187 @@+/**+ * Cross-preference contradiction detector (F1).+ *+ * A contradiction is structural, not lexical: two confirmed+ * preferences about the same subject (high principle token overlap)+ * that carry an opposite sign of record. No negation word list - the+ * polarity comes entirely from each preference's `evidenced_by` signals.+ */++import { describe, expect, test } from "bun:test";++import {+ BRAIN_PREFERENCE_STATUS,+ BRAIN_SIGNAL_SIGN,+} from "../../../../src/core/brain/types.ts";+import {+ detectContradictions,+ type PreferenceForContradiction,+} from "../../../../src/core/brain/health/contradiction.ts";++function pref(+ over: Partial<PreferenceForContradiction> &+ Pick<PreferenceForContradiction, "id" | "principle" | "evidenced_by">,+): PreferenceForContradiction {+ return {+ scope: "coding",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ ...over,+ };+}++const signs = new Map([+ ["sig-pos", BRAIN_SIGNAL_SIGN.positive],+ ["sig-neg", BRAIN_SIGNAL_SIGN.negative],+]);++describe("detectContradictions", () => {+ test("flags same-scope high-overlap pair with opposite signs", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-a",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ principle: "never indent source with tabs always spaces",+ evidenced_by: ["[[sig-neg]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings.length).toBe(1);+ expect(findings[0]!.aId).toBe("pref-a");+ expect(findings[0]!.bId).toBe("pref-b");+ expect(findings[0]!.aSign).toBe(BRAIN_SIGNAL_SIGN.positive);+ expect(findings[0]!.bSign).toBe(BRAIN_SIGNAL_SIGN.negative);+ expect(findings[0]!.jaccard).toBeGreaterThanOrEqual(0.5);+ });++ test("same sign is not a contradiction (those are duplicates)", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-a",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ principle: "always indent source with tabs not spaces here",+ evidenced_by: ["[[sig-pos]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings).toEqual([]);+ });++ test("low token overlap is not compared even with opposite signs", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-a",+ principle: "deploy releases on friday afternoon",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ principle: "write unit tests before merging code",+ evidenced_by: ["[[sig-neg]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings).toEqual([]);+ });++ test("different scopes are bucketed apart and never paired", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-a",+ scope: "coding",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ scope: "writing",+ principle: "never indent source with tabs always spaces",+ evidenced_by: ["[[sig-neg]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings).toEqual([]);+ });++ test("unconfirmed preferences are skipped", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-a",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,+ principle: "never indent source with tabs always spaces",+ evidenced_by: ["[[sig-neg]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings).toEqual([]);+ });++ test("unknown-sign preferences are skipped (no resolvable evidence)", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-a",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ principle: "never indent source with tabs always spaces",+ evidenced_by: ["[[sig-orphaned]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings).toEqual([]);+ });++ test("output is deterministically ordered with aId < bId", () => {+ const findings = detectContradictions(+ [+ pref({+ id: "pref-zebra",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-neg]]"],+ }),+ pref({+ id: "pref-alpha",+ principle: "never indent source with tabs always spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ ],+ signs,+ { jaccard: 0.5 },+ );+ expect(findings.length).toBe(1);+ expect(findings[0]!.aId).toBe("pref-alpha");+ expect(findings[0]!.bId).toBe("pref-zebra");+ });+});diff --git a/tests/core/brain/health/edit-history.test.ts b/tests/core/brain/health/edit-history.test.tsnew file mode 100644index 00000000..53f73b8c--- /dev/null+++ b/tests/core/brain/health/edit-history.test.ts@@ -0,0 +1,112 @@+/**+ * Per-preference edit-history sidecar (F4).+ *+ * Append-only `Brain/preferences/pref-<slug>.history.jsonl` capturing+ * one entry per content mutation. Convergent under Syncthing: appending+ * an entry whose (revision, field, after) already exists is a no-op, so+ * two peers replaying the same write do not diverge. Reads skip+ * malformed lines; rendering is deterministic.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ appendEditHistory,+ readEditHistory,+ renderEditHistory,+ type EditHistoryEntry,+} from "../../../../src/core/brain/health/edit-history.ts";+import { preferenceHistoryPath } from "../../../../src/core/brain/paths.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-edit-history-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++const entry = (over: Partial<EditHistoryEntry>): EditHistoryEntry => ({+ ts: "2026-05-27T00:00:00Z",+ agent: "claude-vps-agent",+ revision: 1,+ field: "principle",+ before: "use tabs",+ after: "use spaces",+ ...over,+});++describe("appendEditHistory / readEditHistory", () => {+ test("appends entries and round-trips them", () => {+ appendEditHistory(vault, "tabs", [+ entry({ revision: 1, field: "principle" }),+ entry({ revision: 1, field: "scope", before: null, after: "coding" }),+ ]);+ const read = readEditHistory(vault, "tabs");+ expect(read.length).toBe(2);+ expect(read[0]!.field).toBe("principle");+ expect(read[1]!.after).toBe("coding");+ });++ test("is idempotent per (revision, field, after)", () => {+ appendEditHistory(vault, "tabs", [entry({})]);+ const appended = appendEditHistory(vault, "tabs", [entry({})]);+ expect(appended).toBe(0);+ expect(readEditHistory(vault, "tabs").length).toBe(1);+ });++ test("a later revision touching the same field is a new entry", () => {+ appendEditHistory(vault, "tabs", [entry({ revision: 1 })]);+ appendEditHistory(vault, "tabs", [+ entry({ revision: 2, before: "use spaces", after: "use 2-space indent" }),+ ]);+ expect(readEditHistory(vault, "tabs").length).toBe(2);+ });++ test("read returns empty for a missing sidecar", () => {+ expect(readEditHistory(vault, "never-written")).toEqual([]);+ });++ test("read skips malformed lines", () => {+ const path = preferenceHistoryPath(vault, "tabs");+ writeFileSync(+ path,+ [+ JSON.stringify(entry({})),+ "this is not json",+ JSON.stringify({ partial: true }),+ JSON.stringify(entry({ revision: 2, field: "scope", after: "writing" })),+ "",+ ].join("\n"),+ );+ const read = readEditHistory(vault, "tabs");+ expect(read.length).toBe(2);+ expect(read.map((e) => e.revision)).toEqual([1, 2]);+ });+});++describe("renderEditHistory", () => {+ test("renders a deterministic timeline ordered by revision then field", () => {+ const out = renderEditHistory([+ entry({ revision: 2, field: "scope", before: null, after: "coding" }),+ entry({ revision: 1, field: "principle", before: "use tabs", after: "use spaces" }),+ ]);+ const firstRev = out.indexOf("rev 1");+ const secondRev = out.indexOf("rev 2");+ expect(firstRev).toBeGreaterThanOrEqual(0);+ expect(firstRev).toBeLessThan(secondRev);+ expect(out).toContain("principle");+ expect(out).toContain("use tabs");+ expect(out).toContain("use spaces");+ });++ test("renders an empty timeline as a stable placeholder", () => {+ expect(renderEditHistory([]).trim().length).toBeGreaterThan(0);+ });+});diff --git a/tests/core/brain/health/reconcile.test.ts b/tests/core/brain/health/reconcile.test.tsnew file mode 100644index 00000000..9d196d48--- /dev/null+++ b/tests/core/brain/health/reconcile.test.ts@@ -0,0 +1,125 @@+/**+ * Semantic-health reconciliation surface (F6).+ *+ * A single deterministic pass that runs the three detectors partitioned+ * into domains and folds their findings into one verdict. No sub-agents,+ * no IO - the caller hands in already-gathered data.+ *+ * Verdict escalation: a contradiction between two confirmed preferences+ * is the most serious finding (two active rules disagree) and forces+ * `investigate`; gaps or stale claims alone are `watch`; nothing is+ * `clean`.+ */++import { describe, expect, test } from "bun:test";++import {+ BRAIN_PREFERENCE_STATUS,+ BRAIN_SIGNAL_SIGN,+} from "../../../../src/core/brain/types.ts";+import {+ reconcileSemanticHealth,+ type PreferenceForHealth,+} from "../../../../src/core/brain/health/reconcile.ts";++const NOW = new Date("2026-05-27T00:00:00Z");++function pref(over: Partial<PreferenceForHealth> & Pick<PreferenceForHealth, "id">): PreferenceForHealth {+ return {+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ scope: "coding",+ principle: "",+ evidenced_by: [],+ last_evidence_at: null,+ ...over,+ };+}++const signs = new Map([+ ["sig-pos", BRAIN_SIGNAL_SIGN.positive],+ ["sig-neg", BRAIN_SIGNAL_SIGN.negative],+]);++const config = {+ contradictionJaccard: 0.5,+ conceptGapMinFrequency: 3,+ staleClaimMaxAgeDays: 90,+ now: NOW,+};++describe("reconcileSemanticHealth", () => {+ test("clean vault yields a clean verdict and empty domains", () => {+ const report = reconcileSemanticHealth(+ {+ preferences: [pref({ id: "pref-a", principle: "write tests first" })],+ signSignById: signs,+ corpusPrinciples: ["write tests first"],+ coveredTopics: ["tests-first"],+ },+ config,+ );+ expect(report.verdict).toBe("clean");+ expect(report.contradictions).toEqual([]);+ expect(report.conceptGaps).toEqual([]);+ expect(report.staleClaims).toEqual([]);+ });++ test("a contradiction forces an investigate verdict", () => {+ const report = reconcileSemanticHealth(+ {+ preferences: [+ pref({+ id: "pref-a",+ principle: "always indent source with tabs not spaces",+ evidenced_by: ["[[sig-pos]]"],+ }),+ pref({+ id: "pref-b",+ principle: "never indent source with tabs always spaces",+ evidenced_by: ["[[sig-neg]]"],+ }),+ ],+ signSignById: signs,+ corpusPrinciples: [],+ coveredTopics: [],+ },+ config,+ );+ expect(report.contradictions.length).toBe(1);+ expect(report.verdict).toBe("investigate");+ });++ test("only stale claims yields a watch verdict", () => {+ const report = reconcileSemanticHealth(+ {+ preferences: [+ pref({+ id: "pref-old",+ principle: "ship on fridays",+ last_evidence_at: "2026-01-01T00:00:00Z",+ }),+ ],+ signSignById: signs,+ corpusPrinciples: [],+ coveredTopics: [],+ },+ config,+ );+ expect(report.staleClaims.length).toBe(1);+ expect(report.verdict).toBe("watch");+ });++ test("only concept gaps yields a watch verdict", () => {+ const report = reconcileSemanticHealth(+ {+ preferences: [],+ signSignById: signs,+ corpusPrinciples: ["Kanban slow", "Kanban stuck", "Kanban grooming"],+ coveredTopics: [],+ },+ config,+ );+ expect(report.conceptGaps.map((g) => g.term)).toContain("kanban");+ expect(report.verdict).toBe("watch");+ });+});diff --git a/tests/core/brain/health/remediation.test.ts b/tests/core/brain/health/remediation.test.tsnew file mode 100644index 00000000..e589c40e--- /dev/null+++ b/tests/core/brain/health/remediation.test.ts@@ -0,0 +1,128 @@+/**+ * Dependency-ordered remediation planner + executor (F5).+ *+ * planRemediation turns findings into a deterministically-ordered plan+ * that classifies each step auto-safe (deterministic, reversible, no+ * judgment) or needs-review. applyRemediation mutates nothing under+ * dry-run, applies only auto-safe steps otherwise, and stops at a step+ * cap. The single auto-safe action is a lossless content-hash re-stamp.+ */++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 { computeContentHash } from "../../../../src/core/brain/content-hash.ts";+import { brainDirs } from "../../../../src/core/brain/paths.ts";+import { parsePreference, writePreference } from "../../../../src/core/brain/preference.ts";+import {+ applyRemediation,+ planRemediation,+} from "../../../../src/core/brain/health/remediation.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-remediation-"));+ mkdirSync(brainDirs(vault).preferences, { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function writeDriftedPref(slug: string): void {+ writePreference(+ vault,+ {+ slug,+ topic: slug,+ principle: "always write tests first in production code",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ content_hash: "0000000000000000000000000000000000000000000000000000000000000000",+ },+ { overwrite: true },+ );+}++const allFindings = {+ driftedSlugs: ["b-drift", "a-drift"],+ contradictions: [{ aId: "pref-x", bId: "pref-y" }],+ staleClaims: [{ id: "pref-stale" }],+ conceptGaps: [{ term: "kanban" }],+};++describe("planRemediation", () => {+ test("classifies drift auto-safe and everything else needs-review", () => {+ const plan = planRemediation(allFindings, { stepCap: 10 });+ const auto = plan.steps.filter((s) => s.classification === "auto-safe");+ const review = plan.steps.filter((s) => s.classification === "needs-review");+ expect(auto.map((s) => s.code)).toEqual([+ "content-hash-drift",+ "content-hash-drift",+ ]);+ expect(review.map((s) => s.code).sort()).toEqual([+ "concept-gap",+ "contradictory-preferences",+ "stale-claim",+ ]);+ });++ test("orders auto-safe structural fixes before semantic review steps", () => {+ const plan = planRemediation(allFindings, { stepCap: 10 });+ const firstReview = plan.steps.findIndex((s) => s.classification === "needs-review");+ const lastAuto = plan.steps.map((s) => s.classification).lastIndexOf("auto-safe");+ expect(lastAuto).toBeLessThan(firstReview);+ });++ test("orders deterministically by target within a code", () => {+ const plan = planRemediation(allFindings, { stepCap: 10 });+ const driftTargets = plan.steps+ .filter((s) => s.code === "content-hash-drift")+ .map((s) => s.target);+ expect(driftTargets).toEqual(["a-drift", "b-drift"]);+ });+});++describe("applyRemediation", () => {+ test("dry-run applies nothing and leaves the file untouched", () => {+ writeDriftedPref("a-drift");+ const plan = planRemediation({ ...allFindings, driftedSlugs: ["a-drift"] }, { stepCap: 10 });+ const outcome = applyRemediation(vault, plan, { dryRun: true });+ expect(outcome.dryRun).toBe(true);+ expect(outcome.applied.map((s) => s.target)).toEqual(["a-drift"]);+ // still drifted - no write happened+ const pref = parsePreference(brainDirs(vault).preferences + "/pref-a-drift.md");+ expect(pref.content_hash).not.toBe(computeContentHash(pref.principle, pref.scope));+ });++ test("re-stamps a drifted content hash and skips needs-review steps", () => {+ writeDriftedPref("a-drift");+ const plan = planRemediation({ ...allFindings, driftedSlugs: ["a-drift"] }, { stepCap: 10 });+ const outcome = applyRemediation(vault, plan, { dryRun: false });+ expect(outcome.applied.map((s) => s.code)).toEqual(["content-hash-drift"]);+ expect(outcome.skipped.every((s) => s.classification === "needs-review")).toBe(true);+ const pref = parsePreference(brainDirs(vault).preferences + "/pref-a-drift.md");+ expect(pref.content_hash).toBe(computeContentHash(pref.principle, pref.scope));+ expect(pref.principle).toBe("always write tests first in production code");+ });++ test("the step cap bounds how many auto-safe steps are applied", () => {+ writeDriftedPref("a-drift");+ writeDriftedPref("b-drift");+ const plan = planRemediation(+ { driftedSlugs: ["a-drift", "b-drift"], contradictions: [], staleClaims: [], conceptGaps: [] },+ { stepCap: 1 },+ );+ const outcome = applyRemediation(vault, plan, { dryRun: false });+ expect(outcome.applied.length).toBe(1);+ expect(outcome.applied[0]!.target).toBe("a-drift");+ expect(outcome.skipped.map((s) => s.target)).toContain("b-drift");+ });+});diff --git a/tests/core/brain/health/stale-claim.test.ts b/tests/core/brain/health/stale-claim.test.tsnew file mode 100644index 00000000..e67c443f--- /dev/null+++ b/tests/core/brain/health/stale-claim.test.ts@@ -0,0 +1,99 @@+/**+ * Stale-claim detector (F3).+ *+ * Flags confirmed preferences whose newest supporting evidence is older+ * than a configured age window. The clock is injected so the detector+ * stays deterministic; preferences with no evidence date are skipped+ * (their absence is reported by other lints).+ */++import { describe, expect, test } from "bun:test";++import { BRAIN_PREFERENCE_STATUS } from "../../../../src/core/brain/types.ts";+import {+ detectStaleClaims,+ type PreferenceForStaleClaim,+} from "../../../../src/core/brain/health/stale-claim.ts";++const NOW = new Date("2026-05-27T00:00:00Z");++function pref(+ over: Partial<PreferenceForStaleClaim> & Pick<PreferenceForStaleClaim, "id">,+): PreferenceForStaleClaim {+ return {+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ last_evidence_at: null,+ ...over,+ };+}++describe("detectStaleClaims", () => {+ test("flags a confirmed preference older than the window", () => {+ const stale = detectStaleClaims(+ [pref({ id: "pref-old", last_evidence_at: "2026-01-01T00:00:00Z" })],+ { maxAgeDays: 90, now: NOW },+ );+ expect(stale).toEqual([+ { id: "pref-old", lastEvidenceAt: "2026-01-01T00:00:00Z", ageDays: 146 },+ ]);+ });++ test("does not flag a preference inside the window", () => {+ const stale = detectStaleClaims(+ [pref({ id: "pref-fresh", last_evidence_at: "2026-05-01T00:00:00Z" })],+ { maxAgeDays: 90, now: NOW },+ );+ expect(stale).toEqual([]);+ });++ test("skips preferences with no evidence date", () => {+ const stale = detectStaleClaims(+ [pref({ id: "pref-none", last_evidence_at: null })],+ { maxAgeDays: 90, now: NOW },+ );+ expect(stale).toEqual([]);+ });++ test("skips unconfirmed preferences", () => {+ const stale = detectStaleClaims(+ [+ pref({+ id: "pref-unconf",+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,+ last_evidence_at: "2026-01-01T00:00:00Z",+ }),+ ],+ { maxAgeDays: 90, now: NOW },+ );+ expect(stale).toEqual([]);+ });++ test("ignores a future evidence date (negative age)", () => {+ const stale = detectStaleClaims(+ [pref({ id: "pref-future", last_evidence_at: "2026-12-01T00:00:00Z" })],+ { maxAgeDays: 90, now: NOW },+ );+ expect(stale).toEqual([]);+ });++ test("parses a date-only evidence value deterministically as UTC midnight", () => {+ const stale = detectStaleClaims(+ [pref({ id: "pref-dateonly", last_evidence_at: "2026-01-01" })],+ { maxAgeDays: 90, now: NOW },+ );+ expect(stale).toEqual([+ { id: "pref-dateonly", lastEvidenceAt: "2026-01-01", ageDays: 146 },+ ]);+ });++ test("orders findings by age descending", () => {+ const stale = detectStaleClaims(+ [+ pref({ id: "pref-b", last_evidence_at: "2026-02-01T00:00:00Z" }),+ pref({ id: "pref-a", last_evidence_at: "2026-01-01T00:00:00Z" }),+ ],+ { maxAgeDays: 30, now: NOW },+ );+ expect(stale.map((s) => s.id)).toEqual(["pref-a", "pref-b"]);+ });+});diff --git a/tests/core/brain/policy-health.test.ts b/tests/core/brain/policy-health.test.tsnew file mode 100644index 00000000..c6c2fe48--- /dev/null+++ b/tests/core/brain/policy-health.test.ts@@ -0,0 +1,79 @@+/**+ * `health` block (v0.14.0) - tunes the semantic-health detectors and+ * the remediation step cap. Absent block falls back to+ * `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.+ */++import { describe, expect, test } from "bun:test";++import {+ BRAIN_HEALTH_DEFAULTS,+ BrainConfigError,+ parseBrainYaml,+ resolveHealth,+ validateBrainConfigDetailed,+} from "../../../src/core/brain/policy.ts";++function validate(yaml: string) {+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");+}++const HEAD = `schema_version: 1\n`;++describe("BRAIN_HEALTH_DEFAULTS", () => {+ test("documents the four knob defaults", () => {+ expect(BRAIN_HEALTH_DEFAULTS.contradiction_jaccard).toBe(0.5);+ expect(BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency).toBe(3);+ expect(BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days).toBe(180);+ expect(BRAIN_HEALTH_DEFAULTS.remediation_step_cap).toBe(20);+ });+});++describe("health config block", () => {+ test("absent block → cfg.health undefined; resolveHealth returns defaults", () => {+ const { config } = validate(HEAD);+ expect(config.health).toBeUndefined();+ expect(resolveHealth(config)).toEqual(BRAIN_HEALTH_DEFAULTS);+ });++ test("present with all fields → loaded fully", () => {+ const { config } = validate(+ HEAD ++ `health:\n` ++ ` contradiction_jaccard: 0.7\n` ++ ` concept_gap_min_frequency: 5\n` ++ ` stale_claim_max_age_days: 90\n` ++ ` remediation_step_cap: 4\n`,+ );+ expect(resolveHealth(config)).toEqual({+ contradiction_jaccard: 0.7,+ concept_gap_min_frequency: 5,+ stale_claim_max_age_days: 90,+ remediation_step_cap: 4,+ });+ });++ test("partial block → missing fields fall back to defaults", () => {+ const { config } = validate(HEAD + `health:\n concept_gap_min_frequency: 2\n`);+ const resolved = resolveHealth(config);+ expect(resolved.concept_gap_min_frequency).toBe(2);+ expect(resolved.contradiction_jaccard).toBe(BRAIN_HEALTH_DEFAULTS.contradiction_jaccard);+ });++ test("contradiction_jaccard out of (0, 1] is rejected", () => {+ expect(() => validate(HEAD + `health:\n contradiction_jaccard: 1.5\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("a non-positive integer knob is rejected", () => {+ expect(() => validate(HEAD + `health:\n concept_gap_min_frequency: 0\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("an unknown sub-key is a forward-compat warning, not an error", () => {+ const { warnings } = validate(HEAD + `health:\n future_knob: 1\n`);+ expect(warnings.some((w) => w.message.includes("health.future_knob"))).toBe(true);+ });+});diff --git a/tests/core/brain/preference-txn-history.test.ts b/tests/core/brain/preference-txn-history.test.tsnew file mode 100644index 00000000..3ba5467e--- /dev/null+++ b/tests/core/brain/preference-txn-history.test.ts@@ -0,0 +1,91 @@+/**+ * Edit-history wiring at the write chokepoint (F4, Task 6).+ *+ * When `writePreferenceTxn` is given an edit-history option and the+ * write actually changes bytes, it appends field-level before/after+ * entries keyed by the resulting revision. A no-op rewrite appends+ * nothing; callers that omit the option create no sidecar (back-compat).+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ brainDirs,+ preferenceHistoryPath,+} from "../../../src/core/brain/paths.ts";+import { writePreferenceTxn } from "../../../src/core/brain/preference-txn.ts";+import { readEditHistory } from "../../../src/core/brain/health/edit-history.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-pref-txn-hist-"));+ mkdirSync(brainDirs(vault).preferences, { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++const baseInput = (overrides: Record<string, unknown> = {}) => ({+ slug: "test-rule",+ topic: "test-topic",+ principle: "do the right thing in production code",+ created_at: "2026-05-26T12:00:00Z",+ unconfirmed_until: "2026-06-02T12:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,+ evidenced_by: [] as ReadonlyArray<string>,+ ...overrides,+});++const history = {+ agent: "tester",+ now: () => new Date("2026-05-27T00:00:00Z"),+};++describe("writePreferenceTxn edit-history", () => {+ test("first write seeds the trail from current state", () => {+ writePreferenceTxn(vault, baseInput(), [], {}, history);+ const entries = readEditHistory(vault, "test-rule");+ const fields = entries.map((e) => e.field).sort();+ expect(fields).toEqual(["principle", "status"]);+ const principle = entries.find((e) => e.field === "principle")!;+ expect(principle.revision).toBe(1);+ expect(principle.before).toBeNull();+ expect(principle.after).toBe("do the right thing in production code");+ expect(principle.agent).toBe("tester");+ });++ test("a content change records the changed field at the new revision", () => {+ writePreferenceTxn(vault, baseInput(), [], {}, history);+ writePreferenceTxn(+ vault,+ baseInput({ principle: "always write tests first in code" }),+ [],+ { overwrite: true },+ history,+ );+ const entries = readEditHistory(vault, "test-rule");+ const rev2 = entries.filter((e) => e.revision === 2);+ expect(rev2.length).toBe(1);+ expect(rev2[0]!.field).toBe("principle");+ expect(rev2[0]!.before).toBe("do the right thing in production code");+ expect(rev2[0]!.after).toBe("always write tests first in code");+ });++ test("a no-op rewrite appends nothing new", () => {+ writePreferenceTxn(vault, baseInput(), [], {}, history);+ const before = readEditHistory(vault, "test-rule").length;+ writePreferenceTxn(vault, baseInput(), [], { overwrite: true }, history);+ expect(readEditHistory(vault, "test-rule").length).toBe(before);+ });++ test("omitting the history option creates no sidecar", () => {+ writePreferenceTxn(vault, baseInput(), [], {});+ expect(existsSync(preferenceHistoryPath(vault, "test-rule"))).toBe(false);+ });+});diff --git a/tests/core/brain/sign.test.ts b/tests/core/brain/sign.test.tsnew file mode 100644index 00000000..4bad673f--- /dev/null+++ b/tests/core/brain/sign.test.ts@@ -0,0 +1,77 @@+/**+ * Tests for the shared "sign of record" helper lifted out of+ * `dream.ts` so the contradiction detector and the dream pass agree on+ * one polarity definition. The evidence-based tier-1 derivation is the+ * reusable part; the tie-break (`pos >= neg -> positive`) and the+ * unresolved-as-skip behaviour mirror dream verbatim.+ */++import { describe, expect, test } from "bun:test";++import { BRAIN_SIGNAL_SIGN } from "../../../src/core/brain/types.ts";+import {+ countSigns,+ dominantSignFromCounts,+ dominantSignOf,+} from "../../../src/core/brain/sign.ts";++describe("countSigns", () => {+ test("counts positive and negative signs", () => {+ const c = countSigns([+ BRAIN_SIGNAL_SIGN.positive,+ BRAIN_SIGNAL_SIGN.positive,+ BRAIN_SIGNAL_SIGN.negative,+ ]);+ expect(c).toEqual({ pos: 2, neg: 1 });+ });++ test("empty input yields zero counts", () => {+ expect(countSigns([])).toEqual({ pos: 0, neg: 0 });+ });+});++describe("dominantSignFromCounts", () => {+ test("no signs is unknown", () => {+ expect(dominantSignFromCounts(0, 0)).toBe("unknown");+ });++ test("positive majority is positive", () => {+ expect(dominantSignFromCounts(3, 1)).toBe(BRAIN_SIGNAL_SIGN.positive);+ });++ test("negative majority is negative", () => {+ expect(dominantSignFromCounts(1, 3)).toBe(BRAIN_SIGNAL_SIGN.negative);+ });++ test("tie breaks to positive (matches dream's pos >= neg)", () => {+ expect(dominantSignFromCounts(2, 2)).toBe(BRAIN_SIGNAL_SIGN.positive);+ });+});++describe("dominantSignOf", () => {+ const byId = new Map([+ ["sig-a", BRAIN_SIGNAL_SIGN.positive],+ ["sig-b", BRAIN_SIGNAL_SIGN.positive],+ ["sig-c", BRAIN_SIGNAL_SIGN.negative],+ ]);++ test("resolves wikilinks and returns dominant sign", () => {+ expect(dominantSignOf(["[[sig-a]]", "[[sig-c]]", "[[sig-b]]"], byId)).toBe(+ BRAIN_SIGNAL_SIGN.positive,+ );+ });++ test("ignores wikilinks that do not resolve in the map", () => {+ expect(dominantSignOf(["[[sig-c]]", "[[sig-missing]]"], byId)).toBe(+ BRAIN_SIGNAL_SIGN.negative,+ );+ });++ test("returns unknown when no cited signal resolves", () => {+ expect(dominantSignOf(["[[sig-missing]]", "[[other]]"], byId)).toBe("unknown");+ });++ test("returns unknown for an empty evidence list", () => {+ expect(dominantSignOf([], byId)).toBe("unknown");+ });+});diff --git a/tests/mcp/brain-health.test.ts b/tests/mcp/brain-health.test.tsnew file mode 100644index 00000000..8b09ea9b--- /dev/null+++ b/tests/mcp/brain-health.test.ts@@ -0,0 +1,107 @@+/**+ * brain_health MCP tool (F6 surface): returns the semantic-health+ * report (contradiction / concept-gap / stale-claim domains + verdict)+ * produced by runDoctor's reconciliation pass. Read-only.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { BRAIN_PREFERENCE_STATUS, BRAIN_SIGNAL_SIGN } from "../../src/core/brain/types.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-health-"));+ vault = join(tmp, "vault");+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {+ mkdirSync(join(vault, "Brain", d), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-health-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "health-test", version: "0" } },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+}++async function callTool(server: MCPServer, name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name, arguments: args },+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };+ return JSON.parse(r.result.content[0]!.text);+}++describe("brain_health MCP tool", () => {+ test("clean vault returns a clean verdict and empty domains", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callTool(server, "brain_health", {});+ expect(out["verdict"]).toBe("clean");+ expect(out["contradictions"]).toEqual([]);+ expect(out["concept_gaps"]).toEqual([]);+ expect(out["stale_claims"]).toEqual([]);+ });++ test("contradictory preferences surface with an investigate verdict", async () => {+ const pos = writeSignal(vault, {+ topic: "indentation", signal: BRAIN_SIGNAL_SIGN.positive, agent: "t",+ principle: "use tabs", created_at: "2026-05-01T00:00:00Z", date: "2026-05-01", slug: "tabs-pos",+ }).id;+ const neg = writeSignal(vault, {+ topic: "indentation", signal: BRAIN_SIGNAL_SIGN.negative, agent: "t",+ principle: "use spaces", created_at: "2026-05-01T00:00:00Z", date: "2026-05-01", slug: "tabs-neg",+ }).id;+ for (const [slug, principle, ev] of [+ ["tabs-rule", "always indent source with tabs not spaces", pos],+ ["spaces-rule", "never indent source with tabs always spaces", neg],+ ] as const) {+ writePreference(vault, {+ slug, topic: slug, principle,+ created_at: "2026-05-01T00:00:00Z", unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z", status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[${ev}]]`],+ }, { overwrite: true });+ }+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callTool(server, "brain_health", {});+ expect(out["verdict"]).toBe("investigate");+ expect((out["contradictions"] as unknown[]).length).toBe(1);+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 716e0eea..f0f9b06d 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -172,6 +172,7 @@ describe("tool listing", () => {"brain_digest","brain_query","brain_doctor",+ "brain_health","brain_backlinks","brain_context_pack","brain_unlinked_mentions",@@ -382,12 +383,13 @@ describe("stdio loop", () => {const list = JSON.parse(lines[1]!);expect(init.id).toBe(1);expect(list.id).toBe(2);- // v0.12.0: 3 core + 20 Brain (brain_review_candidates added in- // v0.12.0 Brain Integrity Suite, brain_timeline /- // brain_belief_evolution / brain_stale_scan / brain_daily_brief /- // brain_weekly_synthesis added v0.10.18)- // + 8 Pay Memory + 1 Search = 32.- expect(list.result.tools.length).toBe(32);+ // v0.14.0: 3 core + 21 Brain (brain_health added in v0.14.0+ // Semantic Brain Health; brain_review_candidates added in v0.12.0+ // Brain Integrity Suite; brain_timeline / brain_belief_evolution /+ // brain_stale_scan / brain_daily_brief / brain_weekly_synthesis+ // added v0.10.18)+ // + 8 Pay Memory + 1 Search = 33.+ expect(list.result.tools.length).toBe(33);});test("returns parse error for invalid JSON", async () => {