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: Workspace Insight Suite - project pointers, cross-vault recall, trigger queue, proactive synthesis (#69)
Sol Aitkeneb56c9f5a91f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 23a7998d..5123ad94 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.37.0",+ "version": "0.38.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 9d4bf4d6..cc10ad21 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.37.0",+ "version": "0.38.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cd22cbb2..5f284c7a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,93 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.38.0] - 2026-06-03++Workspace Insight Suite: eight changes in two themes. Theme A makes+the Brain reachable from anywhere in the workspace - a pointer file+links any project directory to its owning vault, external vaults+attach as read-only recall sources, one query can search every+registered vault with origin labels, and a shell-native surface+(materialized profile digest plus a grep-shaped search verb) works+without MCP. Theme B makes the Brain proactive with memory of what it+already said - a topic dossier cross-references notes for+contradictions and gaps, a Markdown trigger queue gives findings an+anti-nag lifecycle, idea discovery ranks next directions from open+loops, and recall-gate decisions become observable telemetry. All+behaviour-changing pieces are off by default or per-call explicit.++### Added++- **Project vault pointers.** `o2b brain project link <path>` writes a+ `.o2b-vault.json` pointer into any project directory - a repo, a+ monorepo package, a sibling worktree - and `resolveVault` now walks+ up from the working directory and honours it (after the `VAULT_DIR`+ env override, before the profile chain). `list`, `remove`, and+ `status` inspect and repair links via a `projects.json` registry+ beside the config; malformed pointers and dangling targets fail soft+ and are reported, never thrown.+- **Read-only recall sources.** `o2b brain source add <vault> --alias+ <name>` attaches an external vault as a read-only recall origin of+ the active Brain. The registry is keyed by owning vault (switching+ profiles never leaks sources), validation concentrates in one place+ (alias and path uniqueness, self-links, direct circular links), and+ deleted targets are flagged BROKEN rather than dropped.+- **Cross-vault union search.** `o2b search <query> --global` (and+ `brain_search { global: true }`) fans one query out over the active+ vault, registered profile vaults, and read-only sources, merging+ results by score. Every result carries its origin as an additive+ `origin` field plus an `origin:<label>` entry in `reasons[]`+ (`local`, `profile/<name>`, `source/<alias>`). Read-only invariant:+ non-active origins search with self-healing and the query cache+ disabled, so an external vault is never written to - a missing index+ degrades to a per-origin warning.+- **Configurable wikilink path format.** The `wiki_link_format` config+ key selects `preserve` (default, byte-identical), `full`+ (vault-relative key path), or `short` (shortest unambiguous suffix)+ for generated and normalized links. `o2b brain links normalize+ [path] [--mode M] [--write]` rewrites wikilinks across Brain notes -+ dry-run by default, decorations and code blocks preserved verbatim,+ ambiguous and unknown targets left as typed and reported.+- **Shell-native Brain surface.** `o2b brain profile` materializes a+ compact `Brain/profile.md` digest (facts, top preferences, recent+ activity; age-gated regeneration) plus a `.o2bfs` root marker so+ shell wrappers can detect a Brain root safely. `o2b brain sgrep+ <query> [path]` is a grep-shaped semantic search - `path:line:`+ output lines, path scoping, `--json`, exit 1 on no matches - with no+ MCP and no OSB-specific knowledge required.+- **Grounded trigger queue with anti-nag lifecycle.** `o2b brain+ trigger scan` turns existing semantic-health and retention findings+ into Markdown trigger records under `Brain/triggers/` (urgency,+ reason, suggested action, source artifacts, context snippets).+ Stable cooldown keys make repeated scans idempotent: an open twin+ blocks recreation, a dismissed/acted twin blocks for+ `trigger_cooldown_days` (default 7), an expired twin allows.+ Lifecycle is a strict machine (`pending β delivered β acknowledged β+ acted`, dismiss from any open state) over `list`, `ack`, `dismiss`,+ `act`, and `history` verbs plus one consolidated `brain_trigger` MCP+ tool. The morning brief surfaces capped pending triggers and marks+ them delivered, so the same prompt shows at most once per cooldown+ window and dismissed items never resurface.+- **Deep vault synthesis.** `o2b brain deep-synthesis <topic>` (and+ `brain_deep_synthesis`) assembles a deterministic topic dossier:+ matched notes, agreements (positive typed relations),+ contradictions (`contradicts` relations), stale claims (aged or+ superseded notes), and knowledge gaps (dangling wikilink targets).+ The dossier names exactly which dimensions it checked; prose+ synthesis stays with the calling agent. `--triggers` enqueues+ contradiction and gap findings into the trigger queue.+- **Idea discovery.** `o2b brain ideas` (and `brain_idea_discovery`)+ ranks next-direction candidates from the vault's open loops -+ unanswered open questions, orphan research notes with no inbound+ links, and aging unresolved inbox signals - with documented+ deterministic scoring. `--triggers` enqueues the ranked ideas.+- **Recall-gate telemetry.** With `recall_gate_telemetry: "true"`+ (default off), every `brain_recall_gate` decision lands as a+ `gate_telemetry` continuity record - decision, stable reason, host,+ and a SHA-256 prompt prefix; the raw prompt is never stored.+ `brain_recall_telemetry` and `o2b brain recall-telemetry` gain+ `gate_list` / `gate_summary` operations for skip/retrieve analysis.+## [0.37.0] - 2026-06-03Agent Surface Suite: eight changes in two themes. Theme A makes the@@ -4184,6 +4271,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.38.0]: https://github.com/itechmeat/open-second-brain/compare/v0.37.0...v0.38.0[0.37.0]: https://github.com/itechmeat/open-second-brain/compare/v0.36.0...v0.37.0[0.36.0]: https://github.com/itechmeat/open-second-brain/compare/v0.35.0...v0.36.0[0.35.0]: https://github.com/itechmeat/open-second-brain/compare/v0.34.0...v0.35.0diff --git a/README.md b/README.mdindex 219e4af0..b4045ac6 100644--- a/README.md+++ b/README.md@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`).+The v0.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).## CLIdiff --git a/docs/brainstorm/workspace-insight-suite/cli-output/claude.md b/docs/brainstorm/workspace-insight-suite/cli-output/claude.mdnew file mode 100644index 00000000..cb0e8ca7--- /dev/null+++ b/docs/brainstorm/workspace-insight-suite/cli-output/claude.md@@ -0,0 +1,36 @@+### Variant 1: Two cluster-aligned kernels+- **Approach**: Build exactly two shared kernels matching the two clusters. Cluster A gets a **read-side resolution + origin-tagging kernel**: a `SourceResolver` that extends the existing `profiles.ts` resolution chain to cover project pointer files (A2), registered read-only sources (A2), and union/global mode (A3), emitting a single `origin` label that rides the existing `reasons[]` mechanism and feeds `profile.md`/`sgrep` (A4). A1's link builder and B's pipeline are smaller standalone pieces: Cluster B gets a **deterministic candidateβtrigger kernel** that normalizes output from existing report generators (health, retention, stale, watchdog, backlinks, pre-compact) into a common `Candidate` record, which the `Brain/triggers/` lifecycle (B2) consumes and which B1/B3 produce; B4 plugs decisions into the existing `recall-telemetry.ts`.+- **Trade-offs**:+ - Pro: kernel boundaries follow the cluster seams, so the PR reads as two coherent stories rather than eight patches.+ - Pro: origin label reuses `reasons[]` and trigger records reuse Markdown+JSONL β no new cross-cutting abstractions.+ - Pro: writes-stay-local and read-only invariants concentrate in one resolver, easy to test once.+ - Con: A1 (link format) and B4 (telemetry) don't fit either kernel cleanly and remain semi-isolated.+ - Con: the candidate kernel must accommodate heterogeneous report shapes, risking a lowest-common-denominator record.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Minimal shared primitives, feature-local modules+- **Approach**: Introduce only the smallest shared types β an `origin` field on search results, a `LinkFormat` config + builder, and a `Candidate` record shape β then implement all eight tasks as independent modules consuming those primitives. No shared resolver or pipeline; each feature owns its own vault discovery, candidate assembly, and surface wiring.+- **Trade-offs**:+ - Pro: lowest coupling; any single feature can be reverted or deferred without disturbing the others.+ - Pro: each module is individually small and easy to TDD in isolation.+ - Pro: least risk of touching the sensitive `profiles.ts` resolution chain in a wide-reaching way.+ - Con: duplicates vault-resolution and origin-labelling logic across A2/A3/A4, and report-scanning logic across B1/B3 β directly against the "small number of shared kernels" constraint.+ - Con: eight loosely-related modules make the PR feel like a grab-bag, weakening reviewability and consistency.+ - Con: invariant enforcement (read-only sources, writes-local) is scattered, raising the chance one path leaks a write.+- **Complexity**: small-to-medium+- **Risk**: medium (incoherence + duplicated invariant checks)++### Variant 3: Unified federation registry + insight bus+- **Approach**: Collapse all read-source concerns (profiles, project pointers, read-only sources, global mode) behind one `SourceRegistry` federation abstraction that becomes the single resolver for every read path, and collapse all proactive output behind one "insight bus" where every report generator emits events into `Brain/triggers/` and the lifecycle is the sole consumer. A1, A4, B3, B1 all become thin producers/consumers on these two backbones.+- **Trade-offs**:+ - Pro: maximal reuse; conceptually the cleanest end state (one read federation, one insight stream).+ - Pro: future vaults/sources/reports plug in with near-zero new surface.+ - Con: rewrites the `profiles.ts` resolution chain and reroutes existing search/context-pack reads through a new layer β high blast radius against "additive only / backward compatible" and "full/writer scopes byte-identical" constraints.+ - Con: forcing health/retention/stale/synthesis/idea generators to emit into one bus is a large refactor of working deterministic code for features that are mostly default-off.+ - Con: hardest to land safely in one PR; a bug in the federation layer breaks every read.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1+**Rationale**: It satisfies the explicit "small number of shared kernels" directive by mapping two kernels to the two clusters, while keeping each kernel additive β the origin label rides the existing `reasons[]` field and the trigger queue consumes existing report output, so no public API or scope changes. Variant 2 duplicates the very vault-resolution and candidate logic the constraint warns against, and Variant 3's rewrite of the `profiles.ts` resolution chain and report generators carries too much blast radius for default-off features shipping in a single PR.diff --git a/docs/brainstorm/workspace-insight-suite/cli-output/prompt.md b/docs/brainstorm/workspace-insight-suite/cli-output/prompt.mdnew file mode 100644index 00000000..60c0adb1--- /dev/null+++ b/docs/brainstorm/workspace-insight-suite/cli-output/prompt.md@@ -0,0 +1,109 @@+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++One release (target v0.38.0) ships eight kanban tasks in two theme clusters as a single PR on one feature branch.++## Cluster A - Workspace Reach (the Brain reachable from anywhere in the workspace)++### A1 (t_5f31b5f1, p3) Configurable wiki link path format (preserve/full/short)+Add a config option with three modes: preserve (keep links as typed), full (rewrite to full key path like [[folder/target]]), short (rewrite to shortest unambiguous suffix). Applied when Open Second Brain generates or normalizes notes (ADR candidates, decision notes, generated Brain content). The repo parses wiki links via src/core/brain/link-graph/parse-wikilink.ts (WikilinkParse, parseWikilinkRich) but has no configurable output format or link-builder; generated notes concatenate strings manually.++### A2 (t_1375e69f, p2) Project worktree links and read-only Brain sources+A repo, monorepo package, sibling worktree, or satellite project should discover the right Brain vault automatically, and optionally search selected external Brains as read-only sources without importing or mutating them.+Suggested design from the task:+- `o2b brain project link <path> --vault <vault>` writes a pointer file into a project directory.+- `o2b brain project list/remove/status` to inspect and repair linked project pointers.+- `o2b brain source add <vault-or-project> --alias <name> --read-only` for read-only recall sources.+- Source origin metadata in brain_search, context packs, and why_retrieved, distinguishing local results from shared/read-only sources.+- Refuse self-links, duplicate sources, malformed pointer files, circular source links.+- Write tools stay scoped to the active local Brain.+Acceptance: link a nested project dir to an existing vault without copying files; commands launched from the linked dir resolve the owning vault; read-only sources can be added/listed/removed/marked broken; search output shows origin labels; writes cannot mutate read-only sources; status/doctor reports malformed pointers.++### A3 (t_72a22658, p2) Global search mode for cross-vault memory access+Search is currently scoped to the active vault. Add a global/union mode: one query searches all registered vaults (multi-vault profile registry exists: src/core/brain/portability/profiles.ts, .profiles.json with {active, profiles:{name:{vault}}}). Writes remain scoped to the active vault. Complements A2: read-only sources and cross-vault union share the origin-label mechanism in result output.++### A4 (t_323a9a83, p2) Shell-native Brain profile and semantic grep surface+A shell-native surface so simple agents, scripts, and humans use ordinary filesystem reflexes without MCP:+- Generate a materialized `profile.md` (compact current-Brain digest: static facts, dynamic/recent context, source timestamps) without walking every file.+- `o2b brain sgrep <query> [path]` for semantic Brain search with path scoping and JSON output.+- `.o2bfs` marker metadata so wrappers can detect the Brain root safely.+Acceptance: profile generation, path-scoped semantic grep, exact-grep fallback preserved, marker detection, stale profile invalidation. Out of scope: FUSE/NFS mounts, hosted sync.++## Cluster B - Proactive Insight (the Brain says what needs attention, with memory of what it already said)++### B1 (t_04e94382, p3) Deep vault synthesis: cross-reference notes by topic for contradictions and gaps+Topic-scoped synthesis that crawls all notes mentioning a concept and produces a structured analysis of agreements, contradictions, stale claims, and knowledge gaps. Complements brain_health (preference-level contradictions) and brain_concept_synthesis (depth-1 wikilink clusters). Reuse FTS5 search for topic matching; keep candidate assembly deterministic (LLM synthesis stays outside core, consistent with project style).++### B2 (t_cd1fee79, p2) Grounded proactive trigger queue with anti-nag lifecycle+`Brain/triggers/` as a Markdown-first trigger queue for grounded proactive prompts. Trigger generation deterministic, source-linked, conservative - generated from existing health/retention/stale/reconcile data.+- Store each trigger with trigger_id, trigger_type, status, urgency, reason, suggested_action, source_artifacts, context_snippets, cooldown_key, created_at, expires_at, lifecycle timestamps.+- Statuses: pending, delivered, acknowledged, acted, dismissed, expired.+- Deduplicate with a stable cooldown key so the same issue does not reappear every run.+- CLI/MCP surfaces: list pending, acknowledge, dismiss, act-on, history.+- Feed pending triggers into morning brief or summary only once per cooldown window.+Acceptance: generate candidates from existing report data without duplicates; persisted triggers include source links and context snippets; acknowledged/dismissed/acted/expired triggers stop resurfacing until cooldown allows; morning brief includes pending without repeating dismissed; CLI and MCP expose pending/history + acknowledge/dismiss/act; tests cover cooldown dedup, expiry, transitions, idempotency. Out of scope: push notifications, valence tracking, LLM-generated triggers.++### B3 (t_8722a62a, p2) Idea discovery: rank next-direction candidates from open loops+Scan the vault for orphan research (low backlink count via link graph), unresolved open questions (pre-compact extraction), and undeveloped ideas/signals to produce 3-5 ranked next-direction candidates. Could feed the trigger queue from B2 rather than being a separate report.++### B4 (t_65036e02, p2) Recall gate telemetry (follow-up to PR #54)+The pure recall gate (brain_recall_gate with stable skip/retrieve reasons) shipped in v0.27.0; the Hermes provider calls it every turn since v0.32.0. Remaining scope: (1) automatic context-injection telemetry - record gate decisions and surfaced/suppressed context for observability and tuning; (2) host-hook wiring for non-Hermes hosts where feasible. There is an existing telemetry kernel: src/core/brain/recall-telemetry.ts (emitRecallTelemetry -> Brain/continuity/ records with mode/status, listRecallTelemetry, summarizeRecallTelemetry).++# Project context++Open Second Brain - a local-first, Markdown/Obsidian-first second brain for AI agents. TypeScript on Bun; CLI (`o2b`) + MCP server; Python provider plugin for Hermes. Core principles: deterministic state transitions (no LLM inside core), fail-soft reads, behavior-changing features ship off by default, Markdown stays the record.++Recent commits:+707197a feat: Agent Surface Suite - skills over MCP, two-pass tool catalog, surface profiles, session lifecycle (#68)+eda202d feat: Embedding Provider Suite - local embedder, provider registry, cost gate, RRF fusion (#67)+dee5ab7 feat: Memory Integrity Suite - canonical entities, conflict-free log shards, capture boundaries, fact extraction (#66)+5066e71 feat: Token Diet - budgeted injection, reminder cadence, consolidated MCP surface (#65)+c494fd8 feat(search): Recall Trust Suite - relation polarity, learned weights, time-aware and verified recall (#64)++Related files:+- src/core/brain/link-graph/parse-wikilink.ts - WikilinkParse (target/anchor/block/alias), parseWikilinkRich, extractWikilinkRichBodies. Parser only; no link builder/normalizer.+- src/core/brain/portability/profiles.ts - VaultProfile registry (.profiles.json beside config.yaml), listProfiles/createProfile/switchProfile/resolveActiveProfileVault. Resolution chain: profiles -> config "vault" key -> env var.+- src/core/config.ts - resolve* helper convention for config keys (config key, env var override, default), e.g. resolveSessionHandoff, resolveSkillAutoAttach.+- src/core/search/search.ts (search entry), src/core/search/types.ts (SearchOptions: semantic, keywordOnly, sessionFocus, properties, visibility, since/until, mmrLambda, maxHops), query-plan.ts. Results carry reasons[] ("lane:lex/fts5", "lane:vec/semantic", "intent:..."), so an origin label fits the existing reasons mechanism.+- src/core/brain/context-pack.ts - packContext with tiers core/supporting/peripheral, char budgets, skipped reasons, receipts/telemetry ids.+- src/core/brain/digest.ts, morning-brief.ts - compact digest surfaces that could feed a generated profile.md.+- src/core/brain/recall-gate.ts, recall-telemetry.ts - gate decision logic + continuity-record telemetry kernel (Brain/continuity/, JSONL).+- src/core/brain/health.ts, retention.ts (RetentionReviewReport: summary keep/improve/park/prune + recommendations[]), stale scan, watchdog.ts (BrainWatchdogResult with remediation_plan), morning-brief.ts - deterministic report generators that a trigger queue can consume.+- src/core/brain/link-graph/backlinks.ts (buildLinkGraph inbound counts), pre-compact-extract.ts (open-question extraction), Brain/inbox/sig-*.md signals - inputs for idea discovery.+- src/core/brain/session-scope.ts - resolveSessionScope slug kernel (lowercase, non-alnum -> dash, cap 64).+- src/core/brain/intentions.ts / handoff.ts - frontmatter writing pattern with JSON.stringify quoting.+- src/cli/command-manifest.ts + src/cli/brain/verbs/*.ts - CLI verb registration; src/mcp/brain-tools.ts + src/mcp/tools.ts + registry-guard.ts + tests/mcp/mcp.test.ts - MCP tool registration with preview budgets and a contract test asserting the advertised tool list.++Conventions:+- Deterministic core; LLM work stays outside (agents/consultants), core produces candidate data.+- Every behavior-changing feature is gated by a config key, default off; resolve* helper + env var override.+- New CLI verbs registered in verbs/index.ts + brain.ts dispatch + command-manifest.ts; CLI handlers wrap errors in try/catch boundaries.+- New MCP tools added to BRAIN_TOOLS (or a dedicated module spread into the table), with preview budgets, registry-guard entries, and mcp.test.ts contract updates.+- Frozen return objects, code-point sorts (not localeCompare), plain toLowerCase, JSON-quoted frontmatter values.+- Tests: bun test, TDD per feature; lint oxlint (baseline 111 warnings), fmt oxfmt; tsc --noEmit.+- Markdown stays the record: durable artifacts are .md files under Brain/ with frontmatter, JSONL sidecars only as derived indexes.++Constraints:+- Do not change existing public APIs (existing CLI verbs, MCP tool shapes, search result fields stay backward compatible; additive only).+- No new external runtime dependencies.+- Writes always stay scoped to the active local vault; external vaults/sources are strictly read-only.+- The full/writer MCP scopes must stay byte-identical except for deliberately added tools.+- Eight features in one PR: prefer a small number of shared kernels over eight isolated implementations - that is what keeps the PR coherent.++# 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/workspace-insight-suite/design.md b/docs/brainstorm/workspace-insight-suite/design.mdnew file mode 100644index 00000000..dd3472b3--- /dev/null+++ b/docs/brainstorm/workspace-insight-suite/design.md@@ -0,0 +1,75 @@+# Workspace Insight Suite - reach the Brain from anywhere; the Brain says what needs attention++**Status:** approved+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation+**Epic:** t_618c7bd8 (children: t_5f31b5f1, t_1375e69f, t_72a22658, t_323a9a83, t_04e94382, t_cd1fee79, t_8722a62a, t_65036e02)++## Problem statement++Open Second Brain works only when an agent runs inside the vault or a directory with a configured pointer; cross-project use needs a manually pasted prompt snippet, and recall never crosses vault boundaries. At the same time the Brain is entirely reactive: its reports (health, retention, stale, brief) rediscover the same findings every run with no memory of what the operator already saw, dismissed, or acted on, and nothing proactively surfaces contradictions, orphaned research, or next directions.++## Scope++Two theme clusters, eight kanban tasks, one PR, target v0.38.0.++Cluster A - Workspace Reach:++- **A1 wikilink path format** (t_5f31b5f1): a pure link-format kernel with three modes - `preserve` (default, no change), `full` (rewrite to full vault-relative key path), `short` (shortest unambiguous suffix) - plus a `wiki_link_format` config key and an `o2b brain links normalize` verb that rewrites wikilinks in Brain-owned notes.+- **A2 project links + read-only sources** (t_1375e69f): `o2b brain project link|list|remove|status` writes/inspects a JSON pointer file in any project directory; `resolveVault` walks up from cwd and honours the pointer (after env, before profiles). `o2b brain source add|list|remove` registers external vaults as read-only recall sources with alias, duplicate/self/circular validation, and broken-target detection.+- **A3 cross-vault search** (t_72a22658): explicit per-call union mode (`o2b search query --global`, `brain_search { global: true }`) that fans the query out over the active vault, registered profile vaults, and read-only sources, merges by score, and labels every result with its origin. Writes stay scoped to the active vault.+- **A4 shell-native surface** (t_323a9a83): `o2b brain profile` materializes a compact `Brain/profile.md` digest (with stale-by-age regeneration), `o2b brain sgrep <query> [path]` is a grep-shaped semantic search wrapper (path scoping, `--json`), and a `.o2bfs` marker file lets shell wrappers detect a Brain root safely.++Cluster B - Proactive Insight:++- **B1 deep vault synthesis** (t_04e94382): `o2b brain deep-synthesis <topic>` + `brain_deep_synthesis` assemble a deterministic topic dossier - matched notes, typed-relation contradictions, stale claims (superseded or aged), and knowledge gaps (linked-but-missing targets, unanswered open questions) - as evidence for an external synthesizer. Contradiction and gap findings become trigger candidates.+- **B2 trigger queue** (t_cd1fee79): `Brain/triggers/<id>.md` records with frontmatter lifecycle (`pending`, `delivered`, `acknowledged`, `acted`, `dismissed`, `expired`), urgency, source artifacts, context snippets, and a stable cooldown key. `o2b brain trigger scan` generates candidates from existing health/retention/stale data; `list|ack|dismiss|act|history` manage the lifecycle; one consolidated `brain_trigger` MCP tool mirrors it. Morning brief shows pending triggers (marking them delivered) and never repeats dismissed ones inside their cooldown window.+- **B3 idea discovery** (t_8722a62a): `o2b brain ideas` + `brain_idea_discovery` rank next-direction candidates from orphan notes (low inbound link count), open questions, and aging unresolved inbox signals; `--triggers` enqueues them into the B2 queue.+- **B4 recall-gate telemetry** (t_65036e02): the `brain_recall_gate` handler emits a `gate_telemetry` continuity record (decision, reason, prompt hash - never the raw prompt) when `recall_gate_telemetry` is on (default off); `brain_recall_telemetry` and the CLI gain a gate-decision summary section.++## Out of scope++- FUSE/NFS mounts, hosted sync, or a grep-intercepting shell wrapper (A4 ships the sgrep verb and marker only; an interactive wrapper can layer on later).+- Indexing external vaults implicitly: union search reads an existing `<vault>/.open-second-brain/brain.sqlite` per source and fail-softs (with a warning naming the missing index) when absent. Operators index sources explicitly.+- LLM synthesis inside core: B1 produces the dossier; prose synthesis stays with the calling agent.+- Push notifications, valence tracking, or LLM-generated triggers (B2 task's explicit out-of-scope list).+- Claude Code / Codex host-hook gate wiring beyond what lives in this repo; the telemetry kernel is host-agnostic and hooks adopt it when their surfaces land.++## Chosen approach++Consultant Variant 1 - two cluster-aligned kernels (see `variants.md`).++**Kernel A - source resolution + origin tagging** (`src/core/brain/portability/`): one pointer/marker discovery util (walk-up file search shared by project pointers and the `.o2bfs` marker), one `recall-sources` registry module (validation lives in exactly one place), and one `listSearchOrigins` enumerator that returns `{alias, vault, kind: "active" | "profile" | "source"}` consumed by cross-vault search and `project status` (which also reports malformed pointers and broken sources; a doctor integration can adopt the same enumerator later). Origin labels ride the existing `reasons[]` mechanism (`origin:<alias>`) plus one additive optional `origin?: string` field on `BrainSearchResult`.++**Kernel B - candidate-to-trigger pipeline** (`src/core/brain/triggers/`): one `InsightCandidate` record (kind, urgency, reason, suggested action, source artifacts, context snippets, cooldown key) produced by report adapters (health, retention, stale) and by the B1/B3 generators; one Markdown-first trigger store with lifecycle transitions and cooldown dedup that is the single consumer. B4 reuses the existing continuity-record telemetry kernel rather than inventing a new sink.++A1 and B4 are deliberately smaller satellites: A1 is a pure formatting kernel the generators adopt, B4 is an emission point on an existing kernel. The consultant flagged this as the variant's main concession; we accept it - forcing them into a kernel they do not need would be the Variant 3 mistake in miniature.++## Design decisions++- **Pointer resolution order: env β pointer walk-up β profile β config.** `VAULT_DIR` stays the strongest (explicit per-process override); a pointer file is the most specific durable artifact, so it beats the profile pointer. Pointer files only exist when the operator created one - resolution is artifact-gated, no config key needed.+- **Pointer file is JSON (`.o2b-vault.json`), not Markdown.** Operational metadata follows the `profiles.json` precedent (stable key order, atomic writes, tolerant reads); Markdown stays the record for knowledge, not plumbing.+- **Read-only source registry lives beside the config (`recall-sources.json`), not inside the vault.** Sources are a device-level concern like profiles; keeping them out of the synced vault avoids leaking one machine's filesystem paths to every replica.+- **Union search is per-call explicit, not a config default.** `--global` / `global: true` changes recall results, so it must be a visible per-query decision; there is no key that silently widens every search.+- **Cross-vault scores merge as-is with origin labels.** Scores from identical ranking pipelines are comparable enough for a first version; the origin label and per-origin warnings make any skew diagnosable. Per-origin score normalization is a future tunable, not a v1 requirement.+- **Trigger records are Markdown files with JSON-quoted frontmatter** (intentions/handoff pattern), one file per trigger, filenames from the existing content-hash util over the cooldown key. History is a status change, not a file move - `history` lists terminal-status files; nothing leaves `Brain/triggers/`.+- **Cooldown dedup checks ALL existing triggers (any status) by cooldown key**: an active (pending/delivered/acknowledged) twin always blocks recreation; a dismissed twin blocks until `dismissed_at + cooldown_days`; acted/expired twins block until `expires_at`. This is what makes repeated `scan` runs idempotent.+- **Trigger generation is pull, not push**: `scan` is an explicit command (and the brief integration only surfaces already-persisted pending triggers). No report generator gains a write path - adapters read their existing frozen report shapes.+- **Gate telemetry stores a prompt hash, never the prompt.** Continuity records sync with the vault; raw prompts may contain anything. SHA-256 prefix is enough for duplicate analysis.+- **All eight features are additive**: no existing CLI verb, MCP tool shape, or search result field changes; new MCP tools (`brain_trigger`, `brain_deep_synthesis`, `brain_idea_discovery`) extend the contract test list; full/writer scopes stay byte-identical apart from the deliberately added tools.++## File changes++New (core): `src/core/brain/portability/pointer.ts` (walk-up discovery + pointer read/write), `recall-sources.ts` (registry + validation), `origins.ts` (enumerator); `src/core/brain/link-graph/format-wikilink.ts`; `src/core/brain/profile-doc.ts`; `src/core/brain/triggers/{types,store,scan,adapters}.ts`; `src/core/brain/deep-synthesis.ts`; `src/core/brain/idea-discovery.ts`; `src/core/brain/gate-telemetry.ts`; `src/core/search/cross-vault.ts`.+New (CLI): `src/cli/brain/verbs/{project,source,links,profile,sgrep,trigger,deep-synthesis,ideas}.ts` + registration in `verbs/index.ts`, `brain.ts`, `command-manifest.ts`; `--global` flag in `src/cli/search.ts`.+New (MCP): three tools in `src/mcp/brain-tools.ts` (or a dedicated module), additive `global` input on `brain_search` in `src/mcp/search-tools.ts`, gate-telemetry emission in the `brain_recall_gate` handler, gate section in `brain_recall_telemetry`.+Modified: `src/core/config.ts` (resolve helpers: `wiki_link_format`, `recall_gate_telemetry`, trigger cooldown days; pointer hook in `resolveVault`), `src/core/search/types.ts` (+`origin?`), `src/core/brain/morning-brief.ts` (pending-trigger section), `src/mcp/registry-guard.ts`, `tests/mcp/mcp.test.ts` (contract), docs.+Tests: one suite per new core module + CLI/MCP integration suites + one e2e suite for the release theme.++## Risks and open questions++- **resolveVault now consults the filesystem walk-up on every call.** Mitigation: the walk stops at the filesystem root, reads at most one small JSON per level, caches per-process, and short-circuits when `VAULT_DIR` is set; behaviour without pointer files is byte-identical.+- **External vault index may be stale or schema-mismatched.** Union search opens each source read-only inside a try/catch; a failed origin contributes a warning, never an error.+- **Deterministic contradiction/gap detection is conservative by design** - typed `contradicts` relations, supersession, link-graph dangling targets, unanswered open questions. The dossier states what it checked so the absence of findings is interpretable.+- **Trigger volume**: adapters cap candidates per kind per scan (documented constant) so a neglected vault cannot flood `Brain/triggers/` in one run.+- **Morning-brief growth**: the trigger section is capped (top N pending by urgency) and only renders when pending triggers exist.diff --git a/docs/brainstorm/workspace-insight-suite/plan.md b/docs/brainstorm/workspace-insight-suite/plan.mdnew file mode 100644index 00000000..19588dde--- /dev/null+++ b/docs/brainstorm/workspace-insight-suite/plan.md@@ -0,0 +1,55 @@+# Workspace Insight Suite - implementation plan++One feature branch (`feat/workspace-insight-suite`), one conventional commit per task, formatter + linter green before every commit. TDD: failing test first, implement, refactor.++## Tasks++### Task 1: Kernel A - pointer discovery + project links (t_1375e69f, part 1)+- **Files**: `src/core/brain/portability/pointer.ts` (new), `src/core/config.ts` (resolveVault hook), `src/cli/brain/verbs/project.ts` (new), `src/cli/brain/verbs/index.ts`, `src/cli/brain/brain.ts`, `src/cli/command-manifest.ts`, `tests/core/brain/pointer.test.ts`, `tests/cli/project-verb.test.ts`+- **Acceptance**: `o2b brain project link <path> --vault <v>` writes `.o2b-vault.json`; `resolveVault` from a linked (or nested) cwd returns the pointed vault; env `VAULT_DIR` still wins; malformed pointer is skipped fail-soft and reported by `project status`; self-link (path inside the vault) refused; `list/remove/status` work.+- **Depends on**: none++### Task 2: Kernel A - read-only recall sources registry (t_1375e69f, part 2)+- **Files**: `src/core/brain/portability/recall-sources.ts` (new), `src/cli/brain/verbs/source.ts` (new), CLI registration files, `tests/core/brain/recall-sources.test.ts`, `tests/cli/source-verb.test.ts`+- **Acceptance**: `source add <vault> --alias <name>` validates (vault exists, alias unique, not the active vault, no duplicate path, refuses direct circular reference); `list` marks broken targets; `remove` works; registry file has stable key order and tolerant reads.+- **Depends on**: none++### Task 3: Kernel A - origins enumerator + cross-vault search (t_72a22658)+- **Files**: `src/core/brain/portability/origins.ts` (new), `src/core/search/cross-vault.ts` (new), `src/core/search/types.ts` (+`origin?`), `src/cli/search.ts` (`--global`), `src/mcp/search-tools.ts` (`global` input), `tests/core/search/cross-vault.test.ts`, `tests/mcp/search-global.test.ts`+- **Acceptance**: `listSearchOrigins` returns active + profiles + sources deduped by real path; union search merges results by score with `origin:<alias>` reason and `origin` field; an origin without an index yields a warning, not an error; default (no flag) path byte-identical to before.+- **Depends on**: Task 2++### Task 4: wikilink format kernel + normalize verb (t_5f31b5f1)+- **Files**: `src/core/brain/link-graph/format-wikilink.ts` (new), `src/core/config.ts` (`wiki_link_format` helper), `src/cli/brain/verbs/links.ts` (new), CLI registration, `tests/core/brain/format-wikilink.test.ts`, `tests/cli/links-verb.test.ts`+- **Acceptance**: `formatWikilink`/`normalizeWikilinks` pure functions handle target/anchor/block/alias round-trips; `full` rewrites to vault-relative key path; `short` computes shortest unambiguous suffix from known paths and leaves ambiguous links untouched; `preserve` is byte-identical; code blocks and media links untouched; verb dry-runs by default, `--write` applies.+- **Depends on**: none++### Task 5: shell-native surface - profile.md + sgrep + marker (t_323a9a83)+- **Files**: `src/core/brain/profile-doc.ts` (new), `src/cli/brain/verbs/profile.ts` (new), `src/cli/brain/verbs/sgrep.ts` (new), CLI registration, `tests/core/brain/profile-doc.test.ts`, `tests/cli/sgrep-verb.test.ts`+- **Acceptance**: `buildProfileDoc` assembles digest (facts, top preferences, recent activity, generated_at) without walking every vault file; `o2b brain profile` writes `Brain/profile.md` + `.o2bfs` marker and regenerates only when stale (age or `--force`); `sgrep` prints `path:line: snippet` lines, scopes by path argument, supports `--json`.+- **Depends on**: none++### Task 6: Kernel B - trigger queue with lifecycle (t_cd1fee79)+- **Files**: `src/core/brain/triggers/types.ts`, `store.ts`, `scan.ts`, `adapters.ts` (new), `src/core/brain/morning-brief.ts` (pending section), `src/core/config.ts` (cooldown helper), `src/cli/brain/verbs/trigger.ts` (new), CLI registration, `src/mcp/brain-tools.ts` (`brain_trigger`), `src/mcp/registry-guard.ts`, `tests/core/brain/trigger-store.test.ts`, `tests/core/brain/trigger-scan.test.ts`, `tests/mcp/brain-trigger-tool.test.ts`+- **Acceptance**: candidates from health/retention/stale adapters persist as `Brain/triggers/<id>.md` with full frontmatter; repeated scans are idempotent (cooldown-key dedup across all statuses); transitions pendingβdeliveredβacknowledged/acted/dismissed enforced, expiry honoured; dismissed stays silent during cooldown; morning brief lists capped pending triggers and marks them delivered; CLI list/ack/dismiss/act/history and MCP operations mirror each other.+- **Depends on**: none++### Task 7: deep vault synthesis (t_04e94382)+- **Files**: `src/core/brain/deep-synthesis.ts` (new), `src/cli/brain/verbs/synthesis.ts` (new), CLI registration, `src/mcp/brain-tools.ts` (`brain_deep_synthesis`), `tests/core/brain/deep-synthesis.test.ts`, `tests/mcp/deep-synthesis-tool.test.ts`+- **Acceptance**: topic dossier lists matched notes, contradictions (typed relations), stale claims (superseded or aged), gaps (dangling link targets, unanswered open questions); dossier states checked dimensions; contradiction/gap findings convert to `InsightCandidate`s and `--triggers` enqueues them via the Task 6 store.+- **Depends on**: Task 6++### Task 8: idea discovery (t_8722a62a)+- **Files**: `src/core/brain/idea-discovery.ts` (new), `src/cli/brain/verbs/ideas.ts` (new), CLI registration, `src/mcp/brain-tools.ts` (`brain_idea_discovery`), `tests/core/brain/idea-discovery.test.ts`, `tests/mcp/idea-discovery-tool.test.ts`+- **Acceptance**: ranked candidates from orphan notes (low inbound links), open questions, aging inbox signals; deterministic scoring documented in the module; top 3-5 returned; `--triggers` enqueues into the queue.+- **Depends on**: Task 6++### Task 9: recall-gate telemetry (t_65036e02)+- **Files**: `src/core/brain/gate-telemetry.ts` (new), `src/core/config.ts` (`recall_gate_telemetry` helper), `src/mcp/search-tools.ts` (gate handler emission), `src/mcp/brain-tools.ts` or existing telemetry tool (gate summary section), `tests/core/brain/gate-telemetry.test.ts`, `tests/mcp/recall-gate-telemetry.test.ts`+- **Acceptance**: gate handler emits `gate_telemetry` continuity record (decision, reason, prompt hash, host) only when the key is on; off by default leaves behaviour byte-identical; summary aggregates by decision/reason; raw prompt never stored.+- **Depends on**: none++### Task 10: e2e integration + docs+- **Files**: `tests/e2e/workspace-insight.integration.test.ts` (new), `tests/mcp/mcp.test.ts` (contract: +3 tools), `README.md`, `CHANGELOG.md`, `docs/cli-reference.md`, `docs/mcp.md`, `docs/how-it-works.md`+- **Acceptance**: one e2e flow exercises project link β cross-vault search with origins β trigger scan β ack β brief inclusion; MCP contract test passes with the new advertised list; docs describe all eight capabilities.+- **Depends on**: Tasks 1-9diff --git a/docs/brainstorm/workspace-insight-suite/variants.md b/docs/brainstorm/workspace-insight-suite/variants.mdnew file mode 100644index 00000000..1fa57231--- /dev/null+++ b/docs/brainstorm/workspace-insight-suite/variants.md@@ -0,0 +1,53 @@+# Workspace Insight Suite - brainstorm audit trail++Consultant: Claude Code (`claude -p`), prompt in `cli-output/prompt.md`, raw output in `cli-output/claude.md`. Codex fallback not needed (primary returned 3 parseable variants).++## Variant 1: Two cluster-aligned kernels++- **Approach**: Build exactly two shared kernels matching the two clusters. Cluster A gets a **read-side resolution + origin-tagging kernel**: a `SourceResolver` that extends the existing `profiles.ts` resolution chain to cover project pointer files (A2), registered read-only sources (A2), and union/global mode (A3), emitting a single `origin` label that rides the existing `reasons[]` mechanism and feeds `profile.md`/`sgrep` (A4). A1's link builder and B's pipeline are smaller standalone pieces: Cluster B gets a **deterministic candidateβtrigger kernel** that normalizes output from existing report generators (health, retention, stale, watchdog, backlinks, pre-compact) into a common `Candidate` record, which the `Brain/triggers/` lifecycle (B2) consumes and which B1/B3 produce; B4 plugs decisions into the existing `recall-telemetry.ts`.+- **Trade-offs**:+ - Pro: kernel boundaries follow the cluster seams, so the PR reads as two coherent stories rather than eight patches.+ - Pro: origin label reuses `reasons[]` and trigger records reuse Markdown+JSONL - no new cross-cutting abstractions.+ - Pro: writes-stay-local and read-only invariants concentrate in one resolver, easy to test once.+ - Con: A1 (link format) and B4 (telemetry) don't fit either kernel cleanly and remain semi-isolated.+ - Con: the candidate kernel must accommodate heterogeneous report shapes, risking a lowest-common-denominator record.+- **Complexity**: medium+- **Risk**: low++## Variant 2: Minimal shared primitives, feature-local modules++- **Approach**: Introduce only the smallest shared types - an `origin` field on search results, a `LinkFormat` config + builder, and a `Candidate` record shape - then implement all eight tasks as independent modules consuming those primitives. No shared resolver or pipeline; each feature owns its own vault discovery, candidate assembly, and surface wiring.+- **Trade-offs**:+ - Pro: lowest coupling; any single feature can be reverted or deferred without disturbing the others.+ - Pro: each module is individually small and easy to TDD in isolation.+ - Pro: least risk of touching the sensitive `profiles.ts` resolution chain in a wide-reaching way.+ - Con: duplicates vault-resolution and origin-labelling logic across A2/A3/A4, and report-scanning logic across B1/B3 - directly against the "small number of shared kernels" constraint.+ - Con: eight loosely-related modules make the PR feel like a grab-bag, weakening reviewability and consistency.+ - Con: invariant enforcement (read-only sources, writes-local) is scattered, raising the chance one path leaks a write.+- **Complexity**: small-to-medium+- **Risk**: medium (incoherence + duplicated invariant checks)++## Variant 3: Unified federation registry + insight bus++- **Approach**: Collapse all read-source concerns (profiles, project pointers, read-only sources, global mode) behind one `SourceRegistry` federation abstraction that becomes the single resolver for every read path, and collapse all proactive output behind one "insight bus" where every report generator emits events into `Brain/triggers/` and the lifecycle is the sole consumer. A1, A4, B3, B1 all become thin producers/consumers on these two backbones.+- **Trade-offs**:+ - Pro: maximal reuse; conceptually the cleanest end state (one read federation, one insight stream).+ - Pro: future vaults/sources/reports plug in with near-zero new surface.+ - Con: rewrites the `profiles.ts` resolution chain and reroutes existing search/context-pack reads through a new layer - high blast radius against "additive only / backward compatible" and "full/writer scopes byte-identical" constraints.+ - Con: forcing health/retention/stale/synthesis/idea generators to emit into one bus is a large refactor of working deterministic code for features that are mostly default-off.+ - Con: hardest to land safely in one PR; a bug in the federation layer breaks every read.+- **Complexity**: large+- **Risk**: high++## Consultant recommendation++### Recommended: Variant 1++**Rationale**: It satisfies the explicit "small number of shared kernels" directive by mapping two kernels to the two clusters, while keeping each kernel additive - the origin label rides the existing `reasons[]` field and the trigger queue consumes existing report output, so no public API or scope changes. Variant 2 duplicates the very vault-resolution and candidate logic the constraint warns against, and Variant 3's rewrite of the `profiles.ts` resolution chain and report generators carries too much blast radius for default-off features shipping in a single PR.++## Orchestrator decision++Variant 1 accepted as recommended, with two refinements documented in `design.md`:++1. The Kernel A "SourceResolver" is decomposed into three small modules (pointer discovery, recall-sources registry, origins enumerator) rather than one class - same kernel boundary, but each piece stays independently testable and `resolveVault` gains only a walk-up hook instead of a new abstraction layer.+2. The accepted con "A1 and B4 remain semi-isolated" is treated as a feature: A1 stays a pure formatting kernel and B4 an emission point on the existing continuity-record kernel; neither is forced into a kernel it does not need.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex a37b364a..3b03eca4 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -119,6 +119,23 @@ o2b brain intention set|show|list|move [--scope S] [--text T] [--json]Receipts, telemetry, transforms, and session recall import are opt-in. Receipt and telemetry records store redaction-safe payloads, source references, hashes, counters, and bounded snippets rather than raw private prompt context; session recall stores redacted turn text only when explicitly imported for later expansion.+### Workspace reach and proactive insight (since v0.38.0)++```text+o2b brain project link <path> [--vault V] | list | remove <path> | status [path] [--json] - .o2b-vault.json pointer files; resolveVault honours the nearest pointer (env override still wins)+o2b brain source add <vault> --alias <name> | list | remove <alias> [--json] - read-only recall sources of the active vault; BROKEN flag for missing targets+o2b brain links normalize [path-prefix] [--mode preserve|full|short] [--write] [--json] - wikilink path format rewrite; dry-run by default; config key wiki_link_format+o2b brain profile [--stale-seconds N] [--force] [--json] - materialize Brain/profile.md digest + .o2bfs root marker (age-gated)+o2b brain sgrep <query> [path-prefix] [--limit N] [--keyword-only] [--json] - grep-shaped semantic search; path:line: lines; exit 1 on no matches+o2b brain trigger scan | list [--status S] | ack <id> | dismiss <id> | act <id> | history [--json] - grounded trigger queue; cooldown via trigger_cooldown_days (default 7)+o2b brain deep-synthesis <topic> [--limit N] [--triggers] [--json] - deterministic topic dossier: agreements, contradictions, stale claims, knowledge gaps+o2b brain ideas [--cap N] [--triggers] [--json] - ranked next-direction candidates from open questions, orphan notes, aging signals+o2b brain recall-telemetry gate-list | gate-summary [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--json] - recall-gate decision telemetry (recall_gate_telemetry, default off)+o2b search <query> --global Cross-vault union over profiles + read-only sources; origin-labelled results; external vaults are never written to+```++Trigger generation, brief delivery, and gate telemetry are pull-based or config-gated; pointer resolution activates only when a pointer file exists.+## Vault scopeSingle exclusion policy for every vault walker.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 4ac6ab7d..7ad28fe5 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -833,6 +833,39 @@ Full design and migration notes:and the matching implementation plan[`docs/plans/2026-05-16-brain-search-impl.md`](plans/2026-05-16-brain-search-impl.md).+## Workspace reach and proactive insight (since v0.38.0)++Two suites extend where the Brain can be reached and what it+volunteers.++Workspace reach: a `.o2b-vault.json` pointer file written by+`o2b brain project link` binds any project directory (repo, monorepo+package, worktree) to its owning vault; `resolveVault` walks up from+the working directory and honours the nearest pointer after the+`VAULT_DIR` env override and before the profile chain, so commands run+from a linked tree resolve the right Brain with zero per-command+flags. External vaults attach as read-only recall sources+(`o2b brain source add`), and `o2b search <query> --global` unions the+active vault, profile vaults, and sources with per-result origin+labels - reads only, never a write or an index build inside an+external vault. For shell-first use, `o2b brain profile` materializes+a compact `Brain/profile.md` digest plus a `.o2bfs` root marker, and+`o2b brain sgrep` answers with grep-shaped `path:line:` lines.++Proactive insight: `o2b brain trigger scan` converts semantic-health+and retention findings into Markdown trigger records under+`Brain/triggers/` with a strict lifecycle (pending, delivered,+acknowledged, acted, dismissed, expired). Stable cooldown keys make+scans idempotent, and the morning brief delivers pending triggers at+most once per cooldown window - the Brain remembers what the operator+already saw, dismissed, or acted on instead of rediscovering it every+run. `o2b brain deep-synthesis <topic>` builds a deterministic topic+dossier (agreements, contradictions, stale claims, knowledge gaps)+and `o2b brain ideas` ranks next directions from open loops; both can+enqueue their findings as triggers. Opt-in recall-gate telemetry+records every automatic-recall decision with a hashed prompt for+tuning, never the raw text.+## Safety propertiesThese are invariants of the system, not configuration to enable.diff --git a/docs/mcp.md b/docs/mcp.mdindex 08113b09..57b74ed8 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -11,14 +11,14 @@ in Open Second Brain depends on the MCP server being running.- Transport: stdio (JSON-RPC 2.0, newline-delimited).- Protocol version: `2025-06-18`.-- Capabilities advertised: `tools` only. No `resources`, `prompts`, or- `sampling`.+- Capabilities advertised: `tools` and `resources` (see "Resources"+ below). No `prompts` or `sampling`.- Standard MCP lifecycle: `initialize`, `notifications/initialized`,`tools/list`, `tools/call`, optional `ping`.## Tool Highlights-The full server currently advertises 56 tools; 18 further names stay callable+The full server currently advertises 65 tools; 18 further names stay callablethrough `tools/call` as hidden deprecated aliases (see "Consolidated views anddeprecated aliases" below). The table highlights the operator-facing core,schema, agent-source, health, recovery, and Pay Memory tools; the full surface@@ -274,6 +274,37 @@ scorer and returns a char-budgeted block of top matches; it returnsconfig key is `"true"`, so default per-turn injection is unchanged. Thenative Hermes provider calls it from `prefetch()` fail-soft.+## Workspace Insight Suite tools (since v0.38.0)++`brain_search` accepts `global: true` for cross-vault union search:+one query fans out over the active vault, registered profile vaults,+and read-only recall sources (managed by `o2b brain source`), merging+results by score. Each result carries an additive `origin` field plus+an `origin:<label>` reason (`local`, `profile/<name>`,+`source/<alias>`). Non-active origins search with self-healing and the+query cache disabled, so an external vault is never written to; a+missing index degrades to a per-origin warning.++`brain_trigger` is the consolidated trigger-queue tool: `scan`+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+triggers and marks them delivered (once per `trigger_cooldown_days`).++`brain_deep_synthesis` assembles a deterministic topic dossier+(matched notes, agreements, contradictions, stale claims, knowledge+gaps; `triggers: true` enqueues findings). `brain_idea_discovery`+ranks next-direction candidates from open questions, orphan notes, and+aging inbox signals.++`brain_recall_gate` emits a `gate_telemetry` continuity record per+decision when the `recall_gate_telemetry` config key is `"true"`+(default off) - decision, stable reason, host, SHA-256 prompt prefix;+never the raw prompt. `brain_recall_telemetry` gains `gate_list` /+`gate_summary` operations.+## Hermes integrationHermes discovers MCP servers from `~/.hermes/config.yaml` under thediff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 2511c74a..09db5d21 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.37.0",+ "version": "0.38.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex bcfcefb4..f4e203e3 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.37.0",+ "version": "0.38.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 5078d54c..8a85fc0e 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.37.0"+version: "0.38.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 5e9fafb9..a3b892ff 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.37.0",+ "version": "0.38.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 5078d54c..8a85fc0e 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.37.0"+version: "0.38.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex ee6d295d..4d3abcf9 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.37.0"+version = "0.38.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 9c1ba0e1..ad202f3b 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -52,6 +52,14 @@ import {cmdBrainImportSession,cmdBrainHandoff,cmdBrainIntention,+ cmdBrainProject,+ cmdBrainSource,+ cmdBrainLinks,+ cmdBrainProfile,+ cmdBrainSgrep,+ cmdBrainTrigger,+ cmdBrainDeepSynthesis,+ cmdBrainIdeas,cmdBrainSessionHook,cmdBrainImportClaudeMemory,cmdBrainPageDedup,@@ -178,6 +186,22 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainHandoff(rest);case "intention":return await cmdBrainIntention(rest);+ case "project":+ return await cmdBrainProject(rest);+ case "source":+ return await cmdBrainSource(rest);+ case "links":+ return await cmdBrainLinks(rest);+ case "profile":+ return await cmdBrainProfile(rest);+ case "sgrep":+ return await cmdBrainSgrep(rest);+ case "trigger":+ return await cmdBrainTrigger(rest);+ case "deep-synthesis":+ return await cmdBrainDeepSynthesis(rest);+ case "ideas":+ return await cmdBrainIdeas(rest);case "entity":return await cmdBrainEntity(rest);case "session-hook":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 32233a94..9c59b506 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -80,6 +80,14 @@ Brain verbs (observing memory):stale Stale preferences/signals/log files (configurable thresholds)daily Daily brief: events by kind, status transitions, vault deltaweekly 7-day synthesis: transitions, retired, contradictions, vault delta+ project Link project directories to their owning vault (link/list/remove/status)+ source Read-only recall sources of the active vault (add/list/remove)+ links Normalize wikilink path format (preserve/full/short); dry-run by default+ profile Materialize Brain/profile.md digest + .o2bfs root marker (age-gated)+ sgrep Grep-shaped semantic search: o2b brain sgrep <query> [path]+ trigger Proactive trigger queue with anti-nag lifecycle (scan/list/ack/dismiss/act/history)+ deep-synthesis Topic dossier: notes, agreements, contradictions, stale claims, gaps+ ideas Ranked next-direction candidates from open loops (--triggers to enqueue)Common flags:--vault <path> Override the configured vault@@ -491,4 +499,42 @@ export const VERB_HELP: Record<string, string> = {"retired-in-window list, contradictions (signal-suppressed plus\n" +"apply-evidence violated), vault delta, source pointers. Defaults to\n" +"today UTC for week-end. Read-only.\n",+ project:+ "usage: o2b brain project <link|list|remove|status> [path] [--vault <path>] [--json]\n" ++ "Link a project directory to its owning vault via a .o2b-vault.json pointer.\n" ++ "resolveVault honours the nearest pointer above the working directory\n" ++ "(VAULT_DIR still wins). status reports resolution mode and registry health.\n",+ source:+ "usage: o2b brain source <add|list|remove> [path|alias] [--alias <name>] [--vault <path>] [--json]\n" ++ "Read-only recall sources of the active vault. add validates self-links,\n" ++ "duplicates, and direct circular references; list flags missing targets\n" ++ "as BROKEN. Distinct from `o2b brain sources` (signals dashboard).\n",+ links:+ "usage: o2b brain links normalize [path-prefix] [--mode preserve|full|short] [--write] [--json]\n" ++ "Rewrite wikilink targets to the configured path format (wiki_link_format).\n" ++ "Dry-run by default; decorations, code fences, and media embeds stay\n" ++ "verbatim; ambiguous targets are reported and left as typed.\n",+ profile:+ "usage: o2b brain profile [--stale-seconds <n>] [--force] [--vault <path>] [--json]\n" ++ "Materialize the compact Brain/profile.md digest plus the .o2bfs root\n" ++ "marker. Age-gated: a fresh profile is left alone unless --force.\n",+ sgrep:+ "usage: o2b brain sgrep <query> [path-prefix] [--limit <n>] [--keyword-only] [--vault <path>] [--json]\n" ++ "Grep-shaped semantic Brain search: path:line: output lines, path\n" ++ "scoping, exit 1 on no matches (also in --json mode).\n",+ trigger:+ "usage: o2b brain trigger <scan|list|ack|dismiss|act|history> [id] [--status <s>] [--vault <path>] [--json]\n" ++ "Grounded proactive trigger queue under Brain/triggers/. scan generates\n" ++ "deduped triggers from health/retention data (cooldown via\n" ++ "trigger_cooldown_days, default 7); ack/dismiss/act transition one\n" ++ "trigger; history lists terminal ones.\n",+ "deep-synthesis":+ "usage: o2b brain deep-synthesis <topic> [--limit <n>] [--triggers] [--vault <path>] [--json]\n" ++ "Deterministic topic dossier: matched notes, agreements, contradictions,\n" ++ "stale claims, knowledge gaps. --triggers enqueues contradiction/gap\n" ++ "findings into the trigger queue.\n",+ ideas:+ "usage: o2b brain ideas [--cap <n>] [--triggers] [--vault <path>] [--json]\n" ++ "Ranked next-direction candidates from open questions, orphan notes,\n" ++ "and aging inbox signals. --triggers enqueues the ranked ideas.\n",};diff --git a/src/cli/brain/verbs/deep-synthesis.ts b/src/cli/brain/verbs/deep-synthesis.tsnew file mode 100644index 00000000..db981cf6--- /dev/null+++ b/src/cli/brain/verbs/deep-synthesis.ts@@ -0,0 +1,85 @@+/**+ * `o2b brain deep-synthesis <topic>` (Workspace Insight Suite,+ * t_04e94382): deterministic topic dossier - matched notes,+ * agreements, contradictions, stale claims, knowledge gaps. With+ * `--triggers` the contradiction/gap findings enqueue into the+ * trigger queue.+ */++import { defaultConfigPath, resolveTriggerCooldownDays } from "../../../core/config.ts";+import { deepSynthesis, synthesisCandidates } from "../../../core/brain/deep-synthesis.ts";+import { createTriggers } from "../../../core/brain/triggers/store.ts";+import { resolveSearchConfig, SearchError } from "../../../core/search/index.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainDeepSynthesis(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ limit: { type: "string" },+ triggers: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;++ const topic = positional[0];+ if (!topic || topic.trim() === "") {+ return fail("usage: o2b brain deep-synthesis <topic> [--limit N] [--triggers] [--json]");+ }+ const limitRaw = flags["limit"];+ const limit = typeof limitRaw === "string" && limitRaw.trim() !== "" ? Number(limitRaw) : 30;+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {+ return fail("--limit must be an integer in 1..100");+ }++ try {+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const searchConfig = resolveSearchConfig({ vault, configPath: config });+ const now = new Date();+ const report = await deepSynthesis(searchConfig, topic, { now, limit });++ let enqueued = 0;+ if (flags["triggers"] === true) {+ const result = createTriggers(vault, synthesisCandidates(report), {+ now,+ cooldownDays: resolveTriggerCooldownDays(config),+ });+ enqueued = result.created.length;+ }++ if (json) {+ okJson({+ ok: true,+ topic: report.topic,+ generated_at: report.generatedAt,+ checked: report.checked,+ notes: report.notes,+ agreements: report.agreements,+ contradictions: report.contradictions,+ stale_claims: report.staleClaims.map((s) => ({+ path: s.path,+ age_days: s.ageDays,+ superseded_by: s.supersededBy,+ })),+ gaps: report.gaps,+ ...(flags["triggers"] === true ? { triggers_created: enqueued } : {}),+ });+ return 0;+ }+ ok(`topic: ${report.topic} (checked: ${report.checked.join(", ")})`);+ ok(`notes: ${report.notes.length}`);+ for (const a of report.agreements) ok(`[agreement] ${a.path} ${a.relation} ${a.target}`);+ for (const c of report.contradictions) ok(`[contradiction] ${c.path} contradicts ${c.target}`);+ for (const s of report.staleClaims) {+ ok(+ `[stale] ${s.path} (${s.ageDays}d${s.supersededBy !== null ? `, superseded by ${s.supersededBy}` : ""})`,+ );+ }+ for (const g of report.gaps) ok(`[gap] ${g.target} <- ${g.sources.join(", ")}`);+ if (flags["triggers"] === true) ok(`triggers created: ${enqueued}`);+ return 0;+ } catch (err) {+ if (err instanceof SearchError) return fail(`${err.message} [${err.code}]`);+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/ideas.ts b/src/cli/brain/verbs/ideas.tsnew file mode 100644index 00000000..7f8ebafc--- /dev/null+++ b/src/cli/brain/verbs/ideas.ts@@ -0,0 +1,68 @@+/**+ * `o2b brain ideas` (Workspace Insight Suite, t_8722a62a): ranked+ * next-direction candidates from open loops. `--triggers` enqueues+ * them into the trigger queue.+ */++import { defaultConfigPath, resolveTriggerCooldownDays } from "../../../core/config.ts";+import { discoverIdeas, ideaCandidates } from "../../../core/brain/idea-discovery.ts";+import { createTriggers } from "../../../core/brain/triggers/store.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainIdeas(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ cap: { type: "string" },+ triggers: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;++ const capRaw = flags["cap"];+ const cap = typeof capRaw === "string" && capRaw.trim() !== "" ? Number(capRaw) : 5;+ if (!Number.isInteger(cap) || cap < 1 || cap > 50) {+ return fail("--cap must be an integer in 1..50");+ }++ try {+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const now = new Date();+ const ideas = discoverIdeas(vault, { now, cap });++ let enqueued = 0;+ if (flags["triggers"] === true) {+ const result = createTriggers(vault, ideaCandidates(ideas), {+ now,+ cooldownDays: resolveTriggerCooldownDays(config),+ });+ enqueued = result.created.length;+ }++ if (json) {+ okJson({+ ok: true,+ ideas: ideas.map((idea) => ({+ kind: idea.kind,+ title: idea.title,+ reason: idea.reason,+ score: idea.score,+ source_artifacts: idea.sourceArtifacts,+ })),+ ...(flags["triggers"] === true ? { triggers_created: enqueued } : {}),+ });+ return 0;+ }+ if (ideas.length === 0) {+ ok("no next-direction candidates");+ return 0;+ }+ ideas.forEach((idea, index) => {+ ok(`[${index + 1}] (${idea.kind}) ${idea.title}: ${idea.reason}`);+ });+ if (flags["triggers"] === true) ok(`triggers created: ${enqueued}`);+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex db82b1cb..2e923e9a 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -38,6 +38,14 @@ export { cmdBrainScanInline } from "./scan-inline.ts";export { cmdBrainImportSession } from "./import-session.ts";export { cmdBrainHandoff } from "./handoff.ts";export { cmdBrainIntention } from "./intention.ts";+export { cmdBrainProject } from "./project.ts";+export { cmdBrainSource } from "./source.ts";+export { cmdBrainLinks } from "./links.ts";+export { cmdBrainProfile } from "./profile.ts";+export { cmdBrainSgrep } from "./sgrep.ts";+export { cmdBrainTrigger } from "./trigger.ts";+export { cmdBrainDeepSynthesis } from "./deep-synthesis.ts";+export { cmdBrainIdeas } from "./ideas.ts";export { cmdBrainEntity } from "./entity.ts";export { cmdBrainSessionHook } from "./session-hook.ts";export { cmdBrainImportClaudeMemory } from "./import-claude-memory.ts";diff --git a/src/cli/brain/verbs/links.ts b/src/cli/brain/verbs/links.tsnew file mode 100644index 00000000..0d452420--- /dev/null+++ b/src/cli/brain/verbs/links.ts@@ -0,0 +1,116 @@+/**+ * `o2b brain links normalize` (Workspace Insight Suite, t_5f31b5f1):+ * rewrite wikilink targets across Brain-owned notes to the configured+ * path format. Dry-run by default; `--write` applies.+ */++import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { defaultConfigPath, resolveWikiLinkFormat } from "../../../core/config.ts";+import {+ isWikiLinkFormat,+ normalizeWikilinks,+ WIKI_LINK_FORMATS,+ type WikiLinkFormat,+} from "../../../core/brain/link-graph/format-wikilink.ts";+import { resolveSearchConfig } from "../../../core/search/index.ts";+import { walkVault } from "../../../core/search/walker.ts";+import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++interface FileChange {+ readonly path: string;+ readonly changed: number;+ readonly ambiguous: ReadonlyArray<string>;+}++export async function cmdBrainLinks(argv: string[]): Promise<number> {+ const action = argv[0];+ if (action !== "normalize") {+ return fail(+ "usage: o2b brain links normalize [path-prefix] [--mode preserve|full|short] [--write] [--json]",+ );+ }+ const { flags, positional } = parse(argv.slice(1), {+ vault: { type: "string" },+ mode: { type: "string" },+ write: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;+ const write = flags["write"] === true;++ try {+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const modeFlag = normalizeFlagString(flags["mode"]);+ let mode: WikiLinkFormat;+ if (modeFlag !== null) {+ if (!isWikiLinkFormat(modeFlag)) {+ return fail(`--mode must be one of ${WIKI_LINK_FORMATS.join(", ")}; got '${modeFlag}'`);+ }+ mode = modeFlag;+ } else {+ mode = resolveWikiLinkFormat(config);+ }++ const pathPrefix = positional[0] ?? "Brain/";+ const searchConfig = resolveSearchConfig({ vault, configPath: config });++ // Known pages: every .md in the vault (ignore-rule aware), as+ // vault-relative paths without the extension.+ const files: Array<{ absPath: string; relPath: string }> = [];+ for (const file of walkVault(searchConfig)) {+ files.push({ absPath: file.absPath, relPath: file.relPath });+ }+ const knownPaths = files.map((f) =>+ f.relPath.endsWith(".md") ? f.relPath.slice(0, -".md".length) : f.relPath,+ );++ const changes: FileChange[] = [];+ let totalChanged = 0;+ for (const file of files) {+ if (!file.relPath.startsWith(pathPrefix)) continue;+ const before = readFileSync(file.absPath, "utf8");+ const result = normalizeWikilinks(before, mode, knownPaths);+ if (result.changed === 0 && result.ambiguous.length === 0) continue;+ changes.push({+ path: file.relPath,+ changed: result.changed,+ ambiguous: result.ambiguous,+ });+ totalChanged += result.changed;+ if (write && result.changed > 0) {+ writeFileSync(join(vault, file.relPath), result.content);+ }+ }++ if (json) {+ okJson({+ ok: true,+ mode,+ applied: write,+ total_changed: totalChanged,+ files: changes.map((c) => ({+ path: c.path,+ changed: c.changed,+ ambiguous: c.ambiguous,+ })),+ });+ return 0;+ }+ ok(`mode: ${mode} (${write ? "applied" : "dry-run"})`);+ if (changes.length === 0) {+ ok("no links to rewrite");+ return 0;+ }+ for (const c of changes) {+ ok(`${c.path}: ${c.changed} link(s)`);+ for (const a of c.ambiguous) ok(` ambiguous: ${a}`);+ }+ ok(`total: ${totalChanged} link(s)${write ? "" : " (re-run with --write to apply)"}`);+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/morning-brief.ts b/src/cli/brain/verbs/morning-brief.tsindex a2c44610..8c3a4011 100644--- a/src/cli/brain/verbs/morning-brief.ts+++ b/src/cli/brain/verbs/morning-brief.ts@@ -1,5 +1,9 @@-import { defaultConfigPath } from "../../../core/config.ts";+import { defaultConfigPath, resolveTriggerCooldownDays } from "../../../core/config.ts";import { buildMorningBrief } from "../../../core/brain/morning-brief.ts";+import {+ deliverBriefTriggers,+ renderTriggerBriefSection,+} from "../../../core/brain/triggers/brief.ts";import { parseOptionalNumberFlag } from "../../coerce.ts";import { fail, parse, resolveBrainVault } from "../helpers.ts";@@ -54,10 +58,47 @@ export async function cmdBrainMorningBrief(argv: string[]): Promise<number> {return fail(`morning-brief failed: ${(exc as Error).message ?? exc}`);}+ // Pending-trigger section (t_cd1fee79): renders only when a trigger+ // scan has produced surfaceable triggers; included triggers are+ // marked delivered so the same prompt shows once per cooldown window.+ const now = new Date();+ let triggerSection;+ try {+ triggerSection = renderTriggerBriefSection(vault, {+ now,+ cooldownDays: resolveTriggerCooldownDays(config),+ });+ } catch {+ triggerSection = null;+ }++ // Delivery is the store mutation: do it BEFORE emitting output so a+ // failed write cannot follow a successful-looking response.+ if (triggerSection !== null && triggerSection.triggers.length > 0) {+ deliverBriefTriggers(vault, triggerSection, now);+ }if (flags["json"]) {- process.stdout.write(JSON.stringify(brief, null, 2) + "\n");+ const payload = {+ ...brief,+ ...(triggerSection !== null && triggerSection.triggers.length > 0+ ? {+ triggers: triggerSection.triggers.map((t) => ({+ id: t.id,+ kind: t.kind,+ urgency: t.urgency,+ reason: t.reason,+ })),+ }+ : {}),+ };+ process.stdout.write(JSON.stringify(payload, null, 2) + "\n");} else {- process.stdout.write((brief.text.length > 0 ? brief.text : "(nothing to surface)") + "\n");+ const base = brief.text.length > 0 ? brief.text : "(nothing to surface)";+ const text =+ triggerSection !== null && triggerSection.text !== ""+ ? `${base}\n\n${triggerSection.text}`+ : base;+ process.stdout.write(text + "\n");}return 0;}diff --git a/src/cli/brain/verbs/profile.ts b/src/cli/brain/verbs/profile.tsnew file mode 100644index 00000000..3b16b935--- /dev/null+++ b/src/cli/brain/verbs/profile.ts@@ -0,0 +1,53 @@+/**+ * `o2b brain profile` (Workspace Insight Suite, t_323a9a83): materialize+ * the compact `Brain/profile.md` digest plus the `.o2bfs` root marker.+ * Age-gated: an existing fresh profile is left alone unless --force.+ */++import { defaultConfigPath } from "../../../core/config.ts";+import { isProfileStale, writeProfileDoc } from "../../../core/brain/profile-doc.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const DEFAULT_STALE_SECONDS = 3600;++export async function cmdBrainProfile(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "stale-seconds": { type: "string" },+ force: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;++ try {+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const staleRaw = flags["stale-seconds"];+ const staleSeconds =+ typeof staleRaw === "string" && staleRaw.trim() !== ""+ ? Number(staleRaw)+ : DEFAULT_STALE_SECONDS;+ if (!Number.isFinite(staleSeconds) || staleSeconds < 0) {+ return fail("--stale-seconds must be a non-negative number");+ }+ const now = new Date();+ if (flags["force"] !== true && !isProfileStale(vault, staleSeconds, now)) {+ if (json) okJson({ ok: true, refreshed: false, reason: "fresh" });+ else ok("profile is fresh (use --force to regenerate)");+ return 0;+ }+ const result = writeProfileDoc(vault, { now });+ if (json) {+ okJson({+ ok: true,+ refreshed: true,+ path: result.path,+ marker: result.markerPath,+ generated_at: result.generatedAt,+ });+ } else ok(`profile written: ${result.path}`);+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/project.ts b/src/cli/brain/verbs/project.tsnew file mode 100644index 00000000..d08b09af--- /dev/null+++ b/src/cli/brain/verbs/project.ts@@ -0,0 +1,145 @@+/**+ * `o2b brain project <link|list|remove|status>` (Workspace Insight+ * Suite, t_1375e69f): pointer files that link project directories to+ * their owning vault, plus the linked-projects registry.+ */++import { resolve } from "node:path";++import { defaultConfigPath, resolveVault } from "../../../core/config.ts";+import {+ findVaultPointer,+ linkedProjectsStatus,+ listLinkedProjects,+ readVaultPointer,+ registerLinkedProject,+ removeVaultPointer,+ unregisterLinkedProject,+ writeVaultPointer,+} from "../../../core/brain/portability/pointer.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainProject(argv: string[]): Promise<number> {+ const action = argv[0];+ if (!action || !["link", "list", "remove", "status"].includes(action)) {+ return fail("usage: o2b brain project <link|list|remove|status> [path] [--vault V] [--json]");+ }+ const { flags, positional } = parse(argv.slice(1), {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;++ try {+ if (action === "link") {+ const target = positional[0];+ if (!target) return fail("brain project link requires a project path");+ const projectDir = resolve(target);+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const priorPointer = readVaultPointer(projectDir);+ const pointerPath = writeVaultPointer(projectDir, vault);+ try {+ registerLinkedProject(config, projectDir, vault);+ } catch (registryErr) {+ // Keep the two stores in agreement: roll the pointer back to+ // its prior state before surfacing the registry failure.+ if (priorPointer === null) removeVaultPointer(projectDir);+ else if (priorPointer.pointer !== null) {+ writeVaultPointer(projectDir, priorPointer.pointer.vault);+ }+ throw registryErr;+ }+ if (json) okJson({ ok: true, path: projectDir, vault, pointer: pointerPath });+ else ok(`linked ${projectDir} -> ${vault}`);+ return 0;+ }++ if (action === "list") {+ const projects = listLinkedProjects(config);+ if (json) {+ okJson({ ok: true, projects: projects.map((p) => ({ path: p.path, vault: p.vault })) });+ return 0;+ }+ if (projects.length === 0) {+ ok("no linked projects");+ return 0;+ }+ for (const p of projects) ok(`${p.path} -> ${p.vault}`);+ return 0;+ }++ if (action === "remove") {+ const target = positional[0];+ if (!target) return fail("brain project remove requires a project path");+ const projectDir = resolve(target);+ // Registry first: if the pointer removal then fails, a re-run+ // still succeeds (pointer present, entry already gone). The+ // reverse order would leave a registered project with no pointer.+ const removedEntry = unregisterLinkedProject(config, projectDir);+ const removedPointer = removeVaultPointer(projectDir);+ if (!removedPointer && !removedEntry) {+ return fail(`no project link found at ${projectDir}`);+ }+ if (json) {+ okJson({+ ok: true,+ path: projectDir,+ pointer_removed: removedPointer,+ registry_removed: removedEntry,+ });+ } else ok(`unlinked ${projectDir}`);+ return 0;+ }++ // status: walk-up probe for [path]/cwd + registry-wide health.+ const probeDir = resolve(positional[0] ?? process.cwd());+ const probe = findVaultPointer(probeDir);+ const resolvedVault = resolveVault(config, { cwd: probeDir });+ const mode =+ process.env["VAULT_DIR"] !== undefined && process.env["VAULT_DIR"] !== ""+ ? "env"+ : probe !== null && probe.pointer !== null && resolvedVault === probe.pointer.vault+ ? "pointer"+ : resolvedVault !== null+ ? "config"+ : "unresolved";+ const projects = linkedProjectsStatus(config);+ if (json) {+ okJson({+ ok: true,+ probe_dir: probeDir,+ resolved_vault: resolvedVault,+ resolution: mode,+ pointer:+ probe === null+ ? null+ : {+ path: probe.path,+ dir: probe.dir,+ vault: probe.pointer?.vault ?? null,+ error: probe.error,+ },+ projects: projects.map((p) => ({+ path: p.path,+ vault: p.vault,+ pointer: p.pointer,+ vault_exists: p.vaultExists,+ })),+ });+ return 0;+ }+ ok(`resolved vault: ${resolvedVault ?? "(none)"} [${mode}]`);+ if (probe !== null) {+ if (probe.error !== null) ok(`pointer ${probe.path}: MALFORMED (${probe.error})`);+ else ok(`pointer ${probe.path} -> ${probe.pointer!.vault}`);+ }+ for (const p of projects) {+ const vaultNote = p.vaultExists ? "" : " (vault missing)";+ ok(`${p.path} -> ${p.vault} [${p.pointer}]${vaultNote}`);+ }+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/recall-telemetry.ts b/src/cli/brain/verbs/recall-telemetry.tsindex f43cfc54..0f64753e 100644--- a/src/cli/brain/verbs/recall-telemetry.ts+++ b/src/cli/brain/verbs/recall-telemetry.ts@@ -5,6 +5,7 @@ import {listRecallTelemetry,summarizeRecallTelemetry,} from "../../../core/brain/recall-telemetry.ts";+import { listGateTelemetry, summarizeGateTelemetry } from "../../../core/brain/gate-telemetry.ts";import { CliError, parse, resolveBrainVault } from "../helpers.ts";export async function cmdBrainRecallTelemetry(argv: string[]): Promise<number> {@@ -12,7 +13,10 @@ export async function cmdBrainRecallTelemetry(argv: string[]): Promise<number> {const rest = argv.slice(1);if (subcommand === "list") return listTelemetry(rest);if (subcommand === "summary") return summarizeTelemetry(rest);- throw new CliError("brain recall-telemetry: expected list or summary");+ // Gate-decision telemetry (Workspace Insight Suite, t_65036e02).+ if (subcommand === "gate-list") return listGate(rest);+ if (subcommand === "gate-summary") return summarizeGate(rest);+ throw new CliError("brain recall-telemetry: expected list, summary, gate-list, or gate-summary");}function listTelemetry(argv: string[]): number {@@ -57,6 +61,65 @@ function summarizeTelemetry(argv: string[]): number {return 0;}+function rejectRecallOnlyFlags(+ flags: Record<string, string | boolean | string[] | undefined>,+ command: string,+ alsoReject: ReadonlyArray<string> = [],+): void {+ // Gate records have no mode/status dimensions - dropping these+ // silently would hand back unfiltered results.+ for (const name of ["mode", "status", ...alsoReject]) {+ if (flags[name] !== undefined) {+ throw new CliError(`${command}: --${name} is not supported for gate telemetry`);+ }+ }+}++function listGate(argv: string[]): number {+ const { flags } = parseTelemetryFlags(argv);+ rejectRecallOnlyFlags(flags, "brain recall-telemetry gate-list");+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());+ const filter = telemetryFilter(flags, "brain recall-telemetry gate-list");+ const records = listGateTelemetry(vault, {+ ...(filter.host !== undefined ? { host: filter.host } : {}),+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ ...(filter.limit !== undefined ? { limit: filter.limit } : {}),+ });+ if (flags["json"]) {+ process.stdout.write(JSON.stringify({ total: records.length, records }, null, 2) + "\n");+ return 0;+ }+ process.stdout.write(`${records.length} gate decision(s):\n`);+ for (const record of records) {+ process.stdout.write(+ ` ${record.createdAt} ${record.payload["decision"]} ${record.payload["reason"]} host=${record.payload["host"] ?? "?"}\n`,+ );+ }+ return 0;+}++function summarizeGate(argv: string[]): number {+ const { flags } = parseTelemetryFlags(argv);+ rejectRecallOnlyFlags(flags, "brain recall-telemetry gate-summary", ["limit"]);+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());+ const filter = telemetryFilter(flags, "brain recall-telemetry gate-summary");+ const summary = summarizeGateTelemetry(vault, {+ ...(filter.host !== undefined ? { host: filter.host } : {}),+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ });+ if (flags["json"]) {+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");+ return 0;+ }+ process.stdout.write(`decisions: ${summary.total}\n`);+ process.stdout.write(`retrieved: ${summary.retrieved}\n`);+ process.stdout.write(`skipped: ${summary.skipped}\n`);+ process.stdout.write(`by reason: ${JSON.stringify(summary.by_reason)}\n`);+ return 0;+}+function parseTelemetryFlags(argv: string[]): {readonly flags: Record<string, string | boolean | string[] | undefined>;} {diff --git a/src/cli/brain/verbs/sgrep.ts b/src/cli/brain/verbs/sgrep.tsnew file mode 100644index 00000000..b6a37f56--- /dev/null+++ b/src/cli/brain/verbs/sgrep.ts@@ -0,0 +1,71 @@+/**+ * `o2b brain sgrep <query> [path]` (Workspace Insight Suite,+ * t_323a9a83): grep-shaped semantic Brain search. Ordinary shell+ * reflexes - positional query, optional path scope, `path:line:`+ * output lines - over the existing search pipeline. Exact `grep`+ * stays untouched; this is a separate verb, never a wrapper.+ */++import { defaultConfigPath } from "../../../core/config.ts";+import { resolveSearchConfig, search, SearchError } from "../../../core/search/index.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainSgrep(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ limit: { type: "string" },+ "keyword-only": { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;++ const query = positional[0];+ if (!query || query.trim() === "") {+ return fail(+ "usage: o2b brain sgrep <query> [path-prefix] [--limit N] [--keyword-only] [--json]",+ );+ }+ const pathPrefix = positional[1];+ const limitRaw = flags["limit"];+ const limit = typeof limitRaw === "string" && limitRaw.trim() !== "" ? Number(limitRaw) : 10;+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {+ return fail("--limit must be an integer in 1..100");+ }++ try {+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const searchConfig = resolveSearchConfig({ vault, configPath: config });+ const outcome = await search(searchConfig, {+ query,+ limit,+ keywordOnly: flags["keyword-only"] === true,+ ...(pathPrefix !== undefined ? { pathPrefix } : {}),+ });+ if (json) {+ okJson({+ ok: true,+ results: outcome.results.map((r) => ({+ path: r.path,+ line: r.startLine,+ score: r.score,+ snippet: r.content.trim().replace(/\s+/gu, " ").slice(0, 200),+ })),+ total: outcome.total,+ warnings: outcome.warnings,+ });+ // Grep-like contract holds in JSON mode too: no matches -> 1.+ return outcome.results.length > 0 ? 0 : 1;+ }+ for (const r of outcome.results) {+ const snippet = r.content.trim().replace(/\s+/gu, " ").slice(0, 160);+ ok(`${r.path}:${r.startLine}: ${snippet}`);+ }+ if (outcome.results.length === 0) ok("(no matches)");+ for (const warning of outcome.warnings) ok(`warning: ${warning}`);+ return outcome.results.length > 0 ? 0 : 1;+ } catch (err) {+ if (err instanceof SearchError) return fail(`${err.message} [${err.code}]`);+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/source.ts b/src/cli/brain/verbs/source.tsnew file mode 100644index 00000000..87dc5bec--- /dev/null+++ b/src/cli/brain/verbs/source.ts@@ -0,0 +1,75 @@+/**+ * `o2b brain source <add|list|remove>` (Workspace Insight Suite,+ * t_1375e69f): read-only recall sources of the active vault. Distinct+ * from `o2b brain sources` (the signals-by-agent dashboard): this verb+ * manages which EXTERNAL vaults participate in recall as read-only+ * origins.+ */++import { resolve } from "node:path";++import { defaultConfigPath } from "../../../core/config.ts";+import {+ addRecallSource,+ listRecallSources,+ removeRecallSource,+} from "../../../core/brain/portability/recall-sources.ts";+import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainSource(argv: string[]): Promise<number> {+ const action = argv[0];+ if (!action || !["add", "list", "remove"].includes(action)) {+ return fail("usage: o2b brain source <add|list|remove> [path|alias] [--alias A] [--json]");+ }+ const { flags, positional } = parse(argv.slice(1), {+ vault: { type: "string" },+ alias: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;++ try {+ const owner = resolveBrainVault(flags["vault"] as string | undefined, config);++ if (action === "add") {+ const target = positional[0];+ if (!target) return fail("brain source add requires a vault path");+ const alias = normalizeFlagString(flags["alias"]);+ if (alias === null) return fail("brain source add requires --alias");+ addRecallSource(config, owner, alias, resolve(target));+ if (json) okJson({ ok: true, alias, vault: resolve(target), read_only: true });+ else ok(`source ${alias} -> ${resolve(target)} (read-only)`);+ return 0;+ }++ if (action === "list") {+ const sources = listRecallSources(config, owner);+ if (json) {+ okJson({+ ok: true,+ sources: sources.map((s) => ({ alias: s.alias, vault: s.vault, broken: s.broken })),+ });+ return 0;+ }+ if (sources.length === 0) {+ ok("no recall sources");+ return 0;+ }+ for (const s of sources) ok(`${s.alias} -> ${s.vault}${s.broken ? " (BROKEN)" : ""}`);+ return 0;+ }++ // remove+ const alias = positional[0] ?? normalizeFlagString(flags["alias"]);+ if (!alias) return fail("brain source remove requires an alias");+ if (!removeRecallSource(config, owner, alias)) {+ return fail(`no recall source with alias: ${alias}`);+ }+ if (json) okJson({ ok: true, alias, removed: true });+ else ok(`source ${alias} removed`);+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/trigger.ts b/src/cli/brain/verbs/trigger.tsnew file mode 100644index 00000000..207af977--- /dev/null+++ b/src/cli/brain/verbs/trigger.ts@@ -0,0 +1,117 @@+/**+ * `o2b brain trigger <scan|list|ack|dismiss|act|history>` (Workspace+ * Insight Suite, t_cd1fee79): the grounded proactive trigger queue+ * with its anti-nag lifecycle.+ */++import { defaultConfigPath, resolveTriggerCooldownDays } from "../../../core/config.ts";+import { scanTriggers } from "../../../core/brain/triggers/scan.ts";+import {+ listTriggers,+ transitionTrigger,+ type TriggerAction,+} from "../../../core/brain/triggers/store.ts";+import { isTriggerStatus, type TriggerRecord } from "../../../core/brain/triggers/types.ts";+import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const TERMINAL = new Set(["acted", "dismissed", "expired"]);++function triggerJson(record: TriggerRecord): Record<string, unknown> {+ return {+ id: record.id,+ kind: record.kind,+ status: record.effectiveStatus,+ urgency: record.urgency,+ reason: record.reason,+ suggested_action: record.suggestedAction,+ source_artifacts: record.sourceArtifacts,+ cooldown_key: record.cooldownKey,+ created_at: record.createdAt,+ expires_at: record.expiresAt,+ delivered_at: record.deliveredAt,+ resolved_at: record.resolvedAt,+ };+}++function printTrigger(record: TriggerRecord): void {+ ok(`${record.id} [${record.effectiveStatus}] (${record.urgency}) ${record.reason}`);+}++export async function cmdBrainTrigger(argv: string[]): Promise<number> {+ const action = argv[0];+ const actions = ["scan", "list", "ack", "dismiss", "act", "history"];+ if (!action || !actions.includes(action)) {+ return fail(+ "usage: o2b brain trigger <scan|list|ack|dismiss|act|history> [id] [--status S] [--json]",+ );+ }+ const { flags, positional } = parse(argv.slice(1), {+ vault: { type: "string" },+ status: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const json = flags["json"] === true;+ const now = new Date();++ try {+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ if (action === "scan") {+ const cooldownDays = resolveTriggerCooldownDays(config);+ const result = scanTriggers(vault, { now, cooldownDays });+ if (json) {+ okJson({+ ok: true,+ candidates: result.candidates,+ created: result.created.map(triggerJson),+ skipped: result.skipped.map((s) => ({ cooldown_key: s.cooldownKey, reason: s.reason })),+ });+ return 0;+ }+ ok(+ `candidates: ${result.candidates}, created: ${result.created.length}, skipped: ${result.skipped.length}`,+ );+ for (const record of result.created) printTrigger(record);+ return 0;+ }++ if (action === "list" || action === "history") {+ const statusFlag = normalizeFlagString(flags["status"]);+ if (statusFlag !== null && !isTriggerStatus(statusFlag)) {+ return fail(`unknown trigger status: ${statusFlag}`);+ }+ let records = listTriggers(vault, {+ now,+ ...(statusFlag !== null ? { status: statusFlag } : {}),+ });+ if (action === "history") {+ records = records.filter((r) => TERMINAL.has(r.effectiveStatus));+ } else if (statusFlag === null) {+ records = records.filter((r) => !TERMINAL.has(r.effectiveStatus));+ }+ if (json) {+ okJson({ ok: true, triggers: records.map(triggerJson) });+ return 0;+ }+ if (records.length === 0) {+ ok(action === "history" ? "no trigger history" : "no open triggers");+ return 0;+ }+ for (const record of records) printTrigger(record);+ return 0;+ }++ // ack / dismiss / act+ const id = positional[0];+ if (!id) return fail(`brain trigger ${action} requires a trigger id`);+ const verb: TriggerAction =+ action === "ack" ? "acknowledge" : action === "dismiss" ? "dismiss" : "act";+ const record = transitionTrigger(vault, id, verb, { now });+ if (json) okJson({ ok: true, trigger: triggerJson(record) });+ else printTrigger(record);+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex d839c37e..ec1df713 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -152,6 +152,14 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("import-session", "Replay registered agent sessions"),command("handoff", "Write an operator-readable session handoff note"),command("intention", "Manage scoped current-intention chains"),+ command("project", "Link project directories to their owning vault"),+ command("source", "Manage read-only recall sources of the active vault"),+ command("links", "Normalize wikilink path format across Brain notes"),+ command("profile", "Materialize the compact Brain/profile.md digest"),+ command("sgrep", "Grep-shaped semantic Brain search (path:line: output)"),+ command("trigger", "Grounded proactive trigger queue (scan/list/ack/dismiss/act/history)"),+ command("deep-synthesis", "Topic dossier: agreements, contradictions, stale claims, gaps"),+ command("ideas", "Ranked next-direction candidates from open loops"),command("entity", "Canonical entity registry: set, get, list, relate, archive"),command("session-hook", "Capture runtime lifecycle hook payloads"),command("import-claude-memory", "Import Claude memory feedback"),diff --git a/src/cli/search.ts b/src/cli/search.tsindex 3a8c89d0..51c92c96 100644--- a/src/cli/search.ts+++ b/src/cli/search.ts@@ -49,6 +49,7 @@ import type {SearchSessionFocus,SearchOutcome,} from "../core/search/index.ts";+import { searchAcrossVaults } from "../core/search/cross-vault.ts";import { CliError, parseFlags } from "./argparse.ts";import { CronTemplateError, renderCronTemplate } from "./search-cron-template.ts";@@ -416,6 +417,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {"include-superseded": { type: "boolean" },since: { type: "string" },until: { type: "string" },+ global: { type: "boolean" },json: { type: "boolean" },verbose: { type: "boolean" },});@@ -463,7 +465,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {const properties = parsePropertyFlags(flags["property"] as string[] | undefined);const visibility = flags["visibility"] as string[] | undefined;- const outcome = await search(cfg, {+ const searchOpts = {query,limit: limitNum,semantic: semanticOverride,@@ -476,7 +478,18 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {...(flags["include-superseded"] === true ? { includeSuperseded: true } : {}),...(typeof flags["since"] === "string" ? { since: flags["since"] as string } : {}),...(typeof flags["until"] === "string" ? { until: flags["until"] as string } : {}),- });+ };+ // Cross-vault union (t_72a22658): explicit per-call opt-in fans the+ // query out over profiles and read-only sources with origin labels.+ const outcome =+ flags["global"] === true+ ? await searchAcrossVaults(+ typeof flags["config"] === "string" ? (flags["config"] as string) : defaultConfigPath(),+ cfg.vault,+ searchOpts,+ cfg,+ )+ : await search(cfg, searchOpts);if (flags["json"]) {process.stdout.write(JSON.stringify(jsonForOutcome(outcome)) + "\n");@@ -531,6 +544,7 @@ function jsonForOutcome(o: SearchOutcome): unknown {end_line: r.endLine,search_type: r.searchType,reasons: r.reasons,+ ...(r.origin !== undefined ? { origin: r.origin } : {}),...(o.evidencePack ? { why_retrieved: r.reasons } : {}),document_id: r.documentId,chunk_id: r.chunkId,@@ -599,7 +613,8 @@ function renderOutcomeHuman(o: SearchOutcome, verbose: boolean): string {}o.results.forEach((r, i) => {const score = r.score.toFixed(2);- lines.push(`[${i + 1}] ${r.path} β’ ${score}`);+ const originSuffix = r.origin !== undefined ? ` β’ ${r.origin}` : "";+ lines.push(`[${i + 1}] ${r.path} β’ ${score}${originSuffix}`);lines.push(` line ${r.startLine}-${r.endLine} β’ ${r.searchType}` +(verbosediff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.tsindex 0371f18e..db77fc71 100644--- a/src/core/brain/continuity/types.ts+++ b/src/core/brain/continuity/types.ts@@ -1,6 +1,7 @@export type ContinuityRecordKind =| "context_receipt"| "recall_telemetry"+ | "gate_telemetry"| "pre_compact_extract"| "session_turn"| "session_summary_node"diff --git a/src/core/brain/deep-synthesis.ts b/src/core/brain/deep-synthesis.tsnew file mode 100644index 00000000..26e59462--- /dev/null+++ b/src/core/brain/deep-synthesis.ts@@ -0,0 +1,236 @@+/**+ * Deep vault synthesis (Workspace Insight Suite, t_04e94382).+ *+ * Topic-scoped, deterministic evidence assembly: every note matching a+ * topic is cross-referenced for agreements (positive typed relations+ * between matched notes), contradictions (`contradicts` relations),+ * stale claims (aged or superseded notes), and knowledge gaps+ * (dangling wikilink targets). The dossier states exactly which+ * dimensions were checked so an empty section is interpretable as+ * "checked, nothing found" - prose synthesis stays with the calling+ * agent, never inside core.+ *+ * Contradiction and gap findings convert into trigger candidates+ * (Kernel B) via {@link synthesisCandidates}.+ */++import { readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import { search } from "../search/search.ts";+import { walkVault } from "../search/walker.ts";+import type { BrainSearchResult, ResolvedSearchConfig } from "../search/types.ts";+import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";+import type { InsightCandidate } from "./triggers/types.ts";++const POSITIVE_RELATIONS: ReadonlySet<string> = new Set(["related", "extends", "supports"]);++export interface SynthesisNote {+ readonly path: string;+ readonly title: string | null;+ readonly score: number;+}++export interface SynthesisAgreement {+ readonly path: string;+ readonly relation: string;+ readonly target: string;+}++export interface SynthesisContradiction {+ readonly path: string;+ readonly target: string;+}++export interface SynthesisStaleClaim {+ readonly path: string;+ readonly ageDays: number;+ readonly supersededBy: string | null;+}++export interface SynthesisGap {+ readonly target: string;+ readonly sources: ReadonlyArray<string>;+}++export interface DeepSynthesisReport {+ readonly topic: string;+ readonly generatedAt: string;+ /** Dimensions this dossier actually checked, in order. */+ readonly checked: ReadonlyArray<string>;+ readonly notes: ReadonlyArray<SynthesisNote>;+ readonly agreements: ReadonlyArray<SynthesisAgreement>;+ readonly contradictions: ReadonlyArray<SynthesisContradiction>;+ readonly staleClaims: ReadonlyArray<SynthesisStaleClaim>;+ readonly gaps: ReadonlyArray<SynthesisGap>;+}++export interface DeepSynthesisOptions {+ readonly now: Date;+ /** Max matched notes considered. Default 30. */+ readonly limit?: number;+ /** A matched note older than this counts as a stale claim. Default 90. */+ readonly staleAgeDays?: number;+}++const CHECKED = Object.freeze([+ "matched_notes",+ "agreements",+ "contradictions",+ "stale_claims",+ "knowledge_gaps",+]);++function stripMd(path: string): string {+ return path.endsWith(".md") ? path.slice(0, -".md".length) : path;+}++export async function deepSynthesis(+ config: ResolvedSearchConfig,+ topic: string,+ opts: DeepSynthesisOptions,+): Promise<DeepSynthesisReport> {+ const limit = opts.limit ?? 30;+ const staleAgeDays = opts.staleAgeDays ?? 90;+ // Fetch raw CHUNK hits well past the note limit: one long document+ // can produce many chunks, and capping before the per-document+ // dedupe would let it crowd every other note out of the dossier.+ const rawLimit = Math.min(100, Math.max(limit * 3, limit));+ const outcome = await search(config, { query: topic, limit: rawLimit, keywordOnly: true });++ // Dedupe chunk hits into per-document notes (best score wins), THEN+ // apply the note limit.+ const byPath = new Map<string, BrainSearchResult>();+ for (const result of outcome.results) {+ const seen = byPath.get(result.path);+ if (seen === undefined || result.score > seen.score) byPath.set(result.path, result);+ }+ const matched = [...byPath.values()]+ .toSorted((a, b) => (a.score !== b.score ? b.score - a.score : a.path < b.path ? -1 : 1))+ .slice(0, limit);++ // Known pages across the vault: gap detection needs the full set,+ // not just the matched slice.+ const knownTargets = new Set<string>();+ for (const file of walkVault(config)) {+ const page = stripMd(file.relPath);+ knownTargets.add(page);+ const slash = page.lastIndexOf("/");+ knownTargets.add(slash >= 0 ? page.slice(slash + 1) : page);+ }++ // Agreement edges stay scoped to the matched-topic set: a positive+ // relation to an off-topic note is not evidence about THIS topic.+ // Contradiction edges deliberately stay unscoped - the counterpart+ // of a topical claim often uses different vocabulary and would never+ // match the query, and those are exactly the finds a synthesis is+ // for.+ const matchedTargets = new Set<string>();+ for (const note of matched) {+ const page = stripMd(note.path);+ matchedTargets.add(page);+ const slash = page.lastIndexOf("/");+ matchedTargets.add(slash >= 0 ? page.slice(slash + 1) : page);+ }++ const agreements: SynthesisAgreement[] = [];+ const contradictions: SynthesisContradiction[] = [];+ const staleClaims: SynthesisStaleClaim[] = [];+ const gapSources = new Map<string, Set<string>>();++ for (const note of matched) {+ let supersededBy: string | null = null;+ for (const rel of note.relations ?? []) {+ if (rel.relation === "contradicts") {+ contradictions.push(Object.freeze({ path: note.path, target: rel.target }));+ } else if (rel.relation === "superseded_by") {+ supersededBy = rel.target;+ } else if (POSITIVE_RELATIONS.has(rel.relation) && matchedTargets.has(rel.target)) {+ agreements.push(+ Object.freeze({ path: note.path, relation: rel.relation, target: rel.target }),+ );+ }+ }++ // Stale: superseded notes always; otherwise age by mtime.+ let ageDays = 0;+ try {+ const mtimeMs = statSync(join(config.vault, note.path)).mtimeMs;+ ageDays = Math.floor((opts.now.getTime() - mtimeMs) / (24 * 3600 * 1000));+ } catch {+ ageDays = 0;+ }+ if (supersededBy !== null || ageDays > staleAgeDays) {+ staleClaims.push(Object.freeze({ path: note.path, ageDays, supersededBy }));+ }++ // Gaps: wikilink targets referenced by this note that resolve to+ // no vault page.+ let content: string;+ try {+ content = readFileSync(join(config.vault, note.path), "utf8");+ } catch {+ continue;+ }+ for (const body of extractWikilinkRichBodies(content)) {+ const target = parseWikilinkRich(body).target;+ if (target === "" || knownTargets.has(target)) continue;+ const sources = gapSources.get(target) ?? new Set<string>();+ sources.add(note.path);+ gapSources.set(target, sources);+ }+ }++ return Object.freeze({+ topic,+ generatedAt: opts.now.toISOString(),+ checked: CHECKED,+ notes: Object.freeze(+ matched.map((note) =>+ Object.freeze({ path: note.path, title: note.title, score: note.score }),+ ),+ ),+ agreements: Object.freeze(agreements),+ contradictions: Object.freeze(contradictions),+ staleClaims: Object.freeze(staleClaims),+ gaps: Object.freeze(+ [...gapSources.entries()]+ .toSorted((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))+ .map(([target, sources]) =>+ Object.freeze({ target, sources: Object.freeze([...sources].toSorted()) }),+ ),+ ),+ });+}++/** Contradiction and gap findings as trigger candidates (Kernel B). */+export function synthesisCandidates(report: DeepSynthesisReport): ReadonlyArray<InsightCandidate> {+ const out: InsightCandidate[] = [];+ for (const finding of report.contradictions) {+ out.push(+ Object.freeze({+ kind: "contradiction" as const,+ urgency: "high" as const,+ reason: `${finding.path} declares contradicts -> ${finding.target} (topic: ${report.topic})`,+ suggestedAction: "Reconcile the two notes or retire the stale claim",+ sourceArtifacts: Object.freeze([finding.path, `[[${finding.target}]]`]),+ contextSnippets: Object.freeze([`topic: ${report.topic}`]),+ cooldownKey: `contradiction:${finding.path}:${finding.target}`,+ }),+ );+ }+ for (const gap of report.gaps) {+ out.push(+ Object.freeze({+ kind: "knowledge_gap" as const,+ urgency: "medium" as const,+ reason: `[[${gap.target}]] is referenced but has no note (topic: ${report.topic})`,+ suggestedAction: "Write the missing note or fix the dangling link",+ sourceArtifacts: Object.freeze([...gap.sources]),+ contextSnippets: Object.freeze([`topic: ${report.topic}`]),+ cooldownKey: `knowledge_gap:${gap.target}`,+ }),+ );+ }+ return Object.freeze(out);+}diff --git a/src/core/brain/gate-telemetry.ts b/src/core/brain/gate-telemetry.tsnew file mode 100644index 00000000..b6e07951--- /dev/null+++ b/src/core/brain/gate-telemetry.ts@@ -0,0 +1,101 @@+/**+ * Recall-gate telemetry (Workspace Insight Suite, t_65036e02).+ *+ * Records every automatic-recall gate decision as a `gate_telemetry`+ * continuity record so the skip/retrieve behaviour becomes observable+ * and tunable. Privacy invariant: the RAW PROMPT is never stored -+ * continuity records sync with the vault, so only a SHA-256 prefix+ * (enough for duplicate analysis) and the prompt length land on disk.+ *+ * Default OFF: the `brain_recall_gate` handler emits only when the+ * `recall_gate_telemetry` config key is on, keeping the gate's+ * pure-diagnostic contract byte-identical otherwise. Reuses the+ * continuity-record kernel rather than inventing a new sink.+ */++import { createHash } from "node:crypto";++import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";+import type { ContinuityRecord } from "./continuity/types.ts";++export interface GateTelemetryInput {+ readonly host: string;+ readonly prompt: string;+ readonly retrieve: boolean;+ readonly reason: string;+ readonly sessionId?: string;+ readonly createdAt?: string;+}++export interface GateTelemetryFilter {+ readonly host?: string;+ readonly since?: string;+ readonly until?: string;+ readonly limit?: number;+}++export interface GateTelemetrySummary {+ readonly total: number;+ readonly retrieved: number;+ readonly skipped: number;+ readonly by_reason: Record<string, number>;+}++export function hashPrompt(prompt: string): string {+ return createHash("sha256").update(prompt).digest("hex").slice(0, 16);+}++/** Record one gate decision. Never stores the raw prompt. */+export function emitGateTelemetry(vault: string, input: GateTelemetryInput): ContinuityRecord {+ return appendContinuityRecord(vault, {+ kind: "gate_telemetry",+ createdAt: input.createdAt ?? new Date().toISOString(),+ sourceRefs: [],+ payload: {+ host: input.host,+ ...(input.sessionId !== undefined ? { session_id: input.sessionId } : {}),+ decision: input.retrieve ? "retrieve" : "skip",+ reason: input.reason,+ prompt_hash: hashPrompt(input.prompt),+ prompt_chars: input.prompt.length,+ },+ });+}++/** Gate decisions, newest first. */+export function listGateTelemetry(+ vault: string,+ filter: GateTelemetryFilter = {},+): ReadonlyArray<ContinuityRecord> {+ let records = listContinuityRecords(vault, {+ kind: "gate_telemetry",+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ }).filter((record) => filter.host === undefined || record.payload["host"] === filter.host);+ records = records.toReversed();+ if (filter.limit !== undefined) records = records.slice(0, Math.max(0, Math.floor(filter.limit)));+ return Object.freeze(records);+}++/** Aggregate decisions by outcome and reason. */+export function summarizeGateTelemetry(+ vault: string,+ filter: GateTelemetryFilter = {},+): GateTelemetrySummary {+ const records = listGateTelemetry(vault, filter);+ let retrieved = 0;+ const byReason: Record<string, number> = {};+ for (const record of records) {+ if (record.payload["decision"] === "retrieve") retrieved += 1;+ const reason = record.payload["reason"];+ if (typeof reason === "string" && reason !== "") {+ byReason[reason] = (byReason[reason] ?? 0) + 1;+ }+ }+ return Object.freeze({+ total: records.length,+ retrieved,+ skipped: records.length - retrieved,+ by_reason: Object.freeze(byReason),+ });+}diff --git a/src/core/brain/idea-discovery.ts b/src/core/brain/idea-discovery.tsnew file mode 100644index 00000000..910170f9--- /dev/null+++ b/src/core/brain/idea-discovery.ts@@ -0,0 +1,219 @@+/**+ * Idea discovery (Workspace Insight Suite, t_8722a62a).+ *+ * Ranks next-direction candidates from the vault's open loops:+ * unanswered open questions (reconcile log entries), orphan research+ * notes (no inbound wikilink anywhere under Brain/), and aging+ * unresolved inbox signals. Scoring is deterministic and documented+ * here: open questions (weight 3) outrank orphans (2) outrank aging+ * signals (1); ties break by age (older first), then by title. The+ * top candidates can feed the trigger queue (Kernel B).+ */++import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import { buildMorningBrief, type MorningBriefOpenQuestion } from "./morning-brief.ts";+import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";+import { parseFrontmatterText } from "../vault.ts";+import type { InsightCandidate, TriggerKind } from "./triggers/types.ts";++const DAY_MS = 24 * 3600 * 1000;+const KIND_WEIGHT: Readonly<Record<string, number>> = Object.freeze({+ open_question: 3,+ orphan_research: 2,+ idea_direction: 1,+});++export interface IdeaCandidate {+ readonly kind: TriggerKind;+ readonly title: string;+ readonly reason: string;+ readonly score: number;+ readonly sourceArtifacts: ReadonlyArray<string>;+}++export interface DiscoverIdeasOptions {+ readonly now: Date;+ /** Ranked candidates returned. Default 5. */+ readonly cap?: number;+ /** Days before an unresolved inbox signal counts as aging. Default 14. */+ readonly agingSignalDays?: number;+ /** Log lookback for open questions. Default 30. */+ readonly lookbackDays?: number;+ /** Injection point for tests; default reads the morning-brief scan. */+ readonly openQuestions?: ReadonlyArray<MorningBriefOpenQuestion>;+}++interface NoteFile {+ readonly relPath: string;+ readonly absPath: string;+}++/** Top-level Brain dirs whose notes never count as orphan CANDIDATES. */+const MACHINE_DIRS: ReadonlySet<string> = new Set([+ "log",+ "inbox",+ "triggers",+ "intentions",+ "handoffs",+ "continuity",+]);++/** Recursively list .md files under Brain/, optionally skipping dirs. */+function listBrainNotes(vault: string, skipTopLevel: ReadonlySet<string> = new Set()): NoteFile[] {+ const out: NoteFile[] = [];+ const walk = (dir: string, rel: string): void => {+ let entries;+ try {+ entries = readdirSync(join(dir), { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry.name.startsWith(".")) continue;+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;+ if (entry.isDirectory()) {+ if (rel === "" && skipTopLevel.has(entry.name)) continue;+ walk(join(dir, entry.name), childRel);+ } else if (entry.name.endsWith(".md")) {+ out.push({ relPath: `Brain/${childRel}`, absPath: join(dir, entry.name) });+ }+ }+ };+ walk(join(vault, "Brain"), "");+ return out;+}++function baseName(relPath: string): string {+ const slash = relPath.lastIndexOf("/");+ const name = slash >= 0 ? relPath.slice(slash + 1) : relPath;+ return name.endsWith(".md") ? name.slice(0, -".md".length) : name;+}++function ageDays(absPath: string, now: Date): number {+ try {+ return Math.floor((now.getTime() - statSync(absPath).mtimeMs) / DAY_MS);+ } catch {+ return 0;+ }+}++export function discoverIdeas(+ vault: string,+ opts: DiscoverIdeasOptions,+): ReadonlyArray<IdeaCandidate> {+ const cap = opts.cap ?? 5;+ const agingSignalDays = opts.agingSignalDays ?? 14;+ const candidates: IdeaCandidate[] = [];++ // 1. Open questions from the reconcile trail.+ const openQuestions =+ opts.openQuestions ??+ buildMorningBrief(vault, {+ now: opts.now,+ topK: 0,+ lookbackDays: opts.lookbackDays ?? 30,+ }).openQuestions;+ for (const question of openQuestions) {+ candidates.push(+ Object.freeze({+ kind: "open_question" as const,+ title: question.topic,+ reason: `open question '${question.topic}' (${question.domain}) has no resolution on record`,+ score: KIND_WEIGHT["open_question"]!,+ sourceArtifacts: Object.freeze([question.topic]),+ }),+ );+ }++ // 2. Orphan research notes: no inbound wikilink from ANY Brain note.+ // Two passes: inbound links are collected from the FULL Brain tree+ // (a reference from a handoff or trigger still counts), while orphan+ // CANDIDATES come only from non-machine dirs.+ const allNotes = listBrainNotes(vault);+ const notes = listBrainNotes(vault, MACHINE_DIRS);+ const inbound = new Set<string>();+ for (const note of allNotes) {+ let content: string;+ try {+ content = readFileSync(note.absPath, "utf8");+ } catch {+ continue;+ }+ for (const body of extractWikilinkRichBodies(content)) {+ const target = parseWikilinkRich(body).target;+ if (target !== "") inbound.add(target);+ }+ }+ for (const note of notes) {+ const name = baseName(note.relPath);+ if (name === "profile" || name === "active" || name === "pinned") continue;+ // Heuristic: inbound matching is by bare basename, so two notes+ // sharing a basename can mask a true orphan. Acceptable for a+ // ranked suggestion list - precision over completeness.+ if (inbound.has(name)) continue;+ const age = ageDays(note.absPath, opts.now);+ candidates.push(+ Object.freeze({+ kind: "orphan_research" as const,+ title: name,+ reason: `${note.relPath} has no inbound links (${age}d old) - research nobody picked up`,+ score: KIND_WEIGHT["orphan_research"]! + Math.min(age, 365) / 1000,+ sourceArtifacts: Object.freeze([note.relPath]),+ }),+ );+ }++ // 3. Aging unresolved inbox signals.+ const inbox = join(vault, "Brain", "inbox");+ if (existsSync(inbox)) {+ for (const name of readdirSync(inbox)) {+ if (!name.startsWith("sig-") || !name.endsWith(".md")) continue;+ const absPath = join(inbox, name);+ const age = ageDays(absPath, opts.now);+ if (age < agingSignalDays) continue;+ let topic = name.slice(0, -".md".length);+ try {+ const [meta] = parseFrontmatterText(readFileSync(absPath, "utf8"));+ if (typeof meta["topic"] === "string" && meta["topic"] !== "") topic = meta["topic"];+ } catch {+ // keep the filename-derived topic+ }+ candidates.push(+ Object.freeze({+ kind: "idea_direction" as const,+ title: topic,+ reason: `inbox signal '${topic}' has waited ${age}d without becoming a preference`,+ score: KIND_WEIGHT["idea_direction"]! + Math.min(age, 365) / 1000,+ sourceArtifacts: Object.freeze([`Brain/inbox/${name}`]),+ }),+ );+ }+ }++ const ranked = candidates.toSorted((a, b) => {+ if (a.score !== b.score) return b.score - a.score;+ return a.title < b.title ? -1 : a.title > b.title ? 1 : 0;+ });+ return Object.freeze(ranked.slice(0, Math.max(0, cap)));+}++/** Ranked ideas as trigger candidates (Kernel B). */+export function ideaCandidates(+ ideas: ReadonlyArray<IdeaCandidate>,+): ReadonlyArray<InsightCandidate> {+ return Object.freeze(+ ideas.map((idea) =>+ Object.freeze({+ kind: idea.kind,+ urgency: "low" as const,+ reason: idea.reason,+ suggestedAction: "Pick this up as a next direction or archive it deliberately",+ sourceArtifacts: idea.sourceArtifacts,+ contextSnippets: Object.freeze([`score: ${idea.score.toFixed(3)}`]),+ cooldownKey: `${idea.kind}:${idea.sourceArtifacts[0] ?? idea.title}`,+ }),+ ),+ );+}diff --git a/src/core/brain/link-graph/format-wikilink.ts b/src/core/brain/link-graph/format-wikilink.tsnew file mode 100644index 00000000..59315ea8--- /dev/null+++ b/src/core/brain/link-graph/format-wikilink.ts@@ -0,0 +1,173 @@+/**+ * Wikilink output format kernel (Workspace Insight Suite, t_5f31b5f1).+ *+ * Three explicit modes for the TARGET side of a wikilink when Open+ * Second Brain generates or normalizes notes:+ *+ * - `preserve` (default) - links stay exactly as typed; the+ * normalizer is the identity function.+ * - `full` - the target is rewritten to the full vault-relative key+ * path (`[[Brain/notes/alpha]]`).+ * - `short` - the target is rewritten to the shortest path suffix+ * that is unambiguous across the known pages (`[[alpha]]`, or+ * `[[deep/beta]]` when two pages share a basename).+ *+ * Pure functions: the caller supplies the known-page list (vault-+ * relative paths without the `.md` extension). Resolution is+ * conservative - a target that does not resolve to exactly ONE known+ * page (unknown or ambiguous) is left untouched and reported, never+ * guessed. Decorations (heading anchor, block anchor, alias) and code+ * blocks are preserved verbatim; media embeds are never rewritten.+ */++export type WikiLinkFormat = "preserve" | "full" | "short";++export const WIKI_LINK_FORMATS: ReadonlyArray<WikiLinkFormat> = Object.freeze([+ "preserve",+ "full",+ "short",+]);++export function isWikiLinkFormat(value: string): value is WikiLinkFormat {+ return (WIKI_LINK_FORMATS as ReadonlyArray<string>).includes(value);+}++/** Mirrors the masks used by the link-graph parser, broadened for the+ * rewrite path: backtick fences of any length (3+), tilde fences, and+ * inline code spans all stay verbatim. */+const RICH_WIKILINK_RE = /\[\[([^\]\n]+)\]\]/g;+const CODE_BLOCK_RE = /(`{3,}|~{3,})[\s\S]*?\1|`[^`]+`/g;++export interface NormalizeResult {+ readonly content: string;+ /** Number of links whose target side was rewritten. */+ readonly changed: number;+ /** Target sides that matched more than one known page (left as typed). */+ readonly ambiguous: ReadonlyArray<string>;+}++function stripMd(path: string): string {+ return path.endsWith(".md") ? path.slice(0, -".md".length) : path;+}++/**+ * The shortest trailing-segment suffix of `path` that no other known+ * page shares. `Brain/notes/alpha` with no sibling `alpha` yields+ * `alpha`; two pages ending in `beta` yield `deep/beta` /+ * `archive/beta`.+ */+export function shortestUniqueSuffix(path: string, knownPaths: ReadonlyArray<string>): string {+ const segments = path.split("/");+ const others = knownPaths.map(stripMd).filter((p) => p !== path);+ for (let take = 1; take <= segments.length; take += 1) {+ const suffix = segments.slice(segments.length - take).join("/");+ const clash = others.some((p) => p === suffix || p.endsWith("/" + suffix));+ if (!clash) return suffix;+ }+ return path;+}++/**+ * Resolve a target side to the unique known page it names: an exact+ * path match or a `/`-aligned suffix match. Returns the full page+ * path, "ambiguous", or null when nothing matches.+ */+function resolveTarget(+ targetSide: string,+ knownPaths: ReadonlyArray<string>,+): string | "ambiguous" | null {+ const target = stripMd(targetSide.trim());+ if (target === "") return null;+ const matches: string[] = [];+ for (const raw of knownPaths) {+ const page = stripMd(raw);+ if (page === target || page.endsWith("/" + target)) matches.push(page);+ }+ if (matches.length === 1) return matches[0]!;+ if (matches.length > 1) return "ambiguous";+ return null;+}++interface BodyRewrite {+ readonly body: string;+ readonly changed: boolean;+ readonly ambiguous: string | null;+}++function rewriteBody(+ body: string,+ mode: WikiLinkFormat,+ knownPaths: ReadonlyArray<string>,+): BodyRewrite {+ if (mode === "preserve") return { body, changed: false, ambiguous: null };++ // Split decorations off verbatim: pipe binds tighter than hash in+ // the Obsidian grammar, so locate the alias first.+ const pipeIdx = body.indexOf("|");+ const aliasPart = pipeIdx >= 0 ? body.slice(pipeIdx) : "";+ const beforeAlias = pipeIdx >= 0 ? body.slice(0, pipeIdx) : body;+ const hashIdx = beforeAlias.indexOf("#");+ const anchorPart = hashIdx >= 0 ? beforeAlias.slice(hashIdx) : "";+ const targetSide = hashIdx >= 0 ? beforeAlias.slice(0, hashIdx) : beforeAlias;++ const resolved = resolveTarget(targetSide, knownPaths);+ if (resolved === null) return { body, changed: false, ambiguous: null };+ if (resolved === "ambiguous") {+ return { body, changed: false, ambiguous: targetSide.trim() };+ }+ const formatted = mode === "full" ? resolved : shortestUniqueSuffix(resolved, knownPaths);+ if (formatted === targetSide.trim()) return { body, changed: false, ambiguous: null };+ return { body: `${formatted}${anchorPart}${aliasPart}`, changed: true, ambiguous: null };+}++/** Format a single bracket body (no surrounding `[[ ]]`). */+export function formatWikilinkBody(+ body: string,+ mode: WikiLinkFormat,+ knownPaths: ReadonlyArray<string>,+): string {+ return rewriteBody(body, mode, knownPaths).body;+}++/**+ * Rewrite every wikilink in a Markdown document to the requested+ * format, skipping fenced/inline code spans and media embeds+ * (`![[...]]`).+ */+export function normalizeWikilinks(+ content: string,+ mode: WikiLinkFormat,+ knownPaths: ReadonlyArray<string>,+): NormalizeResult {+ if (mode === "preserve") {+ return Object.freeze({ content, changed: 0, ambiguous: Object.freeze([]) });+ }+ let changed = 0;+ const ambiguous = new Set<string>();++ const transformSegment = (segment: string): string =>+ segment.replace(RICH_WIKILINK_RE, (match: string, body: string, offset: number) => {+ // Media embeds (`![[...]]`) are renders, not references.+ if (offset > 0 && segment[offset - 1] === "!") return match;+ const rewrite = rewriteBody(body, mode, knownPaths);+ if (rewrite.ambiguous !== null) ambiguous.add(rewrite.ambiguous);+ if (!rewrite.changed) return match;+ changed += 1;+ return `[[${rewrite.body}]]`;+ });++ let out = "";+ let last = 0;+ for (const m of content.matchAll(CODE_BLOCK_RE)) {+ out += transformSegment(content.slice(last, m.index));+ out += m[0];+ last = m.index + m[0].length;+ }+ out += transformSegment(content.slice(last));++ return Object.freeze({+ content: out,+ changed,+ ambiguous: Object.freeze([...ambiguous].toSorted()),+ });+}diff --git a/src/core/brain/portability/origins.ts b/src/core/brain/portability/origins.tsnew file mode 100644index 00000000..868f9b76--- /dev/null+++ b/src/core/brain/portability/origins.ts@@ -0,0 +1,83 @@+/**+ * Search-origin enumeration (Workspace Insight Suite, t_72a22658).+ *+ * One place answers "which vaults participate in cross-vault recall":+ * the active vault first (label `local`), then registered profile+ * vaults (`profile/<name>`), then read-only recall sources+ * (`source/<alias>`), deduped by resolved path with earlier kinds+ * winning. Labels are namespaced by kind so a profile and a source can+ * never collide, and they double as the `origin:` reason prefix on+ * search results.+ *+ * Only existing directories are enumerated: broken sources stay+ * visible through `listRecallSources` / `o2b brain source list`, but+ * they never reach the search fan-out.+ */++import { statSync } from "node:fs";+import { resolve } from "node:path";++import { listProfiles } from "./profiles.ts";+import { listRecallSources } from "./recall-sources.ts";++export type SearchOriginKind = "active" | "profile" | "source";++export interface SearchOrigin {+ /** Bare name: profile name, source alias, or "local". */+ readonly alias: string;+ /** Kind-namespaced label used in `origin:` reasons: "local", "profile/x", "source/y". */+ readonly label: string;+ readonly vault: string;+ readonly kind: SearchOriginKind;+}++function isDirectory(path: string): boolean {+ try {+ return statSync(path).isDirectory();+ } catch {+ return false;+ }+}++export function listSearchOrigins(+ configPath: string,+ activeVault: string,+): ReadonlyArray<SearchOrigin> {+ const activeResolved = resolve(activeVault);+ const seen = new Set<string>([activeResolved]);+ const origins: SearchOrigin[] = [+ Object.freeze({+ alias: "local",+ label: "local",+ vault: activeResolved,+ kind: "active" as const,+ }),+ ];+ for (const profile of listProfiles(configPath).profiles) {+ const vault = resolve(profile.vault);+ if (seen.has(vault) || !isDirectory(vault)) continue;+ seen.add(vault);+ origins.push(+ Object.freeze({+ alias: profile.name,+ label: `profile/${profile.name}`,+ vault,+ kind: "profile" as const,+ }),+ );+ }+ for (const source of listRecallSources(configPath, activeVault)) {+ const vault = resolve(source.vault);+ if (seen.has(vault) || source.broken) continue;+ seen.add(vault);+ origins.push(+ Object.freeze({+ alias: source.alias,+ label: `source/${source.alias}`,+ vault,+ kind: "source" as const,+ }),+ );+ }+ return Object.freeze(origins);+}diff --git a/src/core/brain/portability/pointer.ts b/src/core/brain/portability/pointer.tsnew file mode 100644index 00000000..6bdce59a--- /dev/null+++ b/src/core/brain/portability/pointer.ts@@ -0,0 +1,269 @@+/**+ * Project vault pointers (Workspace Insight Suite, t_1375e69f).+ *+ * A `.o2b-vault.json` pointer file links any project directory - a repo,+ * a monorepo package, a sibling worktree - to its owning vault, so every+ * command launched from that directory resolves the right Brain without+ * copying vault files or pasting prompt snippets. `resolveVault` consults+ * {@link resolvePointerVault} after the `VAULT_DIR` env override and+ * before the profile/config chain: a pointer only exists when the+ * operator created one, so resolution stays artifact-gated.+ *+ * A linked-projects registry (`projects.json` beside the config file,+ * mirroring the `profiles.json` conventions: stable key order, atomic+ * writes, tolerant reads) lets `o2b brain project list|status` inspect+ * and repair every link without scanning the filesystem.+ *+ * Standalone module (no import of config.ts) so config.ts can depend on+ * it without a cycle - same constraint as `profiles.ts`.+ */++import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";+import { dirname, join, resolve, sep } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";++export const VAULT_POINTER_FILE = ".o2b-vault.json";++export interface VaultPointer {+ readonly vault: string;+ readonly linkedAt: string | null;+}++export interface PointerProbe {+ /** Pointer file location. */+ readonly path: string;+ /** Directory that contains the pointer file. */+ readonly dir: string;+ /** Parsed pointer, or null when the file is malformed. */+ readonly pointer: VaultPointer | null;+ /** Malformation reason, or null when the pointer parsed cleanly. */+ readonly error: string | null;+}++function isDirectory(path: string): boolean {+ try {+ return statSync(path).isDirectory();+ } catch {+ return false;+ }+}++function assertNotInsideVault(projectDir: string, vault: string): void {+ const project = resolve(projectDir);+ const vaultAbs = resolve(vault);+ if (project === vaultAbs || project.startsWith(vaultAbs + sep)) {+ throw new Error(+ `project directory is inside the vault it would point at (${vaultAbs}); ` ++ "a vault never needs a pointer to itself",+ );+ }+}++/** Write (or overwrite) the pointer file linking a project to a vault. */+export function writeVaultPointer(+ projectDir: string,+ vault: string,+ opts: { now?: Date } = {},+): string {+ if (!isDirectory(projectDir)) {+ throw new Error(`project directory does not exist: ${projectDir}`);+ }+ if (!isDirectory(vault)) {+ throw new Error(`vault directory does not exist: ${vault}`);+ }+ assertNotInsideVault(projectDir, vault);+ const path = join(resolve(projectDir), VAULT_POINTER_FILE);+ const linkedAt = (opts.now ?? new Date()).toISOString();+ atomicWriteFileSync(+ path,+ JSON.stringify({ vault: resolve(vault), linked_at: linkedAt }, null, 2) + "\n",+ );+ return path;+}++function probeAt(dir: string): PointerProbe | null {+ const path = join(dir, VAULT_POINTER_FILE);+ if (!existsSync(path)) return null;+ try {+ const raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;+ const vault = raw["vault"];+ if (typeof vault !== "string" || vault.trim() === "") {+ return Object.freeze({ path, dir, pointer: null, error: "pointer has no vault field" });+ }+ const linkedAt = typeof raw["linked_at"] === "string" ? raw["linked_at"] : null;+ return Object.freeze({+ path,+ dir,+ pointer: Object.freeze({ vault, linkedAt }),+ error: null,+ });+ } catch (exc) {+ return Object.freeze({+ path,+ dir,+ pointer: null,+ error: `pointer is not valid JSON: ${(exc as Error).message}`,+ });+ }+}++/** Read the pointer file in exactly this directory (no walk-up). */+export function readVaultPointer(projectDir: string): PointerProbe | null {+ return probeAt(resolve(projectDir));+}++/** Delete the pointer file in this directory. Returns false when absent. */+export function removeVaultPointer(projectDir: string): boolean {+ const path = join(resolve(projectDir), VAULT_POINTER_FILE);+ if (!existsSync(path)) return false;+ rmSync(path);+ return true;+}++/**+ * Walk up from `startDir` to the filesystem root and return the first+ * pointer file found - malformed pointers included (with `error` set),+ * so callers like `project status` can report them. Null when no+ * pointer exists anywhere up the tree.+ */+export function findVaultPointer(startDir: string): PointerProbe | null {+ let dir = resolve(startDir);+ for (;;) {+ const probe = probeAt(dir);+ if (probe !== null) return probe;+ const parent = dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}++/**+ * Fail-soft pointer resolution for `resolveVault`: the nearest pointer's+ * vault when it parses cleanly AND the vault directory exists; null+ * otherwise. A malformed pointer or a dangling target never throws here -+ * `project status` is the surface that reports those.+ */+export function resolvePointerVault(startDir: string): string | null {+ const probe = findVaultPointer(startDir);+ if (probe === null || probe.pointer === null) return null;+ if (!isDirectory(probe.pointer.vault)) return null;+ return probe.pointer.vault;+}++// ββ Linked-projects registry ββββββββββββββββββββββββββββββββββββββββββββββββ++export interface LinkedProject {+ readonly path: string;+ readonly vault: string;+}++export type LinkedPointerState = "ok" | "missing" | "malformed" | "mismatch";++export interface LinkedProjectStatus extends LinkedProject {+ readonly pointer: LinkedPointerState;+ readonly vaultExists: boolean;+}++interface ProjectsFile {+ projects: Record<string, { vault: string }>;+}++/** Path of the linked-projects registry that accompanies a config file. */+export function projectsRegistryPath(configPath: string): string {+ return join(dirname(configPath), "projects.json");+}++function loadRegistry(+ configPath: string,+ opts: { tolerateParseError?: boolean } = {},+): ProjectsFile {+ const path = projectsRegistryPath(configPath);+ if (!existsSync(path)) return { projects: {} };+ try {+ const raw = JSON.parse(readFileSync(path, "utf8")) as Partial<ProjectsFile>;+ const projects: Record<string, { vault: string }> = {};+ if (raw.projects && typeof raw.projects === "object") {+ for (const [projectPath, entry] of Object.entries(raw.projects)) {+ if (entry && typeof entry === "object" && typeof entry.vault === "string") {+ projects[projectPath] = { vault: entry.vault };+ }+ }+ }+ return { projects };+ } catch (exc) {+ // Read-only callers tolerate a malformed registry (treat as empty);+ // mutating callers must fail fast so a save() does not clobber a+ // file we could not parse, silently dropping every other project+ // (same contract as profiles.ts).+ if (!opts.tolerateParseError) {+ throw new Error(`projects registry is malformed: ${path}`, { cause: exc });+ }+ return { projects: {} };+ }+}++function saveRegistry(configPath: string, data: ProjectsFile): void {+ const path = projectsRegistryPath(configPath);+ mkdirSync(dirname(path), { recursive: true });+ // Stable key order for byte-identical writes under Syncthing.+ const ordered: ProjectsFile = {+ projects: Object.fromEntries(+ Object.keys(data.projects)+ .toSorted()+ .map((k) => [k, data.projects[k]!]),+ ),+ };+ atomicWriteFileSync(path, JSON.stringify(ordered, null, 2) + "\n");+}++/** Record (or update) a project link in the registry. */+export function registerLinkedProject(configPath: string, projectDir: string, vault: string): void {+ const data = loadRegistry(configPath);+ data.projects[resolve(projectDir)] = { vault: resolve(vault) };+ saveRegistry(configPath, data);+}++/** Drop a project link from the registry. Returns false when absent. */+export function unregisterLinkedProject(configPath: string, projectDir: string): boolean {+ const data = loadRegistry(configPath);+ const key = resolve(projectDir);+ if (!(key in data.projects)) return false;+ delete data.projects[key];+ saveRegistry(configPath, data);+ return true;+}++/** Every registered project link, sorted by path. */+export function listLinkedProjects(configPath: string): ReadonlyArray<LinkedProject> {+ const data = loadRegistry(configPath, { tolerateParseError: true });+ return Object.freeze(+ Object.keys(data.projects)+ .toSorted()+ .map((path) => Object.freeze({ path, vault: data.projects[path]!.vault })),+ );+}++/**+ * Health of every registered link: whether the pointer file is present,+ * parseable, and agrees with the registry, and whether the vault it+ * names still exists.+ */+export function linkedProjectsStatus(configPath: string): ReadonlyArray<LinkedProjectStatus> {+ return Object.freeze(+ listLinkedProjects(configPath).map((project) => {+ const probe = readVaultPointer(project.path);+ let pointer: LinkedPointerState;+ if (probe === null) pointer = "missing";+ else if (probe.pointer === null) pointer = "malformed";+ else if (resolve(probe.pointer.vault) !== resolve(project.vault)) pointer = "mismatch";+ else pointer = "ok";+ return Object.freeze({+ path: project.path,+ vault: project.vault,+ pointer,+ vaultExists: isDirectory(project.vault),+ });+ }),+ );+}diff --git a/src/core/brain/portability/recall-sources.ts b/src/core/brain/portability/recall-sources.tsnew file mode 100644index 00000000..6c156ba8--- /dev/null+++ b/src/core/brain/portability/recall-sources.ts@@ -0,0 +1,179 @@+/**+ * Read-only recall sources (Workspace Insight Suite, t_1375e69f).+ *+ * Another vault can be attached to the active Brain as a READ-ONLY+ * recall origin: cross-vault search may read it, write tools never+ * touch it. The registry (`recall-sources.json` beside the config+ * file, mirroring the `profiles.json` conventions) is keyed by the+ * OWNING vault, so each Brain keeps its own source list and switching+ * profiles never leaks one vault's sources into another. Keeping the+ * registry out of the synced vault also keeps one machine's+ * filesystem paths off every replica.+ *+ * Standalone module (no import of config.ts), same as `profiles.ts`.+ */++import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";+import { dirname, join, resolve } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";++export interface RecallSource {+ readonly alias: string;+ readonly vault: string;+}++export interface RecallSourceStatus extends RecallSource {+ /** True when the target vault directory no longer exists. */+ readonly broken: boolean;+}++interface SourcesFile {+ sources: Record<string, Record<string, { vault: string }>>;+}++/** Path of the recall-sources registry that accompanies a config file. */+export function recallSourcesPath(configPath: string): string {+ return join(dirname(configPath), "recall-sources.json");+}++function isDirectory(path: string): boolean {+ try {+ return statSync(path).isDirectory();+ } catch {+ return false;+ }+}++function loadRegistry(+ configPath: string,+ opts: { tolerateParseError?: boolean } = {},+): SourcesFile {+ const path = recallSourcesPath(configPath);+ if (!existsSync(path)) return { sources: {} };+ try {+ const raw = JSON.parse(readFileSync(path, "utf8")) as Partial<SourcesFile>;+ const sources: SourcesFile["sources"] = {};+ if (raw.sources && typeof raw.sources === "object") {+ for (const [ownerVault, entries] of Object.entries(raw.sources)) {+ if (!entries || typeof entries !== "object") continue;+ const cleaned: Record<string, { vault: string }> = {};+ for (const [alias, entry] of Object.entries(entries)) {+ if (entry && typeof entry === "object" && typeof entry.vault === "string") {+ cleaned[alias] = { vault: entry.vault };+ }+ }+ sources[ownerVault] = cleaned;+ }+ }+ return { sources };+ } catch (exc) {+ // Read-only callers tolerate a malformed registry; mutating callers+ // must fail fast so a save() cannot truncate sources it could not+ // parse (same contract as profiles.ts).+ if (!opts.tolerateParseError) {+ throw new Error(`recall-sources registry is malformed: ${path}`, { cause: exc });+ }+ return { sources: {} };+ }+}++function saveRegistry(configPath: string, data: SourcesFile): void {+ const path = recallSourcesPath(configPath);+ mkdirSync(dirname(path), { recursive: true });+ // Stable key order at both levels for byte-identical writes.+ const ordered: SourcesFile = {+ sources: Object.fromEntries(+ Object.keys(data.sources)+ .toSorted()+ .map((ownerVault) => [+ ownerVault,+ Object.fromEntries(+ Object.keys(data.sources[ownerVault]!)+ .toSorted()+ .map((alias) => [alias, data.sources[ownerVault]![alias]!]),+ ),+ ]),+ ),+ };+ atomicWriteFileSync(path, JSON.stringify(ordered, null, 2) + "\n");+}++/**+ * Attach an external vault as a read-only recall source of `ownerVault`.+ * Validation is concentrated here: alias shape and uniqueness, target+ * existence, self-links, duplicate paths, and direct circular links+ * (the target already sources the owner).+ */+export function addRecallSource(+ configPath: string,+ ownerVault: string,+ alias: string,+ vault: string,+): void {+ const trimmedAlias = alias.trim();+ if (trimmedAlias === "") throw new Error("source alias must not be empty");+ const owner = resolve(ownerVault);+ const target = resolve(vault);+ if (!isDirectory(target)) {+ throw new Error(`source vault does not exist: ${target}`);+ }+ if (target === owner) {+ throw new Error("a vault cannot be a recall source of itself");+ }+ const data = loadRegistry(configPath);+ const ownEntries = data.sources[owner] ?? {};+ if (trimmedAlias in ownEntries) {+ throw new Error(`source alias already registered: ${trimmedAlias}`);+ }+ for (const [existingAlias, entry] of Object.entries(ownEntries)) {+ if (resolve(entry.vault) === target) {+ throw new Error(`source vault already registered under alias '${existingAlias}'`);+ }+ }+ const reverse = data.sources[target] ?? {};+ for (const entry of Object.values(reverse)) {+ if (resolve(entry.vault) === owner) {+ throw new Error(`refusing a direct circular source: ${target} already sources ${owner}`);+ }+ }+ data.sources[owner] = { ...ownEntries, [trimmedAlias]: { vault: target } };+ saveRegistry(configPath, data);+}++/** Detach a recall source by alias. Returns false when absent. */+export function removeRecallSource(configPath: string, ownerVault: string, alias: string): boolean {+ const owner = resolve(ownerVault);+ const data = loadRegistry(configPath);+ const ownEntries = data.sources[owner];+ if (!ownEntries || !(alias in ownEntries)) return false;+ delete ownEntries[alias];+ if (Object.keys(ownEntries).length === 0) delete data.sources[owner];+ saveRegistry(configPath, data);+ return true;+}++/**+ * Every recall source of `ownerVault`, sorted by alias, with a broken+ * flag for targets that no longer exist (reported, never dropped - the+ * operator decides whether to remove or restore them).+ */+export function listRecallSources(+ configPath: string,+ ownerVault: string,+): ReadonlyArray<RecallSourceStatus> {+ const owner = resolve(ownerVault);+ const data = loadRegistry(configPath, { tolerateParseError: true });+ const ownEntries = data.sources[owner] ?? {};+ return Object.freeze(+ Object.keys(ownEntries)+ .toSorted()+ .map((alias) =>+ Object.freeze({+ alias,+ vault: ownEntries[alias]!.vault,+ broken: !isDirectory(ownEntries[alias]!.vault),+ }),+ ),+ );+}diff --git a/src/core/brain/profile-doc.ts b/src/core/brain/profile-doc.tsnew file mode 100644index 00000000..62de9509--- /dev/null+++ b/src/core/brain/profile-doc.ts@@ -0,0 +1,126 @@+/**+ * Shell-native Brain profile (Workspace Insight Suite, t_323a9a83).+ *+ * `Brain/profile.md` is a materialized compact digest of the current+ * Brain - static facts (artifact counts), the highest-confidence+ * preferences, and recent activity - so simple agents, scripts, and+ * humans can `cat` one file instead of learning MCP tools. The+ * companion `.o2bfs` marker at the vault root lets shell wrappers+ * detect a Brain root safely before applying any semantic behaviour.+ *+ * Built from the morning-brief kernel plus cheap directory counts;+ * never walks the whole vault. Regeneration is age-gated by+ * {@link isProfileStale} so repeated calls stay cheap.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { buildMorningBrief } from "./morning-brief.ts";++export const PROFILE_DOC_REL = join("Brain", "profile.md");+export const O2BFS_MARKER_FILE = ".o2bfs";++export interface ProfileDoc {+ readonly text: string;+ readonly generatedAt: string;+}++export interface ProfileDocOptions {+ readonly now: Date;+ /** Max preferences listed; default 10. */+ readonly topK?: number;+}++function countMdFiles(dir: string): number {+ try {+ return readdirSync(dir).filter((name) => name.endsWith(".md")).length;+ } catch {+ return 0;+ }+}++/** Assemble the profile document. Read-only; deterministic given `now`. */+export function buildProfileDoc(vault: string, opts: ProfileDocOptions): ProfileDoc {+ const generatedAt = opts.now.toISOString();+ const brief = buildMorningBrief(vault, { now: opts.now, topK: opts.topK ?? 10 });++ const confirmed = countMdFiles(join(vault, "Brain", "preferences"));+ const signals = countMdFiles(join(vault, "Brain", "inbox"));+ const logDays = countMdFiles(join(vault, "Brain", "log"));++ const lines: string[] = [+ "---",+ `generated_at: ${generatedAt}`,+ "generator: open-second-brain profile",+ "---",+ "",+ "# Brain profile",+ "",+ "Auto-generated digest. Do not edit - regenerate with `o2b brain profile`.",+ "",+ "## Facts",+ "",+ `- confirmed preferences: ${confirmed}`,+ `- inbox signals: ${signals}`,+ `- log days on record: ${logDays}`,+ "",+ ];++ if (brief.preferences.length > 0) {+ lines.push("## Top preferences", "");+ for (const pref of brief.preferences) {+ lines.push(`- ${pref.id}: ${pref.principle}${pref.trimmed ? " β¦" : ""}`);+ }+ lines.push("");+ }+ if (brief.openQuestions.length > 0) {+ lines.push("## Open questions", "");+ for (const q of brief.openQuestions) lines.push(`- ${q.topic} (${q.domain})`);+ lines.push("");+ }+ if (brief.recentNotes.length > 0) {+ lines.push("## Recent activity", "");+ for (const note of brief.recentNotes) lines.push(`- ${note}`);+ lines.push("");+ }++ return Object.freeze({ text: lines.join("\n"), generatedAt });+}++export interface WriteProfileResult {+ readonly path: string;+ readonly markerPath: string;+ readonly generatedAt: string;+}++/** Materialize `Brain/profile.md` and the `.o2bfs` root marker. */+export function writeProfileDoc(vault: string, opts: ProfileDocOptions): WriteProfileResult {+ const doc = buildProfileDoc(vault, opts);+ const path = join(vault, PROFILE_DOC_REL);+ atomicWriteFileSync(path, doc.text);+ const markerPath = join(vault, O2BFS_MARKER_FILE);+ atomicWriteFileSync(+ markerPath,+ JSON.stringify({ vault, generated_at: doc.generatedAt }, null, 2) + "\n",+ );+ return Object.freeze({ path, markerPath, generatedAt: doc.generatedAt });+}++/**+ * True when the materialized profile is missing or older than+ * `maxAgeSeconds` relative to `now`.+ */+export function isProfileStale(vault: string, maxAgeSeconds: number, now: Date): boolean {+ const path = join(vault, PROFILE_DOC_REL);+ // A missing root marker is stale too: shell-root detection depends+ // on it, so a deleted/failed marker must force regeneration.+ if (!existsSync(path) || !existsSync(join(vault, O2BFS_MARKER_FILE))) return true;+ try {+ const mtimeMs = statSync(path).mtimeMs;+ return now.getTime() - mtimeMs > maxAgeSeconds * 1000;+ } catch {+ return true;+ }+}diff --git a/src/core/brain/triggers/adapters.ts b/src/core/brain/triggers/adapters.tsnew file mode 100644index 00000000..57918b0e--- /dev/null+++ b/src/core/brain/triggers/adapters.ts@@ -0,0 +1,78 @@+/**+ * Report-to-candidate adapters (Workspace Insight Suite, t_cd1fee79).+ *+ * Trigger generation is pull, not push: these adapters READ the+ * existing deterministic report shapes (semantic health, retention+ * review) and normalize findings into {@link InsightCandidate}s. No+ * report generator gains a write path, and every candidate is+ * grounded in artifacts the report already names.+ */++import type { SemanticHealthReport } from "../health/reconcile.ts";+import type { RetentionReviewReport } from "../retention.ts";+import type { InsightCandidate } from "./types.ts";++/** Contradictory preference pairs and stale claims from semantic health. */+export function candidatesFromHealth(+ report: SemanticHealthReport,+): ReadonlyArray<InsightCandidate> {+ const out: InsightCandidate[] = [];+ for (const finding of report.contradictions) {+ const [a, b] = [finding.aId, finding.bId].toSorted();+ out.push(+ Object.freeze({+ kind: "contradiction" as const,+ urgency: "high" as const,+ reason:+ `${finding.aId} (${finding.aSign}) contradicts ${finding.bId} (${finding.bSign})` ++ `${finding.scope !== null ? ` in scope '${finding.scope}'` : ""} ` ++ `(principle similarity ${finding.jaccard.toFixed(2)})`,+ suggestedAction: "Review the pair and retire, merge, or rescope one of the rules",+ sourceArtifacts: Object.freeze([`[[${finding.aId}]]`, `[[${finding.bId}]]`]),+ contextSnippets: Object.freeze([+ `signs: ${finding.aId}=${finding.aSign}, ${finding.bId}=${finding.bSign}`,+ ]),+ cooldownKey: `contradiction:${a}:${b}`,+ }),+ );+ }+ for (const finding of report.staleClaims) {+ out.push(+ Object.freeze({+ kind: "stale_claim" as const,+ urgency: "medium" as const,+ reason: `${finding.id} has had no fresh evidence for ${finding.ageDays} days (last: ${finding.lastEvidenceAt})`,+ suggestedAction: "Re-evidence the preference or let the dream pass retire it",+ sourceArtifacts: Object.freeze([`[[${finding.id}]]`]),+ contextSnippets: Object.freeze([`last_evidence_at: ${finding.lastEvidenceAt}`]),+ cooldownKey: `stale_claim:${finding.id}`,+ }),+ );+ }+ return Object.freeze(out);+}++/** Park/prune recommendations from the retention review. */+export function candidatesFromRetention(+ report: RetentionReviewReport,+): ReadonlyArray<InsightCandidate> {+ const out: InsightCandidate[] = [];+ for (const rec of report.recommendations) {+ if (rec.action !== "park" && rec.action !== "prune") continue;+ out.push(+ Object.freeze({+ kind: "retention_action" as const,+ urgency: rec.action === "prune" ? ("medium" as const) : ("low" as const),+ reason: `retention recommends '${rec.action}' for ${rec.id}: ${rec.reason}`,+ suggestedAction:+ rec.action === "prune"+ ? "Prune the artifact (it no longer earns its keep)"+ : "Park the artifact out of the active set",+ sourceArtifacts: Object.freeze([`[[${rec.id}]]`]),+ contextSnippets: Object.freeze([`path: ${rec.path}`]),+ cooldownKey: `retention_action:${rec.id}:${rec.action}`,+ }),+ );+ }+ return Object.freeze(out);+}diff --git a/src/core/brain/triggers/brief.ts b/src/core/brain/triggers/brief.tsnew file mode 100644index 00000000..f8f47461--- /dev/null+++ b/src/core/brain/triggers/brief.ts@@ -0,0 +1,53 @@+/**+ * Morning-brief integration (Workspace Insight Suite, t_cd1fee79).+ *+ * The brief surfaces (CLI verb + MCP tool) render this section and+ * then mark the included triggers delivered, so the same prompt is+ * shown at most once per cooldown window. The section only renders+ * when surfaceable triggers exist - vaults that never ran a trigger+ * scan keep a byte-identical brief.+ */++import { briefTriggers, markTriggersDelivered } from "./store.ts";+import type { TriggerRecord } from "./types.ts";++export const TRIGGER_BRIEF_CAP = 5;++export interface TriggerBriefSection {+ /** Rendered Markdown section, or "" when nothing surfaces. */+ readonly text: string;+ readonly triggers: ReadonlyArray<TriggerRecord>;+}++export interface TriggerBriefOptions {+ readonly now: Date;+ readonly cooldownDays: number;+ readonly cap?: number;+}++/** Render the pending-triggers section. Read-only. */+export function renderTriggerBriefSection(+ vault: string,+ opts: TriggerBriefOptions,+): TriggerBriefSection {+ const triggers = briefTriggers(vault, {+ now: opts.now,+ cap: opts.cap ?? TRIGGER_BRIEF_CAP,+ cooldownDays: opts.cooldownDays,+ });+ if (triggers.length === 0) return Object.freeze({ text: "", triggers: Object.freeze([]) });+ const lines = ["## Pending triggers", ""];+ for (const trigger of triggers) {+ lines.push(`- [${trigger.urgency}] ${trigger.reason} (${trigger.id})`);+ }+ return Object.freeze({ text: lines.join("\n"), triggers });+}++/** Stamp the surfaced triggers delivered (write step, after render). */+export function deliverBriefTriggers(vault: string, section: TriggerBriefSection, now: Date): void {+ markTriggersDelivered(+ vault,+ section.triggers.map((t) => t.id),+ { now },+ );+}diff --git a/src/core/brain/triggers/scan.ts b/src/core/brain/triggers/scan.tsnew file mode 100644index 00000000..847d511b--- /dev/null+++ b/src/core/brain/triggers/scan.ts@@ -0,0 +1,47 @@+/**+ * Trigger scan (Workspace Insight Suite, t_cd1fee79): one explicit+ * pull that runs the existing report generators, normalizes their+ * findings through the adapters, and persists deduped triggers.+ */++import { runDoctor } from "../doctor.ts";+import { buildRetentionReview } from "../retention.ts";+import { candidatesFromHealth, candidatesFromRetention } from "./adapters.ts";+import { createTriggers, type CreateTriggersOptions, type CreateTriggersResult } from "./store.ts";+import type { InsightCandidate } from "./types.ts";++export interface ScanTriggersOptions extends CreateTriggersOptions {+ /** Extra candidates from other producers (synthesis, ideas). */+ readonly extraCandidates?: ReadonlyArray<InsightCandidate>;+}++export interface ScanTriggersResult extends CreateTriggersResult {+ readonly candidates: number;+}++/**+ * Generate trigger candidates from semantic health and retention data,+ * then persist them with cooldown dedup. Fail-soft per source: a+ * report that cannot run contributes nothing rather than aborting the+ * scan.+ */+export function scanTriggers(vault: string, opts: ScanTriggersOptions): ScanTriggersResult {+ const candidates: InsightCandidate[] = [];+ try {+ const doctor = runDoctor(vault);+ if (doctor.semantic_health !== undefined) {+ candidates.push(...candidatesFromHealth(doctor.semantic_health));+ }+ } catch {+ // semantic health unavailable - skip the source+ }+ try {+ candidates.push(...candidatesFromRetention(buildRetentionReview(vault, { now: opts.now })));+ } catch {+ // retention review unavailable - skip the source+ }+ candidates.push(...(opts.extraCandidates ?? []));++ const result = createTriggers(vault, candidates, opts);+ return Object.freeze({ ...result, candidates: candidates.length });+}diff --git a/src/core/brain/triggers/store.ts b/src/core/brain/triggers/store.tsnew file mode 100644index 00000000..26e26e38--- /dev/null+++ b/src/core/brain/triggers/store.ts@@ -0,0 +1,429 @@+/**+ * Trigger store with anti-nag lifecycle (Workspace Insight Suite,+ * t_cd1fee79).+ *+ * Each trigger is one Markdown file under `Brain/triggers/` - operator+ * readable without tooling, frontmatter carries the machine state.+ * History is a status change, not a file move: terminal triggers+ * (acted / dismissed / expired) stay in place so `history` is just a+ * status filter and the cooldown logic can see them.+ *+ * Anti-nag invariants live here and only here:+ * - cooldown-key dedup across ALL statuses makes repeated scans+ * idempotent (an open twin always blocks; a terminal twin blocks+ * for `cooldownDays` after its resolution; an expired twin allows);+ * - lifecycle transitions: acknowledge / act / dismiss are allowed+ * from ANY open state (an operator may act on a trigger they found+ * via `list` before the brief ever delivered it - delivery is a+ * surfacing step, not a gate), terminal states reject everything;+ * - brief delivery happens at most once per cooldown window+ * ({@link briefTriggers} + {@link markTriggersDelivered}).+ */++import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import lockfile from "proper-lockfile";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { parseFrontmatterText } from "../../vault.ts";+import {+ isTriggerKind,+ isTriggerStatus,+ isTriggerUrgency,+ TRIGGER_URGENCIES,+ type InsightCandidate,+ type TriggerRecord,+ type TriggerStatus,+} from "./types.ts";++export const TRIGGER_TTL_DAYS = 14;+export const TRIGGER_COOLDOWN_DAYS = 7;+export const TRIGGER_MAX_PER_KIND = 10;++const DAY_MS = 24 * 3600 * 1000;+const OPEN_STATUSES: ReadonlySet<TriggerStatus> = new Set(["pending", "delivered", "acknowledged"]);++export function triggersDir(vault: string): string {+ return join(vault, "Brain", "triggers");+}++// ββ Rendering and parsing βββββββββββββββββββββββββββββββββββββββββββββββββββ++interface StoredTrigger extends Omit<TriggerRecord, "effectiveStatus"> {}++function renderTrigger(record: StoredTrigger): string {+ const lines = [+ "---",+ `trigger_id: ${record.id}`,+ `trigger_type: ${record.kind}`,+ `status: ${record.status}`,+ `urgency: ${record.urgency}`,+ // Free-text and list values are JSON-quoted so YAML-significant+ // characters can never corrupt the file (intentions/handoff pattern).+ `cooldown_key: ${JSON.stringify(record.cooldownKey)}`,+ `created_at: ${record.createdAt}`,+ `expires_at: ${record.expiresAt}`,+ ...(record.deliveredAt !== null ? [`delivered_at: ${record.deliveredAt}`] : []),+ ...(record.resolvedAt !== null ? [`resolved_at: ${record.resolvedAt}`] : []),+ `source_artifacts: ${JSON.stringify(record.sourceArtifacts)}`,+ "---",+ "",+ "## Reason",+ "",+ record.reason,+ "",+ "## Suggested action",+ "",+ record.suggestedAction,+ "",+ ];+ if (record.contextSnippets.length > 0) {+ lines.push("## Context", "");+ for (const snippet of record.contextSnippets) lines.push(`- ${snippet}`);+ lines.push("");+ }+ return lines.join("\n");+}++function sectionText(body: string, heading: string): string {+ const re = new RegExp(`^## ${heading}$`, "mu");+ const match = re.exec(body);+ if (!match) return "";+ const start = match.index + match[0].length;+ const next = /^## /mu.exec(body.slice(start + 1));+ const end = next ? start + 1 + next.index : body.length;+ return body.slice(start, end).trim();+}++function parseJsonArray(raw: unknown): ReadonlyArray<string> {+ // Defensive: a frontmatter parser that materializes the value as a+ // real array round-trips too.+ if (Array.isArray(raw) && raw.every((x) => typeof x === "string")) {+ return Object.freeze([...raw]);+ }+ if (typeof raw !== "string" || raw.trim() === "") return Object.freeze([]);+ try {+ const parsed = JSON.parse(raw) as unknown;+ if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {+ return Object.freeze(parsed);+ }+ } catch {+ // fall through - a hand-edited list degrades to empty, never throws+ }+ return Object.freeze([]);+}++function effectiveStatus(status: TriggerStatus, expiresAt: string, now: Date): TriggerStatus {+ if (!OPEN_STATUSES.has(status)) return status;+ const expiry = Date.parse(expiresAt);+ if (Number.isFinite(expiry) && now.getTime() > expiry) return "expired";+ return status;+}++function parseTrigger(vault: string, fileName: string, now: Date): TriggerRecord | null {+ const path = join(triggersDir(vault), fileName);+ let raw: string;+ try {+ raw = readFileSync(path, "utf8");+ } catch {+ return null;+ }+ const [meta, body] = parseFrontmatterText(raw);+ const id = meta["trigger_id"];+ const kind = meta["trigger_type"];+ const status = meta["status"];+ const urgency = meta["urgency"];+ if (typeof id !== "string" || id === "") return null;+ if (typeof kind !== "string" || !isTriggerKind(kind)) return null;+ if (typeof status !== "string" || !isTriggerStatus(status)) return null;+ if (typeof urgency !== "string" || !isTriggerUrgency(urgency)) return null;+ const createdAt = typeof meta["created_at"] === "string" ? meta["created_at"] : "";+ const expiresAt = typeof meta["expires_at"] === "string" ? meta["expires_at"] : "";+ return Object.freeze({+ id,+ kind,+ status,+ effectiveStatus: effectiveStatus(status, expiresAt, now),+ urgency,+ reason: sectionText(body, "Reason"),+ suggestedAction: sectionText(body, "Suggested action"),+ sourceArtifacts: parseJsonArray(meta["source_artifacts"]),+ contextSnippets: Object.freeze(+ sectionText(body, "Context")+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.startsWith("- "))+ .map((line) => line.slice(2)),+ ),+ cooldownKey: typeof meta["cooldown_key"] === "string" ? meta["cooldown_key"] : "",+ createdAt,+ expiresAt,+ deliveredAt: typeof meta["delivered_at"] === "string" ? meta["delivered_at"] : null,+ resolvedAt: typeof meta["resolved_at"] === "string" ? meta["resolved_at"] : null,+ path,+ });+}++function writeRecord(record: TriggerRecord): void {+ const { effectiveStatus: _ignored, ...stored } = record;+ atomicWriteFileSync(record.path, renderTrigger(stored));+}++// ββ Listing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export interface ListTriggersOptions {+ readonly now: Date;+ /** Filter on EFFECTIVE status (expiry applied). */+ readonly status?: TriggerStatus;+}++/** Every trigger, newest first (created_at desc, then id). */+export function listTriggers(+ vault: string,+ opts: ListTriggersOptions,+): ReadonlyArray<TriggerRecord> {+ const dir = triggersDir(vault);+ if (!existsSync(dir)) return Object.freeze([]);+ const records: TriggerRecord[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md")) continue;+ const record = parseTrigger(vault, name, opts.now);+ if (record === null) continue;+ if (opts.status !== undefined && record.effectiveStatus !== opts.status) continue;+ records.push(record);+ }+ records.sort((a, b) => {+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;+ });+ return Object.freeze(records);+}++// ββ Creation with cooldown dedup ββββββββββββββββββββββββββββββββββββββββββββ++export interface CreateTriggersOptions {+ readonly now: Date;+ /** Days a terminal (dismissed/acted) twin blocks recreation. */+ readonly cooldownDays?: number;+ /** Days until a fresh trigger expires. */+ readonly ttlDays?: number;+ /** Per-kind cap for one scan. */+ readonly maxPerKind?: number;+}++export interface SkippedCandidate {+ readonly cooldownKey: string;+ readonly reason: "active" | "cooldown" | "kind-cap" | "invalid";+}++export interface CreateTriggersResult {+ readonly created: ReadonlyArray<TriggerRecord>;+ readonly skipped: ReadonlyArray<SkippedCandidate>;+}++function blockReason(+ twin: TriggerRecord,+ now: Date,+ cooldownDays: number,+): "active" | "cooldown" | null {+ if (OPEN_STATUSES.has(twin.effectiveStatus)) return "active";+ if (twin.effectiveStatus === "expired") return null;+ // dismissed / acted: silent for the cooldown window after resolution.+ const resolved = twin.resolvedAt !== null ? Date.parse(twin.resolvedAt) : Number.NaN;+ if (!Number.isFinite(resolved)) return null;+ return now.getTime() < resolved + cooldownDays * DAY_MS ? "cooldown" : null;+}++/** Persist candidates as triggers, skipping cooldown-blocked twins. */+export function createTriggers(+ vault: string,+ candidates: ReadonlyArray<InsightCandidate>,+ opts: CreateTriggersOptions,+): CreateTriggersResult {+ // Serialize the check-then-write against concurrent scans (CLI and+ // MCP can both reach this): without the lock two callers could each+ // observe "no twin" and persist duplicates for one cooldown key.+ const dir = triggersDir(vault);+ mkdirSync(dir, { recursive: true });+ const release = lockfile.lockSync(dir, { stale: 10_000, realpath: false });+ try {+ return createTriggersLocked(vault, candidates, opts);+ } finally {+ release();+ }+}++function createTriggersLocked(+ vault: string,+ candidates: ReadonlyArray<InsightCandidate>,+ opts: CreateTriggersOptions,+): CreateTriggersResult {+ const cooldownDays = opts.cooldownDays ?? TRIGGER_COOLDOWN_DAYS;+ const ttlDays = opts.ttlDays ?? TRIGGER_TTL_DAYS;+ const maxPerKind = opts.maxPerKind ?? TRIGGER_MAX_PER_KIND;+ const existing = listTriggers(vault, { now: opts.now });+ const byKey = new Map<string, TriggerRecord>();+ for (const record of existing) {+ // Newest record per key wins (list is newest-first, keep the first).+ if (!byKey.has(record.cooldownKey)) byKey.set(record.cooldownKey, record);+ }++ const created: TriggerRecord[] = [];+ const skipped: SkippedCandidate[] = [];+ const perKind = new Map<string, number>();+ const dir = triggersDir(vault);+ const createdAt = opts.now.toISOString();+ const expiresAt = new Date(opts.now.getTime() + ttlDays * DAY_MS).toISOString();+ const usedKeys = new Set<string>();++ for (const candidate of candidates) {+ if (candidate.cooldownKey.trim() === "" || candidate.reason.trim() === "") {+ skipped.push({ cooldownKey: candidate.cooldownKey, reason: "invalid" });+ continue;+ }+ if (usedKeys.has(candidate.cooldownKey)) {+ skipped.push({ cooldownKey: candidate.cooldownKey, reason: "active" });+ continue;+ }+ const twin = byKey.get(candidate.cooldownKey);+ if (twin !== undefined) {+ const reason = blockReason(twin, opts.now, cooldownDays);+ if (reason !== null) {+ skipped.push({ cooldownKey: candidate.cooldownKey, reason });+ continue;+ }+ }+ const count = perKind.get(candidate.kind) ?? 0;+ if (count >= maxPerKind) {+ skipped.push({ cooldownKey: candidate.cooldownKey, reason: "kind-cap" });+ continue;+ }+ perKind.set(candidate.kind, count + 1);+ usedKeys.add(candidate.cooldownKey);++ const hash = createHash("sha256").update(candidate.cooldownKey).digest("hex").slice(0, 10);+ let id = `tr-${hash}-${createdAt.slice(0, 10)}`;+ let suffix = 2;+ while (existsSync(join(dir, `${id}.md`))) {+ id = `tr-${hash}-${createdAt.slice(0, 10)}-${suffix}`;+ suffix += 1;+ }+ const record: TriggerRecord = Object.freeze({+ ...candidate,+ id,+ status: "pending" as const,+ effectiveStatus: "pending" as const,+ createdAt,+ expiresAt,+ deliveredAt: null,+ resolvedAt: null,+ path: join(dir, `${id}.md`),+ });+ writeRecord(record);+ created.push(record);+ }++ return Object.freeze({ created: Object.freeze(created), skipped: Object.freeze(skipped) });+}++// ββ Transitions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export type TriggerAction = "acknowledge" | "dismiss" | "act";++export interface TransitionOptions {+ readonly now: Date;+}++const ACTION_TO_STATUS: Record<TriggerAction, TriggerStatus> = {+ acknowledge: "acknowledged",+ dismiss: "dismissed",+ act: "acted",+};++/** Apply one lifecycle transition. Throws on unknown id or terminal state. */+export function transitionTrigger(+ vault: string,+ id: string,+ action: TriggerAction,+ opts: TransitionOptions,+): TriggerRecord {+ const record = listTriggers(vault, { now: opts.now }).find((r) => r.id === id);+ if (record === undefined) throw new Error(`unknown trigger: ${id}`);+ if (!OPEN_STATUSES.has(record.effectiveStatus)) {+ throw new Error(`trigger ${id} is terminal (${record.effectiveStatus})`);+ }+ if (action === "acknowledge" && record.effectiveStatus === "acknowledged") {+ return record; // idempotent+ }+ const nowIso = opts.now.toISOString();+ const next: TriggerRecord = Object.freeze({+ ...record,+ status: ACTION_TO_STATUS[action],+ effectiveStatus: ACTION_TO_STATUS[action],+ resolvedAt: action === "acknowledge" ? record.resolvedAt : nowIso,+ });+ writeRecord(next);+ return next;+}++/** Stamp delivered_at + status=delivered on the given pending triggers. */+export function markTriggersDelivered(+ vault: string,+ ids: ReadonlyArray<string>,+ opts: TransitionOptions,+): void {+ if (ids.length === 0) return;+ const wanted = new Set(ids);+ const nowIso = opts.now.toISOString();+ for (const record of listTriggers(vault, { now: opts.now })) {+ if (!wanted.has(record.id)) continue;+ if (record.effectiveStatus !== "pending" && record.effectiveStatus !== "delivered") continue;+ writeRecord(+ Object.freeze({+ ...record,+ status: "delivered" as const,+ effectiveStatus: "delivered" as const,+ deliveredAt: nowIso,+ }),+ );+ }+}++// ββ Brief integration βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export interface BriefTriggersOptions {+ readonly now: Date;+ readonly cap: number;+ readonly cooldownDays: number;+}++const URGENCY_RANK: Record<string, number> = Object.fromEntries(+ TRIGGER_URGENCIES.map((u, i) => [u, i]),+);++/**+ * Triggers the morning brief may surface NOW: pending ones, plus+ * delivered-but-still-open ones whose last delivery is older than the+ * cooldown window. Ranked urgency desc, then newest first, capped.+ */+export function briefTriggers(+ vault: string,+ opts: BriefTriggersOptions,+): ReadonlyArray<TriggerRecord> {+ const eligible = listTriggers(vault, { now: opts.now }).filter((record) => {+ if (record.effectiveStatus === "pending") return true;+ if (record.effectiveStatus !== "delivered") return false;+ const delivered = record.deliveredAt !== null ? Date.parse(record.deliveredAt) : Number.NaN;+ if (!Number.isFinite(delivered)) return true;+ return opts.now.getTime() >= delivered + opts.cooldownDays * DAY_MS;+ });+ const ranked = eligible.toSorted((a, b) => {+ const ur = (URGENCY_RANK[b.urgency] ?? 0) - (URGENCY_RANK[a.urgency] ?? 0);+ if (ur !== 0) return ur;+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;+ });+ return Object.freeze(ranked.slice(0, Math.max(0, opts.cap)));+}diff --git a/src/core/brain/triggers/types.ts b/src/core/brain/triggers/types.tsnew file mode 100644index 00000000..4949e676--- /dev/null+++ b/src/core/brain/triggers/types.ts@@ -0,0 +1,80 @@+/**+ * Trigger queue types (Workspace Insight Suite, t_cd1fee79).+ *+ * `InsightCandidate` is the shared record every producer emits - the+ * health/retention/stale adapters, deep vault synthesis, and idea+ * discovery all normalize their findings into this one shape, and the+ * trigger store is its single consumer (Kernel B of the suite).+ */++export const TRIGGER_STATUSES = [+ "pending",+ "delivered",+ "acknowledged",+ "acted",+ "dismissed",+ "expired",+] as const;+export type TriggerStatus = (typeof TRIGGER_STATUSES)[number];++export function isTriggerStatus(value: string): value is TriggerStatus {+ return (TRIGGER_STATUSES as ReadonlyArray<string>).includes(value);+}++export const TRIGGER_URGENCIES = ["low", "medium", "high"] as const;+export type TriggerUrgency = (typeof TRIGGER_URGENCIES)[number];++export function isTriggerUrgency(value: string): value is TriggerUrgency {+ return (TRIGGER_URGENCIES as ReadonlyArray<string>).includes(value);+}++export const TRIGGER_KINDS = [+ "contradiction",+ "stale_claim",+ "concept_gap",+ "retention_action",+ "knowledge_gap",+ "open_question",+ "orphan_research",+ "idea_direction",+] as const;+export type TriggerKind = (typeof TRIGGER_KINDS)[number];++export function isTriggerKind(value: string): value is TriggerKind {+ return (TRIGGER_KINDS as ReadonlyArray<string>).includes(value);+}++/** One grounded proactive finding, ready to become a trigger. */+export interface InsightCandidate {+ readonly kind: TriggerKind;+ readonly urgency: TriggerUrgency;+ /** Why this needs attention - deterministic evidence, never prose guesses. */+ readonly reason: string;+ /** What the operator can do about it. */+ readonly suggestedAction: string;+ /** Wikilinks / paths of the artifacts the finding is grounded in. */+ readonly sourceArtifacts: ReadonlyArray<string>;+ /** Enough context to act without a separate search step. */+ readonly contextSnippets: ReadonlyArray<string>;+ /**+ * Stable dedup key: the same issue must map to the same key on every+ * scan so it cannot reappear while an earlier trigger is live or+ * cooling down. Convention: `<kind>:<primary-artifact[:secondary]>`.+ */+ readonly cooldownKey: string;+}++/** A persisted trigger - one Markdown file under `Brain/triggers/`. */+export interface TriggerRecord extends InsightCandidate {+ readonly id: string;+ /** Status as written in the file. */+ readonly status: TriggerStatus;+ /** Status with expiry applied at read time. */+ readonly effectiveStatus: TriggerStatus;+ readonly createdAt: string;+ readonly expiresAt: string;+ readonly deliveredAt: string | null;+ /** Timestamp of the terminal transition (acknowledge counts as open). */+ readonly resolvedAt: string | null;+ readonly path: string;+}diff --git a/src/core/config.ts b/src/core/config.tsindex f4e1bcce..f92b5175 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -17,6 +17,12 @@ import lockfile from "proper-lockfile";import { atomicWriteFileSync } from "./fs-atomic.ts";import { isFile } from "./fs-utils.ts";import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";+import { resolvePointerVault } from "./brain/portability/pointer.ts";+import {+ isWikiLinkFormat,+ WIKI_LINK_FORMATS,+ type WikiLinkFormat,+} from "./brain/link-graph/format-wikilink.ts";import type { ConfigDiscovery } from "./types.ts";const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"] as const;@@ -149,12 +155,22 @@ export function resolveTimezone(configPath?: string): string | null {/*** Resolve the vault directory.*- * Order: `VAULT_DIR` env β `vault` field in plugin config β `null`. Caller- * decides whether to error out or accept a positional path.+ * Order: `VAULT_DIR` env β project pointer walk-up β active profile β+ * `vault` field in plugin config β `null`. Caller decides whether to+ * error out or accept a positional path.*/-export function resolveVault(configPath?: string): string | null {+export function resolveVault(configPath?: string, opts: { cwd?: string } = {}): string | null {const env = process.env["VAULT_DIR"];if (env) return expandTilde(env);+ // Project pointer (Workspace Insight Suite, t_1375e69f): a pointer file+ // in (or above) the working directory is the most specific durable+ // artifact, so it beats the profile pointer. Pointers only exist when+ // the operator linked the directory - without one the chain is+ // byte-identical to before. The walk stops at the filesystem root and+ // reads at most one small JSON per level; malformed pointers and+ // dangling targets fail soft to the next resolution step.+ const pointerVault = resolvePointerVault(opts.cwd ?? process.cwd());+ if (pointerVault !== null) return expandTilde(pointerVault);// Multi-vault profiles (v0.22.0): an active named profile overrides the// bare `vault` key. With no profiles registry the result is unchanged.const discovery = discoverConfig(configPath);@@ -300,6 +316,56 @@ export function resolveSessionHandoff(configPath?: string): boolean {return raw === "true" || raw === "1";}+/**+ * Wikilink output format (Workspace Insight Suite, t_5f31b5f1).+ * Default `preserve` keeps every generated/normalized link exactly as+ * typed - byte-identical to pre-suite behaviour. `full` and `short`+ * select the rewrite mode for `o2b brain links normalize` and for+ * generators that adopt the kernel. An unknown value fails fast: a+ * typo must never silently rewrite links in the wrong mode.+ */+export function resolveWikiLinkFormat(configPath?: string): WikiLinkFormat {+ const env = process.env["OPEN_SECOND_BRAIN_WIKI_LINK_FORMAT"]?.trim();+ const raw = env || discoverConfig(configPath).data["wiki_link_format"]?.trim();+ if (raw === undefined || raw === "") return "preserve";+ if (!isWikiLinkFormat(raw)) {+ throw new Error(+ `wiki_link_format must be one of ${WIKI_LINK_FORMATS.join(", ")}; got '${raw}'`,+ );+ }+ return raw;+}++/**+ * Trigger cooldown window in days (Workspace Insight Suite,+ * t_cd1fee79): how long a dismissed/acted trigger blocks recreation+ * and how long a delivered trigger stays out of the morning brief.+ * Default 7. An invalid value fails fast.+ */+export function resolveTriggerCooldownDays(configPath?: string): number {+ const env = process.env["OPEN_SECOND_BRAIN_TRIGGER_COOLDOWN_DAYS"]?.trim();+ const raw = env || discoverConfig(configPath).data["trigger_cooldown_days"]?.trim();+ if (raw === undefined || raw === "") return 7;+ const days = Number(raw);+ if (!Number.isInteger(days) || days < 0) {+ throw new Error(`trigger_cooldown_days must be a non-negative integer; got '${raw}'`);+ }+ return days;+}++/**+ * Recall-gate telemetry gate (Workspace Insight Suite, t_65036e02).+ * Default OFF: brain_recall_gate stays a pure diagnostic unless+ * `recall_gate_telemetry: "true"`, when every decision lands as a+ * gate_telemetry continuity record (prompt hash only, never the+ * prompt).+ */+export function resolveRecallGateTelemetry(configPath?: string): boolean {+ const env = process.env["OPEN_SECOND_BRAIN_RECALL_GATE_TELEMETRY"]?.trim();+ const raw = env || discoverConfig(configPath).data["recall_gate_telemetry"]?.trim();+ return raw === "true" || raw === "1";+}+export const SESSION_CAPTURE_ROLES = ["user", "assistant", "system", "tool", "meta"] as const;export type SessionCaptureRole = (typeof SESSION_CAPTURE_ROLES)[number];diff --git a/src/core/search/cross-vault.ts b/src/core/search/cross-vault.tsnew file mode 100644index 00000000..77ef6ec8--- /dev/null+++ b/src/core/search/cross-vault.ts@@ -0,0 +1,126 @@+/**+ * Cross-vault union search (Workspace Insight Suite, t_72a22658).+ *+ * Fans one query out over every search origin - the active vault,+ * registered profile vaults, and read-only recall sources - and merges+ * the per-origin outcomes into one result list ordered by score.+ * Every result carries its origin label both as an additive `origin`+ * field and as an `origin:<label>` entry riding the existing+ * `reasons[]` mechanism.+ *+ * Read-only invariants concentrate here:+ * - non-active origins search with `selfHeal: false`, so a missing+ * or stale index is NEVER rebuilt inside an external vault;+ * - non-active origins search with the query cache disabled, so no+ * cache rows are written into an external index;+ * - a failing origin (no index, schema mismatch, unreadable store)+ * contributes a `[label] ...` warning, never an error.+ *+ * Scores merge as-is: every origin runs the same ranking pipeline with+ * the same options, which keeps them comparable enough for a first+ * version; the origin label makes any skew diagnosable per result.+ */++import { resolve } from "node:path";++import { listSearchOrigins } from "../brain/portability/origins.ts";+import { resolveSearchConfig } from "./index.ts";+import { search } from "./search.ts";+import { readActiveSessionFocus } from "./session-focus.ts";+import type {+ BrainSearchResult,+ ResolvedSearchConfig,+ SearchOptions,+ SearchOutcome,+} from "./types.ts";++function labelled(result: BrainSearchResult, label: string): BrainSearchResult {+ return Object.freeze({+ ...result,+ origin: label,+ reasons: Object.freeze([...result.reasons, `origin:${label}`]),+ });+}++/** Deterministic merge order: score desc, then label, path, chunk id. */+function compareMerged(a: BrainSearchResult, b: BrainSearchResult): number {+ if (a.score !== b.score) return b.score - a.score;+ const al = a.origin ?? "";+ const bl = b.origin ?? "";+ if (al !== bl) return al < bl ? -1 : 1;+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;+ return a.chunkId - b.chunkId;+}++export async function searchAcrossVaults(+ configPath: string,+ activeVault: string,+ opts: SearchOptions,+ /**+ * Caller-resolved config for the ACTIVE origin (preserves CLI+ * overrides like --db / --keyword-weight in global mode). Non-active+ * origins always resolve fresh: per-vault overrides such as a dbPath+ * would point at the wrong index there.+ */+ activeConfig?: ResolvedSearchConfig,+): Promise<SearchOutcome> {+ const origins = listSearchOrigins(configPath, activeVault);+ const limit = Math.max(1, Math.min(100, opts.limit ?? 10));+ const merged: BrainSearchResult[] = [];+ const warnings: string[] = [];+ let total = 0;++ // Session focus resolves ONCE in the active-vault context: otherwise+ // each origin would load ITS OWN persisted search-focus state and+ // filter its slice of the union differently.+ let sessionFocus = opts.sessionFocus;+ if (sessionFocus === undefined) {+ try {+ const focusConfig =+ activeConfig ?? resolveSearchConfig({ vault: resolve(activeVault), configPath });+ sessionFocus = readActiveSessionFocus(focusConfig, opts.focusSession, Date.now());+ } catch {+ sessionFocus = null;+ }+ }++ // Origins run sequentially: each opens its own SQLite store, and a+ // handful of local index reads gains nothing from interleaving.+ for (const origin of origins) {+ const isActive = origin.kind === "active";+ try {+ const base =+ isActive && activeConfig !== undefined+ ? activeConfig+ : resolveSearchConfig({ vault: origin.vault, configPath });+ // Never write cache rows into a read-only external index.+ const config = isActive+ ? base+ : Object.freeze({+ ...base,+ recall: Object.freeze({ ...base.recall, cacheEnabled: false }),+ });+ // eslint-disable-next-line no-await-in-loop -- per-origin stores, sequential by design+ const outcome = await search(config, {+ ...opts,+ sessionFocus,+ limit,+ ...(isActive ? {} : { selfHeal: false }),+ });+ merged.push(...outcome.results.map((result) => labelled(result, origin.label)));+ warnings.push(...outcome.warnings.map((warning) => `[${origin.label}] ${warning}`));+ total += outcome.total;+ } catch (exc) {+ warnings.push(`[${origin.label}] ${(exc as Error).message ?? String(exc)}`);+ }+ }++ merged.sort(compareMerged);+ return Object.freeze({+ results: Object.freeze(merged.slice(0, limit)),+ warnings: Object.freeze(warnings),+ // Sum of per-origin totals - informational, mirrors single-vault+ // semantics where `total` can exceed the capped `results` length.+ total,+ });+}diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex 1121e108..ddd9eff0 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -212,7 +212,13 @@ export async function search(// folded in once they have been derived from the store below.const basePlan = buildQueryPlan(keywordQuery, [], structured?.intent);- const store = await openReadOrSelfHeal(config);+ // Read-only origins (cross-vault search) disable self-healing: a+ // rebuild would write an index INTO the external vault. Default+ // (selfHeal absent) keeps the legacy heal-and-retry behaviour.+ const store =+ opts.selfHeal === false+ ? await Store.open(config, { mode: "read" })+ : await openReadOrSelfHeal(config);try {// Persistent query cache (v0.20.0): opt-in. Keyed by the request +// base plan hash + a config fingerprint, gated by the corpusdiff --git a/src/core/search/types.ts b/src/core/search/types.tsindex 088aa7c4..aabaed9b 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -68,6 +68,13 @@ export interface BrainSearchResult {readonly relation: string;readonly target: string;}>;+ /**+ * Kind-namespaced origin label (Workspace Insight Suite, cross-vault+ * search): "local", "profile/<name>", or "source/<alias>". Only set+ * by `searchAcrossVaults`; plain single-vault search leaves it+ * absent, keeping the legacy result shape byte-identical.+ */+ readonly origin?: string;}/**@@ -242,6 +249,14 @@ export interface SearchOptions {*/readonly since?: string;readonly until?: string;+ /**+ * Self-healing index policy (Workspace Insight Suite). Default true:+ * a missing or schema-stale index is rebuilt once and the search+ * retried. `searchAcrossVaults` passes false for non-active origins+ * so a read-only external vault is NEVER written to - its missing+ * index surfaces as a per-origin warning instead.+ */+ readonly selfHeal?: boolean;}export interface SearchOutcome {diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex added9e2..fa0840d7 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -44,6 +44,7 @@ import {resolveAgentName,resolveLinkOutputFormat,resolveSearchFocusContextPack,+ resolveTriggerCooldownDays,} from "../core/config.ts";import { resolveSearchConfig } from "../core/search/index.ts";import { readActiveSessionFocus } from "../core/search/session-focus.ts";@@ -60,6 +61,13 @@ import { EntityAmbiguityError, getEntity, listEntities } from "../core/brain/entimport { validateEntityCategory } from "../core/brain/entities/canonical.ts";import { readPrefAudit } from "../core/brain/pref-audit.ts";import { buildMorningBrief } from "../core/brain/morning-brief.ts";+import { deliverBriefTriggers, renderTriggerBriefSection } from "../core/brain/triggers/brief.ts";+import { scanTriggers } from "../core/brain/triggers/scan.ts";+import { createTriggers, listTriggers, transitionTrigger } from "../core/brain/triggers/store.ts";+import { deepSynthesis, synthesisCandidates } from "../core/brain/deep-synthesis.ts";+import { discoverIdeas, ideaCandidates } from "../core/brain/idea-discovery.ts";+import { listGateTelemetry, summarizeGateTelemetry } from "../core/brain/gate-telemetry.ts";+import { isTriggerStatus, type TriggerRecord } from "../core/brain/triggers/types.ts";import { aggregateSources } from "../core/brain/portability/sources.ts";import { switchProfile, listProfiles } from "../core/brain/portability/profiles.ts";import { defaultConfigPath } from "../core/config.ts";@@ -1055,19 +1063,48 @@ async function toolBrainMorningBrief("brain_morning_brief",);const maxTotalChars = optionalPositiveInt(args, "max_total_chars", "brain_morning_brief");+ const now = new Date();const brief = buildMorningBrief(ctx.vault, {- now: new Date(),+ now,topK,lookbackDays,...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),...(maxTotalChars !== undefined ? { maxTotalChars } : {}),});+ // Pending-trigger section (t_cd1fee79): renders only when a trigger+ // scan persisted surfaceable triggers; included triggers are marked+ // delivered so a prompt shows once per cooldown window. Fail-soft -+ // a broken queue never breaks the brief.+ let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;+ try {+ triggerSection = renderTriggerBriefSection(ctx.vault, {+ now,+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),+ });+ if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);+ } catch {+ triggerSection = null;+ }+ const text =+ triggerSection !== null && triggerSection.text !== ""+ ? `${brief.text}${brief.text.length > 0 ? "\n\n" : ""}${triggerSection.text}`+ : brief.text;return {- text: brief.text,+ text,preferences: brief.preferences,open_questions: brief.openQuestions,recent_notes: brief.recentNotes,total_chars: brief.totalChars,+ ...(triggerSection !== null && triggerSection.triggers.length > 0+ ? {+ triggers: triggerSection.triggers.map((t) => ({+ id: t.id,+ kind: t.kind,+ urgency: t.urgency,+ reason: t.reason,+ })),+ }+ : {}),};}@@ -1868,6 +1905,155 @@ function toolBrainIntention();}+// ----- brain_trigger (Workspace Insight Suite) ------------------------------++function triggerToJson(record: TriggerRecord): Record<string, unknown> {+ return {+ id: record.id,+ kind: record.kind,+ status: record.effectiveStatus,+ urgency: record.urgency,+ reason: record.reason,+ suggested_action: record.suggestedAction,+ source_artifacts: record.sourceArtifacts,+ cooldown_key: record.cooldownKey,+ created_at: record.createdAt,+ expires_at: record.expiresAt,+ delivered_at: record.deliveredAt,+ resolved_at: record.resolvedAt,+ };+}++const TRIGGER_TERMINAL = new Set(["acted", "dismissed", "expired"]);++function toolBrainTrigger(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const operation = coerceStr(args, "operation", true)!;+ const now = new Date();+ if (operation === "scan") {+ const cooldownDays = resolveTriggerCooldownDays(ctx.configPath ?? undefined);+ const result = scanTriggers(ctx.vault, { now, cooldownDays });+ return {+ operation,+ candidates: result.candidates,+ created: result.created.map(triggerToJson),+ skipped: result.skipped.map((skip) => ({+ cooldown_key: skip.cooldownKey,+ reason: skip.reason,+ })),+ };+ }+ if (operation === "list" || operation === "history") {+ const statusRaw = coerceStr(args, "status", false);+ if (statusRaw !== null && statusRaw !== undefined && !isTriggerStatus(statusRaw)) {+ throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`);+ }+ let records = listTriggers(ctx.vault, {+ now,+ ...(statusRaw ? { status: statusRaw } : {}),+ });+ if (operation === "history") {+ records = records.filter((record) => TRIGGER_TERMINAL.has(record.effectiveStatus));+ } else if (!statusRaw) {+ records = records.filter((record) => !TRIGGER_TERMINAL.has(record.effectiveStatus));+ }+ return { operation, triggers: records.map(triggerToJson) };+ }+ if (operation === "acknowledge" || operation === "dismiss" || operation === "act") {+ const id = coerceStr(args, "id", true)!;+ try {+ return {+ operation,+ trigger: triggerToJson(transitionTrigger(ctx.vault, id, operation, { now })),+ };+ } catch (err) {+ throw new MCPError(INVALID_PARAMS, `brain_trigger: ${(err as Error).message}`);+ }+ }+ throw new MCPError(+ INVALID_PARAMS,+ "brain_trigger operation must be one of: scan, list, history, acknowledge, dismiss, act",+ );+}++// ----- brain_deep_synthesis (Workspace Insight Suite) -----------------------++async function toolBrainDeepSynthesis(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const topic = coerceStr(args, "topic", true)!;+ const limit = optionalPositiveInt(args, "limit", "brain_deep_synthesis") ?? 30;+ if (limit > 100) {+ throw new MCPError(INVALID_PARAMS, "brain_deep_synthesis: limit must be at most 100");+ }+ const enqueue = coerceBool(args, "triggers");+ const now = new Date();+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ const report = await deepSynthesis(searchConfig, topic, { now, limit });+ let triggersCreated: number | undefined;+ if (enqueue) {+ const result = createTriggers(ctx.vault, synthesisCandidates(report), {+ now,+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),+ });+ triggersCreated = result.created.length;+ }+ return {+ topic: report.topic,+ generated_at: report.generatedAt,+ checked: report.checked,+ notes: report.notes,+ agreements: report.agreements,+ contradictions: report.contradictions,+ stale_claims: report.staleClaims.map((s) => ({+ path: s.path,+ age_days: s.ageDays,+ superseded_by: s.supersededBy,+ })),+ gaps: report.gaps,+ ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),+ };+}++// ----- brain_idea_discovery (Workspace Insight Suite) ------------------------++function toolBrainIdeaDiscovery(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const cap = optionalPositiveInt(args, "cap", "brain_idea_discovery") ?? 5;+ if (cap > 50) {+ throw new MCPError(INVALID_PARAMS, "brain_idea_discovery: cap must be at most 50");+ }+ const enqueue = coerceBool(args, "triggers");+ const now = new Date();+ const ideas = discoverIdeas(ctx.vault, { now, cap });+ let triggersCreated: number | undefined;+ if (enqueue) {+ const result = createTriggers(ctx.vault, ideaCandidates(ideas), {+ now,+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),+ });+ triggersCreated = result.created.length;+ }+ return {+ ideas: ideas.map((idea) => ({+ kind: idea.kind,+ title: idea.title,+ reason: idea.reason,+ score: idea.score,+ source_artifacts: idea.sourceArtifacts,+ })),+ ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),+ };+}+// ----- brain_context_pack (v0.10.15) ---------------------------------------/**@@ -2055,7 +2241,29 @@ async function toolBrainRecallTelemetry(const summary = summarizeRecallTelemetry(ctx.vault, filter);return { ...summary };}- throw new MCPError(INVALID_PARAMS, "brain_recall_telemetry: operation must be list or summary");+ // Gate-decision telemetry (Workspace Insight Suite, t_65036e02):+ // records emitted by brain_recall_gate when recall_gate_telemetry is on.+ if (operation === "gate_list") {+ const records = listGateTelemetry(ctx.vault, {+ ...(filter.host !== undefined ? { host: filter.host } : {}),+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ ...(filter.limit !== undefined ? { limit: filter.limit } : {}),+ });+ return { vault_path: ctx.vault, total: records.length, records };+ }+ if (operation === "gate_summary") {+ const summary = summarizeGateTelemetry(ctx.vault, {+ ...(filter.host !== undefined ? { host: filter.host } : {}),+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ });+ return { ...summary };+ }+ throw new MCPError(+ INVALID_PARAMS,+ "brain_recall_telemetry: operation must be list, summary, gate_list, or gate_summary",+ );}function recallTelemetryFilter(args: Record<string, unknown>): RecallTelemetryFilter {@@ -2949,6 +3157,74 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([previewBudget: MCP_PREVIEW_BUDGET,handler: toolBrainIntention,},+ {+ name: "brain_trigger",+ description:+ "Grounded proactive trigger queue under Brain/triggers/: scan generates deduped triggers from health/retention data, list/history read by lifecycle status, acknowledge/dismiss/act transition one trigger. Anti-nag: cooldown keys keep the same issue from reappearing every run.",+ inputSchema: {+ type: "object",+ properties: {+ operation: {+ type: "string",+ enum: ["scan", "list", "history", "acknowledge", "dismiss", "act"],+ description: "Operation to perform.",+ },+ id: {+ type: "string",+ minLength: 1,+ maxLength: 128,+ description: "Trigger id for acknowledge/dismiss/act.",+ },+ status: {+ type: "string",+ enum: ["pending", "delivered", "acknowledged", "acted", "dismissed", "expired"],+ description: "Effective-status filter for list.",+ },+ },+ required: ["operation"],+ additionalProperties: false,+ },+ previewBudget: MCP_PREVIEW_BUDGET,+ handler: toolBrainTrigger,+ },+ {+ name: "brain_deep_synthesis",+ description:+ "Topic-scoped deterministic dossier: matched notes, agreements (positive typed relations), contradictions, stale claims, and knowledge gaps (dangling wikilinks). Evidence assembly only - prose synthesis stays with the caller. Optional triggers=true enqueues findings.",+ inputSchema: {+ type: "object",+ properties: {+ topic: { type: "string", minLength: 1, maxLength: 500 },+ limit: { type: "integer", minimum: 1, maximum: 100 },+ triggers: {+ type: "boolean",+ description: "Enqueue contradiction/gap findings into the trigger queue.",+ },+ },+ required: ["topic"],+ additionalProperties: false,+ },+ previewBudget: MCP_PREVIEW_BUDGET,+ handler: toolBrainDeepSynthesis,+ },+ {+ name: "brain_idea_discovery",+ description:+ "Ranked next-direction candidates from the vault's open loops: unanswered open questions, orphan research notes (no inbound links), and aging unresolved inbox signals. Deterministic scoring; triggers=true enqueues the ranked ideas.",+ inputSchema: {+ type: "object",+ properties: {+ cap: { type: "integer", minimum: 1, maximum: 50 },+ triggers: {+ type: "boolean",+ description: "Enqueue the ranked ideas into the trigger queue.",+ },+ },+ additionalProperties: false,+ },+ previewBudget: MCP_PREVIEW_BUDGET,+ handler: toolBrainIdeaDiscovery,+ },{name: "brain_context",description:@@ -3396,8 +3672,9 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {operation: {type: "string",- enum: ["list", "summary"],- description: "Use list for raw records, summary for aggregate counts.",+ enum: ["list", "summary", "gate_list", "gate_summary"],+ description:+ "list/summary for recall telemetry; gate_list/gate_summary for recall-gate decisions.",},mode: {type: "string",diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex acd3c116..baf6b144 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -20,13 +20,16 @@ import {} from "../core/search/index.ts";import { normalizeSessionFocus, parseStructuredRecallQueryDocument } from "../core/search/index.ts";import type { BrainSearchResult, SearchOutcome } from "../core/search/index.ts";+import { searchAcrossVaults } from "../core/search/cross-vault.ts";import { withTimeout } from "../core/search/with-timeout.ts";+import { defaultConfigPath, resolveRecallGateTelemetry } from "../core/config.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";import type { ServerContext, ToolDefinition } from "./tools.ts";import { coerceBoolOptional, coerceStr, coerceStringOptional } from "./coerce.ts";import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";import { deriveRecallHint } from "../core/search/recall-hint.ts";import { emitRecallTelemetry } from "../core/brain/recall-telemetry.ts";+import { emitGateTelemetry } from "../core/brain/gate-telemetry.ts";const MCP_LIMIT_MAX = 50;const MCP_CONTENT_MAX = 600;@@ -66,6 +69,11 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {limit: { type: "integer", minimum: 1, maximum: MCP_LIMIT_MAX },semantic: { type: "boolean" },keyword_only: { type: "boolean" },+ global: {+ type: "boolean",+ description:+ "Cross-vault union: search profile vaults and read-only recall sources too, merging results with origin labels. Default false (active vault only).",+ },path_prefix: { type: "string", maxLength: 256 },telemetry: { type: "boolean" },telemetry_host: { type: "string", maxLength: 200 },@@ -118,6 +126,7 @@ const SEARCH_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {endLine: { type: "integer" },searchType: { type: "string" },reasons: { type: "array", items: { type: "string" } },+ origin: { type: "string" },why_retrieved: { type: "array", items: { type: "string" } },relations: {type: "array",@@ -147,6 +156,8 @@ const RECALL_GATE_INPUT_SCHEMA: Record<string, unknown> = {prompt: { type: "string", minLength: 1, maxLength: 4000 },previous_prompt: { type: "string", maxLength: 4000 },explicit: { type: "boolean" },+ telemetry_host: { type: "string", maxLength: 200 },+ session_id: { type: "string", maxLength: 512 },},required: ["prompt"],additionalProperties: false,@@ -270,6 +281,7 @@ async function toolBrainSearch(const semantic = coerceBoolOptional(args, "semantic");const keywordOnly = coerceBoolOptional(args, "keyword_only") ?? false;+ const globalSearch = coerceBoolOptional(args, "global") ?? false;const pathPrefix = coerceStringOptional(args, "path_prefix", 256);const evidencePack = coerceBoolOptional(args, "evidence_pack") ?? false;const includeSuperseded = coerceBoolOptional(args, "include_superseded") ?? false;@@ -304,24 +316,28 @@ async function toolBrainSearch(let outcome: SearchOutcome;const startedAtMs = Date.now();+ const searchOpts = {+ query,+ limit,+ semantic: semantic ?? null,+ keywordOnly,+ pathPrefix,+ ...(properties !== undefined ? { properties } : {}),+ ...(visibility !== undefined ? { visibility } : {}),+ ...(structuredQuery !== undefined ? { structuredQuery } : {}),+ ...(sessionFocus !== undefined ? { sessionFocus } : {}),+ ...(focusSession !== undefined ? { focusSession } : {}),+ ...(evidencePack ? { evidencePack: true } : {}),+ ...(includeSuperseded ? { includeSuperseded: true } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ };try {+ // Cross-vault union (t_72a22658): explicit per-call opt-in.outcome = await withTimeout(- search(config, {- query,- limit,- semantic: semantic ?? null,- keywordOnly,- pathPrefix,- ...(properties !== undefined ? { properties } : {}),- ...(visibility !== undefined ? { visibility } : {}),- ...(structuredQuery !== undefined ? { structuredQuery } : {}),- ...(sessionFocus !== undefined ? { sessionFocus } : {}),- ...(focusSession !== undefined ? { focusSession } : {}),- ...(evidencePack ? { evidencePack: true } : {}),- ...(includeSuperseded ? { includeSuperseded: true } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- }),+ globalSearch+ ? searchAcrossVaults(ctx.configPath ?? defaultConfigPath(), ctx.vault, searchOpts, config)+ : search(config, searchOpts),SEARCH_TIMEOUT_MS,searchTimeoutError,);@@ -389,6 +405,7 @@ async function toolBrainSearch(endLine: r.endLine,searchType: r.searchType,reasons: r.reasons,+ ...(r.origin !== undefined ? { origin: r.origin } : {}),...(outcome.evidencePack ? { why_retrieved: r.reasons } : {}),...(r.relations && r.relations.length > 0 ? { relations: r.relations } : {}),})),@@ -462,7 +479,7 @@ function mcpEvidencePack(}async function toolBrainRecallGate(- _ctx: ServerContext,+ ctx: ServerContext,args: Record<string, unknown>,): Promise<Record<string, unknown>> {const prompt = args["prompt"];@@ -474,13 +491,29 @@ async function toolBrainRecallGate(}const previousPrompt = coerceStringOptional(args, "previous_prompt", 4000);const explicit = coerceBoolOptional(args, "explicit") ?? false;- return {- ...evaluateSurfacingGate({- prompt,- previousPrompt: previousPrompt ?? null,- explicit,- }),- };+ const decision = evaluateSurfacingGate({+ prompt,+ previousPrompt: previousPrompt ?? null,+ explicit,+ });+ // Gate telemetry (t_65036e02): default off; fail-soft so a broken+ // continuity store never breaks the gate's pure-diagnostic contract.+ if (resolveRecallGateTelemetry(ctx.configPath ?? undefined)) {+ try {+ const host = coerceStringOptional(args, "telemetry_host", 200) ?? "mcp";+ const sessionId = coerceStringOptional(args, "session_id", 512);+ emitGateTelemetry(ctx.vault, {+ host,+ prompt,+ retrieve: decision.retrieve,+ reason: decision.reason,+ ...(sessionId !== undefined ? { sessionId } : {}),+ });+ } catch {+ // never let telemetry break the gate+ }+ }+ return { ...decision };}const RECALL_FEEDBACK_INPUT_SCHEMA: Record<string, unknown> = {diff --git a/tests/cli/links-verb.test.ts b/tests/cli/links-verb.test.tsnew file mode 100644index 00000000..51605354--- /dev/null+++ b/tests/cli/links-verb.test.ts@@ -0,0 +1,82 @@+/**+ * `o2b brain links normalize` (Workspace Insight Suite, t_5f31b5f1):+ * CLI surface over the wikilink format kernel.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-links-cli-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "notes", "deep"), { recursive: true });+ writeFileSync(join(vault, "Brain", "notes", "alpha.md"), "# Alpha\n");+ writeFileSync(join(vault, "Brain", "notes", "deep", "beta.md"), "# Beta deep\n");+ writeFileSync(join(vault, "Brain", "beta.md"), "# Beta top\n");+ writeFileSync(+ join(vault, "Brain", "notes", "index.md"),+ "Links: [[alpha]], [[beta]], [[Brain/notes/deep/beta]].\n",+ );+ config = join(tmp, "config.yaml");+ writeFileSync(config, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: config });++test("dry-run reports rewrites and ambiguities without touching files", async () => {+ const before = readFileSync(join(vault, "Brain", "notes", "index.md"), "utf8");+ const r = await runCli(["brain", "links", "normalize", "--mode", "full", "--json"], {+ env: env(),+ });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout) as {+ applied: boolean;+ total_changed: number;+ files: Array<{ path: string; ambiguous: string[] }>;+ };+ expect(parsed.applied).toBe(false);+ expect(parsed.total_changed).toBe(1); // [[alpha]] -> full; [[beta]] ambiguous; deep/beta already full+ expect(parsed.files[0]!.ambiguous).toEqual(["beta"]);+ expect(readFileSync(join(vault, "Brain", "notes", "index.md"), "utf8")).toBe(before);+});++test("--write applies the full-path rewrite", async () => {+ const r = await runCli(["brain", "links", "normalize", "--mode", "full", "--write"], {+ env: env(),+ });+ expect(r.returncode).toBe(0);+ const after = readFileSync(join(vault, "Brain", "notes", "index.md"), "utf8");+ expect(after).toContain("[[Brain/notes/alpha]]");+ expect(after).toContain("[[beta]]"); // ambiguous, untouched+});++test("config key supplies the default mode; unknown --mode fails", async () => {+ writeFileSync(config, `vault: "${vault}"\nwiki_link_format: "short"\n`);+ const r = await runCli(["brain", "links", "normalize", "--write", "--json"], { env: env() });+ expect(r.returncode).toBe(0);+ const after = readFileSync(join(vault, "Brain", "notes", "index.md"), "utf8");+ expect(after).toContain("[[deep/beta]]");++ const bad = await runCli(["brain", "links", "normalize", "--mode", "fancy"], { env: env() });+ expect(bad.returncode).not.toBe(0);+});++test("preserve mode (default) changes nothing", async () => {+ const r = await runCli(["brain", "links", "normalize", "--write", "--json"], { env: env() });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout) as { mode: string; total_changed: number };+ expect(parsed.mode).toBe("preserve");+ expect(parsed.total_changed).toBe(0);+});diff --git a/tests/cli/project-verb.test.ts b/tests/cli/project-verb.test.tsnew file mode 100644index 00000000..18b13852--- /dev/null+++ b/tests/cli/project-verb.test.ts@@ -0,0 +1,99 @@+/**+ * `o2b brain project <link|list|remove|status>` (Workspace Insight+ * Suite, t_1375e69f): CLI surface over project vault pointers.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { VAULT_POINTER_FILE } from "../../src/core/brain/portability/pointer.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let project: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-project-cli-"));+ vault = join(tmp, "vault");+ project = join(tmp, "project");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ mkdirSync(project, { recursive: true });+ config = join(tmp, "config.yaml");+ writeFileSync(config, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: config });++test("link writes the pointer and registers the project", async () => {+ const r = await runCli(["brain", "project", "link", project, "--json"], { env: env() });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout) as Record<string, unknown>;+ expect(parsed["vault"]).toBe(vault);+ expect(existsSync(join(project, VAULT_POINTER_FILE))).toBe(true);++ const list = await runCli(["brain", "project", "list", "--json"], { env: env() });+ const listed = JSON.parse(list.stdout) as { projects: Array<{ path: string; vault: string }> };+ expect(listed.projects).toHaveLength(1);+ expect(listed.projects[0]!.path).toBe(project);+});++test("a command launched from the linked directory resolves the owning vault", async () => {+ const otherVault = join(tmp, "other-vault");+ mkdirSync(join(otherVault, "Brain"), { recursive: true });+ const link = await runCli(["brain", "project", "link", project, "--vault", otherVault], {+ env: env(),+ });+ expect(link.returncode).toBe(0);++ const nested = join(project, "packages", "api");+ mkdirSync(nested, { recursive: true });+ const status = await runCli(["brain", "project", "status", "--json"], {+ env: env(),+ cwd: nested,+ });+ expect(status.returncode).toBe(0);+ const parsed = JSON.parse(status.stdout) as Record<string, unknown>;+ expect(parsed["resolved_vault"]).toBe(otherVault);+ expect(parsed["resolution"]).toBe("pointer");+});++test("status reports malformed pointers and registry health", async () => {+ await runCli(["brain", "project", "link", project], { env: env() });+ writeFileSync(join(project, VAULT_POINTER_FILE), "{broken");+ const status = await runCli(["brain", "project", "status", project, "--json"], { env: env() });+ expect(status.returncode).toBe(0);+ const parsed = JSON.parse(status.stdout) as {+ pointer: { error: string | null } | null;+ projects: Array<{ pointer: string }>;+ };+ expect(parsed.pointer?.error).not.toBeNull();+ expect(parsed.projects[0]!.pointer).toBe("malformed");+});++test("link refuses a directory inside the vault", async () => {+ const inside = join(vault, "Brain", "area");+ mkdirSync(inside, { recursive: true });+ const r = await runCli(["brain", "project", "link", inside], { env: env() });+ expect(r.returncode).not.toBe(0);+ expect(r.stderr).toContain("inside");+});++test("remove deletes the pointer and the registry entry", async () => {+ await runCli(["brain", "project", "link", project], { env: env() });+ const r = await runCli(["brain", "project", "remove", project, "--json"], { env: env() });+ expect(r.returncode).toBe(0);+ expect(existsSync(join(project, VAULT_POINTER_FILE))).toBe(false);+ const list = await runCli(["brain", "project", "list", "--json"], { env: env() });+ expect((JSON.parse(list.stdout) as { projects: unknown[] }).projects).toHaveLength(0);++ const again = await runCli(["brain", "project", "remove", project], { env: env() });+ expect(again.returncode).not.toBe(0);+});diff --git a/tests/cli/sgrep-verb.test.ts b/tests/cli/sgrep-verb.test.tsnew file mode 100644index 00000000..9631923c--- /dev/null+++ b/tests/cli/sgrep-verb.test.ts@@ -0,0 +1,69 @@+/**+ * `o2b brain sgrep` + `o2b brain profile` (Workspace Insight Suite,+ * t_323a9a83): shell-native surface CLI tests.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { O2BFS_MARKER_FILE, PROFILE_DOC_REL } from "../../src/core/brain/profile-doc.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-sgrep-cli-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ mkdirSync(join(vault, "Projects"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "notes", "creatures.md"),+ "# Creatures\n\nThe basilisk hibernates in winter.\n",+ );+ writeFileSync(join(vault, "Projects", "plan.md"), "# Plan\n\nThe basilisk project ships soon.\n");+ config = join(tmp, "config.yaml");+ writeFileSync(config, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: config });++test("sgrep prints grep-shaped path:line: matches", async () => {+ const r = await runCli(["brain", "sgrep", "basilisk"], { env: env() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toMatch(/Brain\/notes\/creatures\.md:\d+: /);+});++test("sgrep scopes by path prefix and supports --json", async () => {+ const r = await runCli(["brain", "sgrep", "basilisk", "Projects/", "--json"], { env: env() });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout) as { results: Array<{ path: string }> };+ expect(parsed.results.length).toBeGreaterThan(0);+ expect(parsed.results.every((x) => x.path.startsWith("Projects/"))).toBe(true);+});++test("sgrep with no matches exits 1, grep-style", async () => {+ const r = await runCli(["brain", "sgrep", "zzznothing"], { env: env() });+ expect(r.returncode).toBe(1);+});++test("profile writes Brain/profile.md and the .o2bfs marker, then stays fresh", async () => {+ const first = await runCli(["brain", "profile", "--json"], { env: env() });+ expect(first.returncode).toBe(0);+ expect((JSON.parse(first.stdout) as Record<string, unknown>)["refreshed"]).toBe(true);+ expect(existsSync(join(vault, PROFILE_DOC_REL))).toBe(true);+ expect(existsSync(join(vault, O2BFS_MARKER_FILE))).toBe(true);++ const second = await runCli(["brain", "profile", "--json"], { env: env() });+ expect((JSON.parse(second.stdout) as Record<string, unknown>)["refreshed"]).toBe(false);++ const forced = await runCli(["brain", "profile", "--force", "--json"], { env: env() });+ expect((JSON.parse(forced.stdout) as Record<string, unknown>)["refreshed"]).toBe(true);+});diff --git a/tests/cli/source-verb.test.ts b/tests/cli/source-verb.test.tsnew file mode 100644index 00000000..e6f03064--- /dev/null+++ b/tests/cli/source-verb.test.ts@@ -0,0 +1,75 @@+/**+ * `o2b brain source <add|list|remove>` (Workspace Insight Suite,+ * t_1375e69f): CLI surface over read-only recall sources.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let external: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-source-cli-"));+ vault = join(tmp, "vault");+ external = join(tmp, "external");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ mkdirSync(join(external, "Brain"), { recursive: true });+ config = join(tmp, "config.yaml");+ writeFileSync(config, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: config });++test("add registers a read-only source and list shows it", async () => {+ const add = await runCli(["brain", "source", "add", external, "--alias", "team", "--json"], {+ env: env(),+ });+ expect(add.returncode).toBe(0);+ expect((JSON.parse(add.stdout) as Record<string, unknown>)["read_only"]).toBe(true);++ const list = await runCli(["brain", "source", "list", "--json"], { env: env() });+ const parsed = JSON.parse(list.stdout) as {+ sources: Array<{ alias: string; vault: string; broken: boolean }>;+ };+ expect(parsed.sources).toHaveLength(1);+ expect(parsed.sources[0]!.alias).toBe("team");+ expect(parsed.sources[0]!.broken).toBe(false);+});++test("add without --alias fails; self-source is refused", async () => {+ const noAlias = await runCli(["brain", "source", "add", external], { env: env() });+ expect(noAlias.returncode).not.toBe(0);++ const self = await runCli(["brain", "source", "add", vault, "--alias", "self"], { env: env() });+ expect(self.returncode).not.toBe(0);+ expect(self.stderr).toContain("itself");+});++test("a broken source is flagged in list output", async () => {+ await runCli(["brain", "source", "add", external, "--alias", "team"], { env: env() });+ rmSync(external, { recursive: true, force: true });+ const list = await runCli(["brain", "source", "list"], { env: env() });+ expect(list.stdout).toContain("BROKEN");+});++test("remove drops the source; removing an unknown alias fails", async () => {+ await runCli(["brain", "source", "add", external, "--alias", "team"], { env: env() });+ const rm = await runCli(["brain", "source", "remove", "team", "--json"], { env: env() });+ expect(rm.returncode).toBe(0);+ const list = await runCli(["brain", "source", "list", "--json"], { env: env() });+ expect((JSON.parse(list.stdout) as { sources: unknown[] }).sources).toHaveLength(0);++ const again = await runCli(["brain", "source", "remove", "team"], { env: env() });+ expect(again.returncode).not.toBe(0);+});diff --git a/tests/core/brain/deep-synthesis.test.ts b/tests/core/brain/deep-synthesis.test.tsnew file mode 100644index 00000000..b15cf890--- /dev/null+++ b/tests/core/brain/deep-synthesis.test.ts@@ -0,0 +1,111 @@+/**+ * Deep vault synthesis (Workspace Insight Suite, t_04e94382): a+ * deterministic topic dossier - matched notes, agreements (positive+ * typed relations), contradictions, stale claims, knowledge gaps+ * (dangling wikilink targets) - assembled as evidence for an external+ * synthesizer, convertible into trigger candidates.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { utimesSync } from "node:fs";++import { deepSynthesis, synthesisCandidates } from "../../../src/core/brain/deep-synthesis.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;+const NOW = new Date("2026-06-03T10:00:00Z");++beforeEach(async () => {+ ({ vault, dbPath, cleanup } = createTempVault("deep-synthesis"));+ writeMd(+ vault,+ "Brain/notes/claim.md",+ [+ "---",+ "title: Claim",+ "contradicts: [[counter]]",+ "---",+ "# Claim",+ "",+ "Manticores hunt at dawn. See [[missing-study]] for details.",+ ].join("\n"),+ );+ writeMd(+ vault,+ "Brain/notes/counter.md",+ "---\ntitle: Counter\n---\n# Counter\n\nManticores hunt strictly at night.",+ );+ writeMd(+ vault,+ "Brain/notes/support.md",+ [+ "---",+ "title: Support",+ "related: [[claim]]",+ "---",+ "# Support",+ "",+ "Field observations of manticores corroborate the dawn pattern.",+ ].join("\n"),+ );+ const old = writeMd(+ vault,+ "Brain/notes/ancient.md",+ "# Ancient\n\nA very old taxonomy entry about manticores.",+ );+ const past = new Date("2025-01-01T00:00:00Z");+ utimesSync(old, past, past);+ await indexVault(makeConfig({ vault, dbPath }));+});++afterEach(() => {+ cleanup();+});++test("the dossier reports notes, agreements, contradictions, stale claims, and gaps", async () => {+ const report = await deepSynthesis(makeConfig({ vault, dbPath }), "manticores", { now: NOW });+ expect(report.topic).toBe("manticores");+ expect(report.checked).toEqual([+ "matched_notes",+ "agreements",+ "contradictions",+ "stale_claims",+ "knowledge_gaps",+ ]);+ expect(report.notes.length).toBeGreaterThanOrEqual(3);++ expect(report.contradictions).toHaveLength(1);+ expect(report.contradictions[0]!.path).toBe("Brain/notes/claim.md");+ expect(report.contradictions[0]!.target).toBe("counter");++ expect(report.agreements.some((a) => a.path === "Brain/notes/support.md")).toBe(true);++ expect(report.staleClaims.some((s) => s.path === "Brain/notes/ancient.md")).toBe(true);++ expect(report.gaps).toHaveLength(1);+ expect(report.gaps[0]!.target).toBe("missing-study");+ expect(report.gaps[0]!.sources).toContain("Brain/notes/claim.md");+});++test("an empty topic yields an empty but interpretable dossier", async () => {+ const report = await deepSynthesis(makeConfig({ vault, dbPath }), "zeppelins", { now: NOW });+ expect(report.notes).toHaveLength(0);+ expect(report.contradictions).toHaveLength(0);+ expect(report.gaps).toHaveLength(0);+ expect(report.checked).toHaveLength(5);+});++test("contradiction and gap findings convert to trigger candidates", async () => {+ const report = await deepSynthesis(makeConfig({ vault, dbPath }), "manticores", { now: NOW });+ const candidates = synthesisCandidates(report);+ const keys = candidates.map((c) => c.cooldownKey);+ expect(keys).toContain("contradiction:Brain/notes/claim.md:counter");+ expect(keys).toContain("knowledge_gap:missing-study");+ for (const c of candidates) {+ expect(c.sourceArtifacts.length).toBeGreaterThan(0);+ expect(c.reason.length).toBeGreaterThan(0);+ }+});diff --git a/tests/core/brain/format-wikilink.test.ts b/tests/core/brain/format-wikilink.test.tsnew file mode 100644index 00000000..8665dbdf--- /dev/null+++ b/tests/core/brain/format-wikilink.test.ts@@ -0,0 +1,127 @@+/**+ * Wikilink output format kernel (Workspace Insight Suite, t_5f31b5f1):+ * pure functions that rewrite wikilink targets to a configured path+ * format - preserve (byte-identical), full (vault-relative key path),+ * short (shortest unambiguous suffix). Decorations (anchor, block,+ * alias) and code blocks are never touched; ambiguous and unresolved+ * targets stay as typed.+ */++import { expect, test } from "bun:test";++import {+ formatWikilinkBody,+ normalizeWikilinks,+ shortestUniqueSuffix,+} from "../../../src/core/brain/link-graph/format-wikilink.ts";++const PAGES = [+ "Brain/notes/alpha",+ "Brain/notes/deep/beta",+ "Brain/archive/beta",+ "Projects/gamma",+] as const;++// ββ shortestUniqueSuffix ββββββββββββββββββββββββββββββββββββββββββββββββββββ++test("shortestUniqueSuffix returns the basename when unique", () => {+ expect(shortestUniqueSuffix("Brain/notes/alpha", PAGES)).toBe("alpha");+});++test("shortestUniqueSuffix grows until the suffix is unambiguous", () => {+ expect(shortestUniqueSuffix("Brain/notes/deep/beta", PAGES)).toBe("deep/beta");+ expect(shortestUniqueSuffix("Brain/archive/beta", PAGES)).toBe("archive/beta");+});++// ββ formatWikilinkBody ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++test("full mode rewrites a unique basename to its full key path", () => {+ expect(formatWikilinkBody("alpha", "full", PAGES)).toBe("Brain/notes/alpha");+ expect(formatWikilinkBody("gamma", "full", PAGES)).toBe("Projects/gamma");+});++test("full mode keeps decorations verbatim", () => {+ expect(formatWikilinkBody("alpha#Heading|shown", "full", PAGES)).toBe(+ "Brain/notes/alpha#Heading|shown",+ );+ expect(formatWikilinkBody("alpha#^blk", "full", PAGES)).toBe("Brain/notes/alpha#^blk");+});++test("short mode rewrites a full path to the shortest unambiguous suffix", () => {+ expect(formatWikilinkBody("Brain/notes/alpha", "short", PAGES)).toBe("alpha");+ expect(formatWikilinkBody("Brain/notes/deep/beta", "short", PAGES)).toBe("deep/beta");+});++test("an ambiguous bare target is left untouched in both modes", () => {+ expect(formatWikilinkBody("beta", "full", PAGES)).toBe("beta");+ expect(formatWikilinkBody("beta", "short", PAGES)).toBe("beta");+});++test("an unknown target is left untouched", () => {+ expect(formatWikilinkBody("ghost", "full", PAGES)).toBe("ghost");+});++test("a partial-path suffix resolves when unique", () => {+ expect(formatWikilinkBody("notes/deep/beta", "full", PAGES)).toBe("Brain/notes/deep/beta");+});++test("preserve mode is the identity", () => {+ expect(formatWikilinkBody("alpha", "preserve", PAGES)).toBe("alpha");+});++// ββ normalizeWikilinks ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++test("normalizeWikilinks rewrites links outside code blocks only", () => {+ const content = [+ "See [[alpha]] and [[beta]].",+ "```",+ "[[alpha]] inside a fence stays",+ "```",+ "Inline `[[alpha]]` stays too; [[gamma|G]] changes.",+ ].join("\n");+ const result = normalizeWikilinks(content, "full", PAGES);+ expect(result.content).toContain("[[Brain/notes/alpha]] and [[beta]].");+ expect(result.content).toContain("[[alpha]] inside a fence stays");+ expect(result.content).toContain("`[[alpha]]` stays too");+ expect(result.content).toContain("[[Projects/gamma|G]]");+ expect(result.changed).toBe(2);+ expect(result.ambiguous).toEqual(["beta"]);+});++test("normalizeWikilinks in preserve mode returns byte-identical content", () => {+ const content = "A [[alpha]] link and a [[Brain/archive/beta]] link.";+ const result = normalizeWikilinks(content, "preserve", PAGES);+ expect(result.content).toBe(content);+ expect(result.changed).toBe(0);+});++test("tilde and long-backtick fences are preserved too", () => {+ const content = [+ "Outside [[alpha]].",+ "~~~",+ "[[alpha]] in a tilde fence stays",+ "~~~",+ "````",+ "[[alpha]] in a four-backtick fence stays",+ "````",+ ].join("\n");+ const result = normalizeWikilinks(content, "full", PAGES);+ expect(result.content).toContain("Outside [[Brain/notes/alpha]].");+ expect(result.content).toContain("[[alpha]] in a tilde fence stays");+ expect(result.content).toContain("[[alpha]] in a four-backtick fence stays");+ expect(result.changed).toBe(1);+});++test("media embeds are never rewritten", () => {+ const content = "![[diagram.png]] and [[alpha]]";+ const result = normalizeWikilinks(content, "full", PAGES);+ expect(result.content).toContain("![[diagram.png]]");+ expect(result.content).toContain("[[Brain/notes/alpha]]");+});++test("an already-canonical link is not counted as a change", () => {+ const content = "[[Brain/notes/alpha]]";+ const result = normalizeWikilinks(content, "full", PAGES);+ expect(result.content).toBe(content);+ expect(result.changed).toBe(0);+});diff --git a/tests/core/brain/gate-telemetry.test.ts b/tests/core/brain/gate-telemetry.test.tsnew file mode 100644index 00000000..b5693cd5--- /dev/null+++ b/tests/core/brain/gate-telemetry.test.ts@@ -0,0 +1,74 @@+/**+ * Recall-gate telemetry kernel (Workspace Insight Suite, t_65036e02).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ emitGateTelemetry,+ hashPrompt,+ listGateTelemetry,+ summarizeGateTelemetry,+} from "../../../src/core/brain/gate-telemetry.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-gate-telemetry-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("emit stores decision, reason, and prompt hash - never the raw prompt", () => {+ const record = emitGateTelemetry(vault, {+ host: "hermes",+ prompt: "secret operational detail",+ retrieve: false,+ reason: "no_recall_intent",+ });+ expect(record.payload["decision"]).toBe("skip");+ expect(record.payload["reason"]).toBe("no_recall_intent");+ expect(record.payload["prompt_hash"]).toBe(hashPrompt("secret operational detail"));+ expect(record.payload["prompt_chars"]).toBe("secret operational detail".length);+ expect(JSON.stringify(record.payload)).not.toContain("secret operational detail");+});++test("summary aggregates by decision and reason", () => {+ emitGateTelemetry(vault, { host: "a", prompt: "p1", retrieve: true, reason: "explicit" });+ emitGateTelemetry(vault, { host: "a", prompt: "p2", retrieve: false, reason: "greeting" });+ emitGateTelemetry(vault, { host: "b", prompt: "p3", retrieve: false, reason: "greeting" });+ const summary = summarizeGateTelemetry(vault);+ expect(summary.total).toBe(3);+ expect(summary.retrieved).toBe(1);+ expect(summary.skipped).toBe(2);+ expect(summary.by_reason["greeting"]).toBe(2);++ const hostOnly = summarizeGateTelemetry(vault, { host: "a" });+ expect(hostOnly.total).toBe(2);+});++test("list is newest-first and respects limit", () => {+ emitGateTelemetry(vault, {+ host: "a",+ prompt: "first",+ retrieve: true,+ reason: "explicit",+ createdAt: "2026-06-01T00:00:00Z",+ });+ emitGateTelemetry(vault, {+ host: "a",+ prompt: "second",+ retrieve: true,+ reason: "explicit",+ createdAt: "2026-06-02T00:00:00Z",+ });+ const listed = listGateTelemetry(vault, { limit: 1 });+ expect(listed).toHaveLength(1);+ expect(listed[0]!.payload["prompt_hash"]).toBe(hashPrompt("second"));+});diff --git a/tests/core/brain/idea-discovery.test.ts b/tests/core/brain/idea-discovery.test.tsnew file mode 100644index 00000000..2e9e8196--- /dev/null+++ b/tests/core/brain/idea-discovery.test.ts@@ -0,0 +1,76 @@+/**+ * Idea discovery (Workspace Insight Suite, t_8722a62a): ranked+ * next-direction candidates from open questions, orphan notes, and+ * aging inbox signals.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { discoverIdeas, ideaCandidates } from "../../../src/core/brain/idea-discovery.ts";+import { createTriggers } from "../../../src/core/brain/triggers/store.ts";++let vault: string;+const NOW = new Date("2026-06-03T10:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-ideas-"));+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ // hub links to linked-note; orphan-note has no inbound reference.+ writeFileSync(join(vault, "Brain", "notes", "hub.md"), "# Hub\n\nSee [[linked-note]].\n");+ writeFileSync(join(vault, "Brain", "notes", "linked-note.md"), "# Linked\n");+ const orphan = join(vault, "Brain", "notes", "orphan-note.md");+ writeFileSync(orphan, "# Orphan\n\nUnpicked research.\n");+ const past = new Date(NOW.getTime() - 30 * 24 * 3600 * 1000);+ utimesSync(orphan, past, past);+ // One aging signal, one fresh signal.+ const oldSig = join(vault, "Brain", "inbox", "sig-2026-05-01-old-idea.md");+ writeFileSync(oldSig, "---\ntopic: old-idea\n---\n");+ utimesSync(oldSig, past, past);+ writeFileSync(+ join(vault, "Brain", "inbox", "sig-2026-06-02-fresh.md"),+ "---\ntopic: fresh\n---\n",+ );+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("ranks open questions above orphans above aging signals", () => {+ const ideas = discoverIdeas(vault, {+ now: NOW,+ openQuestions: [{ topic: "unify-naming", domain: "coding" }],+ });+ expect(ideas.map((i) => i.kind)).toEqual([+ "open_question",+ "orphan_research",+ "orphan_research",+ "idea_direction",+ ]);+ expect(ideas[0]!.title).toBe("unify-naming");+ expect(ideas.some((i) => i.title === "orphan-note")).toBe(true);+ expect(ideas.some((i) => i.title === "old-idea")).toBe(true);+ // The fresh signal and the linked note never surface.+ expect(ideas.some((i) => i.title === "fresh")).toBe(false);+ expect(ideas.some((i) => i.title === "linked-note")).toBe(false);+});++test("cap bounds the ranked list", () => {+ const ideas = discoverIdeas(vault, { now: NOW, cap: 2, openQuestions: [] });+ expect(ideas).toHaveLength(2);+});++test("ideaCandidates convert into enqueueable trigger candidates", () => {+ const ideas = discoverIdeas(vault, { now: NOW, cap: 3, openQuestions: [] });+ const candidates = ideaCandidates(ideas);+ expect(candidates.length).toBe(3);+ const result = createTriggers(vault, candidates, { now: NOW });+ expect(result.created.length).toBe(3);+ // Re-enqueue is blocked by the cooldown keys.+ const again = createTriggers(vault, candidates, { now: NOW });+ expect(again.created).toHaveLength(0);+});diff --git a/tests/core/brain/pointer.test.ts b/tests/core/brain/pointer.test.tsnew file mode 100644index 00000000..d14bb245--- /dev/null+++ b/tests/core/brain/pointer.test.ts@@ -0,0 +1,189 @@+/**+ * Project vault pointers (Workspace Insight Suite, t_1375e69f): a JSON+ * pointer file links any project directory to its owning vault, with a+ * walk-up discovery used by `resolveVault` and a linked-projects+ * registry beside the config file.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ VAULT_POINTER_FILE,+ findVaultPointer,+ linkedProjectsStatus,+ listLinkedProjects,+ projectsRegistryPath,+ readVaultPointer,+ registerLinkedProject,+ removeVaultPointer,+ resolvePointerVault,+ unregisterLinkedProject,+ writeVaultPointer,+} from "../../../src/core/brain/portability/pointer.ts";+import { resolveVault } from "../../../src/core/config.ts";++let tmp: string;+let vault: string;+let project: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pointer-"));+ vault = join(tmp, "vault");+ project = join(tmp, "project");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ mkdirSync(project, { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++// ββ pointer file round-trip βββββββββββββββββββββββββββββββββββββββββββββββββ++test("writeVaultPointer creates the pointer file and readVaultPointer round-trips", () => {+ const path = writeVaultPointer(project, vault);+ expect(path).toBe(join(project, VAULT_POINTER_FILE));+ const probe = readVaultPointer(project);+ expect(probe).not.toBeNull();+ expect(probe!.pointer!.vault).toBe(vault);+ expect(probe!.error).toBeNull();+ // On-disk shape is snake_case with a linked_at stamp.+ const raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, string>;+ expect(raw["vault"]).toBe(vault);+ expect(typeof raw["linked_at"]).toBe("string");+});++test("readVaultPointer returns null when no pointer file exists", () => {+ expect(readVaultPointer(project)).toBeNull();+});++test("writeVaultPointer validates project dir, vault dir, and self-links", () => {+ expect(() => writeVaultPointer(join(tmp, "ghost"), vault)).toThrow("project directory");+ expect(() => writeVaultPointer(project, join(tmp, "no-vault"))).toThrow("vault");+ // A directory inside the vault must not point at that same vault.+ const inside = join(vault, "Brain", "sub");+ mkdirSync(inside, { recursive: true });+ expect(() => writeVaultPointer(inside, vault)).toThrow("inside");+ expect(() => writeVaultPointer(vault, vault)).toThrow("inside");+});++test("removeVaultPointer deletes the file and reports absence", () => {+ writeVaultPointer(project, vault);+ expect(removeVaultPointer(project)).toBe(true);+ expect(readVaultPointer(project)).toBeNull();+ expect(removeVaultPointer(project)).toBe(false);+});++// ββ walk-up discovery βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++test("findVaultPointer walks up from a nested directory", () => {+ writeVaultPointer(project, vault);+ const nested = join(project, "packages", "api", "src");+ mkdirSync(nested, { recursive: true });+ const probe = findVaultPointer(nested);+ expect(probe).not.toBeNull();+ expect(probe!.dir).toBe(project);+ expect(probe!.pointer!.vault).toBe(vault);+});++test("findVaultPointer returns null when nothing is found up to the root", () => {+ expect(findVaultPointer(project)).toBeNull();+});++test("a malformed pointer is surfaced with an error and resolves to null", () => {+ writeFileSync(join(project, VAULT_POINTER_FILE), "{not json");+ const probe = findVaultPointer(project);+ expect(probe).not.toBeNull();+ expect(probe!.pointer).toBeNull();+ expect(probe!.error).not.toBeNull();+ expect(resolvePointerVault(project)).toBeNull();+});++test("resolvePointerVault is fail-soft when the pointed vault is gone", () => {+ writeVaultPointer(project, vault);+ rmSync(vault, { recursive: true, force: true });+ expect(resolvePointerVault(project)).toBeNull();+});++// ββ resolveVault integration ββββββββββββββββββββββββββββββββββββββββββββββββ++test("resolveVault prefers a project pointer over the config vault key", () => {+ const otherVault = join(tmp, "other-vault");+ mkdirSync(join(otherVault, "Brain"), { recursive: true });+ writeVaultPointer(project, otherVault);+ const nested = join(project, "deep", "dir");+ mkdirSync(nested, { recursive: true });+ expect(resolveVault(configPath, { cwd: nested })).toBe(otherVault);+});++test("VAULT_DIR env still wins over a project pointer", () => {+ writeVaultPointer(project, vault);+ const prev = process.env["VAULT_DIR"];+ process.env["VAULT_DIR"] = join(tmp, "env-vault");+ try {+ expect(resolveVault(configPath, { cwd: project })).toBe(join(tmp, "env-vault"));+ } finally {+ if (prev === undefined) delete process.env["VAULT_DIR"];+ else process.env["VAULT_DIR"] = prev;+ }+});++test("resolveVault without a pointer keeps the config-key behaviour", () => {+ expect(resolveVault(configPath, { cwd: project })).toBe(vault);+});++// ββ linked-projects registry ββββββββββββββββββββββββββββββββββββββββββββββββ++test("register/list/unregister round-trip with stable path order", () => {+ const projectB = join(tmp, "a-project");+ mkdirSync(projectB, { recursive: true });+ registerLinkedProject(configPath, project, vault);+ registerLinkedProject(configPath, projectB, vault);+ const listed = listLinkedProjects(configPath);+ expect(listed.map((p) => p.path)).toEqual([projectB, project].toSorted());+ expect(listed[0]!.vault).toBe(vault);+ expect(unregisterLinkedProject(configPath, projectB)).toBe(true);+ expect(unregisterLinkedProject(configPath, projectB)).toBe(false);+ expect(listLinkedProjects(configPath)).toHaveLength(1);+});++test("a malformed registry is tolerated on read", () => {+ writeFileSync(projectsRegistryPath(configPath), "{broken");+ expect(listLinkedProjects(configPath)).toHaveLength(0);+});++test("linkedProjectsStatus reports ok, missing, malformed, and broken vaults", () => {+ registerLinkedProject(configPath, project, vault);+ writeVaultPointer(project, vault);++ const missing = join(tmp, "missing-pointer");+ mkdirSync(missing, { recursive: true });+ registerLinkedProject(configPath, missing, vault);++ const malformed = join(tmp, "malformed-pointer");+ mkdirSync(malformed, { recursive: true });+ registerLinkedProject(configPath, malformed, vault);+ writeFileSync(join(malformed, VAULT_POINTER_FILE), "{broken");++ const statuses = linkedProjectsStatus(configPath);+ const byPath = new Map(statuses.map((s) => [s.path, s]));+ expect(byPath.get(project)!.pointer).toBe("ok");+ expect(byPath.get(project)!.vaultExists).toBe(true);+ expect(byPath.get(missing)!.pointer).toBe("missing");+ expect(byPath.get(malformed)!.pointer).toBe("malformed");+});++test("linkedProjectsStatus flags a pointer that disagrees with the registry", () => {+ const otherVault = join(tmp, "other-vault");+ mkdirSync(join(otherVault, "Brain"), { recursive: true });+ registerLinkedProject(configPath, project, vault);+ writeVaultPointer(project, otherVault);+ const statuses = linkedProjectsStatus(configPath);+ expect(statuses[0]!.pointer).toBe("mismatch");+});diff --git a/tests/core/brain/profile-doc.test.ts b/tests/core/brain/profile-doc.test.tsnew file mode 100644index 00000000..2fbb3025--- /dev/null+++ b/tests/core/brain/profile-doc.test.ts@@ -0,0 +1,84 @@+/**+ * Shell-native Brain profile (Workspace Insight Suite, t_323a9a83):+ * a materialized `Brain/profile.md` digest plus a `.o2bfs` marker so+ * shell wrappers can detect a Brain root without MCP.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ buildProfileDoc,+ isProfileStale,+ O2BFS_MARKER_FILE,+ PROFILE_DOC_REL,+ writeProfileDoc,+} from "../../../src/core/brain/profile-doc.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";++let vault: string;+const NOW = new Date("2026-06-03T10:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-profile-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writePreference(vault, {+ slug: "no-shouting",+ topic: "no-shouting",+ principle: "Do not use exclamation marks in docs.",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: ["[[sig-2026-05-01-no-shouting]]"],+ confidence_value: 0.9,+ });+ writeFileSync(join(vault, "Brain", "inbox", "sig-sample.md"), "---\ntopic: sample\n---\n");+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("buildProfileDoc assembles facts, preferences, and a generated_at stamp", () => {+ const doc = buildProfileDoc(vault, { now: NOW });+ expect(doc.text).toContain("# Brain profile");+ expect(doc.text).toContain("generated_at: 2026-06-03T10:00:00.000Z");+ expect(doc.text).toContain("Do not use exclamation marks in docs.");+ expect(doc.text).toContain("confirmed preferences: 1");+ expect(doc.text).toContain("inbox signals: 1");+ expect(doc.text).toContain("Auto-generated");+});++test("writeProfileDoc materializes Brain/profile.md and the .o2bfs marker", () => {+ const result = writeProfileDoc(vault, { now: NOW });+ expect(result.path).toBe(join(vault, PROFILE_DOC_REL));+ expect(existsSync(result.path)).toBe(true);+ const marker = join(vault, O2BFS_MARKER_FILE);+ expect(existsSync(marker)).toBe(true);+ const parsed = JSON.parse(readFileSync(marker, "utf8")) as Record<string, unknown>;+ expect(parsed["vault"]).toBe(vault);+ expect(typeof parsed["generated_at"]).toBe("string");+});++test("isProfileStale: missing file is stale, fresh file is not, old file is", () => {+ expect(isProfileStale(vault, 3600, NOW)).toBe(true);+ writeProfileDoc(vault, { now: NOW });+ expect(isProfileStale(vault, 3600, NOW)).toBe(false);+ // Age the file two hours past NOW's threshold.+ const old = new Date(NOW.getTime() - 2 * 3600 * 1000);+ utimesSync(join(vault, PROFILE_DOC_REL), old, old);+ expect(isProfileStale(vault, 3600, NOW)).toBe(true);+});diff --git a/tests/core/brain/recall-sources.test.ts b/tests/core/brain/recall-sources.test.tsnew file mode 100644index 00000000..ab137750--- /dev/null+++ b/tests/core/brain/recall-sources.test.ts@@ -0,0 +1,91 @@+/**+ * Read-only recall sources (Workspace Insight Suite, t_1375e69f): a+ * per-owner-vault registry of external vaults that participate in+ * recall as read-only origins. Registry lives beside the config file+ * (device-level concern, like profiles.json), never inside the vault.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ addRecallSource,+ listRecallSources,+ recallSourcesPath,+ removeRecallSource,+} from "../../../src/core/brain/portability/recall-sources.ts";++let tmp: string;+let owner: string;+let external: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-recall-sources-"));+ owner = join(tmp, "owner-vault");+ external = join(tmp, "external-vault");+ mkdirSync(join(owner, "Brain"), { recursive: true });+ mkdirSync(join(external, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${owner}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("add/list/remove round-trip, sorted by alias", () => {+ const second = join(tmp, "second-vault");+ mkdirSync(second, { recursive: true });+ addRecallSource(configPath, owner, "zeta", external);+ addRecallSource(configPath, owner, "alpha", second);+ const listed = listRecallSources(configPath, owner);+ expect(listed.map((s) => s.alias)).toEqual(["alpha", "zeta"]);+ expect(listed[1]!.vault).toBe(external);+ expect(listed[0]!.broken).toBe(false);+ expect(removeRecallSource(configPath, owner, "alpha")).toBe(true);+ expect(removeRecallSource(configPath, owner, "alpha")).toBe(false);+ expect(listRecallSources(configPath, owner)).toHaveLength(1);+});++test("sources are scoped to their owner vault", () => {+ const otherOwner = join(tmp, "other-owner");+ mkdirSync(join(otherOwner, "Brain"), { recursive: true });+ addRecallSource(configPath, owner, "ext", external);+ expect(listRecallSources(configPath, otherOwner)).toHaveLength(0);+});++test("validation: empty alias, duplicate alias, duplicate path, missing target", () => {+ addRecallSource(configPath, owner, "ext", external);+ expect(() => addRecallSource(configPath, owner, " ", external)).toThrow("alias");+ expect(() => addRecallSource(configPath, owner, "ext", external)).toThrow("already");+ expect(() => addRecallSource(configPath, owner, "ext2", external)).toThrow("already");+ expect(() => addRecallSource(configPath, owner, "ghost", join(tmp, "nope"))).toThrow(+ "does not exist",+ );+});++test("a source pointing at the owner vault itself is refused", () => {+ expect(() => addRecallSource(configPath, owner, "self", owner)).toThrow("itself");+});++test("a direct circular source is refused", () => {+ // external already sources owner; owner sourcing external would be circular.+ addRecallSource(configPath, external, "back", owner);+ expect(() => addRecallSource(configPath, owner, "ext", external)).toThrow("circular");+});++test("a deleted target is listed as broken, not dropped", () => {+ addRecallSource(configPath, owner, "ext", external);+ rmSync(external, { recursive: true, force: true });+ const listed = listRecallSources(configPath, owner);+ expect(listed).toHaveLength(1);+ expect(listed[0]!.broken).toBe(true);+});++test("a malformed registry is tolerated on read", () => {+ writeFileSync(recallSourcesPath(configPath), "{broken");+ expect(listRecallSources(configPath, owner)).toHaveLength(0);+});diff --git a/tests/core/brain/trigger-scan.test.ts b/tests/core/brain/trigger-scan.test.tsnew file mode 100644index 00000000..614efd1e--- /dev/null+++ b/tests/core/brain/trigger-scan.test.ts@@ -0,0 +1,114 @@+/**+ * Trigger scan + report adapters (Workspace Insight Suite, t_cd1fee79).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ candidatesFromHealth,+ candidatesFromRetention,+} from "../../../src/core/brain/triggers/adapters.ts";+import { scanTriggers } from "../../../src/core/brain/triggers/scan.ts";+import { listTriggers } from "../../../src/core/brain/triggers/store.ts";+import type { SemanticHealthReport } from "../../../src/core/brain/health/reconcile.ts";+import type { RetentionReviewReport } from "../../../src/core/brain/retention.ts";++const NOW = new Date("2026-06-03T10:00:00Z");++const HEALTH: SemanticHealthReport = {+ verdict: "investigate",+ contradictions: [+ {+ aId: "pref-b",+ bId: "pref-a",+ scope: "writing",+ jaccard: 0.8,+ aSign: "positive",+ bSign: "negative",+ },+ ],+ conceptGaps: [],+ staleClaims: [{ id: "pref-old", lastEvidenceAt: "2026-01-01T00:00:00Z", ageDays: 120 }],+};++const RETENTION: RetentionReviewReport = {+ schema_version: 1,+ generated_at: NOW.toISOString(),+ summary: { keep: 1, improve: 0, park: 1, prune: 1 },+ recommendations: [+ {+ id: "pref-keep",+ artifact_type: "retired_preference",+ action: "keep",+ reason: "active",+ path: "a.md",+ },+ {+ id: "pref-park",+ artifact_type: "retired_preference",+ action: "park",+ reason: "old retired",+ path: "b.md",+ },+ {+ id: "sig-prune",+ artifact_type: "processed_signal",+ action: "prune",+ reason: "processed long ago",+ path: "c.md",+ },+ ],+};++test("candidatesFromHealth normalizes contradictions and stale claims", () => {+ const candidates = candidatesFromHealth(HEALTH);+ expect(candidates).toHaveLength(2);+ const contradiction = candidates[0]!;+ expect(contradiction.kind).toBe("contradiction");+ expect(contradiction.urgency).toBe("high");+ // Cooldown key is order-independent: the pair sorts.+ expect(contradiction.cooldownKey).toBe("contradiction:pref-a:pref-b");+ expect(contradiction.sourceArtifacts).toContain("[[pref-a]]");+ const stale = candidates[1]!;+ expect(stale.kind).toBe("stale_claim");+ expect(stale.cooldownKey).toBe("stale_claim:pref-old");+});++test("candidatesFromRetention keeps only park and prune actions", () => {+ const candidates = candidatesFromRetention(RETENTION);+ expect(candidates).toHaveLength(2);+ expect(candidates.map((c) => c.cooldownKey)).toEqual([+ "retention_action:pref-park:park",+ "retention_action:sig-prune:prune",+ ]);+ expect(candidates[1]!.urgency).toBe("medium");+});++// ββ scanTriggers over a real (empty) vault ββββββββββββββββββββββββββββββββββ++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-trigger-scan-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("scanTriggers is fail-soft on a bare vault and persists extra candidates", () => {+ const result = scanTriggers(vault, {+ now: NOW,+ extraCandidates: candidatesFromHealth(HEALTH),+ });+ expect(result.created.length).toBeGreaterThanOrEqual(2);+ expect(listTriggers(vault, { now: NOW }).length).toBe(result.created.length);++ // Re-run: idempotent, everything active.+ const again = scanTriggers(vault, { now: NOW, extraCandidates: candidatesFromHealth(HEALTH) });+ expect(again.created).toHaveLength(0);+});diff --git a/tests/core/brain/trigger-store.test.ts b/tests/core/brain/trigger-store.test.tsnew file mode 100644index 00000000..9bbe43a4--- /dev/null+++ b/tests/core/brain/trigger-store.test.ts@@ -0,0 +1,155 @@+/**+ * Grounded trigger queue (Workspace Insight Suite, t_cd1fee79):+ * Markdown-first trigger records in Brain/triggers/ with an anti-nag+ * lifecycle - cooldown-key dedup, status transitions, expiry, and+ * once-per-cooldown brief delivery.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ briefTriggers,+ createTriggers,+ listTriggers,+ markTriggersDelivered,+ transitionTrigger,+ TRIGGER_TTL_DAYS,+} from "../../../src/core/brain/triggers/store.ts";+import type { InsightCandidate } from "../../../src/core/brain/triggers/types.ts";++let vault: string;+const NOW = new Date("2026-06-03T10:00:00Z");+const DAY_MS = 24 * 3600 * 1000;++function candidate(overrides: Partial<InsightCandidate> = {}): InsightCandidate {+ return {+ kind: "contradiction",+ urgency: "high",+ reason: "pref-a contradicts pref-b on the same scope",+ suggestedAction: "Review both preferences and retire one",+ sourceArtifacts: ["[[pref-a]]", "[[pref-b]]"],+ contextSnippets: ["pref-a: do X", "pref-b: never do X"],+ cooldownKey: "contradiction:pref-a:pref-b",+ ...overrides,+ };+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-triggers-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("createTriggers persists Markdown records with full frontmatter", () => {+ const result = createTriggers(vault, [candidate()], { now: NOW });+ expect(result.created).toHaveLength(1);+ const record = result.created[0]!;+ expect(record.status).toBe("pending");+ expect(record.expiresAt).toBe(new Date(NOW.getTime() + TRIGGER_TTL_DAYS * DAY_MS).toISOString());+ const raw = readFileSync(record.path, "utf8");+ expect(raw).toContain("trigger_type: contradiction");+ expect(raw).toContain("urgency: high");+ expect(raw).toContain("## Reason");+ expect(raw).toContain("## Suggested action");+ expect(raw).toContain("pref-b: never do X");+ expect(readdirSync(join(vault, "Brain", "triggers"))).toHaveLength(1);+});++test("repeated scans are idempotent: an active twin blocks recreation", () => {+ createTriggers(vault, [candidate()], { now: NOW });+ const second = createTriggers(vault, [candidate()], { now: NOW });+ expect(second.created).toHaveLength(0);+ expect(second.skipped[0]!.reason).toBe("active");+ expect(listTriggers(vault, { now: NOW })).toHaveLength(1);+});++test("a dismissed trigger stays silent during cooldown, recreatable after", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ transitionTrigger(vault, created[0]!.id, "dismiss", { now: NOW });++ const during = createTriggers(vault, [candidate()], {+ now: new Date(NOW.getTime() + 3 * DAY_MS),+ cooldownDays: 7,+ });+ expect(during.created).toHaveLength(0);+ expect(during.skipped[0]!.reason).toBe("cooldown");++ const after = createTriggers(vault, [candidate()], {+ now: new Date(NOW.getTime() + 8 * DAY_MS),+ cooldownDays: 7,+ });+ expect(after.created).toHaveLength(1);+});++test("lifecycle transitions are enforced", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ const acked = transitionTrigger(vault, id, "acknowledge", { now: NOW });+ expect(acked.status).toBe("acknowledged");+ const acted = transitionTrigger(vault, id, "act", { now: NOW });+ expect(acted.status).toBe("acted");+ // Terminal: no further transitions.+ expect(() => transitionTrigger(vault, id, "dismiss", { now: NOW })).toThrow("terminal");+ expect(() => transitionTrigger(vault, "tr-nope", "act", { now: NOW })).toThrow("unknown");+});++test("expiry is computed on read and unblocks recreation", () => {+ createTriggers(vault, [candidate()], { now: NOW });+ const later = new Date(NOW.getTime() + (TRIGGER_TTL_DAYS + 1) * DAY_MS);+ const listed = listTriggers(vault, { now: later });+ expect(listed[0]!.effectiveStatus).toBe("expired");+ const recreate = createTriggers(vault, [candidate()], { now: later });+ expect(recreate.created).toHaveLength(1);+});++test("per-kind candidate cap bounds one scan", () => {+ const flood = Array.from({ length: 25 }, (_, i) =>+ candidate({ cooldownKey: `contradiction:pair-${i}` }),+ );+ const result = createTriggers(vault, flood, { now: NOW, maxPerKind: 10 });+ expect(result.created).toHaveLength(10);+ expect(result.skipped.filter((s) => s.reason === "kind-cap")).toHaveLength(15);+});++test("briefTriggers delivers pending once per cooldown window", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const first = briefTriggers(vault, { now: NOW, cap: 5, cooldownDays: 7 });+ expect(first.map((t) => t.id)).toEqual([created[0]!.id]);+ markTriggersDelivered(+ vault,+ first.map((t) => t.id),+ { now: NOW },+ );++ // Delivered yesterday -> silent today (anti-nag).+ const tomorrow = new Date(NOW.getTime() + 1 * DAY_MS);+ expect(briefTriggers(vault, { now: tomorrow, cap: 5, cooldownDays: 7 })).toHaveLength(0);++ // Past the cooldown window the still-open trigger resurfaces.+ const nextWeek = new Date(NOW.getTime() + 8 * DAY_MS);+ expect(briefTriggers(vault, { now: nextWeek, cap: 5, cooldownDays: 7 })).toHaveLength(1);++ // A dismissed trigger never resurfaces in the brief.+ transitionTrigger(vault, created[0]!.id, "dismiss", { now: nextWeek });+ expect(briefTriggers(vault, { now: nextWeek, cap: 5, cooldownDays: 7 })).toHaveLength(0);+});++test("briefTriggers ranks by urgency then recency and respects the cap", () => {+ createTriggers(+ vault,+ [+ candidate({ cooldownKey: "k1", urgency: "low" }),+ candidate({ cooldownKey: "k2", urgency: "high" }),+ candidate({ cooldownKey: "k3", urgency: "medium" }),+ ],+ { now: NOW },+ );+ const listed = briefTriggers(vault, { now: NOW, cap: 2, cooldownDays: 7 });+ expect(listed).toHaveLength(2);+ expect(listed.map((t) => t.urgency)).toEqual(["high", "medium"]);+});diff --git a/tests/core/search/cross-vault.test.ts b/tests/core/search/cross-vault.test.tsnew file mode 100644index 00000000..84ef56ef--- /dev/null+++ b/tests/core/search/cross-vault.test.ts@@ -0,0 +1,95 @@+/**+ * Cross-vault union search (Workspace Insight Suite, t_72a22658):+ * one query fans out over the active vault, registered profile vaults,+ * and read-only recall sources; results merge by score with origin+ * labels; a failing origin degrades to a warning, never an error.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createProfile } from "../../../src/core/brain/portability/profiles.ts";+import { addRecallSource } from "../../../src/core/brain/portability/recall-sources.ts";+import { listSearchOrigins } from "../../../src/core/brain/portability/origins.ts";+import { searchAcrossVaults } from "../../../src/core/search/cross-vault.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import { writeMd } from "../../helpers/search-fixtures.ts";++let tmp: string;+let active: string;+let external: string;+let configPath: string;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cross-vault-"));+ active = join(tmp, "active-vault");+ external = join(tmp, "external-vault");+ mkdirSync(join(active, "Brain"), { recursive: true });+ mkdirSync(join(external, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${active}"\n`);++ writeMd(active, "Brain/notes/local-note.md", "# Local\n\nThe griffin nests in the local vault.");+ writeMd(+ external,+ "Brain/notes/external-note.md",+ "# External\n\nThe griffin also visits the external vault aviary.",+ );+ await indexVault(resolveSearchConfig({ vault: active, configPath }));+ await indexVault(resolveSearchConfig({ vault: external, configPath }));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("listSearchOrigins enumerates active, profiles, and sources, deduped by path", () => {+ createProfile(configPath, "work", external);+ createProfile(configPath, "same-as-active", active);+ addRecallSource(configPath, active, "team", external);+ const origins = listSearchOrigins(configPath, active);+ // active first, then the profile; the source duplicates the profile's+ // path and the profile duplicating the active vault is dropped.+ expect(origins.map((o) => o.label)).toEqual(["local", "profile/work"]);+ expect(origins[0]!.kind).toBe("active");+});++test("union search labels results with their origin and merges by score", async () => {+ addRecallSource(configPath, active, "team", external);+ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });+ const labels = new Set(outcome.results.map((r) => r.origin));+ expect(labels).toEqual(new Set(["local", "source/team"]));+ for (const r of outcome.results) {+ expect(r.reasons.some((reason) => reason.startsWith("origin:"))).toBe(true);+ }+ const scores = outcome.results.map((r) => r.score);+ expect([...scores].toSorted((a, b) => b - a)).toEqual(scores);+});++test("an origin without an index degrades to a warning and writes nothing", async () => {+ const bare = join(tmp, "bare-vault");+ mkdirSync(join(bare, "Brain"), { recursive: true });+ addRecallSource(configPath, active, "bare", bare);+ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });+ expect(outcome.results.length).toBeGreaterThan(0);+ expect(outcome.warnings.some((w) => w.includes("source/bare"))).toBe(true);+ // Read-only invariant: the union search never builds an index inside+ // an external vault.+ expect(existsSync(join(bare, ".open-second-brain", "brain.sqlite"))).toBe(false);+});++test("limit applies to the merged result set", async () => {+ addRecallSource(configPath, active, "team", external);+ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 1 });+ expect(outcome.results).toHaveLength(1);+ expect(outcome.total).toBeGreaterThanOrEqual(2);+});++test("single-origin union (no profiles, no sources) matches plain search shape", async () => {+ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 5 });+ expect(outcome.results.length).toBeGreaterThan(0);+ expect(outcome.results.every((r) => r.origin === "local")).toBe(true);+});diff --git a/tests/e2e/workspace-insight.integration.test.ts b/tests/e2e/workspace-insight.integration.test.tsnew file mode 100644index 00000000..3313817a--- /dev/null+++ b/tests/e2e/workspace-insight.integration.test.ts@@ -0,0 +1,133 @@+/**+ * Workspace Insight Suite e2e (epic t_618c7bd8): one flow exercises+ * both kernels end to end over the real CLI - link a project to its+ * vault, attach a read-only source, search across vaults with origin+ * labels, generate triggers, transition one, and watch the morning+ * brief deliver pending triggers once.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createTriggers } from "../../src/core/brain/triggers/store.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let external: string;+let project: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-wis-e2e-"));+ vault = join(tmp, "vault");+ external = join(tmp, "external");+ project = join(tmp, "repo");+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ mkdirSync(join(external, "Brain", "notes"), { recursive: true });+ mkdirSync(project, { recursive: true });+ writeFileSync(+ join(vault, "Brain", "notes", "local.md"),+ "# Local\n\nThe kraken charter lives in the local vault.\n",+ );+ writeFileSync(+ join(external, "Brain", "notes", "shared.md"),+ "# Shared\n\nThe kraken charter is mirrored in the team vault.\n",+ );+ config = join(tmp, "config.yaml");+ writeFileSync(config, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: config });++test("workspace reach: link, attach, search across vaults from the project dir", async () => {+ // 1. Link the project directory to the vault.+ const link = await runCli(["brain", "project", "link", project], { env: env() });+ expect(link.returncode).toBe(0);++ // 2. Attach the external vault as a read-only recall source.+ const source = await runCli(["brain", "source", "add", external, "--alias", "team"], {+ env: env(),+ });+ expect(source.returncode).toBe(0);++ // 3. Index both vaults explicitly (union search never builds one).+ expect((await runCli(["search", "index"], { env: env() })).returncode).toBe(0);+ expect((await runCli(["search", "index", "--vault", external], { env: env() })).returncode).toBe(+ 0,+ );++ // 4. Search from inside the linked project dir with --global: the+ // pointer resolves the vault, the union labels both origins.+ const out = await runCli(["search", "kraken charter", "--global", "--json"], {+ env: env(),+ cwd: project,+ });+ expect(out.returncode).toBe(0);+ const parsed = JSON.parse(out.stdout) as {+ results: Array<{ origin?: string; path: string }>;+ };+ const origins = new Set(parsed.results.map((r) => r.origin));+ expect(origins).toEqual(new Set(["local", "source/team"]));++ // 5. The external vault was never written to.+ expect(existsSync(join(external, ".o2bfs"))).toBe(false);+});++test("proactive insight: triggers flow from scan to brief to lifecycle", async () => {+ // Seed one trigger directly (scan over a bare vault finds nothing).+ const NOW = new Date();+ createTriggers(+ vault,+ [+ {+ kind: "contradiction",+ urgency: "high",+ reason: "pref-x contradicts pref-y",+ suggestedAction: "Reconcile the pair",+ sourceArtifacts: ["[[pref-x]]"],+ contextSnippets: [],+ cooldownKey: "contradiction:pref-x:pref-y",+ },+ ],+ { now: NOW },+ );++ // 1. The morning brief surfaces the pending trigger and delivers it.+ const brief = await runCli(["brain", "morning-brief"], { env: env() });+ expect(brief.returncode).toBe(0);+ expect(brief.stdout).toContain("Pending triggers");+ expect(brief.stdout).toContain("pref-x contradicts pref-y");++ // 2. A second brief inside the cooldown window stays silent.+ const second = await runCli(["brain", "morning-brief"], { env: env() });+ expect(second.stdout).not.toContain("Pending triggers");++ // 3. The operator acknowledges and acts on it via the CLI.+ const list = await runCli(["brain", "trigger", "list", "--json"], { env: env() });+ const triggers = (JSON.parse(list.stdout) as { triggers: Array<{ id: string }> }).triggers;+ expect(triggers).toHaveLength(1);+ const id = triggers[0]!.id;+ expect((await runCli(["brain", "trigger", "ack", id], { env: env() })).returncode).toBe(0);+ expect((await runCli(["brain", "trigger", "act", id], { env: env() })).returncode).toBe(0);++ // 4. History shows the acted trigger; the open list is empty.+ const history = await runCli(["brain", "trigger", "history", "--json"], { env: env() });+ const acted = (JSON.parse(history.stdout) as { triggers: Array<{ status: string }> }).triggers;+ expect(acted[0]!.status).toBe("acted");+ const openList = await runCli(["brain", "trigger", "list", "--json"], { env: env() });+ expect((JSON.parse(openList.stdout) as { triggers: unknown[] }).triggers).toHaveLength(0);++ // 5. An idea scan with --triggers enqueues fresh directions.+ writeFileSync(join(vault, "Brain", "notes", "orphan.md"), "# Orphan idea\n");+ const ideas = await runCli(["brain", "ideas", "--triggers", "--json"], { env: env() });+ expect(ideas.returncode).toBe(0);+ const ideasParsed = JSON.parse(ideas.stdout) as { triggers_created: number };+ expect(ideasParsed.triggers_created).toBeGreaterThan(0);+});diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.tsindex a0d6c7fb..7ea16a7b 100644--- a/tests/helpers/run-cli.ts+++ b/tests/helpers/run-cli.ts@@ -36,11 +36,14 @@ const RUNTIME_OVERRIDABLE_ENV = ["VAULT_AGENT_NAME","VAULT_TIMEZONE","OPEN_SECOND_BRAIN_CONFIG",+ "OPEN_SECOND_BRAIN_TRIGGER_COOLDOWN_DAYS",+ "OPEN_SECOND_BRAIN_WIKI_LINK_FORMAT",+ "OPEN_SECOND_BRAIN_RECALL_GATE_TELEMETRY",] as const;export async function runCli(args: ReadonlyArray<string>,- opts: { env?: Record<string, string>; stdin?: string } = {},+ opts: { env?: Record<string, string>; stdin?: string; cwd?: string } = {},): Promise<RunResult> {const callerEnv = opts.env ?? {};// Build the child env from process.env, then strip any runtime-resolution@@ -58,7 +61,7 @@ export async function runCli(}try {const proc = Bun.spawn(["bun", "run", CLI_ENTRY, ...args], {- cwd: ROOT,+ cwd: opts.cwd ?? ROOT,env,stdin: opts.stdin === undefined ? "ignore" : "pipe",stdout: "pipe",diff --git a/tests/mcp/brain-trigger-tool.test.ts b/tests/mcp/brain-trigger-tool.test.tsnew file mode 100644index 00000000..2581ee1b--- /dev/null+++ b/tests/mcp/brain-trigger-tool.test.ts@@ -0,0 +1,111 @@+/**+ * `brain_trigger` MCP tool + morning-brief trigger section (Workspace+ * Insight Suite, t_cd1fee79).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createTriggers } from "../../src/core/brain/triggers/store.ts";+import type { InsightCandidate } from "../../src/core/brain/triggers/types.ts";+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";++let tmp: string;+let vault: string;+let ctx: ServerContext;+const NOW = new Date("2026-06-03T10:00:00Z");++const CANDIDATE: InsightCandidate = {+ kind: "contradiction",+ urgency: "high",+ reason: "pref-a contradicts pref-b",+ suggestedAction: "Review the pair",+ sourceArtifacts: ["[[pref-a]]"],+ contextSnippets: [],+ cooldownKey: "contradiction:pref-a:pref-b",+};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-trigger-mcp-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+ ctx = { vault, configPath, repoRoot: null };+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function tool(name: string) {+ return findTool(buildToolTable("full"), name);+}++test("brain_trigger list/acknowledge/act round-trip", async () => {+ const { created } = createTriggers(vault, [CANDIDATE], { now: NOW });+ const id = created[0]!.id;++ const listed = (await tool("brain_trigger").handler(ctx, { operation: "list" })) as {+ triggers: Array<{ id: string; status: string }>;+ };+ expect(listed.triggers.map((t) => t.id)).toEqual([id]);++ const acked = (await tool("brain_trigger").handler(ctx, {+ operation: "acknowledge",+ id,+ })) as { trigger: { status: string } };+ expect(acked.trigger.status).toBe("acknowledged");++ const acted = (await tool("brain_trigger").handler(ctx, { operation: "act", id })) as {+ trigger: { status: string };+ };+ expect(acted.trigger.status).toBe("acted");++ const history = (await tool("brain_trigger").handler(ctx, { operation: "history" })) as {+ triggers: Array<{ id: string }>;+ };+ expect(history.triggers.map((t) => t.id)).toEqual([id]);+});++test("brain_trigger scan on a bare vault is fail-soft", async () => {+ const result = (await tool("brain_trigger").handler(ctx, { operation: "scan" })) as {+ created: unknown[];+ candidates: number;+ };+ expect(Array.isArray(result.created)).toBe(true);+});++test("brain_trigger rejects unknown operations and terminal transitions", async () => {+ expect(() => tool("brain_trigger").handler(ctx, { operation: "explode" })).toThrow();+ const { created } = createTriggers(vault, [CANDIDATE], { now: NOW });+ await tool("brain_trigger").handler(ctx, { operation: "dismiss", id: created[0]!.id });+ expect(() =>+ tool("brain_trigger").handler(ctx, { operation: "act", id: created[0]!.id }),+ ).toThrow("terminal");+});++test("brain_morning_brief surfaces pending triggers once per cooldown", async () => {+ createTriggers(vault, [CANDIDATE], { now: new Date() });+ const first = (await tool("brain_morning_brief").handler(ctx, {})) as {+ text: string;+ triggers?: Array<{ id: string }>;+ };+ expect(first.triggers).toBeDefined();+ expect(first.text).toContain("Pending triggers");++ // Second brief inside the cooldown window: silent.+ const second = (await tool("brain_morning_brief").handler(ctx, {})) as {+ text: string;+ triggers?: unknown[];+ };+ expect(second.triggers).toBeUndefined();+ 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>;+ expect(brief["triggers"]).toBeUndefined();+});diff --git a/tests/mcp/deep-synthesis-tool.test.ts b/tests/mcp/deep-synthesis-tool.test.tsnew file mode 100644index 00000000..e0631b92--- /dev/null+++ b/tests/mcp/deep-synthesis-tool.test.ts@@ -0,0 +1,59 @@+/**+ * `brain_deep_synthesis` MCP tool (Workspace Insight Suite, t_04e94382).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { indexVault } from "../../src/core/search/indexer.ts";+import { resolveSearchConfig } from "../../src/core/search/index.ts";+import { listTriggers } from "../../src/core/brain/triggers/store.ts";+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { writeMd } from "../helpers/search-fixtures.ts";++let tmp: string;+let vault: string;+let ctx: ServerContext;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-synth-mcp-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+ writeMd(+ vault,+ "Brain/notes/claim.md",+ "---\ncontradicts: [[counter]]\n---\n# Claim\n\nWyverns roost in cliffs. See [[lost-note]].",+ );+ writeMd(vault, "Brain/notes/counter.md", "# Counter\n\nWyverns roost in forests.");+ await indexVault(resolveSearchConfig({ vault, configPath }));+ ctx = { vault, configPath, repoRoot: null };+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("returns the dossier and optionally enqueues triggers", async () => {+ const tool = findTool(buildToolTable("full"), "brain_deep_synthesis");+ const report = (await tool.handler(ctx, { topic: "wyverns", triggers: true })) as {+ checked: string[];+ contradictions: Array<{ target: string }>;+ gaps: Array<{ target: string }>;+ triggers_created: number;+ };+ expect(report.checked).toContain("knowledge_gaps");+ expect(report.contradictions[0]!.target).toBe("counter");+ expect(report.gaps[0]!.target).toBe("lost-note");+ expect(report.triggers_created).toBeGreaterThanOrEqual(2);+ expect(listTriggers(vault, { now: new Date() }).length).toBe(report.triggers_created);+});++test("rejects a missing topic", async () => {+ const tool = findTool(buildToolTable("full"), "brain_deep_synthesis");+ // The handler is async: assert the rejected promise, not a sync throw.+ await expect(Promise.resolve(tool.handler(ctx, {}))).rejects.toThrow();+});diff --git a/tests/mcp/idea-discovery-tool.test.ts b/tests/mcp/idea-discovery-tool.test.tsnew file mode 100644index 00000000..471658fd--- /dev/null+++ b/tests/mcp/idea-discovery-tool.test.ts@@ -0,0 +1,48 @@+/**+ * `brain_idea_discovery` MCP tool (Workspace Insight Suite, t_8722a62a).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { listTriggers } from "../../src/core/brain/triggers/store.ts";+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";++let tmp: string;+let vault: string;+let ctx: ServerContext;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-ideas-mcp-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ const orphan = join(vault, "Brain", "notes", "orphan.md");+ writeFileSync(orphan, "# Orphan research\n");+ const past = new Date(Date.now() - 40 * 24 * 3600 * 1000);+ utimesSync(orphan, past, past);+ const configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+ ctx = { vault, configPath, repoRoot: null };+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("returns ranked ideas and optionally enqueues triggers", async () => {+ const tool = findTool(buildToolTable("full"), "brain_idea_discovery");+ const result = (await tool.handler(ctx, { triggers: true })) as {+ ideas: Array<{ kind: string; title: string }>;+ triggers_created: number;+ };+ expect(result.ideas.some((i) => i.title === "orphan")).toBe(true);+ expect(result.triggers_created).toBeGreaterThan(0);+ expect(listTriggers(vault, { now: new Date() }).length).toBe(result.triggers_created);+});++test("cap above 50 is rejected", () => {+ const tool = findTool(buildToolTable("full"), "brain_idea_discovery");+ expect(() => tool.handler(ctx, { cap: 99 })).toThrow();+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 50eacf10..979ffd9d 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -253,6 +253,10 @@ describe("tool listing", () => {"skills_attach","tool_hydrate","brain_intention",+ // Workspace Insight Suite: trigger queue + proactive insight.+ "brain_trigger",+ "brain_deep_synthesis",+ "brain_idea_discovery",].toSorted(),);// Explicit grep: legacy writable tools are no longer advertised.@@ -502,7 +506,9 @@ describe("stdio loop", () => {// tools/call, not advertised) = 56 (+1 capability diagnostic = 57).// + list_skills / get_skill / skills_attach / tool_hydrate /// brain_intention (Agent Surface Suite) = 62.- expect(list.result.tools.length).toBe(62);+ // + brain_trigger / brain_deep_synthesis / brain_idea_discovery+ // (Workspace Insight Suite) = 65.+ expect(list.result.tools.length).toBe(65);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/recall-gate-telemetry.test.ts b/tests/mcp/recall-gate-telemetry.test.tsnew file mode 100644index 00000000..4ce91a57--- /dev/null+++ b/tests/mcp/recall-gate-telemetry.test.ts@@ -0,0 +1,89 @@+/**+ * `brain_recall_gate` telemetry emission + `brain_recall_telemetry`+ * gate operations (Workspace Insight Suite, t_65036e02).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { listGateTelemetry } from "../../src/core/brain/gate-telemetry.ts";+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";++let tmp: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-gate-mcp-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function ctx(): ServerContext {+ return { vault, configPath, repoRoot: null };+}++function tool(name: string) {+ return findTool(buildToolTable("full"), name);+}++test("default off: the gate emits no telemetry", async () => {+ const decision = (await tool("brain_recall_gate").handler(ctx(), { prompt: "hello" })) as {+ retrieve: boolean;+ };+ expect(decision.retrieve).toBe(false);+ expect(listGateTelemetry(vault)).toHaveLength(0);+});++test("with recall_gate_telemetry on, decisions land as continuity records", async () => {+ writeFileSync(configPath, `vault: "${vault}"\nrecall_gate_telemetry: "true"\n`);+ await tool("brain_recall_gate").handler(ctx(), {+ prompt: "what did we decide about the index?",+ telemetry_host: "hermes",+ session_id: "sess-1",+ });+ await tool("brain_recall_gate").handler(ctx(), { prompt: "hi" });+ const records = listGateTelemetry(vault);+ expect(records).toHaveLength(2);+ expect(records.some((r) => r.payload["decision"] === "retrieve")).toBe(true);+ expect(records.some((r) => r.payload["decision"] === "skip")).toBe(true);+ expect(records.some((r) => r.payload["host"] === "hermes")).toBe(true);+ // The raw prompt never lands on disk - assert against the PERSISTED+ // continuity files, not just the returned payloads, so a serializer+ // regression cannot slip through.+ for (const record of records) {+ expect(JSON.stringify(record.payload)).not.toContain("what did we decide");+ }+ const continuityDir = join(vault, "Brain", "log", "continuity");+ for (const name of readdirSync(continuityDir, { recursive: true }) as string[]) {+ const filePath = join(continuityDir, name);+ let content: string;+ try {+ content = readFileSync(filePath, "utf8");+ } catch {+ continue; // directories+ }+ expect(content).not.toContain("what did we decide");+ }++ const summary = (await tool("brain_recall_telemetry").handler(ctx(), {+ operation: "gate_summary",+ })) as { total: number; retrieved: number; skipped: number };+ expect(summary.total).toBe(2);+ expect(summary.retrieved).toBe(1);+ expect(summary.skipped).toBe(1);++ const listed = (await tool("brain_recall_telemetry").handler(ctx(), {+ operation: "gate_list",+ limit: 1,+ })) as { total: number; records: unknown[] };+ expect(listed.total).toBe(1);+});diff --git a/tests/mcp/search-global.test.ts b/tests/mcp/search-global.test.tsnew file mode 100644index 00000000..f3b32b1e--- /dev/null+++ b/tests/mcp/search-global.test.ts@@ -0,0 +1,74 @@+/**+ * `brain_search { global: true }` (Workspace Insight Suite,+ * t_72a22658): cross-vault union over MCP with origin labels.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { addRecallSource } from "../../src/core/brain/portability/recall-sources.ts";+import { indexVault } from "../../src/core/search/indexer.ts";+import { resolveSearchConfig } from "../../src/core/search/index.ts";+import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { writeMd } from "../helpers/search-fixtures.ts";++let tmp: string;+let vault: string;+let external: string;+let configPath: string;+let ctx: ServerContext;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-global-"));+ vault = join(tmp, "vault");+ external = join(tmp, "external");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ mkdirSync(join(external, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+ writeMd(vault, "Brain/notes/local.md", "# Local\n\nA chimera sighting in the local vault.");+ writeMd(+ external,+ "Brain/notes/ext.md",+ "# Ext\n\nA chimera sighting in the external vault. Xylocopa beacon.",+ );+ await indexVault(resolveSearchConfig({ vault, configPath }));+ await indexVault(resolveSearchConfig({ vault: external, configPath }));+ addRecallSource(configPath, vault, "team", external);+ ctx = { vault, configPath, repoRoot: null };+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function searchTool() {+ return findTool(buildToolTable("full"), "brain_search");+}++test("global search returns origin-labelled results from both vaults", async () => {+ const result = (await searchTool().handler(ctx, { query: "chimera", global: true })) as {+ results: Array<{ origin?: string; reasons: string[] }>;+ total: number;+ };+ const origins = new Set(result.results.map((r) => r.origin));+ expect(origins).toEqual(new Set(["local", "source/team"]));+ expect(result.total).toBeGreaterThanOrEqual(2);+});++test("default (no global flag) stays scoped to the active vault", async () => {+ const result = (await searchTool().handler(ctx, { query: "chimera" })) as {+ results: Array<{ origin?: string }>;+ };+ expect(result.results.length).toBeGreaterThan(0);+ expect(result.results.every((r) => r.origin === undefined)).toBe(true);+ // A token that exists ONLY in the external vault must yield nothing+ // without the global flag - leaked external matches would slip past+ // the origin-field check above.+ const externalOnly = (await searchTool().handler(ctx, { query: "xylocopa" })) as {+ results: unknown[];+ };+ expect(externalOnly.results).toHaveLength(0);+});