Skip to content

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

TypeScript

feat!: Stability & Trust - 1.0.0 API freeze, deprecation sweep, safeguard, staged dream, timezone, report deltas (#79)

Sol Aitken957a40320637
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index c3936d13..50195acd 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.45.0",
+ "version": "1.0.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 074889dd..95bdfb26 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.45.0",
+ "version": "1.0.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7cf1e5f2..28bf7477 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,88 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.0.0] - 2026-06-05
+
+Stability & Trust: the first major release formalizes what eleven
+release cycles built. The public contracts - the MCP tool surface,
+the CLI verb tree, configuration keys, the search schema ladder, and
+every on-disk format schema - are now frozen under an explicit
+stability policy (`docs/stability.md`), and the one breaking change a
+major allows is spent deliberately: the 18 hidden alias tools left
+over from the token-diet consolidation are removed, replaced by
+server-side tombstones that answer a stale call with the exact
+replacement tool and view. The hardening set makes "production-ready"
+an earned label: every long-running operation (dream, reindex, bridge
+discovery, communities, the maintenance lane) runs under a
+cooperative safeguard deadline with clean abort semantics and
+config-resolvable budgets; the self-improvement loop gains a staged
+stage -> validate -> apply lifecycle over a persisted, discardable
+proposal bundle while `dream()` stays the only promotion engine;
+user-facing and LLM-facing timestamps render the operator's
+configured timezone at the presentation layer while storage stays
+canonical UTC; and the digest / daily / weekly surfaces persist
+machine-diffable snapshots that report a deterministic "since last
+run" delta. A vault that configures nothing behaves identically -
+except calls to the 18 removed aliases, which is the documented
+break with a migration table in `docs/updating.md`.
+
+### Removed
+
+- **The 18 deprecated hidden MCP alias tools** (10 brain aliases of
+ `brain_brief` / `brain_analytics` views, 8 schema aliases of
+ `schema_inspect` views). Hidden from `tools/list` since v0.34.0,
+ they stayed callable; 1.0.0 deletes the alias layer so the
+ advertised list and the callable surface are the same set. Calling
+ a removed name answers an INVALID_PARAMS tombstone naming the
+ replacement (`brain_digest was removed in 1.0.0; call brain_brief
+ with view="digest"`). Full table in `docs/updating.md`.
+
+### Added
+
+- **Stability policy.** `docs/stability.md` pins the frozen contracts
+ and defines what counts as breaking per class; `docs/updating.md`
+ gains the 0.x -> 1.0.0 upgrade section.
+- **Doctor removed-surface check.** `removed-tool-reference` warnings
+ for Brain notes, root instruction files, and installed skills that
+ still name a removed tool, each with its replacement.
+- **Operation safeguard.** A cooperative deadline object checkpointed
+ at natural iteration boundaries in dream, indexing, bridge
+ discovery, communities, and the maintenance lane - honest abort
+ between atomic writes, never a fake async cancellation. Budgets
+ resolve per-operation (`safeguard_timeout_<op>_seconds`) -> env
+ (`OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`) -> global
+ (`safeguard_timeout_seconds`) -> default 600s; `0` disables. Lane
+ task results classify `timed_out`; persisted error strings cap at
+ 4096 bytes with an explicit marker.
+- **Staged dream pipeline.** `o2b brain dream stage | validate
+ <run-id> | apply <run-id> | discard <run-id> | list` (MCP
+ `brain_dream` gains an `action` parameter - no new tools). Stage
+ persists a reviewable bundle under `Brain/dream/staged/<run-id>/`
+ (manifest with schema `o2b.dream-stage.v1`, human REPORT.md,
+ sources with content hashes, proposals as data); validate
+ recomputes the clock-normalized plan and reports drift; apply
+ re-validates and runs the same engine live, archives the bundle,
+ and records a `dream_stage` metric. A drifted bundle aborts before
+ any write.
+- **Timezone presentation layer.** With `timezone:` configured
+ (env `VAULT_TIMEZONE`), brief and analytics envelopes gain additive
+ `timezone` + `local_time` fields and human output renders local
+ wall time; storage, frontmatter, log headings, and run ids stay
+ canonical UTC.
+- **Dual-output reports.** With `report_snapshots_enabled` (env
+ `OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS`), digest / daily / weekly runs
+ persist `Brain/reports/<surface>/<date>.json` (schema
+ `o2b.report-snapshot.v1`) and report a deterministic keyed delta -
+ arrays diff by stable identity, never by order - as a `delta` JSON
+ field and a "Since last run" block.
+
+### Changed
+
+- Error-message prefixes inside the consolidated view handlers now
+ name the consolidated form (`brain_brief view=monthly: ...`).
+- The `o2b brain dream` verb accepts an optional positional action;
+ the bare form is unchanged.
+
## [0.45.0] - 2026-06-05
Link & Recall Intelligence Suite: the graph self-organizes and recall
@@ -4822,6 +4904,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.0.0]: https://github.com/itechmeat/open-second-brain/compare/v0.45.0...v1.0.0
[0.45.0]: https://github.com/itechmeat/open-second-brain/compare/v0.44.0...v0.45.0
[0.44.0]: https://github.com/itechmeat/open-second-brain/compare/v0.43.1...v0.44.0
[0.43.1]: https://github.com/itechmeat/open-second-brain/compare/v0.43.0...v0.43.1
diff --git a/README.md b/README.md
index ad58d588..b74fcceb 100644
--- a/README.md
+++ b/README.md
@@ -112,9 +112,9 @@ The capabilities you actually feel day to day:
| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open --evidence-pack --since 7d` — SQLite + FTS5 and an optional semantic layer, with CJK-aware token expansion for unspaced Chinese/Japanese/Korean text. Recall is sharpened by MMR diversity, link-graph traversal, entity boosting, structured query lanes, session focus, and header-anchored chunking; typed relations carry recall polarity (a `superseded_by` predecessor is demoted below its successor, `contradicts` warns without endorsing); `--since` / `--until` scope recall by time; `o2b search feedback` trains bounded, auditable learned weights; opt-in evidence packs show matched/missing terms, IDF-weighted coverage, per-token union records, a completeness verdict with a false-absence guard, abstention text, terminal-state downranks, and `why_retrieved` reasons. |
| 10 | Pay Memory — audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |
-These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), 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.
+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_brief view=morning` 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.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). The v0.44.0 surface adds the Write-Time Integrity & Governance Suite: schema-pack ontology fields (controlled-vocabulary `labels`, per-link-type `link_constraints` endpoint pairs, per-type `attributes` descriptors, and a `frontmatter_tiers` map - all additive with audited mutations), fail-closed label classification (`o2b brain label`, MCP `brain_labels` - unknown dimensions and values are rejected with the declared vocabulary, persisted as a filterable frontmatter array plus a canonical label entity), link-type endpoint constraints enforced at index materialization (violating typed edges fall back to untyped links, surfaced by `schema lint` and restored automatically when the constraint is removed), per-type attribute fields whose validation errors teach the declared vocabulary (`o2b brain attr`), a four-level frontmatter tier guard (identity/system/business/user with built-in framework defaults, a tier-respecting merge in framework writers, index-time identity-drift detection that never absorbs a hand-edit, and the staged `o2b brain tiers check | restore | accept` repair surface, MCP `brain_tiers`), capability-gated secret custody (`o2b brain secret set | list | rm | run`, MCP `brain_secrets` - per-value AES-256-GCM ciphertext under the vault-local state dir, stdin-only ingestion, allowlist-gated subprocess env injection with redacted output, and a no-values audit trail in `Brain/log/secret-custody/`), and a quiet-window lease-guarded maintenance lane (`o2b brain maintenance run | status`, MCP `brain_maintenance` - a tz-aware hour window, a recall-telemetry busy gate, an expiring SQLite lease no second worker can grab, stale-first task ordering, and a bounded journal of every attempt including gate refusals). The v0.45.0 surface adds the Link & Recall Intelligence Suite: vault-wide frontmatter alias resolution materialized at index time (schema v7 `doc_aliases`, shadowing-safe, exact paths always win), orphan-first bridge discovery over the vec index (`o2b brain bridges discover | list | accept | dismiss`, MCP `brain_bridges` - embedding-near unlinked pairs land in a reviewable `Brain/proposals/bridges.md`, accept writes one `related:` wikilink honoring schema-pack link constraints, dismissals persist), deterministic graph-wide community detection with derived cluster digests (`o2b brain clusters run | list`, MCP `brain_clusters` - label propagation with a stable tie-break, `Brain/clusters/` notes regenerate per run, hand-written files untouched), a reproducible recall benchmark with a committed fixture dataset and CI thresholds (`o2b brain benchmark run`, MCP `brain_benchmark` - hit@k and MRR against the live hybrid pipeline), deterministic query expansion into the structured lex/vec/hyde lanes (`o2b search --expand` - stopword-stripped lex terms, entity-context vec line, template hyde passage, no model and no paid call), opt-in self-tuning recall judged by the benchmark (`o2b brain tune run | status | reset`, MCP `brain_tune` - a bounded replayable grid persisted to `Brain/search/tuning.json`, applied only under `search_self_tuning_enabled`), and a dashboard-ready run-level metrics layer (`Brain/metrics/<surface>.jsonl`, schema `o2b.metrics.v1`, contract in `docs/metrics.md`).
+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). The v0.44.0 surface adds the Write-Time Integrity & Governance Suite: schema-pack ontology fields (controlled-vocabulary `labels`, per-link-type `link_constraints` endpoint pairs, per-type `attributes` descriptors, and a `frontmatter_tiers` map - all additive with audited mutations), fail-closed label classification (`o2b brain label`, MCP `brain_labels` - unknown dimensions and values are rejected with the declared vocabulary, persisted as a filterable frontmatter array plus a canonical label entity), link-type endpoint constraints enforced at index materialization (violating typed edges fall back to untyped links, surfaced by `schema lint` and restored automatically when the constraint is removed), per-type attribute fields whose validation errors teach the declared vocabulary (`o2b brain attr`), a four-level frontmatter tier guard (identity/system/business/user with built-in framework defaults, a tier-respecting merge in framework writers, index-time identity-drift detection that never absorbs a hand-edit, and the staged `o2b brain tiers check | restore | accept` repair surface, MCP `brain_tiers`), capability-gated secret custody (`o2b brain secret set | list | rm | run`, MCP `brain_secrets` - per-value AES-256-GCM ciphertext under the vault-local state dir, stdin-only ingestion, allowlist-gated subprocess env injection with redacted output, and a no-values audit trail in `Brain/log/secret-custody/`), and a quiet-window lease-guarded maintenance lane (`o2b brain maintenance run | status`, MCP `brain_maintenance` - a tz-aware hour window, a recall-telemetry busy gate, an expiring SQLite lease no second worker can grab, stale-first task ordering, and a bounded journal of every attempt including gate refusals). The v0.45.0 surface adds the Link & Recall Intelligence Suite: vault-wide frontmatter alias resolution materialized at index time (schema v7 `doc_aliases`, shadowing-safe, exact paths always win), orphan-first bridge discovery over the vec index (`o2b brain bridges discover | list | accept | dismiss`, MCP `brain_bridges` - embedding-near unlinked pairs land in a reviewable `Brain/proposals/bridges.md`, accept writes one `related:` wikilink honoring schema-pack link constraints, dismissals persist), deterministic graph-wide community detection with derived cluster digests (`o2b brain clusters run | list`, MCP `brain_clusters` - label propagation with a stable tie-break, `Brain/clusters/` notes regenerate per run, hand-written files untouched), a reproducible recall benchmark with a committed fixture dataset and CI thresholds (`o2b brain benchmark run`, MCP `brain_benchmark` - hit@k and MRR against the live hybrid pipeline), deterministic query expansion into the structured lex/vec/hyde lanes (`o2b search --expand` - stopword-stripped lex terms, entity-context vec line, template hyde passage, no model and no paid call), opt-in self-tuning recall judged by the benchmark (`o2b brain tune run | status | reset`, MCP `brain_tune` - a bounded replayable grid persisted to `Brain/search/tuning.json`, applied only under `search_self_tuning_enabled`), and a dashboard-ready run-level metrics layer (`Brain/metrics/<surface>.jsonl`, schema `o2b.metrics.v1`, contract in `docs/metrics.md`). The v1.0.0 surface is the Stability & Trust release: the public contracts freeze under `docs/stability.md` (the 18 hidden alias tools are removed with tombstones naming each replacement - migration table in `docs/updating.md`), every long-running operation runs under a cooperative safeguard deadline with clean abort semantics, the dream loop gains a staged stage/validate/apply lifecycle over a persisted reviewable bundle (`o2b brain dream stage`), configured-timezone rendering arrives at the presentation layer while storage stays canonical UTC, and the digest/daily/weekly surfaces persist machine-diffable snapshots with a deterministic since-last-run delta (`report_snapshots_enabled`).
## CLI
diff --git a/docs/brainstorm/release-1-0-stability-trust/cli-output/claude.md b/docs/brainstorm/release-1-0-stability-trust/cli-output/claude.md
new file mode 100644
index 00000000..1a010490
--- /dev/null
+++ b/docs/brainstorm/release-1-0-stability-trust/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Independent vertical slices
+- **Approach**: Each of the five units lands as a self-contained module with its own atomic commit, sharing only small existing primitives (`atomicWriteFileSync`, the `o2b.metrics.v1` writer, `time.ts`). The safeguard is a thin wrapper invoked at each long-running call site; the staged dream pipeline adds an output mode to existing `dream()` rather than a new engine; Unit 5's snapshot-diff and Unit 4's timezone formatter are local utilities threaded through their own render/persist sites. No new cross-unit abstraction is extracted.
+- **Trade-offs**:
+ - Pro: Cleanest fit for TDD with per-unit atomic commits; each unit independently reviewable and revertible.
+ - Pro: Smallest blast radius — byte-compatibility of untouched surfaces is trivially preserved.
+ - Pro: No risk of forking promotion logic, since dream stays the single engine with an added serialization mode.
+ - Con: Units 3 and 5 both implement persisted-artifact + diff mechanics; mild duplication of "manifest, generated_at frontmatter, diff-against-prior" logic.
+ - Con: Timezone presentation (Unit 4) and snapshot rendering (Unit 5) touch overlapping render sites twice instead of once.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Shared artifact-and-presentation substrate
+- **Approach**: Extract two reusable layers up front — a "persisted bundle + structured snapshot + deterministic diff" core that both the staged dream pipeline (Unit 3) and dual-output reports (Unit 5) build on, and a presentation module where the timezone formatter (Unit 4) and report rendering (Unit 5) share one timestamp/projection path. The safeguard (Unit 2) becomes shared middleware wrapping registered long-running operations. Unit 1's freeze documents these new shared contracts.
+- **Trade-offs**:
+ - Pro: Eliminates duplication across the genuinely overlapping units (3/5 artifacts, 4/5 rendering).
+ - Pro: One diff engine and one presentation contract are easier to test exhaustively and to freeze coherently for 1.0.
+ - Con: Higher coupling; per-unit atomic commits become interdependent (substrate must land before its consumers), straining the TDD-per-unit convention.
+ - Con: Larger blast radius across render sites raises the chance of an accidental byte-compat regression in a frozen surface.
+ - Con: Pressure to over-generalize the bundle abstraction risks the "don't fork the promotion engine" constraint if dream staging drifts toward the shared layer.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Contract-registry spine
+- **Approach**: Make Unit 1 the architectural spine — build a machine-readable freeze manifest (tool surface, schema versions, config keys/env vars, on-disk formats) that the `doctor` probe reads to flag removed/relied-on surfaces. Units 2–5 then declare their new surfaces (safeguard timeout keys, bundle schema, snapshot schema, timezone config key) into that same registry, so "what is frozen" has one source of truth and the doctor check is data-driven rather than hand-maintained.
+- **Trade-offs**:
+ - Pro: Strongest trust story — the compatibility policy is enforced by a manifest, not prose, and the doctor probe stays accurate as surfaces evolve.
+ - Pro: New 1.0 surfaces are born registered and frozen, preventing drift.
+ - Con: A full contract registry is heavyweight for a single PR; most surfaces are already stable, so much of the registry is descriptive scaffolding with low immediate payoff.
+ - Con: Couples four feature units to a new meta-layer, complicating atomic commits and adding a frozen surface that itself must be maintained forever.
+ - Con: Doctor-as-registry-reader risks scope creep beyond the "callable-name probe or docs guidance" the task scopes.
+- **Complexity**: large
+- **Risk**: medium
+
+### Recommended: Variant 1
+**Rationale**: The constraints most strongly favor independence — per-unit atomic commits, byte-compatibility on every surface but the 9 aliases, and a single promotion engine all argue against the up-front coupling of Variants 2 and 3. The real overlaps (artifact persistence in Units 3/5, rendering in Units 4/5) are small enough to capture with a shared helper extracted opportunistically inside the slice work, without committing to a substrate or registry whose cost outweighs its one-PR payoff.
diff --git a/docs/brainstorm/release-1-0-stability-trust/cli-output/prompt.md b/docs/brainstorm/release-1-0-stability-trust/cli-output/prompt.md
new file mode 100644
index 00000000..4ad36546
--- /dev/null
+++ b/docs/brainstorm/release-1-0-stability-trust/cli-output/prompt.md
@@ -0,0 +1,85 @@
+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
+
+Epic: Release 1.0.0 - Stability & Trust: API freeze, deprecation sweep, hardening. One PR ships five atomic units that together justify the first major version of Open Second Brain (a TypeScript/Bun memory plugin for coding agents: MCP server + `o2b` CLI over an Obsidian-compatible vault).
+
+## Unit 1 (epic-level): API freeze and deprecation sweep
+
+- Remove the 9 `deprecatedAlias(...)` MCP tools that survive from the token-diet pass (hidden from `tools/list` but still callable): brain_digest, brain_daily_brief, brain_morning_brief, brain_weekly_synthesis, brain_monthly_review (aliases of `brain_brief` views) and brain_attention_flows, brain_concept_synthesis, brain_timeline, brain_belief_evolution (aliases of `brain_analytics` views). A major bump is the only legitimate moment to drop them.
+- Pin public contracts as frozen-under-semver and document the compatibility policy: MCP tool surface (77 tools), CLI verb tree, config keys + env vars, search index schema (v7) and its migration ladder, on-disk formats (`o2b.metrics.v1`, `o2b.tuning.v1`, continuity records, `Brain/` layout).
+- Write a SemVer policy section (what counts as breaking for schemas and file formats) and an upgrade guide 0.x -> 1.0.0 listing every removed alias with its replacement.
+- An `o2b doctor`-style check that flags clients/configs still relying on removed surfaces (e.g. a callable-name probe or docs-level guidance; the right mechanism is part of this brainstorm).
+
+## Unit 2: Per-command timeout safeguard with output caps (kanban t_06784b8d, upstream:mirage)
+
+Long-running operations (dream pass, reindex, bridge discovery, cluster materialization, maintenance lane, large sync) currently have no hang protection and no output caps. Upstream mirage added a CommandSafeguard: per-command timeout resolution (override -> command default -> global fallback), stream wrapper firing a timeout error, background jobs propagating exit 124, YAML-configurable max_lines/max_bytes caps. For Open Second Brain the analogue is a safeguard layer around the long-running brain/search operations (CLI verbs and MCP tools), with per-operation timeout defaults, a config surface, and graceful partial-result or clean-abort semantics.
+
+## Unit 3: Staged dream pipeline - persisted proposal bundle with validate-before-apply (kanban t_ae8a8ec0, article: Hermes Dreaming)
+
+Today `dream()` (src/core/brain/dream.ts, ~2200 lines) promotes inline with a dryRun preview (`brain_review_candidates`) and snapshot+rollback as the post-hoc safety net. The task: make each dream run able to produce a persisted on-disk proposal bundle (manifest, human-readable report, scanned sources, proposed mutations as data) that can be diffed, validated, applied, or discarded as a unit - with an explicit validate step that must pass before apply writes anything to live state. Stage-validate-apply over a discardable artifact raises trust in the self-improvement loop.
+
+## Unit 4: User-configurable timezone for all LLM/user-facing timestamps (kanban t_2ccadc6a, upstream:tencentdb-agent-memory)
+
+Storage stays UTC. `resolveTimezone()` already exists in src/core/config.ts (order: VAULT_TIMEZONE env -> `timezone` config field -> null) but is consumed only by the openclaw surface and pay-memory verbs. The task: route user-facing and LLM-facing timestamp rendering (briefs, digests, timeline, recall output, CLI verbs, MCP tool responses) through a presentation-layer conversion honoring the configured IANA timezone, with UTC fallback when unset. Internal storage, frontmatter, log headings, and run ids remain canonical UTC.
+
+## Unit 5: Dual-output reports - human-readable plus machine-diffable snapshot (kanban t_00eece5d, article: Hermes as an Onchain Analyst)
+
+Digest/synthesis surfaces (daily/weekly/monthly briefs, digest) return structured envelopes in-memory but persist no machine snapshot for run-over-run diffing. The task: from one run, emit the human-readable report plus a structured JSON snapshot of the same findings, so a later run can diff against the prior snapshot and report "what changed since last digest" deterministically. This extends the dashboard-ready `Brain/metrics/` contract shipped in v0.45.0 (schema-versioned, append-only JSONL, fail-soft readers).
+
+# Project context
+
+Open Second Brain - TypeScript on Bun. SQLite (bun:sqlite) search index with FTS5 + optional sqlite-vec. MCP server (stdio JSON-RPC) + `o2b` CLI. 4176 tests across 539 files; oxlint baseline 111 warnings / 0 errors; oxfmt formatter; tsc typecheck.
+
+Recent commits:
+6d09d3c feat: Link & Recall Intelligence Suite - alias resolution, bridge discovery, communities, recall benchmark, self-tuning (#77)
+789e3e3 feat: Write-Time Integrity & Governance Suite - schema ontology, tier guard, secret custody, maintenance lane (#76)
+c03d569 fix(hermes): root cli.py shim completes the upstream CLI discovery contract (#75)
+a0054dd feat: Entity Truth & Self-Improving Dream Suite - claim ledger, outcome-aware dream, foresight (#74)
+b16c37d feat: Time-Aware Recall & Activation Suite - usage-aware ranking, event-time recall, two-pass recovery (#73)
+
+Related files:
+- src/mcp/tools.ts (deprecatedAlias helper, ToolDefinition, hidden flag), src/mcp/brain-tools.ts (9 alias registrations, ~5500 lines), src/mcp/server.ts (hidden tools callable but unlisted)
+- src/core/brain/dream.ts (dream() with dryRun), src/core/brain/review-candidates.ts (read-only preview), src/core/brain/snapshot.ts (post-hoc rollback)
+- src/core/config.ts (resolveTimezone, discoverConfig), src/core/brain/time.ts (isoSecond/isoDate canonical UTC)
+- src/core/brain/temporal/ (daily-brief.ts, weekly-brief.ts, period-common.ts), src/core/brain/digest.ts
+- src/core/brain/metrics.ts (o2b.metrics.v1 append-only JSONL layer, fail-soft reader)
+- src/cli/brain/verbs/maintenance.ts (lane: dream, reindex, bridges, clusters), src/cli/command-manifest.ts
+- src/core/brain/doctor.ts (diagnostic surface)
+
+Conventions:
+- Deterministic core: no LLM calls in library code; derived artifacts are deterministic projections
+- Fail-soft observability: metrics/telemetry failures never break the operation ("Metrics are observability, not correctness")
+- Reviewable artifacts: generated files under Brain/ with frontmatter kind + generated_at, regenerated per run, hand-written files never touched
+- Atomic writes (atomicWriteFileSync), O_APPEND single-line JSONL for append-only logs
+- Run-level metrics into Brain/metrics/<surface>.jsonl with schema "o2b.metrics.v1"
+- CLI verbs: exit 0 success/fail-soft skip, exit 1 operational failure (JSON {ok:false}), exit 2 usage errors (plain stderr)
+- MCP tools: INVALID_PARAMS before environment checks, descriptions <= 300 chars, previewBudget envelopes
+- Opt-in behavior changes behind config flags; a vault that enables nothing behaves bit-identically
+- TDD with per-unit atomic commits
+
+Constraints:
+- No new external dependencies
+- Breaking changes allowed ONLY for the 9 documented deprecated aliases; every other public surface must stay byte-compatible
+- Storage timestamps stay canonical UTC everywhere (frontmatter, logs, run ids); timezone is strictly presentation-layer
+- dream() public API stays backward compatible; the staged pipeline must not fork a second promotion engine (single source of truth for promotion logic)
+- Safeguard layer must not wrap synchronous SQLite calls with fake async timeouts; honest cancellation points only
+- New run-level surfaces publish o2b.metrics.v1 records
+- Doc artifacts: docs/ directory, CHANGELOG one version per PR
+
+# 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/release-1-0-stability-trust/design.md b/docs/brainstorm/release-1-0-stability-trust/design.md
new file mode 100644
index 00000000..7ee51d4d
--- /dev/null
+++ b/docs/brainstorm/release-1-0-stability-trust/design.md
@@ -0,0 +1,71 @@
+# Release 1.0.0 - Stability & Trust: API freeze, deprecation sweep, hardening
+
+**Status:** accepted
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain is natively integrable with Hermes and its surface has been stable across many release cycles, but nothing formalizes that stability. Nine deprecated MCP aliases linger from the token-diet pass, no document states what counts as a breaking change for schemas and on-disk formats, long-running operations have no hang protection, the self-improvement loop applies changes inline with only post-hoc rollback, timestamps render in UTC regardless of the operator's locale, and periodic reports cannot say what changed since the previous run. Version 1.0.0 is the moment to fix all six: a major bump is the only legitimate point to drop deprecated surfaces, and the hardening work earns the "production-ready" label the version number claims.
+
+## Scope
+
+Five atomic units in one PR (epic t_a77ade0a):
+
+1. **API freeze + deprecation sweep** (epic-level): remove the 18 `deprecatedAlias` MCP tools (10 brain aliases of `brain_brief`/`brain_analytics` views, 8 schema aliases of `schema_inspect` views), replace them with server-side tombstones that return a precise migration error, pin the public contracts in a stability policy document, and write the 0.x -> 1.0.0 upgrade guide. A doctor check flags vault-side references to removed tool names.
+2. **Operation safeguard** (t_06784b8d): cooperative deadline + output-cap layer around the long-running brain operations (dream, reindex, bridge discovery, communities, maintenance lane), config-resolvable timeouts, clean-abort semantics, `timed_out` surfaced in lane metrics.
+3. **Staged dream pipeline** (t_ae8a8ec0): `stage -> validate -> apply` lifecycle over a persisted, discardable proposal bundle, with `dream()` remaining the single promotion engine.
+4. **Timezone presentation layer** (t_2ccadc6a): user/LLM-facing timestamp rendering honors the configured IANA timezone; storage stays canonical UTC.
+5. **Dual-output reports** (t_00eece5d): digest and brief surfaces persist a machine-diffable JSON snapshot per run and report a deterministic "since last run" delta.
+
+## Out of scope
+
+- UI surfaces (inbox pill, voice chat) - dashboard-plugin material.
+- Artifact ingest with OCR (t_77f9d89b), subagent tool loop (t_8bf27494), OTel LLM tracing (t_281c3edc), PDF export (t_64d65fb7) - each its own minor after 1.0.
+- Copilot/Pi session adapters - blocked on external format reverse-engineering.
+- Renaming the writer MCP server (deferred since v0.10.10) - a rename is breaking for client configs and the cost/benefit does not clear the bar even at a major.
+- Preemptive cancellation of synchronous SQLite work - the safeguard is cooperative by design (see decisions).
+
+## Chosen approach
+
+Variant 1 from the consultant pass: independent vertical slices. Each unit lands as a self-contained module with its own atomic commits, sharing only existing primitives (`atomicWriteFileSync`, the `o2b.metrics.v1` writer, `time.ts`, `resolveTimezone`). The safeguard is a thin cooperative deadline object checked at iteration boundaries; the staged dream pipeline adds a persistence-and-gate mode around the existing `dream()` engine rather than a second mutation path; the timezone formatter and the snapshot-diff helper are local utilities threaded through their own render/persist sites. No new cross-unit abstraction is extracted up front; if units 3 and 5 converge on identical bundle mechanics during implementation, a small shared helper is extracted opportunistically inside the slice work.
+
+## Design decisions
+
+- **Tombstones instead of silent removal.** Removing the 18 aliases makes `tools/call` on an old name fail with a generic "unknown tool". A static `REMOVED_TOOLS` map (name -> `{removedIn: "1.0.0", replacement: "brain_brief", view: "digest"}`) lets the server return one precise INVALID_PARAMS error: `brain_digest was removed in 1.0.0; call brain_brief with view="digest"`. Zero token cost (tombstones are never listed), maximal migration clarity. The `deprecatedAlias` helper itself is deleted - nothing uses it after the sweep.
+- **The advertised tool count stays 77; the callable surface shrinks 95 -> 77.** The 18 aliases were `hidden: true` - absent from `tools/list` but callable. The sweep makes the advertised list and the callable surface identical, which is itself a 1.0 property (no shadow API). The staged dream lifecycle rides the existing `brain_dream` tool via an optional `action` parameter (`run` default | `stage` | `validate` | `apply` | `discard` | `list`); timezone and snapshots ride existing brief/digest tools. No new tools.
+- **Stability policy is prose, not a registry.** Variant 3's machine-readable contract registry is heavyweight scaffolding for surfaces that are already stable. `docs/stability.md` lists the frozen contracts (MCP tool surface, CLI verb tree, config keys + env vars, search schema ladder, on-disk format schemas) and defines what counts as breaking for each class. The upgrade guide lands as a 0.x -> 1.0.0 section in `docs/updating.md` with the full alias -> replacement table.
+- **Doctor check scopes to what doctor can see.** Doctor cannot inspect remote client configs; it scans vault-side surfaces it already reads (installed skill files, openclaw config block, `Brain/` notes) for the 9 removed names and emits a warning naming the replacement. Best-effort, fail-soft, no false authority.
+- **Safeguard is cooperative, not preemptive.** Bun + synchronous SQLite cannot be preempted honestly; wrapping sync calls in fake async timeouts would lie about cancellation. `createSafeguard({timeoutMs})` returns a deadline object whose `checkpoint()` throws `SafeguardTimeoutError` when the deadline passes; long operations call `checkpoint()` at natural iteration boundaries (per file in `indexVault`, per candidate in `discoverBridges`, per propagation sweep in `detectCommunities`, per phase in `dream`, per task in the maintenance lane). Abort is clean: the operation stops at a boundary, partial artifacts are not half-written (writes stay atomic), and the caller reports `timed_out: true`.
+- **Safeguard config is flat keys with a global fallback.** `safeguard_timeout_seconds` (global default 600) plus per-operation overrides (`safeguard_timeout_dream_seconds`, `_reindex_`, `_bridges_`, `_clusters_`, `_maintenance_`), env mirror `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`. Resolution order mirrors mirage: per-op override -> global -> built-in fallback. `0` disables (no deadline). Existing lane metrics gain a `timed_out` payload field; exit codes keep the repo convention (timeout is an operational failure: exit 1, `{ok:false, timed_out:true}`).
+- **Output caps live where output is unbounded.** The maintenance lane captures per-task output; it gains `max_bytes`-style caps with an explicit `truncated` marker. List-style verbs already have `--max` style limits; no blanket stream wrapper.
+- **Staged dream never forks the promotion engine.** `stageDream()` runs the existing engine in dry-run mode and persists the planned summary as a bundle under `Brain/dream/staged/<run-id>/`: `manifest.json` (schema `o2b.dream-stage.v1`, input fingerprint = hash over inbox signals + preference files the plan read), `REPORT.md` (human-readable, deterministic projection), `sources.jsonl` (scanned signals), `proposals.jsonl` (planned mutations as data). `validateDreamBundle()` recomputes the dry-run plan and compares it to the staged proposals - identical means the vault has not drifted. `applyDreamBundle()` re-validates, then runs `dream()` live; determinism guarantees the live run performs exactly the staged plan. Drift at any point aborts with a mismatch report and the operator re-stages. Apply records a `dream_stage` metric (o2b.metrics.v1).
+- **Timezone is presentation-only and additive.** `resolveTimezone()` already exists (env `VAULT_TIMEZONE` -> config `timezone` -> null). A new `formatLocalTimestamp(isoUtc, tz)` helper (Intl.DateTimeFormat, no dependencies) renders `YYYY-MM-DDTHH:MM:SS+HH:MM`. When a timezone is configured, human-readable CLI output renders local time and JSON/MCP envelopes gain additive `*_local` fields plus a top-level `timezone` echo; when unset, output is byte-identical to 0.45.0. Storage, frontmatter, log headings, and run ids stay canonical UTC - `time.ts` is untouched.
+- **Report snapshots are opt-in and fail-soft.** Brief/digest runs persist `Brain/reports/<surface>/<ISO-date>.json` (schema `o2b.report-snapshot.v1`, atomic write) when `report_snapshots_enabled` is set (env `OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS`). The next run loads the most recent prior snapshot (fail-soft: torn or missing reads as none) and computes a deterministic diff (added/removed/changed per section) appended to the report as a "Since last run" block and a `delta` JSON field. Surfaces: digest, daily brief, weekly synthesis.
+- **A vault that enables nothing behaves bit-identically** - except for calls to the 9 removed aliases, which is the one documented break of the release.
+
+## File changes
+
+New files:
+- `src/core/brain/safeguard.ts` - createSafeguard, SafeguardTimeoutError, output-cap helper, config resolution.
+- `src/core/brain/dream-stage.ts` - stage/validate/apply/discard/list over the bundle layout.
+- `src/core/brain/present-time.ts` - formatLocalTimestamp + envelope localization helpers.
+- `src/core/brain/report-snapshot.ts` - snapshot persist/load/diff engine.
+- `docs/stability.md` - frozen contracts + semver policy.
+- Tests mirroring each new module plus integration coverage.
+
+Modified files:
+- `src/mcp/brain-tools.ts` (remove 10 alias registrations; brain_dream action param; localized fields), `src/mcp/schema-tools.ts` (remove 8 alias registrations), `src/mcp/tools.ts` (delete deprecatedAlias; REMOVED_TOOLS support), `src/mcp/server.ts` (tombstone dispatch).
+- `src/core/brain/dream.ts` (safeguard checkpoints; plan capture reuse), `src/core/search/indexer.ts`, `src/core/brain/link-graph/bridge-discovery.ts`, `src/core/brain/link-graph/communities.ts` (checkpoints).
+- `src/cli/brain/verbs/maintenance.ts` (per-task timeouts, output caps, timed_out metric field), dream/brief/digest/timeline CLI verbs (stage actions, local time, snapshots), `src/cli/command-manifest.ts`, help-text.
+- `src/core/brain/doctor.ts` (removed-name scan), `src/core/config.ts` (safeguard + snapshot key resolution).
+- `tests/mcp/mcp.test.ts` (tool count 77 -> 68 and related pins), affected verb/tool tests.
+- `README.md`, `CHANGELOG.md`, `docs/cli-reference.md`, `docs/mcp.md`, `docs/how-it-works.md`, `docs/updating.md`, `docs/metrics.md` (dream_stage surface).
+
+## Risks and open questions
+
+- **Hidden alias dependencies in tests/skills.** Some tests or shipped skill files may call alias names; the sweep must update them to the consolidated forms. Grep before removal.
+- **Dream determinism is the load-bearing wall for validate-then-apply.** Any nondeterminism (clock, iteration order) between recompute and live run breaks the equality gate. The dry-run plan comparison must normalize clock-derived fields (run ids, timestamps) out of the equality check.
+- **Checkpoint placement granularity.** Too coarse and timeouts overshoot; too fine and hot loops pay overhead. Place at I/O-adjacent boundaries only; benchmark-sensitive paths (recall) are out of safeguard scope.
+- **Intl.DateTimeFormat offset formatting** varies for exotic zones; the formatter must be covered by tests pinned to fixed zones (UTC, Europe/Berlin, America/New_York) and fail-soft to UTC on invalid zone names.
+- **Snapshot diff stability.** The diff must key on stable section identities (paths, pref ids), not array order, or every run reports spurious changes.
diff --git a/docs/brainstorm/release-1-0-stability-trust/plan.md b/docs/brainstorm/release-1-0-stability-trust/plan.md
new file mode 100644
index 00000000..be131616
--- /dev/null
+++ b/docs/brainstorm/release-1-0-stability-trust/plan.md
@@ -0,0 +1,106 @@
+# Release 1.0.0 - Stability & Trust - implementation plan
+
+One feature branch (`feat/release-1-0-stability-trust`), one task per atomic commit, TDD throughout: failing test first, implement, refactor green, `bun run fmt` + `bun run lint` before every commit.
+
+## Tasks
+
+### Task 1: Tombstones + alias sweep (MCP surface)
+- **Files**: `src/mcp/tools.ts` (REMOVED_TOOLS map + lookup, delete `deprecatedAlias`), `src/mcp/server.ts` (tombstone dispatch on tools/call), `src/mcp/brain-tools.ts` (remove the 10 brain alias registrations), `src/mcp/schema-tools.ts` (remove the 8 schema alias registrations), `tests/mcp/mcp.test.ts` (listed count stays 77; hidden surface gone), new `tests/mcp/removed-tools.test.ts`.
+- **Acceptance**: calling each of the 18 removed names via tools/call returns INVALID_PARAMS naming the replacement tool and view; `tools/list` length stays 77; no tool carries `hidden: true` in the full scope; no `deprecatedAlias` symbol remains.
+- **Depends on**: none.
+
+### Task 2: Alias-reference cleanup across tests, skills, and docs
+- **Files**: every test/skill/doc file that invokes one of the 18 removed names (grep-driven), `skills/` shipped surfaces if any reference them.
+- **Acceptance**: repo-wide grep for the 18 names finds only tombstone map, upgrade guide, CHANGELOG, and historical brainstorm docs; full MCP test suite green.
+- **Depends on**: Task 1.
+
+### Task 3: Doctor check for removed-surface references
+- **Files**: `src/core/brain/doctor.ts`, `tests/core/brain/doctor-removed-tools.test.ts`.
+- **Acceptance**: a vault note or installed skill file containing any of the 18 removed tool names yields a doctor warning naming the replacement; clean vault yields none.
+- **Depends on**: Task 1.
+
+### Task 4: Safeguard core
+- **Files**: new `src/core/brain/safeguard.ts`, `src/core/config.ts` (flat key + env resolution), `tests/core/brain/safeguard.test.ts`.
+- **Acceptance**: createSafeguard deadline fires SafeguardTimeoutError at checkpoint() past the deadline; resolution order per-op key -> global key -> built-in default; `0` disables; output-cap helper truncates with explicit marker.
+- **Depends on**: none.
+
+### Task 5: Safeguard wiring into long-running operations
+- **Files**: `src/core/brain/dream.ts`, `src/core/search/indexer.ts`, `src/core/brain/link-graph/bridge-discovery.ts`, `src/core/brain/link-graph/communities.ts`, `src/cli/brain/verbs/maintenance.ts` (+ verbs dream/reindex surfaces), `src/mcp/brain-tools.ts` (maintenance tool), lane metric payload `timed_out`, tests per wired operation.
+- **Acceptance**: each wired operation aborts cleanly at a boundary under a 1ms-deadline test and reports `timed_out: true` (exit 1 JSON contract for CLI); maintenance lane caps per-task output with truncated marker; default config changes nothing (suite green untouched).
+- **Depends on**: Task 4.
+
+### Task 6: Dream plan capture + stage bundle writer
+- **Files**: new `src/core/brain/dream-stage.ts` (stageDream, bundle layout `Brain/dream/staged/<run-id>/` with manifest.json / REPORT.md / sources.jsonl / proposals.jsonl, input fingerprint, clock-normalized plan projection), `src/core/brain/dream.ts` (export the dry-run plan in a comparable shape if not already), `tests/core/brain/dream-stage.test.ts`.
+- **Acceptance**: stageDream on a seeded vault persists a complete bundle; the proposals projection is stable across two stage runs on an unchanged vault (normalized: no run ids/timestamps in the equality surface).
+- **Depends on**: none (parallel to safeguard).
+
+### Task 7: Validate / apply / discard / list lifecycle
+- **Files**: `src/core/brain/dream-stage.ts` (validateDreamBundle recompute-compare, applyDreamBundle re-validate + live `dream()`, discard, list), `tests/core/brain/dream-stage-lifecycle.test.ts`.
+- **Acceptance**: validate passes on unchanged vault and fails with a drift report after a new signal lands; apply on a valid bundle performs exactly the staged promotions (live summary matches plan) and records a `dream_stage` metric; apply on a drifted bundle aborts without writes; discard removes the bundle.
+- **Depends on**: Task 6.
+
+### Task 8: Staged dream CLI + MCP surface
+- **Files**: dream CLI verb (stage/validate/apply/discard/list actions), `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`, `src/mcp/brain-tools.ts` (brain_dream optional `action` param, INVALID_PARAMS first), `docs/metrics.md` (dream_stage surface row), `tests/cli/brain-dream-stage.test.ts`, `tests/mcp/` coverage.
+- **Acceptance**: full stage -> validate -> apply cycle via CLI and via MCP brain_dream action param; usage errors exit 2; tool count stays 68.
+- **Depends on**: Task 7.
+
+### Task 9: Timezone presentation helper
+- **Files**: new `src/core/brain/present-time.ts` (formatLocalTimestamp via Intl.DateTimeFormat, invalid-zone fail-soft to UTC), `tests/core/brain/present-time.test.ts` pinned to UTC / Europe/Berlin / America/New_York including a DST boundary.
+- **Acceptance**: canonical UTC input renders `YYYY-MM-DDTHH:MM:SS+HH:MM` in the target zone; invalid zone returns UTC rendering; helper is pure and deterministic for fixed inputs.
+- **Depends on**: none.
+
+### Task 10: Timezone wiring across user/LLM-facing surfaces
+- **Files**: brief/digest/timeline/analytics CLI verbs and MCP tools (additive `*_local` fields + `timezone` echo when configured; human output renders local), `tests/cli/` + `tests/mcp/` coverage proving byte-identical output when timezone is unset.
+- **Acceptance**: with `timezone: Europe/Berlin` configured, brief output carries local renderings; with no timezone, output is byte-identical to pre-change snapshots.
+- **Depends on**: Task 9.
+
+### Task 11: Report snapshot + diff engine
+- **Files**: new `src/core/brain/report-snapshot.ts` (persist `Brain/reports/<surface>/<date>.json` schema `o2b.report-snapshot.v1`, load-latest fail-soft, deterministic keyed diff), `src/core/config.ts` (`report_snapshots_enabled` + env), `tests/core/brain/report-snapshot.test.ts`.
+- **Acceptance**: two snapshots diff into added/removed/changed keyed by stable identities regardless of array order; torn prior snapshot reads as none; disabled flag writes nothing.
+- **Depends on**: none.
+
+### Task 12: Dual-output wiring into digest, daily brief, weekly synthesis
+- **Files**: digest/brief surfaces (persist snapshot when enabled, append "Since last run" block + `delta` field on subsequent runs), corresponding CLI/MCP tests, `docs/metrics.md` if a metric is recorded.
+- **Acceptance**: first enabled run persists a snapshot and reports no delta; second run after a vault change reports the precise delta in both human and JSON output; disabled vault output byte-identical.
+- **Depends on**: Task 11.
+
+### Task 13: Stability policy + upgrade guide
+- **Files**: new `docs/stability.md` (frozen contracts: MCP tool surface, CLI verb tree, config keys + env vars, search schema ladder, on-disk format schemas; breaking-change definitions per class), `docs/updating.md` (0.x -> 1.0.0 section with the full 9-row alias -> replacement table), README pointer.
+- **Acceptance**: every removed alias has a documented replacement; policy enumerates every schema string shipped (`o2b.metrics.v1`, `o2b.tuning.v1`, `o2b.dream-stage.v1`, `o2b.report-snapshot.v1`, continuity records, search schema v7).
+- **Depends on**: Tasks 1, 8, 11 (schema names final).
+
+### Task 14: Integration test - the 1.0 composition
+- **Files**: `tests/e2e/release-1-0-stability.integration.test.ts`.
+- **Acceptance**: one flow exercises tombstone error -> staged dream full cycle -> timezone-rendered brief -> snapshot delta on second digest run -> safeguard abort under a tiny deadline, all on one temp vault.
+- **Depends on**: Tasks 1-12.
+
+Docs phase (playbook phase 5) additionally updates `README.md`, `CHANGELOG.md` (single `[1.0.0]` entry), `docs/cli-reference.md`, `docs/mcp.md`, `docs/how-it-works.md`. Version bump to 1.0.0 happens at phase 9 via `bun run sync-version`.
+
+## Implementation deviations
+
+- **18 aliases, not ~10.** The live registry carried 18 hidden
+ `deprecatedAlias` tools (10 brain + 8 schema); the sweep covers all
+ of them. The advertised `tools/list` count stays 77 - the aliases
+ were hidden, so the sweep shrinks the CALLABLE surface 95 -> 77.
+- **`timed_out` lives in lane task results / journal / CLI JSON**, not
+ in the per-run lane metric payloads as the design sketched: an
+ aborted bridges/clusters run never reaches its own metric write, so
+ a `timed_out` field there could only ever read false.
+- **Output caps scoped to lane error strings** (4096 bytes with an
+ explicit marker) rather than a blanket stream wrapper - the lane is
+ the only place with unbounded captured output.
+- **CLI timeout trip-path is unit-covered, not CLI-tested.** The
+ cooperative deadline needs an injected clock to trip
+ deterministically; across a process boundary that clock cannot be
+ injected, so the abort contract is proven on the core operations and
+ the lane, while CLI tests prove the plumbing (config keys resolve,
+ default behavior unchanged).
+- **Timezone localization is envelope-level** (`timezone` +
+ `local_time` additive fields, human-output line); per-event
+ `*_local` fields on timeline events are deferred.
+- **`stage` also records a `dream_stage` metric**, not only `apply` -
+ more dashboard signal at no cost.
+- **Digest JSON delta rides the tool envelope** (`delta` next to
+ `content`); the digest content's own `schema_version: 1` contract is
+ untouched. The CLI digest appends the Since-last-run block after the
+ markdown rendering.
diff --git a/docs/brainstorm/release-1-0-stability-trust/variants.md b/docs/brainstorm/release-1-0-stability-trust/variants.md
new file mode 100644
index 00000000..c6b9eed6
--- /dev/null
+++ b/docs/brainstorm/release-1-0-stability-trust/variants.md
@@ -0,0 +1,61 @@
+# Release 1.0.0 - Stability & Trust - variant audit trail
+
+Consultant: Claude Code (`claude -p`), single pass, 2026-06-05. Full
+verbatim output in `cli-output/claude.md`; prompt in
+`cli-output/prompt.md`.
+
+## Variant 1: Independent vertical slices (consultant verbatim)
+
+- **Approach**: Each of the five units lands as a self-contained module with its own atomic commit, sharing only small existing primitives (`atomicWriteFileSync`, the `o2b.metrics.v1` writer, `time.ts`). The safeguard is a thin wrapper invoked at each long-running call site; the staged dream pipeline adds an output mode to existing `dream()` rather than a new engine; Unit 5's snapshot-diff and Unit 4's timezone formatter are local utilities threaded through their own render/persist sites. No new cross-unit abstraction is extracted.
+- **Trade-offs**:
+ - Pro: Cleanest fit for TDD with per-unit atomic commits; each unit independently reviewable and revertible.
+ - Pro: Smallest blast radius - byte-compatibility of untouched surfaces is trivially preserved.
+ - Pro: No risk of forking promotion logic, since dream stays the single engine with an added serialization mode.
+ - Con: Units 3 and 5 both implement persisted-artifact + diff mechanics; mild duplication of "manifest, generated_at frontmatter, diff-against-prior" logic.
+ - Con: Timezone presentation (Unit 4) and snapshot rendering (Unit 5) touch overlapping render sites twice instead of once.
+- **Complexity**: medium
+- **Risk**: low
+
+## Variant 2: Shared artifact-and-presentation substrate (consultant verbatim)
+
+- **Approach**: Extract two reusable layers up front - a "persisted bundle + structured snapshot + deterministic diff" core that both the staged dream pipeline (Unit 3) and dual-output reports (Unit 5) build on, and a presentation module where the timezone formatter (Unit 4) and report rendering (Unit 5) share one timestamp/projection path. The safeguard (Unit 2) becomes shared middleware wrapping registered long-running operations. Unit 1's freeze documents these new shared contracts.
+- **Trade-offs**:
+ - Pro: Eliminates duplication across the genuinely overlapping units (3/5 artifacts, 4/5 rendering).
+ - Pro: One diff engine and one presentation contract are easier to test exhaustively and to freeze coherently for 1.0.
+ - Con: Higher coupling; per-unit atomic commits become interdependent (substrate must land before its consumers), straining the TDD-per-unit convention.
+ - Con: Larger blast radius across render sites raises the chance of an accidental byte-compat regression in a frozen surface.
+ - Con: Pressure to over-generalize the bundle abstraction risks the "don't fork the promotion engine" constraint if dream staging drifts toward the shared layer.
+- **Complexity**: large
+- **Risk**: medium
+
+## Variant 3: Contract-registry spine (consultant verbatim)
+
+- **Approach**: Make Unit 1 the architectural spine - build a machine-readable freeze manifest (tool surface, schema versions, config keys/env vars, on-disk formats) that the `doctor` probe reads to flag removed/relied-on surfaces. Units 2-5 then declare their new surfaces (safeguard timeout keys, bundle schema, snapshot schema, timezone config key) into that same registry, so "what is frozen" has one source of truth and the doctor check is data-driven rather than hand-maintained.
+- **Trade-offs**:
+ - Pro: Strongest trust story - the compatibility policy is enforced by a manifest, not prose, and the doctor probe stays accurate as surfaces evolve.
+ - Pro: New 1.0 surfaces are born registered and frozen, preventing drift.
+ - Con: A full contract registry is heavyweight for a single PR; most surfaces are already stable, so much of the registry is descriptive scaffolding with low immediate payoff.
+ - Con: Couples four feature units to a new meta-layer, complicating atomic commits and adding a frozen surface that itself must be maintained forever.
+ - Con: Doctor-as-registry-reader risks scope creep beyond the "callable-name probe or docs guidance" the task scopes.
+- **Complexity**: large
+- **Risk**: medium
+
+## Consultant recommendation (verbatim)
+
+### Recommended: Variant 1
+**Rationale**: The constraints most strongly favor independence - per-unit atomic commits, byte-compatibility on every surface but the 9 aliases, and a single promotion engine all argue against the up-front coupling of Variants 2 and 3. The real overlaps (artifact persistence in Units 3/5, rendering in Units 4/5) are small enough to capture with a shared helper extracted opportunistically inside the slice work, without committing to a substrate or registry whose cost outweighs its one-PR payoff.
+
+## Orchestrator decision
+
+Variant 1 accepted as recommended; no override. Two refinements
+folded into the design (both within the consultant's own framing):
+
+1. **Tombstones** for the removed aliases (a static REMOVED_TOOLS map
+ answering tools/call with the precise replacement) - this is the
+ one element of Variant 3's "data-driven doctor" idea worth its
+ cost, because it lives at a single dispatch point and pays off on
+ every stale client, while the full registry does not clear the bar.
+2. The consultant's own caveat about opportunistic shared helpers is
+ adopted as an explicit rule: if dream-stage and report-snapshot
+ converge on identical bundle mechanics, extract a small helper
+ inside the slice work, never a substrate up front.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index df531d69..98c0f265 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -34,7 +34,7 @@ o2b brain note <text> Append a one-line narrative milestone to Brain/log
o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback; Markdown links follow link_output_format / OBSIDIAN_LINK_FORMAT
o2b brain intent-review Read-only pre-dream review of active signal clusters; --now ISO; --json mirrors brain_intent_review
o2b brain retention Recommendation-only lifecycle review over retired preferences and processed signals; --now ISO; --json mirrors brain_retention
-o2b brain monthly Month-level Brain synthesis over timeline events, transitions, retirements, contradictions, and neglected areas; --month YYYY-MM; --json mirrors brain_monthly_review
+o2b brain monthly Month-level Brain synthesis over timeline events, transitions, retirements, contradictions, and neglected areas; --month YYYY-MM; --json mirrors brain_brief view=monthly
o2b brain query Read helper: by preference, by topic, or by log timestamp
o2b brain agent-query Read source-agent provenance; filters by --agent, --topic, --query, --kind, --limit; --json mirrors brain_agent_query
o2b brain agent-diff Compare source-agent coverage in browse/search/diff/map modes; --json mirrors brain_agent_diff
@@ -221,6 +221,19 @@ o2b search <query> --expand deterministic lex/vec/hyde expansion of a bare que
Wikilinks to frontmatter `aliases:` resolve at index materialization (schema v7): exact paths always win, a real basename is never shadowed, collisions resolve first-wins by sorted path, and `o2b search status` counts the pass via `IndexStats.aliasResolved`. Bridge discovery and clusters also run as maintenance-lane tasks after `reindex`. Self-tuning only changes behavior under `search_self_tuning_enabled` (or `OPEN_SECOND_BRAIN_SEARCH_SELF_TUNING=1`); an explicit `--expand`/`expand` always wins over the tuned default. Every surface appends one run-level record to `Brain/metrics/<surface>.jsonl` - the dashboard data contract documented in `docs/metrics.md`.
+## Stability and trust (since v1.0.0)
+
+```text
+o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apply <run-id> | discard <run-id> | list - staged lifecycle over a persisted proposal bundle; validate/apply exit 1 on drift
+o2b brain doctor gains the removed-tool-reference warning: vault notes, root instruction files, and installed skills naming a tool removed in 1.0.0 are flagged with the replacement
+o2b brain daily | weekly | monthly | morning-brief | timeline
+ gain additive timezone + local_time JSON fields when `timezone:` is configured; storage stays canonical UTC
+o2b brain digest | daily | weekly
+ with report_snapshots_enabled persist Brain/reports/<surface>/<date>.json and report a deterministic Since-last-run delta
+```
+
+Long-running operations (dream, `o2b search index | reindex`, bridges discover, clusters run, the maintenance lane) run under a cooperative safeguard deadline: `safeguard_timeout_seconds` (default 600, `0` disables, env `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`) with per-operation overrides like `safeguard_timeout_dream_seconds`. A tripped deadline aborts at the next checkpoint - between atomic writes - and reports `{ok:false, timed_out:true}` on exit 1; maintenance-lane task results carry `timed_out` per task. The frozen-surface policy lives in `docs/stability.md`; the 0.x to 1.0.0 migration table in `docs/updating.md`.
+
## Vault scope
Single exclusion policy for every vault walker.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index e399343e..3957decf 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -995,6 +995,36 @@ A second brain's value compounds through connections, but until now the graph on
**Every pass reports to one place.** Each feature appends one run-level record to `Brain/metrics/<surface>.jsonl` (`o2b.metrics.v1` envelope) - the stable contract a dashboard reads without importing internals, documented in `docs/metrics.md`.
+## Stability and trust (since v1.0.0)
+
+The first major release froze the public contracts - the advertised
+MCP tool surface, the CLI verb tree, configuration keys, the search
+schema ladder, and every on-disk schema string - under
+`docs/stability.md`, and spent its one breaking change on deleting the
+18 hidden alias tools from the token-diet era. A stale client that
+calls a removed name gets a tombstone naming the exact replacement,
+and `brain_doctor` flags vault-side text that still references one.
+
+Three hardening layers ship alongside the freeze. A cooperative
+safeguard gives every long pass (dream, reindex, bridge discovery,
+communities, the maintenance lane) a deadline checked at natural
+iteration boundaries: Bun runs SQLite synchronously, so the honest
+contract is to abort BETWEEN atomic writes rather than pretend an
+async cancellation. The staged dream pipeline turns the
+self-improvement loop inspectable before anything lands: `stage`
+persists the dry-run plan as a discardable bundle, `validate`
+recomputes it and reports drift, `apply` re-validates with the clock
+it runs with and then executes the one and only promotion engine -
+determinism guarantees the live run performs exactly the reviewed
+plan. And the reporting surfaces become self-comparing: with
+snapshots enabled, each digest / daily / weekly run persists a
+machine-diffable JSON snapshot and reports a deterministic "since
+last run" delta keyed on stable identities, never on array order.
+Presentation grows timezone awareness on the same principle the rest
+of the system follows - storage stays canonical UTC, conversion
+happens at the boundary, and an unconfigured vault renders
+byte-identically.
+
## Safety properties
These are invariants of the system, not configuration to enable.
diff --git a/docs/mcp.md b/docs/mcp.md
index e8f5b1b1..ff0e1666 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -71,19 +71,15 @@ flags for a narrower per-process full server.
`brain_brief`, `brain_analytics`, and `schema_inspect` replaced three
overlapping tool families in v0.34.0; per-view output is identical to the
predecessor tools because dispatch goes to the same handlers. The 18
-predecessor names (`brain_morning_brief`, `brain_daily_brief`,
-`brain_weekly_synthesis`, `brain_monthly_review`, `brain_operator_summary`,
-`brain_digest`, `brain_timeline`, `brain_attention_flows`,
-`brain_belief_evolution`, `brain_concept_synthesis`, `get_active_schema_pack`,
-`list_schema_packs`, `schema_stats`, `schema_lint`, `schema_graph`,
-`schema_explain_type`, `schema_review_orphans`, `reload_schema_pack`) remain
-callable through `tools/call` as deprecated aliases for at least one minor
-release, but are hidden from `tools/list` so clients stop paying for their
-schemas. Migrate by switching to the consolidated tool with the matching
-`view` value; per-view parameters keep their old names (for example
+predecessor names were removed in 1.0.0: calling one answers a precise
+INVALID_PARAMS tombstone naming the replacement tool and `view` (for
+example `brain_digest was removed in 1.0.0; call brain_brief with
+view="digest"`), so a stale client learns the migration from the error
+itself. Per-view parameters keep their old names (for example
`brain_brief` with `view: "daily"` accepts the same `date` argument
`brain_daily_brief` did, and `brain_analytics` with
-`view: "attention_flows"` defaults `operation` to `list`).
+`view: "attention_flows"` defaults `operation` to `list`). The full
+alias-to-replacement table lives in `docs/updating.md`.
`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).
`vault_health` accepts `repo` (string) for plugin manifest validation.
@@ -163,8 +159,8 @@ come back from `resources/list`:
generated digest of confirmed + quarantined preferences plus the
last three retired entries. Auto-regenerated on first read if the
file does not exist yet.
-- `osb://digest/latest` — same body as the `brain_digest` tool's
- default (24h) Markdown window.
+- `osb://digest/latest` — same body as `brain_brief` `view="digest"`
+ in its default (24h) Markdown window.
- `osb://status` — Brain operational snapshot: counts (inbox /
preferences by status / retired / log_days / snapshots), last
`dream` and `apply-evidence` timestamps, and a sanity flag for
@@ -290,7 +286,7 @@ generates deduped triggers from semantic-health and retention data,
`list` / `history` read by effective lifecycle status,
`acknowledge` / `dismiss` / `act` transition one trigger. Cooldown keys
keep the same issue from reappearing while an earlier trigger is open
-or cooling down; `brain_morning_brief` surfaces capped pending
+or cooling down; `brain_brief` `view="morning"` surfaces capped pending
triggers and marks them delivered (once per `trigger_cooldown_days`).
`brain_deep_synthesis` assembles a deterministic topic dossier
diff --git a/docs/metrics.md b/docs/metrics.md
index 07a1c79b..982311f6 100644
--- a/docs/metrics.md
+++ b/docs/metrics.md
@@ -16,7 +16,8 @@ Brain/metrics/
├── bridge_discovery.jsonl
├── communities.jsonl
├── recall_benchmark.jsonl
-└── self_tuning.jsonl
+├── self_tuning.jsonl
+└── dream_stage.jsonl
```
Surface names are lowercase snake_case (`[a-z][a-z0-9_]*`, max 64
@@ -61,6 +62,7 @@ writes, and a metric record is a summary, not a report.
| `communities` | `o2b brain clusters run`, MCP `brain_clusters`, maintenance lane | `communities`, `sizes`, `written`, `removed`, `min_size`, `lane` (lane runs) |
| `recall_benchmark` | `o2b brain benchmark run`, MCP `brain_benchmark` | `total`, `k`, `expand`, `hit_at_k`, `mrr`, `misses` |
| `self_tuning` | `o2b brain tune run`, MCP `brain_tune` | `chosen`, `evaluated`, `best_mrr`, `dataset_hash` |
+| `dream_stage` | `o2b brain dream stage` / `apply`, MCP `brain_dream` (since 1.0.0) | `action` (`stage`/`apply`), `run_id`, `proposals`, `sources`, `changed`; apply adds `new_unconfirmed`, `confirmed`, `retired` counts |
Payload fields marked "(lane runs)" appear only on maintenance-lane
emissions. All fields are additive-optional from a consumer's point
diff --git a/docs/stability.md b/docs/stability.md
new file mode 100644
index 00000000..6f4f1c85
--- /dev/null
+++ b/docs/stability.md
@@ -0,0 +1,94 @@
+# Stability policy
+
+Since 1.0.0, Open Second Brain follows
+[Semantic Versioning](https://semver.org/spec/v2.0.0.html) with the
+contracts below treated as the public API. Anything not listed here is
+an internal detail and may change in any release.
+
+## Frozen contracts
+
+### MCP tool surface
+
+Every tool advertised by `tools/list` (77 tools at 1.0.0) is frozen:
+the tool name, its input schema's existing parameters, and the
+documented meaning of its response fields. New optional parameters and
+new response fields are additive (minor); removing or renaming a tool,
+making a parameter required, or changing a response field's meaning is
+breaking (major). Since 1.0.0 the advertised list and the callable
+surface are the same set - there is no hidden alias layer. Removed
+tools answer `tools/call` with an INVALID_PARAMS tombstone naming the
+replacement for at least one major cycle.
+
+### CLI verb tree
+
+The verb tree in `o2b help` / `src/cli/command-manifest.ts` is frozen:
+existing verbs, their positional forms, their documented flags, their
+exit-code contract (0 success or fail-soft skip, 1 operational
+failure, 2 usage error), and the shape of their `--json` output. New
+verbs, new optional flags, and additive JSON fields are minor.
+
+### Configuration keys and environment variables
+
+Every documented config key and its env mirror keeps its name, type,
+default, and resolution order (environment beats config file).
+Examples frozen at 1.0.0: `vault`, `agent_name`, `timezone`
+(`VAULT_TIMEZONE`), the `search_*` family
+(`OPEN_SECOND_BRAIN_SEARCH_*`), `safeguard_timeout_seconds` and its
+per-operation variants (`OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`), and
+`report_snapshots_enabled` (`OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS`).
+Unknown keys remain warnings, never errors.
+
+### Search index schema
+
+The SQLite search index migrates forward only, one numbered step at a
+time (v7 at 1.0.0). Opening a newer-schema index with an older build
+fails with `SCHEMA_MISMATCH` instead of corrupting it. Removing a
+migration step from the ladder is breaking.
+
+### On-disk format schemas
+
+Every persisted machine-readable format carries an explicit schema
+string, and the reader for version N keeps reading N for at least one
+major cycle after N+1 ships:
+
+| Schema string | File | Since |
+| --- | --- | --- |
+| `o2b.metrics.v1` | `Brain/metrics/<surface>.jsonl` | 0.45.0 |
+| `o2b.tuning.v1` | `Brain/search/tuning.json` | 0.45.0 |
+| `o2b.dream-stage.v1` | `Brain/dream/staged/<run-id>/manifest.json` | 1.0.0 |
+| `o2b.report-snapshot.v1` | `Brain/reports/<surface>/<date>.json` | 1.0.0 |
+| continuity records (versioned envelope) | `Brain/continuity/` | 0.39.0 |
+
+Evolution rule (mirrors the metrics contract in
+[`docs/metrics.md`](metrics.md)): adding optional payload fields is
+compatible; renaming or retyping a field, or changing a record's
+identity semantics, requires a new schema string.
+
+### `Brain/` layout conventions
+
+Generated artifacts carry a frontmatter `kind` plus `generated_at` and
+are regenerated whole per run; hand-written files inside agent-owned
+directories are never modified or deleted by generators. Storage
+timestamps are canonical UTC everywhere (frontmatter, log headings,
+run ids); timezone conversion is strictly a presentation-layer
+concern.
+
+## What counts as breaking
+
+- Removing or renaming anything listed above.
+- Changing a default in a way that alters behavior for an unchanged
+ config file.
+- Tightening validation so previously accepted input is rejected.
+- Changing the meaning (not just the set) of an emitted field.
+
+Breaking changes ship only in a major release, with tombstones or
+documented migrations, and are listed in the upgrade guide
+([`docs/updating.md`](updating.md)).
+
+## What is explicitly NOT frozen
+
+- The exact wording of human-readable (non-JSON) CLI output and error
+ messages.
+- The internal module layout under `src/`.
+- Lint/test tooling, internal scripts, and development workflows.
+- The contents of `docs/brainstorm/` (historical design records).
diff --git a/docs/updating.md b/docs/updating.md
index c75910c6..33c23582 100644
--- a/docs/updating.md
+++ b/docs/updating.md
@@ -6,6 +6,47 @@ git marketplace snapshot). **An update must never break an existing install or
the agent.** This document is the contract that guarantees it, for both
operators and any agent that edits the plugin.
+## Upgrading from 0.x to 1.0.0
+
+1.0.0 is the first major release and ships exactly one breaking
+change: the 18 hidden MCP alias tools left over from the token-diet
+consolidation are removed. They were already absent from `tools/list`;
+since 1.0.0 calling one through `tools/call` answers an INVALID_PARAMS
+tombstone naming the replacement instead of executing. Everything else
+- CLI verbs, config keys, on-disk formats, the search schema ladder -
+is unchanged and now formally frozen under the stability policy
+([`docs/stability.md`](stability.md)).
+
+Migrate by switching each removed name to its consolidated tool with
+the matching `view` argument; every other parameter keeps its old name
+and meaning:
+
+| Removed tool | Replacement |
+| --- | --- |
+| `brain_digest` | `brain_brief` with `view: "digest"` |
+| `brain_daily_brief` | `brain_brief` with `view: "daily"` |
+| `brain_morning_brief` | `brain_brief` with `view: "morning"` |
+| `brain_weekly_synthesis` | `brain_brief` with `view: "weekly"` |
+| `brain_monthly_review` | `brain_brief` with `view: "monthly"` |
+| `brain_operator_summary` | `brain_brief` with `view: "operator"` |
+| `brain_timeline` | `brain_analytics` with `view: "timeline"` |
+| `brain_attention_flows` | `brain_analytics` with `view: "attention_flows"` |
+| `brain_belief_evolution` | `brain_analytics` with `view: "belief_evolution"` |
+| `brain_concept_synthesis` | `brain_analytics` with `view: "concept_synthesis"` |
+| `get_active_schema_pack` | `schema_inspect` with `view: "active_pack"` |
+| `list_schema_packs` | `schema_inspect` with `view: "packs"` |
+| `schema_stats` | `schema_inspect` with `view: "stats"` |
+| `schema_lint` | `schema_inspect` with `view: "lint"` |
+| `schema_graph` | `schema_inspect` with `view: "graph"` |
+| `schema_explain_type` | `schema_inspect` with `view: "explain_type"` |
+| `schema_review_orphans` | `schema_inspect` with `view: "orphans"` |
+| `reload_schema_pack` | `schema_inspect` with `view: "active_pack"` |
+
+`o2b brain doctor` scans your vault-side surfaces (Brain notes, root
+instruction files such as `CLAUDE.md`/`AGENTS.md`, installed
+`.claude/skills/`) and warns with the exact replacement for any stale
+reference it finds (`removed-tool-reference`).
+
## For operators
Normal updates need no manual steps:
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 27b3c190..0257c212 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.45.0",
+ "version": "1.0.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 05cd5ae8..51247436 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.45.0",
+ "version": "1.0.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 9db70b93..3aaedbed 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.45.0"
+version: "1.0.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 0b2cf0a8..dba6086f 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.45.0",
+ "version": "1.0.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 9db70b93..3aaedbed 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.45.0"
+version: "1.0.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index c905d895..cd44898d 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.45.0"
+version = "1.0.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/skills/brain-memory/SKILL.md b/skills/brain-memory/SKILL.md
index 4d22a4df..a8291ad3 100644
--- a/skills/brain-memory/SKILL.md
+++ b/skills/brain-memory/SKILL.md
@@ -84,7 +84,7 @@ Mixed-language session → match the most recent user message at the time the ar
- `brain_query --preference pref-foo` — full preference frontmatter + every evidence record in `Brain/log/*` referencing it.
- `brain_query --topic <slug>` — all artifacts (signals, current preference, retired ones) by topic.
- `brain_query --since <ISO>` — recent log events of any type.
-- `brain_digest` — daily summary of what `dream` did: new unconfirmed, confirmations, retirements, confidence shifts, contradictions.
+- `brain_brief` (`view="digest"`) — daily summary of what `dream` did: new unconfirmed, confirmations, retirements, confidence shifts, contradictions.
## CLI fallback
diff --git a/skills/open-second-brain/SKILL.md b/skills/open-second-brain/SKILL.md
index e00fe6a3..773d65fb 100644
--- a/skills/open-second-brain/SKILL.md
+++ b/skills/open-second-brain/SKILL.md
@@ -11,7 +11,7 @@ Use this skill when a user asks an agent to use, configure, inspect, or maintain
Open Second Brain owns one top-level directory in the vault: `Brain/`. Everything the agent writes lives under it.
-- **`Brain/`** - agent-writable observing memory. Taste signals, accreted preferences (unconfirmed → confirmed → retired), evidence log, snapshots. Operations go through MCP tools `brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_digest`, `brain_query`, `brain_doctor` - see the `brain-memory` skill for the calling protocol. CLI counterparts: `o2b brain *`.
+- **`Brain/`** - agent-writable observing memory. Taste signals, accreted preferences (unconfirmed → confirmed → retired), evidence log, snapshots. Operations go through MCP tools `brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_brief`, `brain_query`, `brain_doctor` - see the `brain-memory` skill for the calling protocol. CLI counterparts: `o2b brain *`.
- **`Brain/payments/`** - Pay Memory subtree (optional). Receipts, generated-asset notes, drafts, reports, policies, pending-approval requests. Agents use `payment_*` MCP tools when they make paid API calls. Same write contract as the rest of `Brain/` - one root.
- **User-authored notes** - the operator's daily journal, weekly notes, project notes, etc. Folder names are operator-chosen. The agent reads these paths only when they appear under `notes.read_paths` in `Brain/_brain.yaml`; the agent never writes to them.
diff --git a/skills/schema-author/SKILL.md b/skills/schema-author/SKILL.md
index b9384e0a..3173700f 100644
--- a/skills/schema-author/SKILL.md
+++ b/skills/schema-author/SKILL.md
@@ -9,9 +9,9 @@ Use this skill when a task changes the active Brain schema pack in `Brain/_brain
## Workflow
-1. Inspect the active schema pack with `get_active_schema_pack` or `o2b brain schema --json`.
-2. Check current usage and findings with `schema_stats`, `schema_lint`, and `schema_review_orphans`.
-3. Explain candidate tokens with `schema_explain_type` before renaming or deleting them.
+1. Inspect the active schema pack with `schema_inspect` (`view="active_pack"`) or `o2b brain schema --json`.
+2. Check current usage and findings with `schema_inspect` views `stats`, `lint`, and `orphans`.
+3. Explain candidate tokens with `schema_inspect` (`view="explain_type"`) before renaming or deleting them.
4. Apply schema changes only through `schema_apply_mutations` or `o2b brain schema apply --mutation ...` so writes are locked, atomic, and audited.
5. Re-run lint/stats after mutation and report changed tokens plus any remaining findings.
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index ae709be6..56039997 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -12,7 +12,7 @@ export const BRAIN_HELP = `usage: o2b brain <verb> [args...]
Brain verbs (observing memory):
init Bootstrap <vault>/Brain/ (idempotent; --force overwrites)
feedback Record a taste signal (--topic, --signal, --principle)
- dream Run the deterministic dreaming pass (idempotent)
+ dream Deterministic dreaming pass; stage/validate/apply staged bundles
apply-evidence Log a real-work application of a preference
note Append a one-line narrative milestone to Brain/log/today
digest Render the recent-changes digest (markdown or --json)
@@ -127,8 +127,12 @@ export const VERB_HELP: Record<string, string> = {
" [--force-confirmed] [--vault <path>] [--json]\n" +
"Creates a `sig-*.md` in Brain/inbox/. With --force-confirmed also creates a `pref-*.md`.\n",
dream:
- "usage: o2b brain dream [--vault <path>] [--dry-run] [--now <ISO-8601>] [--json]\n" +
- "Runs the deterministic dreaming algorithm. Idempotent on rerun.\n",
+ "usage: o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apply <run-id> |\n" +
+ " discard <run-id> | list [--now <ISO-8601>] [--agent <name>] [--vault <path>] [--json]\n" +
+ "Runs the deterministic dreaming algorithm (idempotent), or manages the staged\n" +
+ "lifecycle: stage persists a reviewable proposal bundle under Brain/dream/staged/,\n" +
+ "validate proves the vault has not drifted, apply re-validates then runs the same\n" +
+ "engine live, discard drops the bundle.\n",
"apply-evidence":
"usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated|outdated\n" +
" [--agent <name>] [--note <text>] [--vault <path>] [--json]\n" +
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index 6ebf7d7f..4f5e186e 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -23,7 +23,9 @@
* file because they are tiny and called by every verb.
*/
-import { resolveVault } from "../../core/config.ts";
+import { resolveTimezone, resolveVault } from "../../core/config.ts";
+import { formatLocalTimestamp } from "../../core/brain/present-time.ts";
+import { isoSecond } from "../../core/brain/time.ts";
import { CliError, parseFlags, type FlagsSchema } from "../argparse.ts";
import { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
@@ -75,3 +77,14 @@ export {
renderQueryLogText,
} from "./query-render.ts";
export { diffSummary, readSingleLine, type DiffSummary } from "./rollback-prompt.ts";
+
+/**
+ * Timezone presentation (t_2ccadc6a): additive `timezone` +
+ * `local_time` fields for JSON envelopes when the operator configured
+ * an IANA zone; empty object (byte-identical output) otherwise.
+ */
+export function localTimeFields(configPath: string | null): Record<string, string> {
+ const tz = resolveTimezone(configPath ?? undefined);
+ if (tz === null) return {};
+ return { timezone: tz, local_time: formatLocalTimestamp(isoSecond(new Date()), tz) };
+}
diff --git a/src/cli/brain/verbs/bridges.ts b/src/cli/brain/verbs/bridges.ts
index 21c0bf84..83d5d0ef 100644
--- a/src/cli/brain/verbs/bridges.ts
+++ b/src/cli/brain/verbs/bridges.ts
@@ -25,6 +25,11 @@ import {
BRIDGE_DEFAULT_MIN_SIMILARITY,
} from "../../../core/brain/link-graph/bridge-discovery.ts";
import { appendMetric } from "../../../core/brain/metrics.ts";
+import {
+ createSafeguard,
+ resolveSafeguardTimeoutMs,
+ SafeguardTimeoutError,
+} from "../../../core/brain/safeguard.ts";
import { loadSchemaPack } from "../../../core/brain/schema-pack.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
@@ -130,6 +135,10 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {
...(max !== undefined ? { maxProposals: max } : {}),
...(minSimilarity !== undefined ? { minSimilarity } : {}),
dismissed,
+ safeguard: createSafeguard({
+ operation: "bridges",
+ timeoutMs: resolveSafeguardTimeoutMs("bridges", config ?? undefined),
+ }),
});
const path = writeBridgeProposals(vault, report, { now });
try {
@@ -171,9 +180,10 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {
await store.close();
}
} catch (exc) {
+ const timedOut = exc instanceof SafeguardTimeoutError;
const message = `bridges ${action} failed: ${(exc as Error).message ?? exc}`;
if (asJson) {
- okJson({ ok: false, message });
+ okJson({ ok: false, message, ...(timedOut ? { timed_out: true } : {}) });
return 1;
}
return fail(message);
diff --git a/src/cli/brain/verbs/clusters.ts b/src/cli/brain/verbs/clusters.ts
index 14a67a29..eaf0500f 100644
--- a/src/cli/brain/verbs/clusters.ts
+++ b/src/cli/brain/verbs/clusters.ts
@@ -19,6 +19,11 @@ import {
COMMUNITY_DEFAULT_MIN_SIZE,
} from "../../../core/brain/link-graph/communities.ts";
import { appendMetric } from "../../../core/brain/metrics.ts";
+import {
+ createSafeguard,
+ resolveSafeguardTimeoutMs,
+ SafeguardTimeoutError,
+} from "../../../core/brain/safeguard.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
@@ -104,7 +109,14 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
const now = new Date();
try {
- const communities = detectCommunities(store, minSize !== undefined ? { minSize } : {});
+ const safeguard = createSafeguard({
+ operation: "clusters",
+ timeoutMs: resolveSafeguardTimeoutMs("clusters", config ?? undefined),
+ });
+ const communities = detectCommunities(store, {
+ ...(minSize !== undefined ? { minSize } : {}),
+ safeguard,
+ });
const result = materializeClusterNotes(vault, communities, { store, now });
try {
appendMetric(vault, {
@@ -146,9 +158,10 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
await store.close();
}
} catch (exc) {
+ const timedOut = exc instanceof SafeguardTimeoutError;
const message = `clusters ${action} failed: ${(exc as Error).message ?? exc}`;
if (asJson) {
- okJson({ ok: false, message });
+ okJson({ ok: false, message, ...(timedOut ? { timed_out: true } : {}) });
return 1;
}
return fail(message);
diff --git a/src/cli/brain/verbs/digest.ts b/src/cli/brain/verbs/digest.ts
index 82070644..7e8254a7 100644
--- a/src/cli/brain/verbs/digest.ts
+++ b/src/cli/brain/verbs/digest.ts
@@ -1,4 +1,6 @@
import { defaultConfigPath, resolveLinkOutputFormat } from "../../../core/config.ts";
+import { captureReportDelta, renderReportDelta } from "../../../core/brain/report-snapshot.ts";
+import { isoDate } from "../../../core/brain/time.ts";
import { renderDigest, type RenderDigestOptions } from "../../../core/brain/digest.ts";
import { parse, fail, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";
@@ -56,7 +58,35 @@ export async function cmdBrainDigest(argv: string[]): Promise<number> {
}
if (result.empty && flags["silent-if-empty"]) return 2;
+
+ // Dual-output (t_00eece5d): snapshot the structured JSON digest and
+ // report the run-over-run delta when report snapshots are enabled.
+ let delta = null;
+ const digestDate = isoDate(untilDate ?? new Date());
+ const jsonContent = flags["json"]
+ ? result.content
+ : renderDigest(vault, { ...opts, format: "json" }).content;
+ try {
+ delta = captureReportDelta(
+ vault,
+ "digest",
+ digestDate,
+ JSON.parse(jsonContent),
+ config ? { configPath: config } : {},
+ );
+ } catch {
+ // Snapshots are observability, not correctness.
+ }
+
+ if (flags["json"] && delta !== null) {
+ const parsed = JSON.parse(result.content) as Record<string, unknown>;
+ process.stdout.write(JSON.stringify({ ...parsed, delta }, null, 2) + "\n");
+ return 0;
+ }
process.stdout.write(result.content);
if (!result.content.endsWith("\n")) process.stdout.write("\n");
+ if (!flags["json"] && delta !== null) {
+ process.stdout.write("\n" + renderReportDelta(delta) + "\n");
+ }
return 0;
}
diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.ts
index 531a8193..33d00447 100644
--- a/src/cli/brain/verbs/dream.ts
+++ b/src/cli/brain/verbs/dream.ts
@@ -1,15 +1,57 @@
+/**
+ * `o2b brain dream [run] [--dry-run] | stage | validate <run-id> |
+ * apply <run-id> | discard <run-id> | list` - the learning pass plus
+ * the staged lifecycle (t_ae8a8ec0). `run` (the default, kept
+ * positional-free for back-compat) promotes inline; `stage` persists
+ * a reviewable proposal bundle; `validate` proves the vault has not
+ * drifted; `apply` re-validates and runs the same engine live;
+ * `discard` drops the bundle.
+ *
+ * Exit codes: 0 on success, 1 on operational failure (including a
+ * failed validation - scripts gate on it), 2 on usage errors.
+ */
+
import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { dream } from "../../../core/brain/dream.ts";
-import { parse, fail, ok, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";
+import {
+ applyDreamBundle,
+ discardDreamBundle,
+ listDreamBundles,
+ stageDream,
+ validateDreamBundle,
+} from "../../../core/brain/dream-stage.ts";
+import {
+ createSafeguard,
+ resolveSafeguardTimeoutMs,
+ SafeguardTimeoutError,
+} from "../../../core/brain/safeguard.ts";
+import { parse, fail, ok, okJson, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain dream [run] [--dry-run] | stage | validate <run-id> | " +
+ "apply <run-id> | discard <run-id> | list [--now ISO] [--agent A] [--vault <path>] [--json]";
+
+const ACTIONS = new Set(["run", "stage", "validate", "apply", "discard", "list"]);
export async function cmdBrainDream(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
+ const { flags, positional } = parse(argv, {
vault: { type: "string" },
"dry-run": { type: "boolean" },
now: { type: "string" },
agent: { type: "string" },
json: { type: "boolean" },
});
+ const asJson = flags["json"] === true;
+ const action = positional[0] ?? "run";
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
+ const needsRunId = action === "validate" || action === "apply" || action === "discard";
+ if (needsRunId ? positional.length !== 2 : positional.length > 1) {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
@@ -28,14 +70,129 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
const { value: now, error: nowErr } = parseOptionalIsoDate(flags, "now");
if (nowErr) return fail(nowErr);
+ const guard = () =>
+ createSafeguard({
+ operation: "dream",
+ timeoutMs: resolveSafeguardTimeoutMs("dream", config ?? undefined),
+ });
+
+ try {
+ if (action === "stage") {
+ const bundle = stageDream(vault, {
+ now: now ?? new Date(),
+ safeguard: guard(),
+ ...(agent ? { agentName: agent } : {}),
+ });
+ if (asJson) {
+ okJson({
+ run_id: bundle.runId,
+ plan: bundle.plan,
+ sources: bundle.sources.length,
+ dir: `Brain/dream/staged/${bundle.runId}`,
+ });
+ } else {
+ ok(`staged: ${bundle.runId} -> Brain/dream/staged/${bundle.runId}/`);
+ ok(`planned changes: ${bundle.plan.changed ? "yes" : "none"}`);
+ }
+ return 0;
+ }
+
+ if (action === "validate" || action === "apply") {
+ const runId = positional[1]!;
+ const stageOpts = {
+ now: now ?? new Date(),
+ safeguard: guard(),
+ ...(agent ? { agentName: agent } : {}),
+ };
+ if (action === "validate") {
+ const verdict = validateDreamBundle(vault, runId, stageOpts);
+ if (asJson) okJson({ run_id: runId, valid: verdict.valid, drift: verdict.drift });
+ else if (verdict.valid) ok(`validate ${runId}: clean`);
+ else {
+ ok(`validate ${runId}: DRIFT`);
+ for (const line of verdict.drift) ok(` ${line}`);
+ }
+ return verdict.valid ? 0 : 1;
+ }
+ const outcome = applyDreamBundle(vault, runId, stageOpts);
+ if (asJson) {
+ okJson({
+ run_id: runId,
+ applied: outcome.applied,
+ drift: outcome.validation.drift,
+ ...(outcome.summary !== undefined
+ ? {
+ changed: outcome.summary.changed,
+ new_unconfirmed: outcome.summary.new_unconfirmed,
+ confirmed: outcome.summary.confirmed,
+ }
+ : {}),
+ });
+ } else if (outcome.applied) {
+ ok(`apply ${runId}: done (changed: ${outcome.summary!.changed})`);
+ } else {
+ ok(`apply ${runId}: ABORTED - bundle drifted, re-stage first`);
+ for (const line of outcome.validation.drift) ok(` ${line}`);
+ }
+ return outcome.applied ? 0 : 1;
+ }
+
+ if (action === "discard") {
+ const runId = positional[1]!;
+ const removed = discardDreamBundle(vault, runId);
+ if (asJson) okJson({ run_id: runId, removed });
+ else ok(removed ? `discarded ${runId}` : `no staged bundle named ${runId}`);
+ return 0;
+ }
+
+ if (action === "list") {
+ const bundles = listDreamBundles(vault);
+ if (asJson) {
+ okJson({
+ bundles: bundles.map((b) => ({
+ run_id: b.runId,
+ status: b.status,
+ staged_at: b.stagedAt,
+ proposals: b.proposals,
+ sources: b.sources,
+ })),
+ });
+ } else if (bundles.length === 0) {
+ ok("no dream bundles - run: o2b brain dream stage");
+ } else {
+ for (const b of bundles) {
+ ok(`${b.runId} ${b.status} staged ${b.stagedAt} ${b.proposals} proposal(s)`);
+ }
+ }
+ return 0;
+ }
+ } catch (exc) {
+ const timedOut = exc instanceof SafeguardTimeoutError;
+ if (asJson) {
+ okJson({
+ ok: false,
+ message: `dream ${action} failed: ${(exc as Error).message ?? exc}`,
+ ...(timedOut ? { timed_out: true } : {}),
+ });
+ return 1;
+ }
+ return fail(`dream ${action} failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ // action === "run": the legacy inline pass.
let summary;
try {
summary = dream(vault, {
...(now !== null ? { now } : {}),
dryRun: Boolean(flags["dry-run"]),
...(agent ? { agentName: agent } : {}),
+ safeguard: guard(),
});
} catch (exc) {
+ if (exc instanceof SafeguardTimeoutError && asJson) {
+ okJson({ ok: false, timed_out: true, message: exc.message });
+ return 1;
+ }
return fail(`dream failed: ${(exc as Error).message ?? exc}`);
}
@@ -43,7 +200,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
process.stderr.write(`warning: ${w.code}: ${w.message}\n`);
}
- if (flags["json"]) {
+ if (asJson) {
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
return 0;
}
diff --git a/src/cli/brain/verbs/maintenance.ts b/src/cli/brain/verbs/maintenance.ts
index c008089a..25e2be38 100644
--- a/src/cli/brain/verbs/maintenance.ts
+++ b/src/cli/brain/verbs/maintenance.ts
@@ -25,6 +25,7 @@ import {
materializeClusterNotes,
} from "../../../core/brain/link-graph/communities.ts";
import { appendMetric } from "../../../core/brain/metrics.ts";
+import { createSafeguard, resolveSafeguardTimeoutMs } from "../../../core/brain/safeguard.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import { Store } from "../../../core/search/store.ts";
import { currentLease, MAINTENANCE_LEASE_NAME } from "../../../core/brain/maintenance/lease.ts";
@@ -113,6 +114,14 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
const holder =
((flags["agent"] as string | undefined)?.trim() || resolveAgentName(config)) +
`@${process.pid}`;
+ // One fresh deadline per lane task: each long pass gets its own
+ // budget (per-op key -> global -> default), created lazily so the
+ // clock starts when the task starts, not when the lane is gated.
+ const laneSafeguard = (operation: "dream" | "reindex" | "bridges" | "clusters") =>
+ createSafeguard({
+ operation,
+ timeoutMs: resolveSafeguardTimeoutMs(operation, config ?? undefined),
+ });
const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });
const result = await runMaintenance(vault, {
now,
@@ -124,13 +133,13 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
{
name: "dream",
run: async () => {
- dream(vault, { now });
+ dream(vault, { now, safeguard: laneSafeguard("dream") });
},
},
{
name: "reindex",
run: async () => {
- await indexVault(searchConfig);
+ await indexVault(searchConfig, { safeguard: laneSafeguard("reindex") });
},
},
// Link-recall-intelligence passes ride the same lease, after
@@ -143,6 +152,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
try {
const report = discoverBridges(store, {
dismissed: readDismissedBridges(vault),
+ safeguard: laneSafeguard("bridges"),
});
writeBridgeProposals(vault, report, { now });
try {
@@ -169,7 +179,9 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
run: async () => {
const store = await Store.open(searchConfig, { mode: "read" });
try {
- const communities = detectCommunities(store, {});
+ const communities = detectCommunities(store, {
+ safeguard: laneSafeguard("clusters"),
+ });
const materialized = materializeClusterNotes(vault, communities, { store, now });
try {
appendMetric(vault, {
diff --git a/src/cli/brain/verbs/monthly.ts b/src/cli/brain/verbs/monthly.ts
index d4e7cfa9..20e16f11 100644
--- a/src/cli/brain/verbs/monthly.ts
+++ b/src/cli/brain/verbs/monthly.ts
@@ -3,7 +3,7 @@ import {
buildMonthlyReview,
normalizeMonthlyReviewMonth,
} from "../../../core/brain/monthly-review.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
const MONTH_RE = /^\d{4}-\d{2}$/;
@@ -24,7 +24,7 @@ export async function cmdBrainMonthly(argv: string[]): Promise<number> {
const report = buildMonthlyReview(vault, month ? { month } : {});
if (flags["json"]) {
- process.stdout.write(JSON.stringify(report, null, 2) + "\n");
+ process.stdout.write(JSON.stringify({ ...report, ...localTimeFields(config) }, null, 2) + "\n");
return 0;
}
diff --git a/src/cli/brain/verbs/morning-brief.ts b/src/cli/brain/verbs/morning-brief.ts
index 8c3a4011..857422dc 100644
--- a/src/cli/brain/verbs/morning-brief.ts
+++ b/src/cli/brain/verbs/morning-brief.ts
@@ -5,7 +5,7 @@ import {
renderTriggerBriefSection,
} from "../../../core/brain/triggers/brief.ts";
import { parseOptionalNumberFlag } from "../../coerce.ts";
-import { fail, parse, resolveBrainVault } from "../helpers.ts";
+import { fail, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
/**
* `o2b brain morning-brief` - render a read-only session-start summary:
@@ -91,7 +91,9 @@ export async function cmdBrainMorningBrief(argv: string[]): Promise<number> {
}
: {}),
};
- process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
+ process.stdout.write(
+ JSON.stringify({ ...payload, ...localTimeFields(config) }, null, 2) + "\n",
+ );
} else {
const base = brief.text.length > 0 ? brief.text : "(nothing to surface)";
const text =
diff --git a/src/cli/brain/verbs/temporal-daily.ts b/src/cli/brain/verbs/temporal-daily.ts
index 19c46190..b6676934 100644
--- a/src/cli/brain/verbs/temporal-daily.ts
+++ b/src/cli/brain/verbs/temporal-daily.ts
@@ -2,7 +2,8 @@ import { defaultConfigPath } from "../../../core/config.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { buildDailyBrief } from "../../../core/brain/temporal/daily-brief.ts";
import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
+import { captureReportDelta, renderReportDelta } from "../../../core/brain/report-snapshot.ts";
const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -33,8 +34,21 @@ export async function cmdBrainDaily(argv: string[]): Promise<number> {
throw exc;
}
+ const delta = captureReportDelta(
+ vault,
+ "daily",
+ brief.date,
+ brief,
+ config ? { configPath: config } : {},
+ );
if (flags["json"]) {
- process.stdout.write(JSON.stringify(brief, null, 2) + "\n");
+ process.stdout.write(
+ JSON.stringify(
+ { ...brief, ...(delta !== null ? { delta } : {}), ...localTimeFields(config) },
+ null,
+ 2,
+ ) + "\n",
+ );
return 0;
}
@@ -51,6 +65,7 @@ export async function cmdBrainDaily(argv: string[]): Promise<number> {
process.stdout.write(` evidence applied: ${brief.vaultDelta.evidenceApplied}\n`);
process.stdout.write(` evidence violated: ${brief.vaultDelta.evidenceViolated}\n`);
process.stdout.write(` status transitions: ${brief.statusTransitions.length}\n`);
+ if (delta !== null) process.stdout.write(renderReportDelta(delta) + "\n");
process.stdout.write(` source pointers: ${brief.sourcePointers.length}\n`);
return 0;
}
diff --git a/src/cli/brain/verbs/temporal-timeline.ts b/src/cli/brain/verbs/temporal-timeline.ts
index 15ba83ac..31ab3b48 100644
--- a/src/cli/brain/verbs/temporal-timeline.ts
+++ b/src/cli/brain/verbs/temporal-timeline.ts
@@ -2,7 +2,7 @@ import { defaultConfigPath } from "../../../core/config.ts";
import { isBrainLogEventKind, type BrainLogEventKind } from "../../../core/brain/types.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { selectEvents } from "../../../core/brain/temporal/select-events.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
/**
* `o2b brain timeline [--vault PATH] [--pref-id ID] [--topic SLUG]
@@ -69,8 +69,11 @@ export async function cmdBrainTimeline(argv: string[]): Promise<number> {
if (flags["json"]) {
process.stdout.write(
- JSON.stringify({ window: index.window, total: events.length, events: sliced }, null, 2) +
- "\n",
+ JSON.stringify(
+ { window: index.window, total: events.length, events: sliced, ...localTimeFields(config) },
+ null,
+ 2,
+ ) + "\n",
);
return 0;
}
diff --git a/src/cli/brain/verbs/temporal-weekly.ts b/src/cli/brain/verbs/temporal-weekly.ts
index b51442dc..28437ad6 100644
--- a/src/cli/brain/verbs/temporal-weekly.ts
+++ b/src/cli/brain/verbs/temporal-weekly.ts
@@ -1,8 +1,9 @@
import { defaultConfigPath } from "../../../core/config.ts";
+import { captureReportDelta, renderReportDelta } from "../../../core/brain/report-snapshot.ts";
import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";
import { buildWeeklySynthesis } from "../../../core/brain/temporal/weekly-brief.ts";
import { loadTemporalConfigSafe } from "../../../core/brain/policy.ts";
-import { CliError, parse, resolveBrainVault } from "../helpers.ts";
+import { CliError, parse, resolveBrainVault, localTimeFields } from "../helpers.ts";
const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -31,8 +32,21 @@ export async function cmdBrainWeekly(argv: string[]): Promise<number> {
throw exc;
}
+ const delta = captureReportDelta(
+ vault,
+ "weekly",
+ weekEnd,
+ synth,
+ config ? { configPath: config } : {},
+ );
if (flags["json"]) {
- process.stdout.write(JSON.stringify(synth, null, 2) + "\n");
+ process.stdout.write(
+ JSON.stringify(
+ { ...synth, ...(delta !== null ? { delta } : {}), ...localTimeFields(config) },
+ null,
+ 2,
+ ) + "\n",
+ );
return 0;
}
@@ -52,6 +66,7 @@ export async function cmdBrainWeekly(argv: string[]): Promise<number> {
` ${c.at} ${c.kind}${c.prefId ? ` ${c.prefId}` : ""}${c.reason ? ` (${c.reason})` : ""}\n`,
);
}
+ if (delta !== null) process.stdout.write(renderReportDelta(delta) + "\n");
return 0;
}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 4ce08fed..62ed7cb1 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -87,7 +87,10 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
[
command("init", "Bootstrap Brain skeleton"),
command("feedback", "Record a taste signal"),
- command("dream", "Run deterministic consolidation"),
+ command(
+ "dream",
+ "Run deterministic consolidation; staged lifecycle via stage/validate/apply",
+ ),
command("apply-evidence", "Record preference evidence"),
command("note", "Append a narrative milestone"),
command("digest", "Render recent Brain transitions"),
diff --git a/src/cli/search.ts b/src/cli/search.ts
index d2da10a8..ea6245ec 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -14,6 +14,11 @@
*/
import { defaultConfigPath, resolveVault } from "../core/config.ts";
+import {
+ createSafeguard,
+ resolveSafeguardTimeoutMs,
+ SafeguardTimeoutError,
+} from "../core/brain/safeguard.ts";
import {
captureRecallFeedback,
indexCheck,
@@ -104,6 +109,14 @@ export async function handleSearchSubcommand(argv: ReadonlyArray<string>): Promi
process.stderr.write(`error: ${e.message}\n`);
return 2;
}
+ if (e instanceof SafeguardTimeoutError) {
+ // Operational failure with a precise cause: the cooperative
+ // deadline tripped at a checkpoint (t_06784b8d). Search verbs
+ // report errors as stderr text regardless of --json, so the
+ // timeout follows the same convention.
+ process.stderr.write(`error: ${e.message} [SAFEGUARD_TIMEOUT]\n`);
+ return 1;
+ }
if (e instanceof SearchError) {
process.stderr.write(`error: ${e.message} [${e.code}]\n`);
return e.code === "INVALID_INPUT" ? 2 : 1;
@@ -662,7 +675,12 @@ async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<number> {
const cfg = resolveConfig(flags);
const events: IndexProgressEvent[] = [];
+ const safeguard = createSafeguard({
+ operation: "reindex",
+ timeoutMs: resolveSafeguardTimeoutMs("reindex", flags["config"] as string | undefined),
+ });
const stats = await indexVault(cfg, {
+ safeguard,
embeddings: flags["embeddings"] === true,
force: flags["force"] === true,
forceCost: flags["force-cost"] === true,
@@ -752,6 +770,10 @@ async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {
}
const cfg = resolveConfig(flags);
const stats = await reindexVault(cfg, {
+ safeguard: createSafeguard({
+ operation: "reindex",
+ timeoutMs: resolveSafeguardTimeoutMs("reindex", flags["config"] as string | undefined),
+ }),
embeddings: flags["embeddings"] === true,
forceCost: flags["force-cost"] === true,
onFile: flags["verbose"] ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`) : undefined,
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 9df50dc2..e83fa184 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -36,9 +36,10 @@
* the existing `doctor` legacy command on an empty vault.
*/
-import { existsSync, readdirSync } from "node:fs";
-import { join } from "node:path";
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+import { REMOVED_TOOLS } from "../removed-surfaces.ts";
import { extractWikilinks, listVaultBasenames, parseFrontmatter } from "../vault.ts";
import { resolveVaultScope } from "../vault-scope/index.ts";
import { buildBacklinkIndex } from "./backlinks.ts";
@@ -295,6 +296,18 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
// to see it without failing the run.
checkBrokenBacklinks(vault, issues, knownBasenames);
+ // 8b (1.0.0). Removed-surface references — Brain notes, root
+ // instruction files, and installed skill files that still name
+ // an MCP tool deleted in the 1.0.0 deprecation sweep. One
+ // warning per file, naming each replacement, so an operator
+ // upgrading an old vault learns the migration from the doctor
+ // output. Best-effort and fail-soft like every other lint.
+ try {
+ checkRemovedToolReferences(vault, issues);
+ } catch {
+ /* doctor never throws */
+ }
+
// 9. Hygiene lints — duplicate prefs, low-evidence confirmed, pinned
// without recent evidence, malformed apply-evidence ranges,
// orphan apply-evidence artifacts. Each is non-blocking (warning
@@ -1288,3 +1301,92 @@ function collectAllBasenames(vault: string): ReadonlySet<string> {
// invariants ultimately bottom out in the same parse pipeline as the
// dream loop.
void parseFrontmatter;
+
+// ---------------------------------------------------------------------------
+// Removed-surface references (1.0.0 deprecation sweep)
+// ---------------------------------------------------------------------------
+
+/** Word-boundary regex per removed tool name, compiled once. */
+const REMOVED_TOOL_PATTERNS: ReadonlyArray<{ name: string; pattern: RegExp }> = Object.freeze(
+ Object.keys(REMOVED_TOOLS).map((name) => ({
+ name,
+ // \b treats `_` as a word character, so `my_brain_digestion` does
+ // not match `brain_digest` but `call brain_digest.` does.
+ pattern: new RegExp(`\\b${name}\\b`),
+ })),
+);
+
+/** Hard cap so a pathological vault cannot flood the doctor report. */
+const REMOVED_TOOL_MAX_WARNINGS = 50;
+
+/**
+ * Scan vault-side text surfaces for references to MCP tools removed
+ * in 1.0.0. Scope is exactly what the doctor can see locally:
+ *
+ * - every Markdown file under `Brain/` (recursive),
+ * - root instruction files (`CLAUDE.md`, `AGENTS.md`),
+ * - installed skills under `.claude/skills/` (recursive `.md`).
+ *
+ * One warning per file lists every removed name it mentions with the
+ * replacement spelling, mirroring the server-side tombstone error.
+ */
+function checkRemovedToolReferences(vault: string, issues: DoctorIssue[]): void {
+ const candidates: string[] = [];
+ const dirs = brainDirs(vault);
+ collectMarkdownFiles(dirs.brain, candidates);
+ for (const name of ["CLAUDE.md", "AGENTS.md"]) {
+ const p = join(vault, name);
+ try {
+ if (existsSync(p) && statSync(p).isFile()) candidates.push(p);
+ } catch {
+ // One unreadable root file must not disable the whole scan.
+ }
+ }
+ collectMarkdownFiles(join(vault, ".claude", "skills"), candidates);
+
+ let emitted = 0;
+ for (const path of candidates) {
+ if (emitted >= REMOVED_TOOL_MAX_WARNINGS) return;
+ let body: string;
+ try {
+ body = readFileSync(path, "utf8");
+ } catch {
+ continue;
+ }
+ const hits: string[] = [];
+ for (const { name, pattern } of REMOVED_TOOL_PATTERNS) {
+ if (pattern.test(body)) hits.push(name);
+ }
+ if (hits.length === 0) continue;
+ const replacements = hits
+ .map((name) => {
+ const record = REMOVED_TOOLS[name]!;
+ return `${name} -> ${record.target} view="${record.view}"`;
+ })
+ .join("; ");
+ issues.push({
+ severity: "warning",
+ code: "removed-tool-reference",
+ message:
+ `${relative(vault, path)} references tool(s) removed in 1.0.0: ` +
+ `${replacements} (see docs/updating.md)`,
+ });
+ emitted += 1;
+ }
+}
+
+/** Recursive `.md` collection, fail-soft on unreadable directories. */
+function collectMarkdownFiles(dir: string, out: string[]): void {
+ if (!existsSync(dir)) return;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const p = join(dir, entry.name);
+ if (entry.isDirectory()) collectMarkdownFiles(p, out);
+ else if (entry.isFile() && entry.name.endsWith(".md")) out.push(p);
+ }
+}
diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.ts
new file mode 100644
index 00000000..8a775071
--- /dev/null
+++ b/src/core/brain/dream-stage.ts
@@ -0,0 +1,463 @@
+/**
+ * Staged dream pipeline (t_ae8a8ec0, article: Hermes Dreaming).
+ *
+ * `dream()` promotes inline; `brain_review_candidates` previews; the
+ * snapshot layer rolls back after the fact. What was missing is a
+ * REVIEWABLE artifact between "the engine planned this" and "the
+ * engine wrote this": a persisted, discardable proposal bundle an
+ * operator (or watchdog) can diff, validate, apply, or throw away as
+ * a unit.
+ *
+ * The cardinal rule: dream() stays the ONLY promotion engine.
+ *
+ * - `stageDream` runs the engine in dry-run mode and persists the
+ * clock-normalized plan projection plus the scanned sources under
+ * `Brain/dream/staged/<run-id>/` (manifest.json / REPORT.md /
+ * sources.jsonl / proposals.jsonl).
+ * - `validateDreamBundle` recomputes the dry-run plan and compares
+ * projections - equality proves the vault has not drifted since
+ * staging (the engine is deterministic for fixed inputs + clock-
+ * relevant state).
+ * - `applyDreamBundle` re-validates with the SAME `now` it will run
+ * with, then executes `dream()` live; determinism guarantees the
+ * live run performs exactly the staged plan. Drift at any point
+ * aborts before a single write.
+ *
+ * The projection deliberately drops run ids, timestamps, and any
+ * field that legitimately varies with the wall clock without changing
+ * the plan (e.g. quarantine `age_days` - threshold crossings still
+ * surface because `failed_gates` flips).
+ */
+
+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { createHash } from "node:crypto";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { appendMetric } from "./metrics.ts";
+import { brainDirs } from "./paths.ts";
+import { dream, type DreamOptions, type DreamRunSummary } from "./dream.ts";
+import { isoSecond } from "./time.ts";
+
+export const DREAM_STAGE_SCHEMA_VERSION = "o2b.dream-stage.v1";
+
+/**
+ * Clock-normalized projection of a dream plan. Every array is sorted
+ * so equality is insensitive to scan order; no run ids or timestamps.
+ */
+export interface DreamStagePlan {
+ readonly changed: boolean;
+ readonly new_unconfirmed: ReadonlyArray<string>;
+ readonly confirmed: ReadonlyArray<string>;
+ readonly retired: ReadonlyArray<{ id: string; reason: string }>;
+ readonly contradictions: ReadonlyArray<string>;
+ readonly moved_to_processed: ReadonlyArray<string>;
+ readonly suppressed: ReadonlyArray<string>;
+ readonly quarantined: ReadonlyArray<{ topic: string; failed_gates: ReadonlyArray<string> }>;
+ readonly gated_retires: ReadonlyArray<{ pref_id: string; attempted_reason: string }>;
+}
+
+export interface DreamStageSource {
+ readonly path: string;
+ readonly sha256: string;
+}
+
+export interface DreamStageBundle {
+ readonly runId: string;
+ /** Absolute bundle directory. */
+ readonly dir: string;
+ readonly plan: DreamStagePlan;
+ readonly sources: ReadonlyArray<DreamStageSource>;
+}
+
+export interface DreamStageValidation {
+ readonly valid: boolean;
+ /** Human-readable drift lines; empty when valid. */
+ readonly drift: ReadonlyArray<string>;
+ readonly staged: DreamStagePlan | null;
+ readonly recomputed: DreamStagePlan | null;
+}
+
+export interface DreamStageApplyOutcome {
+ readonly applied: boolean;
+ readonly validation: DreamStageValidation;
+ /** Present iff applied. */
+ readonly summary?: DreamRunSummary;
+}
+
+export interface DreamBundleInfo {
+ readonly runId: string;
+ readonly status: "staged" | "applied";
+ readonly stagedAt: string;
+ readonly proposals: number;
+ readonly sources: number;
+}
+
+export interface DreamStageOptions {
+ readonly now: Date;
+ /** Forwarded to the underlying dream pass. */
+ readonly safeguard?: DreamOptions["safeguard"];
+ readonly agentName?: string;
+}
+
+/** Sorted-copy helper keeping projections order-insensitive. */
+function sorted<T>(values: ReadonlyArray<T>, key: (v: T) => string): T[] {
+ return [...values].toSorted((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
+}
+
+/** The comparable plan projection of one dream summary. */
+export function projectDreamPlan(summary: DreamRunSummary): DreamStagePlan {
+ return Object.freeze({
+ changed: summary.changed,
+ new_unconfirmed: Object.freeze([...summary.new_unconfirmed].toSorted()),
+ confirmed: Object.freeze([...summary.confirmed].toSorted()),
+ retired: Object.freeze(
+ sorted(
+ summary.retired.map((r) => ({ id: r.id, reason: String(r.reason) })),
+ (r) => r.id,
+ ),
+ ),
+ contradictions: Object.freeze([...summary.contradictions].toSorted()),
+ moved_to_processed: Object.freeze([...summary.moved_to_processed].toSorted()),
+ suppressed: Object.freeze([...summary.suppressed].toSorted()),
+ quarantined: Object.freeze(
+ sorted(
+ summary.quarantined.map((q) => ({
+ topic: q.topic,
+ failed_gates: Object.freeze([...q.failed_gates].toSorted()),
+ })),
+ (q) => q.topic,
+ ),
+ ),
+ gated_retires: Object.freeze(
+ sorted(
+ summary.gated_retires.map((g) => ({
+ pref_id: g.pref_id,
+ attempted_reason: String(g.attempted_reason),
+ })),
+ (g) => g.pref_id,
+ ),
+ ),
+ });
+}
+
+/**
+ * Bundle ids are generated by stageDream and must never carry path
+ * semantics: validate/apply/discard join them into filesystem paths,
+ * so anything outside the generated shape (plus a collision suffix)
+ * is rejected before touching the disk.
+ */
+const RUN_ID_RE = /^stage-[0-9-]+(?:-[0-9]+)?$/;
+
+function isValidRunId(runId: string): boolean {
+ return RUN_ID_RE.test(runId);
+}
+
+function stagedRoot(vault: string): string {
+ return join(vault, "Brain", "dream", "staged");
+}
+
+function appliedRoot(vault: string): string {
+ return join(vault, "Brain", "dream", "applied");
+}
+
+function sha256(text: string): string {
+ return createHash("sha256").update(text).digest("hex");
+}
+
+/** Active inbox signals (not processed/) with content hashes. */
+function scanSources(vault: string): DreamStageSource[] {
+ const inbox = brainDirs(vault).inbox;
+ if (!existsSync(inbox)) return [];
+ const out: DreamStageSource[] = [];
+ for (const entry of readdirSync(inbox, { withFileTypes: true })) {
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
+ const abs = join(inbox, entry.name);
+ try {
+ out.push({ path: `Brain/inbox/${entry.name}`, sha256: sha256(readFileSync(abs, "utf8")) });
+ } catch {
+ // A torn read shows up as plan drift later, not as a stage crash.
+ }
+ }
+ return out.toSorted((a, b) => (a.path < b.path ? -1 : 1));
+}
+
+/** Flatten one plan into proposal records for proposals.jsonl. */
+function planToProposals(plan: DreamStagePlan): Array<Record<string, unknown>> {
+ const rows: Array<Record<string, unknown>> = [];
+ for (const id of plan.new_unconfirmed) rows.push({ type: "create_preference", id });
+ for (const id of plan.confirmed) rows.push({ type: "confirm_preference", id });
+ for (const r of plan.retired)
+ rows.push({ type: "retire_preference", id: r.id, reason: r.reason });
+ for (const id of plan.moved_to_processed) rows.push({ type: "process_signal", id });
+ for (const id of plan.suppressed) rows.push({ type: "suppress_signal", id });
+ for (const q of plan.quarantined) {
+ rows.push({ type: "quarantine_cluster", topic: q.topic, failed_gates: q.failed_gates });
+ }
+ for (const g of plan.gated_retires) {
+ rows.push({ type: "gate_retire", pref_id: g.pref_id, attempted_reason: g.attempted_reason });
+ }
+ for (const topic of plan.contradictions) rows.push({ type: "open_contradiction", topic });
+ return rows;
+}
+
+const section = (title: string, lines: ReadonlyArray<string>): string[] =>
+ lines.length === 0 ? [] : [`## ${title}`, "", ...lines.map((l) => `- ${l}`), ""];
+
+function renderReport(runId: string, stagedAt: string, plan: DreamStagePlan): string {
+ return [
+ `# Dream stage ${runId}`,
+ "",
+ "Auto-generated by `o2b brain dream stage`. Do not edit - validate",
+ "before apply; discard to drop the whole bundle.",
+ "",
+ `Staged at: ${stagedAt}`,
+ `Planned changes: ${plan.changed ? "yes" : "none"}`,
+ "",
+ ...section("Would create (unconfirmed)", plan.new_unconfirmed),
+ ...section("Would confirm", plan.confirmed),
+ ...section(
+ "Would retire",
+ plan.retired.map((r) => `${r.id} (${r.reason})`),
+ ),
+ ...section("Would move to processed", plan.moved_to_processed),
+ ...section("Would suppress", plan.suppressed),
+ ...section(
+ "Quarantined clusters",
+ plan.quarantined.map((q) => `${q.topic} (failed: ${q.failed_gates.join(", ")})`),
+ ),
+ ...section(
+ "Gated retires",
+ plan.gated_retires.map((g) => `${g.pref_id} (${g.attempted_reason})`),
+ ),
+ ...section("Open contradictions", plan.contradictions),
+ ].join("\n");
+}
+
+/**
+ * Run the engine in dry-run mode and persist the proposal bundle.
+ * Read-only against live Brain state.
+ */
+export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBundle {
+ const summary = dream(vault, {
+ now: opts.now,
+ dryRun: true,
+ ...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),
+ ...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),
+ });
+ const plan = projectDreamPlan(summary);
+ const sources = scanSources(vault);
+ const stagedAt = isoSecond(opts.now);
+ // Second-resolution ids can collide (same --now, same second): take
+ // the first free -N suffix instead of overwriting a prior bundle.
+ const base = `stage-${stagedAt.replaceAll(/[:T]/g, "").replace("Z", "")}`;
+ let runId = base;
+ for (let suffix = 2; existsSync(join(stagedRoot(vault), runId)); suffix++) {
+ runId = `${base}-${suffix}`;
+ }
+ const dir = join(stagedRoot(vault), runId);
+ mkdirSync(dir, { recursive: true });
+
+ const proposals = planToProposals(plan);
+ const proposalsBody = proposals.map((p) => JSON.stringify(p)).join("\n") + "\n";
+ const sourcesBody =
+ sources.length === 0 ? "" : sources.map((s) => JSON.stringify(s)).join("\n") + "\n";
+
+ atomicWriteFileSync(join(dir, "proposals.jsonl"), proposalsBody);
+ atomicWriteFileSync(join(dir, "sources.jsonl"), sourcesBody);
+ atomicWriteFileSync(join(dir, "REPORT.md"), renderReport(runId, stagedAt, plan) + "\n");
+ atomicWriteFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify(
+ {
+ schema: DREAM_STAGE_SCHEMA_VERSION,
+ run_id: runId,
+ staged_at: stagedAt,
+ proposals: proposals.length,
+ sources: sources.length,
+ plan,
+ plan_hash: sha256(JSON.stringify(plan)),
+ sources_hash: sha256(sourcesBody),
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+
+ try {
+ appendMetric(vault, {
+ surface: "dream_stage",
+ runAt: stagedAt,
+ payload: {
+ action: "stage",
+ run_id: runId,
+ proposals: proposals.length,
+ sources: sources.length,
+ changed: plan.changed,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+
+ return Object.freeze({ runId, dir, plan, sources: Object.freeze(sources) });
+}
+
+/** Parse one bundle manifest; null on any defect (fail-soft reads). */
+function readManifest(dir: string): Record<string, unknown> | null {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8"));
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ const m = parsed as Record<string, unknown>;
+ if (m["schema"] !== DREAM_STAGE_SCHEMA_VERSION) return null;
+ return m;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Recompute the dry-run plan and compare it to the staged one.
+ * `now` should be the clock the eventual apply will run with - the
+ * comparison is only meaningful for the run it gates.
+ */
+export function validateDreamBundle(
+ vault: string,
+ runId: string,
+ opts: DreamStageOptions,
+): DreamStageValidation {
+ if (!isValidRunId(runId)) {
+ return Object.freeze({
+ valid: false,
+ drift: Object.freeze([`invalid bundle id: ${JSON.stringify(runId)}`]),
+ staged: null,
+ recomputed: null,
+ });
+ }
+ const dir = join(stagedRoot(vault), runId);
+ const manifest = readManifest(dir);
+ if (manifest === null) {
+ return Object.freeze({
+ valid: false,
+ drift: Object.freeze([`no staged bundle named ${runId} (or its manifest is unreadable)`]),
+ staged: null,
+ recomputed: null,
+ });
+ }
+ const planRaw = manifest["plan"];
+ if (planRaw === null || typeof planRaw !== "object" || Array.isArray(planRaw)) {
+ return Object.freeze({
+ valid: false,
+ drift: Object.freeze([`bundle ${runId} has a malformed plan - re-stage`]),
+ staged: null,
+ recomputed: null,
+ });
+ }
+ const staged = planRaw as DreamStagePlan;
+ const summary = dream(vault, {
+ now: opts.now,
+ dryRun: true,
+ ...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),
+ ...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),
+ });
+ const recomputed = projectDreamPlan(summary);
+
+ const drift: string[] = [];
+ const keys = Object.keys(recomputed) as Array<keyof DreamStagePlan>;
+ for (const key of keys) {
+ const before = JSON.stringify(staged[key] ?? null);
+ const after = JSON.stringify(recomputed[key]);
+ if (before !== after) drift.push(`${key}: staged ${before} -> now ${after}`);
+ }
+ return Object.freeze({
+ valid: drift.length === 0,
+ drift: Object.freeze(drift),
+ staged,
+ recomputed,
+ });
+}
+
+/**
+ * Re-validate, then run the engine live. The bundle archives under
+ * `Brain/dream/applied/<run-id>/` with `applied_at` stamped into the
+ * manifest. A failed validation aborts before any write.
+ */
+export function applyDreamBundle(
+ vault: string,
+ runId: string,
+ opts: DreamStageOptions,
+): DreamStageApplyOutcome {
+ const validation = validateDreamBundle(vault, runId, opts);
+ if (!validation.valid) {
+ return Object.freeze({ applied: false, validation });
+ }
+ const summary = dream(vault, {
+ now: opts.now,
+ ...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),
+ ...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),
+ });
+
+ const dir = join(stagedRoot(vault), runId);
+ const manifest = readManifest(dir);
+ const appliedDir = join(appliedRoot(vault), runId);
+ mkdirSync(appliedRoot(vault), { recursive: true });
+ if (manifest !== null) {
+ atomicWriteFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify({ ...manifest, applied_at: isoSecond(opts.now) }, null, 2) + "\n",
+ );
+ }
+ renameSync(dir, appliedDir);
+
+ try {
+ appendMetric(vault, {
+ surface: "dream_stage",
+ runAt: isoSecond(opts.now),
+ payload: {
+ action: "apply",
+ run_id: runId,
+ changed: summary.changed,
+ new_unconfirmed: summary.new_unconfirmed.length,
+ confirmed: summary.confirmed.length,
+ retired: summary.retired.length,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+
+ return Object.freeze({ applied: true, validation, summary });
+}
+
+/** Remove one staged bundle. True when it existed. */
+export function discardDreamBundle(vault: string, runId: string): boolean {
+ if (!isValidRunId(runId)) return false;
+ const dir = join(stagedRoot(vault), runId);
+ if (!existsSync(dir)) return false;
+ rmSync(dir, { recursive: true, force: true });
+ return true;
+}
+
+/** Staged + applied bundles, newest staged_at first. */
+export function listDreamBundles(vault: string): DreamBundleInfo[] {
+ const out: DreamBundleInfo[] = [];
+ for (const [root, status] of [
+ [stagedRoot(vault), "staged"],
+ [appliedRoot(vault), "applied"],
+ ] as const) {
+ if (!existsSync(root)) continue;
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ const manifest = readManifest(join(root, entry.name));
+ if (manifest === null) continue;
+ out.push({
+ runId: entry.name,
+ status,
+ stagedAt: String(manifest["staged_at"] ?? ""),
+ proposals: Number(manifest["proposals"] ?? 0),
+ sources: Number(manifest["sources"] ?? 0),
+ });
+ }
+ }
+ return out.toSorted((a, b) => (a.stagedAt > b.stagedAt ? -1 : 1));
+}
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 3f96cec2..1b39209d 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -261,6 +261,14 @@ export interface DreamOptions {
* threaded yet); the CLI always provides the value.
*/
readonly agentName?: string;
+ /**
+ * Cooperative deadline (t_06784b8d): checkpointed at entry and at
+ * the phase seams (pre-mutation, post-promote, pre-finalize). A
+ * tripped guard on the mutation path leaves the durable workrun
+ * dangling, which is exactly the integrity contract - the next
+ * pass spots and reports it.
+ */
+ readonly safeguard?: import("./safeguard.ts").Safeguard;
}
// ----- Internal scan types ------------------------------------------------
@@ -307,6 +315,7 @@ interface ScanResult {
export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
const now = opts.now ?? new Date();
const dryRun = opts.dryRun === true;
+ opts.safeguard?.checkpoint();
const cfg = loadBrainConfig(vault);
let runId = formatRunId(now);
const wikilinkToRun = `[[Brain/log/${isoDate(now)}]]`;
@@ -415,6 +424,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// Snapshot must succeed before any mutation. If it fails, the
// function throws and nothing changes on disk.
let snapshotPathStr: string | undefined;
+ // Honor an already-expired deadline BEFORE spending snapshot I/O.
+ opts.safeguard?.checkpoint();
if (!dryRun) {
runId = nextAvailableDreamRunId(vault, runId);
const snap = createSnapshot(vault, runId);
@@ -446,6 +457,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// no-op early-return). The handle is null until the exec branch
// claims it; `finally` finalises if non-null.
let workrun: WorkrunHandle | null = null;
+ opts.safeguard?.checkpoint();
if (!dryRun) {
workrun = openWorkrun(vault, runId);
workrun.checkpoint(WORKRUN_PHASE.clusterComplete);
@@ -623,6 +635,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// dream.ts execution loop runs promote (writePreference) then retire
// (moveToRetired) sequentially; one checkpoint covers both
// mutations so the workrun stays compact yet recovery-meaningful.
+ opts.safeguard?.checkpoint();
if (workrun !== null) {
workrun.checkpoint(WORKRUN_PHASE.promoteComplete);
// Multi-phase dream (F2): synthesize = the promote/confirm writes
diff --git a/src/core/brain/link-graph/bridge-discovery.ts b/src/core/brain/link-graph/bridge-discovery.ts
index b4c15418..39760d16 100644
--- a/src/core/brain/link-graph/bridge-discovery.ts
+++ b/src/core/brain/link-graph/bridge-discovery.ts
@@ -67,6 +67,11 @@ export interface DiscoverBridgesOptions {
readonly maxCandidates?: number;
/** Pair keys (see {@link bridgePairKey}) to suppress. */
readonly dismissed?: ReadonlySet<string>;
+ /**
+ * Cooperative deadline (t_06784b8d): checkpointed at entry and once
+ * per scanned candidate document.
+ */
+ readonly safeguard?: import("../safeguard.ts").Safeguard;
}
/** Canonical unordered pair key. */
@@ -86,6 +91,7 @@ export function discoverBridges(
const maxProposals = Math.max(1, opts.maxProposals ?? BRIDGE_DEFAULT_MAX_PROPOSALS);
const maxCandidates = Math.max(1, opts.maxCandidates ?? BRIDGE_DEFAULT_MAX_CANDIDATES);
const dismissed = opts.dismissed ?? new Set<string>();
+ opts.safeguard?.checkpoint();
if (!store.vecLoaded() || store.countEmbeddings() === 0) {
return Object.freeze({
@@ -123,6 +129,8 @@ export function discoverBridges(
// Best similarity per unordered pair.
const best = new Map<string, BridgeProposal>();
for (const candidate of candidates) {
+ // Cooperative deadline: abort between candidates (read-only scan).
+ opts.safeguard?.checkpoint();
const chunks = store.chunksForDocument(candidate.id).slice(0, BRIDGE_CHUNKS_PER_DOC);
for (const chunk of chunks) {
const embedding = store.embeddingForChunk(chunk.id);
diff --git a/src/core/brain/link-graph/communities.ts b/src/core/brain/link-graph/communities.ts
index 88e966c9..8d9152f2 100644
--- a/src/core/brain/link-graph/communities.ts
+++ b/src/core/brain/link-graph/communities.ts
@@ -60,6 +60,11 @@ export interface Community {
export interface DetectCommunitiesOptions {
readonly minSize?: number;
readonly maxIterations?: number;
+ /**
+ * Cooperative deadline (t_06784b8d): checkpointed at entry and once
+ * per propagation sweep.
+ */
+ readonly safeguard?: import("../safeguard.ts").Safeguard;
}
/**
@@ -69,6 +74,7 @@ export interface DetectCommunitiesOptions {
export function detectCommunities(store: Store, opts: DetectCommunitiesOptions = {}): Community[] {
const minSize = Math.max(2, opts.minSize ?? COMMUNITY_DEFAULT_MIN_SIZE);
const maxIterations = Math.max(1, opts.maxIterations ?? COMMUNITY_MAX_ITERATIONS);
+ opts.safeguard?.checkpoint();
const pathById = new Map<number, string>();
for (const [path, summary] of store.listDocuments()) pathById.set(summary.id, path);
@@ -89,6 +95,8 @@ export function detectCommunities(store: Store, opts: DetectCommunitiesOptions =
const nodes = [...adjacency.keys()].toSorted((a, b) => a - b);
const labels = new Map<number, number>(nodes.map((n) => [n, n]));
for (let iteration = 0; iteration < maxIterations; iteration++) {
+ // Cooperative deadline: abort between sweeps (read-only pass).
+ opts.safeguard?.checkpoint();
let changed = false;
const next = new Map<number, number>();
for (const node of nodes) {
diff --git a/src/core/brain/maintenance/lane.ts b/src/core/brain/maintenance/lane.ts
index 9c8be873..bc667fef 100644
--- a/src/core/brain/maintenance/lane.ts
+++ b/src/core/brain/maintenance/lane.ts
@@ -19,6 +19,7 @@
*/
import { listRecallTelemetry } from "../recall-telemetry.ts";
+import { capOutput, SafeguardTimeoutError } from "../safeguard.ts";
import { acquireLease, MAINTENANCE_LEASE_NAME, releaseLease } from "./lease.ts";
import { appendJournal, listJournal, sweepJournal, type MaintenanceVerdict } from "./journal.ts";
@@ -49,6 +50,9 @@ export interface EvaluateGatesOptions {
readonly busy?: BusyGate;
}
+/** Cap for persisted per-task error strings (journal + results). */
+const LANE_ERROR_MAX_BYTES = 4096;
+
export interface MaintenanceTask {
readonly name: string;
readonly run: () => Promise<void>;
@@ -67,6 +71,8 @@ export interface MaintenanceTaskResult {
readonly ok: boolean;
readonly duration_ms: number;
readonly error?: string;
+ /** True when the task tripped its cooperative safeguard deadline. */
+ readonly timed_out?: boolean;
}
export interface RunMaintenanceResult {
@@ -138,16 +144,29 @@ export async function runMaintenance(
const startedAt = Date.now();
let ok = true;
let error: string | undefined;
+ let timedOut = false;
try {
// Sequential by design: the lane exists to serialize heavy work.
// eslint-disable-next-line no-await-in-loop
await task.run();
} catch (exc) {
ok = false;
- error = exc instanceof Error ? exc.message : String(exc);
+ timedOut = exc instanceof SafeguardTimeoutError;
+ // Caps keep a pathological error string from flooding the
+ // journal and every status render downstream.
+ error = capOutput(
+ exc instanceof Error ? exc.message : String(exc),
+ LANE_ERROR_MAX_BYTES,
+ ).text;
}
const duration = Date.now() - startedAt;
- results.push({ name: task.name, ok, duration_ms: duration, ...(error ? { error } : {}) });
+ results.push({
+ name: task.name,
+ ok,
+ duration_ms: duration,
+ ...(error ? { error } : {}),
+ ...(timedOut ? { timed_out: true } : {}),
+ });
appendJournal(vault, {
ts: nowIso,
holder: opts.holder,
diff --git a/src/core/brain/present-time.ts b/src/core/brain/present-time.ts
new file mode 100644
index 00000000..6105c5e9
--- /dev/null
+++ b/src/core/brain/present-time.ts
@@ -0,0 +1,71 @@
+/**
+ * Timezone presentation layer (t_2ccadc6a,
+ * upstream:tencentdb-agent-memory).
+ *
+ * Storage timestamps stay canonical UTC everywhere - frontmatter, log
+ * headings, run ids, metrics (`time.ts` is untouched). This module
+ * converts ONE instant at the presentation boundary: user-facing CLI
+ * output and LLM-facing MCP envelopes render the operator's configured
+ * IANA zone (`timezone` config field / `VAULT_TIMEZONE` env, resolved
+ * by `resolveTimezone()` in core/config.ts).
+ *
+ * Output shape is the full-offset ISO-8601 form
+ * `YYYY-MM-DDTHH:MM:SS+HH:MM` so a reader always sees both the local
+ * wall time and how far it sits from the stored UTC value. Fail-soft:
+ * a missing or invalid zone renders the canonical UTC `Z` form, and an
+ * unparseable instant is returned verbatim - presentation must never
+ * break the surface it decorates.
+ */
+
+const PART_TYPES = ["year", "month", "day", "hour", "minute", "second"] as const;
+
+/**
+ * Render one ISO-8601 UTC instant in the given IANA zone with an
+ * explicit offset. `tz === null` (not configured) or an invalid zone
+ * returns the canonical UTC `Z` rendering of the same instant.
+ */
+export function formatLocalTimestamp(isoUtc: string, tz: string | null): string {
+ const date = new Date(isoUtc);
+ if (Number.isNaN(date.getTime())) return isoUtc;
+ const canonical = date.toISOString().replace(/\.\d{3}Z$/, "Z");
+ if (tz === null) return canonical;
+
+ let parts: Intl.DateTimeFormatPart[];
+ try {
+ parts = new Intl.DateTimeFormat("en-CA", {
+ timeZone: tz,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ hour12: false,
+ }).formatToParts(date);
+ } catch {
+ return canonical;
+ }
+
+ const v: Record<string, string> = {};
+ for (const part of parts) {
+ if ((PART_TYPES as ReadonlyArray<string>).includes(part.type)) v[part.type] = part.value;
+ }
+ // `hour12: false` can render midnight as "24" in some engines.
+ const hour = v["hour"] === "24" ? "00" : v["hour"]!;
+
+ // Offset = local wall clock reinterpreted as UTC minus the instant.
+ const wallAsUtc = Date.UTC(
+ Number(v["year"]),
+ Number(v["month"]) - 1,
+ Number(v["day"]),
+ Number(hour),
+ Number(v["minute"]),
+ Number(v["second"]),
+ );
+ const offsetMinutes = Math.round((wallAsUtc - date.getTime()) / 60_000);
+ const sign = offsetMinutes < 0 ? "-" : "+";
+ const abs = Math.abs(offsetMinutes);
+ const offset = `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`;
+
+ return `${v["year"]}-${v["month"]}-${v["day"]}T${hour}:${v["minute"]}:${v["second"]}${offset}`;
+}
diff --git a/src/core/brain/report-snapshot.ts b/src/core/brain/report-snapshot.ts
new file mode 100644
index 00000000..84858fb7
--- /dev/null
+++ b/src/core/brain/report-snapshot.ts
@@ -0,0 +1,252 @@
+/**
+ * Dual-output reports (t_00eece5d, article: Hermes as an Onchain
+ * Analyst): digest/brief surfaces persist a machine-diffable JSON
+ * snapshot per run so the NEXT run can report "what changed since
+ * last time" deterministically - the run-over-run continuation of the
+ * dashboard-ready `Brain/metrics/` contract from v0.45.0.
+ *
+ * Layout: `Brain/reports/<surface>/<ISO-date>.json`, schema
+ * `o2b.report-snapshot.v1`, atomic single-file writes, fail-soft
+ * reader (a torn prior snapshot reads as none - the delta degrades to
+ * "no prior", never to a crash).
+ *
+ * The diff keys on STABLE identities, not array order:
+ *
+ * - objects flatten by key path (`counts/events`);
+ * - arrays of objects key each element by its `id` / `topic` /
+ * `path` / `slug` field when one exists (index as last resort);
+ * - arrays of primitives compare as sets (`topics[gamma]` added).
+ *
+ * Opt-in: `report_snapshots_enabled` config key, env mirror
+ * `OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS`. A vault that enables nothing
+ * writes nothing and renders byte-identically.
+ */
+
+import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { discoverConfig } from "../config.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+
+export const REPORT_SNAPSHOT_SCHEMA_VERSION = "o2b.report-snapshot.v1";
+
+/** Fields stripped before snapshotting: volatile per-render decoration. */
+const VOLATILE_KEYS: ReadonlySet<string> = new Set([
+ "generated_at",
+ // CLI surfaces snapshot raw core envelopes whose render stamp is
+ // camelCase - both spellings are per-render decoration.
+ "generatedAt",
+ "run_id",
+ "local_time",
+ "timezone",
+ "delta",
+]);
+
+/** Identity fields tried (in order) to key array-of-object elements. */
+const IDENTITY_KEYS = ["id", "pref_id", "topic", "path", "slug", "date"] as const;
+
+export interface ReportChange {
+ readonly path: string;
+ readonly before: string;
+ readonly after: string;
+}
+
+export interface ReportDelta {
+ /** Date of the prior snapshot the delta is computed against. */
+ readonly prior_date: string | null;
+ readonly added: ReadonlyArray<string>;
+ readonly removed: ReadonlyArray<string>;
+ readonly changed: ReadonlyArray<ReportChange>;
+}
+
+export interface LoadedReportSnapshot {
+ readonly date: string;
+ readonly payload: unknown;
+}
+
+export function reportSnapshotsEnabled(configPath?: string): boolean {
+ const env = process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"];
+ if (env === "true" || env === "1") return true;
+ if (env === "false" || env === "0") return false;
+ try {
+ const value = discoverConfig(configPath).data["report_snapshots_enabled"];
+ return value === "true" || value === "1";
+ } catch {
+ return false;
+ }
+}
+
+function reportsDir(vault: string, surface: string): string {
+ return join(vault, "Brain", "reports", surface);
+}
+
+/** Strip volatile decoration recursively before persisting/diffing. */
+function stripVolatile(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(stripVolatile);
+ if (value !== null && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ if (VOLATILE_KEYS.has(k)) continue;
+ out[k] = stripVolatile(v);
+ }
+ return out;
+ }
+ return value;
+}
+
+/** Flatten one payload into stable-identity leaf paths. */
+function flatten(value: unknown, prefix: string, out: Map<string, string>): void {
+ if (Array.isArray(value)) {
+ const allPrimitive = value.every((v) => v === null || typeof v !== "object");
+ if (allPrimitive) {
+ // Set semantics: membership is the identity.
+ for (const item of value) out.set(`${prefix}[${String(item)}]`, "present");
+ return;
+ }
+ value.forEach((item, index) => {
+ let key = String(index);
+ if (item !== null && typeof item === "object" && !Array.isArray(item)) {
+ for (const idKey of IDENTITY_KEYS) {
+ const candidate = (item as Record<string, unknown>)[idKey];
+ if (typeof candidate === "string" && candidate !== "") {
+ key = candidate;
+ break;
+ }
+ }
+ }
+ flatten(item, prefix === "" ? key : `${prefix}/${key}`, out);
+ });
+ return;
+ }
+ if (value !== null && typeof value === "object") {
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ flatten(v, prefix === "" ? k : `${prefix}/${k}`, out);
+ }
+ return;
+ }
+ out.set(prefix, JSON.stringify(value) ?? "undefined");
+}
+
+/** Deterministic keyed diff between two report payloads. */
+export function diffReportPayloads(
+ before: unknown,
+ after: unknown,
+): Pick<ReportDelta, "added" | "removed" | "changed"> {
+ const a = new Map<string, string>();
+ const b = new Map<string, string>();
+ flatten(stripVolatile(before), "", a);
+ flatten(stripVolatile(after), "", b);
+ const added: string[] = [];
+ const removed: string[] = [];
+ const changed: ReportChange[] = [];
+ for (const [path, value] of b) {
+ if (!a.has(path)) added.push(path);
+ else if (a.get(path) !== value) changed.push({ path, before: a.get(path)!, after: value });
+ }
+ for (const path of a.keys()) {
+ if (!b.has(path)) removed.push(path);
+ }
+ return {
+ added: Object.freeze(added.toSorted()),
+ removed: Object.freeze(removed.toSorted()),
+ changed: Object.freeze(changed.toSorted((x, y) => (x.path < y.path ? -1 : 1))),
+ };
+}
+
+/** Persist one surface snapshot (atomic; same-date overwrite is fine). */
+export function writeReportSnapshot(
+ vault: string,
+ surface: string,
+ date: string,
+ payload: unknown,
+): string {
+ const dir = reportsDir(vault, surface);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, `${date}.json`);
+ atomicWriteFileSync(
+ path,
+ JSON.stringify(
+ { schema: REPORT_SNAPSHOT_SCHEMA_VERSION, surface, date, payload: stripVolatile(payload) },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return path;
+}
+
+/** Newest snapshot strictly before `beforeDate`. Fail-soft null. */
+export function loadLatestReportSnapshot(
+ vault: string,
+ surface: string,
+ beforeDate: string,
+): LoadedReportSnapshot | null {
+ const dir = reportsDir(vault, surface);
+ if (!existsSync(dir)) return null;
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ return null;
+ }
+ const dates = names
+ .filter((n) => n.endsWith(".json"))
+ .map((n) => n.slice(0, -".json".length))
+ .filter((d) => d < beforeDate)
+ .toSorted();
+ for (let i = dates.length - 1; i >= 0; i--) {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(join(dir, `${dates[i]}.json`), "utf8"));
+ if (parsed === null || typeof parsed !== "object") continue;
+ const record = parsed as Record<string, unknown>;
+ if (record["schema"] !== REPORT_SNAPSHOT_SCHEMA_VERSION) continue;
+ return { date: dates[i]!, payload: record["payload"] };
+ } catch {
+ // Torn snapshot: skip to the next-older one.
+ }
+ }
+ return null;
+}
+
+/**
+ * The one call surfaces make: when snapshots are enabled, persist the
+ * current payload and return the delta against the latest prior
+ * snapshot (no prior -> empty delta with `prior_date: null`). When
+ * disabled, returns null and touches nothing.
+ */
+export function captureReportDelta(
+ vault: string,
+ surface: string,
+ date: string,
+ payload: unknown,
+ opts: { configPath?: string } = {},
+): ReportDelta | null {
+ if (!reportSnapshotsEnabled(opts.configPath)) return null;
+ const prior = loadLatestReportSnapshot(vault, surface, date);
+ writeReportSnapshot(vault, surface, date, payload);
+ if (prior === null) {
+ return Object.freeze({
+ prior_date: null,
+ added: Object.freeze([]),
+ removed: Object.freeze([]),
+ changed: Object.freeze([]),
+ });
+ }
+ return Object.freeze({ prior_date: prior.date, ...diffReportPayloads(prior.payload, payload) });
+}
+
+/** Human-readable "Since last run" block for markdown/text output. */
+export function renderReportDelta(delta: ReportDelta): string {
+ if (delta.prior_date === null) {
+ return "Since last run: first snapshot - nothing to compare yet.";
+ }
+ if (delta.added.length === 0 && delta.removed.length === 0 && delta.changed.length === 0) {
+ return `Since last run (${delta.prior_date}): no changes.`;
+ }
+ const lines = [`Since last run (${delta.prior_date}):`];
+ for (const path of delta.added) lines.push(` + ${path}`);
+ for (const path of delta.removed) lines.push(` - ${path}`);
+ for (const change of delta.changed) {
+ lines.push(` ~ ${change.path}: ${change.before} -> ${change.after}`);
+ }
+ return lines.join("\n");
+}
diff --git a/src/core/brain/safeguard.ts b/src/core/brain/safeguard.ts
new file mode 100644
index 00000000..1b8edb26
--- /dev/null
+++ b/src/core/brain/safeguard.ts
@@ -0,0 +1,146 @@
+/**
+ * Operation safeguard (t_06784b8d, upstream:mirage): cooperative
+ * deadline + output caps for long-running brain operations (dream,
+ * reindex, bridge discovery, communities, maintenance lane).
+ *
+ * Bun runs SQLite synchronously, so a preemptive timeout would have
+ * to lie - wrapping sync work in a fake async race never actually
+ * cancels it. The honest contract is cooperative: an operation
+ * receives a `Safeguard` and calls `checkpoint()` at its natural
+ * iteration boundaries (per file, per candidate pair, per propagation
+ * sweep, per lane task). Past the deadline the NEXT checkpoint throws
+ * `SafeguardTimeoutError`; writes stay atomic, so a tripped operation
+ * stops at a boundary instead of half-writing an artifact.
+ *
+ * Timeout resolution mirrors mirage's ladder: per-operation config
+ * key (`safeguard_timeout_<op>_seconds`) -> global key
+ * (`safeguard_timeout_seconds`, env mirror
+ * `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`) -> built-in default. `0`
+ * disables the deadline. Invalid values fail soft to the default -
+ * a typo in a timeout must never break the operation it guards.
+ */
+
+import { discoverConfig } from "../config.ts";
+
+/** Operations that accept a safeguard. */
+export type SafeguardOperation = "dream" | "reindex" | "bridges" | "clusters" | "maintenance";
+
+/** Built-in fallback budget (mirage uses 600s; same scale fits here). */
+export const SAFEGUARD_DEFAULT_TIMEOUT_SECONDS = 600;
+
+export class SafeguardTimeoutError extends Error {
+ readonly operation: string;
+ readonly timeoutMs: number;
+
+ constructor(operation: string, timeoutMs: number) {
+ super(
+ `${operation} exceeded its safeguard timeout of ${timeoutMs}ms - aborted at a checkpoint`,
+ );
+ this.name = "SafeguardTimeoutError";
+ this.operation = operation;
+ this.timeoutMs = timeoutMs;
+ }
+}
+
+export interface Safeguard {
+ /** Throws `SafeguardTimeoutError` when the deadline has passed. */
+ checkpoint(): void;
+ /** The active budget, or null when the deadline is disabled. */
+ readonly timeoutMs: number | null;
+ /** The operation this guard protects (for error reporting). */
+ readonly operation: string;
+}
+
+export interface CreateSafeguardOptions {
+ readonly operation: SafeguardOperation | string;
+ /** Budget in milliseconds; `0`, `null`, or `undefined` disable. */
+ readonly timeoutMs?: number | null;
+ /** Injected clock (tests). Defaults to `Date.now`. */
+ readonly now?: () => number;
+}
+
+/** A no-deadline guard for callers that need a Safeguard-shaped arg. */
+export function noopSafeguard(operation = "unguarded"): Safeguard {
+ return Object.freeze({
+ operation,
+ timeoutMs: null,
+ checkpoint: () => {},
+ });
+}
+
+export function createSafeguard(opts: CreateSafeguardOptions): Safeguard {
+ const budget =
+ opts.timeoutMs === undefined || opts.timeoutMs === null || opts.timeoutMs <= 0
+ ? null
+ : opts.timeoutMs;
+ if (budget === null) return noopSafeguard(opts.operation);
+ const now = opts.now ?? Date.now;
+ const deadline = now() + budget;
+ return Object.freeze({
+ operation: opts.operation,
+ timeoutMs: budget,
+ checkpoint: () => {
+ if (now() > deadline) throw new SafeguardTimeoutError(opts.operation, budget);
+ },
+ });
+}
+
+/**
+ * Resolve the timeout budget for one operation in milliseconds.
+ * Returns `null` when the resolved value is `0` (disabled).
+ */
+export function resolveSafeguardTimeoutMs(
+ operation: SafeguardOperation,
+ configPath?: string,
+): number | null {
+ let config: Readonly<Record<string, string>>;
+ try {
+ config = discoverConfig(configPath).data;
+ } catch {
+ config = {};
+ }
+ const perOp = parseSeconds(config[`safeguard_timeout_${operation}_seconds`]);
+ if (perOp !== undefined) return perOp === 0 ? null : perOp * 1000;
+ const envGlobal = parseSeconds(process.env["OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT"]);
+ if (envGlobal !== undefined) return envGlobal === 0 ? null : envGlobal * 1000;
+ const global = parseSeconds(config["safeguard_timeout_seconds"]);
+ if (global !== undefined) return global === 0 ? null : global * 1000;
+ return SAFEGUARD_DEFAULT_TIMEOUT_SECONDS * 1000;
+}
+
+/** Non-negative integer seconds, or undefined when absent/invalid. */
+function parseSeconds(raw: string | undefined): number | undefined {
+ if (raw === undefined || raw === "") return undefined;
+ const n = Number(raw);
+ if (!Number.isInteger(n) || n < 0) return undefined;
+ return n;
+}
+
+export interface CappedOutput {
+ readonly text: string;
+ readonly truncated: boolean;
+}
+
+/**
+ * Cap a text payload at `maxBytes` UTF-8 bytes without splitting a
+ * character. The marker makes silent truncation impossible to misread
+ * as a complete report, and its bytes count AGAINST the cap, so the
+ * returned text never exceeds `maxBytes` (unless the cap is smaller
+ * than the marker itself, in which case the marker alone returns).
+ */
+export function capOutput(text: string, maxBytes: number): CappedOutput {
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) {
+ return { text, truncated: false };
+ }
+ const marker = `\n[output truncated at ${maxBytes} bytes]`;
+ const budget = Math.max(0, maxBytes - Buffer.byteLength(marker, "utf8"));
+ let kept = "";
+ let bytes = 0;
+ for (const ch of text) {
+ const w = Buffer.byteLength(ch, "utf8");
+ if (bytes + w > budget) break;
+ kept += ch;
+ bytes += w;
+ }
+ return { text: `${kept}${marker}`, truncated: true };
+}
diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tpl
index 598b0f5b..615fd5aa 100644
--- a/src/core/brain/templates/_BRAIN.md.tpl
+++ b/src/core/brain/templates/_BRAIN.md.tpl
@@ -150,7 +150,7 @@ them as part of normal agent work.
The full CLI surface is documented in `docs/plans/2026-05-15-brain-observing-memory.md`
section 9; the MCP tool surface mirrors it for the most common verbs
-(`brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_digest`,
+(`brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_brief`,
`brain_query`, `brain_doctor`).
## Reading order for a new agent
diff --git a/src/core/removed-surfaces.ts b/src/core/removed-surfaces.ts
new file mode 100644
index 00000000..a1cff969
--- /dev/null
+++ b/src/core/removed-surfaces.ts
@@ -0,0 +1,65 @@
+/**
+ * Public surfaces removed at a major version (1.0.0 deprecation
+ * sweep, epic t_a77ade0a). One canonical map serves two consumers:
+ *
+ * - the MCP server answers `tools/call` on a removed name with an
+ * INVALID_PARAMS tombstone naming the replacement
+ * (src/mcp/tools.ts `findTool`);
+ * - `brain_doctor` scans vault-side text surfaces (Brain notes,
+ * root instruction files, installed skills) for stale references
+ * and warns with the same replacement
+ * (src/core/brain/doctor.ts).
+ *
+ * Lives in core (not src/mcp/) so the doctor never imports the MCP
+ * layer.
+ */
+
+export interface RemovedToolRecord {
+ /** Version that removed the surface, e.g. "1.0.0". */
+ readonly removedIn: string;
+ /** Consolidated tool that replaced it. */
+ readonly target: string;
+ /** `view` argument value selecting the predecessor's behavior. */
+ readonly view: string;
+}
+
+/** The 18 token-diet aliases deleted in 1.0.0. */
+export const REMOVED_TOOLS: Readonly<Record<string, RemovedToolRecord>> = Object.freeze({
+ brain_digest: { removedIn: "1.0.0", target: "brain_brief", view: "digest" },
+ brain_daily_brief: { removedIn: "1.0.0", target: "brain_brief", view: "daily" },
+ brain_morning_brief: { removedIn: "1.0.0", target: "brain_brief", view: "morning" },
+ brain_weekly_synthesis: { removedIn: "1.0.0", target: "brain_brief", view: "weekly" },
+ brain_monthly_review: { removedIn: "1.0.0", target: "brain_brief", view: "monthly" },
+ brain_operator_summary: { removedIn: "1.0.0", target: "brain_brief", view: "operator" },
+ brain_attention_flows: {
+ removedIn: "1.0.0",
+ target: "brain_analytics",
+ view: "attention_flows",
+ },
+ brain_concept_synthesis: {
+ removedIn: "1.0.0",
+ target: "brain_analytics",
+ view: "concept_synthesis",
+ },
+ brain_timeline: { removedIn: "1.0.0", target: "brain_analytics", view: "timeline" },
+ brain_belief_evolution: {
+ removedIn: "1.0.0",
+ target: "brain_analytics",
+ view: "belief_evolution",
+ },
+ get_active_schema_pack: { removedIn: "1.0.0", target: "schema_inspect", view: "active_pack" },
+ list_schema_packs: { removedIn: "1.0.0", target: "schema_inspect", view: "packs" },
+ schema_stats: { removedIn: "1.0.0", target: "schema_inspect", view: "stats" },
+ schema_lint: { removedIn: "1.0.0", target: "schema_inspect", view: "lint" },
+ schema_graph: { removedIn: "1.0.0", target: "schema_inspect", view: "graph" },
+ schema_explain_type: { removedIn: "1.0.0", target: "schema_inspect", view: "explain_type" },
+ schema_review_orphans: { removedIn: "1.0.0", target: "schema_inspect", view: "orphans" },
+ reload_schema_pack: { removedIn: "1.0.0", target: "schema_inspect", view: "active_pack" },
+});
+
+/** `name -> replacement` rendered the way tombstone errors phrase it. */
+export function removedToolReplacement(name: string): string | null {
+ const record = REMOVED_TOOLS[name];
+ if (record === undefined) return null;
+ return `${record.target} with view="${record.view}"`;
+}
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index 7b908bbd..bec85177 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -71,6 +71,11 @@ export interface IndexVaultOptions {
/** When true, bypass the embedding cost gate for this run. */
readonly forceCost?: boolean;
readonly onFile?: (event: IndexProgressEvent) => void;
+ /**
+ * Cooperative deadline (t_06784b8d): checkpointed once per walked
+ * file, so a tripped guard aborts between files - never mid-write.
+ */
+ readonly safeguard?: import("../brain/safeguard.ts").Safeguard;
}
interface MutableStats {
@@ -201,6 +206,10 @@ async function indexInto(
}> = [];
for (const file of walkVault(config)) {
+ // Cooperative deadline: abort between files, never mid-write.
+ // Per-file document upserts are transactional, so a tripped
+ // guard leaves a consistent (partially refreshed) index.
+ opts?.safeguard?.checkpoint();
// Mark seen FIRST. If anything downstream throws (read fault,
// chunker bug, transient FS error), the file must not look
// "missing" to the deletion sweep below — that would wipe a
@@ -406,7 +415,7 @@ async function indexInto(
}
if (opts?.embeddings) {
- await populateEmbeddings(store, config, stats, opts?.forceCost === true);
+ await populateEmbeddings(store, config, stats, opts?.forceCost === true, opts?.safeguard);
}
const now = new Date().toISOString();
@@ -470,6 +479,7 @@ async function populateEmbeddings(
config: ResolvedSearchConfig,
stats: MutableStats,
forceCost: boolean,
+ safeguard?: import("../brain/safeguard.ts").Safeguard,
): Promise<void> {
if (!config.semantic.enabled) {
throw new SearchError(
@@ -522,6 +532,9 @@ async function populateEmbeddings(
const superBatch = batchSize * Math.max(1, config.semantic.concurrency);
for (let i = 0; i < pending.length; i += superBatch) {
+ // Cooperative deadline: embedding batches are the other long
+ // phase of an index run - abort between batches, never mid-batch.
+ safeguard?.checkpoint();
const batch = pending.slice(i, i + superBatch);
const texts = batch.map((p) => p.content);
const vectors = await provider.embed(texts);
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index aec7b764..8b1db6e4 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -44,6 +44,7 @@ import {
resolveAgentName,
resolveLinkOutputFormat,
resolveSearchFocusContextPack,
+ resolveTimezone,
resolveTriggerCooldownDays,
} from "../core/config.ts";
import { indexVault, resolveSearchConfig } from "../core/search/index.ts";
@@ -70,6 +71,7 @@ import {
materializeClusterNotes,
} from "../core/brain/link-graph/communities.ts";
import { appendMetric } from "../core/brain/metrics.ts";
+import { createSafeguard, resolveSafeguardTimeoutMs } from "../core/brain/safeguard.ts";
import { parseRecallBenchmarkDataset, runRecallBenchmark } from "../core/search/benchmark.ts";
import { loadTunedParameters, resetTuning, tuneRecall } from "../core/search/tuning.ts";
import { currentLease } from "../core/brain/maintenance/lease.ts";
@@ -180,6 +182,13 @@ import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts"
import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
import { renderDigest, type DigestFormat } from "../core/brain/digest.ts";
import { dream } from "../core/brain/dream.ts";
+import {
+ applyDreamBundle,
+ discardDreamBundle,
+ listDreamBundles,
+ stageDream,
+ validateDreamBundle,
+} from "../core/brain/dream-stage.ts";
import { buildIntentReview } from "../core/brain/intent-review.ts";
import { buildRetentionReview } from "../core/brain/retention.ts";
import { buildMonthlyReview, normalizeMonthlyReviewMonth } from "../core/brain/monthly-review.ts";
@@ -200,6 +209,8 @@ import { writeSignal } from "../core/brain/signal.ts";
import { writePreference } from "../core/brain/preference.ts";
import { validateBrainFeedbackInput } from "../core/brain/sessions/validate-feedback.ts";
import { isoDate, isoSecond } from "../core/brain/time.ts";
+import { formatLocalTimestamp } from "../core/brain/present-time.ts";
+import { captureReportDelta } from "../core/brain/report-snapshot.ts";
import { slugify } from "../core/vault.ts";
import { normalizeAgentArgument } from "../core/agent-identity.ts";
import {
@@ -243,7 +254,7 @@ import {
} from "../core/brain/pinned.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
-import { deprecatedAlias, type ServerContext, type ToolDefinition } from "./tools.ts";
+import type { ServerContext, ToolDefinition } from "./tools.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import {
coerceStr,
@@ -412,11 +423,84 @@ async function toolBrainDream(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
+ const action = args["action"] ?? "run";
+ if (
+ action !== "run" &&
+ action !== "stage" &&
+ action !== "validate" &&
+ action !== "apply" &&
+ action !== "discard" &&
+ action !== "list"
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_dream: action must be run|stage|validate|apply|discard|list",
+ );
+ }
const dryRun = coerceBool(args, "dry_run");
const nowDate = coerceIsoDate(args, "now");
const agentArg = coerceStr(args, "agent", false);
const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+ if (action !== "run") {
+ // Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a
+ // persisted bundle; dream() stays the only promotion engine.
+ const runIdArg = coerceStr(args, "run_id", false);
+ if ((action === "validate" || action === "apply" || action === "discard") && !runIdArg) {
+ throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);
+ }
+ const now = nowDate ?? new Date();
+ const stageOpts = { now, ...(agent ? { agentName: agent } : {}) };
+ switch (action) {
+ case "stage": {
+ const bundle = stageDream(ctx.vault, stageOpts);
+ return {
+ action,
+ run_id: bundle.runId,
+ plan: bundle.plan,
+ sources: bundle.sources.length,
+ dir: `Brain/dream/staged/${bundle.runId}`,
+ };
+ }
+ case "validate": {
+ const verdict = validateDreamBundle(ctx.vault, runIdArg!, stageOpts);
+ return { action, run_id: runIdArg, valid: verdict.valid, drift: [...verdict.drift] };
+ }
+ case "apply": {
+ const outcome = applyDreamBundle(ctx.vault, runIdArg!, stageOpts);
+ return {
+ action,
+ run_id: runIdArg,
+ applied: outcome.applied,
+ drift: [...outcome.validation.drift],
+ ...(outcome.summary !== undefined
+ ? {
+ changed: outcome.summary.changed,
+ new_unconfirmed: [...outcome.summary.new_unconfirmed],
+ confirmed: [...outcome.summary.confirmed],
+ retired: outcome.summary.retired.map((r) => ({ id: r.id, reason: r.reason })),
+ }
+ : {}),
+ };
+ }
+ case "discard": {
+ return { action, run_id: runIdArg, removed: discardDreamBundle(ctx.vault, runIdArg!) };
+ }
+ default: {
+ return {
+ action,
+ bundles: listDreamBundles(ctx.vault).map((b) => ({
+ run_id: b.runId,
+ status: b.status,
+ staged_at: b.stagedAt,
+ proposals: b.proposals,
+ sources: b.sources,
+ })),
+ };
+ }
+ }
+ }
+
const summary = dream(ctx.vault, {
dryRun,
...(nowDate ? { now: nowDate } : {}),
@@ -509,12 +593,12 @@ async function toolBrainMonthlyReview(
let month: string | undefined;
if (monthRaw !== undefined && monthRaw !== null) {
if (typeof monthRaw !== "string") {
- throw new MCPError(INVALID_PARAMS, "brain_monthly_review: month must be YYYY-MM");
+ throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
}
try {
month = normalizeMonthlyReviewMonth(monthRaw);
} catch {
- throw new MCPError(INVALID_PARAMS, "brain_monthly_review: month must be YYYY-MM");
+ throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
}
}
const report = buildMonthlyReview(ctx.vault, month ? { month } : {});
@@ -1001,18 +1085,52 @@ async function toolBrainDigest(
const until = coerceIsoDate(args, "until");
const format = coerceFormat(args) satisfies DigestFormat;
+ // Pin ONE effective until instant so the rendered content, the
+ // snapshot render, and the snapshot date key all describe the same
+ // window even when the caller omitted `until`.
+ const effectiveUntil = until ?? new Date();
const result = renderDigest(ctx.vault, {
...(since ? { since } : {}),
- ...(until ? { until } : {}),
+ until: effectiveUntil,
format,
linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
});
- return {
+ const envelope: Record<string, unknown> = {
format,
empty: result.empty,
content: result.content,
};
+ // Snapshot the structured summary, not the rendered string: render
+ // a JSON digest for the snapshot regardless of the caller's format
+ // so the run-over-run diff keys on data.
+ const digestDate = isoDate(effectiveUntil);
+ const snapshotSource =
+ format === "json"
+ ? result.content
+ : renderDigest(ctx.vault, {
+ ...(since ? { since } : {}),
+ until: effectiveUntil,
+ format: "json",
+ linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
+ }).content;
+ let parsedSnapshot: unknown = null;
+ try {
+ parsedSnapshot = JSON.parse(snapshotSource);
+ } catch {
+ parsedSnapshot = null;
+ }
+ const delta =
+ parsedSnapshot !== null
+ ? captureReportDelta(
+ ctx.vault,
+ "digest",
+ digestDate,
+ parsedSnapshot,
+ ctx.configPath ? { configPath: ctx.configPath } : {},
+ )
+ : null;
+ return delta !== null ? { ...envelope, delta } : envelope;
}
// ----- brain_query ---------------------------------------------------------
@@ -1308,14 +1426,14 @@ async function toolBrainMorningBrief(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
- const topK = optionalPositiveInt(args, "top_k", "brain_morning_brief") ?? 10;
- const lookbackDays = optionalPositiveInt(args, "lookback_days", "brain_morning_brief") ?? 7;
+ const topK = optionalPositiveInt(args, "top_k", "brain_brief view=morning") ?? 10;
+ const lookbackDays = optionalPositiveInt(args, "lookback_days", "brain_brief view=morning") ?? 7;
const maxCharsPerMemory = optionalPositiveInt(
args,
"max_chars_per_memory",
- "brain_morning_brief",
+ "brain_brief view=morning",
);
- const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_morning_brief");
+ const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_brief view=morning");
const now = new Date();
const brief = buildMorningBrief(ctx.vault, {
now,
@@ -1670,7 +1788,7 @@ async function toolBrainOperatorSummary(
if (!Number.isInteger(topRaw) || topRaw < 0) {
throw new MCPError(
INVALID_PARAMS,
- "brain_operator_summary: top_actions must be a non-negative integer",
+ "brain_brief view=operator: top_actions must be a non-negative integer",
);
}
topActionsN = topRaw;
@@ -1679,14 +1797,14 @@ async function toolBrainOperatorSummary(
if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
throw new MCPError(
INVALID_PARAMS,
- "brain_operator_summary: top_actions must be a non-negative integer",
+ "brain_brief view=operator: top_actions must be a non-negative integer",
);
}
topActionsN = Number.parseInt(trimmed, 10);
} else {
throw new MCPError(
INVALID_PARAMS,
- "brain_operator_summary: top_actions must be a non-negative integer",
+ "brain_brief view=operator: top_actions must be a non-negative integer",
);
}
}
@@ -1698,7 +1816,10 @@ async function toolBrainOperatorSummary(
} else if (typeof includeDreamRaw === "boolean") {
includeDream = includeDreamRaw;
} else {
- throw new MCPError(INVALID_PARAMS, "brain_operator_summary: include_dream must be a boolean");
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_brief view=operator: include_dream must be a boolean",
+ );
}
let dreamSummary;
@@ -2067,6 +2188,14 @@ async function toolBrainMaintenance(
vault: ctx.vault,
configPath: ctx.configPath ?? undefined,
});
+ // Same per-task deadlines as the CLI lane (t_06784b8d): one fresh
+ // cooperative safeguard per task, budget resolved per-op -> global
+ // -> default.
+ const laneSafeguard = (operation: "dream" | "reindex" | "bridges" | "clusters") =>
+ createSafeguard({
+ operation,
+ timeoutMs: resolveSafeguardTimeoutMs(operation, ctx.configPath ?? undefined),
+ });
const result = await runMaintenance(ctx.vault, {
now,
holder: `${agent}@${process.pid}`,
@@ -2076,13 +2205,13 @@ async function toolBrainMaintenance(
{
name: "dream",
run: async () => {
- dream(ctx.vault, { now });
+ dream(ctx.vault, { now, safeguard: laneSafeguard("dream") });
},
},
{
name: "reindex",
run: async () => {
- await indexVault(searchConfig);
+ await indexVault(searchConfig, { safeguard: laneSafeguard("reindex") });
},
},
// Same lane contract as the CLI verb (link-recall-intelligence):
@@ -2096,6 +2225,7 @@ async function toolBrainMaintenance(
try {
const report = discoverBridges(store, {
dismissed: readDismissedBridges(ctx.vault),
+ safeguard: laneSafeguard("bridges"),
});
writeBridgeProposals(ctx.vault, report, { now });
try {
@@ -2122,7 +2252,7 @@ async function toolBrainMaintenance(
run: async () => {
const store = await Store.open(searchConfig, { mode: "read" });
try {
- const communities = detectCommunities(store, {});
+ const communities = detectCommunities(store, { safeguard: laneSafeguard("clusters") });
const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });
try {
appendMetric(ctx.vault, {
@@ -2616,7 +2746,10 @@ async function toolBrainConceptSynthesis(
): Promise<Record<string, unknown>> {
const idRaw = args["id"];
if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
- throw new MCPError(INVALID_PARAMS, "brain_concept_synthesis: id must be a non-empty string");
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_analytics view=concept_synthesis: id must be a non-empty string",
+ );
}
const includeUnlinkedRaw = args["include_unlinked"];
let includeUnlinked = false;
@@ -2624,7 +2757,7 @@ async function toolBrainConceptSynthesis(
if (typeof includeUnlinkedRaw !== "boolean") {
throw new MCPError(
INVALID_PARAMS,
- "brain_concept_synthesis: include_unlinked must be a boolean",
+ "brain_analytics view=concept_synthesis: include_unlinked must be a boolean",
);
}
includeUnlinked = includeUnlinkedRaw;
@@ -2809,7 +2942,7 @@ async function toolBrainBeliefEvolution(
if (hasPref === hasTopic) {
throw new MCPError(
INVALID_PARAMS,
- "brain_belief_evolution: exactly one of pref_id or topic is required",
+ "brain_analytics view=belief_evolution: exactly one of pref_id or topic is required",
);
}
const target = hasPref
@@ -2866,7 +2999,7 @@ async function toolBrainDailyBrief(
const brief = buildDailyBrief(index, ctx.vault, date, {
offsetHours: cfg.daily_window_offset_hours,
});
- return {
+ const envelope: Record<string, unknown> = {
vault_path: ctx.vault,
date: brief.date,
window: brief.window,
@@ -2876,6 +3009,16 @@ async function toolBrainDailyBrief(
source_pointers: brief.sourcePointers,
generated_at: brief.generatedAt,
};
+ // Dual-output (t_00eece5d): persist a machine snapshot and report
+ // the run-over-run delta when report snapshots are enabled.
+ const delta = captureReportDelta(
+ ctx.vault,
+ "daily",
+ brief.date,
+ envelope,
+ ctx.configPath ? { configPath: ctx.configPath } : {},
+ );
+ return delta !== null ? { ...envelope, delta } : envelope;
}
/**
@@ -2897,7 +3040,7 @@ async function toolBrainWeeklySynthesis(
const cfg = loadTemporalConfigSafe(ctx.vault);
const index = buildTimelineIndex(ctx.vault, {});
const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);
- return {
+ const envelope: Record<string, unknown> = {
vault_path: ctx.vault,
window_start: synth.windowStart,
window_end: synth.windowEnd,
@@ -2909,6 +3052,14 @@ async function toolBrainWeeklySynthesis(
source_pointers: synth.sourcePointers,
generated_at: synth.generatedAt,
};
+ const delta = captureReportDelta(
+ ctx.vault,
+ "weekly",
+ weekEnd,
+ envelope,
+ ctx.configPath ? { configPath: ctx.configPath } : {},
+ );
+ return delta !== null ? { ...envelope, delta } : envelope;
}
// ----- brain_intention (Agent Surface Suite) --------------------------------
@@ -3777,7 +3928,7 @@ async function toolBrainAttentionFlows(
}
throw new MCPError(
INVALID_PARAMS,
- "brain_attention_flows: operation must be one of list|evaluate|render",
+ "brain_analytics view=attention_flows: operation must be one of list|evaluate|render",
);
}
@@ -3837,8 +3988,26 @@ function dispatchByView(
return handler(ctx, args);
}
+/**
+ * Timezone presentation (t_2ccadc6a): when the operator configured an
+ * IANA zone, brief/analytics envelopes gain two ADDITIVE fields - a
+ * `timezone` echo and `local_time` (the render instant in that zone).
+ * Stored timestamps inside the envelope stay canonical UTC; with no
+ * timezone configured the envelope is byte-identical to 0.45.0.
+ */
+function localizeEnvelope(ctx: ServerContext, result: unknown): unknown {
+ if (result === null || typeof result !== "object" || Array.isArray(result)) return result;
+ const tz = resolveTimezone(ctx.configPath ?? undefined);
+ if (tz === null) return result;
+ return {
+ ...(result as Record<string, unknown>),
+ timezone: tz,
+ local_time: formatLocalTimestamp(isoSecond(new Date()), tz),
+ };
+}
+
async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {
- return await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args);
+ return localizeEnvelope(ctx, await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args));
}
async function toolBrainAnalytics(
@@ -3848,7 +4017,7 @@ async function toolBrainAnalytics(
// attention_flows requires an `operation`; the consolidated surface
// defaults it to the read-only `list` so `{view}` alone is valid.
const withDefaults = args["view"] === "attention_flows" ? { operation: "list", ...args } : args;
- return await dispatchByView(ANALYTICS_VIEW_HANDLERS, ctx, withDefaults);
+ return localizeEnvelope(ctx, await dispatchByView(ANALYTICS_VIEW_HANDLERS, ctx, withDefaults));
}
export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
@@ -4021,13 +4190,23 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_dream",
description:
- "Run the deterministic learning pass over `Brain/inbox/` (clusters signals, promotes preferences, retires stale rules). Typically scheduled via cron rather than invoked interactively.",
+ "Deterministic learning pass over `Brain/inbox/`. action=run (default) promotes inline; the staged lifecycle persists a reviewable bundle: stage -> validate -> apply (or discard), plus list. Typically scheduled via cron.",
inputSchema: {
type: "object",
properties: {
+ action: {
+ type: "string",
+ enum: ["run", "stage", "validate", "apply", "discard", "list"],
+ description:
+ "run executes inline; stage persists a proposal bundle; validate/apply/discard manage one bundle by run_id; list shows bundles.",
+ },
+ run_id: {
+ type: "string",
+ description: "Bundle id for validate/apply/discard (from action=stage or list).",
+ },
dry_run: {
type: "boolean",
- description: "When true, compute the plan without writing any files.",
+ description: "action=run only: compute the plan without writing any files.",
},
now: {
type: "string",
@@ -4078,15 +4257,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainRetention,
},
- {
- ...deprecatedAlias({
- name: "brain_monthly_review",
- target: "brain_brief",
- view: "monthly",
- handler: toolBrainMonthlyReview,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
{
name: "brain_review_candidates",
description:
@@ -4366,15 +4536,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
outputSchema: BRAIN_CONTEXT_OUTPUT_SCHEMA,
handler: toolBrainContext,
},
- {
- ...deprecatedAlias({
- name: "brain_digest",
- target: "brain_brief",
- view: "digest",
- handler: toolBrainDigest,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
{
name: "brain_query",
previewBudget: MCP_PREVIEW_BUDGET,
@@ -4638,14 +4799,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainAudit,
},
- {
- ...deprecatedAlias({
- name: "brain_morning_brief",
- target: "brain_brief",
- view: "morning",
- handler: toolBrainMorningBrief,
- }),
- },
{
name: "brain_sources",
description:
@@ -5249,15 +5402,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainProceduralGraph,
},
- {
- ...deprecatedAlias({
- name: "brain_attention_flows",
- target: "brain_analytics",
- view: "attention_flows",
- handler: toolBrainAttentionFlows,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
{
name: "brain_pre_compact_extract",
description:
@@ -5440,15 +5584,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainUnlinkedMentions,
},
- {
- ...deprecatedAlias({
- name: "brain_concept_synthesis",
- target: "brain_analytics",
- view: "concept_synthesis",
- handler: toolBrainConceptSynthesis,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
{
name: "brain_moc_audit",
description:
@@ -5466,24 +5601,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainMocAudit,
},
- {
- ...deprecatedAlias({
- name: "brain_timeline",
- target: "brain_analytics",
- view: "timeline",
- handler: toolBrainTimeline,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- ...deprecatedAlias({
- name: "brain_belief_evolution",
- target: "brain_analytics",
- view: "belief_evolution",
- handler: toolBrainBeliefEvolution,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
{
name: "brain_stale_scan",
description:
@@ -5495,31 +5612,4 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainStaleScan,
},
- {
- ...deprecatedAlias({
- name: "brain_daily_brief",
- target: "brain_brief",
- view: "daily",
- handler: toolBrainDailyBrief,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- ...deprecatedAlias({
- name: "brain_weekly_synthesis",
- target: "brain_brief",
- view: "weekly",
- handler: toolBrainWeeklySynthesis,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
- {
- ...deprecatedAlias({
- name: "brain_operator_summary",
- target: "brain_brief",
- view: "operator",
- handler: toolBrainOperatorSummary,
- }),
- previewBudget: MCP_PREVIEW_BUDGET,
- },
]);
diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.ts
index c09b859d..fccd2499 100644
--- a/src/mcp/registry-guard.ts
+++ b/src/mcp/registry-guard.ts
@@ -102,7 +102,6 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr
brain_context:
"session bootstrap; deliberately returns the full preference set - it is the full-view target the budgeted SessionStart injection points at",
brain_pre_compress_pack: "self-budgeting; enforces its own char budget internally",
- brain_morning_brief: "self-budgeting via max_chars_per_memory / max_total_chars",
brain_artifact_get: "the preview-budget escape hatch; truncating it would defeat itself",
brain_health: "fixed-shape counters",
brain_doctor: "issue list bounded by vault invariants; CLI surface renders full detail",
@@ -128,18 +127,8 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr
brain_agent_diff: "bounded two-agent comparison",
get_skill: "explicit full-content fetch; truncating the skill the agent asked for defeats it",
tool_hydrate: "the two-pass schema escape hatch; truncating hydration would defeat itself",
-
- // Deprecated aliases (token-diet): the consolidated tool carries the
- // budget; the alias keeps its predecessor's budget status until
- // removal.
- get_active_schema_pack: "deprecated alias for schema_inspect; slated for removal",
- list_schema_packs: "deprecated alias for schema_inspect; slated for removal",
- schema_stats: "deprecated alias for schema_inspect; slated for removal",
- schema_lint: "deprecated alias for schema_inspect; slated for removal",
- schema_graph: "deprecated alias for schema_inspect; slated for removal",
- schema_explain_type: "deprecated alias for schema_inspect; slated for removal",
- schema_review_orphans: "deprecated alias for schema_inspect; slated for removal",
- reload_schema_pack: "deprecated alias for schema_inspect; slated for removal",
+ // The deprecated-alias exemptions were dropped with the aliases
+ // themselves in the 1.0.0 sweep (tombstones in REMOVED_TOOLS).
});
export interface PreviewBudgetAudit {
diff --git a/src/mcp/resources.ts b/src/mcp/resources.ts
index 955cf92e..e06415db 100644
--- a/src/mcp/resources.ts
+++ b/src/mcp/resources.ts
@@ -90,7 +90,7 @@ const CONCRETE: ReadonlyArray<ResourceDescriptor> = [
{
uri: "osb://digest/latest",
name: "Latest Brain digest",
- description: "Same body as `brain_digest` (default window: last 24h). Markdown.",
+ description: "Same body as `brain_brief` view=digest (default window: last 24h). Markdown.",
mimeType: MIME_MARKDOWN,
},
{
diff --git a/src/mcp/schema-tools.ts b/src/mcp/schema-tools.ts
index ccc28047..5f7f6984 100644
--- a/src/mcp/schema-tools.ts
+++ b/src/mcp/schema-tools.ts
@@ -14,10 +14,11 @@ import { resolveSearchConfig } from "../core/search/index.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import { coerceStr } from "./coerce.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
-import { deprecatedAlias, type ServerContext, type ToolDefinition } from "./tools.ts";
+import type { ServerContext, ToolDefinition } from "./tools.ts";
-// Read-side handlers shared by the consolidated `schema_inspect` and
-// its deprecated per-view aliases (token-diet, t_3920db77).
+// Read-side handlers behind the consolidated `schema_inspect` views.
+// The per-view alias tools were removed in 1.0.0 (tombstones in
+// `REMOVED_TOOLS`, src/mcp/tools.ts).
const SCHEMA_INSPECT_VIEWS: Readonly<
Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>
> = Object.freeze({
@@ -73,48 +74,6 @@ export const SCHEMA_TOOLS: ReadonlyArray<ToolDefinition> = [
},
handler: toolSchemaInspect,
},
- deprecatedAlias({
- name: "get_active_schema_pack",
- target: "schema_inspect",
- view: "active_pack",
- handler: SCHEMA_INSPECT_VIEWS["active_pack"]!,
- }),
- deprecatedAlias({
- name: "list_schema_packs",
- target: "schema_inspect",
- view: "packs",
- handler: SCHEMA_INSPECT_VIEWS["packs"]!,
- }),
- deprecatedAlias({
- name: "schema_stats",
- target: "schema_inspect",
- view: "stats",
- handler: SCHEMA_INSPECT_VIEWS["stats"]!,
- }),
- deprecatedAlias({
- name: "schema_lint",
- target: "schema_inspect",
- view: "lint",
- handler: SCHEMA_INSPECT_VIEWS["lint"]!,
- }),
- deprecatedAlias({
- name: "schema_graph",
- target: "schema_inspect",
- view: "graph",
- handler: SCHEMA_INSPECT_VIEWS["graph"]!,
- }),
- deprecatedAlias({
- name: "schema_explain_type",
- target: "schema_inspect",
- view: "explain_type",
- handler: SCHEMA_INSPECT_VIEWS["explain_type"]!,
- }),
- deprecatedAlias({
- name: "schema_review_orphans",
- target: "schema_inspect",
- view: "orphans",
- handler: SCHEMA_INSPECT_VIEWS["orphans"]!,
- }),
{
name: "schema_apply_mutations",
description:
@@ -156,10 +115,4 @@ export const SCHEMA_TOOLS: ReadonlyArray<ToolDefinition> = [
});
},
},
- deprecatedAlias({
- name: "reload_schema_pack",
- target: "schema_inspect",
- view: "active_pack",
- handler: SCHEMA_INSPECT_VIEWS["active_pack"]!,
- }),
];
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 1220483d..f5adc6b6 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -24,6 +24,7 @@
*/
import { discoverConfig, redactMapping } from "../core/config.ts";
+import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
import { isDir } from "../core/fs-utils.ts";
@@ -291,29 +292,19 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {
export type ToolScope = "full" | "writer" | "catalog";
/**
- * Deprecated delegating alias (token-diet, t_3920db77): the tool name
- * stays callable for at least one minor release after its capability
- * moved into a consolidated view tool, but its registry footprint
- * shrinks to a one-line description and a permissive input schema.
- * The handler is the exact function the consolidated tool dispatches
- * to, so behavior is byte-identical under either name.
+ * Tombstones for the deprecated aliases removed in 1.0.0 (epic
+ * t_a77ade0a). The token-diet pass (t_3920db77) consolidated these 18
+ * tools into `brain_brief` / `brain_analytics` / `schema_inspect`
+ * views and kept the old names callable as hidden aliases; the 1.0.0
+ * sweep deletes the alias layer entirely. Calling a tombstoned name
+ * answers INVALID_PARAMS with the exact replacement instead of a
+ * generic METHOD_NOT_FOUND, so a stale client learns the migration
+ * from the error message itself. Zero token cost: tombstones are
+ * never advertised. The canonical map lives in core
+ * (src/core/removed-surfaces.ts) so `brain_doctor` shares it without
+ * importing the MCP layer; re-exported here for the server and tests.
*/
-export function deprecatedAlias(opts: {
- readonly name: string;
- readonly target: string;
- readonly view: string;
- readonly handler: ToolDefinition["handler"];
- readonly previewBudget?: number;
-}): ToolDefinition {
- return {
- name: opts.name,
- description: `Deprecated alias for ${opts.target} with view="${opts.view}". Will be removed in a future minor release.`,
- inputSchema: { type: "object" },
- hidden: true,
- ...(opts.previewBudget !== undefined ? { previewBudget: opts.previewBudget } : {}),
- handler: opts.handler,
- };
-}
+export { REMOVED_TOOLS };
// The set is named after the original payload (mutating writers). As
// of v0.10.10 it also hosts `brain_context`, a *reader* tool that has
@@ -442,7 +433,16 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): ToolDefinition {
const tool = tools.find((t) => t.name === name);
- if (!tool) throw new MCPError(METHOD_NOT_FOUND, `unknown tool: ${name}`);
+ if (!tool) {
+ const tombstone = REMOVED_TOOLS[name];
+ if (tombstone !== undefined) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${name} was removed in ${tombstone.removedIn}; call ${tombstone.target} with view="${tombstone.view}"`,
+ );
+ }
+ throw new MCPError(METHOD_NOT_FOUND, `unknown tool: ${name}`);
+ }
return tool;
}
diff --git a/tests/cli/brain-dream-stage.test.ts b/tests/cli/brain-dream-stage.test.ts
new file mode 100644
index 00000000..0850d6cb
--- /dev/null
+++ b/tests/cli/brain-dream-stage.test.ts
@@ -0,0 +1,168 @@
+/**
+ * `o2b brain dream stage|validate|apply|discard|list` CLI surface
+ * (t_ae8a8ec0): the staged lifecycle drives the same engine as the
+ * inline pass; validate exits 1 on drift so cron and scripts can gate
+ * on it; usage errors exit 2; legacy `o2b brain dream` keeps working
+ * positional-free.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-dream-stage-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "VAULT_DIR"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+function seedCluster(topic: string): void {
+ for (const i of [1, 2, 3]) {
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle: `Rule for ${topic}.`,
+ created_at: "2026-06-01T10:00:00Z",
+ date: "2026-06-01",
+ slug: `${topic}-${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+test("full stage -> validate -> apply cycle via the CLI", async () => {
+ seedCluster("cli-cycle");
+ const staged = await runCli([
+ "brain",
+ "dream",
+ "stage",
+ "--now",
+ "2026-06-05T12:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(staged.returncode).toBe(0);
+ const stagedOut = JSON.parse(staged.stdout) as { run_id: string; plan: { changed: boolean } };
+ expect(stagedOut.plan.changed).toBe(true);
+
+ const validated = await runCli([
+ "brain",
+ "dream",
+ "validate",
+ stagedOut.run_id,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(validated.returncode).toBe(0);
+ expect(JSON.parse(validated.stdout)).toMatchObject({ valid: true, drift: [] });
+
+ const applied = await runCli([
+ "brain",
+ "dream",
+ "apply",
+ stagedOut.run_id,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(applied.returncode).toBe(0);
+ expect(JSON.parse(applied.stdout)).toMatchObject({
+ applied: true,
+ new_unconfirmed: ["pref-cli-cycle"],
+ });
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-cli-cycle.md"))).toBe(true);
+
+ const listed = await runCli(["brain", "dream", "list", "--vault", vault, "--json"]);
+ const bundles = (JSON.parse(listed.stdout) as { bundles: Array<{ status: string }> }).bundles;
+ expect(bundles[0]!.status).toBe("applied");
+});
+
+test("validate exits 1 on drift; apply aborts without writes", async () => {
+ seedCluster("cli-drift");
+ const staged = await runCli([
+ "brain",
+ "dream",
+ "stage",
+ "--now",
+ "2026-06-05T12:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ const runId = (JSON.parse(staged.stdout) as { run_id: string }).run_id;
+ seedCluster("cli-newcomer");
+
+ const validated = await runCli(["brain", "dream", "validate", runId, "--vault", vault, "--json"]);
+ expect(validated.returncode).toBe(1);
+ expect(JSON.parse(validated.stdout)).toMatchObject({ valid: false });
+
+ const applied = await runCli(["brain", "dream", "apply", runId, "--vault", vault, "--json"]);
+ expect(applied.returncode).toBe(1);
+ expect(JSON.parse(applied.stdout)).toMatchObject({ applied: false });
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-cli-drift.md"))).toBe(false);
+});
+
+test("discard removes the bundle; usage errors exit 2", async () => {
+ seedCluster("cli-discard");
+ const staged = await runCli([
+ "brain",
+ "dream",
+ "stage",
+ "--now",
+ "2026-06-05T12:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ const runId = (JSON.parse(staged.stdout) as { run_id: string }).run_id;
+ const discarded = await runCli(["brain", "dream", "discard", runId, "--vault", vault, "--json"]);
+ expect(JSON.parse(discarded.stdout)).toMatchObject({ removed: true });
+
+ const badAction = await runCli(["brain", "dream", "snooze", "--vault", vault]);
+ expect(badAction.returncode).toBe(2);
+ const missingId = await runCli(["brain", "dream", "apply", "--vault", vault]);
+ expect(missingId.returncode).toBe(2);
+});
+
+test("legacy positional-free dream run still works", async () => {
+ seedCluster("cli-legacy");
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--now",
+ "2026-06-05T12:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(r.returncode).toBe(0);
+ const summary = JSON.parse(r.stdout) as { new_unconfirmed: string[] };
+ expect(summary.new_unconfirmed).toEqual(["pref-cli-legacy"]);
+});
diff --git a/tests/cli/brain-report-delta.test.ts b/tests/cli/brain-report-delta.test.ts
new file mode 100644
index 00000000..e5b0d23a
--- /dev/null
+++ b/tests/cli/brain-report-delta.test.ts
@@ -0,0 +1,146 @@
+/**
+ * Dual-output wiring (t_00eece5d): with `report_snapshots_enabled`,
+ * the digest / daily / weekly surfaces persist one snapshot per run
+ * under `Brain/reports/<surface>/` and report a "Since last run"
+ * delta on subsequent runs - in both JSON (`delta` field) and human
+ * output. A vault without the flag renders byte-identically and
+ * writes nothing.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-report-delta-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ writeFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: claude\nreport_snapshots_enabled: true\n`,
+ );
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+test("daily brief: first run no delta, second run reports the change", async () => {
+ const first = await runCli(
+ ["brain", "daily", "--date", "2026-06-04", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ expect(first.returncode).toBe(0);
+ const firstParsed = JSON.parse(first.stdout) as { delta: { prior_date: string | null } };
+ expect(firstParsed.delta.prior_date).toBeNull();
+ expect(existsSync(join(vault, "Brain", "reports", "daily", "2026-06-04.json"))).toBe(true);
+
+ // A new signal shifts the daily counters for the later date.
+ writeSignal(vault, {
+ topic: "delta-topic",
+ signal: "positive",
+ agent: "claude",
+ principle: "Rule for delta-topic.",
+ created_at: "2026-06-05T09:00:00Z",
+ date: "2026-06-05",
+ slug: "delta-1",
+ scope: "writing",
+ });
+ const second = await runCli(
+ ["brain", "daily", "--date", "2026-06-05", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ const secondParsed = JSON.parse(second.stdout) as {
+ delta: { prior_date: string | null; changed: Array<{ path: string }> };
+ };
+ expect(secondParsed.delta.prior_date).toBe("2026-06-04");
+ expect(secondParsed.delta.changed.length).toBeGreaterThan(0);
+});
+
+test("weekly and digest surfaces persist snapshots under Brain/reports/", async () => {
+ const weekly = await runCli(
+ ["brain", "weekly", "--week-end", "2026-06-05", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ expect(weekly.returncode).toBe(0);
+ expect((JSON.parse(weekly.stdout) as { delta: unknown }).delta).toBeDefined();
+ expect(existsSync(join(vault, "Brain", "reports", "weekly", "2026-06-05.json"))).toBe(true);
+
+ const digest = await runCli(["brain", "digest", "--vault", vault, "--json"], { env: env() });
+ expect(digest.returncode).toBe(0);
+ expect((JSON.parse(digest.stdout) as { delta: unknown }).delta).toBeDefined();
+ expect(existsSync(join(vault, "Brain", "reports", "digest"))).toBe(true);
+});
+
+test("a same-date rerun of identical data reports an empty delta", async () => {
+ // Guard against wall-clock leakage (independent review finding):
+ // two runs over the same date and unchanged vault must diff clean
+ // even though their render instants differ.
+ await runCli(["brain", "daily", "--date", "2026-06-04", "--vault", vault, "--json"], {
+ env: env(),
+ });
+ const rerun = await runCli(
+ ["brain", "daily", "--date", "2026-06-05", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ // Different date, no data change: still nothing volatile in the diff.
+ const rerunParsed = JSON.parse(rerun.stdout) as {
+ delta: { changed: Array<{ path: string }> };
+ };
+ expect(rerunParsed.delta.changed.filter((c) => c.path.includes("enerated"))).toEqual([]);
+
+ const weeklyFirst = await runCli(
+ ["brain", "weekly", "--week-end", "2026-06-05", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ expect(weeklyFirst.returncode).toBe(0);
+ const weeklyAgain = await runCli(
+ ["brain", "weekly", "--week-end", "2026-06-05", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ const weeklyParsed = JSON.parse(weeklyAgain.stdout) as {
+ delta: { prior_date: string | null; added: string[]; changed: Array<{ path: string }> };
+ };
+ // Same date overwrites the snapshot; the prior is the older date or
+ // none - either way no generatedAt churn may appear.
+ expect(weeklyParsed.delta.changed.filter((c) => c.path.includes("enerated"))).toEqual([]);
+});
+
+test("human output renders a Since-last-run block", async () => {
+ await runCli(["brain", "daily", "--date", "2026-06-04", "--vault", vault], { env: env() });
+ const second = await runCli(["brain", "daily", "--date", "2026-06-05", "--vault", vault], {
+ env: env(),
+ });
+ expect(second.stdout).toContain("Since last run");
+});
+
+test("disabled vault writes nothing and emits no delta", async () => {
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ const r = await runCli(["brain", "daily", "--date", "2026-06-04", "--vault", vault, "--json"], {
+ env: env(),
+ });
+ expect(r.returncode).toBe(0);
+ expect((JSON.parse(r.stdout) as Record<string, unknown>)["delta"]).toBeUndefined();
+ expect(existsSync(join(vault, "Brain", "reports"))).toBe(false);
+});
diff --git a/tests/cli/brain-timezone.test.ts b/tests/cli/brain-timezone.test.ts
new file mode 100644
index 00000000..16c787dc
--- /dev/null
+++ b/tests/cli/brain-timezone.test.ts
@@ -0,0 +1,86 @@
+/**
+ * Timezone presentation wiring (t_2ccadc6a): with `timezone:` in the
+ * plugin config, the brief-family JSON envelopes (daily, weekly,
+ * monthly, morning, timeline) gain additive `timezone` + `local_time`
+ * fields; without it, output stays byte-identical to 0.45.0. Storage
+ * timestamps inside every envelope remain canonical UTC.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-tz-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "VAULT_TIMEZONE", "VAULT_DIR"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+function enableTimezone(tz: string): void {
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\ntimezone: ${tz}\n`);
+}
+
+test("daily brief JSON gains timezone + local_time when configured", async () => {
+ enableTimezone("Europe/Berlin");
+ const r = await runCli(["brain", "daily", "--date", "2026-06-05", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(parsed["timezone"]).toBe("Europe/Berlin");
+ expect(String(parsed["local_time"])).toMatch(/[+-]\d{2}:\d{2}$/);
+ // Stored window stays canonical UTC.
+ expect(JSON.stringify(parsed["window"])).toContain("Z");
+});
+
+test("without a configured timezone the envelope carries no local fields", async () => {
+ const r = await runCli(["brain", "daily", "--date", "2026-06-05", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(parsed["timezone"]).toBeUndefined();
+ expect(parsed["local_time"]).toBeUndefined();
+});
+
+test("weekly, monthly, and timeline envelopes localize the same way", async () => {
+ enableTimezone("Asia/Tokyo");
+ const env = { OPEN_SECOND_BRAIN_CONFIG: configPath };
+ const results = await Promise.all(
+ [
+ ["brain", "weekly", "--week-end", "2026-06-05", "--vault", vault, "--json"],
+ ["brain", "monthly", "--month", "2026-06", "--vault", vault, "--json"],
+ ["brain", "timeline", "--vault", vault, "--json"],
+ ].map((argv) => runCli(argv, { env })),
+ );
+ for (const r of results) {
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(parsed["timezone"]).toBe("Asia/Tokyo");
+ expect(String(parsed["local_time"])).toContain("+09:00");
+ }
+});
diff --git a/tests/core/brain/doctor-removed-tools.test.ts b/tests/core/brain/doctor-removed-tools.test.ts
new file mode 100644
index 00000000..0d8ce37f
--- /dev/null
+++ b/tests/core/brain/doctor-removed-tools.test.ts
@@ -0,0 +1,90 @@
+/**
+ * Doctor `removed-tool-reference` check (1.0.0 deprecation sweep,
+ * epic t_a77ade0a): vault-side surfaces the doctor can actually see -
+ * Brain notes, root instruction files, installed skill files - are
+ * scanned for the 18 tool names removed in 1.0.0. Each hit yields one
+ * warning naming the replacement so an operator updating an old vault
+ * learns the migration without reading the upgrade guide first.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-doctor-removed-"));
+ const dirs = brainDirs(vault);
+ mkdirSync(dirs.brain, { recursive: true });
+ mkdirSync(dirs.preferences, { recursive: true });
+ mkdirSync(dirs.log, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function removedToolWarnings(): ReadonlyArray<{ code: string; message: string }> {
+ return runDoctor(vault).warnings.filter((w) => w.code === "removed-tool-reference");
+}
+
+describe("removed-tool-reference doctor check", () => {
+ test("clean vault yields no removed-tool warnings", () => {
+ writeFileSync(join(vault, "Brain", "note.md"), "# Note\n\nCall brain_brief for digests.\n");
+ expect(removedToolWarnings()).toEqual([]);
+ });
+
+ test("a Brain note referencing a removed tool warns with the replacement", () => {
+ writeFileSync(
+ join(vault, "Brain", "playbook.md"),
+ "# Playbook\n\nEvery morning call brain_digest and read it.\n",
+ );
+ const warnings = removedToolWarnings();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]!.message).toContain("Brain/playbook.md");
+ expect(warnings[0]!.message).toContain("brain_digest");
+ expect(warnings[0]!.message).toContain("brain_brief");
+ expect(warnings[0]!.message).toContain('view="digest"');
+ });
+
+ test("root instruction files are scanned", () => {
+ writeFileSync(join(vault, "CLAUDE.md"), "Use schema_stats to check usage.\n");
+ const warnings = removedToolWarnings();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]!.message).toContain("CLAUDE.md");
+ expect(warnings[0]!.message).toContain("schema_inspect");
+ });
+
+ test("installed skill files are scanned", () => {
+ const skillDir = join(vault, ".claude", "skills", "old-skill");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(join(skillDir, "SKILL.md"), "Call brain_operator_summary for status.\n");
+ const warnings = removedToolWarnings();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]!.message).toContain("brain_operator_summary");
+ expect(warnings[0]!.message).toContain('view="operator"');
+ });
+
+ test("multiple removed names in one file fold into one warning per file", () => {
+ writeFileSync(
+ join(vault, "Brain", "old-howto.md"),
+ "Use brain_digest then brain_timeline then schema_lint.\n",
+ );
+ const warnings = removedToolWarnings();
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]!.message).toContain("brain_digest");
+ expect(warnings[0]!.message).toContain("brain_timeline");
+ expect(warnings[0]!.message).toContain("schema_lint");
+ });
+
+ test("substring matches do not fire (word boundary)", () => {
+ // `my_brain_digestion` must not match `brain_digest`.
+ writeFileSync(join(vault, "Brain", "note.md"), "my_brain_digestion is a variable name\n");
+ expect(removedToolWarnings()).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/dream-stage-lifecycle.test.ts b/tests/core/brain/dream-stage-lifecycle.test.ts
new file mode 100644
index 00000000..29bbc6e2
--- /dev/null
+++ b/tests/core/brain/dream-stage-lifecycle.test.ts
@@ -0,0 +1,147 @@
+/**
+ * Staged dream pipeline, lifecycle half (t_ae8a8ec0): validate
+ * recomputes the dry-run plan and compares it to the staged
+ * proposals - identical means the vault has not drifted; apply
+ * re-validates and then runs the SAME engine live (no second
+ * promotion path), records a `dream_stage` metric, and archives the
+ * bundle; a drifted bundle aborts without writes; discard removes
+ * the bundle.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ applyDreamBundle,
+ discardDreamBundle,
+ listDreamBundles,
+ stageDream,
+ validateDreamBundle,
+} from "../../../src/core/brain/dream-stage.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { listMetrics } from "../../../src/core/brain/metrics.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+const STAGED_AT = new Date("2026-06-05T12:00:00Z");
+const LATER = new Date("2026-06-05T14:00:00Z");
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-dream-lifecycle-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function seedSignal(topic: string, slug: string): void {
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle: `Rule for ${topic}.`,
+ created_at: "2026-06-01T10:00:00Z",
+ date: "2026-06-01",
+ slug,
+ scope: "writing",
+ });
+}
+
+describe("validateDreamBundle", () => {
+ test("passes on an unchanged vault", () => {
+ seedSignal("lifecycle", "lifecycle-1");
+ seedSignal("lifecycle", "lifecycle-2");
+ seedSignal("lifecycle", "lifecycle-3");
+ const { runId } = stageDream(vault, { now: STAGED_AT });
+ const verdict = validateDreamBundle(vault, runId, { now: LATER });
+ expect(verdict.valid).toBe(true);
+ expect(verdict.drift).toEqual([]);
+ });
+
+ test("fails with a drift report after a new signal lands", () => {
+ seedSignal("lifecycle", "lifecycle-1");
+ seedSignal("lifecycle", "lifecycle-2");
+ seedSignal("lifecycle", "lifecycle-3");
+ const { runId } = stageDream(vault, { now: STAGED_AT });
+ seedSignal("newcomer", "newcomer-1");
+ seedSignal("newcomer", "newcomer-2");
+ seedSignal("newcomer", "newcomer-3");
+ const verdict = validateDreamBundle(vault, runId, { now: LATER });
+ expect(verdict.valid).toBe(false);
+ expect(verdict.drift.length).toBeGreaterThan(0);
+ expect(verdict.drift.join("\n")).toContain("new_unconfirmed");
+ });
+
+ test("an unknown run id reports a missing bundle", () => {
+ const verdict = validateDreamBundle(vault, "stage-nope", { now: LATER });
+ expect(verdict.valid).toBe(false);
+ expect(verdict.drift.join("\n")).toContain("bundle");
+ });
+});
+
+describe("applyDreamBundle", () => {
+ test("a valid bundle applies exactly the staged plan and archives", () => {
+ seedSignal("apply-topic", "apply-1");
+ seedSignal("apply-topic", "apply-2");
+ seedSignal("apply-topic", "apply-3");
+ const { runId, plan } = stageDream(vault, { now: STAGED_AT });
+ expect(plan.new_unconfirmed).toEqual(["pref-apply-topic"]);
+
+ const outcome = applyDreamBundle(vault, runId, { now: LATER });
+ expect(outcome.applied).toBe(true);
+ expect(outcome.summary!.new_unconfirmed).toEqual(["pref-apply-topic"]);
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-apply-topic.md"))).toBe(true);
+
+ // Bundle archived: gone from staged/, present under applied/.
+ expect(existsSync(join(vault, "Brain", "dream", "staged", runId))).toBe(false);
+ expect(existsSync(join(vault, "Brain", "dream", "applied", runId))).toBe(true);
+ const bundles = listDreamBundles(vault);
+ expect(bundles.find((b) => b.runId === runId)!.status).toBe("applied");
+
+ // Run-level dream_stage metric recorded.
+ const metrics = listMetrics(vault, { surface: "dream_stage" });
+ expect(metrics.length).toBeGreaterThanOrEqual(1);
+ expect(metrics[0]!.payload["action"]).toBe("apply");
+ });
+
+ test("a drifted bundle aborts without writes", () => {
+ seedSignal("abort-topic", "abort-1");
+ seedSignal("abort-topic", "abort-2");
+ seedSignal("abort-topic", "abort-3");
+ const { runId } = stageDream(vault, { now: STAGED_AT });
+ seedSignal("drift-topic", "drift-1");
+ seedSignal("drift-topic", "drift-2");
+ seedSignal("drift-topic", "drift-3");
+
+ const outcome = applyDreamBundle(vault, runId, { now: LATER });
+ expect(outcome.applied).toBe(false);
+ expect(outcome.validation.valid).toBe(false);
+ // Neither the staged topic nor the drift topic got promoted.
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-abort-topic.md"))).toBe(false);
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-drift-topic.md"))).toBe(false);
+ // Bundle stays staged for inspection.
+ expect(existsSync(join(vault, "Brain", "dream", "staged", runId))).toBe(true);
+ });
+});
+
+describe("discardDreamBundle", () => {
+ test("removes a staged bundle and reports absence honestly", () => {
+ seedSignal("discard-topic", "discard-1");
+ seedSignal("discard-topic", "discard-2");
+ seedSignal("discard-topic", "discard-3");
+ const { runId } = stageDream(vault, { now: STAGED_AT });
+ expect(discardDreamBundle(vault, runId)).toBe(true);
+ expect(existsSync(join(vault, "Brain", "dream", "staged", runId))).toBe(false);
+ expect(discardDreamBundle(vault, runId)).toBe(false);
+ });
+});
diff --git a/tests/core/brain/dream-stage.test.ts b/tests/core/brain/dream-stage.test.ts
new file mode 100644
index 00000000..f7edd94c
--- /dev/null
+++ b/tests/core/brain/dream-stage.test.ts
@@ -0,0 +1,117 @@
+/**
+ * Staged dream pipeline, stage half (t_ae8a8ec0): `stageDream` runs
+ * the existing engine in dry-run mode and persists a discardable
+ * proposal bundle under `Brain/dream/staged/<run-id>/` - manifest,
+ * human-readable report, scanned sources, and the planned mutations
+ * as data. The plan projection is clock-normalized (no run ids, no
+ * timestamps), so two stages over an unchanged vault project the
+ * same plan byte for byte.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ DREAM_STAGE_SCHEMA_VERSION,
+ listDreamBundles,
+ stageDream,
+} from "../../../src/core/brain/dream-stage.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+const NOW = new Date("2026-06-05T12:00:00Z");
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-dream-stage-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function seedCluster(topic: string): void {
+ for (const i of [1, 2, 3]) {
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle: `Rule for ${topic}.`,
+ created_at: "2026-06-01T10:00:00Z",
+ date: "2026-06-01",
+ slug: `${topic}-${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+describe("stageDream", () => {
+ test("persists a complete bundle and mutates nothing", () => {
+ seedCluster("stage-rules");
+ const bundle = stageDream(vault, { now: NOW });
+
+ const dir = join(vault, "Brain", "dream", "staged", bundle.runId);
+ expect(existsSync(join(dir, "manifest.json"))).toBe(true);
+ expect(existsSync(join(dir, "REPORT.md"))).toBe(true);
+ expect(existsSync(join(dir, "sources.jsonl"))).toBe(true);
+ expect(existsSync(join(dir, "proposals.jsonl"))).toBe(true);
+
+ const manifest = JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8"));
+ expect(manifest.schema).toBe(DREAM_STAGE_SCHEMA_VERSION);
+ expect(manifest.run_id).toBe(bundle.runId);
+ expect(manifest.staged_at).toBe("2026-06-05T12:00:00Z");
+ expect(manifest.sources).toBe(3);
+ expect(typeof manifest.plan_hash).toBe("string");
+
+ // Staging is read-only: the cluster must still sit in the inbox.
+ expect(bundle.plan.new_unconfirmed).toEqual(["pref-stage-rules"]);
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-stage-rules.md"))).toBe(false);
+
+ // The report names the planned promotion.
+ const report = readFileSync(join(dir, "REPORT.md"), "utf8");
+ expect(report).toContain("stage-rules");
+
+ // Sources carry content hashes for provenance.
+ const sources = readFileSync(join(dir, "sources.jsonl"), "utf8").trim().split("\n");
+ expect(sources).toHaveLength(3);
+ for (const line of sources) {
+ const parsed = JSON.parse(line);
+ expect(typeof parsed.path).toBe("string");
+ expect(parsed.sha256).toMatch(/^[0-9a-f]{64}$/);
+ }
+ });
+
+ test("the plan projection is stable across two stages of an unchanged vault", () => {
+ seedCluster("stable-topic");
+ const first = stageDream(vault, { now: new Date("2026-06-05T12:00:00Z") });
+ const second = stageDream(vault, { now: new Date("2026-06-05T13:30:00Z") });
+ expect(JSON.stringify(first.plan)).toBe(JSON.stringify(second.plan));
+ expect(first.runId).not.toBe(second.runId);
+ });
+
+ test("listDreamBundles surfaces staged bundles newest-first", () => {
+ seedCluster("list-topic");
+ stageDream(vault, { now: new Date("2026-06-05T12:00:00Z") });
+ stageDream(vault, { now: new Date("2026-06-05T12:05:00Z") });
+ const bundles = listDreamBundles(vault);
+ expect(bundles).toHaveLength(2);
+ expect(bundles[0]!.status).toBe("staged");
+ expect(bundles[0]!.stagedAt >= bundles[1]!.stagedAt).toBe(true);
+ });
+
+ test("an empty vault stages an empty plan without error", () => {
+ const bundle = stageDream(vault, { now: NOW });
+ expect(bundle.plan.changed).toBe(false);
+ expect(bundle.plan.new_unconfirmed).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/present-time.test.ts b/tests/core/brain/present-time.test.ts
new file mode 100644
index 00000000..2668e35f
--- /dev/null
+++ b/tests/core/brain/present-time.test.ts
@@ -0,0 +1,55 @@
+/**
+ * Timezone presentation helper (t_2ccadc6a): storage stays canonical
+ * UTC; `formatLocalTimestamp` converts one ISO-8601 UTC instant to
+ * the operator's IANA zone for display, rendering the full offset
+ * form `YYYY-MM-DDTHH:MM:SS+HH:MM`. Pure, deterministic for fixed
+ * inputs, fail-soft to the UTC `Z` form on a missing or invalid zone.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { formatLocalTimestamp } from "../../../src/core/brain/present-time.ts";
+
+describe("formatLocalTimestamp", () => {
+ test("UTC zone renders the explicit +00:00 offset form", () => {
+ expect(formatLocalTimestamp("2026-06-05T12:00:00Z", "UTC")).toBe("2026-06-05T12:00:00+00:00");
+ });
+
+ test("Europe/Berlin summer time renders +02:00", () => {
+ expect(formatLocalTimestamp("2026-06-05T12:00:00Z", "Europe/Berlin")).toBe(
+ "2026-06-05T14:00:00+02:00",
+ );
+ });
+
+ test("Europe/Berlin winter time renders +01:00 (DST boundary honored)", () => {
+ expect(formatLocalTimestamp("2026-01-15T12:00:00Z", "Europe/Berlin")).toBe(
+ "2026-01-15T13:00:00+01:00",
+ );
+ });
+
+ test("America/New_York renders a negative offset", () => {
+ expect(formatLocalTimestamp("2026-06-05T12:00:00Z", "America/New_York")).toBe(
+ "2026-06-05T08:00:00-04:00",
+ );
+ });
+
+ test("a date-line crossing changes the calendar day", () => {
+ expect(formatLocalTimestamp("2026-06-05T23:30:00Z", "Asia/Tokyo")).toBe(
+ "2026-06-06T08:30:00+09:00",
+ );
+ });
+
+ test("null zone falls back to the canonical UTC Z form", () => {
+ expect(formatLocalTimestamp("2026-06-05T12:00:00Z", null)).toBe("2026-06-05T12:00:00Z");
+ });
+
+ test("an invalid zone fails soft to the UTC Z form", () => {
+ expect(formatLocalTimestamp("2026-06-05T12:00:00Z", "Mars/Olympus_Mons")).toBe(
+ "2026-06-05T12:00:00Z",
+ );
+ });
+
+ test("an unparseable instant is returned verbatim", () => {
+ expect(formatLocalTimestamp("not-a-date", "UTC")).toBe("not-a-date");
+ });
+});
diff --git a/tests/core/brain/report-snapshot.test.ts b/tests/core/brain/report-snapshot.test.ts
new file mode 100644
index 00000000..56eaaeff
--- /dev/null
+++ b/tests/core/brain/report-snapshot.test.ts
@@ -0,0 +1,130 @@
+/**
+ * Report snapshots + deterministic delta (t_00eece5d): one run emits
+ * the human-readable report AND a machine-diffable JSON snapshot
+ * under `Brain/reports/<surface>/<date>.json` (schema
+ * `o2b.report-snapshot.v1`), so the next run can answer "what changed
+ * since last time" without re-deriving. The diff keys on stable
+ * identities - array order never produces spurious changes - and the
+ * reader is fail-soft: a torn prior snapshot reads as none.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ captureReportDelta,
+ diffReportPayloads,
+ loadLatestReportSnapshot,
+ REPORT_SNAPSHOT_SCHEMA_VERSION,
+ reportSnapshotsEnabled,
+ writeReportSnapshot,
+} from "../../../src/core/brain/report-snapshot.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-report-snap-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ delete process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"];
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ delete process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"];
+});
+
+describe("diffReportPayloads", () => {
+ test("keyed diff is insensitive to array order", () => {
+ const before = { retired: [{ id: "pref-a" }, { id: "pref-b" }], counts: { events: 3 } };
+ const after = { retired: [{ id: "pref-b" }, { id: "pref-a" }], counts: { events: 3 } };
+ const delta = diffReportPayloads(before, after);
+ expect(delta.added).toEqual([]);
+ expect(delta.removed).toEqual([]);
+ expect(delta.changed).toEqual([]);
+ });
+
+ test("added, removed, and changed paths are reported precisely", () => {
+ const before = {
+ retired: [{ id: "pref-a", reason: "stale" }],
+ topics: ["alpha", "beta"],
+ counts: { events: 3 },
+ };
+ const after = {
+ retired: [{ id: "pref-a", reason: "contradiction" }],
+ topics: ["alpha", "gamma"],
+ counts: { events: 5 },
+ };
+ const delta = diffReportPayloads(before, after);
+ expect(delta.added).toContain("topics[gamma]");
+ expect(delta.removed).toContain("topics[beta]");
+ const changedPaths = delta.changed.map((c) => c.path);
+ expect(changedPaths).toContain("retired/pref-a/reason");
+ expect(changedPaths).toContain("counts/events");
+ const events = delta.changed.find((c) => c.path === "counts/events")!;
+ expect(events.before).toBe("3");
+ expect(events.after).toBe("5");
+ });
+});
+
+describe("snapshot persistence", () => {
+ test("write + load round trip", () => {
+ writeReportSnapshot(vault, "digest", "2026-06-04", { counts: { events: 2 } });
+ const loaded = loadLatestReportSnapshot(vault, "digest", "2026-06-05");
+ expect(loaded).not.toBeNull();
+ expect(loaded!.date).toBe("2026-06-04");
+ expect((loaded!.payload as { counts: { events: number } }).counts.events).toBe(2);
+ const raw = JSON.parse(
+ readFileSync(join(vault, "Brain", "reports", "digest", "2026-06-04.json"), "utf8"),
+ );
+ expect(raw.schema).toBe(REPORT_SNAPSHOT_SCHEMA_VERSION);
+ });
+
+ test("loadLatest picks the newest snapshot strictly before the given date", () => {
+ writeReportSnapshot(vault, "digest", "2026-06-01", { v: 1 });
+ writeReportSnapshot(vault, "digest", "2026-06-03", { v: 2 });
+ writeReportSnapshot(vault, "digest", "2026-06-05", { v: 3 });
+ const loaded = loadLatestReportSnapshot(vault, "digest", "2026-06-05");
+ expect(loaded!.date).toBe("2026-06-03");
+ });
+
+ test("a torn prior snapshot reads as none", () => {
+ const dir = join(vault, "Brain", "reports", "digest");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "2026-06-04.json"), "{not json");
+ expect(loadLatestReportSnapshot(vault, "digest", "2026-06-05")).toBeNull();
+ });
+});
+
+describe("captureReportDelta", () => {
+ test("first enabled run persists and reports no delta; second reports the change", () => {
+ process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"] = "true";
+ const first = captureReportDelta(vault, "daily", "2026-06-04", { counts: { events: 1 } });
+ expect(first).not.toBeNull();
+ expect(first!.prior_date).toBeNull();
+ expect(first!.changed).toEqual([]);
+
+ const second = captureReportDelta(vault, "daily", "2026-06-05", { counts: { events: 4 } });
+ expect(second!.prior_date).toBe("2026-06-04");
+ expect(second!.changed.map((c) => c.path)).toContain("counts/events");
+ });
+
+ test("disabled flag writes nothing and returns null", () => {
+ const out = captureReportDelta(vault, "daily", "2026-06-04", { counts: { events: 1 } });
+ expect(out).toBeNull();
+ expect(existsSync(join(vault, "Brain", "reports"))).toBe(false);
+ });
+
+ test("reportSnapshotsEnabled honors config key and env mirror", () => {
+ const configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nreport_snapshots_enabled: true\n`);
+ expect(reportSnapshotsEnabled(configPath)).toBe(true);
+ writeFileSync(configPath, `vault: ${vault}\n`);
+ expect(reportSnapshotsEnabled(configPath)).toBe(false);
+ process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"] = "1";
+ expect(reportSnapshotsEnabled(configPath)).toBe(true);
+ });
+});
diff --git a/tests/core/brain/safeguard-wiring.test.ts b/tests/core/brain/safeguard-wiring.test.ts
new file mode 100644
index 00000000..3d3efa23
--- /dev/null
+++ b/tests/core/brain/safeguard-wiring.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Safeguard wiring (t_06784b8d): every long-running operation accepts
+ * an optional Safeguard and aborts cleanly at a checkpoint once the
+ * deadline passes. A tripped guard (deadline already exceeded at the
+ * first checkpoint) must stop each operation with
+ * SafeguardTimeoutError; an absent guard changes nothing.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { dream } from "../../../src/core/brain/dream.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { discoverBridges } from "../../../src/core/brain/link-graph/bridge-discovery.ts";
+import { detectCommunities } from "../../../src/core/brain/link-graph/communities.ts";
+import { runMaintenance } from "../../../src/core/brain/maintenance/lane.ts";
+import { createSafeguard, SafeguardTimeoutError } from "../../../src/core/brain/safeguard.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { Store } from "../../../src/core/search/store.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { makeConfig } from "../../helpers/search-fixtures.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-safeguard-wiring-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** A guard whose deadline has already passed at the first checkpoint. */
+function trippedGuard(operation: string) {
+ let calls = 0;
+ return createSafeguard({
+ operation,
+ timeoutMs: 1,
+ now: () => {
+ calls += 1;
+ return calls === 1 ? 0 : 1_000;
+ },
+ });
+}
+
+describe("indexVault", () => {
+ test("aborts at a checkpoint under a tripped guard", async () => {
+ writeFileSync(join(vault, "a.md"), "# A\n\nBody.\n");
+ writeFileSync(join(vault, "b.md"), "# B\n\nBody.\n");
+ const config = makeConfig({ vault, dbPath: join(tmp, "index.sqlite") });
+ await expect(indexVault(config, { safeguard: trippedGuard("reindex") })).rejects.toThrow(
+ SafeguardTimeoutError,
+ );
+ });
+
+ test("absent guard indexes normally", async () => {
+ writeFileSync(join(vault, "a.md"), "# A\n\nBody.\n");
+ const config = makeConfig({ vault, dbPath: join(tmp, "index.sqlite") });
+ const stats = await indexVault(config);
+ expect(stats.added).toBe(1);
+ });
+});
+
+describe("discoverBridges and detectCommunities", () => {
+ test("both abort under a tripped guard", async () => {
+ writeFileSync(join(vault, "a.md"), "# A\n\nSee [[b]].\n");
+ writeFileSync(join(vault, "b.md"), "# B\n\nSee [[a]].\n");
+ const config = makeConfig({ vault, dbPath: join(tmp, "index.sqlite") });
+ await indexVault(config);
+ const store = await Store.open(config, { mode: "read" });
+ try {
+ expect(() => discoverBridges(store, { safeguard: trippedGuard("bridges") })).toThrow(
+ SafeguardTimeoutError,
+ );
+ expect(() => detectCommunities(store, { safeguard: trippedGuard("clusters") })).toThrow(
+ SafeguardTimeoutError,
+ );
+ } finally {
+ await store.close();
+ }
+ });
+});
+
+describe("dream", () => {
+ test("aborts under a tripped guard", () => {
+ bootstrapBrain(vault, { configPath });
+ expect(() => dream(vault, { safeguard: trippedGuard("dream") })).toThrow(SafeguardTimeoutError);
+ });
+});
+
+describe("maintenance lane", () => {
+ test("a timed-out task is classified timed_out and the lane survives", async () => {
+ bootstrapBrain(vault, { configPath });
+ const result = await runMaintenance(vault, {
+ now: new Date("2026-06-05T03:00:00Z"),
+ holder: "test@1",
+ force: true,
+ tasks: [
+ {
+ name: "dream",
+ run: async () => {
+ trippedGuard("dream").checkpoint();
+ },
+ },
+ {
+ name: "reindex",
+ run: async () => {},
+ },
+ ],
+ });
+ expect(result.verdict).toBe("run");
+ const dreamTask = result.tasks.find((t) => t.name === "dream")!;
+ expect(dreamTask.ok).toBe(false);
+ expect(dreamTask.timed_out).toBe(true);
+ const reindexTask = result.tasks.find((t) => t.name === "reindex")!;
+ expect(reindexTask.ok).toBe(true);
+ expect(reindexTask.timed_out).toBeUndefined();
+ });
+
+ test("oversized task error strings are capped with a marker", async () => {
+ bootstrapBrain(vault, { configPath });
+ const result = await runMaintenance(vault, {
+ now: new Date("2026-06-05T03:00:00Z"),
+ holder: "test@1",
+ force: true,
+ tasks: [
+ {
+ name: "dream",
+ run: async () => {
+ throw new Error("x".repeat(10_000));
+ },
+ },
+ ],
+ });
+ const task = result.tasks[0]!;
+ expect(task.ok).toBe(false);
+ expect(task.error!.length).toBeLessThan(5_000);
+ expect(task.error).toContain("truncated");
+ });
+});
diff --git a/tests/core/brain/safeguard.test.ts b/tests/core/brain/safeguard.test.ts
new file mode 100644
index 00000000..a6309ae7
--- /dev/null
+++ b/tests/core/brain/safeguard.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Operation safeguard (t_06784b8d): cooperative deadline + output
+ * caps for long-running brain operations. Bun + synchronous SQLite
+ * cannot be preempted honestly, so the safeguard is a deadline object
+ * whose checkpoint() throws at the next natural iteration boundary
+ * past the deadline - no fake async cancellation. Timeouts resolve
+ * per-operation key -> global key -> built-in default; 0 disables.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ capOutput,
+ createSafeguard,
+ resolveSafeguardTimeoutMs,
+ SAFEGUARD_DEFAULT_TIMEOUT_SECONDS,
+ SafeguardTimeoutError,
+} from "../../../src/core/brain/safeguard.ts";
+
+let tmp: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-safeguard-"));
+ for (const key of ["OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+describe("createSafeguard", () => {
+ test("checkpoint passes before the deadline and throws after it", () => {
+ let clock = 1_000;
+ const guard = createSafeguard({ operation: "dream", timeoutMs: 50, now: () => clock });
+ guard.checkpoint();
+ clock += 49;
+ guard.checkpoint();
+ clock += 2;
+ expect(() => guard.checkpoint()).toThrow(SafeguardTimeoutError);
+ });
+
+ test("the error names the operation and the budget", () => {
+ let clock = 0;
+ const guard = createSafeguard({ operation: "reindex", timeoutMs: 10, now: () => clock });
+ clock = 11;
+ try {
+ guard.checkpoint();
+ throw new Error("expected SafeguardTimeoutError");
+ } catch (exc) {
+ expect(exc).toBeInstanceOf(SafeguardTimeoutError);
+ const e = exc as SafeguardTimeoutError;
+ expect(e.operation).toBe("reindex");
+ expect(e.timeoutMs).toBe(10);
+ expect(e.message).toContain("reindex");
+ expect(e.message).toContain("10");
+ }
+ });
+
+ test("timeoutMs 0 disables the deadline entirely", () => {
+ let clock = 0;
+ const guard = createSafeguard({ operation: "dream", timeoutMs: 0, now: () => clock });
+ clock = Number.MAX_SAFE_INTEGER;
+ expect(() => guard.checkpoint()).not.toThrow();
+ expect(guard.timeoutMs).toBeNull();
+ });
+
+ test("null timeout also disables", () => {
+ const guard = createSafeguard({ operation: "dream", timeoutMs: null });
+ expect(() => guard.checkpoint()).not.toThrow();
+ });
+});
+
+describe("resolveSafeguardTimeoutMs", () => {
+ function writeConfig(body: string): string {
+ const p = join(tmp, "config.yaml");
+ writeFileSync(p, body);
+ return p;
+ }
+
+ test("defaults to the built-in budget with no config", () => {
+ const p = writeConfig(`vault: ${tmp}\n`);
+ expect(resolveSafeguardTimeoutMs("dream", p)).toBe(SAFEGUARD_DEFAULT_TIMEOUT_SECONDS * 1000);
+ });
+
+ test("global key overrides the default", () => {
+ const p = writeConfig(`vault: ${tmp}\nsafeguard_timeout_seconds: 120\n`);
+ expect(resolveSafeguardTimeoutMs("dream", p)).toBe(120_000);
+ expect(resolveSafeguardTimeoutMs("bridges", p)).toBe(120_000);
+ });
+
+ test("per-operation key beats the global key", () => {
+ const p = writeConfig(
+ `vault: ${tmp}\nsafeguard_timeout_seconds: 120\nsafeguard_timeout_dream_seconds: 30\n`,
+ );
+ expect(resolveSafeguardTimeoutMs("dream", p)).toBe(30_000);
+ expect(resolveSafeguardTimeoutMs("reindex", p)).toBe(120_000);
+ });
+
+ test("environment mirror beats the config global", () => {
+ const p = writeConfig(`vault: ${tmp}\nsafeguard_timeout_seconds: 120\n`);
+ process.env["OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT"] = "45";
+ expect(resolveSafeguardTimeoutMs("clusters", p)).toBe(45_000);
+ });
+
+ test("0 disables and resolves to null", () => {
+ const p = writeConfig(`vault: ${tmp}\nsafeguard_timeout_seconds: 0\n`);
+ expect(resolveSafeguardTimeoutMs("dream", p)).toBeNull();
+ });
+
+ test("invalid values fail soft to the default", () => {
+ const p = writeConfig(`vault: ${tmp}\nsafeguard_timeout_seconds: soon\n`);
+ expect(resolveSafeguardTimeoutMs("dream", p)).toBe(SAFEGUARD_DEFAULT_TIMEOUT_SECONDS * 1000);
+ });
+});
+
+describe("capOutput", () => {
+ test("under the cap is returned unchanged", () => {
+ expect(capOutput("hello", 100)).toEqual({ text: "hello", truncated: false });
+ });
+
+ test("over the cap truncates with an explicit marker inside the budget", () => {
+ const out = capOutput("a".repeat(500), 100);
+ expect(out.truncated).toBe(true);
+ expect(out.text).toContain("truncated");
+ expect(out.text.startsWith("aaa")).toBe(true);
+ // The marker counts against the cap: the total stays within it.
+ expect(Buffer.byteLength(out.text, "utf8")).toBeLessThanOrEqual(100);
+ });
+
+ test("multibyte input is not split mid-character", () => {
+ const out = capOutput("я".repeat(200), 100);
+ expect(out.truncated).toBe(true);
+ // Every kept character survives intact (no U+FFFD replacement).
+ expect(out.text).not.toContain("�");
+ expect(Buffer.byteLength(out.text, "utf8")).toBeLessThanOrEqual(100);
+ });
+});
diff --git a/tests/e2e/release-1-0-stability.integration.test.ts b/tests/e2e/release-1-0-stability.integration.test.ts
new file mode 100644
index 00000000..4aec82e0
--- /dev/null
+++ b/tests/e2e/release-1-0-stability.integration.test.ts
@@ -0,0 +1,182 @@
+/**
+ * Release 1.0.0 - Stability & Trust, end-to-end composition
+ * (epic t_a77ade0a): one temp vault exercises every unit together.
+ *
+ * 1. A removed alias answers a tombstone over MCP tools/call.
+ * 2. The staged dream lifecycle runs stage -> validate -> apply and
+ * the doctor flags a stale alias reference in a Brain note.
+ * 3. A brief renders the configured timezone additively.
+ * 4. A second digest run reports a precise snapshot delta.
+ * 5. A long operation aborts cleanly under a tripped safeguard.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runDoctor } from "../../src/core/brain/doctor.ts";
+import {
+ applyDreamBundle,
+ stageDream,
+ validateDreamBundle,
+} from "../../src/core/brain/dream-stage.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { listMetrics } from "../../src/core/brain/metrics.ts";
+import { createSafeguard, SafeguardTimeoutError } from "../../src/core/brain/safeguard.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { makeConfig } from "../helpers/search-fixtures.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-e2e-stability-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ "OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS",
+ ]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: claude\ntimezone: Europe/Berlin\nreport_snapshots_enabled: true\n`,
+ );
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { 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 makeServer(): Promise<MCPServer> {
+ const server = new MCPServer({ vault, configPath });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "stability-e2e", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ return server;
+}
+
+let id = 100;
+async function call(server: MCPServer, name: string, args: Record<string, unknown>) {
+ id += 1;
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id,
+ method: "tools/call",
+ params: { name, arguments: args },
+ })) as {
+ result?: { structuredContent?: Record<string, unknown> };
+ error?: { code: number; message: string };
+ };
+}
+
+test("the 1.0.0 composition holds end to end", async () => {
+ const server = await makeServer();
+
+ // 1. Tombstone: the removed alias names its replacement.
+ const tombstone = await call(server, "brain_digest", {});
+ expect(tombstone.error!.code).toBe(-32602);
+ expect(tombstone.error!.message).toContain("brain_digest was removed in 1.0.0");
+ expect(tombstone.error!.message).toContain('brain_brief with view="digest"');
+
+ // 2. Doctor flags a stale alias reference in a Brain note.
+ writeFileSync(
+ join(vault, "Brain", "old-playbook.md"),
+ "# Playbook\n\nEvery morning call brain_digest first.\n",
+ );
+ const doctorWarnings = runDoctor(vault).warnings.filter(
+ (w) => w.code === "removed-tool-reference",
+ );
+ expect(doctorWarnings).toHaveLength(1);
+ expect(doctorWarnings[0]!.message).toContain("brain_brief");
+
+ // Staged dream lifecycle over a real signal cluster.
+ for (const i of [1, 2, 3]) {
+ writeSignal(vault, {
+ topic: "e2e-topic",
+ signal: "positive",
+ agent: "claude",
+ principle: "Rule for e2e-topic.",
+ created_at: "2026-06-01T10:00:00Z",
+ date: "2026-06-01",
+ slug: `e2e-${i}`,
+ scope: "writing",
+ });
+ }
+ const bundle = stageDream(vault, { now: new Date("2026-06-05T12:00:00Z") });
+ expect(bundle.plan.new_unconfirmed).toEqual(["pref-e2e-topic"]);
+ const verdict = validateDreamBundle(vault, bundle.runId, {
+ now: new Date("2026-06-05T13:00:00Z"),
+ });
+ expect(verdict.valid).toBe(true);
+ const outcome = applyDreamBundle(vault, bundle.runId, {
+ now: new Date("2026-06-05T13:00:00Z"),
+ });
+ expect(outcome.applied).toBe(true);
+ expect(listMetrics(vault, { surface: "dream_stage" }).length).toBeGreaterThanOrEqual(2);
+
+ // 3. Timezone: the daily brief carries additive local fields.
+ const brief = await call(server, "brain_brief", { view: "daily", date: "2026-06-05" });
+ const briefBody = brief.result!.structuredContent!;
+ expect(briefBody["timezone"]).toBe("Europe/Berlin");
+ expect(String(briefBody["local_time"])).toMatch(/\+0[12]:00$/);
+
+ // 4. Dual output: the second digest run reports a delta against the
+ // first day's snapshot (the applied preference changed the data).
+ const firstDigest = await call(server, "brain_brief", {
+ view: "digest",
+ since: "2026-06-01T00:00:00Z",
+ until: "2026-06-04T00:00:00Z",
+ });
+ expect(firstDigest.result!.structuredContent!["delta"]).toBeDefined();
+ const secondDigest = await call(server, "brain_brief", {
+ view: "digest",
+ since: "2026-06-01T00:00:00Z",
+ until: "2026-06-06T00:00:00Z",
+ });
+ const delta = secondDigest.result!.structuredContent!["delta"] as {
+ prior_date: string | null;
+ };
+ expect(delta.prior_date).toBe("2026-06-04");
+
+ // 5. Safeguard: a tripped deadline aborts indexing at a checkpoint.
+ writeFileSync(join(vault, "note-a.md"), "# A\n\nBody.\n");
+ let calls = 0;
+ const tripped = createSafeguard({
+ operation: "reindex",
+ timeoutMs: 1,
+ now: () => {
+ calls += 1;
+ return calls === 1 ? 0 : 10_000;
+ },
+ });
+ const searchConfig = makeConfig({ vault, dbPath: join(tmp, "index.sqlite") });
+ await expect(indexVault(searchConfig, { safeguard: tripped })).rejects.toThrow(
+ SafeguardTimeoutError,
+ );
+});
diff --git a/tests/mcp/brain-monthly.test.ts b/tests/mcp/brain-monthly.test.ts
index 0bb688ca..003c677c 100644
--- a/tests/mcp/brain-monthly.test.ts
+++ b/tests/mcp/brain-monthly.test.ts
@@ -26,11 +26,12 @@ afterEach(() => {
rmSync(vault, { recursive: true, force: true });
});
-describe("brain_monthly_review MCP tool", () => {
+describe("brain_brief view=monthly MCP tool", () => {
test("is registered and returns monthly summary", async () => {
- const tool = BRAIN_TOOLS.find((entry) => entry.name === "brain_monthly_review");
+ const tool = BRAIN_TOOLS.find((entry) => entry.name === "brain_brief");
expect(tool).toBeDefined();
const out = (await tool!.handler(ctx as any, {
+ view: "monthly",
month: "2026-05",
})) as Record<string, unknown>;
expect(out["month"]).toBe("2026-05");
@@ -38,8 +39,10 @@ describe("brain_monthly_review MCP tool", () => {
});
test("rejects malformed month", async () => {
- const tool = BRAIN_TOOLS.find((entry) => entry.name === "brain_monthly_review");
- await expect(tool!.handler(ctx as any, { month: "2026-13" })).rejects.toMatchObject({
+ const tool = BRAIN_TOOLS.find((entry) => entry.name === "brain_brief");
+ await expect(
+ tool!.handler(ctx as any, { view: "monthly", month: "2026-13" }),
+ ).rejects.toMatchObject({
code: -32602,
});
});
diff --git a/tests/mcp/brain-trigger-tool.test.ts b/tests/mcp/brain-trigger-tool.test.ts
index 2581ee1b..9154456c 100644
--- a/tests/mcp/brain-trigger-tool.test.ts
+++ b/tests/mcp/brain-trigger-tool.test.ts
@@ -87,9 +87,9 @@ test("brain_trigger rejects unknown operations and terminal transitions", async
).toThrow("terminal");
});
-test("brain_morning_brief surfaces pending triggers once per cooldown", async () => {
+test("brain_brief view=morning surfaces pending triggers once per cooldown", async () => {
createTriggers(vault, [CANDIDATE], { now: new Date() });
- const first = (await tool("brain_morning_brief").handler(ctx, {})) as {
+ const first = (await tool("brain_brief").handler(ctx, { view: "morning" })) as {
text: string;
triggers?: Array<{ id: string }>;
};
@@ -97,7 +97,7 @@ test("brain_morning_brief surfaces pending triggers once per cooldown", async ()
expect(first.text).toContain("Pending triggers");
// Second brief inside the cooldown window: silent.
- const second = (await tool("brain_morning_brief").handler(ctx, {})) as {
+ const second = (await tool("brain_brief").handler(ctx, { view: "morning" })) as {
text: string;
triggers?: unknown[];
};
@@ -105,7 +105,10 @@ test("brain_morning_brief surfaces pending triggers once per cooldown", async ()
expect(second.text).not.toContain("Pending triggers");
});
-test("brain_morning_brief without triggers keeps the legacy shape", async () => {
- const brief = (await tool("brain_morning_brief").handler(ctx, {})) as Record<string, unknown>;
+test("brain_brief view=morning without triggers keeps the legacy shape", async () => {
+ const brief = (await tool("brain_brief").handler(ctx, { view: "morning" })) as Record<
+ string,
+ unknown
+ >;
expect(brief["triggers"]).toBeUndefined();
});
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index d59d7a96..82c8237f 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -377,11 +377,11 @@ describe("brain_apply_evidence", () => {
// brain_digest
// ---------------------------------------------------------------------------
-describe("brain_digest", () => {
+describe("brain_brief view=digest", () => {
test("empty vault returns 'no changes' markdown", async () => {
const server = makeServer();
await initialize(server);
- const r = await call(server, "brain_digest", {});
+ const r = await call(server, "brain_brief", { view: "digest" });
expect(r.result.isError).toBe(false);
const s = r.result.structuredContent;
expect(s.empty).toBe(true);
@@ -405,7 +405,8 @@ describe("brain_digest", () => {
});
const server = makeServer();
await initialize(server);
- const r = await call(server, "brain_digest", {
+ const r = await call(server, "brain_brief", {
+ view: "digest",
since: "2026-05-14T00:00:00Z",
until: "2026-05-14T23:59:59Z",
});
@@ -435,7 +436,8 @@ describe("brain_digest", () => {
});
const server = makeServer();
await initialize(server);
- const r = await call(server, "brain_digest", {
+ const r = await call(server, "brain_brief", {
+ view: "digest",
since: "2026-05-14T00:00:00Z",
until: "2026-05-14T23:59:59Z",
});
@@ -447,7 +449,7 @@ describe("brain_digest", () => {
test("format=json returns valid JSON content", async () => {
const server = makeServer();
await initialize(server);
- const r = await call(server, "brain_digest", { format: "json" });
+ const r = await call(server, "brain_brief", { view: "digest", format: "json" });
expect(r.result.isError).toBe(false);
const s = r.result.structuredContent;
expect(s.format).toBe("json");
@@ -629,7 +631,7 @@ describe("deprecated MCP tools — advertised list", () => {
"brain_feedback",
"brain_dream",
"brain_apply_evidence",
- "brain_digest",
+ "brain_brief",
"brain_query",
"brain_doctor",
"brain_backlinks",
diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.ts
index d441b0c4..bc125c08 100644
--- a/tests/mcp/consolidated-tools.test.ts
+++ b/tests/mcp/consolidated-tools.test.ts
@@ -1,9 +1,10 @@
/**
* Consolidated read tools (token-diet, t_3920db77): `brain_brief`,
- * `brain_analytics`, and `schema_inspect` dispatch by `view` to the
- * exact handlers of the tools they replace; every predecessor stays
- * registered as a deprecated delegating alias for at least one minor
- * release, so existing MCP clients migrate by renaming the call.
+ * `brain_analytics`, and `schema_inspect` dispatch by `view`. The
+ * per-view predecessor aliases were removed in 1.0.0 (epic
+ * t_a77ade0a) - their tombstones live in `REMOVED_TOOLS` and are
+ * covered by `removed-tools.test.ts`; here every consolidated view
+ * must keep working on its own.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
@@ -49,39 +50,21 @@ async function run(name: string, args: Record<string, unknown>): Promise<unknown
return await findTool(TOOLS, name).handler(ctx, args);
}
-/**
- * Volatile keys stripped before equality: handlers stamp a wall-clock
- * `generated_at` per call, so two back-to-back runs of the SAME code
- * path differ in that field alone. Everything else must match byte
- * for byte.
- */
-function stable(value: unknown): string {
- return JSON.stringify(value, (key, v) => (key === "generated_at" ? undefined : v));
-}
-
describe("brain_brief", () => {
- const CASES: ReadonlyArray<{
- view: string;
- alias: string;
- args?: Record<string, unknown>;
- }> = [
- { view: "morning", alias: "brain_morning_brief" },
- { view: "daily", alias: "brain_daily_brief", args: { date: "2026-05-02" } },
- { view: "weekly", alias: "brain_weekly_synthesis", args: { week_end: "2026-05-08" } },
- { view: "monthly", alias: "brain_monthly_review", args: { month: "2026-05" } },
- { view: "operator", alias: "brain_operator_summary", args: { include_dream: false } },
- {
- view: "digest",
- alias: "brain_digest",
- args: { since: "2026-05-01T00:00:00Z", until: "2026-05-03T00:00:00Z" },
- },
+ const CASES: ReadonlyArray<{ view: string; args?: Record<string, unknown> }> = [
+ { view: "morning" },
+ { view: "daily", args: { date: "2026-05-02" } },
+ { view: "weekly", args: { week_end: "2026-05-08" } },
+ { view: "monthly", args: { month: "2026-05" } },
+ { view: "operator", args: { include_dream: false } },
+ { view: "digest", args: { since: "2026-05-01T00:00:00Z", until: "2026-05-03T00:00:00Z" } },
];
- for (const { view, alias, args } of CASES) {
- test(`view=${view} returns exactly what ${alias} returns`, async () => {
- const consolidated = await run("brain_brief", { view, ...args });
- const predecessor = await run(alias, args ?? {});
- expect(stable(consolidated)).toBe(stable(predecessor));
+ for (const { view, args } of CASES) {
+ test(`view=${view} resolves to a structured envelope`, async () => {
+ const result = await run("brain_brief", { view, ...args });
+ expect(result).toBeDefined();
+ expect(typeof result).toBe("object");
});
}
@@ -95,33 +78,36 @@ describe("brain_brief", () => {
});
describe("brain_analytics", () => {
- test("view=timeline returns exactly what brain_timeline returns", async () => {
- // Explicit window: the tool defaults `until` to wall-clock now,
- // which would differ between two back-to-back calls.
+ test("view=timeline returns an events window", async () => {
const args = { pref_id: "pref-fixture", since: "2026-05-01", until: "2026-06-01" };
- const consolidated = await run("brain_analytics", { view: "timeline", ...args });
- const predecessor = await run("brain_timeline", args);
- expect(stable(consolidated)).toBe(stable(predecessor));
+ const result = (await run("brain_analytics", { view: "timeline", ...args })) as Record<
+ string,
+ unknown
+ >;
+ expect(Array.isArray(result["events"])).toBe(true);
});
- test("view=belief_evolution returns exactly what brain_belief_evolution returns", async () => {
- const args = { pref_id: "pref-fixture" };
- const consolidated = await run("brain_analytics", { view: "belief_evolution", ...args });
- const predecessor = await run("brain_belief_evolution", args);
- expect(stable(consolidated)).toBe(stable(predecessor));
+ test("view=belief_evolution returns transitions for a preference", async () => {
+ const result = (await run("brain_analytics", {
+ view: "belief_evolution",
+ pref_id: "pref-fixture",
+ })) as Record<string, unknown>;
+ expect(result).toBeDefined();
+ expect(typeof result).toBe("object");
});
- test("view=concept_synthesis returns exactly what brain_concept_synthesis returns", async () => {
- const args = { id: "pref-fixture" };
- const consolidated = await run("brain_analytics", { view: "concept_synthesis", ...args });
- const predecessor = await run("brain_concept_synthesis", args);
- expect(stable(consolidated)).toBe(stable(predecessor));
+ test("view=concept_synthesis resolves for a known id", async () => {
+ const result = await run("brain_analytics", { view: "concept_synthesis", id: "pref-fixture" });
+ expect(result).toBeDefined();
});
test("view=attention_flows defaults the operation to list", async () => {
- const consolidated = await run("brain_analytics", { view: "attention_flows" });
- const predecessor = await run("brain_attention_flows", { operation: "list" });
- expect(stable(consolidated)).toBe(stable(predecessor));
+ const result = (await run("brain_analytics", { view: "attention_flows" })) as Record<
+ string,
+ unknown
+ >;
+ expect(result).toBeDefined();
+ expect(typeof result).toBe("object");
});
test("invalid view raises a clear error", async () => {
@@ -130,35 +116,21 @@ describe("brain_analytics", () => {
});
describe("schema_inspect", () => {
- const CASES: ReadonlyArray<{ view: string; alias: string; args?: Record<string, unknown> }> = [
- { view: "graph", alias: "schema_graph" },
- { view: "lint", alias: "schema_lint" },
- { view: "stats", alias: "schema_stats" },
- { view: "orphans", alias: "schema_review_orphans" },
- { view: "active_pack", alias: "get_active_schema_pack" },
- { view: "packs", alias: "list_schema_packs" },
- ];
-
- for (const { view, alias, args } of CASES) {
- test(`view=${view} returns exactly what ${alias} returns`, async () => {
- const consolidated = await run("schema_inspect", { view, ...args });
- const predecessor = await run(alias, args ?? {});
- expect(stable(consolidated)).toBe(stable(predecessor));
+ for (const view of ["graph", "lint", "stats", "orphans", "active_pack", "packs"]) {
+ test(`view=${view} resolves`, async () => {
+ const result = await run("schema_inspect", { view });
+ expect(result).toBeDefined();
});
}
test("view=explain_type forwards the token", async () => {
- const consolidated = run("schema_inspect", { view: "explain_type", token: "no-such-token" });
- const predecessor = run("schema_explain_type", { token: "no-such-token" });
- // Both paths must agree - either both resolve or both reject with
- // the same message.
- const [a, b] = await Promise.allSettled([consolidated, predecessor]);
- expect(a.status).toBe(b.status);
- if (a.status === "rejected" && b.status === "rejected") {
- expect((a.reason as Error).message).toBe((b.reason as Error).message);
- } else if (a.status === "fulfilled" && b.status === "fulfilled") {
- expect(stable(a.value)).toBe(stable(b.value));
- }
+ // The explanation must echo the normalized token, proving the
+ // argument reaches the underlying handler.
+ const result = (await run("schema_inspect", {
+ view: "explain_type",
+ token: "no-such-token",
+ })) as Record<string, unknown>;
+ expect(result["token"]).toBe("no-such-token");
});
test("invalid view raises a clear error", async () => {
@@ -166,45 +138,32 @@ describe("schema_inspect", () => {
});
});
-describe("deprecated aliases", () => {
- const ALIASES = [
- "brain_morning_brief",
- "brain_daily_brief",
- "brain_weekly_synthesis",
- "brain_monthly_review",
- "brain_operator_summary",
- "brain_digest",
- "brain_timeline",
- "brain_attention_flows",
- "brain_belief_evolution",
- "brain_concept_synthesis",
- "schema_graph",
- "schema_lint",
- "schema_stats",
- "schema_review_orphans",
- "schema_explain_type",
- "get_active_schema_pack",
- "list_schema_packs",
- "reload_schema_pack",
- ];
+describe("timezone presentation (t_2ccadc6a)", () => {
+ test("a configured timezone adds additive local fields to brief envelopes", async () => {
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\ntimezone: Asia/Tokyo\n`);
+ const result = (await run("brain_brief", { view: "daily", date: "2026-06-05" })) as Record<
+ string,
+ unknown
+ >;
+ expect(result["timezone"]).toBe("Asia/Tokyo");
+ expect(String(result["local_time"])).toContain("+09:00");
+ });
- test("every alias stays registered with a one-line deprecation description", () => {
- for (const name of ALIASES) {
- const tool = findTool(TOOLS, name);
- expect(tool.description).toContain("Deprecated alias");
- expect(tool.description.length).toBeLessThanOrEqual(160);
- }
+ test("no configured timezone keeps the envelope unchanged", async () => {
+ const result = (await run("brain_brief", { view: "daily", date: "2026-06-05" })) as Record<
+ string,
+ unknown
+ >;
+ expect(result["timezone"]).toBeUndefined();
+ expect(result["local_time"]).toBeUndefined();
});
+});
- test("consolidated tools are registered", () => {
+describe("consolidated registration", () => {
+ test("consolidated tools are registered and advertised", async () => {
for (const name of ["brain_brief", "brain_analytics", "schema_inspect"]) {
expect(() => findTool(TOOLS, name)).not.toThrow();
}
- });
-});
-
-describe("alias listing", () => {
- test("aliases are callable but hidden from the advertised tool list", async () => {
const { MCPServer } = await import("../../src/mcp/server.ts");
const server = new MCPServer({ vault, configPath });
await server.handleRequest({
@@ -225,16 +184,10 @@ describe("alias listing", () => {
})) as { result: { tools: Array<{ name: string }> } };
const listed = new Set(list.result.tools.map((t) => t.name));
expect(listed.has("brain_brief")).toBe(true);
+ expect(listed.has("brain_analytics")).toBe(true);
+ expect(listed.has("schema_inspect")).toBe(true);
+ // The 1.0.0 sweep removed the alias layer entirely.
expect(listed.has("brain_daily_brief")).toBe(false);
expect(listed.has("schema_stats")).toBe(false);
-
- // Still callable: the alias resolves through tools/call.
- const call = (await server.handleRequest({
- jsonrpc: "2.0",
- id: 3,
- method: "tools/call",
- params: { name: "brain_daily_brief", arguments: { date: "2026-05-02" } },
- })) as { result: { isError?: boolean } };
- expect(call.result.isError).not.toBe(true);
});
});
diff --git a/tests/mcp/dream-stage-tool.test.ts b/tests/mcp/dream-stage-tool.test.ts
new file mode 100644
index 00000000..564db4f5
--- /dev/null
+++ b/tests/mcp/dream-stage-tool.test.ts
@@ -0,0 +1,141 @@
+/**
+ * `brain_dream` staged-lifecycle actions over MCP (t_ae8a8ec0): the
+ * one dream tool gains an `action` parameter instead of new tools -
+ * the 1.0.0 surface stays at 77. INVALID_PARAMS fire before any
+ * environment work; the full stage -> validate -> apply cycle runs
+ * through tools/call.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-dream-stage-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "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;
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { 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 makeServer(): Promise<MCPServer> {
+ const server = new MCPServer({ vault, configPath });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "dream-stage-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ return server;
+}
+
+let callId = 10;
+async function call(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<{ structured?: Record<string, unknown>; errorCode?: number }> {
+ callId += 1;
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: callId,
+ method: "tools/call",
+ params: { name: "brain_dream", arguments: args },
+ })) as {
+ result?: { structuredContent?: Record<string, unknown> };
+ error?: { code: number };
+ };
+ if (r.error) return { errorCode: r.error.code };
+ return { structured: r.result?.structuredContent };
+}
+
+function seedCluster(topic: string): void {
+ for (const i of [1, 2, 3]) {
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle: `Rule for ${topic}.`,
+ created_at: "2026-06-01T10:00:00Z",
+ date: "2026-06-01",
+ slug: `${topic}-${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+test("full staged cycle through tools/call", async () => {
+ seedCluster("mcp-cycle");
+ const server = await makeServer();
+
+ const staged = await call(server, { action: "stage", now: "2026-06-05T12:00:00Z" });
+ const runId = staged.structured!["run_id"] as string;
+ expect(runId).toMatch(/^stage-/);
+
+ const validated = await call(server, { action: "validate", run_id: runId });
+ expect(validated.structured!["valid"]).toBe(true);
+
+ const applied = await call(server, { action: "apply", run_id: runId });
+ expect(applied.structured!["applied"]).toBe(true);
+ expect(applied.structured!["new_unconfirmed"]).toEqual(["pref-mcp-cycle"]);
+
+ const listed = await call(server, { action: "list" });
+ const bundles = listed.structured!["bundles"] as Array<{ status: string }>;
+ expect(bundles[0]!.status).toBe("applied");
+});
+
+test("INVALID_PARAMS before environment work", async () => {
+ const server = await makeServer();
+ expect((await call(server, { action: "hibernate" })).errorCode).toBe(-32602);
+ expect((await call(server, { action: "apply" })).errorCode).toBe(-32602);
+ expect((await call(server, { action: "validate" })).errorCode).toBe(-32602);
+});
+
+test("discard over MCP removes a staged bundle", async () => {
+ seedCluster("mcp-discard");
+ const server = await makeServer();
+ const staged = await call(server, { action: "stage", now: "2026-06-05T12:00:00Z" });
+ const runId = staged.structured!["run_id"] as string;
+ const discarded = await call(server, { action: "discard", run_id: runId });
+ expect(discarded.structured!["removed"]).toBe(true);
+});
+
+test("plain action=run keeps the legacy summary shape", async () => {
+ seedCluster("mcp-legacy");
+ const server = await makeServer();
+ const r = await call(server, { now: "2026-06-05T12:00:00Z" });
+ expect(r.structured!["new_unconfirmed"]).toEqual(["pref-mcp-legacy"]);
+ expect(typeof r.structured!["run_id"]).toBe("string");
+});
diff --git a/tests/mcp/link-graph-mcp-fields.test.ts b/tests/mcp/link-graph-mcp-fields.test.ts
index cc230883..c6dc3db2 100644
--- a/tests/mcp/link-graph-mcp-fields.test.ts
+++ b/tests/mcp/link-graph-mcp-fields.test.ts
@@ -194,19 +194,19 @@ describe("brain_moc_audit round trip", () => {
});
});
-describe("brain_concept_synthesis registration", () => {
+describe("brain_analytics view=concept_synthesis registration", () => {
test("registered in the full tool table", () => {
const tools = buildToolTable("full");
- expect(tools.find((t) => t.name === "brain_concept_synthesis")).toBeDefined();
+ expect(tools.find((t) => t.name === "brain_analytics")).toBeDefined();
});
test("NOT in the writer-only scope", () => {
const tools = buildToolTable("writer");
- expect(tools.find((t) => t.name === "brain_concept_synthesis")).toBeUndefined();
+ expect(tools.find((t) => t.name === "brain_analytics")).toBeUndefined();
});
});
-describe("brain_concept_synthesis round trip", () => {
+describe("brain_analytics view=concept_synthesis round trip", () => {
test("returns envelope with linkers", async () => {
writePref("pref-tgt", {
kind: "preference",
@@ -227,7 +227,8 @@ describe("brain_concept_synthesis round trip", () => {
);
const server = new MCPServer({ vault, configPath });
await initialize(server);
- const r = await callTool(server, "brain_concept_synthesis", {
+ const r = await callTool(server, "brain_analytics", {
+ view: "concept_synthesis",
id: "pref-tgt",
});
const out = JSON.parse(r.result!.content[0]!.text);
@@ -257,7 +258,8 @@ describe("brain_concept_synthesis round trip", () => {
);
const server = new MCPServer({ vault, configPath });
await initialize(server);
- const r = await callTool(server, "brain_concept_synthesis", {
+ const r = await callTool(server, "brain_analytics", {
+ view: "concept_synthesis",
id: "pref-tgt",
include_unlinked: true,
});
@@ -269,7 +271,7 @@ describe("brain_concept_synthesis round trip", () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
for (const args of [{ id: "" }, { id: "pref-x", include_unlinked: "yes" }]) {
- const r = await callTool(server, "brain_concept_synthesis", args);
+ const r = await callTool(server, "brain_analytics", { view: "concept_synthesis", ...args });
expect(r.error?.code).toBe(-32602);
}
});
diff --git a/tests/mcp/operator-summary-tool.test.ts b/tests/mcp/operator-summary-tool.test.ts
index e4f4267f..ad6a6bc6 100644
--- a/tests/mcp/operator-summary-tool.test.ts
+++ b/tests/mcp/operator-summary-tool.test.ts
@@ -71,24 +71,24 @@ async function callSummary(
jsonrpc: JSONRPC_VERSION,
id: 9,
method: "tools/call",
- params: { name: "brain_operator_summary", arguments: args },
+ params: { name: "brain_brief", arguments: { view: "operator", ...args } },
})) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
return JSON.parse(r.result.content[0]!.text);
}
-describe("brain_operator_summary tool registration", () => {
+describe("brain_brief view=operator tool registration", () => {
test("registered in the full tool table", () => {
const tools = buildToolTable("full");
- expect(tools.find((t) => t.name === "brain_operator_summary")).toBeDefined();
+ expect(tools.find((t) => t.name === "brain_brief")).toBeDefined();
});
test("NOT in the writer-only scope", () => {
const tools = buildToolTable("writer");
- expect(tools.find((t) => t.name === "brain_operator_summary")).toBeUndefined();
+ expect(tools.find((t) => t.name === "brain_brief")).toBeUndefined();
});
});
-describe("brain_operator_summary tool - round trip", () => {
+describe("brain_brief view=operator - round trip", () => {
test("clean vault returns trust_verdict=clean", async () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
@@ -125,7 +125,7 @@ describe("brain_operator_summary tool - round trip", () => {
jsonrpc: JSONRPC_VERSION,
id,
method: "tools/call",
- params: { name: "brain_operator_summary", arguments: args },
+ params: { name: "brain_brief", arguments: { view: "operator", ...args } },
})) as { error?: { code: number; message: string } };
// JSON-RPC INVALID_PARAMS = -32602. Assert the specific code so
// the test fails on the wrong failure mode (e.g. INTERNAL_ERROR
diff --git a/tests/mcp/procedural-learning-tools.test.ts b/tests/mcp/procedural-learning-tools.test.ts
index 11b33cf6..2f5925b3 100644
--- a/tests/mcp/procedural-learning-tools.test.ts
+++ b/tests/mcp/procedural-learning-tools.test.ts
@@ -72,7 +72,6 @@ describe("procedural learning tool registration", () => {
"brain_procedural_memory",
"brain_procedural_graph",
"brain_recurrence",
- "brain_attention_flows",
] as const) {
expect(buildToolTable("full").find((tool) => tool.name === name)).toBeDefined();
expect(buildToolTable("writer").find((tool) => tool.name === name)).toBeUndefined();
@@ -139,19 +138,22 @@ describe("procedural learning MCP tools", () => {
});
expect((graphHints.entries as unknown[]).length).toBeGreaterThan(0);
- const flowsList = await callTool(server, "brain_attention_flows", {
+ const flowsList = await callTool(server, "brain_analytics", {
+ view: "attention_flows",
operation: "list",
});
expect(flowsList.total).toBeGreaterThan(0);
const flowId = (flowsList.flows as Array<Record<string, unknown>>)[0]!["id"] as string;
- const flowsEval = await callTool(server, "brain_attention_flows", {
+ const flowsEval = await callTool(server, "brain_analytics", {
+ view: "attention_flows",
operation: "evaluate",
flow_id: flowId,
});
expect((flowsEval.sections as unknown[]).length).toBeGreaterThan(0);
- const flowsRender = await callTool(server, "brain_attention_flows", {
+ const flowsRender = await callTool(server, "brain_analytics", {
+ view: "attention_flows",
operation: "render",
flow_id: flowId,
});
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
new file mode 100644
index 00000000..ed71deab
--- /dev/null
+++ b/tests/mcp/removed-tools.test.ts
@@ -0,0 +1,142 @@
+/**
+ * 1.0.0 deprecation sweep (epic t_a77ade0a): the 18 hidden alias
+ * tools from the token-diet pass are removed from the callable
+ * surface and replaced by static tombstones. Calling a removed name
+ * answers INVALID_PARAMS with the exact replacement (tool + view);
+ * the advertised list is unchanged and the shadow surface is gone -
+ * after 1.0.0 the listed tools and the callable tools are the same
+ * set.
+ */
+
+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 { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable, REMOVED_TOOLS } from "../../src/mcp/tools.ts";
+
+let tmp: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-removed-"));
+ for (const key of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { 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: "removed-tools-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+/** Every removed alias with its consolidated replacement. */
+const EXPECTED_TOMBSTONES: ReadonlyArray<readonly [string, string, string]> = [
+ ["brain_digest", "brain_brief", "digest"],
+ ["brain_daily_brief", "brain_brief", "daily"],
+ ["brain_morning_brief", "brain_brief", "morning"],
+ ["brain_weekly_synthesis", "brain_brief", "weekly"],
+ ["brain_monthly_review", "brain_brief", "monthly"],
+ ["brain_operator_summary", "brain_brief", "operator"],
+ ["brain_attention_flows", "brain_analytics", "attention_flows"],
+ ["brain_concept_synthesis", "brain_analytics", "concept_synthesis"],
+ ["brain_timeline", "brain_analytics", "timeline"],
+ ["brain_belief_evolution", "brain_analytics", "belief_evolution"],
+ ["get_active_schema_pack", "schema_inspect", "active_pack"],
+ ["list_schema_packs", "schema_inspect", "packs"],
+ ["schema_stats", "schema_inspect", "stats"],
+ ["schema_lint", "schema_inspect", "lint"],
+ ["schema_graph", "schema_inspect", "graph"],
+ ["schema_explain_type", "schema_inspect", "explain_type"],
+ ["schema_review_orphans", "schema_inspect", "orphans"],
+ ["reload_schema_pack", "schema_inspect", "active_pack"],
+];
+
+test("REMOVED_TOOLS covers exactly the 18 swept aliases", () => {
+ expect(Object.keys(REMOVED_TOOLS).toSorted()).toEqual(
+ EXPECTED_TOMBSTONES.map(([name]) => name).toSorted(),
+ );
+});
+
+test("calling a removed tool answers INVALID_PARAMS naming the replacement", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const responses = await Promise.all(
+ EXPECTED_TOMBSTONES.map(async ([name, target, view], i) => {
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 100 + i,
+ method: "tools/call",
+ params: { name, arguments: {} },
+ })) as { error?: { code: number; message: string } };
+ return { name, target, view, r };
+ }),
+ );
+ for (const { name, target, view, r } of responses) {
+ expect(r.error).toBeDefined();
+ expect(r.error!.code).toBe(-32602);
+ expect(r.error!.message).toContain(`${name} was removed in 1.0.0`);
+ expect(r.error!.message).toContain(target);
+ expect(r.error!.message).toContain(`view="${view}"`);
+ }
+});
+
+test("a genuinely unknown tool still answers METHOD_NOT_FOUND", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 8,
+ method: "tools/call",
+ params: { name: "brain_never_existed", arguments: {} },
+ })) as { error?: { code: number } };
+ expect(r.error).toBeDefined();
+ expect(r.error!.code).toBe(-32601);
+});
+
+test("the shadow surface is gone: no hidden tools, removed names unlisted", async () => {
+ const all = buildToolTable("full");
+ expect(all.filter((t) => t.hidden === true)).toEqual([]);
+ const names = new Set(all.map((t) => t.name));
+ for (const [name] of EXPECTED_TOMBSTONES) {
+ expect(names.has(name)).toBe(false);
+ }
+ // The advertised list is what 0.45.0 advertised - the sweep removes
+ // only the hidden callable layer.
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const list = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/list",
+ params: {},
+ })) as { result: { tools: Array<{ name: string }> } };
+ expect(list.result.tools.length).toBe(77);
+});
diff --git a/tests/mcp/schema-tools.test.ts b/tests/mcp/schema-tools.test.ts
index bc66f92d..5d94c971 100644
--- a/tests/mcp/schema-tools.test.ts
+++ b/tests/mcp/schema-tools.test.ts
@@ -87,8 +87,8 @@ describe("schema MCP tools", () => {
(tool) => tool.name,
);
- // token-diet: the consolidated schema_inspect is advertised; the
- // per-view predecessors stay callable as hidden deprecated aliases.
+ // token-diet consolidated the per-view readers into schema_inspect;
+ // the 1.0.0 sweep removed the hidden aliases entirely.
expect(names).toContain("schema_inspect");
expect(names).toContain("schema_apply_mutations");
expect(names).not.toContain("schema_stats");
@@ -103,7 +103,7 @@ describe("schema MCP tools", () => {
});
expect((applied as any).result.structuredContent.applied).toBe(1);
- const pack = await call(server, "get_active_schema_pack");
+ const pack = await call(server, "schema_inspect", { view: "active_pack" });
expect((pack as any).result.structuredContent.pack.declarations.preference_types).toContain(
"decision",
);
@@ -119,7 +119,7 @@ describe("schema MCP tools", () => {
{ op: "add_link_type", token: "decision" },
],
});
- const graph = await call(server, "schema_graph");
+ const graph = await call(server, "schema_inspect", { view: "graph" });
const nodes = (graph as any).result.structuredContent.nodes as ReadonlyArray<{ id: string }>;
expect(nodes.map((node) => node.id)).toContain("decision");
diff --git a/tests/mcp/temporal-mcp-tools.test.ts b/tests/mcp/temporal-mcp-tools.test.ts
index 26898a14..547db711 100644
--- a/tests/mcp/temporal-mcp-tools.test.ts
+++ b/tests/mcp/temporal-mcp-tools.test.ts
@@ -101,11 +101,11 @@ beforeEach(() => {
]);
});
-describe("brain_timeline", () => {
+describe("brain_analytics view=timeline", () => {
test("happy-path: returns events array + window", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { result } = await callTool(server, "brain_timeline", {});
+ const { result } = await callTool(server, "brain_analytics", { view: "timeline" });
expect(Array.isArray(result?.events)).toBe(true);
expect(result?.window).toBeDefined();
});
@@ -113,7 +113,8 @@ describe("brain_timeline", () => {
test("INVALID_PARAMS: unknown kind", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { errorCode } = await callTool(server, "brain_timeline", {
+ const { errorCode } = await callTool(server, "brain_analytics", {
+ view: "timeline",
kind: "made-up-kind",
});
expect(errorCode).toBeDefined();
@@ -122,18 +123,20 @@ describe("brain_timeline", () => {
test("INVALID_PARAMS: limit must be positive integer", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { errorCode } = await callTool(server, "brain_timeline", {
+ const { errorCode } = await callTool(server, "brain_analytics", {
+ view: "timeline",
limit: -1,
});
expect(errorCode).toBeDefined();
});
});
-describe("brain_belief_evolution", () => {
+describe("brain_analytics view=belief_evolution", () => {
test("happy-path: pref_id returns target + arrays", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { result } = await callTool(server, "brain_belief_evolution", {
+ const { result } = await callTool(server, "brain_analytics", {
+ view: "belief_evolution",
pref_id: "pref-foo",
});
expect(result?.target).toEqual({ prefId: "pref-foo" });
@@ -145,14 +148,15 @@ describe("brain_belief_evolution", () => {
test("INVALID_PARAMS: missing both pref_id and topic", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { errorCode } = await callTool(server, "brain_belief_evolution", {});
+ const { errorCode } = await callTool(server, "brain_analytics", { view: "belief_evolution" });
expect(errorCode).toBeDefined();
});
test("INVALID_PARAMS: both pref_id and topic", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { errorCode } = await callTool(server, "brain_belief_evolution", {
+ const { errorCode } = await callTool(server, "brain_analytics", {
+ view: "belief_evolution",
pref_id: "pref-foo",
topic: "foo",
});
@@ -172,11 +176,12 @@ describe("brain_stale_scan", () => {
});
});
-describe("brain_daily_brief", () => {
+describe("brain_brief view=daily", () => {
test("happy-path: returns date + counters envelope", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { result } = await callTool(server, "brain_daily_brief", {
+ const { result } = await callTool(server, "brain_brief", {
+ view: "daily",
date: "2026-05-20",
});
expect(result?.date).toBe("2026-05-20");
@@ -186,16 +191,17 @@ describe("brain_daily_brief", () => {
test("happy-path: missing date defaults to today UTC", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { result } = await callTool(server, "brain_daily_brief", {});
+ const { result } = await callTool(server, "brain_brief", { view: "daily" });
expect(typeof result?.date).toBe("string");
});
});
-describe("brain_weekly_synthesis", () => {
+describe("brain_brief view=weekly", () => {
test("happy-path: returns window_start/window_end + arrays", async () => {
const server = new MCPServer({ vault: VAULT });
await initialize(server);
- const { result } = await callTool(server, "brain_weekly_synthesis", {
+ const { result } = await callTool(server, "brain_brief", {
+ view: "weekly",
week_end: "2026-05-25",
});
expect(result?.window_end).toBe("2026-05-25T00:00:00Z");