Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: Entity Truth & Self-Improving Dream Suite - claim ledger, outcome-aware dream, foresight (#74)
Sol Aitkena0054dd95317
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 34fc6ad5..629dd5c2 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.42.0",+ "version": "0.43.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 02716fea..00fb37fd 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.42.0",+ "version": "0.43.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 1f0c914f..81c58c83 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,92 @@ 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.43.0] - 2026-06-04++Entity Truth & Self-Improving Dream Suite: a current-truth surface+over entities and a dream pass that learns from outcomes, not only+from claims. An append-only claim ledger folds extracted facts into+addressable per-entity aspect slots with superseded history, detects+contradictions and cross-agent convergence, guards merges against+collapsing different people's claims, and answers quantitative+questions by exact-match aggregation; on the learning side,+apply-evidence carries a downstream outcome that stages regression+findings against rules that look confirmed but hurt, failed+approaches persist as recallable negative knowledge, inbox signals+rank by embedding novelty, the weekly synthesis nominates the+most-developable note, and a foresight fold projects what comes due+next. Everything is deterministic, bounded, fail-closed, and+explainable; a vault without the new data behaves bit-identically.+MCP tool count grows 66 -> 69.++### Added++- **Entity claim ledger** (`Brain/truth/`). Device-sharded append-only+ JSONL claim events (`claims.<deviceId>.jsonl`, schema-versioned,+ fail-closed line parsing) fold into per-`(entity, aspect)` slots+ holding the current value plus superseded history with provenance+ lineage; the derived `state.json` is a recomputable cache, never+ authority. Conflict detection is purely temporal-structural: two+ distinct values for one slot within the window (default 30d) from+ independent sources materialize a `value_conflict` with+ `resolution: ask_user` - never auto-resolved - while a later value+ outside the window supersedes silently. `o2b brain truth+ ingest|slots|conflicts|aggregate|collisions|sweep` and the+ `brain_truth` MCP tool are the operator surface.+- **Atomic-fact decomposition and the quantity family**. `o2b brain+ facts decompose` deterministically splits session text into discrete+ assertions via markdown structure (heading paths, list items,+ sentence boundaries with an abbreviation guard) anchored to+ canonical entities - no model calls; `--ingest` bridges+ structured-family assertions into the ledger. Fact extraction gains+ an actor-framed `quantity` family (spent/ran/worked + value + unit),+ and `aggregateQuantities` sums only exact `(entity, action, unit)`+ matches so nearby numbers never pollute a total.+- **Name-aware merge guard and contamination check**. `mergePreferences`+ refuses to collapse claims about disjoint people/orgs+ (`entity-guard`, CLI `--force` bypass), and the deep-synthesis+ dossier flags notes asserting registered entities their cited+ sources never mention (`entity_contamination` dimension, present+ only when the vault has an entity registry).+- **Cross-agent collision detection**. Two agents independently+ logging claims about one entity within 14 days - citing different+ sources - surface push-mode through the standing trigger queue as+ the new `agent_collision` kind with cooldown dedup, instead of+ waiting for an operator-run diff.+- **Outcome-tied apply-evidence**. `brain_apply_evidence` and the CLI+ accept an optional `outcome: success|failure|unknown`; the dream+ refresh stages an `outcome_regressions` finding with a deterministic+ 0.8 confidence penalty when applied events carry 2+ failures+ outnumbering successes - staged, never silent retirement, idempotent+ on rerun.+- **Dead-end registry** (`Brain/dead-ends/`). Tried-and-failed+ approaches persist as markdown notes (approach + why it failed ++ context) bounded to the most-recent-N with archive-on-overflow;+ FTS indexes them with zero search changes so recall surfaces+ "avoid X" alongside "prefer Y". `o2b brain dead-end record|list`+ and the `brain_dead_ends` MCP tool.+- **Surprisal novelty sampling**. Inbox signals rank by mean kNN+ distance to their nearest indexed neighbours over the existing+ sqlite-vec index (zero provider calls); `brain_review_candidates`+ gains a `signal_novelty` annotation present only when at least one+ signal actually scores.+- **Weekly top-source**. The weekly synthesis nominates the single+ most-developable note of the window (recency + inbound links + link+ centrality, per-signal breakdown, one-line why), absent when nothing+ qualified.+- **Foresight** (`o2b brain foresight`, `brain_foresight`). The+ Brain's first forward-looking fold: recurrence cadences project+ next-due routines inside the horizon (default 14d), recent open+ commitments and open questions surface with sources; `--write`+ persists `Brain/foresight/<date>.md`.++### Changed++- `extractFacts`' span dedup key is now written with a `\u0000`+ escape instead of a literal NUL byte, so the file diffs as text+ again; chunk embeddings are copied out of the SQLite buffer instead+ of viewed, hardening against unaligned pooled buffers.+## [0.42.0] - 2026-06-04Time-Aware Recall & Activation Suite: ranking that reflects what the@@ -4516,6 +4602,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.43.0]: https://github.com/itechmeat/open-second-brain/compare/v0.42.0...v0.43.0[0.42.0]: https://github.com/itechmeat/open-second-brain/compare/v0.41.0...v0.42.0[0.41.0]: https://github.com/itechmeat/open-second-brain/compare/v0.40.0...v0.41.0[0.40.0]: https://github.com/itechmeat/open-second-brain/compare/v0.39.0...v0.40.0diff --git a/README.md b/README.mdindex ef87c267..a5b25835 100644--- a/README.md+++ b/README.md@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). 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.-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution). The v0.42.0 surface adds the Time-Aware Recall & Activation Suite: access-reinforced activation (CLI/MCP searches record surfaced documents as hashed one-file-per-access events; a bounded `activation` ranking boost decays stored strength by a content-type half-life table where preferences and decisions never fade; `o2b brain activation status | sweep` inspects and compacts the store), co-access reinforcement edges (habitual companions in the same candidate pool boost each other with a bounded `co_access` reason), dream-stamped `freshness_trend` on preferences (`new | strengthening | stable | weakening | stale` from the evidence time distribution, multiplying the relevance portion of recall), event-time recall discipline (`since`/`until` filters obey declared `valid_from`/`valid_until` validity windows by overlap, with mtime only as the fallback), temporal-bridge traversal (time-scoped queries pull in linked causes and consequences from a padded event-time neighbourhood instead of leaking arbitrary old neighbours), and self-correcting two-pass recall (a zero-candidate evidence-pack query runs exactly one broadened OR retry, reported as `secondPass`).+The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution). The v0.42.0 surface adds the Time-Aware Recall & Activation Suite: access-reinforced activation (CLI/MCP searches record surfaced documents as hashed one-file-per-access events; a bounded `activation` ranking boost decays stored strength by a content-type half-life table where preferences and decisions never fade; `o2b brain activation status | sweep` inspects and compacts the store), co-access reinforcement edges (habitual companions in the same candidate pool boost each other with a bounded `co_access` reason), dream-stamped `freshness_trend` on preferences (`new | strengthening | stable | weakening | stale` from the evidence time distribution, multiplying the relevance portion of recall), event-time recall discipline (`since`/`until` filters obey declared `valid_from`/`valid_until` validity windows by overlap, with mtime only as the fallback), temporal-bridge traversal (time-scoped queries pull in linked causes and consequences from a padded event-time neighbourhood instead of leaking arbitrary old neighbours), and self-correcting two-pass recall (a zero-candidate evidence-pack query runs exactly one broadened OR retry, reported as `secondPass`). The v0.43.0 surface adds the Entity Truth & Self-Improving Dream Suite: an append-only entity claim ledger under `Brain/truth/` (device-sharded JSONL claim events folded into per-`(entity, aspect)` slots with current value, superseded history, temporal-structural `value_conflict` detection that is always `ask_user`, exact-match quantity aggregation, and `o2b brain truth` / MCP `brain_truth` surfaces), deterministic atomic-fact decomposition (`o2b brain facts decompose`, markdown-structure splitting with an abbreviation guard and optional `--ingest` into the ledger), an actor-framed `quantity` fact family, a name-aware merge guard (`entity-guard` refusal with `--force` bypass) plus an `entity_contamination` deep-synthesis dimension, push-mode cross-agent collision triggers (`agent_collision` kind with cooldown dedup), outcome-tied apply-evidence (`outcome: success|failure|unknown` staging `outcome_regressions` with a deterministic confidence penalty), a markdown-first dead-end registry (`o2b brain dead-end`, MCP `brain_dead_ends` - negative knowledge FTS-recallable beside positive rules), surprisal novelty ranking on `brain_review_candidates` over the existing sqlite-vec index, a weekly `topSource` nomination in the weekly synthesis, and the Brain's first forward-looking fold (`o2b brain foresight`, MCP `brain_foresight` - recurrence cadences project next-due routines, open commitments and questions surface with sources).## CLIdiff --git a/docs/brainstorm/entity-truth-dream-suite/cli-output/claude.md b/docs/brainstorm/entity-truth-dream-suite/cli-output/claude.mdnew file mode 100644index 00000000..dd2a6f3c--- /dev/null+++ b/docs/brainstorm/entity-truth-dream-suite/cli-output/claude.md@@ -0,0 +1,36 @@+### Variant 1: Ten Independent Feature Modules+- **Approach**: Treat each kanban task as a self-contained module with its own versioned store/envelope and its own CLI verb + MCP tool, sharing only the existing substrate (buildEntityIndex, dream.ts, weekly-brief.ts) read-only. Parent/child pairs (1↔2, 3↔4) sit in sibling files with a thin internal import rather than a shared abstraction. No new cross-cutting layer is introduced.+- **Trade-offs**:+ - Pro: maximum parallelizability — ten features can be built/tested/reviewed nearly independently; smallest blast radius per feature; bit-identical defaults are trivial to guarantee since each module is inert with no new data.+ - Pro: failure of one feature can't corrupt another; fail-closed parsing is per-store and simple.+ - Con: real duplication — entity-anchor resolution, claim addressing, and ranked-reason emission get reimplemented across conflicts/claim-slots/atomic-facts/contamination.+ - Con: weak synergy — claim slots (2), conflict records (1), and quantitative facts (4) clearly want one addressable per-entity representation; keeping them separate pushes integration cost downstream.+ - Con: ten new persisted formats to version and migrate.+- **Complexity**: large+- **Risk**: low++### Variant 2: Two Shared Backbones (Entity-Truth Ledger + Dream Signal Bus)+- **Approach**: Build one Entity-Truth Ledger that all of Half A reads/writes through — atomic-fact decomposition (3) and the quantitative family (4) feed addressable per-entity aspect slots (2), conflicts (1) and contamination checks are queries over that ledger, and cross-agent collision (5) diffs two agents' ledger writes. Half B introduces a Dream Signal Bus: surprisal (9), dead-ends (8), outcome-tied evidence (7), top-source (6), and foresight (10) all emit ranked, reasoned signals folded into the existing dream/weekly envelopes. Two cohesive cores instead of ten silos.+- **Trade-offs**:+ - Pro: strong cohesion where the domain genuinely shares structure — entity anchors and claim addressing live in exactly one place; conflict/slot/quantitative logic compose instead of duplicating.+ - Pro: cross-agent collision (5) and contamination (1) become near-free queries once the ledger exists; dream features share one ranking/reason convention.+ - Con: largest blast radius — the ledger sits on the hot fact-extraction path, so guaranteeing bit-identical neutral defaults requires careful gating.+ - Con: backbone must be designed before features land, reducing early parallelism; a ledger schema bug touches five features at once.+ - Con: temptation to over-generalize the bus for features (6, 10) that aren't really signals.+- **Complexity**: large+- **Risk**: medium++### Variant 3: Pure Fold-Over-Append-Only-Events+- **Approach**: Add no mutable state; every feature is a deterministic, replayable fold over existing append-only logs (sig-*.md, log JSONL, recurrence/events.jsonl) producing frozen envelopes, with new persisted artifacts limited to append-only event streams (conflict events, claim-supersede events, dead-end entries, foresight notes) each carrying a schema-version and fail-closed parser. Claim "current value" and conflict status are derived projections recomputed from the event stream, never stored mutably.+- **Trade-offs**:+ - Pro: most faithful to the stated convention (folds over mutable state, frozen replayable envelopes); bit-identical defaults fall out naturally since an empty event stream folds to the existing output.+ - Pro: provenance lineage (2) and superseded history are first-class because nothing is overwritten; auditing and rollback are uniform.+ - Pro: low risk to existing code — reads compose, writes only append.+ - Con: some features (claim slots with fast "what is true now", quantitative aggregation) need projection caches anyway, so a pure-fold stance leaks into derived stores regardless.+ - Con: recomputing folds for collision detection (5, push-mode within a recent window) and surprisal (9) on every event can be costly without indexing.+ - Con: more conceptual overhead per feature; contributors must think in folds even for simple checks.+- **Complexity**: medium+- **Risk**: low++### Recommended: Variant 2+**Rationale**: Half A's five features are not independent — atomic facts, the quantitative family, claim slots, conflicts, and contamination all revolve around one addressable per-entity claim representation, so a shared Entity-Truth Ledger eliminates the duplication of Variant 1 and the projection-cache awkwardness Variant 3 admits it would hit anyway. The medium risk it adds is concentrated on one well-understood path (fact extraction) and is manageable with the project's existing gating + fail-closed + bit-identical-default discipline, while the Dream Signal Bus for Half B reuses the established ranked-reason envelope-fold convention rather than inventing per-feature stores. Variant 1 ships faster but pushes integration debt downstream; Variant 3 is the cleanest philosophically but forces genuinely stateful artifacts (slots, lineage, registries) into a fold-only mold that doesn't fit them.diff --git a/docs/brainstorm/entity-truth-dream-suite/cli-output/prompt.md b/docs/brainstorm/entity-truth-dream-suite/cli-output/prompt.mdnew file mode 100644index 00000000..3478e1d7--- /dev/null+++ b/docs/brainstorm/entity-truth-dream-suite/cli-output/prompt.md@@ -0,0 +1,78 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Implement the "Entity Truth & Self-Improving Dream Suite" for Open Second Brain: ten related kanban tasks shipped as one release. The suite has two halves.++Half A - entity truth and facts:++1. (t_e9692750, p4) Entity-level truth maintenance: scan stored facts/notes for mutually-exclusive claims about the same entity ("works at Google" vs "works at Meta"), materialize a conflict record with type/priority/resolution strategy (ask_user) instead of silently keeping both; add a name-aware merge guard that blocks dedup-merging two notes whose entity anchors differ ("Alice decided X" must not collapse into "Bob decided X"); add an entity-contamination check rejecting synthesized conclusions that mention entities absent from their cited sources.+2. (t_d6849b56, p2, child of 1) Claim slots: organize extracted facts per entity into addressable aspect slots (e.g. "employer of Alice") where each slot holds a current value plus superseded prior values with provenance lineage; answer "what is true now" while keeping history queryable.+3. (t_cbd22536, p4) Atomic-fact decomposition: deterministically decompose session/turn content into discrete single-sentence assertions using markdown structure (headings/lists/sentences) plus the existing entity extractor - today only fixed-label regex lines (decision:/rule:/...) are captured. No LLM calls.+4. (t_220c313e, p2, child of 3) Quantitative fact family: extend fact extraction with a numeric family (counts, totals, durations, prices, quantities) capturing actor + measured action + target + value, and recall-side aggregation that only combines values satisfying exact-match constraints (excluding merely nearby numbers).+5. (t_f2b225b1, p4) Cross-agent collision detection: a push-mode detector that surfaces when two different agents have independently logged related-but-disconnected facts on the same topic/entity within a recent window, emitting a convergence note/alert instead of waiting for an operator to run a pull-mode diff. Existing substrate: agent-source diff builds shared/unique topics on demand.++Half B - self-improving dream:++6. (t_a8d49eae, p4) Weekly top-source: extend the deterministic weekly synthesis envelope to nominate the single most-developable note of the 7-day window (recency + inbound links + topical centrality) as one ranked finding with a one-sentence why.+7. (t_d478df53, p3) Outcome-tied apply-evidence: add an optional outcome field (success|failure|unknown) to apply-evidence events, and a dream-pass regression rule that flags/demotes a preference whose recent applied events co-occur with negative outcomes - a rule that looks confirmed but is actively hurting.+8. (t_be62c62d, p3) Dead-end registry: a negative-knowledge artifact class - agent-authored lessons recording what was tried and why it failed (or which approach was deliberately set aside), trimmed to most-recent-N, retrievable so recall can surface "avoid X" alongside "prefer Y". Today only positive procedures (skill proposals) exist.+9. (t_fddfe64a, p3) Surprisal sampling: rank dream-pass input signals by embedding-space novelty (distance to nearest neighbors over the existing sqlite-vec index) so the pass prioritizes genuinely new/outlier signals; degrade gracefully when embeddings are unavailable.+10. (t_08a79c81, p3) Foresight: a deterministic forward-projection pass over the continuity log + recurrence routines producing anticipatory notes (likely next needs, upcoming recurring obligations) as a distinct artifact kind - every existing temporal surface is retrospective.++# Project context++Open Second Brain: a Markdown+SQLite second-brain for AI agents. TypeScript on Bun, strict tsc, oxlint/oxfmt, bun test (3838 tests), python plugin suite for Hermes integration. Current version 0.42.0. Vault layout: Brain/inbox (sig-*.md signals), Brain/preferences, Brain/entities/<category>/<id>.md, Brain/log/<date>.md + JSONL device-sharded sidecars, Brain/procedural, Brain/recurrence/events.jsonl, Brain/search (FTS5 + sqlite-vec).++Recent commits:+b16c37d feat: Time-Aware Recall & Activation Suite (#73)+c3a2fcc feat: Agent Write Contract Suite (#72)+7733f20 feat: Project History Suite (#71)+8e8c0bc feat: Memory Observability Suite (#70)+eb56c9f feat: Workspace Insight Suite (#69)++Existing substrate (verified):+- fact-extract.ts: FactFamily = identity|preference|possession|location|url|email|confirmation; FAMILY_PATTERNS regex pairs; routeExtractedFacts writes sig-*.md signals with canonical entity anchors via buildEntityIndex.+- pre-compact-extract.ts: LABELS regex (decision:/commitment:/outcome:/rule:/open_question:) over turn buffers -> continuity records with dedupe keys.+- entities/registry.ts: upsertEntity/relateEntities/listEntities, markdown files with frontmatter, alias claims, canonical name normalization.+- agent-source/diff.ts+query.ts: per-agent contribution aggregation, buildSharedTopics/buildUniqueTopics (pull-mode only).+- temporal/weekly-brief.ts: WeeklySynthesisEnvelope {eventsByKind, statusTransitions, retired, contradictions, vaultDelta, sourcePointers}.+- dream.ts: scan signals -> cluster -> promote/retire, planRefresh computes confidence_value + freshness_trend, collectEvidenceForSlug scans log JSONL for apply-evidence rows, snapshot+rollback workrun, DreamRunSummary with warnings/uncertain/quarantined/gated_retires.+- apply-evidence.ts: appendApplyEvidence {pref_id, artifact, result: applied|violated|outdated, agent, note?} -> Brain/log markdown + JSONL.+- search/store.ts: semanticTopK over sqlite-vec; works only when embeddings indexed; keyword FTS fallback.+- recurrence.ts: append-only events.jsonl, commitment ladder exploring->leaning->decided->locked.+- skill-proposals.ts: positive-procedure mining from continuity records into Brain/procedural/proposals/pending.+- maintenance/action-scorer.ts: scoreDedup (content similarity, no entity check) feeding digest action items.+- deep-synthesis.ts: topic-scoped DeepSynthesisReport {notes, agreements, contradictions, staleClaims, gaps}.+- Versioned-envelope convention: schema-version constants (e.g. CONTINUITY_SCHEMA_VERSION "o2b.continuity.v1"), additive optional fields without bump.+- CLI verbs in src/cli/brain/verbs/<name>.ts + switch registration; MCP tools as ToolDefinition in src/mcp/brain-tools.ts.++Conventions:+- Deterministic, provider-free core paths; LLM/embedding-dependent features must degrade gracefully and be opt-in.+- Everything explainable: ranked outputs carry reasons; envelopes are frozen, replayable folds over append-only events preferred over mutable state.+- Fail-closed validation on persisted JSON; bounded caps (retention days, max counts) on every append-only store.+- One PR = one CHANGELOG version; ~50-70 files, 10 features max.++Constraints:+- No new external dependencies (no spaCy/GLiNER; pure TS heuristics only).+- No changes to existing public API semantics; new fields optional/additive.+- bit-identical neutral defaults: with no new data present, existing outputs (search results, dream runs, weekly envelopes) must not change.+- All new persisted formats need version fields and fail-closed parsing.+- Sentence decomposition must be deterministic (no model calls).++# 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/entity-truth-dream-suite/design.md b/docs/brainstorm/entity-truth-dream-suite/design.mdnew file mode 100644index 00000000..ba5e7bdd--- /dev/null+++ b/docs/brainstorm/entity-truth-dream-suite/design.md@@ -0,0 +1,70 @@+# Entity Truth & Self-Improving Dream Suite - one ledger for what is true, one feedback loop for what works++**Status:** approved+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain records facts, preferences, and evidence but has no notion of "what is true about this entity right now": two contradictory stored facts coexist silently, dedup can merge notes about different people, and synthesized conclusions can cite entities their sources never mention. On the learning side, the dream pass trusts self-reported evidence with no outcome signal, keeps no negative knowledge (what was tried and failed), treats all inbox signals as equally novel, and every temporal surface looks backward only.++## Scope++Half A - the Entity-Truth Ledger (`src/core/brain/truth/`):++- **Claim ledger** (t_d6849b56): device-sharded append-only JSONL (`Brain/truth/claims.<deviceId>.jsonl`) of versioned claim events `(entity, aspect, value, source, agent, ts)`; a deterministic fold projects per-`(entity, aspect)` slots holding the current value plus superseded history with provenance lineage.+- **Conflict detection** (t_e9692750): the same fold materializes conflict records when two distinct values for one slot land within the conflict window (default 30 days) from independent sources - typed, prioritized, `resolution: ask_user`, never auto-resolved.+- **Merge guard** (t_e9692750): a name-aware guard refuses dedup-merge recommendations and `brain merge` executions when the two notes' person/org entity anchors differ; explainable refusal reason.+- **Contamination check** (t_e9692750): validates that every entity mentioned in a synthesized conclusion appears in at least one cited source; exposed as a pure function plus CLI verb, wired into deep-synthesis report output.+- **Atomic-fact decomposition** (t_cbd22536): deterministic decomposer (`atomic-facts.ts`) splitting turn/session text into single assertions via markdown structure (heading context, list items, sentence boundaries with abbreviation guard), anchored to canonical entities via the existing entity index; assertions with `(entity, aspect)` shape ingest into the ledger via an explicit verb - the capture hot path is untouched.+- **Quantitative fact family** (t_220c313e): new `quantity` fact family (actor + measured action + target + numeric value + unit) in fact-extract patterns; quantity claims land in the ledger; `aggregateQuantities` sums only exact-`(entity, action, unit)` matches, never nearby numbers.+- **Cross-agent collision detection** (t_f2b225b1): a detector over recent ledger events that surfaces when two agents independently wrote related claims on the same entity within the window without referencing each other; runs inside dream/digest (push-mode) and as a verb; emits a convergence note event to `Brain/log/`.++Half B - self-improving dream (no new shared machinery; additive fields + small modules):++- **Weekly top-source** (t_a8d49eae): `WeeklySynthesisEnvelope` gains optional `topSource` - the single most-developable note of the window ranked by recency + inbound links + topical centrality, with a one-sentence why and the per-signal breakdown.+- **Outcome-tied apply-evidence** (t_d478df53): `appendApplyEvidence` accepts optional `outcome: success|failure|unknown`; dream's refresh detects preferences whose recent `applied` events co-occur with `failure` outcomes and stages an explainable `outcome_regressions` finding with a confidence penalty (demotion is staged, never silent retirement).+- **Dead-end registry** (t_be62c62d): negative-knowledge notes `Brain/dead-ends/*.md` (frontmatter `kind: brain-dead-end`, approach + why-it-failed + context), markdown-first so FTS indexes them for recall; bounded by most-recent-N with archive-on-overflow; CLI verb + MCP tool to record/list.+- **Surprisal sampling** (t_fddfe64a): novelty score per inbox signal = mean sqlite-vec distance to k nearest indexed chunks (existing embeddings only - no provider calls; neutral when vec index is empty); ranks `brain_review_candidates` ordering and annotates the dream summary; never changes which signals get processed.+- **Foresight** (t_08a79c81): deterministic forward projection `buildForesight` folding recurrence routines (cadence next-due), open commitments/open questions from continuity records, and recent log trends into a versioned `ForesightEnvelope` (`upcoming: recurring | commitment | trend` items with sources); CLI verb + MCP tool; optional `--write` persists `Brain/foresight/<date>.md`.++## Out of scope++- LLM/NER-based extraction (no spaCy/GLiNER; pure deterministic heuristics only).+- Auto-resolution of conflicts (strategy is always `ask_user` in this release).+- Observer-scoped beliefs (t_741a64b0), derived-fact synthesis (t_ec6df40a), staged dream bundles (t_ae8a8ec0) - separate cycles.+- UNIQUE-constraint canonical entity enforcement in SQLite (markdown registry stays the source of truth).+- Rewiring capture/pre-compact hot paths to auto-ingest into the ledger (explicit verb only this release).++## Chosen approach++Consultant Variant 2 (two cohesive cores) with three containment refinements (see variants.md): the Entity-Truth Ledger persists as fold-over-append-only events in the proven activation-store/log-jsonl shape rather than mutable state; Half B drops the "Dream Signal Bus" abstraction in favor of the existing ranked-`reasons` convention; the capture hot path stays bit-identical with ledger ingest as an explicit step. All of Half A composes over one claim representation: decomposition and the quantity family produce claims, slots fold them, conflicts and contamination are queries over the fold, collision diffs per-agent writes.++## Design decisions++- **Device-sharded JSONL for claims** - Syncthing-safe concurrent appends, matching `log-jsonl.ts`; the fold (`computeTruthState`) is order-insensitive and recomputable, matching `activation/store.ts`; derived `Brain/truth/state.json` is a cache, never authority.+- **`TRUTH_SCHEMA_VERSION = 1` on every event line + fail-closed parsing** - unknown/invalid lines are skipped with a counted warning, never crash, matching repo convention.+- **Conflict rule is purely temporal-structural** (same slot, distinct normalized values, within window, distinct sources): deterministic, no semantics guessing; later value outside the window supersedes silently (that is normal fact evolution).+- **Merge guard blocks only on disjoint person/org anchor sets** - notes with no entity anchors or overlapping anchors merge as today, so existing dedup behavior changes only where it was demonstrably unsafe.+- **Quantity aggregation requires exact `(entity, action, unit)` equality** after canonical normalization - the article's "exclude nearby numbers" rule made structural.+- **Markdown-first dead-ends** - notes index into FTS automatically, so "recall surfaces avoid-X" needs zero search changes; the bounded registry is a directory listing, not a parallel store.+- **Surprisal reads existing embeddings only** - graceful neutral degradation (`novelty: null`) without a vec index; review-candidates ordering is presentation, so dream mutations stay byte-identical.+- **Outcome regression stages, never retires** - a flagged preference gets `outcome_regressions` entry + confidence penalty; retirement still goes through existing gates (operator-auditable).+- **Foresight is a fold, not a planner** - only deterministic projections (cadence arithmetic, open items, trend counts); no speculation, every item carries `sources`.+- **Bit-identical neutral defaults everywhere** - empty ledger folds to empty state; absent outcome field keeps current confidence math; `topSource` is absent when the window has no candidates; foresight of an empty vault is an empty envelope.++## File changes++New core: `src/core/brain/truth/{types,store,fold,conflicts,merge-guard,contamination,collision,aggregate}.ts`, `src/core/brain/atomic-facts.ts`, `src/core/brain/dead-ends.ts`, `src/core/brain/surprisal.ts`, `src/core/brain/temporal/foresight.ts`.+Modified core: `fact-extract.ts` (quantity family), `apply-evidence.ts` (outcome), `dream.ts` (outcome regressions, collision step, surprisal annotation), `temporal/weekly-brief.ts` (topSource), `deep-synthesis.ts` (contamination wiring), `maintenance/action-scorer.ts` + merge verb (guard), `review-candidates.ts` (novelty ordering), `types.ts` (log event kinds).+CLI: new verbs `truth` (ingest/slots/conflicts/aggregate/collisions), `facts` (decompose), `dead-end` (record/list), `foresight`; registration in `brain.ts`, `verbs/index.ts`, help-text, command-manifest.+MCP: `brain_truth`, `brain_dead_ends`, `brain_foresight` tool definitions; schema extensions for `brain_apply_evidence` (outcome).+Tests: one suite per new module + integration e2e + CLI suites + extended existing suites (apply-evidence, weekly-brief, dream, fact-extract, review-candidates).+Docs: README, CHANGELOG 0.43.0, docs/cli-reference.md, docs/how-it-works.md.++## Risks and open questions++- Sentence splitting on prose is the least deterministic-feeling part - mitigate with a conservative splitter (paragraph/list/heading first, sentence split only with abbreviation guard) and golden-file tests.+- Aspect inference for claims ("employer of Alice") from free text is heuristic - restrict ledger auto-ingest to assertions matching the existing fact families (which carry structure) and accept explicit aspect on the verb; do not guess aspects from arbitrary prose.+- Dream summary growth - new findings (collisions, regressions, novelty) are bounded lists with caps, all optional fields.+- Performance of fold on large ledgers - same mitigation as activation store: retention caps + derived state cache keyed by event count/fingerprint.diff --git a/docs/brainstorm/entity-truth-dream-suite/plan.md b/docs/brainstorm/entity-truth-dream-suite/plan.mdnew file mode 100644index 00000000..136f8840--- /dev/null+++ b/docs/brainstorm/entity-truth-dream-suite/plan.md@@ -0,0 +1,65 @@+# Entity Truth & Self-Improving Dream Suite - implementation plan++TDD order: each task starts with failing tests, lands as one conventional commit, formatter + linter green before every commit.++## Tasks++### Task 1: Claim ledger core (types, store, fold) - t_d6849b56+- **Files**: `src/core/brain/truth/types.ts`, `truth/store.ts`, `truth/fold.ts`; tests `tests/core/brain/truth/store.test.ts`, `truth/fold.test.ts`+- **Acceptance**: append claim events to device-sharded JSONL; fold projects `(entity, aspect)` slots with current value + superseded history + provenance; order-insensitive fold; fail-closed line parsing (invalid lines counted, skipped); derived `Brain/truth/state.json` cache recomputable from events; retention caps enforced.+- **Depends on**: none++### Task 2: Conflict detection over the fold - t_e9692750+- **Files**: `truth/conflicts.ts`; extend fold state with conflicts; tests `truth/conflicts.test.ts`+- **Acceptance**: two distinct normalized values for one slot within the window (default 30d) from distinct sources materialize a typed conflict record (`resolution: ask_user`); later value outside window supersedes silently; conflicts queryable from fold state.+- **Depends on**: Task 1++### Task 3: Merge guard + contamination check - t_e9692750+- **Files**: `truth/merge-guard.ts`, `truth/contamination.ts`; guard wired into the merge execution path (`mergePreferences`, `entity-guard` error code, CLI `--force` maps to bypass); contamination wired into `deep-synthesis.ts` report; tests `truth/merge-guard.test.ts`, `truth/contamination.test.ts`. Deviation from the original sketch: `action-scorer` dedup recommendations come from `findDuplicateCandidates`, which groups EXACT-equal normalized text - both sides always carry identical anchors, so a scorer-side guard is dead code by construction; the guard lives where merges execute instead.+- **Acceptance**: disjoint person/org anchor sets block merge with explainable reason; overlapping/absent anchors unchanged; conclusions mentioning entities absent from cited sources flagged with the offending entities listed.+- **Depends on**: Task 1 (canonical entity normalization helpers)++### Task 4: Atomic-fact decomposition - t_cbd22536+- **Files**: `src/core/brain/atomic-facts.ts`; CLI verb `facts decompose` (+ optional `--ingest` to ledger); tests `tests/core/brain/atomic-facts.test.ts`, CLI test+- **Acceptance**: deterministic split by heading context / list items / sentences (abbreviation guard); assertions carry line, headingPath, canonical entity anchors; golden-file determinism test; fact-family-shaped assertions ingest as claim events via explicit flag only.+- **Depends on**: Task 1++### Task 5: Quantitative fact family + exact aggregation - t_220c313e+- **Files**: `fact-extract.ts` (quantity family), `truth/aggregate.ts`; tests extended fact-extract suite + `truth/aggregate.test.ts`+- **Acceptance**: quantity pattern captures actor + action + value + unit; `aggregateQuantities` sums only exact `(entity, action, unit)` matches after normalization; nearby-number exclusion test; existing families' outputs byte-identical.+- **Depends on**: Tasks 1, 4++### Task 6: Cross-agent collision detection - t_f2b225b1+- **Files**: `truth/collision.ts`; dream/digest push step + log event kind `collision`; tests `truth/collision.test.ts` + dream extension test+- **Acceptance**: claims on one entity/topic from 2+ distinct agents within the window, not referencing each other, emit one bounded convergence finding (push-mode in dream, pull-mode via verb); no events -> no findings (bit-identical dream summary).+- **Depends on**: Tasks 1, 2++### Task 7: Truth CLI verb + MCP tool surface+- **Files**: `src/cli/brain/verbs/truth.ts`, `verbs/facts.ts`; `brain.ts` switch, `verbs/index.ts`, help-text, command-manifest; `src/mcp/brain-tools.ts` `brain_truth`; CLI + MCP tests+- **Acceptance**: `brain truth ingest|slots|conflicts|aggregate|collisions` and `brain facts decompose` work end-to-end on a temp vault; MCP `brain_truth` returns frozen envelopes; exit codes 0/1/2 convention.+- **Depends on**: Tasks 1-6++### Task 8: Outcome-tied apply-evidence + dream regression rule - t_d478df53+- **Files**: `apply-evidence.ts` (optional `outcome`), MCP schema, CLI flag; `dream.ts` planRefresh regression detection (`outcome_regressions` in DreamRunSummary, staged confidence penalty); tests extended apply-evidence + dream suites+- **Acceptance**: outcome persisted in log markdown + JSONL; absent outcome keeps confidence math byte-identical; >=K recent applied-with-failure events stage a regression finding + penalty, never silent retirement; idempotent rerun stays no-op.+- **Depends on**: none (parallel to Half A)++### Task 9: Dead-end registry - t_be62c62d+- **Files**: `src/core/brain/dead-ends.ts`; CLI verb `dead-end record|list`; MCP `brain_dead_ends`; tests core + CLI+- **Acceptance**: markdown notes under `Brain/dead-ends/` with `kind: brain-dead-end` frontmatter (approach, reason, context, agent); bounded most-recent-N with archive-on-overflow; FTS finds them after indexing (recall smoke test).+- **Depends on**: none++### Task 10: Surprisal sampling - t_fddfe64a+- **Files**: `src/core/brain/surprisal.ts`; `review-candidates.ts` novelty ordering + annotation; dream summary annotation; tests core + extended review-candidates+- **Acceptance**: novelty = mean distance to k nearest indexed chunks over existing sqlite-vec; empty/absent vec index -> `novelty: null`, ordering unchanged; dream mutations byte-identical with and without novelty.+- **Depends on**: none++### Task 11: Weekly top-source + foresight - t_a8d49eae, t_08a79c81+- **Files**: `temporal/weekly-brief.ts` (`topSource` optional field), `temporal/foresight.ts` (`ForesightEnvelope`, `buildForesight`); CLI verb `foresight` (+ `--write`); MCP `brain_foresight`; tests extended weekly + new foresight suites+- **Acceptance**: topSource ranks recency + inbound links + centrality with per-signal breakdown and one-line why, absent when no candidates; foresight folds recurrence next-due + open commitments/questions + trend counts into versioned envelope, every item carries sources; empty vault -> empty envelope.+- **Depends on**: none++### Task 12: E2E integration + docs+- **Files**: `tests/e2e/entity-truth-dream.integration.test.ts`; README, CHANGELOG 0.43.0, docs/cli-reference.md, docs/how-it-works.md+- **Acceptance**: one vault exercises ledger ingest -> slots -> conflict -> collision -> aggregation, plus outcome regression, dead-end recall, novelty ranking, topSource, foresight; full suite green; docs describe every new surface.+- **Depends on**: Tasks 1-11diff --git a/docs/brainstorm/entity-truth-dream-suite/variants.md b/docs/brainstorm/entity-truth-dream-suite/variants.mdnew file mode 100644index 00000000..14b03731--- /dev/null+++ b/docs/brainstorm/entity-truth-dream-suite/variants.md@@ -0,0 +1,54 @@+# Entity Truth & Self-Improving Dream Suite - variants audit trail++Consultant: Claude Code (`claude -p`), 2026-06-04. Raw output: `cli-output/claude.md`.++## Variant 1: Ten Independent Feature Modules++- **Approach**: Treat each kanban task as a self-contained module with its own versioned store/envelope and its own CLI verb + MCP tool, sharing only the existing substrate (buildEntityIndex, dream.ts, weekly-brief.ts) read-only. Parent/child pairs (1-2, 3-4) sit in sibling files with a thin internal import rather than a shared abstraction. No new cross-cutting layer is introduced.+- **Trade-offs**:+ - Pro: maximum parallelizability - ten features can be built/tested/reviewed nearly independently; smallest blast radius per feature; bit-identical defaults are trivial to guarantee since each module is inert with no new data.+ - Pro: failure of one feature can't corrupt another; fail-closed parsing is per-store and simple.+ - Con: real duplication - entity-anchor resolution, claim addressing, and ranked-reason emission get reimplemented across conflicts/claim-slots/atomic-facts/contamination.+ - Con: weak synergy - claim slots (2), conflict records (1), and quantitative facts (4) clearly want one addressable per-entity representation; keeping them separate pushes integration cost downstream.+ - Con: ten new persisted formats to version and migrate.+- **Complexity**: large+- **Risk**: low++## Variant 2: Two Shared Backbones (Entity-Truth Ledger + Dream Signal Bus)++- **Approach**: Build one Entity-Truth Ledger that all of Half A reads/writes through - atomic-fact decomposition (3) and the quantitative family (4) feed addressable per-entity aspect slots (2), conflicts (1) and contamination checks are queries over that ledger, and cross-agent collision (5) diffs two agents' ledger writes. Half B introduces a Dream Signal Bus: surprisal (9), dead-ends (8), outcome-tied evidence (7), top-source (6), and foresight (10) all emit ranked, reasoned signals folded into the existing dream/weekly envelopes. Two cohesive cores instead of ten silos.+- **Trade-offs**:+ - Pro: strong cohesion where the domain genuinely shares structure - entity anchors and claim addressing live in exactly one place; conflict/slot/quantitative logic compose instead of duplicating.+ - Pro: cross-agent collision (5) and contamination (1) become near-free queries once the ledger exists; dream features share one ranking/reason convention.+ - Con: largest blast radius - the ledger sits on the hot fact-extraction path, so guaranteeing bit-identical neutral defaults requires careful gating.+ - Con: backbone must be designed before features land, reducing early parallelism; a ledger schema bug touches five features at once.+ - Con: temptation to over-generalize the bus for features (6, 10) that aren't really signals.+- **Complexity**: large+- **Risk**: medium++## Variant 3: Pure Fold-Over-Append-Only-Events++- **Approach**: Add no mutable state; every feature is a deterministic, replayable fold over existing append-only logs (sig-*.md, log JSONL, recurrence/events.jsonl) producing frozen envelopes, with new persisted artifacts limited to append-only event streams (conflict events, claim-supersede events, dead-end entries, foresight notes) each carrying a schema-version and fail-closed parser. Claim "current value" and conflict status are derived projections recomputed from the event stream, never stored mutably.+- **Trade-offs**:+ - Pro: most faithful to the stated convention (folds over mutable state, frozen replayable envelopes); bit-identical defaults fall out naturally since an empty event stream folds to the existing output.+ - Pro: provenance lineage (2) and superseded history are first-class because nothing is overwritten; auditing and rollback are uniform.+ - Pro: low risk to existing code - reads compose, writes only append.+ - Con: some features (claim slots with fast "what is true now", quantitative aggregation) need projection caches anyway, so a pure-fold stance leaks into derived stores regardless.+ - Con: recomputing folds for collision detection (5, push-mode within a recent window) and surprisal (9) on every event can be costly without indexing.+ - Con: more conceptual overhead per feature; contributors must think in folds even for simple checks.+- **Complexity**: medium+- **Risk**: low++## Consultant recommendation++### Recommended: Variant 2++**Rationale**: Half A's five features are not independent - atomic facts, the quantitative family, claim slots, conflicts, and contamination all revolve around one addressable per-entity claim representation, so a shared Entity-Truth Ledger eliminates the duplication of Variant 1 and the projection-cache awkwardness Variant 3 admits it would hit anyway. The medium risk it adds is concentrated on one well-understood path (fact extraction) and is manageable with the project's existing gating + fail-closed + bit-identical-default discipline, while the Dream Signal Bus for Half B reuses the established ranked-reason envelope-fold convention rather than inventing per-feature stores. Variant 1 ships faster but pushes integration debt downstream; Variant 3 is the cleanest philosophically but forces genuinely stateful artifacts (slots, lineage, registries) into a fold-only mold that doesn't fit them.++## Orchestrator decision++Variant 2 accepted with three containment refinements that import Variant 3's storage discipline and neutralize Variant 2's two stated cons:++1. **Ledger storage is fold-over-append-only.** The Entity-Truth Ledger persists as device-sharded append-only JSONL (`Brain/truth/claims.<deviceId>.jsonl`, the `log-jsonl.ts` pattern) plus a derived, recomputable fold state - exactly the activation-store shape shipped in v0.42.0. A ledger schema bug is recoverable by refolding; nothing mutable is the source of truth.+2. **No Dream Signal Bus abstraction.** Half B ships as additive optional envelope fields plus small standalone modules that share the existing ranked-`reasons` convention. The consultant itself flagged the over-generalization temptation for features 6 and 10; a shared convention costs nothing, a shared bus is machinery nobody asked for.+3. **Hot path stays untouched.** Fact extraction and pre-compact extraction behave bit-identically by default; ledger ingest is an explicit step (CLI verb / dream-step) so neutral defaults need no gating analysis on the capture path.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex f6c736ef..1104c7c5 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -181,6 +181,22 @@ o2b brain activation status [--top N] - folded activation state: event/CLI and MCP searches record which documents they surfaced as one JSON event per access under `Brain/search/activation/` (query hashed, never raw text). `o2b search <query> --no-record-access` suppresses recording for one query; the MCP `brain_search` tool accepts `record_access: false`. Cross-vault (`--global`) and query-cache-hit searches never record, so reinforcement is miss-driven. The derived `Brain/search/activation-state.json` is a replayable fold - deleting it loses nothing. `search_activation_enabled: false` disables both the boost and recording; `search_two_pass_enabled: false` disables the evidence-pack broadened retry.+### Entity truth and self-improving dream (since v0.43.0)++```text+o2b brain truth ingest --entity E --aspect A --value V --source S [--quantity-value N --quantity-unit U --quantity-action W] - append one claim to the ledger+ slots [--entity E] - current values with superseded history and CONTESTED flags+ conflicts [--window-days N] - value conflicts (independent sources within the window; resolution always ask_user)+ aggregate --action W [--unit U] [--entity E] - sum exact (entity, action, unit) quantity matches+ collisions [--window-days N] - cross-agent convergence on one entity+ sweep [--max-events N] - keep the newest N claim events and refold+o2b brain facts decompose (--file <path> | --text <text>) [--ingest --entity E] - deterministic atomic assertions; --ingest appends structured-family claims+o2b brain dead-end record --approach T --reason T [--context T] | list - negative-knowledge registry under Brain/dead-ends/+o2b brain foresight [--horizon-days N] [--write] - forward projection: routines coming due, open commitments, open questions+```++Claims live as device-sharded append-only JSONL under `Brain/truth/` with a recomputable `state.json` fold - deleting the cache loses nothing. The merge guard rides `o2b brain merge` (an `entity-guard` refusal when the two preferences anchor disjoint people/orgs; `--force` bypasses). `o2b brain apply-evidence` accepts `--outcome success|failure|unknown`; the dream pass stages `outcome_regressions` with a deterministic confidence penalty when applied events carry repeated failures. `brain_review_candidates` annotates inbox signals with `signal_novelty` when the vault has indexed embeddings.+## Vault scopeSingle exclusion policy for every vault walker.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 64410763..a595f734 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -957,6 +957,14 @@ Recency used to be one Weibull curve over file mtime: a constantly-useful prefer**Two-pass recovery.** Keyword matching is implicit-AND, so a multi-term evidence query whose terms live in different documents can return nothing. In evidence-pack mode that dead end now triggers exactly one broadened retry - the first significant term stays the base group, the rest OR in as alternatives - and the recovered results flow through the normal ranking and a recomputed evidence pack, labelled `second_pass` with a `secondPass` envelope report. Plain searches never broaden; `search_two_pass_enabled: false` turns the retry off entirely.+## Entity truth and the self-improving dream (since v0.43.0)++The Brain recorded facts but had no notion of which one is true NOW: two contradictory claims about the same entity coexisted silently, dedup could merge notes about different people, and the dream pass trusted self-reported evidence with no outcome signal. The Entity Truth & Self-Improving Dream Suite closes both gaps with the same fold-over-append-only discipline the activation store proved.++**The claim ledger.** Claims are append-only JSONL events under `Brain/truth/` (one shard per device, Syncthing-safe), each a versioned `(entity, aspect, value, source, agent, ts)` line parsed fail-closed. A deterministic, order-insensitive fold projects them into addressable slots: the current value of `employer of alice mason`, every superseded prior value with provenance, and `value_conflict` records when two distinct values land within the conflict window from independent sources - resolution is always `ask_user`, never automatic, while a later value outside the window supersedes silently because that is fact evolution, not contradiction. Atomic-fact decomposition feeds the ledger deterministically (markdown structure plus a sentence splitter with an abbreviation guard - no model calls), the actor-framed quantity family captures `I spent 120 USD` shapes, and aggregation sums only exact `(entity, action, unit)` tuples so nearby numbers never pollute a total. The same ledger powers two guards: merges refuse to collapse claims about disjoint people/orgs, and synthesized notes asserting entities their cited sources never mention are flagged as contaminated. Two agents independently writing claims about one entity within 14 days surface push-mode through the trigger queue.++**The self-improving dream.** Apply-evidence events now optionally carry a downstream outcome (`success | failure | unknown`); a rule whose applied events keep co-occurring with failures looks confirmed while actively hurting, so the dream refresh stages an `outcome_regressions` finding with a deterministic confidence penalty - staged for the operator, never silently retired. Failed approaches persist as markdown dead-ends (`Brain/dead-ends/`) that FTS indexes like any note, so recall surfaces "avoid X" beside "prefer Y". Inbox signals rank by surprisal - mean embedding distance to their nearest indexed neighbours, computed over the existing sqlite-vec index with zero provider calls - so review attention lands on genuinely new signals first. The weekly synthesis nominates the single most-developable note of the window, and the foresight fold projects forward for the first time: recurrence cadences yield next-due dates, recent open commitments and questions surface with sources, and an empty vault folds to an empty envelope.+## Safety propertiesThese are invariants of the system, not configuration to enable.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 3fcb34ee..5658cf3f 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.42.0",+ "version": "0.43.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 74520c2e..89d60a3f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.42.0",+ "version": "0.43.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 41f6b6e9..87bedc2a 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.42.0"+version: "0.43.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 6035141e..cad1bf1b 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.42.0",+ "version": "0.43.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 41f6b6e9..87bedc2a 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.42.0"+version: "0.43.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 8d92973e..94b66ded 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.42.0"+version = "0.43.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 61ccca65..da212cc2 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -33,6 +33,10 @@ import {cmdBrainHealth,cmdBrainHistory,cmdBrainActivation,+ cmdBrainTruth,+ cmdBrainFacts,+ cmdBrainDeadEnd,+ cmdBrainForesight,cmdBrainAudit,cmdBrainMorningBrief,cmdBrainCodec,@@ -167,6 +171,14 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainHistory(rest);case "activation":return await cmdBrainActivation(rest);+ case "truth":+ return await cmdBrainTruth(rest);+ case "facts":+ return await cmdBrainFacts(rest);+ case "dead-end":+ return await cmdBrainDeadEnd(rest);+ case "foresight":+ return await cmdBrainForesight(rest);case "audit":return await cmdBrainAudit(rest);case "morning-brief":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 0ba680c5..978d204e 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -40,6 +40,10 @@ Brain verbs (observing memory):health Semantic-health report: contradictions, concept gaps, stale claimshistory Render a preference's edit-history timelineactivation Activation event store: status and sweep+ truth Claim ledger: ingest, slots, conflicts, aggregate, collisions, sweep+ facts Decompose text into atomic assertions (--ingest to ledger)+ dead-end Negative-knowledge registry: record and list failed approaches+ foresight Forward projection: routines coming due, open commitments and questionsaudit Render a preference's full mutation audit trailmorning-brief Session-start summary: top prefs, open questions, recent notescodec Compress/expand session prose with the deterministic codec (stdin/--in)@@ -214,6 +218,32 @@ export const VERB_HELP: Record<string, string> = {"status reports the folded per-path activation and co-access pairs; sweep drops\n" +"events outside the retention window or beyond the newest-N cap and refolds\n" +"(--max-events 0 clears every retained event).\n",+ truth:+ "usage: o2b brain truth <ingest|slots|conflicts|aggregate|collisions|sweep> [--vault <path>] [--json]\n" ++ "Operator surface over the entity claim ledger (Brain/truth/). ingest appends one\n" ++ "claim (--entity --aspect --value --source, optional --quantity-value/--quantity-unit/\n" ++ "--quantity-action); slots renders current values with superseded history; conflicts\n" ++ "lists contested slots (two values within the window from independent sources,\n" ++ "resolution always ask_user); aggregate sums exact (entity, action, unit) quantity\n" ++ "matches; collisions reports cross-agent convergence; sweep keeps the newest N events.\n",+ facts:+ "usage: o2b brain facts decompose (--file <path> | --text <text>) [--ingest --entity E] [--vault <path>] [--json]\n" ++ "Deterministically decompose text into atomic assertions via markdown structure\n" ++ "(headings, list items, sentence boundaries with an abbreviation guard), anchored\n" ++ "to canonical entities. --ingest appends structured-family assertions (quantity,\n" ++ "possession, identity, location, email, url) to the claim ledger for --entity.\n",+ "dead-end":+ "usage: o2b brain dead-end <record|list> [--approach T --reason T [--context T]] [--max-active N] [--vault <path>] [--json]\n" ++ "Negative-knowledge registry under Brain/dead-ends/. record persists one\n" ++ "tried-and-failed approach as a markdown note (FTS-indexed, so recall can\n" ++ "surface avoid-X alongside prefer-Y); the active set is bounded and overflow\n" ++ "archives the oldest entries. list renders active entries newest first.\n",+ foresight:+ "usage: o2b brain foresight [--horizon-days N] [--write] [--vault <path>] [--json]\n" ++ "Forward-looking projection over the continuity log and recurrence ladder:\n" ++ "recurring routines coming due within the horizon (cadence arithmetic, soonest\n" ++ "first), recent open commitments, and open questions - every item carries\n" ++ "deterministic sources. --write persists Brain/foresight/<date>.md.\n",audit:"usage: o2b brain audit <pref-id> [--vault <path>] [--json]\n" +"Render a preference's full mutation audit trail (create / promote /\n" +diff --git a/src/cli/brain/verbs/apply-evidence.ts b/src/cli/brain/verbs/apply-evidence.tsindex ac890953..10bcac66 100644--- a/src/cli/brain/verbs/apply-evidence.ts+++ b/src/cli/brain/verbs/apply-evidence.ts@@ -11,6 +11,7 @@ export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {pref: { type: "string" },artifact: { type: "string" },result: { type: "string" },+ outcome: { type: "string" },agent: { type: "string" },note: { type: "string" },json: { type: "boolean" },@@ -32,6 +33,15 @@ export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {if (resultStr !== "applied" && resultStr !== "violated" && resultStr !== "outdated") {return fail(`--result must be 'applied', 'violated', or 'outdated'; got ${resultStr}`);}+ const outcomeStr = flags["outcome"] !== undefined ? String(flags["outcome"]) : undefined;+ if (+ outcomeStr !== undefined &&+ outcomeStr !== "success" &&+ outcomeStr !== "failure" &&+ outcomeStr !== "unknown"+ ) {+ return fail(`--outcome must be 'success', 'failure', or 'unknown'; got ${outcomeStr}`);+ }try {const out = appendApplyEvidence(vault, {@@ -39,6 +49,7 @@ export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {artifact: String(flags["artifact"]),result: resultStr,agent,+ ...(outcomeStr !== undefined ? { outcome: outcomeStr } : {}),...(flags["note"] ? { note: String(flags["note"]) } : {}),});if (flags["json"]) {diff --git a/src/cli/brain/verbs/dead-end.ts b/src/cli/brain/verbs/dead-end.tsnew file mode 100644index 00000000..a0092d92--- /dev/null+++ b/src/cli/brain/verbs/dead-end.ts@@ -0,0 +1,94 @@+/**+ * `o2b brain dead-end <record|list>` (t_be62c62d): the negative-+ * knowledge surface. `record` persists one tried-and-failed approach+ * as a markdown note (bounded active set, overflow archives);+ * `list` renders the active registry newest first.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage+ * errors.+ */++import { DEAD_END_MAX_ACTIVE, listDeadEnds, recordDeadEnd } from "../../../core/brain/dead-ends.ts";+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const USAGE =+ "usage: o2b brain dead-end <record|list> " ++ "[--approach T --reason T [--context T]] [--max-active N] [--agent N] [--vault <path>] [--json]";++export async function cmdBrainDeadEnd(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ approach: { type: "string" },+ reason: { type: "string" },+ context: { type: "string" },+ "max-active": { type: "string" },+ agent: { type: "string" },+ json: { type: "boolean" },+ });+ const op = positional[0];+ if (op !== "record" && op !== "list") {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const asJson = flags["json"] === true;+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ try {+ if (op === "record") {+ const approach = flags["approach"] as string | undefined;+ const reason = flags["reason"] as string | undefined;+ if (!approach?.trim() || !reason?.trim()) {+ process.stderr.write(`brain dead-end record: --approach and --reason required\n${USAGE}\n`);+ return 2;+ }+ const maxRaw = flags["max-active"] as string | undefined;+ const maxActive = maxRaw !== undefined ? Number(maxRaw) : DEAD_END_MAX_ACTIVE;+ if (!Number.isInteger(maxActive) || maxActive < 1) {+ process.stderr.write(`brain dead-end record: --max-active must be a positive integer\n`);+ return 2;+ }+ const result = recordDeadEnd(vault, {+ approach,+ reason,+ ...(typeof flags["context"] === "string" ? { context: flags["context"] as string } : {}),+ agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),+ now: new Date(),+ maxActive,+ });+ if (asJson) {+ okJson({+ ok: true,+ id: result.entry.id,+ path: result.entry.path,+ archived: result.archived,+ });+ } else {+ ok(`dead-end recorded: ${result.entry.id}`);+ if (result.archived.length > 0) ok(`archived: ${result.archived.join(", ")}`);+ }+ return 0;+ }++ const { entries, warnings } = listDeadEnds(vault);+ if (asJson) {+ okJson({ entries, warnings });+ } else {+ ok(`dead-ends: ${entries.length} active`);+ for (const e of entries) {+ ok(` ${e.created_at} ${e.approach}`);+ ok(` why: ${e.reason}`);+ }+ for (const w of warnings) ok(` [warning] ${w.path}: ${w.message}`);+ }+ return 0;+ } catch (exc) {+ const message = `dead-end ${op} failed: ${(exc as Error).message ?? exc}`;+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+}diff --git a/src/cli/brain/verbs/deep-synthesis.ts b/src/cli/brain/verbs/deep-synthesis.tsindex db981cf6..5b86c082 100644--- a/src/cli/brain/verbs/deep-synthesis.ts+++ b/src/cli/brain/verbs/deep-synthesis.ts@@ -62,6 +62,7 @@ export async function cmdBrainDeepSynthesis(argv: string[]): Promise<number> {superseded_by: s.supersededBy,})),gaps: report.gaps,+ contaminated: report.contaminated,...(flags["triggers"] === true ? { triggers_created: enqueued } : {}),});return 0;@@ -70,6 +71,11 @@ export async function cmdBrainDeepSynthesis(argv: string[]): Promise<number> {ok(`notes: ${report.notes.length}`);for (const a of report.agreements) ok(`[agreement] ${a.path} ${a.relation} ${a.target}`);for (const c of report.contradictions) ok(`[contradiction] ${c.path} contradicts ${c.target}`);+ for (const cont of report.contaminated) {+ ok(+ `[contaminated] ${cont.path} asserts ${cont.entity} uncited by ${cont.sources.join(", ")}`,+ );+ }for (const s of report.staleClaims) {ok(`[stale] ${s.path} (${s.ageDays}d${s.supersededBy !== null ? `, superseded by ${s.supersededBy}` : ""})`,diff --git a/src/cli/brain/verbs/facts.ts b/src/cli/brain/verbs/facts.tsnew file mode 100644index 00000000..b1e1c804--- /dev/null+++ b/src/cli/brain/verbs/facts.ts@@ -0,0 +1,111 @@+/**+ * `o2b brain facts decompose` (t_cbd22536): deterministic atomic-fact+ * decomposition of a file or inline text, with optional explicit+ * ledger ingest (`--ingest --entity E`) for assertions matching a+ * structured fact family. The capture hot path never calls this -+ * decomposition is an operator/agent-invoked step by design.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage+ * errors.+ */++import { readFileSync } from "node:fs";++import { decomposeAtomicFacts } from "../../../core/brain/atomic-facts.ts";+import { buildEntityIndex } from "../../../core/brain/entities/index-builder.ts";+import { isoSecond } from "../../../core/brain/time.ts";+import { claimsFromAssertion } from "../../../core/brain/truth/ingest.ts";+import { appendClaimEvent } from "../../../core/brain/truth/store.ts";+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const USAGE =+ "usage: o2b brain facts decompose (--file <path> | --text <text>) " ++ "[--ingest --entity E] [--agent N] [--vault <path>] [--json]";++export async function cmdBrainFacts(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ file: { type: "string" },+ text: { type: "string" },+ ingest: { type: "boolean" },+ entity: { type: "string" },+ agent: { type: "string" },+ json: { type: "boolean" },+ });+ if (positional[0] !== "decompose") {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const asJson = flags["json"] === true;+ const filePath = flags["file"] as string | undefined;+ const inlineText = flags["text"] as string | undefined;+ if ((filePath === undefined) === (inlineText === undefined)) {+ process.stderr.write(`brain facts decompose: exactly one of --file or --text\n${USAGE}\n`);+ return 2;+ }+ const ingest = flags["ingest"] === true;+ const entity = (flags["entity"] as string | undefined)?.trim();+ if (ingest && (entity === undefined || entity === "")) {+ process.stderr.write(`brain facts decompose: --ingest requires --entity\n${USAGE}\n`);+ return 2;+ }+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ try {+ let text: string;+ let sourceRef: string;+ if (filePath !== undefined) {+ text = readFileSync(filePath, "utf8");+ sourceRef = `[[${filePath}]]`;+ } else {+ text = inlineText!;+ sourceRef = "[[inline-text]]";+ }++ let registryEntities: ReturnType<typeof buildEntityIndex>["entities"];+ try {+ registryEntities = buildEntityIndex(vault).entities;+ } catch {+ registryEntities = [];+ }+ const assertions = decomposeAtomicFacts(text, { entities: registryEntities });++ let ingested = 0;+ if (ingest) {+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);+ const ts = isoSecond(new Date());+ for (const assertion of assertions) {+ const claims = claimsFromAssertion(assertion, {+ entity: entity!,+ agent,+ ts,+ source: sourceRef,+ });+ for (const claim of claims) {+ appendClaimEvent(vault, claim);+ ingested++;+ }+ }+ }++ if (asJson) {+ okJson({ assertions, ...(ingest ? { ingested } : {}) });+ } else {+ ok(`assertions: ${assertions.length}${ingest ? `, ingested: ${ingested}` : ""}`);+ for (const a of assertions) {+ const heading = a.headingPath.length > 0 ? ` [${a.headingPath.join(" > ")}]` : "";+ ok(` L${a.line} ${a.kind}${heading}: ${a.text}`);+ }+ }+ return 0;+ } catch (exc) {+ const message = `facts decompose failed: ${(exc as Error).message ?? exc}`;+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+}diff --git a/src/cli/brain/verbs/foresight.ts b/src/cli/brain/verbs/foresight.tsnew file mode 100644index 00000000..3da0041d--- /dev/null+++ b/src/cli/brain/verbs/foresight.ts@@ -0,0 +1,99 @@+/**+ * `o2b brain foresight` (t_08a79c81): render the forward-looking+ * envelope - recurring routines coming due, open commitments, open+ * questions. `--write` additionally persists a dated markdown note+ * under `Brain/foresight/` so the projection itself becomes+ * recallable vault content.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage+ * errors.+ */++import { mkdirSync } from "node:fs";+import { join } from "node:path";++import {+ buildForesight,+ FORESIGHT_HORIZON_DAYS,+ type ForesightEnvelope,+} from "../../../core/brain/temporal/foresight.ts";+import { isoDate } from "../../../core/brain/time.ts";+import { defaultConfigPath } from "../../../core/config.ts";+import { writeFrontmatterAtomic } from "../../../core/vault.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const USAGE = "usage: o2b brain foresight [--horizon-days N] [--write] [--vault <path>] [--json]";++function renderBody(envelope: ForesightEnvelope): string {+ const lines = [`# Foresight\n`, `Horizon: ${envelope.horizonDays} day(s)\n`];+ for (const item of envelope.upcoming) {+ lines.push(`## ${item.title}\n`);+ lines.push(`- kind: ${item.kind}`);+ if (item.due !== null) lines.push(`- due: ${item.due}`);+ lines.push(`- why: ${item.why}`);+ lines.push(`- sources: ${item.sources.join(", ")}`);+ lines.push("");+ }+ if (envelope.upcoming.length === 0) lines.push("Nothing anticipated inside the horizon.\n");+ return lines.join("\n");+}++export async function cmdBrainForesight(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "horizon-days": { type: "string" },+ write: { type: "boolean" },+ json: { type: "boolean" },+ });+ const asJson = flags["json"] === true;+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());+ const horizonRaw = flags["horizon-days"] as string | undefined;+ const horizonDays = horizonRaw !== undefined ? Number(horizonRaw) : FORESIGHT_HORIZON_DAYS;+ if (!Number.isInteger(horizonDays) || horizonDays < 1) {+ process.stderr.write(`brain foresight: --horizon-days must be a positive integer\n${USAGE}\n`);+ return 2;+ }++ try {+ const now = new Date();+ const envelope = buildForesight(vault, { now, horizonDays });++ let writtenPath: string | undefined;+ if (flags["write"] === true) {+ const dir = join(vault, "Brain", "foresight");+ mkdirSync(dir, { recursive: true });+ writtenPath = join(dir, `${isoDate(now)}.md`);+ writeFrontmatterAtomic(+ writtenPath,+ {+ kind: "brain-foresight",+ date: isoDate(now),+ horizon_days: String(envelope.horizonDays),+ generated_at: envelope.generatedAt,+ tags: ["brain", "brain/foresight"],+ },+ renderBody(envelope),+ { overwrite: true, existsErrorKind: "foresight", vaultForRelativePath: vault },+ );+ }++ if (asJson) {+ okJson({ ...envelope, ...(writtenPath !== undefined ? { written_path: writtenPath } : {}) });+ } else {+ ok(`foresight: ${envelope.upcoming.length} item(s) within ${envelope.horizonDays}d`);+ for (const item of envelope.upcoming) {+ ok(` [${item.kind}]${item.due !== null ? ` due ${item.due}` : ""} ${item.title}`);+ ok(` ${item.why}`);+ }+ if (writtenPath !== undefined) ok(`written: ${writtenPath}`);+ }+ return 0;+ } catch (exc) {+ const message = `foresight failed: ${(exc as Error).message ?? exc}`;+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 6621c27a..8d9e028b 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -20,6 +20,10 @@ export { cmdBrainWatchdog } from "./watchdog.ts";export { cmdBrainHealth } from "./health.ts";export { cmdBrainHistory } from "./history.ts";export { cmdBrainActivation } from "./activation.ts";+export { cmdBrainTruth } from "./truth.ts";+export { cmdBrainFacts } from "./facts.ts";+export { cmdBrainDeadEnd } from "./dead-end.ts";+export { cmdBrainForesight } from "./foresight.ts";export { cmdBrainAudit } from "./audit.ts";export { cmdBrainMorningBrief } from "./morning-brief.ts";export { cmdBrainCodec } from "./codec.ts";diff --git a/src/cli/brain/verbs/merge.ts b/src/cli/brain/verbs/merge.tsindex d7457a0f..4c3d3634 100644--- a/src/cli/brain/verbs/merge.ts+++ b/src/cli/brain/verbs/merge.ts@@ -26,6 +26,7 @@ export async function cmdBrainMerge(argv: string[]): Promise<number> {now: new Date(),agentName: agent,dryRun: true,+ bypassEntityGuard: force,});} catch (exc) {if (exc instanceof BrainMergeError) return fail(`brain merge: ${exc.message}`);@@ -72,7 +73,11 @@ export async function cmdBrainMerge(argv: string[]): Promise<number> {}try {- mergePreferences(vault, keepId, dropId, { now: new Date(), agentName: agent });+ mergePreferences(vault, keepId, dropId, {+ now: new Date(),+ agentName: agent,+ bypassEntityGuard: force,+ });} catch (exc) {if (exc instanceof BrainMergeError) return fail(`brain merge: ${exc.message}`);return fail(`brain merge: failed to commit merge: ${(exc as Error).message ?? exc}`);diff --git a/src/cli/brain/verbs/truth.ts b/src/cli/brain/verbs/truth.tsnew file mode 100644index 00000000..29236a05--- /dev/null+++ b/src/cli/brain/verbs/truth.ts@@ -0,0 +1,228 @@+/**+ * `o2b brain truth <op>` (Entity Truth & Self-Improving Dream Suite):+ * operator surface over the claim ledger - `ingest` appends one claim,+ * `slots` and `conflicts` render the fold (with conflict detection),+ * `aggregate` sums exact-match quantities, `collisions` reports+ * cross-agent convergence, `sweep` bounds the ledger.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage+ * errors.+ */++import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";+import { aggregateQuantities } from "../../../core/brain/truth/aggregate.ts";+import { detectAgentCollisions } from "../../../core/brain/truth/collision.ts";+import { computeTruthStateWithConflicts } from "../../../core/brain/truth/conflicts.ts";+import {+ appendClaimEvent,+ CLAIM_EVENT_MAX_COUNT,+ readClaimEvents,+ sweepClaimEvents,+} from "../../../core/brain/truth/store.ts";+import { normalizeEntityName } from "../../../core/brain/entities/canonical.ts";+import { isoSecond } from "../../../core/brain/time.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const OPS = ["ingest", "slots", "conflicts", "aggregate", "collisions", "sweep"] as const;+type TruthOp = (typeof OPS)[number];++const USAGE =+ "usage: o2b brain truth <ingest|slots|conflicts|aggregate|collisions|sweep>\n" ++ " ingest --entity E --aspect A --value V --source S [--agent N] [--ts ISO]\n" ++ " [--quantity-value N --quantity-unit U --quantity-action W]\n" ++ " slots [--entity E]\n" ++ " conflicts [--window-days N]\n" ++ " aggregate --action W [--unit U] [--entity E]\n" ++ " collisions [--window-days N]\n" ++ " sweep [--max-events N]\n" ++ " common [--vault <path>] [--json]";++function requireString(flags: Record<string, unknown>, name: string): string {+ const value = flags[name];+ if (typeof value !== "string" || value.trim() === "") {+ throw new UsageError(`--${name} is required`);+ }+ return value;+}++class UsageError extends Error {}++export async function cmdBrainTruth(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ entity: { type: "string" },+ aspect: { type: "string" },+ value: { type: "string" },+ source: { type: "string" },+ agent: { type: "string" },+ ts: { type: "string" },+ "quantity-value": { type: "string" },+ "quantity-unit": { type: "string" },+ "quantity-action": { type: "string" },+ action: { type: "string" },+ unit: { type: "string" },+ "window-days": { type: "string" },+ "max-events": { type: "string" },+ json: { type: "boolean" },+ });+ const op = positional[0] as TruthOp | undefined;+ if (op === undefined || !OPS.includes(op)) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const asJson = flags["json"] === true;+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ try {+ switch (op) {+ case "ingest": {+ const quantityValueRaw = flags["quantity-value"] as string | undefined;+ if (+ quantityValueRaw === undefined &&+ (flags["quantity-unit"] !== undefined || flags["quantity-action"] !== undefined)+ ) {+ throw new UsageError(+ "--quantity-value is required when --quantity-unit or --quantity-action is provided",+ );+ }+ let valueKind: "text" | "quantity" = "text";+ let quantity: { value: number; unit: string | null; action: string | null } | undefined;+ if (quantityValueRaw !== undefined) {+ const qv = Number(quantityValueRaw);+ if (!Number.isFinite(qv))+ throw new UsageError("--quantity-value must be a finite number");+ valueKind = "quantity";+ quantity = {+ value: qv,+ unit: (flags["quantity-unit"] as string | undefined) ?? null,+ action: (flags["quantity-action"] as string | undefined) ?? null,+ };+ }+ const result = appendClaimEvent(vault, {+ ts: (flags["ts"] as string | undefined) ?? isoSecond(new Date()),+ agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),+ entity: requireString(flags, "entity"),+ aspect: requireString(flags, "aspect"),+ value: requireString(flags, "value"),+ valueKind,+ ...(quantity !== undefined ? { quantity } : {}),+ source: requireString(flags, "source"),+ });+ const body = {+ ok: true,+ entity: result.event.entity,+ aspect: result.event.aspect,+ value: result.event.value,+ path: result.path,+ };+ if (asJson) okJson(body);+ else ok(`claim recorded: ${body.entity} / ${body.aspect} = ${body.value}`);+ return 0;+ }+ case "slots": {+ const state = computeTruthStateWithConflicts(readClaimEvents(vault).events);+ const entityFilter = flags["entity"] as string | undefined;+ const slots = state.slots.filter(+ (s) => entityFilter === undefined || s.entity === normalizeEntityName(entityFilter),+ );+ if (asJson) {+ okJson({ events: state.events, slots });+ } else {+ ok(`truth: ${state.events} event(s), ${slots.length} slot(s)`);+ for (const s of slots) {+ const flag = s.contested ? " [CONTESTED]" : "";+ ok(` ${s.entity} / ${s.aspect} = ${s.current.value}${flag}`);+ for (const h of s.history) ok(` superseded: ${h.value} (${h.ts}, ${h.source})`);+ }+ }+ return 0;+ }+ case "conflicts": {+ const windowRaw = flags["window-days"] as string | undefined;+ const windowDays = windowRaw !== undefined ? Number(windowRaw) : undefined;+ if (windowDays !== undefined && (!Number.isInteger(windowDays) || windowDays <= 0)) {+ throw new UsageError("--window-days must be a positive integer");+ }+ const state = computeTruthStateWithConflicts(+ readClaimEvents(vault).events,+ windowDays !== undefined ? { windowDays } : {},+ );+ if (asJson) {+ okJson({ conflicts: state.conflicts });+ } else {+ ok(`conflicts: ${state.conflicts.length}`);+ for (const c of state.conflicts) {+ ok(+ ` ${c.entity} / ${c.aspect}: ${c.values.map((v) => v.value).join(" vs ")} ` ++ `(priority ${c.priority}, ${c.resolution})`,+ );+ }+ }+ return 0;+ }+ case "aggregate": {+ const state = computeTruthStateWithConflicts(readClaimEvents(vault).events);+ const result = aggregateQuantities(state.slots, {+ action: requireString(flags, "action"),+ unit: (flags["unit"] as string | undefined) ?? null,+ ...(typeof flags["entity"] === "string" ? { entity: flags["entity"] } : {}),+ });+ if (asJson) {+ okJson({ ...result });+ } else {+ ok(+ `${result.action}${result.unit !== null ? ` (${result.unit})` : ""}: ` ++ `total ${result.total} across ${result.count} value(s)`,+ );+ for (const c of result.contributions) {+ ok(` ${c.value} ${c.entity} / ${c.aspect} ${c.source}`);+ }+ }+ return 0;+ }+ case "collisions": {+ const windowRaw = flags["window-days"] as string | undefined;+ const windowDays = windowRaw !== undefined ? Number(windowRaw) : undefined;+ if (windowDays !== undefined && (!Number.isInteger(windowDays) || windowDays <= 0)) {+ throw new UsageError("--window-days must be a positive integer");+ }+ const collisions = detectAgentCollisions(readClaimEvents(vault).events, {+ now: new Date(),+ ...(windowDays !== undefined ? { windowDays } : {}),+ });+ if (asJson) {+ okJson({ collisions });+ } else {+ ok(`collisions: ${collisions.length}`);+ for (const c of collisions) {+ ok(` ${c.entity}: ${c.agents.join(" + ")} (${c.claims} claim(s))`);+ }+ }+ return 0;+ }+ case "sweep": {+ const maxRaw = flags["max-events"] as string | undefined;+ const maxEvents = maxRaw !== undefined ? Number(maxRaw) : CLAIM_EVENT_MAX_COUNT;+ if (!Number.isInteger(maxEvents) || maxEvents < 0) {+ throw new UsageError("--max-events must be a non-negative integer");+ }+ const outcome = sweepClaimEvents(vault, { maxEvents });+ if (asJson) okJson({ removed: outcome.removed, kept: outcome.kept });+ else ok(`truth sweep: removed ${outcome.removed}, kept ${outcome.kept}`);+ return 0;+ }+ }+ } catch (exc) {+ if (exc instanceof UsageError) {+ process.stderr.write(`brain truth ${op}: ${exc.message}\n${USAGE}\n`);+ return 2;+ }+ const message = `truth ${op} failed: ${(exc as Error).message ?? exc}`;+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+}diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 3422d8a7..32f5c35b 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -114,6 +114,10 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("health", "Render semantic Brain health"),command("history", "Render preference edit history"),command("activation", "Activation event store: status and sweep"),+ command("truth", "Claim ledger: slots, conflicts, aggregate, collisions"),+ command("facts", "Decompose text into atomic assertions"),+ command("dead-end", "Record or list failed approaches"),+ command("foresight", "Render forward-looking projection"),command("audit", "Render mutation audit trail"),command("morning-brief", "Render session-start summary"),command("codec", "Compress or expand session prose"),diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.tsindex ea0c29e3..9ce2b213 100644--- a/src/core/brain/apply-evidence.ts+++ b/src/core/brain/apply-evidence.ts@@ -39,7 +39,13 @@ import { isoSecond } from "./time.ts";import { checkRolePermission } from "./trust/check-role-permission.ts";import { BRAIN_OPERATIONS, type BrainRole } from "./trust/role.ts";import { renderPrefLink } from "./wikilink.ts";-import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND, type BrainApplyResult } from "./types.ts";+import {+ BRAIN_APPLY_OUTCOME,+ BRAIN_APPLY_RESULT,+ BRAIN_LOG_EVENT_KIND,+ type BrainApplyOutcome,+ type BrainApplyResult,+} from "./types.ts";const ARTIFACT_MAX_LEN = 512;const NOTE_MAX_LEN = 4096;@@ -97,6 +103,12 @@ export interface AppendApplyEvidenceInput {readonly result: BrainApplyResult;readonly agent: string;readonly note?: string;+ /**+ * Downstream outcome of the artifact the rule was applied to+ * (t_d478df53). Optional and additive: `unknown` is treated like an+ * absent outcome, only `success`/`failure` persist in the log.+ */+ readonly outcome?: BrainApplyOutcome;}export interface AppendApplyEvidenceOptions {@@ -167,6 +179,16 @@ export function appendApplyEvidence(`apply-evidence field 'result' must be 'applied', 'violated', or 'outdated'; got ${JSON.stringify(input.result)}`,);}+ if (+ input.outcome !== undefined &&+ input.outcome !== BRAIN_APPLY_OUTCOME.success &&+ input.outcome !== BRAIN_APPLY_OUTCOME.failure &&+ input.outcome !== BRAIN_APPLY_OUTCOME.unknown+ ) {+ throw new Error(+ `apply-evidence field 'outcome' must be 'success', 'failure', or 'unknown'; got ${JSON.stringify(input.outcome)}`,+ );+ }// Resolve and validate the preference file. We accept both the bare// slug (`foo`) and the prefixed id (`pref-foo`) for caller comfort.@@ -201,6 +223,12 @@ export function appendApplyEvidence(agent: input.agent.trim(),result: input.result,};+ if (+ input.outcome === BRAIN_APPLY_OUTCOME.success ||+ input.outcome === BRAIN_APPLY_OUTCOME.failure+ ) {+ body["outcome"] = input.outcome;+ }const trimmedNote = note?.trim();if (trimmedNote) body["note"] = trimmedNote;diff --git a/src/core/brain/atomic-facts.ts b/src/core/brain/atomic-facts.tsnew file mode 100644index 00000000..fd6f0492--- /dev/null+++ b/src/core/brain/atomic-facts.ts@@ -0,0 +1,230 @@+/**+ * Atomic-fact decomposition (t_cbd22536): turn session/turn prose into+ * discrete single-sentence assertions - deterministically, with zero+ * model calls. Markdown structure does the heavy lifting (headings+ * carry context, list items are natural assertion units) and a+ * conservative sentence splitter with an abbreviation guard handles+ * paragraphs. The same precision discipline as `fact-extract.ts`:+ * fenced/inline code, quoted lines, and frontmatter never produce+ * assertions, because a hallucinated fact pollutes memory while a+ * missed one costs nothing.+ */++import { normalizeEntityName } from "./entities/canonical.ts";++/** Cap on one assertion's text length. */+export const MAX_ASSERTION_CHARS = 300;++/** Fragments shorter than this many characters are noise, not facts. */+const MIN_ASSERTION_CHARS = 15;++export type AtomicAssertionKind = "sentence" | "list_item";++/** The slice of a registry entity the anchorer needs. */+export interface AtomicEntityLike {+ readonly id: string;+ readonly name: string;+ readonly aliases: ReadonlyArray<string>;+ readonly status: string;+}++export interface AtomicAssertion {+ /** Whitespace-collapsed assertion text, length-capped. */+ readonly text: string;+ /** 1-based line number in the original input. */+ readonly line: number;+ /** Enclosing heading texts, outermost first. */+ readonly headingPath: ReadonlyArray<string>;+ readonly kind: AtomicAssertionKind;+ /** Canonical entity ids anchored in this assertion, sorted. */+ readonly entities: ReadonlyArray<string>;+}++export interface DecomposeOptions {+ /** Registry entities to anchor against (active only). */+ readonly entities?: ReadonlyArray<AtomicEntityLike>;+}++// Abbreviations a period may follow without ending the sentence.+// Lowercased, period-free. Single letters (initials) are handled+// separately by the splitter.+const ABBREVIATIONS = new Set([+ "e.g",+ "i.e",+ "etc",+ "vs",+ "cf",+ "ca",+ "approx",+ "dr",+ "mr",+ "mrs",+ "ms",+ "prof",+ "st",+ "no",+ "fig",+ "min",+ "max",+]);++const HEADING_RE = /^(#{1,6})\s+(.*)$/;+const LIST_ITEM_RE = /^\s*(?:[-*+]|\d{1,3}[.)])\s+(.+)$/;++function collapse(span: string): string {+ return span.replace(/\s+/g, " ").trim().slice(0, MAX_ASSERTION_CHARS);+}++/**+ * Split one paragraph into sentences. A boundary is `.`/`!`/`?`+ * followed by whitespace and an upper-case/digit/quote opener -+ * EXCEPT after a known abbreviation, a single-letter initial, or a+ * digit-dot-digit number (versions, decimals never contain+ * whitespace, so those survive by construction).+ */+export function splitSentences(text: string): string[] {+ const out: string[] = [];+ let start = 0;+ for (let i = 0; i < text.length; i++) {+ const ch = text[i]!;+ if (ch !== "." && ch !== "!" && ch !== "?") continue;+ const next = text[i + 1];+ if (next === undefined) break;+ if (!/\s/.test(next)) continue;+ const after = text.slice(i + 1).trimStart();+ if (after === "" || !/^[A-Z0-9"'([]/.test(after)) continue;+ if (ch === ".") {+ // Word immediately before the period, lowercased, period-free+ // prefix kept (so "e.g" matches as written in ABBREVIATIONS).+ const before = text.slice(start, i);+ const m = /(\S+)$/.exec(before);+ const word = (m?.[1] ?? "").toLowerCase();+ if (ABBREVIATIONS.has(word) || ABBREVIATIONS.has(word.replace(/\.$/, ""))) continue;+ if (/^[a-z]$/i.test(word)) continue; // single-letter initial+ }+ out.push(text.slice(start, i + 1));+ start = i + 1;+ }+ const tail = text.slice(start);+ if (tail.trim() !== "") out.push(tail);+ return out.map((s) => s.trim()).filter((s) => s !== "");+}++/** Anchor an assertion against active registry entities, sorted ids. */+function anchorEntities(text: string, entities: ReadonlyArray<AtomicEntityLike>): string[] {+ if (entities.length === 0) return [];+ const haystack = normalizeEntityName(text);+ const ids: string[] = [];+ for (const entity of entities) {+ if (entity.status !== "active") continue;+ const forms = [entity.name, ...entity.aliases].map((f) => normalizeEntityName(f));+ if (forms.some((f) => f.length >= 3 && haystack.includes(f))) ids.push(entity.id);+ }+ return ids.toSorted();+}++/**+ * Decompose markdown/prose text into atomic assertions. Deterministic:+ * same input and entity set, same output.+ */+export function decomposeAtomicFacts(text: string, opts: DecomposeOptions = {}): AtomicAssertion[] {+ if (!text || text.trim() === "") return [];+ const entities = opts.entities ?? [];+ const lines = text.split(/\r?\n/);++ const out: AtomicAssertion[] = [];+ // Heading stack: [level, text] pairs; path = texts in order.+ const headingStack: Array<{ level: number; text: string }> = [];+ let inFence = false;+ let inFrontmatter = false;++ const push = (raw: string, line: number, kind: AtomicAssertionKind): void => {+ const stripped = collapse(raw.replace(/`[^`\n]*`/g, " "));+ if (stripped.length < MIN_ASSERTION_CHARS) return;+ out.push(+ Object.freeze({+ text: stripped,+ line,+ headingPath: Object.freeze(headingStack.map((h) => h.text)),+ kind,+ entities: Object.freeze(anchorEntities(stripped, entities)),+ }),+ );+ };++ // Paragraph accumulator: prose lines buffer until a blank/structural+ // line, then split into sentences attributed to the paragraph start.+ let paragraph: string[] = [];+ let paragraphStart = 0;+ const flushParagraph = (): void => {+ if (paragraph.length === 0) return;+ const joined = paragraph.join(" ");+ for (const sentence of splitSentences(joined)) {+ push(sentence, paragraphStart, "sentence");+ }+ paragraph = [];+ };++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ const trimmed = line.trim();++ // Frontmatter: only an opening `---` on the very first line.+ if (i === 0 && trimmed === "---") {+ inFrontmatter = true;+ continue;+ }+ if (inFrontmatter) {+ if (trimmed === "---") inFrontmatter = false;+ continue;+ }++ if (trimmed.startsWith("```") || trimmed.startsWith("~~~")) {+ flushParagraph();+ inFence = !inFence;+ continue;+ }+ if (inFence) continue;++ if (trimmed === "") {+ flushParagraph();+ continue;+ }++ if (trimmed.startsWith(">")) {+ flushParagraph();+ continue;+ }++ const heading = HEADING_RE.exec(trimmed);+ if (heading !== null) {+ flushParagraph();+ const level = heading[1]!.length;+ while (headingStack.length > 0 && headingStack.at(-1)!.level >= level) {+ headingStack.pop();+ }+ headingStack.push({ level, text: collapse(heading[2]!) });+ continue;+ }++ const item = LIST_ITEM_RE.exec(line);+ if (item !== null) {+ flushParagraph();+ // A multi-sentence list item still decomposes; single-sentence+ // items (the common case) survive whole.+ const sentences = splitSentences(item[1]!);+ if (sentences.length <= 1) {+ push(item[1]!, i + 1, "list_item");+ } else {+ for (const sentence of sentences) push(sentence, i + 1, "list_item");+ }+ continue;+ }++ if (paragraph.length === 0) paragraphStart = i + 1;+ paragraph.push(trimmed);+ }+ flushParagraph();++ return out;+}diff --git a/src/core/brain/dead-ends.ts b/src/core/brain/dead-ends.tsnew file mode 100644index 00000000..b136a412--- /dev/null+++ b/src/core/brain/dead-ends.ts@@ -0,0 +1,218 @@+/**+ * Dead-end registry (t_be62c62d): the Brain's negative-knowledge+ * class. Skill proposals mine positive procedures; nothing recorded+ * what was TRIED and FAILED, so agents kept re-walking pruned+ * branches. A dead-end is one markdown note under `Brain/dead-ends/`+ * (approach + why it failed + context) - markdown-first so FTS+ * indexes it with zero search changes and recall surfaces "avoid X"+ * alongside "prefer Y". The active set is bounded to the most-recent+ * N; overflow archives the oldest into `Brain/dead-ends/archive/`+ * instead of deleting history.+ */++import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync } from "node:fs";+import { join } from "node:path";++import { sanitiseTextField } from "../redactor.ts";+import { parseFrontmatterText, slugify, writeFrontmatterAtomic } from "../vault.ts";+import type { FrontmatterMap } from "../types.ts";+import { allocateSlug } from "./paths.ts";+import { isoDate, isoSecond } from "./time.ts";++/** Active dead-ends kept before overflow archives the oldest. */+export const DEAD_END_MAX_ACTIVE = 100;++const APPROACH_MAX_LEN = 256;+const REASON_MAX_LEN = 1024;+const CONTEXT_MAX_LEN = 1024;++export function deadEndsDir(vault: string): string {+ return join(vault, "Brain", "dead-ends");+}++export interface DeadEndEntry {+ readonly id: string;+ readonly path: string;+ readonly approach: string;+ readonly reason: string;+ readonly context: string | null;+ readonly agent: string;+ readonly created_at: string;+}++export interface RecordDeadEndInput {+ /** What was tried (one line, the note title). */+ readonly approach: string;+ /** Why it failed or was deliberately set aside. */+ readonly reason: string;+ readonly context?: string;+ readonly agent: string;+ readonly now: Date;+ /** Override the active-set cap (tests). */+ readonly maxActive?: number;+}++export interface RecordDeadEndResult {+ readonly entry: DeadEndEntry;+ /** Ids archived by the overflow trim, oldest first. */+ readonly archived: ReadonlyArray<string>;+}++export interface DeadEndParseWarning {+ readonly path: string;+ readonly message: string;+}++export interface ListDeadEndsResult {+ readonly entries: ReadonlyArray<DeadEndEntry>;+ readonly warnings: ReadonlyArray<DeadEndParseWarning>;+}++function renderBody(approach: string, reason: string, context: string | null): string {+ return (+ `## Approach\n\n${approach}\n\n` ++ `## Why it failed\n\n${reason}\n\n` ++ `## Context\n\n${context ?? "_(not provided)_"}\n`+ );+}++/**+ * Record one dead-end note and trim the active set. The id is+ * `de-<date>-<slug-of-approach>` with `allocateSlug` collision+ * suffixes, matching the signal naming discipline.+ */+export function recordDeadEnd(vault: string, input: RecordDeadEndInput): RecordDeadEndResult {+ const approach = sanitiseTextField(input.approach, {+ maxLen: APPROACH_MAX_LEN,+ singleLine: true,+ }).trim();+ const reason = sanitiseTextField(input.reason, { maxLen: REASON_MAX_LEN }).trim();+ const context =+ input.context !== undefined+ ? sanitiseTextField(input.context, { maxLen: CONTEXT_MAX_LEN }).trim() || null+ : null;+ if (approach === "") throw new Error("dead-end missing field: approach");+ if (reason === "") throw new Error("dead-end missing field: reason");+ if (!input.agent || input.agent.trim() === "") throw new Error("dead-end missing field: agent");++ const dir = deadEndsDir(vault);+ mkdirSync(dir, { recursive: true });+ const date = isoDate(input.now);+ const allocated = allocateSlug({+ vault,+ targetDir: dir,+ prefix: `de-${date}`,+ slug: slugify(approach),+ });+ const id = `de-${date}-${allocated.slug}`;+ const createdAt = isoSecond(input.now);++ const metadata: FrontmatterMap = {+ kind: "brain-dead-end",+ id,+ created_at: createdAt,+ agent: input.agent.trim(),+ approach,+ tags: ["brain", "brain/dead-end"],+ };+ writeFrontmatterAtomic(allocated.path, metadata, renderBody(approach, reason, context), {+ overwrite: false,+ existsErrorKind: "dead-end",+ vaultForRelativePath: vault,+ });++ const archived = trimActive(vault, input.maxActive ?? DEAD_END_MAX_ACTIVE);++ return Object.freeze({+ entry: Object.freeze({+ id,+ path: allocated.path,+ approach,+ reason,+ context,+ agent: input.agent.trim(),+ created_at: createdAt,+ }),+ archived: Object.freeze(archived),+ });+}++/** Move the oldest active entries beyond the cap into `archive/`. */+function trimActive(vault: string, maxActive: number): string[] {+ const { entries } = listDeadEnds(vault);+ if (entries.length <= maxActive) return [];+ // `entries` is newest first; everything past the cap archives.+ const overflow = entries.slice(maxActive).toReversed();+ const archiveDir = join(deadEndsDir(vault), "archive");+ mkdirSync(archiveDir, { recursive: true });+ const archived: string[] = [];+ for (const entry of overflow) {+ renameSync(entry.path, join(archiveDir, `${entry.id}.md`));+ archived.push(entry.id);+ }+ return archived;+}++function parseSections(body: string): { reason: string; context: string | null } {+ const reasonMatch = /## Why it failed\n\n([\s\S]*?)(?:\n## |$)/.exec(body);+ const contextMatch = /## Context\n\n([\s\S]*?)(?:\n## |$)/.exec(body);+ const contextRaw = contextMatch?.[1]?.trim() ?? "";+ return {+ reason: reasonMatch?.[1]?.trim() ?? "",+ context: contextRaw === "" || contextRaw === "_(not provided)_" ? null : contextRaw,+ };+}++/**+ * List active dead-ends, newest first. Files that fail to parse (or+ * carry the wrong kind) surface as warnings and never abort the list.+ */+export function listDeadEnds(vault: string): ListDeadEndsResult {+ const dir = deadEndsDir(vault);+ if (!existsSync(dir)) return { entries: [], warnings: [] };++ const entries: DeadEndEntry[] = [];+ const warnings: DeadEndParseWarning[] = [];+ for (const name of readdirSync(dir).toSorted()) {+ if (!name.endsWith(".md")) continue;+ const path = join(dir, name);+ let metadata: FrontmatterMap;+ let body: string;+ try {+ [metadata, body] = parseFrontmatterText(readFileSync(path, "utf8"));+ } catch (exc) {+ warnings.push({ path, message: `unparseable dead-end: ${(exc as Error).message ?? exc}` });+ continue;+ }+ if (metadata["kind"] !== "brain-dead-end") {+ warnings.push({ path, message: "missing kind: brain-dead-end" });+ continue;+ }+ const id = typeof metadata["id"] === "string" ? metadata["id"] : name.replace(/\.md$/, "");+ const approach = typeof metadata["approach"] === "string" ? metadata["approach"] : "";+ const agent = typeof metadata["agent"] === "string" ? metadata["agent"] : "";+ const createdAt = typeof metadata["created_at"] === "string" ? metadata["created_at"] : "";+ if (approach === "" || createdAt === "") {+ warnings.push({ path, message: "dead-end missing approach/created_at" });+ continue;+ }+ const sections = parseSections(body);+ entries.push(+ Object.freeze({+ id,+ path,+ approach,+ reason: sections.reason,+ context: sections.context,+ agent,+ created_at: createdAt,+ }),+ );+ }++ entries.sort((a, b) => {+ if (a.created_at !== b.created_at) return a.created_at < b.created_at ? 1 : -1;+ return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;+ });+ return { entries: Object.freeze(entries), warnings: Object.freeze(warnings) };+}diff --git a/src/core/brain/deep-synthesis.ts b/src/core/brain/deep-synthesis.tsindex 26e59462..67a9ca40 100644--- a/src/core/brain/deep-synthesis.ts+++ b/src/core/brain/deep-synthesis.ts@@ -20,8 +20,10 @@ import { join } from "node:path";import { search } from "../search/search.ts";import { walkVault } from "../search/walker.ts";import type { BrainSearchResult, ResolvedSearchConfig } from "../search/types.ts";+import { buildEntityIndex } from "./entities/index-builder.ts";import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";import type { InsightCandidate } from "./triggers/types.ts";+import { checkEntityContamination, type ContaminationEntityLike } from "./truth/contamination.ts";const POSITIVE_RELATIONS: ReadonlySet<string> = new Set(["related", "extends", "supports"]);@@ -53,6 +55,15 @@ export interface SynthesisGap {readonly sources: ReadonlyArray<string>;}+export interface SynthesisContamination {+ /** The note asserting the entity. */+ readonly path: string;+ /** Canonical entity id mentioned but uncited. */+ readonly entity: string;+ /** The cited sources that fail to mention it. */+ readonly sources: ReadonlyArray<string>;+}+export interface DeepSynthesisReport {readonly topic: string;readonly generatedAt: string;@@ -63,6 +74,14 @@ export interface DeepSynthesisReport {readonly contradictions: ReadonlyArray<SynthesisContradiction>;readonly staleClaims: ReadonlyArray<SynthesisStaleClaim>;readonly gaps: ReadonlyArray<SynthesisGap>;+ /**+ * Entity-contamination findings (t_e9692750): matched notes whose+ * wikilink-cited sources never mention a registered entity the note+ * asserts. Empty when the vault has no entity registry, and the+ * `entity_contamination` dimension is then omitted from `checked`+ * so registry-free vaults stay byte-identical.+ */+ readonly contaminated: ReadonlyArray<SynthesisContamination>;}export interface DeepSynthesisOptions {@@ -110,13 +129,29 @@ export async function deepSynthesis(.slice(0, limit);// Known pages across the vault: gap detection needs the full set,- // not just the matched slice.+ // not just the matched slice. The name->relPath map additionally+ // lets the contamination check resolve a cited wikilink target back+ // to the source file it names (first deterministic match wins).const knownTargets = new Set<string>();+ const pageByName = new Map<string, string>();for (const file of walkVault(config)) {const page = stripMd(file.relPath);knownTargets.add(page);+ if (!pageByName.has(page)) pageByName.set(page, file.relPath);const slash = page.lastIndexOf("/");- knownTargets.add(slash >= 0 ? page.slice(slash + 1) : page);+ const short = slash >= 0 ? page.slice(slash + 1) : page;+ knownTargets.add(short);+ if (!pageByName.has(short)) pageByName.set(short, file.relPath);+ }++ // Entity-contamination substrate (t_e9692750): the dimension only+ // exists when the vault HAS a registry, so registry-free vaults+ // produce byte-identical reports.+ let guardEntities: ReadonlyArray<ContaminationEntityLike> = [];+ try {+ guardEntities = buildEntityIndex(config.vault).entities;+ } catch {+ guardEntities = [];}// Agreement edges stay scoped to the matched-topic set: a positive@@ -137,6 +172,8 @@ export async function deepSynthesis(const contradictions: SynthesisContradiction[] = [];const staleClaims: SynthesisStaleClaim[] = [];const gapSources = new Map<string, Set<string>>();+ const contaminated: SynthesisContamination[] = [];+ const citedContentCache = new Map<string, string>();for (const note of matched) {let supersededBy: string | null = null;@@ -172,19 +209,67 @@ export async function deepSynthesis(} catch {continue;}+ const citedRel = new Set<string>();for (const body of extractWikilinkRichBodies(content)) {const target = parseWikilinkRich(body).target;- if (target === "" || knownTargets.has(target)) continue;+ if (target === "") continue;+ if (knownTargets.has(target)) {+ const rel = pageByName.get(target);+ if (rel !== undefined && rel !== note.path) citedRel.add(rel);+ continue;+ }const sources = gapSources.get(target) ?? new Set<string>();sources.add(note.path);gapSources.set(target, sources);}++ // Contamination: a note asserting a registered entity its cited+ // sources never mention. Only notes that actually cite something+ // are checked - an uncited note claims no provenance.+ if (guardEntities.length > 0 && citedRel.size > 0) {+ const cited = [...citedRel].toSorted();+ const sourceTexts: string[] = [];+ for (const rel of cited) {+ const cachedText = citedContentCache.get(rel);+ if (cachedText !== undefined) {+ sourceTexts.push(cachedText);+ continue;+ }+ try {+ const text = readFileSync(join(config.vault, rel), "utf8");+ citedContentCache.set(rel, text);+ sourceTexts.push(text);+ } catch {+ // An unreadable source cannot clear an entity; skip it.+ }+ }+ const result = checkEntityContamination({+ conclusion: content,+ sources: sourceTexts,+ entities: guardEntities,+ });+ for (const violation of result.violations) {+ contaminated.push(+ Object.freeze({+ path: note.path,+ entity: violation.entityId,+ sources: Object.freeze(cited),+ }),+ );+ }+ }}+ contaminated.sort((a, b) => {+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;+ return a.entity < b.entity ? -1 : a.entity > b.entity ? 1 : 0;+ });+return Object.freeze({topic,generatedAt: opts.now.toISOString(),- checked: CHECKED,+ checked:+ guardEntities.length > 0 ? Object.freeze([...CHECKED, "entity_contamination"]) : CHECKED,notes: Object.freeze(matched.map((note) =>Object.freeze({ path: note.path, title: note.title, score: note.score }),@@ -200,6 +285,7 @@ export async function deepSynthesis(Object.freeze({ target, sources: Object.freeze([...sources].toSorted()) }),),),+ contaminated: Object.freeze(contaminated),});}diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex c48823ff..3f96cec2 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -215,6 +215,14 @@ export interface DreamRunSummary {* when the config field is absent (the default).*/readonly gated_retires: ReadonlyArray<DreamGatedRetireEntry>;+ /**+ * Outcome-regression findings (t_d478df53): confirmed preferences+ * whose recent applied events co-occur with failure outcomes. The+ * confidence penalty is already applied in this run's refresh; the+ * list is the explainable staging surface. Empty on outcome-free+ * vaults.+ */+ readonly outcome_regressions: ReadonlyArray<DreamOutcomeRegression>;/*** Multi-phase dream pipeline (Brain lifecycle suite, Feature 2).* Ordered per-phase summaries (close, reconcile, synthesize, heal,@@ -395,6 +403,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {quarantined: Object.freeze([...plan.quarantined]),intent_reviews: Object.freeze([...intentReview.reviews]),gated_retires: Object.freeze([] as ReadonlyArray<DreamGatedRetireEntry>),+ outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),phases: Object.freeze([] as ReadonlyArray<DreamPhaseSummary>),open_questions: Object.freeze([...reconcile.openQuestions]),...(dryRun ? { dry_run: true } : {}),@@ -860,6 +869,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {quarantined: Object.freeze([...plan.quarantined]),intent_reviews: Object.freeze([...intentReview.reviews]),gated_retires: Object.freeze([...gatedRetires]),+ outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),...(dryRun? { dry_run: true }@@ -1593,6 +1603,22 @@ interface RefreshUpdate {* during refresh so the digest can render a `## Confidence drops`* section without re-deriving transitions from the log.*/+/**+ * Outcome regression (t_d478df53): minimum applied-with-failure events+ * before a preference is flagged, and the multiplicative confidence+ * penalty a flagged preference receives. The penalty is part of the+ * deterministic confidence derivation, so reruns stay no-ops.+ */+export const OUTCOME_REGRESSION_MIN_FAILURES = 2;+export const OUTCOME_REGRESSION_PENALTY = 0.8;++export interface DreamOutcomeRegression {+ readonly id: string;+ readonly principle: string;+ readonly failures: number;+ readonly successes: number;+}+export interface RefreshBandDrop {readonly id: string;readonly principle: string;@@ -1615,12 +1641,16 @@ interface RefreshResult {* order at construction).*/readonly bandDrops: RefreshBandDrop[];+ /** Preferences flagged by the outcome-regression rule (t_d478df53). */+ readonly outcomeRegressions: DreamOutcomeRegression[];}interface ApplyEvidenceEntry {readonly pref_slug: string;readonly timestamp: string;readonly result: (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];+ /** Downstream outcome when recorded (t_d478df53). */+ readonly outcome?: "success" | "failure";}function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {@@ -1658,6 +1688,9 @@ function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {pref_slug: target.slice("pref-".length),timestamp: e.timestamp,result: result as ApplyEvidenceEntry["result"],+ ...(e.body["outcome"] === "success" || e.body["outcome"] === "failure"+ ? { outcome: e.body["outcome"] as "success" | "failure" }+ : {}),});}}@@ -1698,6 +1731,7 @@ function planRefresh(const confirmed = new Set<string>();const updated = new Map<string, RefreshUpdate>();const bandDrops: RefreshBandDrop[] = [];+ const outcomeRegressions: DreamOutcomeRegression[] = [];// Index evidence by slug.const bySlug = new Map<string, ApplyEvidenceEntry[]>();@@ -1787,7 +1821,36 @@ function planRefresh(}}- const confidence = computeConfidence(applied, violated, lastEvidence, cfg, now);+ const baseConfidence = computeConfidence(applied, violated, lastEvidence, cfg, now);++ // Outcome regression (t_d478df53): applied events whose downstream+ // outcome was `failure` outnumbering `success` mean the rule looks+ // confirmed while actively hurting. The flag stages an explainable+ // finding and a multiplicative confidence penalty - retirement+ // still goes through the existing gates, never silently. The+ // penalty is a pure function of the evidence, so reruns converge.+ const appliedFailures = ev.filter(+ (e) => e.result === BRAIN_APPLY_RESULT.applied && e.outcome === "failure",+ ).length;+ const appliedSuccesses = ev.filter(+ (e) => e.result === BRAIN_APPLY_RESULT.applied && e.outcome === "success",+ ).length;+ const regressed =+ appliedFailures >= OUTCOME_REGRESSION_MIN_FAILURES && appliedFailures > appliedSuccesses;+ const confidence = regressed+ ? rebandConfidence(+ Math.round(baseConfidence.value * OUTCOME_REGRESSION_PENALTY * 10000) / 10000,+ cfg,+ )+ : baseConfidence;+ if (regressed) {+ outcomeRegressions.push({+ id: rec.pref.id,+ principle: rec.pref.principle,+ failures: appliedFailures,+ successes: appliedSuccesses,+ });+ }// Idempotency on a no-op rerun: skip refresh for prefs where// counters AND status are unchanged AND the on-disk body already@@ -1912,7 +1975,7 @@ function planRefresh(}}- return { confirmed, updated, bandDrops };+ return { confirmed, updated, bandDrops, outcomeRegressions };}/**@@ -1984,6 +2047,19 @@ export function computeConfidence(return Object.freeze({ value, band });}+/** Re-derive the confidence band for an externally adjusted value. */+function rebandConfidence(value: number, cfg: BrainConfig): ConfidenceComputeResult {+ let band: BrainConfidence;+ if (value >= cfg.confidence.high_min) {+ band = BRAIN_CONFIDENCE.high;+ } else if (value >= cfg.confidence.medium_min) {+ band = BRAIN_CONFIDENCE.medium;+ } else {+ band = BRAIN_CONFIDENCE.low;+ }+ return Object.freeze({ value, band });+}+// ----- Auto-retires (expired-unconfirmed, stale-no-evidence) --------------function planAutoRetires(diff --git a/src/core/brain/evidence.ts b/src/core/brain/evidence.tsindex 59455080..ab1b25c8 100644--- a/src/core/brain/evidence.ts+++ b/src/core/brain/evidence.ts@@ -99,12 +99,18 @@ export function collectEvidenceForSlug(const artifact = typeof e.body["artifact"] === "string" ? e.body["artifact"] : "";const agent = typeof e.body["agent"] === "string" ? e.body["agent"] : undefined;const note = typeof e.body["note"] === "string" ? e.body["note"] : undefined;+ const outcomeRaw = e.body["outcome"];+ const outcome =+ outcomeRaw === "success" || outcomeRaw === "failure"+ ? (outcomeRaw as BrainEvidenceSummary["outcome"])+ : undefined;const row: BrainEvidenceSummary = Object.freeze({timestamp: e.timestamp,artifact,result: result as BrainApplyResult,...(agent !== undefined ? { agent } : {}),...(note !== undefined ? { note } : {}),+ ...(outcome !== undefined ? { outcome } : {}),});if (result === BRAIN_APPLY_RESULT.applied) {if (applied.length < maxApplied) applied.push(row);diff --git a/src/core/brain/fact-extract.ts b/src/core/brain/fact-extract.tsindex 4219fab3..8d31d089 100644Binary files a/src/core/brain/fact-extract.ts and b/src/core/brain/fact-extract.ts differdiff --git a/src/core/brain/merge.ts b/src/core/brain/merge.tsindex da17ea8b..0cbdaf1b 100644--- a/src/core/brain/merge.ts+++ b/src/core/brain/merge.ts@@ -27,6 +27,8 @@ import { join } from "node:path";import { regenerateActiveQuiet } from "./active.ts";import { computeContentHash } from "./content-hash.ts";+import { buildEntityIndex } from "./entities/index-builder.ts";+import { guardEntityMerge, type GuardEntityLike } from "./truth/merge-guard.ts";import { appendLogEvent } from "./log.ts";import { brainDirs, preferencePath } from "./paths.ts";import { appendPrefAudit } from "./pref-audit.ts";@@ -43,7 +45,8 @@ export type BrainMergeErrorCode =| "topic-mismatch"| "scope-mismatch"| "pin-parity"- | "unsupported-status";+ | "unsupported-status"+ | "entity-guard";export class BrainMergeError extends Error {readonly code: BrainMergeErrorCode;@@ -61,6 +64,12 @@ export interface MergeOptions {readonly agentName?: string;/** When true, return the plan but make no writes. */readonly dryRun?: boolean;+ /**+ * Skip the name-aware entity merge guard (t_e9692750). The CLI maps+ * `--force` here; the guard otherwise refuses to collapse claims+ * about different people/orgs into one preference.+ */+ readonly bypassEntityGuard?: boolean;}export interface MergePlan {@@ -158,6 +167,25 @@ export function mergePreferences();}+ // Name-aware entity guard (t_e9692750): same-topic near-duplicates+ // naming different people/orgs must not collapse into one rule.+ if (opts.bypassEntityGuard !== true) {+ let entities: ReadonlyArray<GuardEntityLike> = [];+ try {+ entities = buildEntityIndex(vault).entities;+ } catch {+ // No readable registry means nothing to anchor against.+ }+ const verdict = guardEntityMerge({+ keepText: `${keep.topic} ${keep.principle}`,+ dropText: `${drop.topic} ${drop.principle}`,+ entities,+ });+ if (!verdict.allowed) {+ throw new BrainMergeError("entity-guard", `${verdict.reason}; pass --force to override`);+ }+ }+const merged_evidenced_by = mergeEvidencedBy(keep.evidenced_by, drop.evidenced_by);const applied_sum = keep.applied_count + drop.applied_count;const violated_sum = keep.violated_count + drop.violated_count;diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.tsindex 5773ec05..c14c913b 100644--- a/src/core/brain/recurrence.ts+++ b/src/core/brain/recurrence.ts@@ -79,6 +79,67 @@ export function getRecurrenceEntry();}+/**+ * Cadence projection for foresight (t_08a79c81): per surviving+ * routine, the latest support timestamp and the mean interval between+ * consecutive `learn` events. A single occurrence has no cadence+ * (`meanIntervalDays: null`) and never projects forward. Purged+ * sources are excluded globally - an approximation of the positional+ * fold that can only under-project, never invent a routine.+ */+export interface RecurrenceCadence {+ readonly contentHash: string;+ readonly topScope: string;+ readonly commitment: RecurrenceCommitment;+ readonly supportCount: number;+ readonly lastAt: string;+ readonly meanIntervalDays: number | null;+}++export function listRecurrenceCadences(+ vault: string,+ thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,+): ReadonlyArray<RecurrenceCadence> {+ const entries = listRecurrenceEntries(vault, thresholds);+ if (entries.length === 0) return Object.freeze([]);+ const events = readEvents(vault);+ const purged = new Set(events.filter((e) => e.kind === "purge-source").map((e) => e.sourceId));+ const byHash = new Map<string, string[]>();+ for (const e of events) {+ if (e.kind !== "support" || !e.contentHash || e.action !== "learn") continue;+ if (purged.has(e.sourceId)) continue;+ const list = byHash.get(e.contentHash) ?? [];+ list.push(e.at);+ byHash.set(e.contentHash, list);+ }++ const out: RecurrenceCadence[] = [];+ for (const entry of entries) {+ const ats = (byHash.get(entry.contentHash) ?? [])+ .map((at) => Date.parse(at))+ .filter((ms) => Number.isFinite(ms))+ .toSorted((a, b) => a - b);+ if (ats.length === 0) continue;+ let meanIntervalDays: number | null = null;+ if (ats.length >= 2) {+ const spanDays = (ats.at(-1)! - ats[0]!) / (24 * 3600 * 1000);+ meanIntervalDays = Math.round((spanDays / (ats.length - 1)) * 10) / 10;+ }+ out.push(+ Object.freeze({+ contentHash: entry.contentHash,+ topScope: entry.scopes[0]?.scope ?? "",+ commitment: entry.commitment,+ supportCount: entry.supportCount,+ lastAt: new Date(ats.at(-1)!).toISOString(),+ meanIntervalDays,+ }),+ );+ }+ out.sort((a, b) => (a.contentHash < b.contentHash ? -1 : a.contentHash > b.contentHash ? 1 : 0));+ return Object.freeze(out);+}+export function listRecurrenceEntries(vault: string,thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,diff --git a/src/core/brain/review-candidates.ts b/src/core/brain/review-candidates.tsindex f792c5c1..e18e3234 100644--- a/src/core/brain/review-candidates.ts+++ b/src/core/brain/review-candidates.ts@@ -13,8 +13,14 @@* `brain_dream` with `dry_run: true` directly.*/+import { existsSync, readdirSync } from "node:fs";+import { join, relative } from "node:path";++import type { ResolvedSearchConfig } from "../search/types.ts";import { dream } from "./dream.ts";import type { BrainIntentReviewEntry } from "./intent-review.ts";+import { brainDirs } from "./paths.ts";+import { scoreSignalNovelty, sortByNovelty, type SignalNoveltyEntry } from "./surprisal.ts";import { BRAIN_RETIRED_REASON, type BrainRetiredReason } from "./types.ts";export interface ReviewCandidatesReport {@@ -58,23 +64,59 @@ export interface ReviewCandidatesReport {}>;/** Intent-review decisions for active signal clusters before main dream planning. */readonly intent_reviews: ReadonlyArray<BrainIntentReviewEntry>;+ /**+ * Surprisal annotation (t_fddfe64a): inbox signals ranked by+ * embedding-space novelty, highest first. Present ONLY when a+ * search config was provided AND at least one signal actually+ * scored - vec-less vaults keep the report byte-identical.+ */+ readonly signal_novelty?: ReadonlyArray<SignalNoveltyEntry>;}export interface BuildReviewCandidatesOptions {/** Wall clock for the underlying dream pass. */readonly now?: Date;+ /**+ * When provided, annotate the report with surprisal novelty over+ * the existing vec index (t_fddfe64a). Read-only; absent or+ * unembedded indexes leave the report unchanged.+ */+ readonly searchConfig?: ResolvedSearchConfig;+}++/** Active inbox signal files as (id, relPath) refs. */+function listInboxSignalRefs(vault: string): Array<{ id: string; relPath: string }> {+ const inbox = brainDirs(vault).inbox;+ if (!existsSync(inbox)) return [];+ const inboxRel = relative(vault, inbox);+ return readdirSync(inbox)+ .filter((n) => n.startsWith("sig-") && n.endsWith(".md"))+ .toSorted()+ .map((n) => ({ id: n.replace(/\.md$/, ""), relPath: join(inboxRel, n) }));}-export function buildReviewCandidates(+export async function buildReviewCandidates(vault: string,opts: BuildReviewCandidatesOptions = {},-): ReviewCandidatesReport {+): Promise<ReviewCandidatesReport> {const summary = dream(vault, {dryRun: true,...(opts.now ? { now: opts.now } : {}),});+ let signalNovelty: ReadonlyArray<SignalNoveltyEntry> | undefined;+ if (opts.searchConfig !== undefined) {+ const refs = listInboxSignalRefs(vault);+ if (refs.length > 0) {+ const scored = await scoreSignalNovelty(opts.searchConfig, refs);+ if (scored.some((s) => s.novelty !== null)) {+ signalNovelty = sortByNovelty(scored);+ }+ }+ }+return Object.freeze({+ ...(signalNovelty !== undefined ? { signal_novelty: signalNovelty } : {}),would_create: Object.freeze([...summary.new_unconfirmed]),would_promote: Object.freeze([...summary.confirmed]),would_retire: Object.freeze(diff --git a/src/core/brain/surprisal.ts b/src/core/brain/surprisal.tsnew file mode 100644index 00000000..9c9ec68a--- /dev/null+++ b/src/core/brain/surprisal.ts@@ -0,0 +1,104 @@+/**+ * Surprisal-based novelty sampling (t_fddfe64a): rank inbox signals+ * by how far they sit from everything the vault already knows -+ * mean L2 distance from the signal's own indexed embedding to its k+ * nearest non-self neighbours over the EXISTING sqlite-vec index.+ * Zero provider calls: a signal that was never embedded (or a vault+ * with no vec layer at all) scores `null` and consumers stay+ * byte-identical. The score only reorders review surfaces; it never+ * changes which signals the dream pass processes.+ */++import { Store } from "../search/store.ts";+import type { ResolvedSearchConfig } from "../search/types.ts";++/** Neighbours averaged into one novelty score. */+export const SURPRISAL_NEIGHBORS = 5;++export interface SignalRef {+ readonly id: string;+ /** Vault-relative path of the signal file. */+ readonly relPath: string;+}++export interface SignalNoveltyEntry {+ readonly id: string;+ readonly path: string;+ /** Mean kNN distance, or null when no embedding exists. */+ readonly novelty: number | null;+}++/**+ * Score each signal's novelty. Degrades to all-null without throwing+ * when the index is missing, the vec extension is unavailable, or a+ * signal carries no embedding.+ */+export async function scoreSignalNovelty(+ config: ResolvedSearchConfig,+ signals: ReadonlyArray<SignalRef>,+): Promise<SignalNoveltyEntry[]> {+ const allNull = (): SignalNoveltyEntry[] =>+ signals.map((s) => Object.freeze({ id: s.id, path: s.relPath, novelty: null }));+ if (signals.length === 0) return [];++ let store: Store;+ try {+ store = await Store.open(config, { mode: "read" });+ } catch {+ return allNull();+ }+ try {+ if (!store.vecLoaded()) return allNull();+ const out: SignalNoveltyEntry[] = [];+ for (const signal of signals) {+ const docId = store.getDocumentIdByPath(signal.relPath);+ if (docId === null) {+ out.push(Object.freeze({ id: signal.id, path: signal.relPath, novelty: null }));+ continue;+ }+ const chunks = store.chunksForDocument(docId);+ const embedding = chunks.length > 0 ? store.embeddingForChunk(chunks[0]!.id) : null;+ if (embedding === null) {+ out.push(Object.freeze({ id: signal.id, path: signal.relPath, novelty: null }));+ continue;+ }+ // Over-fetch so dropping the signal's own chunks still leaves k+ // genuine neighbours.+ const hits = store.semanticTopK(embedding, {+ limit: SURPRISAL_NEIGHBORS + chunks.length + 4,+ });+ const distances = hits+ .filter((h) => h.documentId !== docId)+ .slice(0, SURPRISAL_NEIGHBORS)+ .map((h) => h.distance);+ const novelty =+ distances.length > 0+ ? Math.round((distances.reduce((a, b) => a + b, 0) / distances.length) * 1e6) / 1e6+ : null;+ out.push(Object.freeze({ id: signal.id, path: signal.relPath, novelty }));+ }+ return out;+ } catch {+ return allNull();+ } finally {+ await store.close();+ }+}++/**+ * Sort novelty entries for review surfaces: scored first (highest+ * novelty wins), null-scored after, ties by id for determinism.+ */+export function sortByNovelty(+ entries: ReadonlyArray<SignalNoveltyEntry>,+): ReadonlyArray<SignalNoveltyEntry> {+ return Object.freeze(+ [...entries].toSorted((a, b) => {+ if (a.novelty === null && b.novelty === null) return a.id < b.id ? -1 : 1;+ if (a.novelty === null) return 1;+ if (b.novelty === null) return -1;+ if (a.novelty !== b.novelty) return b.novelty - a.novelty;+ return a.id < b.id ? -1 : 1;+ }),+ );+}diff --git a/src/core/brain/temporal/foresight.ts b/src/core/brain/temporal/foresight.tsnew file mode 100644index 00000000..c45ed07b--- /dev/null+++ b/src/core/brain/temporal/foresight.ts@@ -0,0 +1,124 @@+/**+ * Foresight (t_08a79c81): the Brain's first forward-looking surface.+ * Every other temporal projection (daily brief, weekly synthesis,+ * monthly review, retention) looks backward; foresight folds the+ * continuity log and the recurrence ladder FORWARD - cadence+ * arithmetic projects when a routine comes due next, and recent open+ * commitments / open questions surface as the obligations most+ * likely to matter soon. A fold, not a planner: only deterministic+ * projections, every item carries sources, an empty vault folds to+ * an empty envelope.+ */++import { listContinuityRecords } from "../continuity/store.ts";+import { listRecurrenceCadences } from "../recurrence.ts";+import { isoDate, isoSecond } from "../time.ts";++export const FORESIGHT_SCHEMA_VERSION = 1;+/** Cap on items per envelope. */+export const FORESIGHT_MAX_ITEMS = 20;+/** Default forward horizon, in days. */+export const FORESIGHT_HORIZON_DAYS = 14;+/** Open commitments/questions older than this never surface. */+export const FORESIGHT_EXTRACT_LOOKBACK_DAYS = 30;++const DAY_MS = 24 * 60 * 60 * 1000;+const TITLE_MAX_LEN = 160;++export type ForesightItemKind = "recurring" | "commitment" | "open_question";++export interface ForesightItem {+ readonly kind: ForesightItemKind;+ readonly title: string;+ /** Projected due date (ISO date) for recurring items; null otherwise. */+ readonly due: string | null;+ /** Deterministic evidence for why this item is anticipated. */+ readonly why: string;+ readonly sources: ReadonlyArray<string>;+}++export interface ForesightEnvelope {+ readonly version: typeof FORESIGHT_SCHEMA_VERSION;+ readonly generatedAt: string;+ readonly horizonDays: number;+ readonly upcoming: ReadonlyArray<ForesightItem>;+}++export interface BuildForesightOptions {+ readonly now: Date;+ readonly horizonDays?: number;+}++function recurringItems(vault: string, nowMs: number, horizonDays: number): ForesightItem[] {+ const out: Array<{ item: ForesightItem; dueMs: number }> = [];+ for (const cadence of listRecurrenceCadences(vault)) {+ if (cadence.meanIntervalDays === null) continue;+ const lastMs = Date.parse(cadence.lastAt);+ if (!Number.isFinite(lastMs)) continue;+ const dueMs = lastMs + cadence.meanIntervalDays * DAY_MS;+ // Overdue routines stay in - they are the likeliest next need of+ // all - but anything past the horizon is not foresight yet.+ if (dueMs > nowMs + horizonDays * DAY_MS) continue;+ const title = `Recurring: ${cadence.topScope || cadence.contentHash.slice(0, 12)}`;+ out.push({+ dueMs,+ item: Object.freeze({+ kind: "recurring" as const,+ title: title.slice(0, TITLE_MAX_LEN),+ due: isoDate(new Date(dueMs)),+ why:+ `seen ${cadence.supportCount}x, every ~${Math.round(cadence.meanIntervalDays)}d, ` ++ `last ${cadence.lastAt.slice(0, 10)} (${cadence.commitment})`,+ sources: Object.freeze([`recurrence:${cadence.contentHash}`]),+ }),+ });+ }+ out.sort((a, b) => a.dueMs - b.dueMs || (a.item.title < b.item.title ? -1 : 1));+ return out.map((x) => x.item);+}++function extractItems(vault: string, nowMs: number): ForesightItem[] {+ const since = isoSecond(new Date(nowMs - FORESIGHT_EXTRACT_LOOKBACK_DAYS * DAY_MS));+ const records = listContinuityRecords(vault, { kind: "pre_compact_extract", since });+ const out: Array<{ item: ForesightItem; createdAt: string }> = [];+ for (const record of records) {+ const extractType = record.payload["extract_type"];+ if (extractType !== "commitment" && extractType !== "open_question") continue;+ const text = record.payload["text"];+ if (typeof text !== "string" || text.trim() === "") continue;+ out.push({+ createdAt: record.createdAt,+ item: Object.freeze({+ kind: extractType,+ title: text.trim().slice(0, TITLE_MAX_LEN),+ due: null,+ why: `open ${extractType.replace("_", " ")} captured ${record.createdAt.slice(0, 10)}`,+ sources: Object.freeze(record.sourceRefs.map((ref) => ref.id)),+ }),+ });+ }+ // Newest first inside each kind; commitments ahead of questions.+ out.sort((a, b) => {+ if (a.item.kind !== b.item.kind) return a.item.kind === "commitment" ? -1 : 1;+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;+ return a.item.title < b.item.title ? -1 : 1;+ });+ return out.map((x) => x.item);+}++/**+ * Fold the vault's forward-looking evidence into a bounded,+ * deterministic envelope: recurring routines due within the horizon+ * (soonest first), then recent open commitments, then open questions.+ */+export function buildForesight(vault: string, opts: BuildForesightOptions): ForesightEnvelope {+ const horizonDays = opts.horizonDays ?? FORESIGHT_HORIZON_DAYS;+ const nowMs = opts.now.getTime();+ const upcoming = [...recurringItems(vault, nowMs, horizonDays), ...extractItems(vault, nowMs)];+ return Object.freeze({+ version: FORESIGHT_SCHEMA_VERSION,+ generatedAt: isoSecond(opts.now),+ horizonDays,+ upcoming: Object.freeze(upcoming.slice(0, FORESIGHT_MAX_ITEMS)),+ });+}diff --git a/src/core/brain/temporal/weekly-brief.ts b/src/core/brain/temporal/weekly-brief.tsindex 88f08745..74a9d66a 100644--- a/src/core/brain/temporal/weekly-brief.ts+++ b/src/core/brain/temporal/weekly-brief.ts@@ -16,6 +16,10 @@* Task 7 in `plan.md`.*/+import { readdirSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import { extractWikilinkRichBodies, parseWikilinkRich } from "../link-graph/parse-wikilink.ts";import { isoSecond } from "./../time.ts";import type { BrainLogEventKind, ResolvedBrainTemporalConfig } from "./../types.ts";import { BRAIN_LOG_EVENT_KIND } from "./../types.ts";@@ -47,6 +51,20 @@ export interface WeeklyRetirement {readonly link: string;}+export interface WeeklyTopSource {+ /** Vault-relative path of the nominated note. */+ readonly path: string;+ readonly score: number;+ /** One-line deterministic rationale. */+ readonly why: string;+ /** Per-signal breakdown behind the score. */+ readonly signals: {+ readonly recencyDays: number;+ readonly inboundLinks: number;+ readonly outboundLinks: number;+ };+}+export interface WeeklySynthesisEnvelope {readonly windowStart: string;readonly windowEnd: string;@@ -57,6 +75,13 @@ export interface WeeklySynthesisEnvelope {readonly vaultDelta: PeriodVaultDelta;readonly sourcePointers: ReadonlyArray<string>;readonly generatedAt: string;+ /**+ * Weekly top-source (t_a8d49eae): the single most-developable note+ * of the window - recency + inbound links + link centrality.+ * Absent when no candidate note was modified inside the window, so+ * historic envelopes stay byte-identical.+ */+ readonly topSource?: WeeklyTopSource;}export interface BuildWeeklySynthesisOptions {@@ -66,12 +91,12 @@ export interface BuildWeeklySynthesisOptions {export function buildWeeklySynthesis(index: TimelineIndex,- _vault: string,+ vault: string,weekEnd: string,_cfg: ResolvedBrainTemporalConfig,opts: BuildWeeklySynthesisOptions = {},): WeeklySynthesisEnvelope {- // `_vault` / `_cfg` are part of the helper signature for parity+ // `_cfg` is part of the helper signature for parity// with sibling projections and forward compatibility (weekday-// alignment overrides will read `_cfg.weekly_start_dow` in a// future release); the brief itself is a pure projection over the@@ -96,8 +121,10 @@ export function buildWeeklySynthesis(.filter((t) => t.kind === "retirement").map((t) => Object.freeze({ at: t.at, prefId: t.prefId, link: t.link }));const contradictions = collectContradictions(events);+ const topSource = nominateTopSource(vault, windowStartMs, windowEndMs);return Object.freeze({+ ...(topSource !== null ? { topSource } : {}),windowStart,windowEnd: windowEndIso,eventsByKind: Object.freeze(countByKind(events)),@@ -136,3 +163,168 @@ function makeContradiction(...(ev.artifact !== undefined ? { artifact: ev.artifact } : {}),});}++// ----- Weekly top-source (t_a8d49eae) ---------------------------------------++// Machine-owned content never nominates: logs, signals, machine+// stores, generated digests, and rule files are not "notes worth+// developing further".+const TOP_SOURCE_EXCLUDED_PREFIXES: ReadonlyArray<string> = Object.freeze([+ "Brain/log/",+ "Brain/inbox/",+ "Brain/retired/",+ "Brain/preferences/",+ "Brain/.snapshots/",+ "Brain/snapshots/",+ "Brain/search/",+ "Brain/procedural/",+ "Brain/recurrence/",+ "Brain/truth/",+ "Brain/triggers/",+ "Brain/continuity/",+ "Brain/dead-ends/",+ "Brain/foresight/",+ "Brain/_",+ "Brain/active",+ "Brain/pinned",+]);++const SKIPPED_DIR_NAMES: ReadonlySet<string> = new Set([+ ".git",+ "node_modules",+ ".open-second-brain",+ ".obsidian",+ ".trash",+ ".stversions",+]);++interface TopSourceCandidate {+ readonly relPath: string;+ readonly mtimeMs: number;+}++function walkMarkdown(vault: string): string[] {+ const out: string[] = [];+ const stack: string[] = [""];+ while (stack.length > 0) {+ const rel = stack.pop()!;+ const abs = rel === "" ? vault : join(vault, rel);+ let names: string[];+ try {+ names = readdirSync(abs);+ } catch {+ continue;+ }+ for (const name of names.toSorted()) {+ const childRel = rel === "" ? name : `${rel}/${name}`;+ let isDir: boolean;+ try {+ isDir = statSync(join(vault, childRel)).isDirectory();+ } catch {+ continue;+ }+ if (isDir) {+ if (SKIPPED_DIR_NAMES.has(name) || name.startsWith(".")) continue;+ stack.push(childRel);+ } else if (name.endsWith(".md")) {+ out.push(childRel);+ }+ }+ }+ return out.toSorted();+}++function excluded(relPath: string): boolean {+ return TOP_SOURCE_EXCLUDED_PREFIXES.some((prefix) => relPath.startsWith(prefix));+}++function pageNames(relPath: string): string[] {+ const stripped = relPath.endsWith(".md") ? relPath.slice(0, -3) : relPath;+ const slash = stripped.lastIndexOf("/");+ return slash >= 0 ? [stripped, stripped.slice(slash + 1)] : [stripped];+}++/**+ * Nominate the most-developable note of the window: every candidate+ * modified inside [windowStart, windowEnd) scores+ * `0.5*recency + 0.3*inbound/(inbound+3) + 0.2*outbound/(outbound+5)`+ * over the whole-vault link graph. Null when nothing qualified.+ */+function nominateTopSource(+ vault: string,+ windowStartMs: number,+ windowEndMs: number,+): WeeklyTopSource | null {+ const all = walkMarkdown(vault);+ const candidates: TopSourceCandidate[] = [];+ for (const relPath of all) {+ if (excluded(relPath)) continue;+ let mtimeMs: number;+ try {+ mtimeMs = statSync(join(vault, relPath)).mtimeMs;+ } catch {+ continue;+ }+ if (mtimeMs >= windowStartMs && mtimeMs < windowEndMs) {+ candidates.push({ relPath, mtimeMs });+ }+ }+ if (candidates.length === 0) return null;++ // Inbound counts over the WHOLE vault: links from machine files+ // still count as evidence of centrality, only nomination is scoped.+ const nameToCandidate = new Map<string, string>();+ for (const c of candidates) {+ for (const name of pageNames(c.relPath)) {+ if (!nameToCandidate.has(name)) nameToCandidate.set(name, c.relPath);+ }+ }+ const inbound = new Map<string, number>();+ const outbound = new Map<string, number>();+ for (const relPath of all) {+ let content: string;+ try {+ content = readFileSync(join(vault, relPath), "utf8");+ } catch {+ continue;+ }+ let links = 0;+ for (const body of extractWikilinkRichBodies(content)) {+ const target = parseWikilinkRich(body).target;+ if (target === "") continue;+ links++;+ const hit = nameToCandidate.get(target);+ if (hit !== undefined && hit !== relPath) {+ inbound.set(hit, (inbound.get(hit) ?? 0) + 1);+ }+ }+ outbound.set(relPath, links);+ }++ let best: WeeklyTopSource | null = null;+ for (const c of candidates) {+ const recencyDays = Math.max(0, Math.floor((windowEndMs - c.mtimeMs) / (24 * 60 * 60 * 1000)));+ const recency = Math.max(0, 1 - (windowEndMs - c.mtimeMs) / (windowEndMs - windowStartMs));+ const inboundLinks = inbound.get(c.relPath) ?? 0;+ const outboundLinks = outbound.get(c.relPath) ?? 0;+ const score =+ Math.round(+ (0.5 * recency ++ 0.3 * (inboundLinks / (inboundLinks + 3)) ++ 0.2 * (outboundLinks / (outboundLinks + 5))) *+ 10000,+ ) / 10000;+ const candidate: WeeklyTopSource = Object.freeze({+ path: c.relPath,+ score,+ why:+ `Modified ${recencyDays}d before window end with ${inboundLinks} inbound and ` ++ `${outboundLinks} outbound link(s) - the strongest develop-next lead of the window.`,+ signals: Object.freeze({ recencyDays, inboundLinks, outboundLinks }),+ });+ if (best === null || score > best.score || (score === best.score && c.relPath < best.path)) {+ best = candidate;+ }+ }+ return best;+}diff --git a/src/core/brain/triggers/scan.ts b/src/core/brain/triggers/scan.tsindex 847d511b..d030c906 100644--- a/src/core/brain/triggers/scan.ts+++ b/src/core/brain/triggers/scan.ts@@ -6,6 +6,8 @@import { runDoctor } from "../doctor.ts";import { buildRetentionReview } from "../retention.ts";+import { collisionCandidates, detectAgentCollisions } from "../truth/collision.ts";+import { readClaimEvents } from "../truth/store.ts";import { candidatesFromHealth, candidatesFromRetention } from "./adapters.ts";import { createTriggers, type CreateTriggersOptions, type CreateTriggersResult } from "./store.ts";import type { InsightCandidate } from "./types.ts";@@ -40,6 +42,16 @@ export function scanTriggers(vault: string, opts: ScanTriggersOptions): ScanTrig} catch {// retention review unavailable - skip the source}+ try {+ // Cross-agent collisions (t_f2b225b1): an empty ledger detects+ // nothing, so vaults without claim events stay byte-identical.+ const { events } = readClaimEvents(vault);+ if (events.length > 0) {+ candidates.push(...collisionCandidates(detectAgentCollisions(events, { now: opts.now })));+ }+ } catch {+ // claim ledger unavailable - skip the source+ }candidates.push(...(opts.extraCandidates ?? []));const result = createTriggers(vault, candidates, opts);diff --git a/src/core/brain/triggers/types.ts b/src/core/brain/triggers/types.tsindex 4949e676..d03e26c5 100644--- a/src/core/brain/triggers/types.ts+++ b/src/core/brain/triggers/types.ts@@ -37,6 +37,7 @@ export const TRIGGER_KINDS = ["open_question","orphan_research","idea_direction",+ "agent_collision",] as const;export type TriggerKind = (typeof TRIGGER_KINDS)[number];diff --git a/src/core/brain/truth/aggregate.ts b/src/core/brain/truth/aggregate.tsnew file mode 100644index 00000000..528af609--- /dev/null+++ b/src/core/brain/truth/aggregate.ts@@ -0,0 +1,88 @@+/**+ * Exact-match quantity aggregation (t_220c313e): "how much did I+ * spend" answers combine ONLY values whose (entity, action, unit)+ * tuple matches the query exactly after canonical normalization. A+ * number that is merely nearby - a different unit, a different+ * measured action, a text-kind slot - never pollutes a total. That+ * structural exactness is the whole feature.+ */++import { normalizeEntityName } from "../entities/canonical.ts";+import type { ClaimSlot } from "./types.ts";++export interface AggregateQuery {+ /** Optional entity filter; omitted means every entity combines. */+ readonly entity?: string;+ /** Measured action, exact match after normalization. */+ readonly action: string;+ /** Unit token; null matches only unitless quantities. */+ readonly unit: string | null;+}++export interface AggregateContribution {+ readonly entity: string;+ readonly aspect: string;+ readonly value: number;+ readonly source: string;+ readonly ts: string;+}++export interface AggregateResult {+ readonly action: string;+ readonly unit: string | null;+ readonly total: number;+ readonly count: number;+ readonly contributions: ReadonlyArray<AggregateContribution>;+}++function normalizeUnit(raw: string | null): string | null {+ if (raw === null) return null;+ const unit = normalizeEntityName(raw);+ return unit === "" ? null : unit;+}++/**+ * Sum the CURRENT value of every slot whose quantity matches the+ * query tuple exactly. Superseded history never aggregates - the+ * ledger's current-truth surface is what totals are about.+ */+export function aggregateQuantities(+ slots: ReadonlyArray<ClaimSlot>,+ query: AggregateQuery,+): AggregateResult {+ const wantEntity = query.entity !== undefined ? normalizeEntityName(query.entity) : null;+ const wantAction = normalizeEntityName(query.action);+ const wantUnit = normalizeUnit(query.unit);++ const contributions: AggregateContribution[] = [];+ for (const slot of slots) {+ if (wantEntity !== null && slot.entity !== wantEntity) continue;+ const current = slot.current;+ if (current.valueKind !== "quantity" || current.quantity === undefined) continue;+ const q = current.quantity;+ if (q.action === null || normalizeEntityName(q.action) !== wantAction) continue;+ if (normalizeUnit(q.unit) !== wantUnit) continue;+ contributions.push(+ Object.freeze({+ entity: slot.entity,+ aspect: slot.aspect,+ value: q.value,+ source: current.source,+ ts: current.ts,+ }),+ );+ }++ contributions.sort((a, b) => {+ if (a.entity !== b.entity) return a.entity < b.entity ? -1 : 1;+ return a.aspect < b.aspect ? -1 : a.aspect > b.aspect ? 1 : 0;+ });++ return Object.freeze({+ action: wantAction,+ unit: wantUnit,+ total: contributions.reduce((sum, c) => sum + c.value, 0),+ count: contributions.length,+ contributions: Object.freeze(contributions),+ });+}diff --git a/src/core/brain/truth/collision.ts b/src/core/brain/truth/collision.tsnew file mode 100644index 00000000..1fdbefc2--- /dev/null+++ b/src/core/brain/truth/collision.ts@@ -0,0 +1,115 @@+/**+ * Cross-agent collision detection (t_f2b225b1): two agents that+ * independently logged claims about one entity within the recent+ * window - citing different sources - have converging knowledge+ * neither knows about. The detector folds recent ledger events into+ * bounded findings; `collisionCandidates` turns findings into trigger+ * candidates so the standing trigger queue (Kernel B) delivers them+ * push-mode with cooldown dedup, instead of waiting for an operator+ * to run a pull-mode agent diff.+ */++import type { InsightCandidate } from "../triggers/types.ts";+import type { ClaimEvent } from "./types.ts";++/** Claims older than this many days never participate. */+export const COLLISION_WINDOW_DAYS = 14;+/** Cap on findings per detection pass. */+export const COLLISION_FINDINGS_CAP = 20;++const DAY_MS = 24 * 60 * 60 * 1000;++export interface AgentCollisionFinding {+ readonly entity: string;+ /** Distinct agents involved, sorted. */+ readonly agents: ReadonlyArray<string>;+ /** Distinct aspects touched, sorted. */+ readonly aspects: ReadonlyArray<string>;+ /** Distinct sources cited, sorted. */+ readonly sources: ReadonlyArray<string>;+ /** Participating claim count. */+ readonly claims: number;+ /** Timestamp of the newest participating claim. */+ readonly detectedAt: string;+}++export interface DetectCollisionOptions {+ readonly now: Date;+ readonly windowDays?: number;+ readonly cap?: number;+}++/**+ * Group recent claims by entity; an entity claimed by 2+ distinct+ * agents citing 2+ distinct sources is a collision. Findings sort by+ * recency (newest first) and are bounded by the cap.+ */+export function detectAgentCollisions(+ events: ReadonlyArray<ClaimEvent>,+ opts: DetectCollisionOptions,+): ReadonlyArray<AgentCollisionFinding> {+ const windowDays = opts.windowDays ?? COLLISION_WINDOW_DAYS;+ const cap = opts.cap ?? COLLISION_FINDINGS_CAP;+ const cutoff = opts.now.getTime() - windowDays * DAY_MS;++ const byEntity = new Map<string, ClaimEvent[]>();+ for (const e of events) {+ const ts = Date.parse(e.ts);+ if (!Number.isFinite(ts) || ts < cutoff) continue;+ const list = byEntity.get(e.entity) ?? [];+ list.push(e);+ byEntity.set(e.entity, list);+ }++ const findings: AgentCollisionFinding[] = [];+ for (const entity of [...byEntity.keys()].toSorted()) {+ const claims = byEntity.get(entity)!;+ const agents = [...new Set(claims.map((c) => c.agent))].toSorted();+ if (agents.length < 2) continue;+ const sources = [...new Set(claims.map((c) => c.source))].toSorted();+ if (sources.length < 2) continue;+ const aspects = [...new Set(claims.map((c) => c.aspect))].toSorted();+ const detectedAt = claims+ .map((c) => c.ts)+ .toSorted()+ .at(-1)!;+ findings.push(+ Object.freeze({+ entity,+ agents: Object.freeze(agents),+ aspects: Object.freeze(aspects),+ sources: Object.freeze(sources),+ claims: claims.length,+ detectedAt,+ }),+ );+ }++ findings.sort((a, b) => {+ if (a.detectedAt !== b.detectedAt) return a.detectedAt < b.detectedAt ? 1 : -1;+ return a.entity < b.entity ? -1 : a.entity > b.entity ? 1 : 0;+ });+ return Object.freeze(findings.slice(0, cap));+}++/** Findings as trigger candidates for the standing queue. */+export function collisionCandidates(+ findings: ReadonlyArray<AgentCollisionFinding>,+ windowDays: number = COLLISION_WINDOW_DAYS,+): ReadonlyArray<InsightCandidate> {+ return Object.freeze(+ findings.map((f) =>+ Object.freeze({+ kind: "agent_collision" as const,+ urgency: "medium" as const,+ reason:+ `${f.agents.join(" and ")} independently logged ${f.claims} claim(s) about ` ++ `${f.entity} within ${windowDays}d (aspects: ${f.aspects.join(", ")})`,+ suggestedAction: "Cross-reference the converging claims and connect or reconcile them",+ sourceArtifacts: Object.freeze([...f.sources]),+ contextSnippets: Object.freeze([`entity: ${f.entity}`, `agents: ${f.agents.join(", ")}`]),+ cooldownKey: `agent_collision:${f.entity}:${f.agents.join("+")}`,+ }),+ ),+ );+}diff --git a/src/core/brain/truth/conflicts.ts b/src/core/brain/truth/conflicts.tsnew file mode 100644index 00000000..9c8186a1--- /dev/null+++ b/src/core/brain/truth/conflicts.ts@@ -0,0 +1,91 @@+/**+ * Conflict detection (t_e9692750): a policy layer over the base truth+ * fold. The rule is purely temporal-structural - two distinct values+ * for one slot whose assertions land within the conflict window and+ * come from independent sources are CONTESTED (typed conflict,+ * `resolution: ask_user`, never auto-resolved); a later value outside+ * the window supersedes silently because that is normal fact+ * evolution, not contradiction.+ */++import { computeTruthState } from "./fold.ts";+import type { ClaimEvent, ClaimSlot, ClaimVersion, TruthConflict, TruthState } from "./types.ts";++/** Two values asserted within this many days of each other contest. */+export const CONFLICT_WINDOW_DAYS = 30;++const DAY_MS = 24 * 60 * 60 * 1000;++export interface ConflictOptions {+ /** Override the conflict window, in days. */+ readonly windowDays?: number;+}++function withinWindow(aTs: string, bTs: string, windowDays: number): boolean {+ const delta = Math.abs(Date.parse(aTs) - Date.parse(bTs));+ return Number.isFinite(delta) && delta <= windowDays * DAY_MS;+}++/**+ * Contesting versions for one slot: every history value whose latest+ * assertion is within the window of the current value AND whose source+ * differs (same source changing its value is self-correction). Returns+ * chronological order ending with the current value, or null when+ * nothing contests.+ */+function contestingValues(slot: ClaimSlot, windowDays: number): ClaimVersion[] | null {+ const contesting = slot.history+ .filter(+ (v) => withinWindow(v.ts, slot.current.ts, windowDays) && v.source !== slot.current.source,+ )+ .toReversed(); // history is newest-first; conflicts read chronologically+ if (contesting.length === 0) return null;+ return [...contesting, slot.current];+}++/**+ * The full fold with conflicts materialized and `contested` flags set.+ * With no conflicting events the output is deeply equal to+ * {@link computeTruthState} - the neutral default stays bit-identical.+ */+export function computeTruthStateWithConflicts(+ events: ReadonlyArray<ClaimEvent>,+ opts: ConflictOptions = {},+): TruthState {+ const windowDays = opts.windowDays ?? CONFLICT_WINDOW_DAYS;+ const base = computeTruthState(events);++ const conflicts: TruthConflict[] = [];+ const slots: ClaimSlot[] = [];+ let changed = false;++ for (const slot of base.slots) {+ const values = contestingValues(slot, windowDays);+ if (values === null) {+ slots.push(slot);+ continue;+ }+ changed = true;+ conflicts.push(+ Object.freeze({+ entity: slot.entity,+ aspect: slot.aspect,+ kind: "value_conflict" as const,+ values: Object.freeze(values),+ priority: values.length,+ resolution: "ask_user" as const,+ detectedAt: slot.current.ts,+ }),+ );+ slots.push(Object.freeze({ ...slot, contested: true }));+ }++ if (!changed) return base;+ // Slots are already sorted by (entity, aspect) in the base fold, so+ // conflicts built in slot order inherit the same deterministic sort.+ return Object.freeze({+ ...base,+ slots: Object.freeze(slots),+ conflicts: Object.freeze(conflicts),+ });+}diff --git a/src/core/brain/truth/contamination.ts b/src/core/brain/truth/contamination.tsnew file mode 100644index 00000000..0ea7877f--- /dev/null+++ b/src/core/brain/truth/contamination.ts@@ -0,0 +1,66 @@+/**+ * Entity-contamination check (t_e9692750): a synthesized conclusion+ * that mentions a registered entity absent from every cited source is+ * asserting provenance it does not have. The check is a pure+ * inclusion test over the canonical entity registry - same+ * normalization kernel as fact-extraction's anchors - so "Bob said+ * so" only survives synthesis when some cited source actually+ * mentions Bob.+ */++import { normalizeEntityName } from "../entities/canonical.ts";++/** The slice of a registry entity the check needs. */+export interface ContaminationEntityLike {+ readonly id: string;+ readonly name: string;+ readonly aliases: ReadonlyArray<string>;+ readonly status: string;+}++export interface ContaminationViolation {+ readonly entityId: string;+ readonly name: string;+}++export interface ContaminationResult {+ readonly clean: boolean;+ readonly violations: ReadonlyArray<ContaminationViolation>;+}++export interface ContaminationInput {+ readonly conclusion: string;+ readonly sources: ReadonlyArray<string>;+ readonly entities: ReadonlyArray<ContaminationEntityLike>;+}++function mentions(haystack: string, entity: ContaminationEntityLike): boolean {+ const forms = [entity.name, ...entity.aliases].map((f) => normalizeEntityName(f));+ return forms.some((f) => f.length >= 3 && haystack.includes(f));+}++/**+ * Every active registered entity mentioned in the conclusion must be+ * mentioned by at least one source. An empty registry or an empty+ * conclusion is trivially clean.+ */+export function checkEntityContamination(input: ContaminationInput): ContaminationResult {+ if (input.entities.length === 0 || input.conclusion.trim() === "") {+ return Object.freeze({ clean: true, violations: Object.freeze([]) });+ }+ const conclusion = normalizeEntityName(input.conclusion);+ const sources = input.sources.map((s) => normalizeEntityName(s));++ const violations: ContaminationViolation[] = [];+ for (const entity of input.entities) {+ if (entity.status !== "active") continue;+ if (!mentions(conclusion, entity)) continue;+ const cited = sources.some((source) => mentions(source, entity));+ if (!cited) violations.push(Object.freeze({ entityId: entity.id, name: entity.name }));+ }+ violations.sort((a, b) => (a.entityId < b.entityId ? -1 : a.entityId > b.entityId ? 1 : 0));+ return Object.freeze({+ clean: violations.length === 0,+ violations: Object.freeze(violations),+ });+}diff --git a/src/core/brain/truth/fold.ts b/src/core/brain/truth/fold.tsnew file mode 100644index 00000000..d7c8a16c--- /dev/null+++ b/src/core/brain/truth/fold.ts@@ -0,0 +1,127 @@+/**+ * The truth fold (t_d6849b56): a deterministic, order-insensitive+ * projection of claim events into per-(entity, aspect) slots. The+ * fold sorts its input internally, so the same event set always+ * produces the same state regardless of shard arrival order - the+ * `computeActivationState` discipline applied to claims.+ *+ * Conflict detection (t_e9692750) extends this fold in+ * `conflicts.ts`; the base fold keeps `conflicts` empty and+ * `contested: false` so the ledger core has no policy baked in.+ */++import { normalizeEntityName } from "../entities/canonical.ts";+import type { ClaimEvent, ClaimSlot, ClaimVersion, TruthState } from "./types.ts";+import { TRUTH_SCHEMA_VERSION } from "./types.ts";++/** Superseded values kept per slot, newest first. */+export const SLOT_HISTORY_CAP = 20;++/** Identity used to group claims into one addressable slot. */+export function slotKey(entity: string, aspect: string): string {+ return `${normalizeEntityName(entity)}\n${normalizeEntityName(aspect)}`;+}++/** Value identity inside a slot: case- and whitespace-insensitive. */+export function normalizeClaimValue(raw: string): string {+ return raw.normalize("NFC").trim().replace(/\s+/g, " ").toLowerCase();+}++/** Stable total order over events: (ts, agent, source, value). */+function compareEvents(a: ClaimEvent, b: ClaimEvent): number {+ if (a.ts !== b.ts) return a.ts < b.ts ? -1 : 1;+ if (a.agent !== b.agent) return a.agent < b.agent ? -1 : 1;+ if (a.source !== b.source) return a.source < b.source ? -1 : 1;+ if (a.value !== b.value) return a.value < b.value ? -1 : 1;+ return 0;+}++interface VersionAccumulator {+ value: string;+ valueKind: ClaimVersion["valueKind"];+ quantity: ClaimVersion["quantity"];+ ts: string;+ agent: string;+ source: string;+ assertCount: number;+}++function freezeVersion(acc: VersionAccumulator): ClaimVersion {+ return Object.freeze({+ value: acc.value,+ valueKind: acc.valueKind,+ ...(acc.quantity !== undefined ? { quantity: acc.quantity } : {}),+ ts: acc.ts,+ agent: acc.agent,+ source: acc.source,+ assertCount: acc.assertCount,+ });+}++/**+ * Fold claim events into the derived truth state. Consecutive+ * re-assertions of one value collapse into a single version whose+ * `ts`/`agent`/`source` track the latest assertion and whose+ * `assertCount` counts every one; a different value opens a new+ * version and pushes the previous one into history (bounded to+ * {@link SLOT_HISTORY_CAP}, newest first).+ */+export function computeTruthState(events: ReadonlyArray<ClaimEvent>): TruthState {+ const ordered = [...events].toSorted(compareEvents);+ const byKey = new Map<string, VersionAccumulator[]>();+ let latestTs: string | null = null;++ for (const e of ordered) {+ if (latestTs === null || e.ts > latestTs) latestTs = e.ts;+ const key = slotKey(e.entity, e.aspect);+ const versions = byKey.get(key) ?? [];+ const last = versions.at(-1);+ if (last !== undefined && normalizeClaimValue(last.value) === normalizeClaimValue(e.value)) {+ last.ts = e.ts;+ last.agent = e.agent;+ last.source = e.source;+ last.assertCount++;+ if (e.quantity !== undefined) last.quantity = e.quantity;+ } else {+ versions.push({+ value: e.value,+ valueKind: e.valueKind,+ quantity: e.quantity,+ ts: e.ts,+ agent: e.agent,+ source: e.source,+ assertCount: 1,+ });+ }+ byKey.set(key, versions);+ }++ const slots: ClaimSlot[] = [];+ for (const key of [...byKey.keys()].toSorted()) {+ const versions = byKey.get(key)!;+ const [entity, aspect] = key.split("\n") as [string, string];+ const current = versions.at(-1)!;+ const history = versions+ .slice(0, -1)+ .toReversed()+ .slice(0, SLOT_HISTORY_CAP)+ .map(freezeVersion);+ slots.push(+ Object.freeze({+ entity,+ aspect,+ current: freezeVersion(current),+ history: Object.freeze(history),+ contested: false,+ }),+ );+ }++ return Object.freeze({+ version: TRUTH_SCHEMA_VERSION,+ events: events.length,+ updatedAt: latestTs,+ slots: Object.freeze(slots),+ conflicts: Object.freeze([]),+ });+}diff --git a/src/core/brain/truth/ingest.ts b/src/core/brain/truth/ingest.tsnew file mode 100644index 00000000..9ec6807f--- /dev/null+++ b/src/core/brain/truth/ingest.ts@@ -0,0 +1,104 @@+/**+ * Assertion-to-claim structuring (t_cbd22536 + t_220c313e): the+ * explicit bridge between atomic assertions and the claim ledger.+ * Only assertions matching a structured fact family ingest - aspects+ * are never guessed from arbitrary prose. The capture hot path stays+ * untouched; callers invoke this through the `facts decompose+ * --ingest` verb or the MCP ingest op.+ */++import type { AtomicAssertion } from "../atomic-facts.ts";+import { extractFacts, parseQuantityFact } from "../fact-extract.ts";+import { normalizeClaimValue } from "./fold.ts";+import type { AppendClaimInput } from "./store.ts";++/** Cap on the derived aspect length. */+const MAX_ASPECT_CHARS = 120;++export interface AssertionClaimInput {+ /** Entity the claims are about (explicit, never guessed). */+ readonly entity: string;+ readonly agent: string;+ /** Canonical ISO-8601 UTC timestamp for the claim events. */+ readonly ts: string;+ /** Provenance wikilink or path for every derived claim. */+ readonly source: string;+}++interface FamilyStructurer {+ readonly re: RegExp;+ readonly aspect: string;+ /** Capture group index holding the value. */+ readonly group: number;+}++// Deterministic value structurers for the families with a clean+// (aspect, value) shape. Preference/confirmation spans carry no+// addressable aspect and never ingest.+const STRUCTURERS: ReadonlyArray<FamilyStructurer> = Object.freeze([+ { re: /\bmy name is\s+([^\n.!?]{2,80})/iu, aspect: "name", group: 1 },+ { re: /\bI(?:'m| am) called\s+([^\n.!?]{2,80})/u, aspect: "name", group: 1 },+ { re: /\b(?:live|'m based|am based) in\s+([^\n.!?]{2,80})/iu, aspect: "location", group: 1 },+ { re: /\b([\w.+-]+@[\w.-]+\.\w{2,})\b/u, aspect: "email", group: 1 },+ { re: /\b(https?:\/\/[^\s)>\]]+)/u, aspect: "website", group: 1 },+]);++const POSSESSION_RE = /\bmy ([a-z][\w -]{1,40}?) is\s+([^\n.!?]{2,100})/iu;++/**+ * Derive claim inputs from one assertion's facts. Quantity facts use+ * the normalized assertion text as the aspect, so re-ingesting the+ * same sentence folds idempotently into one slot while distinct+ * measurements stay separate slots that aggregation can sum.+ */+export function claimsFromAssertion(+ assertion: Pick<AtomicAssertion, "text">,+ input: AssertionClaimInput,+): AppendClaimInput[] {+ const out: AppendClaimInput[] = [];+ const facts = extractFacts(assertion.text);+ for (const fact of facts) {+ if (fact.family === "quantity") {+ const quantity = parseQuantityFact(fact.text);+ if (quantity === null) continue;+ out.push({+ ts: input.ts,+ agent: input.agent,+ entity: input.entity,+ aspect: normalizeClaimValue(fact.text).slice(0, MAX_ASPECT_CHARS),+ value: String(quantity.value),+ valueKind: "quantity",+ quantity: { value: quantity.value, unit: quantity.unit, action: quantity.action },+ source: input.source,+ });+ continue;+ }+ if (fact.family === "possession") {+ const m = POSSESSION_RE.exec(fact.text);+ if (m === null) continue;+ out.push({+ ts: input.ts,+ agent: input.agent,+ entity: input.entity,+ aspect: m[1]!.trim().toLowerCase(),+ value: m[2]!.trim(),+ source: input.source,+ });+ continue;+ }+ for (const s of STRUCTURERS) {+ const m = s.re.exec(fact.text);+ if (m === null) continue;+ out.push({+ ts: input.ts,+ agent: input.agent,+ entity: input.entity,+ aspect: s.aspect,+ value: m[s.group]!.trim(),+ source: input.source,+ });+ break;+ }+ }+ return out;+}diff --git a/src/core/brain/truth/merge-guard.ts b/src/core/brain/truth/merge-guard.tsnew file mode 100644index 00000000..d3cbdbf8--- /dev/null+++ b/src/core/brain/truth/merge-guard.ts@@ -0,0 +1,105 @@+/**+ * Name-aware merge guard (t_e9692750): dedup similarity is content+ * similarity, so without this guard "Alice decided X" and "Bob+ * decided X" look like near-duplicates and a merge would collapse two+ * people's decisions into one. The guard anchors both texts against+ * the canonical entity registry and refuses when the guarded anchor+ * sets are disjoint and non-empty - the one shape that is+ * demonstrably unsafe. Everything else (no anchors, overlapping+ * anchors) merges exactly as today.+ */++import { normalizeEntityName } from "../entities/canonical.ts";++/** Categories guarded by default: people and organisations. */+export const GUARDED_ENTITY_CATEGORIES: ReadonlyArray<string> = Object.freeze([+ "people",+ "person",+ "org",+ "organization",+ "organisation",+ "company",+ "team",+]);++/** The slice of a registry entity the guard needs. */+export interface GuardEntityLike {+ readonly id: string;+ readonly category: string;+ readonly name: string;+ readonly aliases: ReadonlyArray<string>;+ readonly status: string;+}++export interface GuardEntityMergeInput {+ readonly keepText: string;+ readonly dropText: string;+ readonly entities: ReadonlyArray<GuardEntityLike>;+ /** Override the guarded category set. */+ readonly categories?: ReadonlyArray<string>;+}++export interface MergeGuardVerdict {+ readonly allowed: boolean;+ /** Explainable refusal reason; null when allowed. */+ readonly reason: string | null;+ readonly keepAnchors: ReadonlyArray<string>;+ readonly dropAnchors: ReadonlyArray<string>;+}++/**+ * Anchor a text against guarded entities: every active entity whose+ * normalized name or alias appears in the normalized text. The same+ * inclusion rule as fact-extraction's `entityAnchors`, restricted to+ * the guarded categories.+ */+function guardedAnchors(+ text: string,+ entities: ReadonlyArray<GuardEntityLike>,+ categories: ReadonlySet<string>,+): string[] {+ const haystack = normalizeEntityName(text);+ const ids: string[] = [];+ for (const entity of entities) {+ if (entity.status !== "active") continue;+ if (!categories.has(entity.category.toLowerCase())) continue;+ const forms = [entity.name, ...entity.aliases].map((f) => normalizeEntityName(f));+ if (forms.some((f) => f.length >= 3 && haystack.includes(f))) ids.push(entity.id);+ }+ return ids.toSorted();+}++/**+ * Decide whether merging two texts is entity-safe. Blocks ONLY when+ * both sides carry guarded anchors and the sets share nothing.+ */+export function guardEntityMerge(input: GuardEntityMergeInput): MergeGuardVerdict {+ const categories = new Set(+ (input.categories ?? GUARDED_ENTITY_CATEGORIES).map((c) => c.toLowerCase()),+ );+ const keepAnchors = guardedAnchors(input.keepText, input.entities, categories);+ const dropAnchors = guardedAnchors(input.dropText, input.entities, categories);++ const disjoint =+ keepAnchors.length > 0 &&+ dropAnchors.length > 0 &&+ !keepAnchors.some((id) => dropAnchors.includes(id));++ if (!disjoint) {+ return Object.freeze({+ allowed: true,+ reason: null,+ keepAnchors: Object.freeze(keepAnchors),+ dropAnchors: Object.freeze(dropAnchors),+ });+ }+ return Object.freeze({+ allowed: false,+ reason:+ `entity merge guard: keep anchors [${keepAnchors.join(", ")}] and ` ++ `drop anchors [${dropAnchors.join(", ")}] are disjoint - merging would ` ++ `collapse claims about different entities`,+ keepAnchors: Object.freeze(keepAnchors),+ dropAnchors: Object.freeze(dropAnchors),+ });+}diff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.tsnew file mode 100644index 00000000..0962ed26--- /dev/null+++ b/src/core/brain/truth/store.ts@@ -0,0 +1,424 @@+/**+ * Claim ledger store (t_d6849b56): device-sharded append-only JSONL+ * under `Brain/truth/`, merging the `log-jsonl.ts` shard discipline+ * (Syncthing-safe concurrent appends) with the `activation/store.ts`+ * derived-fold discipline (the state file is a recomputable cache,+ * never authority).+ *+ * - `claims.jsonl` - legacy/un-sharded shard (empty id);+ * - `claims.<deviceId>.jsonl` - one append-only file per device;+ * - `state.json` - derived fold, safe to delete.+ *+ * Every line carries `v: TRUTH_SCHEMA_VERSION` and parses fail-closed:+ * malformed or unknown-version lines surface as warnings, never throw.+ */++import {+ existsSync,+ mkdirSync,+ appendFileSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";++import { resolveDeviceId } from "../../config.ts";+import { normalizeEntityName } from "../entities/canonical.ts";+import { computeTruthState } from "./fold.ts";+import type {+ ClaimEvent,+ ClaimParseWarning,+ ClaimQuantity,+ ClaimSlot,+ ClaimSweepOutcome,+ ClaimVersion,+ ReadClaimEventsResult,+ TruthConflict,+ TruthState,+} from "./types.ts";+import { TRUTH_SCHEMA_VERSION } from "./types.ts";++/** Default cap on retained claim events (explicit sweep only). */+export const CLAIM_EVENT_MAX_COUNT = 10000;++// Same canonical UTC shape the log writer emits; see ISO_UTC_TS_RE in+// log-jsonl.ts for why this stays strict.+const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;++// `claims.jsonl` or `claims.<deviceId>.jsonl`; device ids are lowercase+// slugs, and Syncthing conflict copies are never shards.+const CLAIM_SHARD_RE = /^claims(?:\.([a-z0-9-]{1,32}))?\.jsonl$/;++export function truthDir(vault: string): string {+ return join(vault, "Brain", "truth");+}++export function truthStatePath(vault: string): string {+ return join(truthDir(vault), "state.json");+}++/** The shard this device appends to. */+export function claimShardPath(vault: string, configPath?: string): string {+ const deviceId = resolveDeviceId(configPath);+ const name = deviceId === "" ? "claims.jsonl" : `claims.${deviceId}.jsonl`;+ return join(truthDir(vault), name);+}++export interface AppendClaimInput {+ readonly ts: string;+ readonly agent: string;+ readonly entity: string;+ readonly aspect: string;+ readonly value: string;+ readonly valueKind?: ClaimEvent["valueKind"];+ readonly quantity?: ClaimQuantity;+ readonly source: string;+}++export interface AppendClaimResult {+ readonly path: string;+ readonly event: ClaimEvent;+}++/**+ * Validate, normalize identity fields, append one JSONL line to this+ * device's shard, and refresh the derived state cache.+ */+export function appendClaimEvent(+ vault: string,+ input: AppendClaimInput,+ opts: { readonly configPath?: string } = {},+): AppendClaimResult {+ const entity = normalizeEntityName(input.entity);+ const aspect = normalizeEntityName(input.aspect);+ if (entity === "") throw new Error("claim entity must not be empty");+ if (aspect === "") throw new Error("claim aspect must not be empty");+ const value = input.value.trim();+ if (value === "") throw new Error("claim value must not be empty");+ if (input.agent.trim() === "") throw new Error("claim agent must not be empty");+ if (input.source.trim() === "") throw new Error("claim source must not be empty");+ if (!ISO_UTC_TS_RE.test(input.ts)) {+ throw new Error(`claim ts must be canonical ISO-8601 UTC: ${JSON.stringify(input.ts)}`);+ }++ const event: ClaimEvent = Object.freeze({+ v: TRUTH_SCHEMA_VERSION,+ ts: input.ts,+ agent: input.agent.trim(),+ entity,+ aspect,+ value,+ valueKind: input.valueKind ?? "text",+ ...(input.quantity !== undefined ? { quantity: input.quantity } : {}),+ source: input.source.trim(),+ });++ mkdirSync(truthDir(vault), { recursive: true });+ const path = claimShardPath(vault, opts.configPath);+ appendFileSync(path, JSON.stringify(event) + "\n");+ writeTruthState(vault, computeTruthState(readClaimEvents(vault).events));+ return Object.freeze({ path, event });+}++/**+ * Read every retained claim event merged across shards, sorted by+ * (ts, shardId, line). Fail-closed per line.+ */+export function readClaimEvents(vault: string): ReadClaimEventsResult {+ const dir = truthDir(vault);+ let names: string[];+ try {+ names = readdirSync(dir).toSorted();+ } catch {+ return { events: [], warnings: [] };+ }++ interface Tagged {+ readonly event: ClaimEvent;+ readonly shardId: string;+ readonly line: number;+ }+ const tagged: Tagged[] = [];+ const warnings: ClaimParseWarning[] = [];++ for (const name of names) {+ const m = CLAIM_SHARD_RE.exec(name);+ if (!m) continue;+ const shardId = m[1] ?? "";+ if (shardId.startsWith("sync-conflict")) continue;+ const path = join(dir, name);+ let text: string;+ try {+ text = readFileSync(path, "utf8");+ } catch (err) {+ const message = (err as NodeJS.ErrnoException).message ?? String(err);+ warnings.push({ path, lineNumber: 0, message: `failed to read shard: ${message}` });+ continue;+ }+ const lines = text.split(/\r?\n/);+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ if (line.trim() === "") continue;+ let parsed: unknown;+ try {+ parsed = JSON.parse(line);+ } catch {+ warnings.push({+ path,+ lineNumber: i + 1,+ message: `malformed JSONL line: ${line.slice(0, 80)}`,+ });+ continue;+ }+ const event = coerceClaim(parsed, path, i + 1, warnings);+ if (event !== null) tagged.push({ event, shardId, line: i });+ }+ }++ tagged.sort((a, b) => {+ if (a.event.ts !== b.event.ts) return a.event.ts < b.event.ts ? -1 : 1;+ if (a.shardId !== b.shardId) return a.shardId < b.shardId ? -1 : 1;+ return a.line - b.line;+ });++ return { events: tagged.map((t) => t.event), warnings };+}++function coerceClaim(+ raw: unknown,+ path: string,+ lineNumber: number,+ warnings: ClaimParseWarning[],+): ClaimEvent | null {+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {+ warnings.push({ path, lineNumber, message: "claim row is not an object" });+ return null;+ }+ const obj = raw as Record<string, unknown>;+ if (obj["v"] !== TRUTH_SCHEMA_VERSION) {+ warnings.push({+ path,+ lineNumber,+ message: `unknown claim schema version: ${String(obj["v"])}`,+ });+ return null;+ }+ const ts = obj["ts"];+ if (typeof ts !== "string" || !ISO_UTC_TS_RE.test(ts)) {+ warnings.push({ path, lineNumber, message: `invalid claim ts: ${String(ts)}` });+ return null;+ }+ for (const key of ["agent", "entity", "aspect", "value", "source"] as const) {+ if (typeof obj[key] !== "string" || (obj[key] as string).trim() === "") {+ warnings.push({ path, lineNumber, message: `claim row missing ${key}` });+ return null;+ }+ }+ const valueKind = obj["valueKind"];+ if (valueKind !== "text" && valueKind !== "quantity") {+ warnings.push({ path, lineNumber, message: `invalid claim valueKind: ${String(valueKind)}` });+ return null;+ }+ let quantity: ClaimQuantity | undefined;+ if (obj["quantity"] !== undefined) {+ const q = obj["quantity"];+ if (+ q === null ||+ typeof q !== "object" ||+ typeof (q as Record<string, unknown>)["value"] !== "number" ||+ !Number.isFinite((q as Record<string, unknown>)["value"])+ ) {+ warnings.push({ path, lineNumber, message: "invalid claim quantity payload" });+ return null;+ }+ const qo = q as Record<string, unknown>;+ const unit = qo["unit"];+ const action = qo["action"];+ if (unit !== null && typeof unit !== "string") {+ warnings.push({ path, lineNumber, message: "invalid claim quantity unit" });+ return null;+ }+ if (action !== null && typeof action !== "string") {+ warnings.push({ path, lineNumber, message: "invalid claim quantity action" });+ return null;+ }+ quantity = Object.freeze({+ value: qo["value"] as number,+ unit: unit as string | null,+ action: action as string | null,+ });+ }+ return Object.freeze({+ v: TRUTH_SCHEMA_VERSION,+ ts,+ agent: obj["agent"] as string,+ entity: obj["entity"] as string,+ aspect: obj["aspect"] as string,+ value: obj["value"] as string,+ valueKind,+ ...(quantity !== undefined ? { quantity } : {}),+ source: obj["source"] as string,+ });+}++export function writeTruthState(vault: string, state: TruthState): void {+ mkdirSync(truthDir(vault), { recursive: true });+ writeFileSync(truthStatePath(vault), JSON.stringify(state, null, 2) + "\n");+}++function isClaimVersion(v: unknown): v is ClaimVersion {+ if (v === null || typeof v !== "object") return false;+ const row = v as Record<string, unknown>;+ return (+ typeof row["value"] === "string" &&+ (row["valueKind"] === "text" || row["valueKind"] === "quantity") &&+ typeof row["ts"] === "string" &&+ typeof row["agent"] === "string" &&+ typeof row["source"] === "string" &&+ typeof row["assertCount"] === "number" &&+ Number.isInteger(row["assertCount"]) &&+ (row["assertCount"] as number) >= 1+ );+}++function isClaimSlot(v: unknown): v is ClaimSlot {+ if (v === null || typeof v !== "object") return false;+ const row = v as Record<string, unknown>;+ return (+ typeof row["entity"] === "string" &&+ typeof row["aspect"] === "string" &&+ isClaimVersion(row["current"]) &&+ Array.isArray(row["history"]) &&+ (row["history"] as unknown[]).every(isClaimVersion) &&+ typeof row["contested"] === "boolean"+ );+}++function isTruthConflict(v: unknown): v is TruthConflict {+ if (v === null || typeof v !== "object") return false;+ const row = v as Record<string, unknown>;+ return (+ typeof row["entity"] === "string" &&+ typeof row["aspect"] === "string" &&+ row["kind"] === "value_conflict" &&+ Array.isArray(row["values"]) &&+ (row["values"] as unknown[]).every(isClaimVersion) &&+ typeof row["priority"] === "number" &&+ Number.isFinite(row["priority"]) &&+ row["resolution"] === "ask_user" &&+ typeof row["detectedAt"] === "string"+ );+}++/**+ * Read the derived state cache; structurally invalid content (including+ * corrupt nested rows) reads as null and the caller refolds from events.+ */+export function readTruthState(vault: string): TruthState | null {+ try {+ const parsed = JSON.parse(readFileSync(truthStatePath(vault), "utf8")) as TruthState;+ if (parsed.version !== TRUTH_SCHEMA_VERSION) return null;+ if (!Number.isInteger(parsed.events) || parsed.events < 0) return null;+ if (!(parsed.updatedAt === null || typeof parsed.updatedAt === "string")) return null;+ if (!Array.isArray(parsed.slots)) return null;+ if (!Array.isArray(parsed.conflicts)) return null;+ for (const slot of parsed.slots as ReadonlyArray<unknown>) {+ if (!isClaimSlot(slot)) return null;+ }+ for (const conflict of parsed.conflicts as ReadonlyArray<unknown>) {+ if (!isTruthConflict(conflict)) return null;+ }+ return parsed;+ } catch {+ return null;+ }+}++export interface ClaimSweepOptions {+ /** At most this many newest events are kept. */+ readonly maxEvents?: number;+}++/**+ * Keep the newest N events across all shards (rewriting each shard+ * with only its surviving lines), then refold the derived state.+ * Sweeping is an explicit operator action - appends never auto-drop+ * history.+ */+export function sweepClaimEvents(vault: string, opts: ClaimSweepOptions): ClaimSweepOutcome {+ const maxEvents = opts.maxEvents ?? CLAIM_EVENT_MAX_COUNT;+ const dir = truthDir(vault);+ let names: string[];+ try {+ names = readdirSync(dir).toSorted();+ } catch {+ // No event directory: refold an orphaned state file so stale slots+ // never outlive their events.+ if (existsSync(truthStatePath(vault))) {+ writeTruthState(vault, computeTruthState([]));+ }+ return Object.freeze({ removed: 0, kept: 0 });+ }++ // Collect (shard, line, ts) for every valid line; drop the oldest+ // beyond the cap. Invalid lines are preserved verbatim in place -+ // sweep bounds growth, doctor surfaces corruption.+ interface ShardLine {+ readonly name: string;+ readonly index: number;+ readonly raw: string;+ readonly ts: string | null;+ }+ const shards = new Map<string, string[]>();+ const valid: ShardLine[] = [];+ for (const name of names) {+ const m = CLAIM_SHARD_RE.exec(name);+ if (!m) continue;+ if ((m[1] ?? "").startsWith("sync-conflict")) continue;+ let text: string;+ try {+ text = readFileSync(join(dir, name), "utf8");+ } catch {+ continue;+ }+ const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");+ shards.set(name, lines);+ lines.forEach((raw, index) => {+ let ts: string | null = null;+ try {+ const parsed = JSON.parse(raw) as Record<string, unknown>;+ if (typeof parsed["ts"] === "string" && ISO_UTC_TS_RE.test(parsed["ts"])) {+ ts = parsed["ts"];+ }+ } catch {+ // Invalid lines never count toward the cap.+ }+ if (ts !== null) valid.push({ name, index, raw, ts });+ });+ }++ valid.sort((a, b) => {+ if (a.ts !== b.ts) return a.ts! < b.ts! ? -1 : 1;+ if (a.name !== b.name) return a.name < b.name ? -1 : 1;+ return a.index - b.index;+ });+ const overflow = valid.length > maxEvents ? valid.slice(0, valid.length - maxEvents) : [];+ const removedKeys = new Set(overflow.map((x) => `${x.name}\n${x.index}`));++ if (removedKeys.size > 0) {+ for (const [name, lines] of shards) {+ const kept = lines.filter((_, index) => !removedKeys.has(`${name}\n${index}`));+ const path = join(dir, name);+ if (kept.length === 0) {+ rmSync(path, { force: true });+ } else if (kept.length !== lines.length) {+ writeFileSync(path, kept.join("\n") + "\n");+ }+ }+ }++ writeTruthState(vault, computeTruthState(readClaimEvents(vault).events));+ return Object.freeze({ removed: overflow.length, kept: valid.length - overflow.length });+}diff --git a/src/core/brain/truth/types.ts b/src/core/brain/truth/types.tsnew file mode 100644index 00000000..aff17d6a--- /dev/null+++ b/src/core/brain/truth/types.ts@@ -0,0 +1,113 @@+/**+ * Entity-Truth Ledger types (Entity Truth & Self-Improving Dream+ * Suite, t_e9692750 + t_d6849b56).+ *+ * The ledger answers "what is true about this entity right now"+ * without ever mutating history: claims are append-only events,+ * slots and conflicts are derived projections (see `fold.ts`).+ */++/** Schema version stamped on every persisted claim line and state file. */+export const TRUTH_SCHEMA_VERSION = 1;++export type ClaimValueKind = "text" | "quantity";++/** Structured payload for the quantitative fact family (t_220c313e). */+export interface ClaimQuantity {+ readonly value: number;+ /** Canonical unit token (`usd`, `hours`, ...) or null when unitless. */+ readonly unit: string | null;+ /** Measured action (`spent`, `ran`, ...) or null when unstated. */+ readonly action: string | null;+}++/**+ * One appended claim line: agent X asserted that `entity`'s `aspect`+ * is `value`, citing `source`. Entity and aspect are stored canonical+ * (NFC, lowercase, collapsed whitespace) so slot addressing compares+ * like with like; `value` keeps its display casing and is normalized+ * only for identity comparison inside the fold.+ */+export interface ClaimEvent {+ readonly v: typeof TRUTH_SCHEMA_VERSION;+ /** Canonical ISO-8601 UTC timestamp. */+ readonly ts: string;+ readonly agent: string;+ readonly entity: string;+ readonly aspect: string;+ readonly value: string;+ readonly valueKind: ClaimValueKind;+ readonly quantity?: ClaimQuantity;+ /** Provenance wikilink or vault-relative path. */+ readonly source: string;+}++/** One value a slot held, with full provenance lineage. */+export interface ClaimVersion {+ readonly value: string;+ readonly valueKind: ClaimValueKind;+ readonly quantity?: ClaimQuantity;+ /** Latest assertion timestamp for this value. */+ readonly ts: string;+ readonly agent: string;+ readonly source: string;+ /** How many events asserted this value. */+ readonly assertCount: number;+}++/**+ * The addressable per-(entity, aspect) projection: current value plus+ * superseded prior values, newest first.+ */+export interface ClaimSlot {+ readonly entity: string;+ readonly aspect: string;+ readonly current: ClaimVersion;+ readonly history: ReadonlyArray<ClaimVersion>;+ /** True when an unresolved conflict involves this slot (t_e9692750). */+ readonly contested: boolean;+}++export type TruthConflictKind = "value_conflict";++/**+ * A materialized contradiction: two distinct values for one slot+ * within the conflict window from independent sources. Never+ * auto-resolved - the strategy is always `ask_user` in this release.+ */+export interface TruthConflict {+ readonly entity: string;+ readonly aspect: string;+ readonly kind: TruthConflictKind;+ readonly values: ReadonlyArray<ClaimVersion>;+ /** Higher = more urgent (more recent, more independent sources). */+ readonly priority: number;+ readonly resolution: "ask_user";+ /** Timestamp of the claim that surfaced the conflict. */+ readonly detectedAt: string;+}++/** The derived fold over all retained claim events. */+export interface TruthState {+ readonly version: typeof TRUTH_SCHEMA_VERSION;+ readonly events: number;+ readonly updatedAt: string | null;+ readonly slots: ReadonlyArray<ClaimSlot>;+ readonly conflicts: ReadonlyArray<TruthConflict>;+}++export interface ClaimParseWarning {+ readonly path: string;+ readonly lineNumber: number;+ readonly message: string;+}++export interface ReadClaimEventsResult {+ readonly events: ReadonlyArray<ClaimEvent>;+ readonly warnings: ReadonlyArray<ClaimParseWarning>;+}++export interface ClaimSweepOutcome {+ readonly removed: number;+ readonly kept: number;+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 7e9e4bff..049015f6 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -131,6 +131,20 @@ export const BRAIN_APPLY_RESULT = {} as const;export type BrainApplyResult = (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];+/**+ * Optional downstream outcome riding on an apply-evidence event+ * (t_d478df53): did the artifact the rule was applied to actually+ * succeed? `unknown` is the explicit "cannot tell" spelling and is+ * treated exactly like an absent outcome - only success/failure+ * persist, so outcome-free vaults stay byte-identical.+ */+export const BRAIN_APPLY_OUTCOME = {+ success: "success",+ failure: "failure",+ unknown: "unknown",+} as const;+export type BrainApplyOutcome = (typeof BRAIN_APPLY_OUTCOME)[keyof typeof BRAIN_APPLY_OUTCOME];+/*** All possible log event types. `dream` summarises a run; `feedback`* records the creation of a signal; `apply-evidence` records a real-work@@ -568,6 +582,8 @@ export interface BrainEvidenceSummary {readonly result: BrainApplyResult;readonly agent?: string;readonly note?: string;+ /** Downstream outcome when recorded (t_d478df53). */+ readonly outcome?: BrainApplyOutcome;}// ----- Log events -----------------------------------------------------------diff --git a/src/core/search/store.ts b/src/core/search/store.tsindex da99e480..2a96b6aa 100644--- a/src/core/search/store.ts+++ b/src/core/search/store.ts@@ -748,6 +748,38 @@ export class Store {}}+ /** Ordered chunk ids for one document (surprisal, t_fddfe64a). */+ chunksForDocument(documentId: number): ReadonlyArray<{ id: number; chunkIndex: number }> {+ return this.db+ .query<{ id: number; chunk_index: number }, [number]>(+ "SELECT id, chunk_index FROM chunks WHERE document_id = ? ORDER BY chunk_index ASC",+ )+ .all(documentId)+ .map((r) => ({ id: r.id, chunkIndex: r.chunk_index }));+ }++ /**+ * The stored embedding for one chunk, or null when the vec layer is+ * unavailable or the chunk was never embedded (surprisal,+ * t_fddfe64a).+ */+ embeddingForChunk(chunkId: number): Float32Array | null {+ if (!this.vecLoaded()) return null;+ const row = this.db+ .query<{ embedding: Uint8Array }, [number]>(+ "SELECT v.embedding AS embedding FROM chunk_vec v " ++ "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid WHERE m.chunk_id = ?",+ )+ .get(chunkId);+ if (!row) return null;+ const bytes = row.embedding;+ // Copy instead of viewing: a pooled buffer with a non-4-byte-aligned+ // byteOffset would make the Float32Array constructor throw.+ return new Float32Array(+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),+ );+ }+getEmbeddingHash(chunkId: number): string | null {const row = this.db.query<{ embedding_hash: string }, [number]>(diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 4838b3a6..b9ae1a2f 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -181,6 +181,13 @@ import {type BrainSignal,type BrainSignalSign,} from "../core/brain/types.ts";+import { normalizeEntityName } from "../core/brain/entities/canonical.ts";+import { listDeadEnds, recordDeadEnd } from "../core/brain/dead-ends.ts";+import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../core/brain/temporal/foresight.ts";+import { aggregateQuantities } from "../core/brain/truth/aggregate.ts";+import { detectAgentCollisions } from "../core/brain/truth/collision.ts";+import { computeTruthStateWithConflicts } from "../core/brain/truth/conflicts.ts";+import { appendClaimEvent, readClaimEvents } from "../core/brain/truth/store.ts";import { appendLogEvent } from "../core/brain/log.ts";import type { BrainLogEntry } from "../core/brain/log.ts";import { appendBrainNote } from "../core/brain/note.ts";@@ -494,8 +501,24 @@ async function toolBrainReviewCandidates(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const nowDate = coerceIsoDate(args, "now");- const report = buildReviewCandidates(ctx.vault, nowDate ? { now: nowDate } : {});+ // Surprisal annotation (t_fddfe64a) is best-effort: a resolvable+ // search config adds novelty ranking, anything else degrades to the+ // plain report.+ let searchConfig: ReturnType<typeof resolveSearchConfig> | undefined;+ try {+ searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ } catch {+ searchConfig = undefined;+ }+ const report = await buildReviewCandidates(ctx.vault, {+ ...(nowDate ? { now: nowDate } : {}),+ ...(searchConfig !== undefined ? { searchConfig } : {}),+ });return {+ ...(report.signal_novelty !== undefined ? { signal_novelty: report.signal_novelty } : {}),would_create: [...report.would_create],would_promote: [...report.would_promote],would_retire: report.would_retire.map((r) => ({@@ -553,6 +576,18 @@ async function toolBrainApplyEvidence(}const agentArg = coerceStr(args, "agent", false);const note = coerceStr(args, "note", false);+ const outcomeRaw = coerceStr(args, "outcome", false);+ if (+ outcomeRaw !== null &&+ outcomeRaw !== "success" &&+ outcomeRaw !== "failure" &&+ outcomeRaw !== "unknown"+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ `argument 'outcome' must be 'success', 'failure', or 'unknown'`,+ );+ }const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);@@ -561,6 +596,7 @@ async function toolBrainApplyEvidence(artifact,result: resultRaw as BrainApplyResult,agent,+ ...(outcomeRaw !== null ? { outcome: outcomeRaw } : {}),...(note ? { note } : {}),};@@ -1733,6 +1769,170 @@ async function toolBrainUnlinkedMentions(};}+// ----- brain_foresight (t_08a79c81) -----------------------------------------++/** Forward-looking projection envelope; read-only fold. */+function toolBrainForesight(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const horizonRaw = args["horizon_days"];+ let horizonDays = FORESIGHT_HORIZON_DAYS;+ if (horizonRaw !== undefined && horizonRaw !== null) {+ if (typeof horizonRaw !== "number" || !Number.isInteger(horizonRaw) || horizonRaw < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_foresight: horizon_days must be a positive integer",+ );+ }+ horizonDays = horizonRaw;+ }+ return { ...buildForesight(ctx.vault, { now: new Date(), horizonDays }) };+}++// ----- brain_dead_ends (t_be62c62d) -----------------------------------------++/**+ * Negative-knowledge registry: record one tried-and-failed approach+ * or list the bounded active set, newest first.+ */+function toolBrainDeadEnds(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const op = args["operation"];+ if (op !== "record" && op !== "list") {+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends: operation must be record|list");+ }+ if (op === "list") {+ const { entries, warnings } = listDeadEnds(ctx.vault);+ return { entries, warnings };+ }+ const approach = args["approach"];+ const reason = args["reason"];+ if (typeof approach !== "string" || approach.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: approach must be non-empty");+ }+ if (typeof reason !== "string" || reason.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: reason must be non-empty");+ }+ const agentArg = args["agent"];+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ const result = recordDeadEnd(ctx.vault, {+ approach,+ reason,+ ...(typeof args["context"] === "string" ? { context: args["context"] as string } : {}),+ agent,+ now: new Date(),+ });+ return { ok: true, id: result.entry.id, path: result.entry.path, archived: result.archived };+}++// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------++/**+ * Operator/agent surface over the entity claim ledger: ingest one+ * claim, render slots/conflicts from the fold, aggregate exact-match+ * quantities, report cross-agent collisions. Read ops are pure folds+ * over the append-only ledger.+ */+function toolBrainTruth(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const op = args["operation"];+ if (+ op !== "ingest" &&+ op !== "slots" &&+ op !== "conflicts" &&+ op !== "aggregate" &&+ op !== "collisions"+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",+ );+ }+ const requireStr = (name: string): string => {+ const value = args[name];+ if (typeof value !== "string" || value.trim() === "") {+ throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a non-empty string`);+ }+ return value;+ };++ if (op === "ingest") {+ const quantityValue = args["quantity_value"];+ if (+ (quantityValue === undefined || quantityValue === null) &&+ (typeof args["quantity_unit"] === "string" || typeof args["quantity_action"] === "string")+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_truth ingest: quantity_value is required when quantity_unit or quantity_action is provided",+ );+ }+ let quantity: { value: number; unit: string | null; action: string | null } | undefined;+ if (quantityValue !== undefined && quantityValue !== null) {+ if (typeof quantityValue !== "number" || !Number.isFinite(quantityValue)) {+ throw new MCPError(INVALID_PARAMS, "brain_truth ingest: quantity_value must be a number");+ }+ quantity = {+ value: quantityValue,+ unit: typeof args["quantity_unit"] === "string" ? (args["quantity_unit"] as string) : null,+ action:+ typeof args["quantity_action"] === "string" ? (args["quantity_action"] as string) : null,+ };+ }+ const agentArg = args["agent"];+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ const result = appendClaimEvent(ctx.vault, {+ ts: isoSecond(new Date()),+ agent,+ entity: requireStr("entity"),+ aspect: requireStr("aspect"),+ value: requireStr("value"),+ ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),+ source: requireStr("source"),+ });+ return {+ ok: true,+ entity: result.event.entity,+ aspect: result.event.aspect,+ path: result.path,+ };+ }++ const events = readClaimEvents(ctx.vault).events;+ if (op === "slots" || op === "conflicts") {+ const state = computeTruthStateWithConflicts(events);+ if (op === "conflicts") return { events: state.events, conflicts: state.conflicts };+ const entityFilter = args["entity"];+ const slots =+ typeof entityFilter === "string" && entityFilter.trim() !== ""+ ? state.slots.filter((s) => s.entity === normalizeEntityName(entityFilter))+ : state.slots;+ return { events: state.events, slots };+ }+ if (op === "aggregate") {+ const state = computeTruthStateWithConflicts(events);+ return {+ ...aggregateQuantities(state.slots, {+ action: requireStr("action"),+ unit: typeof args["unit"] === "string" ? (args["unit"] as string) : null,+ ...(typeof args["entity"] === "string" ? { entity: args["entity"] as string } : {}),+ }),+ };+ }+ return {+ collisions: detectAgentCollisions(events, { now: new Date() }),+ };+}+// ----- brain_concept_synthesis (v0.10.17) ----------------------------------/**@@ -2203,6 +2403,7 @@ async function toolBrainDeepSynthesis(superseded_by: s.supersededBy,})),gaps: report.gaps,+ contaminated: report.contaminated,...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),};}@@ -3258,6 +3459,12 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "string",description: "Optional agent identity override; defaults to the server-resolved name.",},+ outcome: {+ type: "string",+ enum: ["success", "failure", "unknown"],+ description:+ "Optional downstream outcome of the artifact (t_d478df53): did the work the rule was applied to actually succeed? `unknown` is treated like an absent outcome.",+ },note: {type: "string",description: "Optional one-line context.",@@ -4093,6 +4300,79 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},handler: toolBrainRecurrence,},+ {+ name: "brain_truth",+ description:+ "Entity claim ledger: ingest a claim, render current-truth slots with superseded history, list contested conflicts (ask_user), aggregate exact-match quantities, report cross-agent collisions.",+ inputSchema: {+ type: "object",+ properties: {+ operation: {+ type: "string",+ enum: ["ingest", "slots", "conflicts", "aggregate", "collisions"],+ description: "Tool operation.",+ },+ entity: {+ type: "string",+ description: "Entity name (ingest, slots filter, aggregate filter).",+ },+ aspect: { type: "string", description: "Aspect slot for ingest." },+ value: { type: "string", description: "Claim value for ingest." },+ source: { type: "string", description: "Provenance wikilink/path for ingest." },+ agent: { type: "string", description: "Agent identity override for ingest." },+ quantity_value: { type: "number", description: "Numeric value for quantity claims." },+ quantity_unit: { type: "string", description: "Unit token for quantity claims." },+ quantity_action: { type: "string", description: "Measured action for quantity claims." },+ action: { type: "string", description: "Measured action for aggregate." },+ unit: { type: "string", description: "Unit token for aggregate (omit for unitless)." },+ },+ required: ["operation"],+ additionalProperties: false,+ },+ handler: toolBrainTruth,+ previewBudget: MCP_PREVIEW_BUDGET,+ },+ {+ name: "brain_dead_ends",+ description:+ "Negative-knowledge registry (Brain/dead-ends/): record one tried-and-failed approach with why it failed, or list the bounded active set so recall surfaces avoid-X alongside prefer-Y.",+ inputSchema: {+ type: "object",+ properties: {+ operation: {+ type: "string",+ enum: ["record", "list"],+ description: "Tool operation.",+ },+ approach: { type: "string", description: "What was tried (record)." },+ reason: { type: "string", description: "Why it failed or was set aside (record)." },+ context: { type: "string", description: "Optional context (record)." },+ agent: { type: "string", description: "Agent identity override (record)." },+ },+ required: ["operation"],+ additionalProperties: false,+ },+ handler: toolBrainDeadEnds,+ previewBudget: MCP_PREVIEW_BUDGET,+ },+ {+ name: "brain_foresight",+ description:+ "Forward-looking projection (Brain's only anticipatory surface): recurring routines coming due within the horizon via cadence arithmetic, recent open commitments, and open questions - deterministic, every item carries sources.",+ inputSchema: {+ type: "object",+ properties: {+ horizon_days: {+ type: "integer",+ minimum: 1,+ description: "Forward horizon in days (default 14).",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainForesight,+ previewBudget: MCP_PREVIEW_BUDGET,+ },{name: "brain_procedural_graph",description:diff --git a/tests/cli/brain-dead-end.test.ts b/tests/cli/brain-dead-end.test.tsnew file mode 100644index 00000000..ddd6a2aa--- /dev/null+++ b/tests/cli/brain-dead-end.test.ts@@ -0,0 +1,66 @@+/**+ * `o2b brain dead-end` CLI surface (t_be62c62d): record and list the+ * negative-knowledge registry.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { listDeadEnds } from "../../src/core/brain/dead-ends.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-dead-end-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("record persists a dead-end note; list renders it", async () => {+ const rec = await runCli([+ "brain",+ "dead-end",+ "record",+ "--vault",+ vault,+ "--approach",+ "Polling the dashboard every second",+ "--reason",+ "Rate limits made the queue collapse",+ "--context",+ "kanban wrapper rework",+ "--json",+ ]);+ expect(rec.returncode).toBe(0);+ const body = JSON.parse(rec.stdout) as { ok: boolean; id: string };+ expect(body.ok).toBe(true);+ expect(body.id).toContain("polling-the-dashboard");+ expect(listDeadEnds(vault).entries).toHaveLength(1);++ const list = await runCli(["brain", "dead-end", "list", "--vault", vault, "--json"]);+ expect(list.returncode).toBe(0);+ const listed = JSON.parse(list.stdout) as {+ entries: Array<{ approach: string; reason: string; context: string | null }>;+ };+ expect(listed.entries[0]!.approach).toBe("Polling the dashboard every second");+ expect(listed.entries[0]!.reason).toContain("Rate limits");+ expect(listed.entries[0]!.context).toBe("kanban wrapper rework");+});++test("record without required flags exits 2", async () => {+ const res = await runCli(["brain", "dead-end", "record", "--vault", vault, "--approach", "x"]);+ expect(res.returncode).toBe(2);+});++test("unknown op exits 2", async () => {+ const res = await runCli(["brain", "dead-end", "bogus", "--vault", vault]);+ expect(res.returncode).toBe(2);+});diff --git a/tests/cli/brain-foresight.test.ts b/tests/cli/brain-foresight.test.tsnew file mode 100644index 00000000..86e89a6e--- /dev/null+++ b/tests/cli/brain-foresight.test.ts@@ -0,0 +1,58 @@+/**+ * `o2b brain foresight` CLI surface (t_08a79c81).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { applyRecurrenceEvidence } from "../../src/core/brain/recurrence.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-foresight-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("foresight renders an empty envelope on a fresh vault", async () => {+ const res = await runCli(["brain", "foresight", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { version: number; upcoming: unknown[] };+ expect(body.version).toBe(1);+ expect(body.upcoming).toEqual([]);+});++test("foresight projects a routine and --write persists the note", async () => {+ const base = Date.now() - 21 * 24 * 3600 * 1000;+ for (let i = 0; i < 3; i++) {+ applyRecurrenceEvidence(vault, {+ contentHash: "routine1",+ scope: "weekly-review",+ sourceId: `s-${i}`,+ action: "learn",+ at: new Date(base + i * 7 * 24 * 3600 * 1000).toISOString(),+ });+ }+ const res = await runCli(["brain", "foresight", "--vault", vault, "--write", "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as {+ upcoming: Array<{ kind: string; due: string | null }>;+ written_path: string;+ };+ expect(body.upcoming.some((u) => u.kind === "recurring")).toBe(true);+ expect(existsSync(body.written_path)).toBe(true);+});++test("invalid horizon exits 2", async () => {+ const res = await runCli(["brain", "foresight", "--vault", vault, "--horizon-days", "zero"]);+ expect(res.returncode).toBe(2);+});diff --git a/tests/cli/brain-truth.test.ts b/tests/cli/brain-truth.test.tsnew file mode 100644index 00000000..36975f39--- /dev/null+++ b/tests/cli/brain-truth.test.ts@@ -0,0 +1,243 @@+/**+ * `o2b brain truth` and `o2b brain facts` CLI surfaces (Entity Truth &+ * Self-Improving Dream Suite): ledger ingest, slots, conflicts,+ * aggregate, collisions, sweep, and deterministic atomic-fact+ * decomposition with optional ledger ingest.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendClaimEvent, readClaimEvents } from "../../src/core/brain/truth/store.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-truth-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function seedConflict(): void {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/standup.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-10T10:00:00Z",+ agent: "sales-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Meta",+ source: "[[Brain/notes/intro-call.md]]",+ });+}++test("truth ingest appends one claim and reports the slot", async () => {+ const res = await runCli([+ "brain",+ "truth",+ "ingest",+ "--vault",+ vault,+ "--entity",+ "Alice Mason",+ "--aspect",+ "employer",+ "--value",+ "Google",+ "--source",+ "[[Brain/notes/standup.md]]",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { ok: boolean; entity: string; aspect: string };+ expect(body.ok).toBe(true);+ expect(body.entity).toBe("alice mason");+ expect(readClaimEvents(vault).events).toHaveLength(1);+});++test("truth slots renders current values with history", async () => {+ seedConflict();+ const res = await runCli(["brain", "truth", "slots", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as {+ slots: Array<{ entity: string; current: { value: string }; history: unknown[] }>;+ };+ expect(body.slots).toHaveLength(1);+ expect(body.slots[0]!.current.value).toBe("Meta");+ expect(body.slots[0]!.history).toHaveLength(1);+});++test("truth conflicts lists contested slots with ask_user resolution", async () => {+ seedConflict();+ const res = await runCli(["brain", "truth", "conflicts", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as {+ conflicts: Array<{ entity: string; resolution: string }>;+ };+ expect(body.conflicts).toHaveLength(1);+ expect(body.conflicts[0]!.resolution).toBe("ask_user");+});++test("truth aggregate sums exact-match quantities only", async () => {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "operator",+ aspect: "hosting spend",+ value: "120",+ valueKind: "quantity",+ quantity: { value: 120, unit: "usd", action: "spent" },+ source: "[[Brain/notes/a.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "operator",+ aspect: "domain spend",+ value: "42",+ valueKind: "quantity",+ quantity: { value: 42, unit: "usd", action: "spent" },+ source: "[[Brain/notes/b.md]]",+ });+ const res = await runCli([+ "brain",+ "truth",+ "aggregate",+ "--vault",+ vault,+ "--action",+ "spent",+ "--unit",+ "usd",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { total: number; count: number };+ expect(body.total).toBe(162);+ expect(body.count).toBe(2);+});++test("truth collisions reports cross-agent convergence", async () => {+ appendClaimEvent(vault, {+ ts: new Date(Date.now() - 24 * 3600 * 1000).toISOString().replace(/\.\d+Z$/, "Z"),+ agent: "claude-dev-agent",+ entity: "Project Atlas",+ aspect: "pricing page",+ value: "confusing",+ source: "[[Brain/notes/support.md]]",+ });+ appendClaimEvent(vault, {+ ts: new Date().toISOString().replace(/\.\d+Z$/, "Z"),+ agent: "sales-agent",+ entity: "Project Atlas",+ aspect: "pricing deal",+ value: "stalled",+ source: "[[Brain/notes/deal.md]]",+ });+ const res = await runCli(["brain", "truth", "collisions", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { collisions: Array<{ entity: string }> };+ expect(body.collisions).toHaveLength(1);+ expect(body.collisions[0]!.entity).toBe("project atlas");+});++test("truth sweep bounds the ledger", async () => {+ seedConflict();+ const res = await runCli([+ "brain",+ "truth",+ "sweep",+ "--vault",+ vault,+ "--max-events",+ "1",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { removed: number; kept: number };+ expect(body.removed).toBe(1);+ expect(body.kept).toBe(1);+});++test("truth with an unknown op exits 2", async () => {+ const res = await runCli(["brain", "truth", "bogus", "--vault", vault]);+ expect(res.returncode).toBe(2);+});++test("facts decompose splits a file into assertions", async () => {+ const file = join(tmp, "session.md");+ writeFileSync(+ file,+ "# Standup\n\n- Alice approves the deploy window tomorrow\n\nThe rollback plan stays unchanged. Nothing else moved.\n",+ );+ const res = await runCli([+ "brain",+ "facts",+ "decompose",+ "--vault",+ vault,+ "--file",+ file,+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { assertions: Array<{ text: string; kind: string }> };+ expect(body.assertions).toHaveLength(3);+ expect(body.assertions[0]!.kind).toBe("list_item");+});++test("facts decompose --ingest writes entity-aspect-shaped claims to the ledger", async () => {+ const file = join(tmp, "session.md");+ writeFileSync(file, "I spent 120 USD on hosting last month.\n");+ const res = await runCli([+ "brain",+ "facts",+ "decompose",+ "--vault",+ vault,+ "--file",+ file,+ "--ingest",+ "--entity",+ "operator",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { ingested: number };+ expect(body.ingested).toBe(1);+ const events = readClaimEvents(vault).events;+ expect(events).toHaveLength(1);+ expect(events[0]!.valueKind).toBe("quantity");+ expect(events[0]!.quantity?.value).toBe(120);+});++test("facts decompose without --ingest leaves the ledger untouched", async () => {+ const file = join(tmp, "session.md");+ writeFileSync(file, "I spent 120 USD on hosting last month.\n");+ const res = await runCli([+ "brain",+ "facts",+ "decompose",+ "--vault",+ vault,+ "--file",+ file,+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ expect(readClaimEvents(vault).events).toHaveLength(0);+});diff --git a/tests/core/brain/atomic-facts.test.ts b/tests/core/brain/atomic-facts.test.tsnew file mode 100644index 00000000..171fc994--- /dev/null+++ b/tests/core/brain/atomic-facts.test.ts@@ -0,0 +1,142 @@+/**+ * Atomic-fact decomposition (t_cbd22536): deterministic, LLM-free+ * splitting of session/turn text into discrete single-sentence+ * assertions using markdown structure (heading context, list items,+ * sentence boundaries with an abbreviation guard), anchored to+ * canonical entities. Precision discipline mirrors fact-extract:+ * code, quotes, and frontmatter never produce assertions.+ */++import { describe, expect, test } from "bun:test";++import {+ decomposeAtomicFacts,+ MAX_ASSERTION_CHARS,+ type AtomicEntityLike,+} from "../../../src/core/brain/atomic-facts.ts";++const ENTITIES: ReadonlyArray<AtomicEntityLike> = [+ { id: "ent-people-alice-mason", name: "Alice Mason", aliases: ["Alice"], status: "active" },+ { id: "ent-project-atlas", name: "Atlas", aliases: [], status: "active" },+];++describe("decomposeAtomicFacts", () => {+ test("empty and whitespace input decompose to nothing", () => {+ expect(decomposeAtomicFacts("")).toEqual([]);+ expect(decomposeAtomicFacts(" \n\n ")).toEqual([]);+ });++ test("list items become individual assertions under their heading path", () => {+ const text = [+ "# Standup",+ "",+ "## Decisions",+ "",+ "- Alice Mason approves the deploy window for Atlas",+ "- The rollback plan stays unchanged for this release",+ ].join("\n");+ const out = decomposeAtomicFacts(text, { entities: ENTITIES });+ expect(out).toHaveLength(2);+ expect(out[0]!.text).toBe("Alice Mason approves the deploy window for Atlas");+ expect(out[0]!.headingPath).toEqual(["Standup", "Decisions"]);+ expect(out[0]!.kind).toBe("list_item");+ expect(out[0]!.entities).toEqual(["ent-people-alice-mason", "ent-project-atlas"]);+ expect(out[1]!.entities).toEqual([]);+ });++ test("prose paragraphs split into sentences", () => {+ const text =+ "The deploy window moved to Friday evening. Alice signed off on the change. " ++ "Nothing else in the runbook changed.";+ const out = decomposeAtomicFacts(text, { entities: ENTITIES });+ expect(out.map((a) => a.text)).toEqual([+ "The deploy window moved to Friday evening.",+ "Alice signed off on the change.",+ "Nothing else in the runbook changed.",+ ]);+ expect(out[1]!.entities).toEqual(["ent-people-alice-mason"]);+ expect(out[0]!.kind).toBe("sentence");+ });++ test("abbreviations and version numbers never split sentences", () => {+ const text =+ "The fix shipped in v0.42.0 e.g. the activation store now sweeps correctly. " ++ "Costs dropped to 3.5 USD per month.";+ const out = decomposeAtomicFacts(text);+ expect(out).toHaveLength(2);+ expect(out[0]!.text).toContain("e.g. the activation store");+ expect(out[1]!.text).toBe("Costs dropped to 3.5 USD per month.");+ });++ test("code blocks, inline code, quotes, and frontmatter are never assertions", () => {+ const text = [+ "---",+ "kind: note",+ "---",+ "",+ "> Quoted claim that must not extract.",+ "",+ "```",+ "Alice Mason inside a code fence.",+ "```",+ "",+ "Real statement about the `deploy` script behavior here.",+ ].join("\n");+ const out = decomposeAtomicFacts(text, { entities: ENTITIES });+ expect(out).toHaveLength(1);+ expect(out[0]!.text).toBe("Real statement about the script behavior here.");+ expect(out[0]!.entities).toEqual([]);+ });++ test("tiny fragments are dropped", () => {+ const out = decomposeAtomicFacts("Ok. Yes. The migration window opens on Monday morning.");+ expect(out).toHaveLength(1);+ expect(out[0]!.text).toBe("The migration window opens on Monday morning.");+ });++ test("line numbers point into the original input", () => {+ const text = [+ "# H",+ "",+ "First sentence lives here today.",+ "",+ "- A list item assertion",+ ].join("\n");+ const out = decomposeAtomicFacts(text);+ expect(out[0]!.line).toBe(3);+ expect(out[1]!.line).toBe(5);+ });++ test("assertions are capped in length", () => {+ const long = `The plan ${"very ".repeat(120)}long sentence about the rollout.`;+ const out = decomposeAtomicFacts(long);+ expect(out[0]!.text.length).toBeLessThanOrEqual(MAX_ASSERTION_CHARS);+ });++ test("deterministic: same input, deeply equal output", () => {+ const text = "# T\n\n- Alpha decided beta yesterday evening\n\nGamma follows delta now.";+ expect(decomposeAtomicFacts(text, { entities: ENTITIES })).toEqual(+ decomposeAtomicFacts(text, { entities: ENTITIES }),+ );+ });++ test("heading path resets correctly across sibling sections", () => {+ const text = [+ "# Root",+ "## A",+ "Statement under section A goes here.",+ "## B",+ "Statement under section B goes here.",+ ].join("\n");+ const out = decomposeAtomicFacts(text);+ expect(out[0]!.headingPath).toEqual(["Root", "A"]);+ expect(out[1]!.headingPath).toEqual(["Root", "B"]);+ });++ test("archived entities never anchor", () => {+ const out = decomposeAtomicFacts("Alice Mason approved the change for the team.", {+ entities: [{ ...ENTITIES[0]!, status: "archived" }],+ });+ expect(out[0]!.entities).toEqual([]);+ });+});diff --git a/tests/core/brain/dead-ends.test.ts b/tests/core/brain/dead-ends.test.tsnew file mode 100644index 00000000..24350489--- /dev/null+++ b/tests/core/brain/dead-ends.test.ts@@ -0,0 +1,150 @@+/**+ * Dead-end registry (t_be62c62d): negative knowledge as first-class+ * markdown notes under `Brain/dead-ends/` - what was tried, why it+ * failed, in what context - bounded to the most-recent-N with+ * archive-on-overflow. Markdown-first means FTS indexes the notes+ * with zero search changes, so recall surfaces "avoid X" alongside+ * "prefer Y".+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+ mkdirSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ DEAD_END_MAX_ACTIVE,+ deadEndsDir,+ listDeadEnds,+ recordDeadEnd,+} from "../../../src/core/brain/dead-ends.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig } from "../../helpers/search-fixtures.ts";++let vault: string;++const NOW = new Date("2026-06-04T12:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-dead-ends-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function record(approach: string, over: { reason?: string; context?: string; now?: Date } = {}) {+ return recordDeadEnd(vault, {+ approach,+ reason: over.reason ?? "It corrupted the index on concurrent writes",+ ...(over.context !== undefined ? { context: over.context } : {}),+ agent: "claude-dev-agent",+ now: over.now ?? NOW,+ });+}++describe("recordDeadEnd", () => {+ test("writes a markdown note with brain-dead-end frontmatter and sections", () => {+ const { entry } = record("Mutable global cache for the search index", {+ context: "v0.41 indexing rework",+ });+ expect(entry.id).toBe("de-2026-06-04-mutable-global-cache-for-the-search-index");+ const text = readFileSync(entry.path, "utf8");+ expect(text).toContain("kind: brain-dead-end");+ expect(text).toContain("agent: claude-dev-agent");+ expect(text).toContain("## Approach");+ expect(text).toContain("Mutable global cache for the search index");+ expect(text).toContain("## Why it failed");+ expect(text).toContain("corrupted the index");+ expect(text).toContain("## Context");+ expect(text).toContain("v0.41 indexing rework");+ });++ test("same approach on the same day allocates a collision suffix", () => {+ const first = record("Retry loop");+ const second = record("Retry loop");+ expect(first.entry.id).not.toBe(second.entry.id);+ expect(second.entry.id.endsWith("-2")).toBe(true);+ });++ test("empty approach or reason throws", () => {+ expect(() => record(" ")).toThrow();+ expect(() => record("Approach", { reason: " " })).toThrow();+ });++ test("overflow archives the oldest entries", () => {+ for (let i = 0; i < 4; i++) {+ record(`Approach number ${i}`, { now: new Date(`2026-06-0${i + 1}T10:00:00Z`) });+ }+ const result = recordDeadEnd(vault, {+ approach: "The newest approach",+ reason: "Still failed",+ agent: "claude-dev-agent",+ now: new Date("2026-06-05T10:00:00Z"),+ maxActive: 3,+ });+ expect(result.archived.length).toBe(2);+ const active = listDeadEnds(vault);+ expect(active.entries).toHaveLength(3);+ expect(existsSync(join(deadEndsDir(vault), "archive"))).toBe(true);+ const archived = readdirSync(join(deadEndsDir(vault), "archive"));+ expect(archived).toHaveLength(2);+ });++ test("default cap is generous", () => {+ expect(DEAD_END_MAX_ACTIVE).toBeGreaterThanOrEqual(100);+ });+});++describe("listDeadEnds", () => {+ test("returns active entries newest first with parsed fields", () => {+ record("Old approach", { now: new Date("2026-06-01T10:00:00Z") });+ record("New approach", { now: new Date("2026-06-03T10:00:00Z") });+ const { entries } = listDeadEnds(vault);+ expect(entries.map((e) => e.approach)).toEqual(["New approach", "Old approach"]);+ expect(entries[0]!.reason).toContain("corrupted");+ expect(entries[0]!.agent).toBe("claude-dev-agent");+ });++ test("malformed files are skipped fail-closed, never fatal", () => {+ record("Good approach");+ mkdirSync(deadEndsDir(vault), { recursive: true });+ writeFileSync(join(deadEndsDir(vault), "de-2026-06-04-junk.md"), "no frontmatter at all");+ const { entries, warnings } = listDeadEnds(vault);+ expect(entries).toHaveLength(1);+ expect(warnings).toHaveLength(1);+ });++ test("an empty vault lists nothing", () => {+ expect(listDeadEnds(vault).entries).toEqual([]);+ });+});++describe("recall integration", () => {+ test("dead-end notes index into FTS and surface on search", async () => {+ const tmp = createTempVault("dead-end-recall");+ try {+ recordDeadEnd(tmp.vault, {+ approach: "Sharding the quartz ledger by month",+ reason: "Quartz ledger shards desynchronized under Syncthing",+ agent: "claude-dev-agent",+ now: NOW,+ });+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath });+ await indexVault(config);+ const outcome = await search(config, { query: "quartz ledger shards" });+ expect(outcome.results.some((r) => r.path.startsWith("Brain/dead-ends/"))).toBe(true);+ } finally {+ tmp.cleanup();+ }+ });+});diff --git a/tests/core/brain/outcome-evidence.test.ts b/tests/core/brain/outcome-evidence.test.tsnew file mode 100644index 00000000..811ffe28--- /dev/null+++ b/tests/core/brain/outcome-evidence.test.ts@@ -0,0 +1,178 @@+/**+ * Outcome-tied apply-evidence (t_d478df53): an optional+ * success|failure|unknown outcome rides on apply-evidence events, and+ * the dream refresh stages an explainable regression finding with a+ * confidence penalty for preferences whose recent applied events+ * co-occur with failures - a rule that looks confirmed but is+ * actively hurting. Demotion is staged, never silent retirement;+ * absent outcomes keep every existing number byte-identical.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { dream, OUTCOME_REGRESSION_PENALTY } from "../../../src/core/brain/dream.ts";+import { collectEvidenceForSlug } from "../../../src/core/brain/evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";+import { preferencePath } from "../../../src/core/brain/paths.ts";+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;+let configPath: string;++const NOW = new Date("2026-06-04T20:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-outcome-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-outcome-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function seedPref(slug: string): void {+ writePreference(vault, {+ slug,+ topic: `topic-${slug}`,+ principle: `Rule for ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 0,+ violated_count: 0,+ last_evidence_at: null,+ confidence: BRAIN_CONFIDENCE.low,+ confidence_value: null,+ pinned: false,+ });+}++function evidence(slug: string, day: number, outcome?: "success" | "failure" | "unknown"): void {+ appendApplyEvidence(+ vault,+ {+ pref_id: `pref-${slug}`,+ artifact: `[[Brain/notes/work-${day}.md]]`,+ result: "applied",+ agent: "claude",+ ...(outcome !== undefined ? { outcome } : {}),+ },+ { now: new Date(`2026-06-0${day}T10:00:00Z`) },+ );+}++describe("appendApplyEvidence outcome field", () => {+ test("success and failure persist; unknown and absent do not", () => {+ seedPref("alpha");+ evidence("alpha", 1, "failure");+ evidence("alpha", 2, "success");+ evidence("alpha", 3, "unknown");+ evidence("alpha", 4);+ const days = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04"];+ const outcomes = days.map((d) => {+ const { entries } = readLogDay(vault, d);+ return entries.find((e) => e.eventType === "apply-evidence")?.body["outcome"];+ });+ expect(outcomes).toEqual(["failure", "success", undefined, undefined]);+ });++ test("an invalid outcome throws", () => {+ seedPref("beta");+ expect(() =>+ appendApplyEvidence(vault, {+ pref_id: "pref-beta",+ artifact: "[[x]]",+ result: "applied",+ agent: "claude",+ outcome: "exploded" as never,+ }),+ ).toThrow(/outcome/);+ });++ test("collectEvidenceForSlug surfaces the outcome on rows", () => {+ seedPref("gamma");+ evidence("gamma", 1, "failure");+ evidence("gamma", 2);+ const rows = collectEvidenceForSlug(vault, "gamma", { sinceIso: "" });+ expect(rows.applied.find((r) => r.outcome === "failure")).toBeDefined();+ expect(rows.applied.find((r) => r.outcome === undefined)).toBeDefined();+ });+});++describe("dream outcome regression", () => {+ test("repeated applied-with-failure stages a regression and penalizes confidence", () => {+ seedPref("hurting");+ seedPref("control");+ // Identical evidence cadence; only the outcomes differ.+ for (const day of [1, 2, 3]) {+ evidence("hurting", day, "failure");+ evidence("control", day);+ }+ const res = dream(vault, { now: NOW });+ expect(res.outcome_regressions).toHaveLength(1);+ const regression = res.outcome_regressions[0]!;+ expect(regression.id).toBe("pref-hurting");+ expect(regression.failures).toBe(3);+ expect(regression.successes).toBe(0);++ const hurting = parsePreference(preferencePath(vault, "hurting"));+ const control = parsePreference(preferencePath(vault, "control"));+ // Staged, never silently retired.+ expect(hurting.status).toBe(BRAIN_PREFERENCE_STATUS.confirmed);+ expect(hurting.confidence_value).not.toBeNull();+ expect(control.confidence_value).not.toBeNull();+ expect(hurting.confidence_value!).toBeCloseTo(+ control.confidence_value! * OUTCOME_REGRESSION_PENALTY,+ 4,+ );+ });++ test("successes outweighing failures stay un-flagged", () => {+ seedPref("mixed");+ evidence("mixed", 1, "failure");+ evidence("mixed", 2, "success");+ evidence("mixed", 3, "success");+ const res = dream(vault, { now: NOW });+ expect(res.outcome_regressions).toHaveLength(0);+ });++ test("a single failure never flags", () => {+ seedPref("once");+ evidence("once", 1, "failure");+ evidence("once", 2);+ const res = dream(vault, { now: NOW });+ expect(res.outcome_regressions).toHaveLength(0);+ });++ test("outcome-free vaults keep outcome_regressions empty and rerun as no-op", () => {+ seedPref("plain");+ evidence("plain", 1);+ const first = dream(vault, { now: NOW });+ expect(first.outcome_regressions).toEqual([]);+ const rerun = dream(vault, { now: NOW });+ expect(rerun.changed).toBe(false);+ expect(rerun.outcome_regressions).toEqual([]);+ });++ test("a regression run is idempotent on rerun", () => {+ seedPref("hurting");+ for (const day of [1, 2]) evidence("hurting", day, "failure");+ dream(vault, { now: NOW });+ const rerun = dream(vault, { now: NOW });+ expect(rerun.changed).toBe(false);+ });+});diff --git a/tests/core/brain/quantity-facts.test.ts b/tests/core/brain/quantity-facts.test.tsnew file mode 100644index 00000000..b3fe8def--- /dev/null+++ b/tests/core/brain/quantity-facts.test.ts@@ -0,0 +1,79 @@+/**+ * Quantitative fact family (t_220c313e): first-person framed numeric+ * facts (actor + measured action + value + unit) join the extraction+ * families, with a deterministic structurer that turns a captured+ * span into a typed quantity. Precision-first like every other+ * family: bare numbers without an actor frame never extract.+ */++import { describe, expect, test } from "bun:test";++import { extractFacts, parseQuantityFact } from "../../../src/core/brain/fact-extract.ts";++describe("extractFacts quantity family", () => {+ test("first-person spend extracts as a quantity fact", () => {+ const facts = extractFacts("I spent 120 USD on hosting last month.");+ const quantity = facts.filter((f) => f.family === "quantity");+ expect(quantity).toHaveLength(1);+ expect(quantity[0]!.text).toContain("spent 120 USD on hosting");+ });++ test("first-person counts and durations extract", () => {+ const ran = extractFacts("We ran 3 deployments this week.");+ expect(ran.some((f) => f.family === "quantity")).toBe(true);+ const worked = extractFacts("I worked 6.5 hours on the migration.");+ expect(worked.some((f) => f.family === "quantity")).toBe(true);+ });++ test("bare numbers without an actor frame never extract", () => {+ const facts = extractFacts("There are 3 ways to deploy. The build takes 12 minutes.");+ expect(facts.filter((f) => f.family === "quantity")).toHaveLength(0);+ });++ test("existing families keep extracting unchanged", () => {+ const facts = extractFacts("My name is Ada Lovelace. I prefer tabs over spaces.");+ expect(facts.some((f) => f.family === "identity")).toBe(true);+ expect(facts.some((f) => f.family === "preference")).toBe(true);+ });+});++describe("parseQuantityFact", () => {+ test("structures action, value, and unit", () => {+ expect(parseQuantityFact("I spent 120 USD on hosting")).toEqual({+ action: "spent",+ value: 120,+ unit: "usd",+ });+ expect(parseQuantityFact("We ran 3 deployments this week")).toEqual({+ action: "ran",+ value: 3,+ unit: "deployments",+ });+ expect(parseQuantityFact("I worked 6.5 hours on the migration")).toEqual({+ action: "worked",+ value: 6.5,+ unit: "hours",+ });+ });++ test("dollar sign normalizes to usd", () => {+ expect(parseQuantityFact("I paid $42 for the domain")).toEqual({+ action: "paid",+ value: 42,+ unit: "usd",+ });+ });++ test("stop-words after the number leave the unit null", () => {+ expect(parseQuantityFact("I paid 42 for the domain")).toEqual({+ action: "paid",+ value: 42,+ unit: null,+ });+ });++ test("non-quantity text parses to null", () => {+ expect(parseQuantityFact("I prefer tabs over spaces")).toBeNull();+ expect(parseQuantityFact("")).toBeNull();+ });+});diff --git a/tests/core/brain/review-candidates.test.ts b/tests/core/brain/review-candidates.test.tsindex df036521..3ebdb6a3 100644--- a/tests/core/brain/review-candidates.test.ts+++ b/tests/core/brain/review-candidates.test.ts@@ -30,8 +30,8 @@ afterEach(() => {});describe("buildReviewCandidates", () => {- test("returns a frozen report with all six top-level fields", () => {- const r = buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });+ test("returns a frozen report with all six top-level fields", async () => {+ const r = await buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });expect(Object.isFrozen(r)).toBe(true);expect(Array.isArray(r.would_create)).toBe(true);expect(Array.isArray(r.would_promote)).toBe(true);@@ -41,8 +41,8 @@ describe("buildReviewCandidates", () => {expect(Array.isArray(r.gated_retires)).toBe(true);});- test("returns empty arrays on a fresh-bootstrap vault", () => {- const r = buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });+ test("returns empty arrays on a fresh-bootstrap vault", async () => {+ const r = await buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });expect(r.would_create).toEqual([]);expect(r.would_promote).toEqual([]);expect(r.would_retire).toEqual([]);@@ -51,8 +51,8 @@ describe("buildReviewCandidates", () => {expect(r.gated_retires).toEqual([]);});- test("does NOT create a workrun file (dry-run path)", () => {- buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });+ test("does NOT create a workrun file (dry-run path)", async () => {+ await buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });const dir = dreamRunsDir(vault);if (existsSync(dir)) {const entries = readdirSync(dir);@@ -60,9 +60,9 @@ describe("buildReviewCandidates", () => {}});- test("invoked twice in a row produces identical output (idempotent)", () => {- const a = buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });- const b = buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });+ test("invoked twice in a row produces identical output (idempotent)", async () => {+ const a = await buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });+ const b = await buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });expect(JSON.stringify(a)).toBe(JSON.stringify(b));});});diff --git a/tests/core/brain/surprisal.test.ts b/tests/core/brain/surprisal.test.tsnew file mode 100644index 00000000..ceb1de48--- /dev/null+++ b/tests/core/brain/surprisal.test.ts@@ -0,0 +1,172 @@+/**+ * Surprisal-based novelty sampling (t_fddfe64a): inbox signals rank+ * by embedding-space distance to their nearest indexed neighbours+ * over the EXISTING sqlite-vec index - no provider calls. Without a+ * vec index novelty reads null and every consumer stays+ * byte-identical; the score never changes which signals get+ * processed, only how review surfaces order them.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++import { buildReviewCandidates } from "../../../src/core/brain/review-candidates.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { scoreSignalNovelty } from "../../../src/core/brain/surprisal.ts";+import { Store } from "../../../src/core/search/store.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import type {+ ResolvedEmbeddingConfig,+ ResolvedSearchConfig,+} from "../../../src/core/search/types.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;+let configHome: string;++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("surprisal"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-surprisal-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ cleanup();+ rmSync(configHome, { recursive: true, force: true });+});++function vecConfig(): ResolvedSearchConfig {+ const semantic: Partial<ResolvedEmbeddingConfig> = {+ enabled: true,+ baseUrl: "https://x/v1",+ model: "m1",+ apiKey: "k",+ dimension: 4,+ };+ return makeConfig({ vault, dbPath, semantic });+}++function unit(values: number[]): number[] {+ const norm = Math.hypot(...values);+ return values.map((v) => v / norm);+}++async function plantEmbeddings(+ config: ResolvedSearchConfig,+ byPath: Record<string, number[]>,+): Promise<void> {+ const store = await Store.open(config, { mode: "write" });+ try {+ for (const [path, vector] of Object.entries(byPath)) {+ const docId = store.getDocumentIdByPath(path);+ expect(docId).not.toBeNull();+ const chunks = store.chunksForDocument(docId!);+ expect(chunks.length).toBeGreaterThan(0);+ store.vecUpsert(chunks[0]!.id, vector, "m1", 4, `eh-${path}`);+ }+ } finally {+ await store.close();+ }+}++function seedSignal(slug: string, principle: string): { id: string; relPath: string } {+ const res = writeSignal(vault, {+ topic: slug,+ signal: "positive",+ agent: "claude",+ principle,+ created_at: "2026-06-01T10:00:00Z",+ date: "2026-06-01",+ slug,+ });+ return { id: res.id, relPath: `Brain/inbox/${res.id}.md` };+}++describe("scoreSignalNovelty", () => {+ test("an outlier signal scores higher novelty than one inside a cluster", async () => {+ if (!sqliteVecLoadable()) return;+ writeMd(vault, "Brain/notes/a.md", "# A\n\nCluster note alpha.\n");+ writeMd(vault, "Brain/notes/b.md", "# B\n\nCluster note bravo.\n");+ const near = seedSignal("near", "A rule close to the cluster");+ const far = seedSignal("far", "A rule about something entirely new");+ const config = vecConfig();+ await indexVault(config);+ await plantEmbeddings(config, {+ "Brain/notes/a.md": unit([1, 0, 0, 0]),+ "Brain/notes/b.md": unit([0.95, 0.05, 0, 0]),+ [near.relPath]: unit([0.9, 0.1, 0, 0]),+ [far.relPath]: unit([0, 0, 0, 1]),+ });++ const scored = await scoreSignalNovelty(config, [near, far]);+ const nearScore = scored.find((s) => s.id === near.id)!;+ const farScore = scored.find((s) => s.id === far.id)!;+ expect(nearScore.novelty).not.toBeNull();+ expect(farScore.novelty).not.toBeNull();+ expect(farScore.novelty!).toBeGreaterThan(nearScore.novelty!);+ });++ test("signals without an indexed embedding read null novelty", async () => {+ if (!sqliteVecLoadable()) return;+ const sig = seedSignal("plain", "A rule with no embedding");+ const config = vecConfig();+ await indexVault(config);+ const scored = await scoreSignalNovelty(config, [sig]);+ expect(scored[0]!.novelty).toBeNull();+ });++ test("a vault without a vec index degrades to all-null, never throws", async () => {+ const sig = seedSignal("no-vec", "A rule in a keyword-only vault");+ const config = makeConfig({ vault, dbPath });+ await indexVault(config);+ const scored = await scoreSignalNovelty(config, [sig]);+ expect(scored[0]!.novelty).toBeNull();+ });+});++describe("review-candidates novelty annotation", () => {+ test("signal_novelty appears only when at least one signal scores", async () => {+ if (!sqliteVecLoadable()) return;+ writeMd(vault, "Brain/notes/a.md", "# A\n\nCluster note alpha.\n");+ const sig = seedSignal("scored", "A scored signal rule");+ const config = vecConfig();+ await indexVault(config);+ await plantEmbeddings(config, {+ "Brain/notes/a.md": unit([1, 0, 0, 0]),+ [sig.relPath]: unit([0, 1, 0, 0]),+ });++ const report = await buildReviewCandidates(vault, {+ now: new Date("2026-06-02T10:00:00Z"),+ searchConfig: config,+ });+ expect(report.signal_novelty).toBeDefined();+ expect(report.signal_novelty![0]!.id).toBe(sig.id);+ expect(report.signal_novelty![0]!.novelty).not.toBeNull();+ });++ test("without embeddings the report stays byte-identical (no field)", async () => {+ seedSignal("unscored", "An unscored signal rule");+ const config = makeConfig({ vault, dbPath });+ await indexVault(config);+ const withConfig = await buildReviewCandidates(vault, {+ now: new Date("2026-06-02T10:00:00Z"),+ searchConfig: config,+ });+ const without = await buildReviewCandidates(vault, {+ now: new Date("2026-06-02T10:00:00Z"),+ });+ expect(withConfig.signal_novelty).toBeUndefined();+ expect(withConfig).toEqual(without);+ });+});diff --git a/tests/core/brain/temporal/foresight.test.ts b/tests/core/brain/temporal/foresight.test.tsnew file mode 100644index 00000000..df80b0b1--- /dev/null+++ b/tests/core/brain/temporal/foresight.test.ts@@ -0,0 +1,115 @@+/**+ * Foresight (t_08a79c81): the Brain's first forward-looking surface.+ * A deterministic fold over recurrence routines (cadence arithmetic+ * projects the next due date) and open commitments / open questions+ * from continuity records - no speculation, every item carries+ * sources, an empty vault folds to an empty envelope.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendContinuityRecord } from "../../../../src/core/brain/continuity/store.ts";+import { applyRecurrenceEvidence } from "../../../../src/core/brain/recurrence.ts";+import {+ buildForesight,+ FORESIGHT_MAX_ITEMS,+ FORESIGHT_SCHEMA_VERSION,+} from "../../../../src/core/brain/temporal/foresight.ts";++const NOW = new Date("2026-06-04T12:00:00Z");++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-foresight-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function seedRoutine(hash: string, dates: string[], scope = "weekly-review"): void {+ for (const [i, date] of dates.entries()) {+ applyRecurrenceEvidence(vault, {+ contentHash: hash,+ scope,+ sourceId: `session-${hash}-${i}`,+ action: "learn",+ at: `${date}T09:00:00Z`,+ });+ }+}++function seedExtract(type: string, text: string, createdAt: string): void {+ appendContinuityRecord(vault, {+ kind: "pre_compact_extract",+ createdAt,+ sourceRefs: [{ id: `sess-${text.slice(0, 8)}`, kind: "session" }],+ payload: { extract_type: type, text },+ });+}++describe("buildForesight", () => {+ test("an empty vault folds to an empty versioned envelope", () => {+ const envelope = buildForesight(vault, { now: NOW });+ expect(envelope.version).toBe(FORESIGHT_SCHEMA_VERSION);+ expect(envelope.upcoming).toEqual([]);+ expect(envelope.horizonDays).toBe(14);+ });++ test("a steady routine projects its next due date inside the horizon", () => {+ seedRoutine("abc123", ["2026-05-14", "2026-05-21", "2026-05-28"]);+ const envelope = buildForesight(vault, { now: NOW });+ const recurring = envelope.upcoming.filter((u) => u.kind === "recurring");+ expect(recurring).toHaveLength(1);+ const item = recurring[0]!;+ expect(item.due).toBe("2026-06-04");+ expect(item.title).toContain("weekly-review");+ expect(item.why).toContain("every ~7d");+ expect(item.sources.length).toBeGreaterThan(0);+ });++ test("a routine due beyond the horizon stays out", () => {+ seedRoutine("xyz789", ["2026-01-01", "2026-03-01", "2026-05-01"], "quarterly-report");+ const envelope = buildForesight(vault, { now: NOW, horizonDays: 14 });+ expect(envelope.upcoming.filter((u) => u.kind === "recurring")).toHaveLength(0);+ });++ test("a single-occurrence routine has no cadence and never projects", () => {+ seedRoutine("solo01", ["2026-06-01"]);+ const envelope = buildForesight(vault, { now: NOW });+ expect(envelope.upcoming.filter((u) => u.kind === "recurring")).toHaveLength(0);+ });++ test("recent open commitments and questions surface; stale ones do not", () => {+ seedExtract("commitment", "Ship the migration guide to the team", "2026-06-01T10:00:00Z");+ seedExtract(+ "open_question",+ "Should activation decay be configurable?",+ "2026-06-02T10:00:00Z",+ );+ seedExtract("commitment", "An ancient promise nobody remembers", "2026-01-01T10:00:00Z");+ seedExtract("decision", "Decisions are not forward-looking", "2026-06-02T10:00:00Z");+ const envelope = buildForesight(vault, { now: NOW });+ const kinds = envelope.upcoming.map((u) => u.kind);+ expect(kinds).toContain("commitment");+ expect(kinds).toContain("open_question");+ expect(envelope.upcoming.find((u) => u.title.includes("ancient"))).toBeUndefined();+ expect(envelope.upcoming.find((u) => u.title.includes("Decisions"))).toBeUndefined();+ const commitment = envelope.upcoming.find((u) => u.kind === "commitment")!;+ expect(commitment.sources.length).toBeGreaterThan(0);+ });++ test("items are bounded and deterministic", () => {+ for (let i = 0; i < FORESIGHT_MAX_ITEMS + 5; i++) {+ seedExtract("commitment", `Commitment number ${i} for the suite`, "2026-06-03T10:00:00Z");+ }+ const a = buildForesight(vault, { now: NOW });+ const b = buildForesight(vault, { now: NOW });+ expect(a.upcoming.length).toBeLessThanOrEqual(FORESIGHT_MAX_ITEMS);+ expect(a).toEqual(b);+ });+});diff --git a/tests/core/brain/temporal/top-source.test.ts b/tests/core/brain/temporal/top-source.test.tsnew file mode 100644index 00000000..2a88aff0--- /dev/null+++ b/tests/core/brain/temporal/top-source.test.ts@@ -0,0 +1,91 @@+/**+ * Weekly top-source (t_a8d49eae): the weekly synthesis nominates the+ * single most-developable note of the 7-day window - recency,+ * inbound links, and link centrality combined into one ranked+ * finding with a per-signal breakdown and a one-line why. Absent+ * when no candidate note was touched inside the window, so historic+ * envelopes stay byte-identical.+ */++import { beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { BRAIN_TEMPORAL_DEFAULTS } from "../../../../src/core/brain/policy.ts";+import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";+import { buildWeeklySynthesis } from "../../../../src/core/brain/temporal/weekly-brief.ts";++const WEEK_END = "2026-06-04";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-top-source-"));+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+});++function note(rel: string, content: string, mtime: string): string {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, content);+ const when = new Date(mtime);+ utimesSync(abs, when, when);+ return abs;+}++function synthesize() {+ return buildWeeklySynthesis(buildTimelineIndex(vault, {}), vault, WEEK_END, {+ ...BRAIN_TEMPORAL_DEFAULTS,+ });+}++describe("weekly topSource", () => {+ test("the linked, fresh note wins; breakdown and why are explainable", () => {+ note(+ "Brain/notes/hub.md",+ "# Hub\n\nThe restaking writeup everything points at.\n",+ "2026-06-02T10:00:00Z",+ );+ note(+ "Brain/notes/linker-a.md",+ "# A\n\nSee [[Brain/notes/hub.md|hub]] for the model.\n",+ "2026-06-01T10:00:00Z",+ );+ note(+ "Brain/notes/linker-b.md",+ "# B\n\nBuilds on [[Brain/notes/hub.md|hub]].\n",+ "2026-06-01T11:00:00Z",+ );+ const envelope = synthesize();+ expect(envelope.topSource).toBeDefined();+ const top = envelope.topSource!;+ expect(top.path).toBe("Brain/notes/hub.md");+ expect(top.signals.inboundLinks).toBe(2);+ expect(top.signals.recencyDays).toBeLessThanOrEqual(2);+ expect(top.score).toBeGreaterThan(0);+ expect(top.why).toContain("inbound");+ });++ test("absent when nothing was modified inside the window", () => {+ note("Brain/notes/old.md", "# Old\n\nAncient note.\n", "2026-01-01T10:00:00Z");+ const envelope = synthesize();+ expect(envelope.topSource).toBeUndefined();+ });++ test("machine-owned directories never nominate", () => {+ note("Brain/log/2026-06-02.md", "# Log\n\nMachine file.\n", "2026-06-02T10:00:00Z");+ note("Brain/inbox/sig-2026-06-02-x.md", "# Sig\n\nSignal.\n", "2026-06-02T10:00:00Z");+ const envelope = synthesize();+ expect(envelope.topSource).toBeUndefined();+ });++ test("deterministic across repeated builds", () => {+ note("Brain/notes/n1.md", "# N1\n\nFresh note one.\n", "2026-06-02T10:00:00Z");+ note("Brain/notes/n2.md", "# N2\n\nFresh note two.\n", "2026-06-03T10:00:00Z");+ const a = synthesize();+ const b = synthesize();+ expect(a.topSource).toEqual(b.topSource);+ });+});diff --git a/tests/core/brain/truth/aggregate.test.ts b/tests/core/brain/truth/aggregate.test.tsnew file mode 100644index 00000000..57af42fc--- /dev/null+++ b/tests/core/brain/truth/aggregate.test.ts@@ -0,0 +1,130 @@+/**+ * Exact-match quantity aggregation (t_220c313e): totals combine ONLY+ * values whose (entity, action, unit) tuple matches exactly after+ * canonical normalization - merely nearby numbers (different unit,+ * different action, text-kind slots) never pollute a total.+ */++import { describe, expect, test } from "bun:test";++import { aggregateQuantities } from "../../../../src/core/brain/truth/aggregate.ts";+import { computeTruthState } from "../../../../src/core/brain/truth/fold.ts";+import type { ClaimEvent, ClaimQuantity } from "../../../../src/core/brain/truth/types.ts";++function quantityClaim(+ aspect: string,+ quantity: ClaimQuantity,+ over: Partial<ClaimEvent> = {},+): ClaimEvent {+ return {+ v: 1,+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "operator",+ aspect,+ value: String(quantity.value),+ valueKind: "quantity",+ quantity,+ source: `[[Brain/notes/${aspect.replace(/\s+/g, "-")}.md]]`,+ ...over,+ };+}++const SLOTS = computeTruthState([+ quantityClaim("hosting spend may", { value: 120, unit: "usd", action: "spent" }),+ quantityClaim("domain spend may", { value: 42, unit: "usd", action: "spent" }),+ quantityClaim("hosting spend april", { value: 100, unit: "eur", action: "spent" }),+ quantityClaim("migration hours", { value: 6.5, unit: "hours", action: "worked" }),+ quantityClaim("deploy count", { value: 3, unit: "deployments", action: "ran" }),+ {+ v: 1,+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "operator",+ aspect: "favourite number",+ value: "7",+ valueKind: "text",+ source: "[[Brain/notes/text.md]]",+ },+]).slots;++describe("aggregateQuantities", () => {+ test("sums only exact (entity, action, unit) matches", () => {+ const result = aggregateQuantities(SLOTS, {+ entity: "operator",+ action: "spent",+ unit: "usd",+ });+ expect(result.total).toBe(162);+ expect(result.count).toBe(2);+ expect(result.contributions.map((c) => c.value)).toEqual([42, 120]);+ });++ test("different units never combine", () => {+ const eur = aggregateQuantities(SLOTS, { entity: "operator", action: "spent", unit: "eur" });+ expect(eur.total).toBe(100);+ expect(eur.count).toBe(1);+ });++ test("text-kind slots and other actions are excluded", () => {+ const worked = aggregateQuantities(SLOTS, {+ entity: "operator",+ action: "worked",+ unit: "hours",+ });+ expect(worked.total).toBe(6.5);+ expect(worked.count).toBe(1);+ });++ test("normalization makes the match case- and whitespace-insensitive", () => {+ const result = aggregateQuantities(SLOTS, {+ entity: " Operator ",+ action: "SPENT",+ unit: " USD ",+ });+ expect(result.total).toBe(162);+ });++ test("entity filter is optional (all entities combine when omitted)", () => {+ const withOther = computeTruthState([+ quantityClaim("hosting spend", { value: 10, unit: "usd", action: "spent" }),+ quantityClaim(+ "infra spend",+ { value: 5, unit: "usd", action: "spent" },+ { entity: "team atlas" },+ ),+ ]).slots;+ const result = aggregateQuantities(withOther, { action: "spent", unit: "usd" });+ expect(result.total).toBe(15);+ });++ test("null unit matches only null unit", () => {+ const unitless = computeTruthState([+ quantityClaim("misc paid", { value: 42, unit: null, action: "paid" }),+ quantityClaim("hosting paid", { value: 10, unit: "usd", action: "paid" }),+ ]).slots;+ const result = aggregateQuantities(unitless, { action: "paid", unit: null });+ expect(result.total).toBe(42);+ expect(result.count).toBe(1);+ });++ test("no matches aggregate to a zero envelope", () => {+ const result = aggregateQuantities(SLOTS, { action: "earned", unit: "usd" });+ expect(result.total).toBe(0);+ expect(result.count).toBe(0);+ expect(result.contributions).toEqual([]);+ });++ test("contributions carry provenance and sort deterministically", () => {+ const result = aggregateQuantities(SLOTS, {+ entity: "operator",+ action: "spent",+ unit: "usd",+ });+ expect(result.contributions[0]!.source).toBe("[[Brain/notes/domain-spend-may.md]]");+ expect(result.contributions.map((c) => c.aspect)).toEqual([+ "domain spend may",+ "hosting spend may",+ ]);+ });+});diff --git a/tests/core/brain/truth/collision.test.ts b/tests/core/brain/truth/collision.test.tsnew file mode 100644index 00000000..9479711c--- /dev/null+++ b/tests/core/brain/truth/collision.test.ts@@ -0,0 +1,199 @@+/**+ * Cross-agent collision detection (t_f2b225b1): when two agents+ * independently wrote claims about one entity within the recent+ * window - citing different sources, neither aware of the other -+ * the knowledge must not stay trapped where it was learned. Findings+ * surface push-mode through the standing trigger queue with cooldown+ * dedup, not through an operator-invoked diff.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ COLLISION_WINDOW_DAYS,+ collisionCandidates,+ detectAgentCollisions,+} from "../../../../src/core/brain/truth/collision.ts";+import { appendClaimEvent } from "../../../../src/core/brain/truth/store.ts";+import { listTriggers } from "../../../../src/core/brain/triggers/store.ts";+import { scanTriggers } from "../../../../src/core/brain/triggers/scan.ts";+import type { ClaimEvent } from "../../../../src/core/brain/truth/types.ts";++const NOW = new Date("2026-06-04T12:00:00Z");++function claim(over: Partial<ClaimEvent> = {}): ClaimEvent {+ return {+ v: 1,+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "project atlas",+ aspect: "pricing page",+ value: "customers find it confusing",+ valueKind: "text",+ source: "[[Brain/notes/support-call.md]]",+ ...over,+ };+}++describe("detectAgentCollisions (pure)", () => {+ test("two agents, distinct sources, one entity, recent window -> one finding", () => {+ const findings = detectAgentCollisions(+ [+ claim(),+ claim({+ ts: "2026-06-02T10:00:00Z",+ agent: "sales-agent",+ aspect: "pricing deal",+ value: "deal stalled over pricing",+ source: "[[Brain/notes/deal-review.md]]",+ }),+ ],+ { now: NOW },+ );+ expect(findings).toHaveLength(1);+ const f = findings[0]!;+ expect(f.entity).toBe("project atlas");+ expect(f.agents).toEqual(["claude-dev-agent", "sales-agent"]);+ expect(f.aspects).toEqual(["pricing deal", "pricing page"]);+ expect(f.claims).toBe(2);+ expect(f.detectedAt).toBe("2026-06-02T10:00:00Z");+ });++ test("a single agent never collides with itself", () => {+ const findings = detectAgentCollisions(+ [claim(), claim({ ts: "2026-06-02T10:00:00Z", aspect: "pricing deal" })],+ { now: NOW },+ );+ expect(findings).toHaveLength(0);+ });++ test("two agents citing the same source are not independent", () => {+ const findings = detectAgentCollisions(+ [claim(), claim({ ts: "2026-06-02T10:00:00Z", agent: "sales-agent" })],+ { now: NOW },+ );+ expect(findings).toHaveLength(0);+ });++ test("claims outside the window never participate", () => {+ const findings = detectAgentCollisions(+ [+ claim({ ts: "2026-01-01T10:00:00Z" }),+ claim({+ ts: "2026-06-02T10:00:00Z",+ agent: "sales-agent",+ source: "[[Brain/notes/deal-review.md]]",+ }),+ ],+ { now: NOW },+ );+ expect(findings).toHaveLength(0);+ expect(COLLISION_WINDOW_DAYS).toBe(14);+ });++ test("findings are bounded by the cap, most recent first", () => {+ const events: ClaimEvent[] = [];+ for (let i = 0; i < 30; i++) {+ const entity = `entity-${String(i).padStart(2, "0")}`;+ events.push(+ claim({ entity, ts: `2026-06-0${(i % 3) + 1}T10:00:00Z` }),+ claim({+ entity,+ ts: `2026-06-0${(i % 3) + 2}T10:00:00Z`,+ agent: "sales-agent",+ source: "[[Brain/notes/other.md]]",+ }),+ );+ }+ const findings = detectAgentCollisions(events, { now: NOW, cap: 5 });+ expect(findings).toHaveLength(5);+ });++ test("empty events detect nothing", () => {+ expect(detectAgentCollisions([], { now: NOW })).toEqual([]);+ });+});++describe("collisionCandidates", () => {+ test("findings become agent_collision trigger candidates with stable cooldown keys", () => {+ const findings = detectAgentCollisions(+ [+ claim(),+ claim({+ ts: "2026-06-02T10:00:00Z",+ agent: "sales-agent",+ source: "[[Brain/notes/deal-review.md]]",+ }),+ ],+ { now: NOW },+ );+ const candidates = collisionCandidates(findings);+ expect(candidates).toHaveLength(1);+ const c = candidates[0]!;+ expect(c.kind).toBe("agent_collision");+ expect(c.urgency).toBe("medium");+ expect(c.reason).toContain("claude-dev-agent");+ expect(c.reason).toContain("sales-agent");+ expect(c.reason).toContain("project atlas");+ expect(c.cooldownKey).toBe("agent_collision:project atlas:claude-dev-agent+sales-agent");+ expect(c.sourceArtifacts).toContain("[[Brain/notes/support-call.md]]");+ expect(c.sourceArtifacts).toContain("[[Brain/notes/deal-review.md]]");+ });+});++describe("scanTriggers push-mode wiring", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-collision-"));+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ test("a collision in the ledger lands as a pending trigger; cooldown blocks repeats", () => {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "Project Atlas",+ aspect: "pricing page",+ value: "customers find it confusing",+ source: "[[Brain/notes/support-call.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "sales-agent",+ entity: "Project Atlas",+ aspect: "pricing deal",+ value: "deal stalled over pricing",+ source: "[[Brain/notes/deal-review.md]]",+ });++ const first = scanTriggers(vault, { now: NOW });+ const collisions = listTriggers(vault, { now: NOW }).filter(+ (t) => t.kind === "agent_collision",+ );+ expect(collisions).toHaveLength(1);+ expect(first.created.length).toBeGreaterThanOrEqual(1);++ const second = scanTriggers(vault, { now: NOW });+ const after = listTriggers(vault, { now: NOW }).filter((t) => t.kind === "agent_collision");+ expect(after).toHaveLength(1);+ expect(+ second.skipped.some(+ (s) => s.cooldownKey.startsWith("agent_collision:") && s.reason === "active",+ ),+ ).toBe(true);+ });++ test("an empty ledger contributes no collision candidates", () => {+ scanTriggers(vault, { now: NOW });+ expect(listTriggers(vault, { now: NOW }).filter((t) => t.kind === "agent_collision")).toEqual(+ [],+ );+ });+});diff --git a/tests/core/brain/truth/conflicts.test.ts b/tests/core/brain/truth/conflicts.test.tsnew file mode 100644index 00000000..486f4613--- /dev/null+++ b/tests/core/brain/truth/conflicts.test.ts@@ -0,0 +1,124 @@+/**+ * Conflict detection over the truth fold (t_e9692750): two distinct+ * values for one slot within the conflict window from independent+ * sources materialize a typed conflict with `resolution: ask_user`;+ * a later value outside the window supersedes silently (normal fact+ * evolution). Purely temporal-structural - no semantics guessing.+ */++import { describe, expect, test } from "bun:test";++import {+ computeTruthStateWithConflicts,+ CONFLICT_WINDOW_DAYS,+} from "../../../../src/core/brain/truth/conflicts.ts";+import { computeTruthState } from "../../../../src/core/brain/truth/fold.ts";+import type { ClaimEvent } from "../../../../src/core/brain/truth/types.ts";++function claim(over: Partial<ClaimEvent> = {}): ClaimEvent {+ return {+ v: 1,+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "alice mason",+ aspect: "employer",+ value: "Google",+ valueKind: "text",+ source: "[[Brain/notes/standup.md]]",+ ...over,+ };+}++describe("computeTruthStateWithConflicts", () => {+ test("default window is 30 days", () => {+ expect(CONFLICT_WINDOW_DAYS).toBe(30);+ });++ test("two values within the window from distinct sources conflict", () => {+ const state = computeTruthStateWithConflicts([+ claim(),+ claim({ ts: "2026-06-10T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" }),+ ]);+ expect(state.conflicts).toHaveLength(1);+ const conflict = state.conflicts[0]!;+ expect(conflict.entity).toBe("alice mason");+ expect(conflict.aspect).toBe("employer");+ expect(conflict.kind).toBe("value_conflict");+ expect(conflict.resolution).toBe("ask_user");+ expect(conflict.detectedAt).toBe("2026-06-10T10:00:00Z");+ expect(conflict.values.map((v) => v.value)).toEqual(["Google", "Meta"]);+ expect(state.slots[0]!.contested).toBe(true);+ });++ test("a later value outside the window supersedes silently", () => {+ const state = computeTruthStateWithConflicts([+ claim({ ts: "2026-01-01T10:00:00Z" }),+ claim({ ts: "2026-06-01T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" }),+ ]);+ expect(state.conflicts).toHaveLength(0);+ expect(state.slots[0]!.contested).toBe(false);+ expect(state.slots[0]!.current.value).toBe("Meta");+ expect(state.slots[0]!.history.map((v) => v.value)).toEqual(["Google"]);+ });++ test("the same source changing its value is self-correction, not conflict", () => {+ const state = computeTruthStateWithConflicts([+ claim(),+ claim({ ts: "2026-06-10T10:00:00Z", value: "Meta" }),+ ]);+ expect(state.conflicts).toHaveLength(0);+ expect(state.slots[0]!.contested).toBe(false);+ });++ test("three contesting values raise the priority", () => {+ const base = computeTruthStateWithConflicts([+ claim(),+ claim({ ts: "2026-06-05T10:00:00Z", value: "Meta", source: "[[Brain/notes/b.md]]" }),+ ]);+ const more = computeTruthStateWithConflicts([+ claim(),+ claim({ ts: "2026-06-05T10:00:00Z", value: "Meta", source: "[[Brain/notes/b.md]]" }),+ claim({ ts: "2026-06-10T10:00:00Z", value: "Anthropic", source: "[[Brain/notes/c.md]]" }),+ ]);+ expect(more.conflicts[0]!.priority).toBeGreaterThan(base.conflicts[0]!.priority);+ expect(more.conflicts[0]!.values.map((v) => v.value)).toEqual(["Google", "Meta", "Anthropic"]);+ });++ test("custom window widens or narrows detection", () => {+ const events = [+ claim({ ts: "2026-01-01T10:00:00Z" }),+ claim({ ts: "2026-03-01T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" }),+ ];+ expect(computeTruthStateWithConflicts(events).conflicts).toHaveLength(0);+ expect(computeTruthStateWithConflicts(events, { windowDays: 90 }).conflicts).toHaveLength(1);+ });++ test("without conflicts the state matches the base fold exactly", () => {+ const events = [+ claim(),+ claim({ ts: "2026-08-01T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" }),+ claim({ entity: "bob hale", value: "Acme", source: "[[Brain/notes/bob.md]]" }),+ ];+ expect(computeTruthStateWithConflicts(events)).toEqual(computeTruthState(events));+ });++ test("conflicts sort deterministically by entity then aspect", () => {+ const state = computeTruthStateWithConflicts([+ claim({ entity: "zoe", aspect: "role", value: "dev" }),+ claim({+ entity: "zoe",+ aspect: "role",+ ts: "2026-06-02T10:00:00Z",+ value: "ops",+ source: "[[Brain/notes/z.md]]",+ }),+ claim(),+ claim({ ts: "2026-06-02T10:00:00Z", value: "Meta", source: "[[Brain/notes/b.md]]" }),+ ]);+ expect(state.conflicts.map((c) => c.entity)).toEqual(["alice mason", "zoe"]);+ });++ test("empty events fold to the empty state (bit-identical neutral default)", () => {+ expect(computeTruthStateWithConflicts([])).toEqual(computeTruthState([]));+ });+});diff --git a/tests/core/brain/truth/contamination.test.ts b/tests/core/brain/truth/contamination.test.tsnew file mode 100644index 00000000..678a1305--- /dev/null+++ b/tests/core/brain/truth/contamination.test.ts@@ -0,0 +1,121 @@+/**+ * Entity-contamination check (t_e9692750): a synthesized conclusion+ * must not mention registered entities that appear in none of its+ * cited sources. Pure function over the canonical entity index plus+ * deep-synthesis wiring (matched notes with wikilink citations are+ * checked against the notes they cite).+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";++import { upsertEntity } from "../../../../src/core/brain/entities/registry.ts";+import { deepSynthesis } from "../../../../src/core/brain/deep-synthesis.ts";+import {+ checkEntityContamination,+ type ContaminationEntityLike,+} from "../../../../src/core/brain/truth/contamination.ts";+import { indexVault } from "../../../../src/core/search/indexer.ts";+import { createTempVault, makeConfig, writeMd } from "../../../helpers/search-fixtures.ts";++function person(id: string, name: string, aliases: string[] = []): ContaminationEntityLike {+ return { id, name, aliases, status: "active" };+}++describe("checkEntityContamination (pure)", () => {+ const alice = person("ent-people-alice-mason", "Alice Mason", ["Alice"]);+ const bob = person("ent-people-bob-hale", "Bob Hale");++ test("an entity in the conclusion but in no source is a violation", () => {+ const result = checkEntityContamination({+ conclusion: "Alice Mason and Bob Hale both approved the rollout",+ sources: ["Alice Mason approved the rollout yesterday"],+ entities: [alice, bob],+ });+ expect(result.clean).toBe(false);+ expect(result.violations).toHaveLength(1);+ expect(result.violations[0]!.entityId).toBe("ent-people-bob-hale");+ expect(result.violations[0]!.name).toBe("Bob Hale");+ });++ test("alias mentions in a source clear the entity", () => {+ const result = checkEntityContamination({+ conclusion: "Alice Mason approved the rollout",+ sources: ["Alice signed off this morning"],+ entities: [alice],+ });+ expect(result.clean).toBe(true);+ expect(result.violations).toHaveLength(0);+ });++ test("unregistered names are never violations", () => {+ const result = checkEntityContamination({+ conclusion: "Zaphod approved the rollout",+ sources: ["Nothing relevant"],+ entities: [alice],+ });+ expect(result.clean).toBe(true);+ });++ test("empty entity registry is always clean", () => {+ const result = checkEntityContamination({+ conclusion: "Alice Mason approved the rollout",+ sources: [],+ entities: [],+ });+ expect(result.clean).toBe(true);+ });++ test("archived entities are ignored", () => {+ const result = checkEntityContamination({+ conclusion: "Bob Hale approved the rollout",+ sources: ["No people here"],+ entities: [{ ...bob, status: "archived" }],+ });+ expect(result.clean).toBe(true);+ });+});++describe("deepSynthesis wiring", () => {+ let vault: string;+ let dbPath: string;+ let cleanup: () => void;++ beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("contamination"));+ });++ afterEach(() => {+ cleanup();+ });++ test("a matched note citing sources that never mention its entities is flagged", async () => {+ const now = new Date("2026-06-01T10:00:00Z");+ upsertEntity(vault, { category: "people", name: "Bob Hale", agent: "tester", now });+ writeMd(+ vault,+ "Brain/notes/conclusion.md",+ "# Conclusion\n\nRollout policy synthesis: Bob Hale approved the canary rollout.\n\n" ++ "[[Brain/notes/source-a.md|source]]\n",+ );+ writeMd(vault, "Brain/notes/source-a.md", "# Source A\n\nThe canary rollout was approved.\n");+ const config = makeConfig({ vault, dbPath });+ await indexVault(config);++ const report = await deepSynthesis(config, "canary rollout", { now });+ expect(report.checked).toContain("entity_contamination");+ expect(report.contaminated.length).toBeGreaterThanOrEqual(1);+ const finding = report.contaminated.find((c) => c.path === "Brain/notes/conclusion.md")!;+ expect(finding.entity).toBe("ent-people-bob-hale");+ expect(finding.sources).toContain("Brain/notes/source-a.md");+ });++ test("with no entity registry the report is byte-identical to today", async () => {+ const now = new Date("2026-06-01T10:00:00Z");+ writeMd(vault, "Brain/notes/plain.md", "# Plain\n\nCanary rollout notes.\n");+ const config = makeConfig({ vault, dbPath });+ await indexVault(config);+ const report = await deepSynthesis(config, "canary rollout", { now });+ expect(report.checked).not.toContain("entity_contamination");+ expect(report.contaminated).toEqual([]);+ });+});diff --git a/tests/core/brain/truth/fold.test.ts b/tests/core/brain/truth/fold.test.tsnew file mode 100644index 00000000..153847fa--- /dev/null+++ b/tests/core/brain/truth/fold.test.ts@@ -0,0 +1,128 @@+/**+ * Truth fold (Entity Truth & Self-Improving Dream Suite, t_d6849b56):+ * claim events project into per-(entity, aspect) slots holding the+ * current value plus superseded history with provenance lineage. The+ * fold is deterministic and order-insensitive; an empty event stream+ * folds to an empty state (bit-identical neutral default).+ */++import { describe, expect, test } from "bun:test";++import { computeTruthState, SLOT_HISTORY_CAP } from "../../../../src/core/brain/truth/fold.ts";+import type { ClaimEvent } from "../../../../src/core/brain/truth/types.ts";++function claim(over: Partial<ClaimEvent> = {}): ClaimEvent {+ return {+ v: 1,+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "alice mason",+ aspect: "employer",+ value: "Google",+ valueKind: "text",+ source: "[[Brain/notes/standup.md]]",+ ...over,+ };+}++describe("computeTruthState", () => {+ test("empty events fold to the empty state", () => {+ const state = computeTruthState([]);+ expect(state.version).toBe(1);+ expect(state.events).toBe(0);+ expect(state.updatedAt).toBeNull();+ expect(state.slots).toEqual([]);+ expect(state.conflicts).toEqual([]);+ });++ test("one slot per (entity, aspect); current is the latest value with history preserved", () => {+ const state = computeTruthState([+ claim(),+ claim({ ts: "2026-06-03T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" }),+ claim({ entity: "bob hale", value: "Acme", source: "[[Brain/notes/bob.md]]" }),+ ]);+ expect(state.slots).toHaveLength(2);+ const alice = state.slots.find((s) => s.entity === "alice mason")!;+ expect(alice.aspect).toBe("employer");+ expect(alice.current.value).toBe("Meta");+ expect(alice.current.source).toBe("[[Brain/notes/later.md]]");+ expect(alice.history).toHaveLength(1);+ expect(alice.history[0]!.value).toBe("Google");+ expect(alice.history[0]!.source).toBe("[[Brain/notes/standup.md]]");+ });++ test("the fold is order-insensitive", () => {+ const events = [+ claim(),+ claim({ ts: "2026-06-03T10:00:00Z", value: "Meta" }),+ claim({ ts: "2026-06-02T10:00:00Z", value: "Anthropic", agent: "other-agent" }),+ ];+ const forward = computeTruthState(events);+ const reversed = computeTruthState(events.toReversed());+ expect(reversed).toEqual(forward);+ });++ test("re-asserting the identical value refreshes the current version, not history", () => {+ const state = computeTruthState([+ claim(),+ claim({ ts: "2026-06-05T10:00:00Z", value: "Google", source: "[[Brain/notes/again.md]]" }),+ ]);+ const slot = state.slots[0]!;+ expect(slot.current.value).toBe("Google");+ expect(slot.current.ts).toBe("2026-06-05T10:00:00Z");+ expect(slot.history).toHaveLength(0);+ expect(slot.current.assertCount).toBe(2);+ });++ test("value identity is normalized (case and whitespace insensitive)", () => {+ const state = computeTruthState([+ claim(),+ claim({ ts: "2026-06-05T10:00:00Z", value: " google " }),+ ]);+ expect(state.slots[0]!.history).toHaveLength(0);+ });++ test("history is bounded to the cap, newest first", () => {+ const events: ClaimEvent[] = [];+ for (let i = 0; i < SLOT_HISTORY_CAP + 5; i++) {+ events.push(+ claim({+ ts: `2026-05-${String((i % 28) + 1).padStart(2, "0")}T0${i % 10}:0${i % 6}:00Z`,+ value: `employer-${i}`,+ }),+ );+ }+ const slot = computeTruthState(events).slots[0]!;+ expect(slot.history.length).toBeLessThanOrEqual(SLOT_HISTORY_CAP);+ });++ test("slots sort deterministically by entity then aspect", () => {+ const state = computeTruthState([+ claim({ entity: "zoe", aspect: "role" }),+ claim({ entity: "alice mason", aspect: "location", value: "Berlin" }),+ claim({ entity: "alice mason", aspect: "employer" }),+ ]);+ expect(state.slots.map((s) => `${s.entity}/${s.aspect}`)).toEqual([+ "alice mason/employer",+ "alice mason/location",+ "zoe/role",+ ]);+ });++ test("quantity versions carry the quantity payload through the fold", () => {+ const state = computeTruthState([+ claim({+ aspect: "spent total",+ value: "120",+ valueKind: "quantity",+ quantity: { value: 120, unit: "usd", action: "spent" },+ }),+ ]);+ expect(state.slots[0]!.current.quantity).toEqual({ value: 120, unit: "usd", action: "spent" });+ });++ test("updatedAt is the max event ts", () => {+ const state = computeTruthState([claim({ ts: "2026-06-03T10:00:00Z" }), claim()]);+ expect(state.updatedAt).toBe("2026-06-03T10:00:00Z");+ });+});diff --git a/tests/core/brain/truth/merge-guard.test.ts b/tests/core/brain/truth/merge-guard.test.tsnew file mode 100644index 00000000..6b86b153--- /dev/null+++ b/tests/core/brain/truth/merge-guard.test.ts@@ -0,0 +1,186 @@+/**+ * Name-aware merge guard (t_e9692750): refuse merging two notes whose+ * person/org entity anchors are disjoint non-empty sets - "Alice+ * decided X" must never collapse into "Bob decided X". Notes with no+ * guarded anchors or overlapping anchors merge exactly as today.+ */++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 { upsertEntity } from "../../../../src/core/brain/entities/registry.ts";+import { BrainMergeError, mergePreferences } from "../../../../src/core/brain/merge.ts";+import {+ writePreference,+ type WritePreferenceInput,+} from "../../../../src/core/brain/preference.ts";+import {+ GUARDED_ENTITY_CATEGORIES,+ guardEntityMerge,+ type GuardEntityLike,+} from "../../../../src/core/brain/truth/merge-guard.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../../src/core/brain/types.ts";++const NOW = new Date("2026-06-01T10:00:00Z");++function person(id: string, name: string, aliases: string[] = []): GuardEntityLike {+ return { id, category: "people", name, aliases, status: "active" };+}++describe("guardEntityMerge (pure)", () => {+ const alice = person("ent-people-alice-mason", "Alice Mason", ["Alice"]);+ const bob = person("ent-people-bob-hale", "Bob Hale", ["Bob"]);++ test("disjoint person anchors block with an explainable reason", () => {+ const verdict = guardEntityMerge({+ keepText: "Alice Mason decided to ship on Friday",+ dropText: "Bob Hale decided to ship on Friday",+ entities: [alice, bob],+ });+ expect(verdict.allowed).toBe(false);+ expect(verdict.reason).toContain("ent-people-alice-mason");+ expect(verdict.reason).toContain("ent-people-bob-hale");+ expect(verdict.keepAnchors).toEqual(["ent-people-alice-mason"]);+ expect(verdict.dropAnchors).toEqual(["ent-people-bob-hale"]);+ });++ test("overlapping anchors are allowed", () => {+ const verdict = guardEntityMerge({+ keepText: "Alice and Bob agreed on the deploy window",+ dropText: "Bob Hale confirmed the deploy window",+ entities: [alice, bob],+ });+ expect(verdict.allowed).toBe(true);+ expect(verdict.reason).toBeNull();+ });++ test("notes with no guarded anchors are allowed", () => {+ const verdict = guardEntityMerge({+ keepText: "Use spaces over tabs",+ dropText: "Spaces are preferred over tabs",+ entities: [alice, bob],+ });+ expect(verdict.allowed).toBe(true);+ });++ test("alias mentions anchor like canonical names", () => {+ const verdict = guardEntityMerge({+ keepText: "Alice prefers staged rollouts",+ dropText: "Bob prefers staged rollouts",+ entities: [alice, bob],+ });+ expect(verdict.allowed).toBe(false);+ });++ test("non-guarded categories never block by default but can opt in", () => {+ const projectA: GuardEntityLike = {+ id: "ent-project-atlas",+ category: "project",+ name: "Atlas",+ aliases: [],+ status: "active",+ };+ const projectB: GuardEntityLike = {+ id: "ent-project-borealis",+ category: "project",+ name: "Borealis",+ aliases: [],+ status: "active",+ };+ const def = guardEntityMerge({+ keepText: "Atlas ships next week",+ dropText: "Borealis ships next week",+ entities: [projectA, projectB],+ });+ expect(def.allowed).toBe(true);+ const optIn = guardEntityMerge({+ keepText: "Atlas ships next week",+ dropText: "Borealis ships next week",+ entities: [projectA, projectB],+ categories: ["project"],+ });+ expect(optIn.allowed).toBe(false);+ });++ test("archived entities never anchor", () => {+ const gone: GuardEntityLike = { ...bob, status: "archived" };+ const verdict = guardEntityMerge({+ keepText: "Alice decided X",+ dropText: "Bob Hale decided X",+ entities: [alice, gone],+ });+ expect(verdict.allowed).toBe(true);+ });++ test("default guarded categories cover people and orgs", () => {+ expect(GUARDED_ENTITY_CATEGORIES).toContain("people");+ expect(GUARDED_ENTITY_CATEGORIES).toContain("org");+ });+});++describe("mergePreferences integration", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-merge-guard-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ function pref(slug: string, principle: string): WritePreferenceInput {+ return {+ slug,+ topic: "deploys",+ principle,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: BRAIN_CONFIDENCE.high,+ confidence_value: 0.8,+ pinned: false,+ };+ }++ test("cross-person merge throws entity-guard; bypass merges", () => {+ upsertEntity(vault, { category: "people", name: "Alice Mason", agent: "tester", now: NOW });+ upsertEntity(vault, { category: "people", name: "Bob Hale", agent: "tester", now: NOW });+ writePreference(vault, pref("alice-deploy", "Alice Mason approves every deploy"));+ writePreference(vault, pref("bob-deploy", "Bob Hale approves every deploy"));++ let thrown: unknown;+ try {+ mergePreferences(vault, "pref-alice-deploy", "pref-bob-deploy", { now: NOW });+ } catch (exc) {+ thrown = exc;+ }+ expect(thrown).toBeInstanceOf(BrainMergeError);+ expect((thrown as BrainMergeError).code).toBe("entity-guard");++ const plan = mergePreferences(vault, "pref-alice-deploy", "pref-bob-deploy", {+ now: NOW,+ bypassEntityGuard: true,+ dryRun: true,+ });+ expect(plan.keep_id).toBe("pref-alice-deploy");+ });++ test("same-person merge passes the guard", () => {+ upsertEntity(vault, { category: "people", name: "Alice Mason", agent: "tester", now: NOW });+ writePreference(vault, pref("a-one", "Alice Mason approves every deploy"));+ writePreference(vault, pref("a-two", "Alice Mason signs off on deploys"));+ const plan = mergePreferences(vault, "pref-a-one", "pref-a-two", { now: NOW, dryRun: true });+ expect(plan.keep_id).toBe("pref-a-one");+ });+});diff --git a/tests/core/brain/truth/store.test.ts b/tests/core/brain/truth/store.test.tsnew file mode 100644index 00000000..4d682d65--- /dev/null+++ b/tests/core/brain/truth/store.test.ts@@ -0,0 +1,210 @@+/**+ * Claim ledger store (Entity Truth & Self-Improving Dream Suite,+ * t_d6849b56): device-sharded append-only JSONL under `Brain/truth/`,+ * fail-closed line parsing, derived state cache that is never+ * authority, and an explicit sweep bounded by a newest-N cap.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, readFileSync, rmSync, writeFileSync, existsSync } from "node:fs";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ appendClaimEvent,+ CLAIM_EVENT_MAX_COUNT,+ claimShardPath,+ readClaimEvents,+ readTruthState,+ sweepClaimEvents,+ truthDir,+ truthStatePath,+ writeTruthState,+} from "../../../../src/core/brain/truth/store.ts";+import { computeTruthState } from "../../../../src/core/brain/truth/fold.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-truth-store-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function append(+ over: Partial<Parameters<typeof appendClaimEvent>[1]> = {},+): ReturnType<typeof appendClaimEvent> {+ return appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/standup.md]]",+ ...over,+ });+}++describe("appendClaimEvent", () => {+ test("appends one JSONL line to the device shard and normalizes identity", () => {+ const written = append({ entity: " Alice Mason ", aspect: " Employer " });+ expect(written.path).toBe(claimShardPath(vault));+ const lines = readFileSync(written.path, "utf8").trim().split("\n");+ expect(lines).toHaveLength(1);+ const row = JSON.parse(lines[0]!) as Record<string, unknown>;+ expect(row["v"]).toBe(1);+ expect(row["entity"]).toBe("alice mason");+ expect(row["aspect"]).toBe("employer");+ expect(row["value"]).toBe("Google");+ });++ test("two appends accumulate; the derived state cache refreshes", () => {+ append();+ append({ ts: "2026-06-02T10:00:00Z", value: "Meta", source: "[[Brain/notes/later.md]]" });+ expect(readClaimEvents(vault).events).toHaveLength(2);+ const state = readTruthState(vault);+ expect(state).not.toBeNull();+ expect(state!.events).toBe(2);+ });++ test("rejects an empty entity or aspect", () => {+ expect(() => append({ entity: " " })).toThrow();+ expect(() => append({ aspect: "" })).toThrow();+ });++ test("quantity claims persist the quantity payload", () => {+ append({+ value: "3",+ valueKind: "quantity",+ quantity: { value: 3, unit: "usd", action: "spent" },+ });+ const events = readClaimEvents(vault).events;+ expect(events[0]!.valueKind).toBe("quantity");+ expect(events[0]!.quantity).toEqual({ value: 3, unit: "usd", action: "spent" });+ });+});++describe("readClaimEvents", () => {+ test("merges device shards sorted by (ts, shard, line)", () => {+ mkdirSync(truthDir(vault), { recursive: true });+ const rowA = {+ v: 1,+ ts: "2026-06-02T09:00:00Z",+ agent: "a",+ entity: "alice mason",+ aspect: "employer",+ value: "Meta",+ valueKind: "text",+ source: "[[x]]",+ };+ const rowB = { ...rowA, ts: "2026-06-01T09:00:00Z", agent: "b", value: "Google" };+ writeFileSync(join(truthDir(vault), "claims.dev-a.jsonl"), JSON.stringify(rowA) + "\n");+ writeFileSync(join(truthDir(vault), "claims.dev-b.jsonl"), JSON.stringify(rowB) + "\n");+ const { events, warnings } = readClaimEvents(vault);+ expect(warnings).toHaveLength(0);+ expect(events.map((e) => e.value)).toEqual(["Google", "Meta"]);+ });++ test("fail-closed: malformed lines and wrong versions surface as warnings, never throw", () => {+ mkdirSync(truthDir(vault), { recursive: true });+ const good = {+ v: 1,+ ts: "2026-06-01T09:00:00Z",+ agent: "a",+ entity: "alice mason",+ aspect: "employer",+ value: "Google",+ valueKind: "text",+ source: "[[x]]",+ };+ const lines = [+ "not json at all",+ JSON.stringify({ ...good, v: 99 }),+ JSON.stringify({ ...good, ts: "yesterday" }),+ JSON.stringify({ ...good, entity: 42 }),+ JSON.stringify(good),+ ].join("\n");+ writeFileSync(join(truthDir(vault), "claims.jsonl"), lines + "\n");+ const { events, warnings } = readClaimEvents(vault);+ expect(events).toHaveLength(1);+ expect(warnings).toHaveLength(4);+ });++ test("sync-conflict copies are never read as shards", () => {+ mkdirSync(truthDir(vault), { recursive: true });+ writeFileSync(+ join(truthDir(vault), "claims.sync-conflict-20260601-foo.jsonl"),+ JSON.stringify({ v: 1 }) + "\n",+ );+ expect(readClaimEvents(vault).events).toHaveLength(0);+ });++ test("missing directory reads as empty", () => {+ expect(readClaimEvents(vault).events).toHaveLength(0);+ });+});++describe("derived state cache", () => {+ test("readTruthState is fail-closed on corrupt nested rows", () => {+ writeTruthState(vault, computeTruthState([]));+ expect(readTruthState(vault)).not.toBeNull();+ writeFileSync(+ truthStatePath(vault),+ JSON.stringify({+ version: 1,+ events: 1,+ updatedAt: null,+ slots: [{ bogus: true }],+ conflicts: [],+ }),+ );+ expect(readTruthState(vault)).toBeNull();+ writeFileSync(truthStatePath(vault), "{ not json");+ expect(readTruthState(vault)).toBeNull();+ });++ test("state cache is recomputable: deleting it loses nothing", () => {+ append();+ append({ ts: "2026-06-02T10:00:00Z", value: "Meta" });+ const before = readTruthState(vault);+ rmSync(truthStatePath(vault));+ const refolded = computeTruthState(readClaimEvents(vault).events);+ expect(refolded).toEqual(before!);+ });+});++describe("sweepClaimEvents", () => {+ test("keeps the newest N events and refolds", () => {+ for (let i = 0; i < 5; i++) {+ append({+ ts: `2026-06-0${i + 1}T10:00:00Z`,+ value: `v${i}`,+ source: `[[Brain/notes/n${i}.md]]`,+ });+ }+ const outcome = sweepClaimEvents(vault, { maxEvents: 2 });+ expect(outcome.removed).toBe(3);+ expect(outcome.kept).toBe(2);+ const { events } = readClaimEvents(vault);+ expect(events.map((e) => e.value)).toEqual(["v3", "v4"]);+ expect(readTruthState(vault)!.events).toBe(2);+ });++ test("default cap is generous", () => {+ expect(CLAIM_EVENT_MAX_COUNT).toBeGreaterThanOrEqual(10000);+ });++ test("sweep with no directory refolds an orphaned state file", () => {+ writeTruthState(vault, {+ ...computeTruthState([]),+ events: 42,+ });+ const outcome = sweepClaimEvents(vault, {});+ expect(outcome).toEqual({ removed: 0, kept: 0 });+ expect(existsSync(truthStatePath(vault))).toBe(true);+ expect(readTruthState(vault)!.events).toBe(0);+ });+});diff --git a/tests/e2e/entity-truth-dream.integration.test.ts b/tests/e2e/entity-truth-dream.integration.test.tsnew file mode 100644index 00000000..a7bdde60--- /dev/null+++ b/tests/e2e/entity-truth-dream.integration.test.ts@@ -0,0 +1,199 @@+/**+ * Entity Truth & Self-Improving Dream Suite - end-to-end integration+ * over one vault: atomic decomposition feeding the claim ledger+ * (t_cbd22536 + t_d6849b56 + t_220c313e), conflict and cross-agent+ * collision detection (t_e9692750 + t_f2b225b1), outcome-tied+ * evidence regression (t_d478df53), dead-end recall (t_be62c62d),+ * weekly top-source (t_a8d49eae), and foresight (t_08a79c81).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, rmSync, utimesSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../src/core/brain/apply-evidence.ts";+import { decomposeAtomicFacts } from "../../src/core/brain/atomic-facts.ts";+import { applyRecurrenceEvidence } from "../../src/core/brain/recurrence.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { dream } from "../../src/core/brain/dream.ts";+import { recordDeadEnd } from "../../src/core/brain/dead-ends.ts";+import { aggregateQuantities } from "../../src/core/brain/truth/aggregate.ts";+import { detectAgentCollisions } from "../../src/core/brain/truth/collision.ts";+import { computeTruthStateWithConflicts } from "../../src/core/brain/truth/conflicts.ts";+import { claimsFromAssertion } from "../../src/core/brain/truth/ingest.ts";+import { appendClaimEvent, readClaimEvents } from "../../src/core/brain/truth/store.ts";+import { buildForesight } from "../../src/core/brain/temporal/foresight.ts";+import { buildTimelineIndex } from "../../src/core/brain/temporal/build-index.ts";+import { buildWeeklySynthesis } from "../../src/core/brain/temporal/weekly-brief.ts";+import { BRAIN_TEMPORAL_DEFAULTS } from "../../src/core/brain/policy.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { indexVault } from "../../src/core/search/indexer.ts";+import { search } from "../../src/core/search/search.ts";+import { makeConfig } from "../helpers/search-fixtures.ts";++const NOW = new Date("2026-06-04T12:00:00Z");++let vault: string;+let configHome: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-etd-e2e-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-etd-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++test("the suite composes end to end on one vault", async () => {+ // -- Atomic decomposition feeds the ledger (3 + 4 + 2) --------------+ const session = [+ "# Budget standup",+ "",+ "I spent 120 USD on hosting last month.",+ "I spent 42 USD on domains last month.",+ ].join("\n");+ for (const assertion of decomposeAtomicFacts(session)) {+ for (const claim of claimsFromAssertion(assertion, {+ entity: "operator",+ agent: "claude-dev-agent",+ ts: "2026-06-01T10:00:00Z",+ source: "[[Brain/notes/budget-standup.md]]",+ })) {+ appendClaimEvent(vault, claim);+ }+ }+ // Two agents independently claim the same entity's employer.+ appendClaimEvent(vault, {+ ts: "2026-06-01T11:00:00Z",+ agent: "claude-dev-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/standup.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-03T11:00:00Z",+ agent: "sales-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Meta",+ source: "[[Brain/notes/intro-call.md]]",+ });++ const events = readClaimEvents(vault).events;+ expect(events.length).toBe(4);++ // -- Slots, conflicts, aggregation -----------------------------------+ const state = computeTruthStateWithConflicts(events);+ const employer = state.slots.find((s) => s.entity === "alice mason")!;+ expect(employer.contested).toBe(true);+ expect(employer.current.value).toBe("Meta");+ expect(employer.history[0]!.value).toBe("Google");+ expect(state.conflicts).toHaveLength(1);+ expect(state.conflicts[0]!.resolution).toBe("ask_user");++ const spend = aggregateQuantities(state.slots, {+ entity: "operator",+ action: "spent",+ unit: "usd",+ });+ expect(spend.total).toBe(162);+ expect(spend.count).toBe(2);++ // -- Cross-agent collision (5) ----------------------------------------+ const collisions = detectAgentCollisions(events, { now: NOW });+ expect(collisions).toHaveLength(1);+ expect(collisions[0]!.entity).toBe("alice mason");+ expect(collisions[0]!.agents).toEqual(["claude-dev-agent", "sales-agent"]);++ // -- Outcome regression (7) -------------------------------------------+ writePreference(vault, {+ slug: "risky-rule",+ topic: "deploys",+ principle: "Always hotfix straight to main",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: ["[[sig-2026-05-01-risky]]"],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 0,+ violated_count: 0,+ last_evidence_at: null,+ confidence: BRAIN_CONFIDENCE.low,+ confidence_value: null,+ pinned: false,+ });+ for (const day of [1, 2]) {+ appendApplyEvidence(+ vault,+ {+ pref_id: "pref-risky-rule",+ artifact: `[[Brain/notes/deploy-${day}.md]]`,+ result: "applied",+ agent: "claude-dev-agent",+ outcome: "failure",+ },+ { now: new Date(`2026-06-0${day}T10:00:00Z`) },+ );+ }+ const dreamRun = dream(vault, { now: NOW });+ expect(dreamRun.outcome_regressions).toHaveLength(1);+ expect(dreamRun.outcome_regressions[0]!.id).toBe("pref-risky-rule");++ // -- Dead-end recall (8) ----------------------------------------------+ recordDeadEnd(vault, {+ approach: "Hotfixing straight to main without canary",+ reason: "Production breakage twice in one week",+ agent: "claude-dev-agent",+ now: NOW,+ });+ const dbPath = join(vault, ".open-second-brain", "brain.sqlite");+ const searchConfig = makeConfig({ vault, dbPath });+ await indexVault(searchConfig);+ // FTS is implicit-AND at chunk level: query terms that all appear in+ // the dead-end note's body.+ const recall = await search(searchConfig, { query: "canary breakage" });+ expect(recall.results.some((r) => r.path.startsWith("Brain/dead-ends/"))).toBe(true);++ // -- Weekly top-source (6) ---------------------------------------------+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ const hub = join(vault, "Brain", "notes", "deploy-policy.md");+ writeFileSync(hub, "# Deploy policy\n\nThe canary-first rollout writeup.\n");+ const linker = join(vault, "Brain", "notes", "incident-review.md");+ writeFileSync(linker, "# Incident\n\nSee [[Brain/notes/deploy-policy.md|policy]].\n");+ const inWindow = new Date("2026-06-02T10:00:00Z");+ utimesSync(hub, inWindow, inWindow);+ utimesSync(linker, inWindow, inWindow);+ const weekly = buildWeeklySynthesis(+ buildTimelineIndex(vault, {}),+ vault,+ "2026-06-04",+ BRAIN_TEMPORAL_DEFAULTS,+ );+ expect(weekly.topSource).toBeDefined();+ expect(weekly.topSource!.path).toBe("Brain/notes/deploy-policy.md");+ expect(weekly.topSource!.signals.inboundLinks).toBe(1);++ // -- Foresight (10) ------------------------------------------------------+ for (let i = 0; i < 3; i++) {+ applyRecurrenceEvidence(vault, {+ contentHash: "weekly-review",+ scope: "weekly-review",+ sourceId: `sess-${i}`,+ action: "learn",+ at: new Date(Date.parse("2026-05-14T09:00:00Z") + i * 7 * 24 * 3600 * 1000).toISOString(),+ });+ }+ const foresight = buildForesight(vault, { now: NOW });+ const recurring = foresight.upcoming.find((u) => u.kind === "recurring")!;+ expect(recurring.due).toBe("2026-06-04");+ expect(recurring.title).toContain("weekly-review");+});diff --git a/tests/mcp/brain-truth.test.ts b/tests/mcp/brain-truth.test.tsnew file mode 100644index 00000000..5641fe98--- /dev/null+++ b/tests/mcp/brain-truth.test.ts@@ -0,0 +1,145 @@+/**+ * `brain_truth` MCP tool (Entity Truth & Self-Improving Dream Suite):+ * ingest one claim, read slots/conflicts from the fold, aggregate+ * exact-match quantities, report cross-agent collisions.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { appendClaimEvent } from "../../src/core/brain/truth/store.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.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-truth-"));+ vault = join(tmp, "vault");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-truth-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const key of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "truth-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++async function call(+ server: MCPServer,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const res = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 99,+ method: "tools/call",+ params: { name: "brain_truth", arguments: args },+ })) as { result?: { content?: Array<{ text?: string }> }; error?: { message: string } };+ if (res.error !== undefined) throw new Error(res.error.message);+ return JSON.parse(res.result!.content![0]!.text!) as Record<string, unknown>;+}++test("ingest then slots round-trips one claim through the fold", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const ingested = await call(server, {+ operation: "ingest",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/standup.md]]",+ });+ expect(ingested["ok"]).toBe(true);+ expect(ingested["entity"]).toBe("alice mason");++ const slots = await call(server, { operation: "slots" });+ expect(slots["events"]).toBe(1);+ expect((slots["slots"] as Array<{ current: { value: string } }>)[0]!.current.value).toBe(+ "Google",+ );+});++test("conflicts and aggregate read the same ledger", async () => {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/a.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-10T10:00:00Z",+ agent: "sales-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Meta",+ source: "[[Brain/notes/b.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "claude",+ entity: "operator",+ aspect: "hosting spend",+ value: "120",+ valueKind: "quantity",+ quantity: { value: 120, unit: "usd", action: "spent" },+ source: "[[Brain/notes/c.md]]",+ });++ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const conflicts = await call(server, { operation: "conflicts" });+ expect(conflicts["conflicts"]).toHaveLength(1);++ const aggregate = await call(server, { operation: "aggregate", action: "spent", unit: "usd" });+ expect(aggregate["total"]).toBe(120);+ expect(aggregate["count"]).toBe(1);+});++test("unknown operation is an invalid-params error", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ await expect(call(server, { operation: "bogus" })).rejects.toThrow(/operation/);+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 6606a984..475a5a86 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -257,6 +257,10 @@ describe("tool listing", () => {"brain_trigger","brain_deep_synthesis","brain_idea_discovery",+ // Entity Truth & Self-Improving Dream Suite.+ "brain_truth",+ "brain_dead_ends",+ "brain_foresight",// Agent Write Contract Suite: provider-agnostic write sessions."brain_write_session",].toSorted(),@@ -511,7 +515,9 @@ describe("stdio loop", () => {// + brain_trigger / brain_deep_synthesis / brain_idea_discovery// (Workspace Insight Suite) = 65.// + brain_write_session (Agent Write Contract Suite) = 66.- expect(list.result.tools.length).toBe(66);+ // + brain_truth / brain_dead_ends / brain_foresight+ // (Entity Truth & Self-Improving Dream Suite) = 69.+ expect(list.result.tools.length).toBe(69);});test("returns parse error for invalid JSON", async () => {