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: CodeGraph and MCP operational readability (v1.12.0) (#101)
Sol Aitken9c1d48fa15ba
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 3dc5b8e2..8ee040b9 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.11.0",+ "version": "1.12.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 ef9da553..abb55da4 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.11.0",+ "version": "1.12.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 a0cf28a8..bfc7314d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,42 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.12.0] - 2026-06-15++### Added++- **CodeGraph and MCP Operational Readability.** Additive, deterministic+ operator surfaces over the optional Codegraph partner and vault community+ detection. With no new option in use, existing reads stay byte-identical and+ the kernel never calls an LLM.+ - **CodeGraph report surface (`o2b partner codegraph report`,+ `brain_codegraph_report`).** A read-only report that resolves the in-scope+ code project, reports the partner index state (`no_project`, `absent`,+ `not_indexed`, `indexed` with node/file/edge counts, or `error`), and+ structurally parses `Cargo.toml` for Rust workspace members. It never+ installs, initializes, extracts, or mutates a codegraph or Graphify index:+ a missing CLI, a missing `.codegraph/` index, and a non-Rust project are all+ honest report states (the latter returns `cargo_workspace: null` with an+ explicit reason) rather than failures or silent no-ops. The report is+ schema-versioned (`schema_version: 1`) and the same shape backs both the CLI+ (`--json`) and the MCP tool. This surfaces the operationally useful kernel of+ Graphify's Cargo workspace work (workspace membership) without adopting the+ extraction binary as a dependency or adding a `crate_depends_on` edge type to+ the Open Second Brain graph schema.+ - **Batched community materialization (`o2b brain clusters run --batch-size N`,+ `brain_clusters` `batch_size`).** Borrowing Graphify's multi-batch labeling+ for large graphs, cluster note materialization can now run in fixed-size,+ order-preserving chunks. Batched mode returns the same community summaries+ plus a `batches` array, each entry carrying `index`, `start`, `end`,+ `written`, `removed`, and an optional `error`; a batch that fails is isolated+ and reported instead of dropping the whole pass. The stale sweep keys off the+ full detected set, so a failed batch leaves its prior note in place rather+ than deleting it, and the single global sweep is attributed to the final+ batch. Detection stays deterministic and label-free (no LLM labeling, no+ natural-language classification, no Graphify dependency). Without+ `--batch-size`/`batch_size` the run is byte-identical to before, and invalid+ sizes are rejected with the usual usage/`INVALID_PARAMS` errors.+## [1.11.0] - 2026-06-14### Added@@ -5504,6 +5540,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.12.0]: https://github.com/itechmeat/open-second-brain/compare/v1.11.0...v1.12.0[1.11.0]: https://github.com/itechmeat/open-second-brain/compare/v1.10.0...v1.11.0[1.10.0]: https://github.com/itechmeat/open-second-brain/compare/v1.9.0...v1.10.0[1.9.0]: https://github.com/itechmeat/open-second-brain/compare/v1.8.0...v1.9.0diff --git a/README.md b/README.mdindex deca7e87..f30385d8 100644--- a/README.md+++ b/README.md@@ -92,6 +92,8 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra- **Recall you can tune, and a working set that prunes itself.** `o2b search --profile fast|balanced|thorough` (and the `brain_search` `profile` field) pick a recall preset over the same bounded knobs the self-tuner uses - an explicit profile wins over a learned grid point, and no profile leaves ranking bit-for-bit unchanged. `o2b brain file-context <path>` surfaces prior vault work that mentions a file before you read it; `o2b brain co-occurrence` proposes relationship edges between entities repeatedly co-referenced from the same notes, scored structurally over the wikilink graph with no natural-language word list in any language; and `o2b brain continuity rank` weights working-memory records by a usage-driven decay derived only from real recall telemetry, so stale decisions fade while actively-recalled ones stay prominent. All deterministic, all read-only or suggestion-only.- **Session knowledge you can query, trace, and walk.** `o2b brain session-summary` (and `brain_session_summary`) stores a session-scoped digest over four categories - request, decisions, learnings, next_steps - that the agent extracts and the kernel only stores, so you can ask what a session decided as one unit. `o2b brain idea-lineage <id>` traces how a derived artifact was reached as an observation to synthesis to conclusion graph over the edges already recorded (continuity `sourceRefs`, or a preference's belief-evolution), cycle-guarded and depth-bounded. `o2b brain note-history <path>` splits a note's git history into episodic phases on a deterministic commit-time gap - language-agnostic, no commit-message parsing. The kernel never calls a model; absent inputs report honestly rather than fabricating.+- **Operational readability for code partners and large vaults.** Open Second Brain now exposes a read-only CodeGraph report (`o2b partner codegraph report`, `brain_codegraph_report`) that resolves the in-scope code project, reports the codegraph index state with node and edge counts, and structurally parses Cargo.toml for Rust workspace members. The report is honest about missing CLIs, missing indexes, and non-Rust projects. For large vaults, community materialization can run in fixed-size batches (`o2b brain clusters run --batch-size N`, `brain_clusters` `batch_size`) with per-batch success or isolated failure reporting, while the default run stays byte-identical.+That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.## Safetydiff --git a/docs/brainstorm/codegraph-mcp-operational-readability/cli-output/claude.md b/docs/brainstorm/codegraph-mcp-operational-readability/cli-output/claude.mdnew file mode 100644index 00000000..0e289745--- /dev/null+++ b/docs/brainstorm/codegraph-mcp-operational-readability/cli-output/claude.md@@ -0,0 +1,29 @@+## Variant 1: In-place surface augmentation+Approach: Extend the two existing modules directly without adding new surfaces. `codegraph.ts` gains Cargo-workspace detection that enriches the existing `code_graph` `CheckResult` with crate count and workspace-membership readability (reading `Cargo.toml` `[workspace]` members and, when the partner CLI is present, passing through its status), while `communities.ts` gains an opt-in `batchSize` option that chunks label propagation and cluster-note materialization with per-batch failure isolation. Defaults stay unset, so doctor output and community detection remain byte-identical until a flag is used.+Trade-offs:+- Smallest footprint and fastest to ship; no new CLI verbs, MCP tools, or schema tokens to document and version.+- Couples two unrelated concerns (partner readability, graph robustness) onto pre-existing functions, and Rust readability stays buried inside `o2b doctor` output rather than being independently queryable.+- Partial-failure resilience added inside `detectCommunities` risks diluting its current deterministic, fully-in-memory contract that downstream tests rely on.+Complexity: small+Risk: low++## Variant 2: Dedicated operational-readability reporting layer+Approach: Add a new read-only surface (`o2b partner codegraph report` plus a `brain_codegraph_report` MCP tool) that aggregates partner code-graph status, detected Cargo-workspace crate membership, and any partner-reported crate dependency counts into one structured, schema-versioned report with honest absent-data fields and typed errors. Community labeling robustness is delivered as a separate, option-gated batched pass over the existing detection, leaving the default path untouched. Each concern lives in its own discoverable surface.+Trade-offs:+- Operational readability becomes a first-class, queryable artifact for agents and operators rather than a doctor side effect, matching the cards' stated intent.+- Honest-absent-data and typed-error reporting fit the project's existing conventions and stay additive, so existing reads are byte-identical.+- More new surface area to register, document, changelog, and version-sync than Variant 1; two cards land as two distinct surfaces rather than one cohesive change.+Complexity: medium+Risk: low++## Variant 3: Unified batched-graph-pass abstraction with crate edges+Approach: Introduce a shared "batched graph pass with partial-failure accumulation" primitive consumed by both subsystems: community detection runs chunked, fault-isolated batches, and a new crate-graph projection extracts Graphify-style `crate_depends_on` edges from detected Cargo workspaces into Open Second Brain's graph schema as a new typed edge. This generalizes batching as a cross-cutting concern and brings Rust workspace dependencies in as first-class graph structure.+Trade-offs:+- Maximizes reuse and treats batching/partial-failure as one well-tested primitive across the graph layer.+- Adds a new `crate_depends_on` edge type to the graph schema, a non-additive change that touches indexing, recall, and schema-pack surfaces, raising migration and regression surface.+- Presupposes deeper Graphify-style edge mapping the constraints caution against, and risks recasting Open Second Brain's optional partner as an owned ingestion dependency.+Complexity: large+Risk: high++## Recommended: Variant 2+Rationale: The cards are explicitly framed as operational readability rather than new graph machinery, so a dedicated read-only report surface delivers their value where operators and agents can find it, without burying it in doctor output as Variant 1 does. It stays additive and option-gated with typed errors and honest absent-data, preserving byte-identical default behavior per the constraints. It deliberately avoids Variant 3's new `crate_depends_on` schema edge and Graphify-as-dependency overreach, keeping the partner integration detection-only. The modest extra surface area is the right cost for a discoverable, versioned artifact that fits existing conventions.diff --git a/docs/brainstorm/codegraph-mcp-operational-readability/cli-output/prompt.md b/docs/brainstorm/codegraph-mcp-operational-readability/cli-output/prompt.mdnew file mode 100644index 00000000..34cf3fb1--- /dev/null+++ b/docs/brainstorm/codegraph-mcp-operational-readability/cli-output/prompt.md@@ -0,0 +1,1871 @@+You are consulting on Open Second Brain, a TypeScript/Bun project that provides an Obsidian-native memory layer for Hermes Agent and other MCP hosts.++Return exactly 3 distinct architectural variants for the release scope below. For each variant use this exact shape:++## Variant N: <name>+Approach: 2-3 sentences.+Trade-offs:+- ...+- ...+Complexity: small|medium|large+Risk: low|medium|high++After the three variants, return exactly one recommendation section:++## Recommended: Variant N+Rationale: 2-4 sentences.++Do not include code. Do not include sections outside the variants and recommendation.++# Release scope+Chosen scope: CodeGraph and MCP operational readability+Slug: codegraph-mcp-operational-readability+Branch: feat/codegraph-mcp-operational-readability+In-scope task ids: t_a1e76788, t_a286135c++# In-scope card bodies++## t_a1e76788+id: t_a1e76788+title: [upstream:graphify] Cargo workspace dependency extraction for Rust projects+status: triage priority: 1 assignee: -+----- body -----+**Source**: https://github.com/safishamsi/graphify/releases/tag/v0.8.38+**Repo**: safishamsi/graphify (44200★)+**Released**: v0.8.38 (2026-06-11T22:54:39Z)++## What+Graphify v0.8.38 adds Cargo workspace dependency extraction: `graphify extract ./my-workspace --cargo` maps Rust workspace crates and internal `crate_depends_on` edges. This enables analysis of Rust workspace structures with crate-level dependency graphs.++## Why useful for OSB+OSB integrates with Graphify via the codegraph partner module (src/core/partner/codegraph.ts) but the integration focuses on general code graphs. Adding support for Graphify's `--cargo` flag would let OSB operators analyze Rust workspace dependencies as first-class graph structures — crate dependencies, internal crate_depends_on edges, and workspace membership. This complements the existing language support in Graphify.++## Status in OSB+- **Verdict**: not_in_osb_useful+- **Codegraph hints**: src/core/partner/codegraph.ts detects CodeGraph presence/status but has no `--cargo` flag support or Rust workspace-specific extraction logic; no crate_depends_on edge type in OSB's graph schema++## Notes+Could extend the codegraph integration to pass `--cargo` when a Cargo workspace is detected, and map the resulting crate_depends_on edges into OSB's graph. The feature is opt-in via CLI flag.+----- last comments -----+[osb-triage-validator] osb-triage-validator @ 2026-06-13T10:33Z:+- sanity: clean+- cluster: leave: graphify codegraph-partner cluster with t_6c9f4434 - separate backends.+- priority: set to 1: value depends on external fact+++## t_a286135c+id: t_a286135c+title: [upstream:graphify] Multi-batch community labeling for large graphs+status: triage priority: 1 assignee: -+----- body -----+**Source**: https://github.com/safishamsi/graphify/releases/tag/v0.8.36+**Repo**: safishamsi/graphify (44200★)+**Released**: v0.8.36 (2026-06-08T22:58:46Z)++## What+Graphify v0.8.36 added multi-batch community labeling: `label_communities` now chunks in groups of 100 (configurable `batch_size=`) for 16k-context models; partial batch failures no longer drop the whole pass.++## Why useful for OSB+OSB's community detection (src/core/brain/link-graph/communities.ts:74 detectCommunities) processes all nodes in memory with no batching. For large vaults with many notes, this could exceed context limits when using LLM-based labeling. Multi-batch processing with configurable batch size and partial failure resilience would make community labeling scalable and robust.++## Status in OSB+- **Verdict**: not_in_osb_useful+- **Codegraph hints**: src/core/brain/link-graph/communities.ts:74 detectCommunities (no batching, processes all nodes in memory); src/core/brain/link-graph/communities.ts:226 renderClusterNote (generates cluster notes); no batch_size parameter or partial failure handling++## Notes+Graphify's approach: chunk communities into groups of 100, process each batch independently, continue on partial failures. Configurable batch_size for different context windows. Could be adapted for OSB's LLM-based community labeling (if added).++---++## Phase 0 implementation plan pointer++Follow `docs/brainstorm/codegraph-readability-mcp-operations/plan.md`, section `t_a286135c - [upstream:graphify] Multi-batch community labeling for large graphs`, on branch `feat/codegraph-readability-mcp-operations`. Implement under TDD: write/adjust the focused failing test first, then make it pass, then refactor.++## Overall release scope++This card ships as part of the single release scope "CodeGraph readability and MCP operations" on shared branch `feat/codegraph-readability-mcp-operations`.++In-scope cards:++- `t_85252236` - [upstream:graphify] Offline code-only extraction without API keys+- `t_a286135c` - [upstream:graphify] Multi-batch community labeling for large graphs++Combined design: `docs/brainstorm/codegraph-readability-mcp-operations/design.md`.++The cards are driven one at a time on the shared branch. Before editing, inspect the current branch commits and build on any previously-driven in-scope card commits. Do not duplicate sibling work and do not introduce conflicting abstractions; update shared docs/changelog sections in place if a sibling already touched them.+----- last comments -----+[osb-triage-validator] osb-triage-validator @ 2026-06-09T14:26Z:+- sanity: clean+- cluster: no cluster+- priority: set to 1: not_in_osb_useful, multi-batch labeling presupposes LLM-based community labeling that OSB communit+++# Project/runtime+- package: open-second-brain 1.11.0+- runtime/language: Bun + TypeScript ESM+- test/lint/typecheck scripts: bun run test, bun run lint, bun run typecheck, bun run validate+- public docs prefer full product name "Open Second Brain" rather than abbreviation.+- Engineering rules: SOLID, KISS, DRY; no misleading fallbacks; no hardcoding; English-only artifacts; language-agnostic behavior where natural-language processing would otherwise be tempting.++# Recent git log+c2c3ff4 feat: Session Knowledge Synthesis Suite - structured session summaries, idea-lineage, episodic note history (v1.11.0) (#100)+56dd3dd fix(hermes): bridge EOF - byte streams, stderr drain, retry loop (#92)+35b824e feat: Recall & Working-Memory Quality Suite - selectable profiles, usage decay, co-occurrence, file-context (v1.10.0) (#99)+929d54c feat: Brain Portability & Interop Suite - bank export/import, page contract, brain_create_note, in-process SDK (v1.9.0) (#98)+7cdbfc0 feat: Indexer Durability & Resilience Suite - cooperative abort, graceful watch shutdown, resumable reindex (v1.8.0) (#97)+8b679fe feat: Knowledge Provenance Suite - ingest, research, NER, derived facts, owner-scope, standing-query (v1.7.0) (#96)+6e59a42 feat: Vault Integrity & Trust Suite - untrusted-source containment, NFC identity, watch-sync, O(1) graph, agent-scope (v1.6.0) (#95)+70d95c6 chore(release): bump version to 1.5.0 (#94)+e4df212 feat: Search & Recall Quality Suite - explainable scores, trust, threshold, reinforce, eval (#93)+2e74afe feat: native Grok Build CLI integration - bundled plugin, hooks, session import (v1.4.0) (#91)+3e7e233 fix(hermes): serialize handle_tool_call result to a string (v1.3.1) (#90)+2abc90b fix(changelog): the opencode integration ships in v1.3.0, not a phantom 1.4.0 (#89)+96f1ff4 feat: native opencode integration - config-correct install, bundled plugin, session capture (#88)+0340560 feat: Continuity, Hygiene & Freshness Suite - session lineage, memory hygiene, anticipatory cache (v1.3.0) (#87)+8972f13 refactor: SOLID/DRY decomposition - domain modules, unified helpers, surface guards (v1.2.0) (#86)+6651228 refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)+9886d9a refactor: make search and classification language-agnostic (#84)+618870e refactor!: remove the pay.sh integration and the Pay Memory layer (#83)+72bac52 fix(hermes): advertise static tool schemas so the provider registers with its full tool set (#81)+ff43abd fix(ci): treat an existing release as success in the release workflow (#80)+++# README summary excerpt+# Open Second Brain++++> An [Obsidian](https://obsidian.md)-native memory layer for your AI agent. Plain Markdown you own, in the same vault you already use.++Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/hermes-agent) and turns your Obsidian vault into a memory layer the agent reads and writes through deterministic CLI / MCP tools. Preferences, signals, evidence, and audit trails are real `.md` files under `Brain/` in the vault you already open in Obsidian every day. You can grep them, version them with git, search them in Obsidian, edit them by hand. No daemon, no vector black box, no hidden state outside the vault.++## Why++- **Lives in your Obsidian vault.** Open `Brain/preferences/pref-no-internal-abbrev.md` in Obsidian and you literally see what your agent learned about you - title, status, evidence count, confidence band, body text. Wikilinks, backlinks, graph view all work.+- **You own the data.** Plain Markdown on your filesystem. No service to cancel, no cloud account, no schema migration when a vendor pivots. Syncthing to your other machines if you want.+- **Memory that learns deterministically.** A `dream` pass turns repeat signals into rules and retires the ones nothing applies any more. Counters and atomic file moves - no LLM inside the algorithm, no surprise hallucinations in your memory.+- **One vault, every agent.** Hermes Agent is the primary integration. Claude Code, OpenAI Codex, Cursor, Aider, OpenClaw, opencode, Grok Build, kiro, Copilot CLI, Gemini CLI, and Pi all plug into the same Brain through MCP.++## One vault, many runtimes++```mermaid+flowchart LR+ Vault[("Your vault<br/>Brain/ - plain Markdown")]+ Hermes["**Hermes Agent**<br/>(primary)"]+ CC[Claude Code]+ Codex[OpenAI Codex]+ Others["Cursor · Aider · OpenClaw<br/>opencode · Grok Build · kiro · Copilot CLI<br/>Gemini CLI · Pi · any MCP host"]++ Hermes <==> Vault+ CC <--> Vault+ Codex <--> Vault+ Others <--> Vault++ style Hermes fill:#1e3a5f,stroke:#90caf9,color:#fff+ style Vault fill:#5d3a9b,stroke:#ce93d8,color:#fff+```++Hermes Agent owns the schedule (dream cron, daily digests, Telegram delivery). Other runtimes participate as readers and writers of the same Brain through MCP - no per-runtime fork of the memory.++## Quick start with Hermes Agent++**The simplest path - let your agent set it up.** Paste this into Hermes (or whichever AI agent already has shell access on the target machine):++> Install Open Second Brain for me by following the steps at <https://github.com/itechmeat/open-second-brain/blob/main/install/hermes.md>. My vault is at `/path/to/your-vault`.++The agent reads the install doc, runs every command, and verifies the result. That's it.++If you prefer running the steps yourself:++```bash+# 1. Install the plugin+hermes plugins install itechmeat/open-second-brain --enable+hermes gateway restart++# 2. Put `o2b` on PATH+~/.hermes/plugins/open-second-brain/scripts/o2b install-cli++# 3. Bootstrap the vault+o2b init --vault /path/to/your-vault --name "My Second Brain"+o2b brain init --vault /path/to/your-vault --primary-agent <agent-name>++# 4. Verify+o2b doctor --vault /path/to/your-vault+```++Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`memory.provider: open-second-brain`) and restart the gateway one more time - the agent now injects `Brain/active.md` into its system prompt, recalls context before each turn, and writes signals through `brain_feedback`, all through the one native provider. Full step-by-step: [`install/hermes.md`](install/hermes.md).++## Other runtimes++| Runtime | Install |+| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |+| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |+| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) |+| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) |+| opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](install/opencode.md) |+| Grok Build | `o2b install --target grok --apply` (MCP in `config.toml` + native hooks) - [`install/grok.md`](install/grok.md) |+| Cursor · Aider · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |+| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |++Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-brain/install.lock.json` so `o2b uninstall --target <name> --apply` removes exactly what it added.++## What you get++- **Your memory as Markdown.** Every rule the agent learns about you is a file under `Brain/` you can open, edit, grep, and version. Obsidian wikilinks, backlinks, and the graph view just work - there is no separate UI to learn.+- **Memory that learns, and forgets, on its own.** A nightly `dream` pass turns repeated corrections into rules and retires the ones nothing uses any more. Deterministic by design: counters and atomic file moves, no LLM guessing inside your memory.+- **One brain, every agent.** Teach a rule in one agent and the next one already knows it - Hermes, Claude Code, Codex, Cursor, and the rest read and write the same vault.+- **You stay in control.** Pin, merge, retire, or roll back any rule from the `o2b` CLI. Every Brain mutation takes a verified snapshot first, so a bad change is one `o2b brain rollback` away.+- **Search that explains itself.** Keyword plus an optional semantic layer over your vault, with results that show why they surfaced and what was missing - not a black box. Opt into a structured per-result score breakdown (`explain`), inline trust metadata (age, superseded, conflict), a relevance threshold that returns nothing rather than weak noise, and reinforcement that lifts memories you have marked useful. Track retrieval quality over time with `brain_eval` and the recall benchmark (hit@k, MRR, answer-containment@k).+- **Conversations survive compaction.** When the host compresses context and rotates the session id, capture and recall stitch the segments back into one conversation - any segment id returns the whole lineage.+- **Memory that cleans itself, on your terms.** `o2b brain hygiene scan` surfaces contested facts, near-duplicate rules, stale derived pages, and never-recalled memories; `apply` executes only the findings you select, and stale pages recompile from their recorded sources with a dry-run preview.+- **A vault that stays fresh, consistent, and scoped.** `o2b search watch` keeps the index live as you edit, debounced and incremental; note identity is Unicode-normalized so the same file is one entry across macOS and Linux devices instead of a phantom cross-device duplicate; and recall accepts an opt-in `agent_scope` so a page marked with an `owner:` is reachable only to its owner while shared pages stay open to all.+- **Knowledge that knows where it came from.** Drop a source document and the agent's extraction becomes cross-referenced entity and concept pages plus a summary page that backlinks the source and lists its connections; N sources become one dated report whose every finding cites the source that flagged it; a derived fact carries a `deduced`/`inferred` provenance level and links back to its premises, and recall trusts an operator-stated rule above a machine-derived one. A fact can declare an `owner:` so multi-agent brains keep separate truth spaces, and a standing-query attention flow surfaces the open loops you declare. The plugin never runs a model itself - the agent owns generation, the vault owns the durable, provenanced record - and every behaviour is opt-in.+- **An index that survives interruption.** Stopping `o2b search watch` mid-sync finishes the in-flight pass at a file boundary before exiting (within `search_shutdown_grace_seconds`) instead of killing it mid-write; an incremental run is already resumable through the unchanged-file fastpath, and `search_resume_reindex` extends that to a full rebuild - an interrupted reindex resumes its staging build instead of starting over, guarded by a signature+[truncated]++# Top CHANGELOG entry excerpt+# Changelog++All notable changes to this project will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [1.11.0] - 2026-06-14++### Added++- **Session Knowledge Synthesis Suite.** Three additive, deterministic,+ language-agnostic units that turn temporal activity into structured,+ queryable, provenance-traced knowledge. Every unit is a new surface; with no+ new surface in use, reads are byte-identical to before, and the kernel never+ calls an LLM (agent-extracted data is stored verbatim; everything else is a+ pure read).+ - **Structured session summary (`o2b brain session-summary`,+ `brain_session_summary`).** A session-scoped digest over four canonical+ categories - request, decisions, learnings, next_steps - stored as one+ append-only continuity record (`session_summary_digest`), distinct from the+ `session_summary_node` recall rollup and the per-line `pre_compact_extract`.+ The agent supplies the already-extracted categories; the kernel validates,+ dedupes by content hash, and appends, never parsing prose into categories.+ An all-empty digest is rejected; absent a write, reads return null.+ - **Idea-lineage provenance tracer (`o2b brain idea-lineage`,+ `brain_idea_lineage`).** A read-only tracer reconstructing how a derived+ artifact was reached as an observation -> synthesis -> conclusion graph. A+ continuity id walks the `sourceRefs` graph (raw turns are observations,+ summaries/extracts/digests synthesis, the queried record the conclusion),+ resolving edges by record id or turn id, cycle-guarded and depth-bounded; a+ preference id adapts the existing `buildBeliefEvolution` lifecycle into the+ same shape. Unknown ids fail with a typed error rather than a silent empty+ chain.+ - **Episodic note-history decomposition (`o2b brain note-history`,+ `brain_note_history`).** Splits a note's git commit chain into recallable+ episodic phases on a deterministic commit-time gap (default 72h) - a+ language-agnostic rule that never depends on commit-message wording. Each+ phase carries the commit subjects, dates, and authors. A missing repo+ reports `available: false` (no fabricated phase); a path with no commits+ reports `available: true` with zero phases (empty is distinct from broken).+ The sanitized read-only git reader gains an additive `path` pathspec filter.++## [1.10.0] - 2026-06-14++### Added++- **Recall & Working-Memory Quality Suite.** Four additive, deterministic,+ language-agnostic units on top of the mature search/recall subsystem. Every+ unit is flag- or surface-gated; with no profile, flag, or new surface in use,+ search and continuity reads are byte-identical to before.+ - **Selectable recall profiles (`o2b search --profile`, `brain_search`+ `profile` field).** Named presets `fast | balanced | thorough` expand to a+ fixed knob tuple over the same bounded axes the self-tuning grid ranges over+ (candidate pool, traversal depth, learned weights, query expansion) and are+ applied through the same `applyTunedParameters` machinery, so a profile and+ a learned grid point stay coherent. An explicitly selected profile takes+ precedence over a persisted self-tuning grid point; an unknown profile name+ fails loud with a typed `SearchError`. No profile selected leaves ranking on+ the existing config path, bit-for-bit.+ - **Usage-driven working-memory decay (`o2b brain continuity rank`).**+ Continuity records are append-only and immutable, so decay is a pure+ read-side weight in `(0, 1]`, never a mutation. `decayWeight` combines+ record age (exponential half-life) with a usage signal derived only from+ existing `recall_telemetry` surfaced-artifact references; a record whose+ sources were never surfaced - such as a session-scoped `pre_compact_extract`+ decision - has no usage and decays by age alone, with no fabricated coupling.+ `rank` lists working-memory records freshest and most-recalled first.+ - **Language-agnostic co-occurrence auto-relate (`o2b brain co-occurrence`).**+ Entities repeatedly co-referenced from the same notes are scored with a+ structural PMI / document-frequency metric over the wikilink graph - link+ incidence only, no natural-language word list in any language, so a+ non-Latin vault scores identically for the same structure. Output is a+ derived, schema-versioned, hashed suggestion artifact (re-validated on read,+ fail-soft); notes are never mutated and an already directly-linked pair is+ never re-suggested. `--write` persists `Brain/link-graph/co-occurrence.json`.+ - **File-context recall (`o2b brain file-context`, `brain_file_context` MCP+ tool).** Given a file path, surface prior vault work that mentions it by+ querying the existing index with terms derived structurally from the path+ (basename + stem, no natural-language processing, no LLM). A size gate skips+ trivial files (default 1500 bytes) and returns an explicit reason rather+ than a fabricated empty hit.++## [1.9.0] - 2026-06-14++### Added++- **Brain Portability & Interop Suite.** Brain content becomes portable in and+ out of a vault, with provenance, and programmatically writable - composing the+ existing portability helpers rather than adding a new subsystem. Every unit is+ an additive new surface; no existing exporter, importer, CLI verb, or MCP tool+ changes behaviour.+ - **Whole-vault bank export/import (`o2b brain bank-export` / `bank-import`).**+ `exportBankBundle` composes the existing exporters - preferences, the page+ link-graph, the page interchange contract, and the read-only sources+ dashboard - into one deterministic, schema-versioned envelope for backup,+ cross-instance migration, or downstream-tool ingest. `importBankBundle`+ reconstructs the part that round-trips (the page graph, delegated to+ `importVaultGraph` under a conflict mode) and reports preferences, page+ contracts, and the sources dashboard as carried-not-restored - no silent+ partial restore. An unsupported bundle schema fails loudly with a typed+ `BankImportError`.+ - **Page interchange contract (`projectPageContracts`).** A pure, read-only+ projection of every user vault page to a stable, schema-versioned record+ (`path`, `kind`, advisory `confidence`/`provenance`, flattened `citations`,+ `aliases`, `freshness`) a downstream importer can consume without knowing+ Open Second Brain internals. Derivation is structural only (frontmatter+ fields, body wikilinks, typed-relation targets, file mtime); an absent+ advisory field is reported as `null`, never synthesised.+ - **`brain_create_note` MCP tool.** Writes an actual vault note file (path ++ frontmatter + content) atomically through `ensureInsideVault` - distinct+ from `brain_note`, which only appends a log line. Refuses path traversal, the+ Brain machinery root, vault-scope-excluded paths, and overwriting an existing+ note, each with a typed error mapped to INVALID_PARAMS.+ - **In-process SDK (`createBrain(vault)`).** A thin façade over the existing+ core functions - bank export/import, graph export/import, preference export,+ `ingestSource`, and `createNote` - plus source-backed reads+ (`listSources`/`getSource`/`deleteSource`) over the `kind: brain-source`+ summary pages. Every method is a one-line delegation; the upstream+ `writeStatus` maps to `ingestSource` (Open Second Brain has no separate+ source status lifecycle). A source id that resolves outside `Brain/sources`+ is treated as not-found and never deleted.++## [1.8.0] - 2026-06-13++### Added++- **Indexer Durability & Resilience Suite.** Interrupting a long index run no+ longer risks losing work or wedging the index. The suite makes cancellation+ cooperative, the watcher shutdown graceful, a+[truncated]++# Related files and observations++## src/core/partner/codegraph.ts+Current optional partner doctor integration detects code project roots, checks for codegraph CLI, checks .codegraph presence, and runs `codegraph status -j <projectPath>`. It never installs or mutates codegraph and skips silently if the CLI is absent.+/**+ * Partner integration with codegraph (https://github.com/colbymchenry/codegraph).+ *+ * OSB never installs, initializes, or writes data for codegraph. This+ * module only detects presence and reports back through the standard+ * doctor `CheckResult` shape so agents (and humans) know whether the+ * partner tool is available, indexed, or missing in the current scope.+ *+ * Detection scope is intentionally narrow: the current working directory+ * plus the top-level siblings of the vault's parent (where users often+ * keep their code projects next to the vault) plus any explicit extras+ * from config. No deep filesystem walk.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { dirname, join, resolve } from "node:path";++import type { CheckResult } from "../types.ts";++const CODE_MANIFESTS: ReadonlyArray<string> = [+ "package.json",+ "pyproject.toml",+ "Cargo.toml",+ "go.mod",+ "tsconfig.json",+ "Gemfile",+ "composer.json",+ "build.gradle",+ "pom.xml",+];++const DEFAULT_LIMIT = 50;++function isDir(path: string): boolean {+ try {+ return statSync(path).isDirectory();+ } catch {+ return false;+ }+}++/**+ * Heuristic check: does `dir` look like a code project root?+ * Requires BOTH a `.git/` directory AND at least one recognised+ * manifest file (the two-signal rule rejects a stray `package.json`+ * inside a notes folder).+ */+export function isCodeProject(dir: string): boolean {+ try {+ if (!existsSync(dir)) return false;+ if (!isDir(join(dir, ".git"))) return false;+ return CODE_MANIFESTS.some((m) => existsSync(join(dir, m)));+ } catch {+ return false;+ }+}++export interface FindCodeProjectsOptions {+ readonly cwd: string;+ readonly vault: string;+ readonly scanExtraPaths?: ReadonlyArray<string>;+ readonly limit?: number;+}++/**+ * Walk the candidate scope (cwd + top-level siblings of `dirname(vault)`+ * + explicit extras) and return every path that passes `isCodeProject`.+ * The scan is bounded at `limit` inspected directories (default 50)+ * so a huge vault parent cannot slow doctor down.+ */+export function findCodeProjects(opts: FindCodeProjectsOptions): string[] {+ const limit = opts.limit ?? DEFAULT_LIMIT;+ const seen = new Set<string>();+ const found: string[] = [];+ let scanned = 0;++ const consider = (raw: string): void => {+ if (scanned >= limit) return;+ const path = resolve(raw);+ if (seen.has(path)) return;+ seen.add(path);+ if (!isDir(path)) return;+ scanned += 1;+ if (isCodeProject(path)) found.push(path);+ };++ consider(opts.cwd);++ const vaultParent = dirname(resolve(opts.vault));+ if (isDir(vaultParent)) {+ let entries: string[] = [];+ try {+ entries = readdirSync(vaultParent);+ } catch {+ entries = [];+ }+ entries.sort((a, b) => a.localeCompare(b));+ for (const name of entries) {+ if (scanned >= limit) break;+ consider(join(vaultParent, name));+ }+ }++ for (const extra of opts.scanExtraPaths ?? []) {+ if (scanned >= limit) break;+ consider(extra);+ }++ return found;+}++export interface CodegraphStatusData {+ readonly initialized: boolean;+ readonly nodeCount?: number;+ readonly fileCount?: number;+ readonly edgeCount?: number;+}++export type CodegraphStatusResult =+ | { readonly ok: true; readonly data: CodegraphStatusData }+ | { readonly ok: false; readonly error: string };++export interface CodegraphCheckDeps {+ readonly whichCodegraph?: () => string | null;+ readonly runStatusJson?: (projectPath: string) => CodegraphStatusResult;+}++export interface CodegraphCheckOptions {+ readonly cwd: string;+ readonly vault: string;+ readonly scanExtraPaths?: ReadonlyArray<string>;+ readonly limit?: number;+ readonly disabled?: boolean;+}++function defaultWhichCodegraph(): string | null {+ if (typeof Bun !== "undefined" && typeof (Bun as { which?: unknown }).which === "function") {+ const found = (Bun as unknown as { which: (cmd: string) => string | null }).which("codegraph");+ return found ?? null;+ }+ return null;+}++function defaultRunStatusJson(projectPath: string): CodegraphStatusResult {+ try {+ const proc = Bun.spawnSync({+ cmd: ["codegraph", "status", "-j", projectPath],+ stdout: "pipe",+ stderr: "pipe",+ });+ const stdout = new TextDecoder().decode(proc.stdout).trim();+ const stderr = new TextDecoder().decode(proc.stderr).trim();+ if (!proc.success) {+ if (stdout) {+ try {+ const parsed = JSON.parse(stdout) as CodegraphStatusData;+ return { ok: true, data: parsed };+ } catch {}+ }+ return { ok: false, error: stderr || `codegraph status exited ${proc.exitCode}` };+ }+ if (!stdout) {+ return { ok: false, error: stderr || "empty status output" };+ }+ const parsed = JSON.parse(stdout) as CodegraphStatusData;+ return { ok: true, data: parsed };+ } catch (exc) {+ return { ok: false, error: (exc as Error).message ?? String(exc) };+ }+}++/**+ * Doctor-grade check for codegraph partnership. Returns `null` (skip,+ * no doctor output) when the current scope is not a code project, when the+ * user has explicitly disabled the check, or when the codegraph CLI is not+ * installed — codegraph is an optional partner OSB never installs, so its+ * absence must not fail doctor.+ *+ * Non-null results carry a single `code_graph` `CheckResult` describing+ * one of three states: `not_indexed`, `ok`, or `error`.+ */+export function checkCodegraph(+ opts: CodegraphCheckOptions,+ deps?: CodegraphCheckDeps,+): CheckResult | null {+ if (opts.disabled) return null;++ const projects = findCodeProjects(opts);+ if (projects.length === 0) return null;++ const project = projects[0]!;+ const whichFn = deps?.whichCodegraph ?? defaultWhichCodegraph;+ const cliPath = whichFn();++ if (!cliPath) {+ // codegraph is an optional partner OSB never installs. If the CLI is not+ // on PATH there is nothing to check — skip silently rather than failing+ // doctor, so `o2b doctor` stays green for users (and CI) without codegraph.+ return null;+ }++ const indexDir = join(project, ".codegraph");+ if (!isDir(indexDir)) {+ return {+ name: "code_graph",+ ok: false,+ message: `code project at ${project}: not indexed (run: codegraph init ${project})`,+ };+ }++ const runFn = deps?.runStatusJson ?? defaultRunStatusJson;+ const status = runFn(project);+ if (!status.ok) {+ return {+ name: "code_graph",+ ok: false,+ message: `code project at ${project}: codegraph status failed: ${status.error}`,+ };+ }++ if (!status.data.initialized) {+ return {+ name: "code_graph",+ ok: false,+ message: `code project at ${project}: not indexed (run: codegraph init ${project})`,+ };+ }++ const nodes = status.data.nodeCount ?? 0;+ const files = status.data.fileCount ?? 0;+ return {+ name: "code_graph",+ ok: true,+ message: `code project at ${project}: indexed (${nodes} nodes, ${files} files)`,+ };+}+++## src/core/brain/link-graph/communities.ts+Current cluster detection is deterministic in-process label propagation over the resolved vault link graph, with cluster note materialization. It is not LLM community labeling and has no batching parameter or partial batch failure concept today.+/**+ * Graph-wide community detection with materialized cluster notes+ * (link-recall-intelligence, t_4ba927ec).+ *+ * `buildConceptCluster` assembles depth-1 backlinks for ONE named+ * target; nothing discovered structure across the whole graph. This+ * pass runs deterministic synchronous label propagation over the+ * resolved doc-level link graph (undirected): labels start as sorted+ * document ids, every sweep assigns each node the most frequent label+ * among its neighbours (lowest label breaks ties), and a fixed+ * iteration cap guarantees termination on oscillating topologies+ * (bipartite stars flip forever under synchronous updates). No+ * Louvain dependency, no randomness - identical input, identical+ * communities.+ *+ * Communities of size >= minSize materialize one derived note each+ * under `Brain/clusters/`. Cluster notes are projections, not prose:+ * members ranked by internal degree, shared entities from the index,+ * link density - synthesis stays with the calling agent (the+ * deep-synthesis rule). Notes are regenerated every run; a note whose+ * community vanished is removed, but ONLY when it carries the+ * generated marker - hand-written files in the directory are never+ * touched.+ */++import { mkdirSync, readdirSync, rmSync } from "node:fs";+import { basename, join } from "node:path";++import type { Store } from "../../search/store.ts";+import { getGraphSnapshot } from "./graph-index.ts";+import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { isoSecond } from "../time.ts";+import { formatFrontmatter, parseFrontmatter } from "../../vault.ts";++export const COMMUNITY_DEFAULT_MIN_SIZE = 4;+export const COMMUNITY_MAX_ITERATIONS = 20;+/** Shared entities listed per cluster note. */+const CLUSTER_TOP_ENTITIES = 5;++export interface CommunityMember {+ readonly path: string;+ /** Edges to other members of the same community. */+ readonly internalDegree: number;+}++export interface Community {+ /**+ * Stable id: the most-central member's vault-relative path with+ * `/` flattened to `-` (basename alone collides when two folders+ * hold same-named hub notes, and colliding ids would overwrite+ * each other's cluster files).+ */+ readonly id: string;+ /** Members ranked by internal degree desc, path asc. */+ readonly members: ReadonlyArray<CommunityMember>;+ readonly size: number;+ /** internal edges / possible edges, [0, 1]. */+ readonly density: number;+}++export interface DetectCommunitiesOptions {+ readonly minSize?: number;+ readonly maxIterations?: number;+ /**+ * Cooperative deadline (t_06784b8d): checkpointed at entry and once+ * per propagation sweep.+ */+ readonly safeguard?: import("../safeguard.ts").Safeguard;+}++/**+ * Deterministic label propagation over the store's resolved link+ * graph. Read-only.+ */+export function detectCommunities(store: Store, opts: DetectCommunitiesOptions = {}): Community[] {+ const minSize = Math.max(2, opts.minSize ?? COMMUNITY_DEFAULT_MIN_SIZE);+ const maxIterations = Math.max(1, opts.maxIterations ?? COMMUNITY_MAX_ITERATIONS);+ opts.safeguard?.checkpoint();++ // Resolved undirected adjacency + pathById come from the memoized+ // graph snapshot (Unit 4): identical structure to the previous+ // per-call rebuild, but O(1) on repeat reads against an unchanged+ // index. Label propagation below is unchanged - the options vary per+ // call, so only the option-independent graph is shared.+ const snapshot = getGraphSnapshot(store);+ const pathById = snapshot.pathById;+ const adjacency = snapshot.adjacency;++ // Synchronous sweeps in sorted-id order; lowest label wins ties.+ const nodes = snapshot.nodesSorted;+ const labels = new Map<number, number>(nodes.map((n) => [n, n]));+ for (let iteration = 0; iteration < maxIterations; iteration++) {+ // Cooperative deadline: abort between sweeps (read-only pass).+ opts.safeguard?.checkpoint();+ let changed = false;+ const next = new Map<number, number>();+ for (const node of nodes) {+ const counts = new Map<number, number>();+ for (const neighbour of adjacency.get(node)!) {+ const label = labels.get(neighbour)!;+ counts.set(label, (counts.get(label) ?? 0) + 1);+ }+ let bestLabel = labels.get(node)!;+ let bestCount = 0;+ for (const [label, count] of counts) {+ if (count > bestCount || (count === bestCount && label < bestLabel)) {+ bestLabel = label;+ bestCount = count;+ }+ }+ next.set(node, bestLabel);+ if (bestLabel !== labels.get(node)) changed = true;+ }+ for (const [node, label] of next) labels.set(node, label);+ if (!changed) break;+ }++ // Group, rank members, compute density. Groups are final-label+ // equivalence classes: when the iteration cap interrupts an+ // oscillating topology, a group is not guaranteed to be a connected+ // component - acceptable for a digest surface, never for routing.+ const groups = new Map<number, number[]>();+ for (const node of nodes) {+ const label = labels.get(node)!;+ const group = groups.get(label);+ if (group) group.push(node);+ else groups.set(label, [node]);+ }++ const communities: Community[] = [];+ for (const ids of groups.values()) {+ if (ids.length < minSize) continue;+ const memberSet = new Set(ids);+ let internalEdges = 0;+ const members = ids+ .map((id) => {+ let degree = 0;+ for (const neighbour of adjacency.get(id)!) {+ if (memberSet.has(neighbour)) degree++;+ }+ internalEdges += degree;+ return { path: pathById.get(id)!, internalDegree: degree };+ })+ .toSorted((a, b) =>+ a.internalDegree !== b.internalDegree+ ? b.internalDegree - a.internalDegree+ : a.path < b.path+ ? -1+ : 1,+ );+ internalEdges /= 2; // each undirected edge counted from both ends+ const possible = (ids.length * (ids.length - 1)) / 2;+ communities.push(+ Object.freeze({+ id: communityId(members[0]!.path),+ members: Object.freeze(members),+ size: ids.length,+ density: possible === 0 ? 0 : internalEdges / possible,+ }),+ );+ }++ return communities.toSorted((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+}++/** Collision-free id: vault-relative path, `/` -> `-`, no `.md`. */+function communityId(relPath: string): string {+ return relPath.replace(/\.md$/u, "").split("/").join("-");+}++// ── materialization ──────────────────────────────────────────────────────────++const GENERATED_KIND = "brain-cluster";++export interface MaterializeClusterNotesResult {+ readonly written: ReadonlyArray<string>;+ readonly removed: ReadonlyArray<string>;+}++function clustersDir(vault: string): string {+ return join(vault, "Brain", "clusters");+}++/**+ * Regenerate one derived note per community and remove generated+ * notes whose community vanished. Hand-written files (no+ * `kind: brain-cluster`) are never touched.+ */+export function materializeClusterNotes(+ vault: string,+ communities: ReadonlyArray<Community>,+ opts: { readonly store: Store; readonly now: Date },+): MaterializeClusterNotesResult {+ const dir = clustersDir(vault);+ mkdirSync(dir, { recursive: true });++ const written: string[] = [];+ const expected = new Set<string>();+ for (const community of communities) {+ const fileName = `cluster-${community.id}.md`;+ expected.add(fileName);+ const path = join(dir, fileName);+ atomicWriteFileSync(path, renderClusterNote(community, opts));+ written.push(`Brain/clusters/${fileName}`);+ }++ // Stale sweep: only generated notes are eligible for removal.+ const removed: string[] = [];+ for (const file of readdirSync(dir).toSorted()) {+ if (!file.endsWith(".md") || expected.has(file)) continue;+ const full = join(dir, file);+ const [meta] = parseFrontmatter(full);+ if (meta["kind"] !== GENERATED_KIND) continue;+ rmSync(full);+ removed.push(`Brain/clusters/${file}`);+ }++ return Object.freeze({ written: Object.freeze(written), removed: Object.freeze(removed) });+}++function renderClusterNote(+ community: Community,+ opts: { readonly store: Store; readonly now: Date },+): string {+ const entities = sharedEntities(opts.store, community);+ const lines: string[] = [+ `# Cluster: ${community.id}`,+ "",+ "Auto-generated by `o2b brain clusters run`. Do not edit - regenerated on",+ "every run; synthesis belongs to the reading agent, not this file.",+ "",+ `${community.size} notes, link density ${community.density.toFixed(2)}.`,+ "",+ "## Members (by internal degree)",+ "",+ ];+ for (const member of community.members) {+ lines.push(+ `- [[${basename(member.path, ".md")}]] (${member.path}) - ${member.internalDegree} internal link(s)`,+ );+ }+ if (entities.length > 0) {+ lines.push("", "## Shared entities", "");+ for (const [entity, count] of entities) {+ lines.push(`- ${entity} (${count} member note(s))`);+ }+ }+ return formatFrontmatter(+ {+ kind: GENERATED_KIND,+ cluster: community.id,+ generated_at: isoSecond(opts.now),+ size: community.size,+ density: community.density.toFixed(2),+ members: community.members.map((m) => m.path),+ },+ lines.join("\n"),+ );+}++/** Entities appearing in >= 2 member notes, by member count desc. */+function sharedEntities(store: Store, community: Community): Array<[string, number]> {+ const counts = new Map<string, number>();+ const summaries = store.listDocuments();+ for (const member of community.members) {+ const summary = summaries.get(member.path);+ if (!summary) continue;+ for (const entity of store.entitiesForDocument(summary.id)) {+ counts.set(entity, (counts.get(entity) ?? 0) + 1);+ }+ }+ return [...counts.entries()]+ .filter(([, count]) => count >= 2)+ .toSorted((a, b) => (a[1] !== b[1] ? b[1] - a[1] : a[0] < b[0] ? -1 : 1))+ .slice(0, CLUSTER_TOP_ENTITIES);+}+++## src/mcp/brain/knowledge-tools.ts excerpt+brain_clusters MCP run/list wraps detectCommunities/materializeClusterNotes. It validates min_size and returns deterministic data.+/**+ * Knowledge graph: foresight, bridge discovery, community clusters, MOC audit, deep synthesis, idea discovery, the claim ledger, and dead ends.+ *+ * Extracted from the former brain-tools.ts monolith; registration+ * happens through the aggregator, which preserves the public+ * BRAIN_TOOLS surface.+ */++import { join } from "node:path";+import { existsSync, readdirSync } from "node:fs";+import { resolveAgentName, resolveTriggerCooldownDays } from "../../core/config.ts";+import { resolveSearchConfig } from "../../core/search/index.ts";+import { Store } from "../../core/search/store.ts";+import { loadSchemaPack } from "../../core/brain/schema-pack.ts";+import {+ acceptBridge,+ bridgePairKey,+ discoverBridges,+ dismissBridge,+ readDismissedBridges,+ writeBridgeProposals,+} from "../../core/brain/link-graph/bridge-discovery.ts";+import {+ detectCommunities,+ materializeClusterNotes,+} from "../../core/brain/link-graph/communities.ts";+import { appendMetric } from "../../core/brain/metrics.ts";+import { parseFrontmatter } from "../../core/vault.ts";+import { createTriggers } 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 { auditMoc, MocAuditError } from "../../core/brain/link-graph/moc-audit.ts";+import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";+import { isoSecond } from "../../core/brain/time.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";+import { listDeadEnds, recordDeadEnd } from "../../core/brain/dead-ends.ts";+import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../../core/brain/temporal/foresight.ts";+import { aggregateQuantities } from "../../core/brain/truth/aggregate.ts";+import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";+import { computeTruthStateWithConflicts } from "../../core/brain/truth/conflicts.ts";+import { appendClaimEvent, readClaimEvents } from "../../core/brain/truth/store.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext, ToolDefinition } from "../tools.ts";+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";+import { coerceStr, coerceBool } from "../coerce.ts";+import { optionalPositiveInt } from "./shared.ts";++/** Forward-looking projection envelope; read-only fold. */+function toolBrainForesight(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const horizonRaw = args["horizon_days"];+ let horizonDays = FORESIGHT_HORIZON_DAYS;+ if (horizonRaw !== undefined && horizonRaw !== null) {+ if (typeof horizonRaw !== "number" || !Number.isInteger(horizonRaw) || horizonRaw < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_foresight: horizon_days must be a positive integer",+ );+ }+ horizonDays = horizonRaw;+ }+ return { ...buildForesight(ctx.vault, { now: new Date(), horizonDays }) };+}++// ----- brain_labels (t_7a41f42d) ---------------------------------------------++/**+ * Bridge discovery over the vec index: discover regenerates the+ * reviewable proposals artifact, accept writes one related wikilink,+ * dismiss persists a pair suppression, list reads the artifact back.+ */+async function toolBrainBridges(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_bridges: operation must be discover|list|accept|dismiss",+ );+ }+ if (op === "accept" || op === "dismiss") {+ const source = args["source"];+ const target = args["target"];+ if (typeof source !== "string" || source.trim() === "") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_bridges ${op}: source must be a vault-relative path`,+ );+ }+ if (typeof target !== "string" || target.trim() === "") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_bridges ${op}: target must be a vault-relative path`,+ );+ }+ if (op === "dismiss") {+ return {+ dismissed: bridgePairKey(source, target),+ added: dismissBridge(ctx.vault, source, target),+ };+ }+ try {+ const pack = loadSchemaPack(ctx.vault);+ return { ...acceptBridge(ctx.vault, source, target, { pack }), source, target };+ } catch (exc) {+ const message = (exc as Error).message ?? String(exc);+ if (/outside the vault|does not exist|link constraint/.test(message)) {+ throw new MCPError(INVALID_PARAMS, `brain_bridges accept: ${message}`);+ }+ throw exc;+ }+ }+ if (op === "list") {+ const path = join(ctx.vault, "Brain", "proposals", "bridges.md");+ if (!existsSync(path)) return { exists: false, proposals: 0 };+ const [meta] = parseFrontmatter(path);+ return {+ exists: true,+ path: "Brain/proposals/bridges.md",+ generated_at: meta["generated_at"] ?? null,+ proposals: Number(meta["proposals"] ?? 0),+ };+ }+ // discover+ const max = args["max"];+ if (max !== undefined && (!Number.isInteger(max) || (max as number) < 1)) {+ throw new MCPError(INVALID_PARAMS, "brain_bridges discover: max must be a positive integer");+ }+ const minSimilarity = args["min_similarity"];+ if (+ minSimilarity !== undefined &&+ (typeof minSimilarity !== "number" || minSimilarity <= 0 || minSimilarity > 1)+ ) {+ throw new MCPError(INVALID_PARAMS, "brain_bridges discover: min_similarity must be in (0, 1]");+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ if (!existsSync(searchConfig.dbPath)) {+ return { vec_available: false, proposals: [], reason: "index not built" };+ }+ const store = await Store.open(searchConfig, { mode: "read" });+ const now = new Date();+ try {+ const dismissed = readDismissedBridges(ctx.vault);+ const report = discoverBridges(store, {+ ...(max !== undefined ? { maxProposals: max as number } : {}),+ ...(minSimilarity !== undefined ? { minSimilarity } : {}),+ dismissed,+ });+ writeBridgeProposals(ctx.vault, report, { now });+ try {+ appendMetric(ctx.vault, {+ surface: "bridge_discovery",+ runAt: isoSecond(now),+ payload: {+ proposals: report.proposals.length,+ scanned_candidates: report.scannedCandidates,+ vec_available: report.vecAvailable,+ dismissed_total: dismissed.size,+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ return {+ vec_available: report.vecAvailable,+ ...(report.reason !== undefined ? { reason: report.reason } : {}),+ scanned_candidates: report.scannedCandidates,+ proposals: report.proposals,+ artifact: "Brain/proposals/bridges.md",+ };+ } finally {+ await store.close();+ }+}++// ----- brain_clusters (t_4ba927ec) --------------------------------------------++/** Graph-wide community detection with materialized cluster notes. */+async function toolBrainClusters(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "run" && op !== "list") {+ throw new MCPError(INVALID_PARAMS, "brain_clusters: operation must be run|list");+ }+ if (op === "list") {+ const dir = join(ctx.vault, "Brain", "clusters");+ if (!existsSync(dir)) return { clusters: [] };+ const clusters = readdirSync(dir)+ .filter((f) => f.endsWith(".md"))+ .toSorted()+ .map((f) => {+ const [meta] = parseFrontmatter(join(dir, f));+ return meta["kind"] === "brain-cluster"+ ? {+ path: `Brain/clusters/${f}`,+ cluster: String(meta["cluster"] ?? ""),+ size: Number(meta["size"] ?? 0),+ density: Number(meta["density"] ?? 0),+ generated_at: String(meta["generated_at"] ?? ""),+ }+ : null;+ })+ .filter((c) => c !== null);+ return { clusters };+ }+ const minSize = args["min_size"];+ if (minSize !== undefined && (!Number.isInteger(minSize) || (minSize as number) < 2)) {+ throw new MCPError(INVALID_PARAMS, "brain_clusters run: min_size must be an integer >= 2");+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ if (!existsSync(searchConfig.dbPath)) {+ return { communities: [], reason: "index not built" };+ }+ const store = await Store.open(searchConfig, { mode: "read" });+ const now = new Date();+ try {+ const communities = detectCommunities(+ store,+ minSize !== undefined ? { minSize: minSize as number } : {},+ );+ co+[truncated]++## src/cli/brain/verbs/clusters.ts excerpt+CLI cluster run/list is deterministic, fail-soft for missing index, and records metrics.+/**+ * `o2b brain clusters run|list` (t_4ba927ec): graph-wide community+ * detection over the search index's link graph. `run` detects+ * communities (deterministic label propagation), materializes one+ * derived note per community under `Brain/clusters/`, removes stale+ * generated notes, and records one `communities` metric. `list`+ * reads the generated notes back. Fail-soft on a missing index.+ *+ * Exit codes: 0 on success/fail-soft skip, 1 on an operational+ * failure, 2 on usage errors.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import {+ detectCommunities,+ materializeClusterNotes,+ COMMUNITY_DEFAULT_MIN_SIZE,+} from "../../../core/brain/link-graph/communities.ts";+import { graphStats } from "../../../core/brain/link-graph/graph-index.ts";+import { appendMetric } from "../../../core/brain/metrics.ts";+import {+ createSafeguard,+ resolveSafeguardTimeoutMs,+ SafeguardTimeoutError,+} from "../../../core/brain/safeguard.ts";+import { isoSecond } from "../../../core/brain/time.ts";+import { resolveSearchConfig } from "../../../core/search/index.ts";+import { Store } from "../../../core/search/store.ts";+import { SearchError } from "../../../core/search/types.ts";+import { parseFrontmatter } from "../../../core/vault.ts";+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";++const USAGE = "usage: o2b brain clusters run [--min-size N] | list [--vault <path>] [--json]";++export async function cmdBrainClusters(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ "min-size": { type: "string" },+ json: { type: "boolean" },+ });+ const asJson = flags["json"] === true;+ const action = positional[0];+ if ((action !== "run" && action !== "list") || positional.length !== 1) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }++ const { config, vault } = brainVerbContext(flags);++ try {+ if (action === "list") {+ const dir = join(vault, "Brain", "clusters");+ if (!existsSync(dir)) {+ if (asJson) okJson({ clusters: [] });+ else ok("no cluster notes yet - run: o2b brain clusters run");+ return 0;+ }+ const clusters = readdirSync(dir)+ .filter((f) => f.endsWith(".md"))+ .toSorted()+ .map((f) => {+ const [meta] = parseFrontmatter(join(dir, f));+ return meta["kind"] === "brain-cluster"+ ? {+ path: `Brain/clusters/${f}`,+ cluster: String(meta["cluster"] ?? ""),+ size: Number(meta["size"] ?? 0),+ density: Number(meta["density"] ?? 0),+ generated_at: String(meta["generated_at"] ?? ""),+ }+ : null;+ })+ .filter((c) => c !== null);+ if (asJson) okJson({ clusters });+ else if (clusters.length === 0) ok("no generated cluster notes");+ else {+ for (const c of clusters) {+ ok(`${c.cluster}: ${c.size} notes, density ${c.density} (${c.path})`);+ }+ }+ return 0;+ }++ // run+ const minSize = parsePositiveInt(flags["min-size"] as string | undefined);+ if (minSize === false) {+ process.stderr.write("brain clusters run: --min-size must be a positive integer\n");+ return 2;+ }++ const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });+ let store: Store;+ try {+ store = await Store.open(searchConfig, { mode: "read" });+ } catch (exc) {+ if (+ exc instanceof SearchError &&+ (exc.code === "INDEX_MISSING" || exc.code === "SCHEMA_MISMATCH")+ ) {+ if (asJson) okJson({ communities: 0, reason: "index not built" });+ else ok("clusters run: search index not initialised - run: o2b search index");+ return 0;+ }+ throw exc;+ }++ const now = new Date();+ try {+ const safeguard = createSafeguard({+ operation: "clusters",+ timeoutMs: resolveSafeguardTimeoutMs("clusters", config ?? undefined),+ });+ const communities = detectCommunities(store, {+ ...(minSize !== undefined ? { minSize } : {}),+ safeguard,+ });+ // O(1) from the snapshot detectCommunities just built (same index+ // revision -> cache hit, no second graph rebuild).+ const stats = graphStats(store, { top: 5 });+ const result = materializeClusterNotes(vault, communities, { store, now });+ try {+ appendMetric(vault, {+ surface: "communities",+ runAt: isoSecond(now),+ payload: {+ communities: communities.length,+ sizes: communities.map((c) => c.size),+ written: result.written.length,+ removed: result.removed.length,+ min_size: minSize ?? COMMUNITY_DEFAULT_MIN_SIZE,+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ if (asJson) {+ okJson({+ communities: communities.map((c) => ({+ id: c.id,+ size: c.size,+ density: c.density,+ members: c.members.map((m) => m.path),+ })),+ graph: {+ documents: stats.documentCount,+ linked_nodes: stats.nodeCount,+ edges: stats.edgeCount,+ top_degree: stats.topByDegree,+ },+ written: result.written,+ removed: result.removed,+ });+ } else if (communities.length === 0) {+ ok("clusters run: no communities at the current threshold");+ ok(` graph: ${stats.nodeCount} linked nodes, ${stats.edgeCount} edges`);+ } else {+ ok(`clusters run: ${communities.length} communit${communities.length === 1 ? "y" : "ies"}`);+ for (const c of communities) {+ ok(` ${c.id}: ${c.size} notes, density ${c.density.toFixed(2)}`);+ }+ ok(` graph: ${stats.nodeCount} linked nodes, ${stats.edgeCount} edges`);+ if (result.removed.length > 0) ok(` removed stale: ${result.removed.join(", ")}`);+ }+ return 0;+ } finally {+ await store.close();+ }+ } catch (exc) {+ const timedOut = exc instanceof SafeguardTimeoutError;+ const message = `clusters ${action} failed: ${(exc as Error).message ?? exc}`;+ if (asJson) {+ okJson({ ok: false, message, ...(timedOut ? { timed_out: true } : {}) });+ return 1;+ }+ return fail(message);+ }+}++function parsePositiveInt(raw: string | undefined): number | undefined | false {+ if (raw === undefined) return undefined;+ const n = Number(raw);+ return Number.isInteger(n) && n > 0 ? n : false;+}+++## tests/cli/brain-clusters.test.ts+/**+ * `o2b brain clusters` CLI surface (t_4ba927ec): run detects+ * communities, materializes derived notes, records the communities+ * metric; list reads them back; the maintenance lane executes the+ * bridges and clusters tasks under its lease.+ */++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 { bootstrapBrain } from "../../src/core/brain/init.ts";+import { indexVault } from "../../src/core/search/indexer.ts";+import { listMetrics } from "../../src/core/brain/metrics.ts";+import { makeConfig } from "../helpers/search-fixtures.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-clusters-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const group = ["team-a", "team-b", "team-c", "team-d"];+ for (const name of group) {+ const others = group+ .filter((g) => g !== name)+ .map((g) => `[[${g}]]`)+ .join(" ");+ writeFileSync(join(vault, `${name}.md`), `# ${name}\n\nSee ${others}.\n`);+ }+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++async function index(): Promise<void> {+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+}++test("run on an unindexed vault exits 0 with a reason", async () => {+ const r = await runCli(["brain", "clusters", "run", "--vault", vault, "--json"]);+ expect(r.returncode).toBe(0);+ expect(JSON.parse(r.stdout)).toMatchObject({ communities: 0, reason: "index not built" });+});++test("run materializes the community, records the metric, list reads it back", async () => {+ await index();+ const run = await runCli(["brain", "clusters", "run", "--vault", vault, "--json"]);+ expect(run.returncode).toBe(0);+ const parsed = JSON.parse(run.stdout) as {+ communities: Array<{ id: string; size: number }>;+ written: string[];+ graph: { documents: number; linked_nodes: number; edges: number };+ };+ expect(parsed.communities).toHaveLength(1);+ expect(parsed.communities[0]!.size).toBe(4);+ expect(parsed.written).toHaveLength(1);+ // Unit 4: O(1) graph stats from the precomputed snapshot. The seeded+ // 4-clique has 4 linked nodes and 6 undirected edges.+ expect(parsed.graph.linked_nodes).toBe(4);+ expect(parsed.graph.edges).toBe(6);++ const metrics = listMetrics(vault, { surface: "communities" });+ expect(metrics).toHaveLength(1);+ expect(metrics[0]!.payload).toMatchObject({ communities: 1, written: 1 });++ const list = await runCli(["brain", "clusters", "list", "--vault", vault, "--json"]);+ const listed = JSON.parse(list.stdout) as { clusters: Array<{ size: number }> };+ expect(listed.clusters).toHaveLength(1);+ expect(listed.clusters[0]!.size).toBe(4);+});++test("min-size above the community suppresses it", async () => {+ await index();+ const run = await runCli([+ "brain",+ "clusters",+ "run",+ "--min-size",+ "5",+ "--vault",+ vault,+ "--json",+ ]);+ expect(JSON.parse(run.stdout)).toMatchObject({ communities: [] });+});++test("maintenance lane executes the bridges and clusters tasks", async () => {+ // dream needs an initialised Brain config.+ const configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ const r = await runCli(["brain", "maintenance", "run", "--vault", vault, "--json"]);+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout) as {+ verdict: string;+ tasks: Array<{ name: string; ok: boolean }>;+ };+ expect(parsed.verdict).toBe("run");+ const names = parsed.tasks.map((t) => t.name);+ expect(names).toEqual(["dream", "reindex", "bridges", "clusters"]);+ expect(parsed.tasks.every((t) => t.ok)).toBe(true);+ // The lane's reindex built the index, so both passes left a metric.+ expect(listMetrics(vault, { surface: "bridge_discovery" })).toHaveLength(1);+ expect(listMetrics(vault, { surface: "communities" })).toHaveLength(1);+});++test("usage errors exit 2", async () => {+ const r = await runCli(["brain", "clusters", "nope", "--vault", vault]);+ expect(r.returncode).toBe(2);+ const bad = await runCli(["brain", "clusters", "run", "--min-size", "0", "--vault", vault]);+ expect(bad.returncode).toBe(2);+});+++## tests/core/partner/codegraph.test.ts excerpt+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ checkCodegraph,+ findCodeProjects,+ isCodeProject,+} from "../../../src/core/partner/codegraph.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-codegraph-partner-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function makeRepo(dir: string, manifest: string = "package.json"): string {+ mkdirSync(dir, { recursive: true });+ mkdirSync(join(dir, ".git"));+ writeFileSync(join(dir, manifest), "{}\n");+ return dir;+}++function makeIndexed(dir: string): void {+ mkdirSync(join(dir, ".codegraph"), { recursive: true });+ writeFileSync(join(dir, ".codegraph", "codegraph.db"), "");+}++describe("isCodeProject", () => {+ test("empty directory is not a code project", () => {+ expect(isCodeProject(tmp)).toBe(false);+ });++ test(".git alone is not enough", () => {+ mkdirSync(join(tmp, ".git"));+ expect(isCodeProject(tmp)).toBe(false);+ });++ test("manifest alone is not enough", () => {+ writeFileSync(join(tmp, "package.json"), "{}\n");+ expect(isCodeProject(tmp)).toBe(false);+ });++ test(".git + package.json -> code project", () => {+ makeRepo(tmp);+ expect(isCodeProject(tmp)).toBe(true);+ });++ test(".git + tsconfig.json -> code project", () => {+ makeRepo(tmp, "tsconfig.json");+ expect(isCodeProject(tmp)).toBe(true);+ });++ test(".git + pyproject.toml -> code project", () => {+ makeRepo(tmp, "pyproject.toml");+ expect(isCodeProject(tmp)).toBe(true);+ });++ test(".git + Cargo.toml -> code project", () => {+ makeRepo(tmp, "Cargo.toml");+ expect(isCodeProject(tmp)).toBe(true);+ });++ test(".git + go.mod -> code project", () => {+ makeRepo(tmp, "go.mod");+ expect(isCodeProject(tmp)).toBe(true);+ });++ test("non-existent dir -> false", () => {+ expect(isCodeProject(join(tmp, "missing"))).toBe(false);+ });+});++describe("findCodeProjects", () => {+ test("cwd as a code project is included", () => {+ const repo = makeRepo(join(tmp, "repo"));+ const out = findCodeProjects({ cwd: repo, vault: join(tmp, "vault") });+ expect(out).toContain(repo);+ });++ test("empty scope yields empty result", () => {+ mkdirSync(join(tmp, "vault"));+ mkdirSync(join(tmp, "vault-sibling"));+ const out = findCodeProjects({ cwd: tmp, vault: join(tmp, "vault") });+ expect(out).toEqual([]);+ });++ test("vault parent siblings are inspected", () => {+ const vault = join(tmp, "vault");+ mkdirSync(vault);+ const sibling = makeRepo(join(tmp, "my-app"));+ const out = findCodeProjects({ cwd: vault, vault });+ expect(out).toContain(sibling);+ });++ test("does not descend below depth 1 in vault parent", () => {+ const vault = join(tmp, "vault");+ mkdirSync(vault);+ const nested = makeRepo(join(tmp, "outer", "inner", "deep-repo"));+ const out = findCodeProjects({ cwd: vault, vault });+ expect(out).not.toContain(nested);+ });++ test("honors scanExtraPaths", () => {+ mkdirSync(join(tmp, "vault"));+ const extra = makeRepo(join(tmp, "elsewhere", "ext-repo"));+ const out = findCodeProjects({+ cwd: join(tmp, "vault"),+ vault: join(tmp, "vault"),+ scanExtraPaths: [extra],+ });+ expect(out).toContain(extra);+ });++ test("dedupes overlapping scopes", () => {+ const repo = makeRepo(join(tmp, "repo"));+ const out = findCodeProjects({+ cwd: repo,+ vault: join(tmp, "vault"),+ scanExtraPaths: [repo],+ });+ expect(out.filter((p: string) => p === repo).length).toBe(1);+ });++ test("bails out at the scan limit", () => {+ const vault = join(tmp, "vault");+ mkdirSync(vault);+ for (let i = 0; i < 60; i++) {+ makeRepo(join(tmp, `repo-${i}`));+ }+ const out = findCodeProjects({ cwd: vault, vault, limit: 10 });+ expect(out.length).toBeLessThanOrEqual(10);+ });+});++describe("checkCodegraph", () => {+ test("null when nothing in scope is a code project", () => {+ mkdirSync(join(tmp, "vault"));+ const r = checkCodegraph(+ { cwd: tmp, vault: join(tmp, "vault") },+ { whichCodegraph: () => null },+ );+ expect(r).toBeNull();+ });++ test("null when disabled", () => {+ const repo = makeRepo(join(tmp, "repo"));+ const r = checkCodegraph(+ { cwd: repo, vault: join(tmp, "vault"), disabled: true },+ { whichCodegraph: () => "/usr/bin/codegraph" },+ );+ expect(r).toBeNull();+ });++ test("code project + no CLI -> skipped (codegraph is optional)", () => {+ // OSB never installs codegraph; its absence is normal, not a doctor+ // failure. When the CLI is not on PATH the check is skipped entirely so+ // `o2b doctor` stays green for the many users without codegraph.+ const repo = makeRepo(join(tmp, "repo"));+ const r = checkCodegraph(+ { cwd: repo, vault: join(tmp, "vault") },+ { whichCodegraph: () => null },+ );+ expect(r).toBeNull();+ });++ test("code project + CLI + no .codegraph/ -> not_indexed", () => {+ const repo = makeRepo(join(tmp, "repo"));+ const r = checkCodegraph(+ { cwd: repo, vault: join(tmp, "vault") },+ { whichCodegraph: () => "/usr/bin/codegraph" },+ );+ expect(r!.ok).toBe(false);+ expect(r!.message.toLowerCase()).toContain("not indexed");+ expect(r!.message).toContain("codegraph init");+ });++ test("code project + CLI + indexed + status ok -> ok", () => {+ const repo = makeRepo(join(tmp, "repo"));+ makeIndexed(repo);+ const r = checkCodegraph(+ { cwd: repo, vault: join(tmp, "vault") },+ {+ whichCodegraph: () => "/usr/bin/codegraph",+ runStatusJson: () => ({+ ok: true,+ data: { initialized: true, nodeCount: 4737, fileCount: 392, edgeCount: 11342 },+ }),+ },+ );+ expect(r!.ok).toBe(true);+ expect(r!.message).toContain("4737");+ expect(r!.message).toContain("392");+ });++ test("status reports initialized:false -> not_indexed", () => {+ const repo = makeRepo(join(tmp, "repo"));+ makeIndexed(repo);+ const r = checkCodegraph(+ { cwd: repo, vault: join(tmp, "vault") },+ {+ whichCodegraph: () => "/usr/bin/codegraph",+ runStatusJson: () => ({ ok: true, data: { initialized: false } }),+ },+ );+ expect(r!.ok).toBe(false);+ expect(r!.message.toLowerCase()).toContain("not indexed");+ });++ test("status returns an error -> error state surfaced", () => {+ const repo = makeRepo(join(tmp, "repo"));+ makeIndexed(repo);+ const r = checkCodegraph(+ { cwd: repo, vault: join(tmp, "vault") },+ {+ whichCodegraph: () => "/usr/bin/codegraph",+ runStatusJson: () => ({ ok: false, error: "stale lock" }),+ },+ );+ expect(r!.ok).toBe(false);+ expect(r!.message.toLowerCase()).toContain("stale lock");+ });++ test("falls back to real PATH lookup when no whichCodegraph dep provided", () => {+ const repo = makeRepo(join(tmp, "repo"));+ // No injected dep -> real PATH lookup. The result is environment-dependent+ // (null when codegraph is not installed, a code_graph result when it is),+ // so assert only that the fallback wiring runs without throwing and yields+ // a well-formed value either way.+ const r = checkCodegraph({ cwd: repo, vault: join(tmp, "vault") });+ expect(r === null || r.name === "code_graph").toBe(true);+ });+});+++# Docs index+- docs/architecture.md+- docs/brainstorm/agent-boundary-control-surfaces/README.md+- docs/brainstorm/agent-boundary-control-surfaces/cli-output/claude.md+- docs/brainstorm/agent-boundary-control-surfaces/cli-output/prompt.md+- docs/brainstorm/agent-boundary-control-surfaces/design.md+- docs/brainstorm/agent-boundary-control-surfaces/plan.md+- docs/brainstorm/agent-boundary-control-surfaces/variants.md+- docs/brainstorm/agent-capability-cli-integration/README.md+- docs/brainstorm/agent-capability-cli-integration/adr.md+- docs/brainstorm/agent-capability-cli-integration/cli-output/claude.md+- docs/brainstorm/agent-capability-cli-integration/cli-output/prompt.md+- docs/brainstorm/agent-capability-cli-integration/context.md+- docs/brainstorm/agent-capability-cli-integration/design.md+- docs/brainstorm/agent-capability-cli-integration/implementation-notes.md+- docs/brainstorm/agent-capability-cli-integration/notes.md+- docs/brainstorm/agent-capability-cli-integration/phase-log.md+- docs/brainstorm/agent-capability-cli-integration/plan.md+- docs/brainstorm/agent-capability-cli-integration/pr-notes.md+- docs/brainstorm/agent-capability-cli-integration/scope.md+- docs/brainstorm/agent-capability-cli-integration/task-body.md+- docs/brainstorm/agent-capability-cli-integration/test-matrix.md+- docs/brainstorm/agent-capability-cli-integration/variants.md+- docs/brainstorm/agent-capability-cli-integration/verification.md+- docs/brainstorm/agent-surface-suite/cli-output/claude.md+- docs/brainstorm/agent-surface-suite/cli-output/prompt.md+- docs/brainstorm/agent-surface-suite/design.md+- docs/brainstorm/agent-surface-suite/plan.md+- docs/brainstorm/agent-surface-suite/variants.md+- docs/brainstorm/agent-write-contract-suite/cli-output/claude.md+- docs/brainstorm/agent-write-contract-suite/cli-output/prompt.md+- docs/brainstorm/agent-write-contract-suite/design.md+- docs/brainstorm/agent-write-contract-suite/plan.md+- docs/brainstorm/agent-write-contract-suite/variants.md+- docs/brainstorm/auto-migrate-on-upgrade/design.md+- docs/brainstorm/auto-migrate-on-upgrade/plan.md+- docs/brainstorm/auto-migrate-on-upgrade/variants.md+- docs/brainstorm/brain-centric-layout/design.md+- docs/brainstorm/brain-centric-layout/plan.md+- docs/brainstorm/brain-integrity-suite/cli-output/claude.md+- docs/brainstorm/brain-integrity-suite/cli-output/prompt.md+- docs/brainstorm/brain-integrity-suite/design.md+- docs/brainstorm/brain-integrity-suite/plan.md+- docs/brainstorm/brain-integrity-suite/pr-body.md+- docs/brainstorm/brain-integrity-suite/variants.md+- docs/brainstorm/brain-lifecycle-review-suite/cli-output/claude.md+- docs/brainstorm/brain-lifecycle-review-suite/cli-output/prompt.md+- docs/brainstorm/brain-lifecycle-review-suite/design.md+- docs/brainstorm/brain-lifecycle-review-suite/plan.md+- docs/brainstorm/brain-lifecycle-review-suite/variants.md+- docs/brainstorm/brain-lifecycle-suite/cli-output/claude.md+- docs/brainstorm/brain-lifecycle-suite/cli-output/prompt.md+- docs/brainstorm/brain-lifecycle-suite/design.md+- docs/brainstorm/brain-lifecycle-suite/plan.md+- docs/brainstorm/brain-lifecycle-suite/variants.md+- docs/brainstorm/brain-model-semantics-foundation/adr.md+- docs/brainstorm/brain-model-semantics-foundation/cli-output/claude.md+- docs/brainstorm/brain-model-semantics-foundation/cli-output/prompt.md+- docs/brainstorm/brain-model-semantics-foundation/design.md+- docs/brainstorm/brain-model-semantics-foundation/plan.md+- docs/brainstorm/brain-model-semantics-foundation/variants.md+- docs/brainstorm/brain-portability-interop/cli-output/claude.md+- docs/brainstorm/brain-portability-interop/cli-output/prompt.md+- docs/brainstorm/brain-portability-interop/design.md+- docs/brainstorm/brain-portability-interop/plan.md+- docs/brainstorm/brain-portability-interop/variants.md+- docs/brainstorm/brain-safety-governance-suite/cli-output/claude.md+- docs/brainstorm/brain-safety-governance-suite/cli-output/prompt.md+- docs/brainstorm/brain-safety-governance-suite/design.md+- docs/brainstorm/brain-safety-governance-suite/plan.md+- docs/brainstorm/brain-safety-governance-suite/variants.md+- docs/brainstorm/cjk-schema-lifecycle-recovery/cli-output/claude.md+- docs/brainstorm/cjk-schema-lifecycle-recovery/cli-output/prompt.md+- docs/brainstorm/cjk-schema-lifecycle-recovery/design.md+- docs/brainstorm/cjk-schema-lifecycle-recovery/plan.md+- docs/brainstorm/cjk-schema-lifecycle-recovery/variants.md+- docs/brainstorm/context-continuity-receipts-suite/cli-output/claude.md+- docs/brainstorm/context-continuity-receipts-suite/cli-output/prompt.md+- docs/brainstorm/context-continuity-receipts-suite/design.md+- docs/brainstorm/context-continuity-receipts-suite/plan.md+- docs/brainstorm/context-continuity-receipts-suite/variants.md+- docs/brainstorm/continuity-hygiene-freshness/cli-output/claude.md+- docs/brainstorm/continuity-hygiene-freshness/cli-output/prompt.md+- docs/brainstorm/continuity-hygiene-freshness/design.md+- docs/brainstorm/continuity-hygiene-freshness/plan.md+- docs/brainstorm/continuity-hygiene-freshness/variants.md+- docs/brainstorm/cross-agent-query-foundation/cli-output/claude.md+- docs/brainstorm/cross-agent-query-foundation/cli-output/prompt.md+- docs/brainstorm/cross-agent-query-foundation/design.md+- docs/brainstorm/cross-agent-query-foundation/plan.md+- docs/brainstorm/cross-agent-query-foundation/variants.md+- docs/brainstorm/embedding-provider-suite/cli-output/claude.md+- docs/brainstorm/embedding-provider-suite/cli-output/prompt.md+- docs/brainstorm/embedding-provider-suite/design.md+- docs/brainstorm/embedding-provider-suite/plan.md+- docs/brainstorm/embedding-provider-suite/variants.md+- docs/brainstorm/entity-truth-dream-suite/cli-output/claude.md+- docs/brainstorm/entity-truth-dream-suite/cli-output/prompt.md+- docs/brainstorm/entity-truth-dream-suite/design.md+- docs/brainstorm/entity-truth-dream-suite/plan.md+- docs/brainstorm/entity-truth-dream-suite/variants.md+- docs/brainstorm/grok-native-integration/cli-output/claude.md+- docs/brainstorm/grok-native-integration/cli-output/prompt.md+- docs/brainstorm/grok-native-integration/design.md+- docs/brainstorm/grok-native-integration/plan.md+- docs/brainstorm/grok-native-integration/variants.md+- docs/brainstorm/hermes-memory-provider/cli-output/claude.md+- docs/brainstorm/hermes-memory-provider/cli-output/prompt.md+- docs/brainstorm/hermes-memory-provider/design.md+- docs/brainstorm/hermes-memory-provider/plan.md+- docs/brainstorm/hermes-memory-provider/variants.md+- docs/brainstorm/hermes-static-tool-schemas/cli-output/claude.md+- docs/brainstorm/hermes-static-tool-schemas/cli-output/prompt.md+- docs/brainstorm/hermes-static-tool-schemas/design.md+- docs/brainstorm/hermes-static-tool-schemas/plan.md+- docs/brainstorm/hermes-static-tool-schemas/variants.md+- docs/brainstorm/hook-update-resilience/design.md+- docs/brainstorm/hook-update-resilience/plan.md+- docs/brainstorm/hook-update-resilience/variants.md+- docs/brainstorm/indexer-durability/cli-output/claude.md+- docs/brainstorm/indexer-durability/cli-output/prompt.md+- docs/brainstorm/indexer-durability/design.md+- docs/brainstorm/indexer-durability/plan.md+- docs/brainstorm/indexer-durability/variants.md+- docs/brainstorm/knowledge-provenance/cli-output/claude.md+- docs/brainstorm/knowledge-provenance/cli-output/prompt.md+- docs/brainstorm/knowledge-provenance/design.md+- docs/brainstorm/knowledge-provenance/plan.md+- docs/brainstorm/knowledge-provenance/variants.md+- docs/brainstorm/language-agnostic-fact-extraction/cli-output/claude.md+- docs/brainstorm/language-agnostic-fact-extraction/cli-output/prompt.md+- docs/brainstorm/language-agnostic-fact-extraction/design.md+- docs/brainstorm/language-agnostic-fact-extraction/plan.md+- docs/brainstorm/language-agnostic-fact-extraction/variants.md+- docs/brainstorm/link-graph-surfaces/cli-output/claude.md+- docs/brainstorm/link-graph-surfaces/cli-output/prompt.md+- docs/brainstorm/link-graph-surfaces/design.md+- docs/brainstorm/link-graph-surfaces/plan.md+- docs/brainstorm/link-graph-surfaces/variants.md+- docs/brainstorm/link-recall-intelligence/cli-output/claude.md+- docs/brainstorm/link-recall-intelligence/cli-output/prompt.md+- docs/brainstorm/link-recall-intelligence/design.md+- docs/brainstorm/link-recall-intelligence/plan.md+- docs/brainstorm/link-recall-intelligence/variants.md+- docs/brainstorm/mcp-context-economy/cli-output/claude.md+- docs/brainstorm/mcp-context-economy/cli-output/prompt.md+- docs/brainstorm/mcp-context-economy/design.md+- docs/brainstorm/mcp-context-economy/plan.md+- docs/brainstorm/mcp-context-economy/variants.md+- docs/brainstorm/memory-integrity/cli-output/claude.md+- docs/brainstorm/memory-integrity/cli-output/prompt.md+- docs/brainstorm/memory-integrity/design.md+- docs/brainstorm/memory-integrity/plan.md+- docs/brainstorm/memory-integrity/variants.md+- docs/brainstorm/memory-observability-suite/atof-atif-mapping.md+- docs/brainstorm/memory-observability-suite/cli-output/claude.md+- docs/brainstorm/memory-observability-suite/cli-output/prompt.md+- docs/brainstorm/memory-observability-suite/design.md+- docs/brainstorm/memory-observability-suite/plan.md+- docs/brainstorm/memory-observability-suite/variants.md+- docs/brainstorm/opencode-native-integration/cli-output/claude.md++# Active Brain preferences relevant to this design+---+kind: brain-active+generated_at: 2026-06-14T14:16:01Z+---++# Active Brain Preferences++Auto-generated by `dream`. Do not edit — changes will be overwritten.++## Confirmed (30)++- `pref-no-exclamation-marks-in-docs` (scope: writing, confidence: high (0.95)) — Do NOT use exclamation marks in technical documentation; use neutral, measured punctuation.+- `pref-agents-use-user-chat-language` (confidence: medium (0.52)) — Every agent that sends a user-facing message MUST write that message in the language of the user's most recent inbound chat reply, detected at runtime from the visible task / session context. Do NOT hardcode any specific language (Russian, English, Chinese, etc.) — what the chat language is today may be different tomorrow. Skill / instruction source files stay in the project's authoring language (English by convention); only the OUTBOUND user message translates. Also: do NOT name specific users (Sergey, etc.) in skill files, workflows, or shared rules — the user identity is server-specific runtime context, not part of the rule.+- `pref-full-product-name-in-public` (scope: writing, confidence: medium (0.51)) — В публичных материалах Open Second Brain (release notes, README, документация, code comments, agent skills, картинки, CHANGELOG) использовать полное название "Open Second Brain", не аббревиатуру "OSB". Аббревиатуру "OSB" оператор использует только в личной переписке для краткости.+- `pref-no-claude-code-marker-in-public` (scope: writing, confidence: medium (0.51)) — Не добавлять "🤖 Generated with [Claude Code](https://claude.com/claude-code)" или подобные маркеры авторства AI в публичные артефакты Open Second Brain (release notes, PR descriptions, commit messages для public-facing коммитов). Co-Authored-By trailer в commit messages допустим, но не visible AI-маркеры в prose.+- `pref-description-is-not-authorization` (confidence: low (0.00)) — When the user describes a rule, fix, or desired change during a discussion — even with imperative-sounding phrasing like "давай так:" or "пусть агент делает X" — that is design intent, NOT authorization to edit code/skills/configs. In observation mode (and generally during planning), wait for an unambiguous per-action go-ahead like "правь / фиксим / поехали / сделай это сейчас" before touching files. The single exception in observation mode is appending to the agreed observation log (Issues.md); everything else needs explicit per-edit approval.+- `pref-diagram-connectors-clean-orthogonal` (scope: writing, confidence: low) — Соединительные/обратные стрелки в SVG-диаграммах должны быть аккуратными: прямые сегменты или ортогональный маршрут со скруглёнными углами (H/V + Q-скругления, stroke-linejoin round), якорённые к краям блоков. НЕ диагональные кривые Безье со случайными контрольными точками, которые выглядят криво. Якорить концы к реальным граням блоков, не стартовать из пустого места под углом.+- `pref-frontx-native-only-when-learning-frontx` (scope: coding, confidence: low (0.33)) — При обучении/тренировке FrontX использовать исключительно FrontX-native подходы (EventBus, slices, actions, lifecycle, federation shared) — не заменять их vanilla-альтернативами ради «упрощения».+- `pref-language-agnostic-search` (scope: coding, confidence: low) — Поиск и классификация в Open Second Brain должны быть языко-независимыми: нельзя гейтить, классифицировать, ранжировать или извлекать поведение по захардкоженным спискам слов естественного языка (приветствия, стоп-слова, ключевые слова, отрицания) — ни на одном языке. Вместо этого: структурные сигналы, явные поля frontmatter, частота в корпусе (document-frequency/IDF), либо извлечение агентом/LLM.+- `pref-merge-on-github-approval-not-chat` (scope: git, confidence: low (0.21)) — Когда репозиторий имеет branch protection с required approval, агент использует GitHub PR approval как signal к merge, а не chat-подтверждение. Это значит: agent отправляет PR, опрашивает `gh pr view --json reviewDecision` (или включает `gh pr merge --auto`), и при `APPROVED` автоматически делает squash merge без дополнительного "ок" в чате. Stop-point остаётся, но он signal-based.+- `pref-meta-conventions-allowed-in-skills` (scope: orchestration, confidence: low) — Skills MAY include meta-level directives that tell agents to follow the host system's own conventions ("use Hermes conventions for X"), pointing the agent back at the system as source of truth. These are NOT crutches. What stays forbidden is concrete content that encodes specifics of those conventions in the skill itself (direction, scale, ordering rules, anti-X warnings). The distinction: meta = "follow Hermes for X" (allowed). Concrete = "Hermes priority direction is DESC" / "P1 means top" (crutch).+- `pref-never-propose-hermes-convention-violations` (scope: orchestration, confidence: low (0.21)) — Никогда не предлагать пользователю решения, которые отходят от конвенций или schema-design Hermes. Если Hermes имеет `DEFAULT 0` - не предлагать `NULL`. Если Hermes сортирует `ORDER BY priority DESC` - не предлагать инвертировать сортировку. Любое отклонение от Hermes должно идти ТОЛЬКО как явный bugfix самого Hermes (через upstream PR), не как локальный divergent workaround. Если предлагаешь вариант - сначала проверяй: не предлагает ли он отойти от Hermes intent. Прецедент: предложение менять `priority=0` на `NULL` для семантики "не оценено" - схема Hermes уже использует 0 как default, NULL это divergence.+- `pref-no-automerge-without-operator-request` (scope: process, confidence: low) — Не включать auto-merge на PR, пока оператор явно не попросил мержить: на репозитории без branch protection `gh pr merge --auto` сливает мгновенно, до ревью. Если оператор просил дождаться ревью (CodeRabbit или своего) — PR должен оставаться открытым до вердикта; merge — отдельное явное действие оператора.+- `pref-no-em-dashes` (scope: writing, confidence: low) — Never use long (em) dashes in generated texts (posts, docs, copy, любые материалы). Use a regular hyphen, colon, or restructure the sentence instead.+- `pref-no-em-dashes-ever` (scope: writing, confidence: low) — Никогда не использовать длинные тире (em dash) в любых текстах: чат, документы, комментарии, релизы. Заменять обычным дефисом, запятой или перестройкой фразы. Правило вечное, заявлено оператором явно.+- `pref-no-em-dashes-russian-writing` (scope: writing, confidence: low (0.14)) — Forbidden to use em-dashes (long dashes, U+2014 «—») in Russian-language content I write for this user — blog posts, documentation, Telegram messages, any user-facing prose. Use regular hyphens with surrounding spaces ( - ) instead. This applies to ALL Russian writing for them, not just one post. The rule is explicit and was reinforced by manual file edits replacing every em-dash with a hyphen.+- `pref-no-priority-direction-in-skills` (scope: orchestration, confidence: low) — Skills, references, and playbooks for Hermes agents MUST NOT describe priority direction at all - not via 'higher = more important', not via 'matches ORDER BY DESC', not via examples that imply direction. Even a 'factual SQL-mechanic description' inside a skill is a crutch. The agent is a Hermes agent and must learn priority semantics natively from Hermes itself (source code, --help, dispatcher behavior). Skill text may state only what the field is (integer, default 0) and CLI usage (pass a number, not a string).+- `pref-no-typescript-cast-crutches` (scope: coding, confidence: low) — Forbidden to use `as` / `as unknown as <T>` TypeScript casts as a shortcut to silence type errors caused by inadequate object construction. Build the value with the correct type from the start — use object literals with conditional spreads (`...(value !== undefined ? { field: value } : {})`), narrowing functions that return the correct literal type, or split builders. `as` is a code smell indicating the value's construction shape doesn't match the contract; fix the construction, don't cast around it. Exceptions: legitimate framework boundaries (e.g. JSON.parse → typed shape after validation), `as const` for literal narrowing, `satisfies` for shape checks.+- `pref-outbound-default-english` (scope: writing, confidence: low) — Тексты от имени оператора (Zulip, YouTrack, Outline, почта) по умолчанию пиши на английском. На русском — только если оператор явно попросил, либо если по истории Zulip видно, что с этим адресатом он общается на русском (основной язык общения помечен в списке коллег в CLAUDE.md). Это правило про OUTBOUND-контент, а не про язык диалога со мной (диалог — русский).+- `pref-plain-language-actionable-only` (scope: communication, confidence: low) — Объяснять простыми словами, без академической терминологии и жаргона (аудитория может быть нетехнической, напр. фронтендер). Предлагать только действенные решения, без длинных рассуждений о том, что НЕ подходит.+- `pref-release-diagram-style-v33-35` (scope: writing, confidence: low) — Релизные диаграммы Open Second Brain делать в подходе релизов v0.33-v0.35 (и+[truncated]++# Constraints to consider+- The two task cards are upstream Graphify-inspired, but Open Second Brain currently integrates with the optional `codegraph` partner, not Graphify as an owned runtime dependency.+- `t_a1e76788` requests Rust Cargo workspace dependency operational readability around code graph extraction and internal crate dependency edges.+- `t_a286135c` mentions Graphify multi-batch community labeling, but Open Second Brain currently has deterministic graph-wide cluster detection, not LLM labeling. Treat this as an operational readability/robustness opportunity only if it fits existing surfaces without inventing an LLM labeling subsystem.+- Prefer additive, option-gated behavior with typed errors and honest absent-data reports. Existing behavior should remain byte-identical unless a new flag/surface is used.diff --git a/docs/brainstorm/codegraph-mcp-operational-readability/design.md b/docs/brainstorm/codegraph-mcp-operational-readability/design.mdnew file mode 100644index 00000000..b02fa1f5--- /dev/null+++ b/docs/brainstorm/codegraph-mcp-operational-readability/design.md@@ -0,0 +1,85 @@+# CodeGraph and MCP operational readability design++## Problem++Open Second Brain has two adjacent graph operations that are hard for agents to inspect precisely. The optional `codegraph` partner check tells an operator whether a code project is indexed, but it does not expose a structured report that answers Rust workspace questions such as which Cargo workspace members were detected and whether crate-level dependency information is available. The Brain cluster surface runs deterministic community detection, but the only tunable control is `min_size`; large-vault operators do not have a documented, option-gated way to run the pass in bounded chunks or inspect partial progress without changing the default behavior.++The release must improve operational readability without turning Graphify into an owned Open Second Brain dependency, without adding natural-language labeling, and without changing existing default reads.++## Scope++- Add a first-class, read-only CodeGraph report surface for CLI and MCP consumers.+- Detect Cargo workspace membership structurally from `Cargo.toml` when a code project is in scope.+- Report partner status honestly: CLI absent, project not indexed, status unavailable, or indexed with known counts.+- Add an option-gated batched cluster run path that keeps the existing default `brain_clusters` behavior byte-identical when no batch option is supplied.+- Document and test the new surfaces through focused unit and CLI or MCP coverage.++## Out of scope++- Installing, initializing, or mutating `codegraph` or Graphify indexes.+- Adding `crate_depends_on` to the Open Second Brain graph schema.+- Introducing LLM-generated community labels.+- Replacing deterministic label propagation with a third-party graph algorithm.+- Changing the default `o2b doctor`, `o2b brain clusters run`, or existing MCP output when no new option is used.++## Chosen approach++Use Variant 2: Dedicated operational-readability reporting layer.++Add a read-only CodeGraph report surface, exposed as `o2b partner codegraph report` and `brain_codegraph_report`, backed by a core reporter module rather than by `doctor` formatting. The CLI work therefore includes a small top-level `partner` dispatcher wired from `src/cli/main.ts`; it is not a `brain` verb because it reports on an external code-project partner, not on vault memory content. The reporter composes existing code-project discovery and status checks with a small Cargo workspace reader that parses only structural manifest fields needed for membership reporting. It returns a schema-versioned object with explicit absent-data reasons instead of guessing or fabricating crate edges.++For community operations, add an explicit batch option to the existing cluster run surface. The default path continues to call `detectCommunities` as it does today. When a batch option is provided, a separate orchestration path chunks cluster-note materialization and accumulates per-batch results or errors without changing the deterministic detection contract or adding LLM-generated labels.++We agree with the consultant recommendation. The two cards are about operational readability, so a discoverable report surface is more useful than burying richer text inside `doctor`, and it avoids the overreach of adding a new graph edge schema.++## Design decisions++1. Keep partner integration optional and read-only.+ - The reporter may inspect local manifests and call existing status helpers.+ - It must not run initialization, extraction, or writes.+ - Missing CLI and missing indexes are normal report states, not unhandled failures.++2. Make Cargo workspace support structural.+ - Parse `Cargo.toml` for `[workspace]` and `members` only.+ - Resolve member globs conservatively under the project root.+ - Report `cargo_workspace: null` with a reason when no workspace is present.+ - Do not infer dependency edges from prose or external command output that is not explicitly structured.++3. Separate report code from doctor checks.+ - Existing `checkCodegraph` remains doctor-grade and compatible.+ - New report code can reuse `findCodeProjects` and status helpers, but should have its own return type and tests.+ - CLI and MCP wrappers should be thin delegations over the core report.++4. Keep cluster batching option-gated.+ - Existing calls without `batch_size` or `--batch-size` must keep the current result shape and deterministic behavior.+ - Batched mode should use typed validation for positive integer limits.+ - Batch failures should be returned as explicit per-batch errors while successful batches remain visible.++5. Preserve language-agnostic behavior.+ - No natural-language keyword lists for project or community classification.+ - Use manifests, graph structure, typed fields, and explicit operator input only.++## Report contracts++The CodeGraph report should be stable enough for MCP consumers to branch on without scraping prose. It reports a single in-scope project. Required top-level fields: `schema_version`, `project` (the resolved project path, or `null` when none is in scope), `cli` (`{ available, path }`), `index` (`{ state, ... }` where `state` is `no_project`, `absent`, `not_indexed`, `indexed`, or `error`, plus optional `node_count`, `file_count`, `edge_count`, and `reason`), `cargo_workspace` (`null`, or `{ root, members, memberCount }`), and `cargo_workspace_reason`. Do not expose `crate_depends_on` unless a future release adds that graph schema deliberately.++Batched cluster mode should be explicit in both CLI and MCP inputs as `batch_size` / `--batch-size`. In batched mode, return the same community summaries as the default run plus a `batches` array containing `index`, `start`, `end`, `written`, `removed`, and optional `error`. Without `batch_size`, do not include `batches` and keep the existing output shape.++## File changes++Expected implementation touchpoints:++- `src/core/partner/codegraph-report.ts` for structured CodeGraph report types and Cargo workspace inspection, reusing `src/core/partner/codegraph.ts` discovery/status helpers where practical.+- `src/cli/partner.ts`, `src/cli/main.ts`, and `src/cli/command-manifest.ts` for the `o2b partner codegraph report` command, command dispatch, help text, and JSON contract.+- `src/mcp/brain/knowledge-tools.ts` for `brain_codegraph_report`, unless implementation review shows the MCP brain tool table has been split before this card starts.+- `src/core/brain/link-graph/communities.ts`, `src/cli/brain/verbs/clusters.ts`, and `src/mcp/brain/knowledge-tools.ts` for option-gated batching.+- `tests/core/partner/codegraph.test.ts`, `tests/cli/partner-codegraph-report.test.ts`, and/or focused MCP parity coverage for the new report.+- `tests/cli/brain-clusters.test.ts` and `tests/mcp/link-recall-tools.test.ts` for batch validation and default-output regression.+- `docs/cli-reference.md`, `docs/mcp.md`, and `CHANGELOG.md` for user-visible surfaces.++## Risks++- The CodeGraph report can drift into partner ingestion. Mitigation: keep it read-only and explicitly report absent data rather than adding schema edges.+- Cargo manifest parsing can become too broad. Mitigation: parse only workspace membership for this release and cover common missing/malformed cases.+- Cluster batching can accidentally change default results. Mitigation: preserve the existing path when no batch option is supplied and add a regression test proving default output stability.+- New CLI/MCP surface area increases documentation burden. Mitigation: keep wrappers thin and document the structured result once in the CLI and MCP references.diff --git a/docs/brainstorm/codegraph-mcp-operational-readability/plan.md b/docs/brainstorm/codegraph-mcp-operational-readability/plan.mdnew file mode 100644index 00000000..5cef53e9--- /dev/null+++ b/docs/brainstorm/codegraph-mcp-operational-readability/plan.md@@ -0,0 +1,70 @@+# CodeGraph and MCP operational readability implementation plan++Branch: `feat/codegraph-mcp-operational-readability`+Design: `docs/brainstorm/codegraph-mcp-operational-readability/design.md`++## t_a1e76788 - [upstream:graphify] Cargo workspace dependency extraction for Rust projects++### Files++- `src/core/partner/codegraph.ts` or `src/core/partner/codegraph-report.ts`+- `src/cli/...` for the `o2b partner codegraph report` command and help text+- `src/mcp/brain/knowledge-tools.ts` or the current MCP registration module for `brain_codegraph_report`+- `tests/core/partner/codegraph.test.ts`+- Focused CLI or MCP tests for the report wrapper+- `docs/cli-reference.md`+- `docs/mcp.md`+- `CHANGELOG.md`++### Acceptance++A focused test suite passes that proves:++- A Rust project with a structural `Cargo.toml` workspace reports workspace members.+- A non-Rust project reports `cargo_workspace: null` with an explicit reason.+- Missing `codegraph` CLI and missing `.codegraph/` are represented as honest report states rather than thrown failures.+- The CLI and MCP wrappers return the core report shape without mutating the project or vault.++Suggested verification command for the worker:++```bash+bun test tests/core/partner/codegraph.test.ts <new focused CLI or MCP test file>+bun run typecheck+```++### Depends on++No sibling task needs to land first. Build this as the first card if possible, because it establishes the dedicated report surface and naming conventions that the release docs can reuse.++## t_a286135c - [upstream:graphify] Multi-batch community labeling for large graphs++### Files++- `src/core/brain/link-graph/communities.ts`+- `src/cli/brain/verbs/clusters.ts`+- `src/mcp/brain/knowledge-tools.ts`+- `tests/cli/brain-clusters.test.ts`+- `tests/mcp/link-recall-tools.test.ts` or the current MCP cluster test file+- `docs/cli-reference.md`+- `docs/mcp.md`+- `CHANGELOG.md`++### Acceptance++A focused test suite passes that proves:++- Existing `brain_clusters` and `o2b brain clusters run` output remains unchanged when no batch option is supplied.+- Invalid batch sizes fail with typed validation or usage errors.+- Batched mode processes cluster note materialization in bounded chunks and reports per-batch successes and failures explicitly.+- The implementation does not introduce LLM labeling, natural-language classification, or a Graphify dependency.++Suggested verification command for the worker:++```bash+bun test tests/cli/brain-clusters.test.ts <new focused MCP test if added>+bun run typecheck+```++### Depends on++Prefer running after `t_a1e76788` on the same branch so shared release documentation and changelog entries can build on the CodeGraph report wording. The implementation itself should not depend on the CodeGraph report code.diff --git a/docs/brainstorm/codegraph-mcp-operational-readability/variants.md b/docs/brainstorm/codegraph-mcp-operational-readability/variants.mdnew file mode 100644index 00000000..6f838782--- /dev/null+++ b/docs/brainstorm/codegraph-mcp-operational-readability/variants.md@@ -0,0 +1,39 @@+# CodeGraph and MCP operational readability variants++## Consultant variants++## Variant 1: In-place surface augmentation+Approach: Extend the two existing modules directly without adding new surfaces. `codegraph.ts` gains Cargo-workspace detection that enriches the existing `code_graph` `CheckResult` with crate count and workspace-membership readability (reading `Cargo.toml` `[workspace]` members and, when the partner CLI is present, passing through its status), while `communities.ts` gains an opt-in `batchSize` option that chunks label propagation and cluster-note materialization with per-batch failure isolation. Defaults stay unset, so doctor output and community detection remain byte-identical until a flag is used.+Trade-offs:+- Smallest footprint and fastest to ship; no new CLI verbs, MCP tools, or schema tokens to document and version.+- Couples two unrelated concerns (partner readability, graph robustness) onto pre-existing functions, and Rust readability stays buried inside `o2b doctor` output rather than being independently queryable.+- Partial-failure resilience added inside `detectCommunities` risks diluting its current deterministic, fully-in-memory contract that downstream tests rely on.+Complexity: small+Risk: low++## Variant 2: Dedicated operational-readability reporting layer+Approach: Add a new read-only surface (`o2b partner codegraph report` plus a `brain_codegraph_report` MCP tool) that aggregates partner code-graph status, detected Cargo-workspace crate membership, and any partner-reported crate dependency counts into one structured, schema-versioned report with honest absent-data fields and typed errors. Community labeling robustness is delivered as a separate, option-gated batched pass over the existing detection, leaving the default path untouched. Each concern lives in its own discoverable surface.+Trade-offs:+- Operational readability becomes a first-class, queryable artifact for agents and operators rather than a doctor side effect, matching the cards' stated intent.+- Honest-absent-data and typed-error reporting fit the project's existing conventions and stay additive, so existing reads are byte-identical.+- More new surface area to register, document, changelog, and version-sync than Variant 1; two cards land as two distinct surfaces rather than one cohesive change.+Complexity: medium+Risk: low++## Variant 3: Unified batched-graph-pass abstraction with crate edges+Approach: Introduce a shared "batched graph pass with partial-failure accumulation" primitive consumed by both subsystems: community detection runs chunked, fault-isolated batches, and a new crate-graph projection extracts Graphify-style `crate_depends_on` edges from detected Cargo workspaces into Open Second Brain's graph schema as a new typed edge. This generalizes batching as a cross-cutting concern and brings Rust workspace dependencies in as first-class graph structure.+Trade-offs:+- Maximizes reuse and treats batching/partial-failure as one well-tested primitive across the graph layer.+- Adds a new `crate_depends_on` edge type to the graph schema, a non-additive change that touches indexing, recall, and schema-pack surfaces, raising migration and regression surface.+- Presupposes deeper Graphify-style edge mapping the constraints caution against, and risks recasting Open Second Brain's optional partner as an owned ingestion dependency.+Complexity: large+Risk: high++## Recommended: Variant 2+Rationale: The cards are explicitly framed as operational readability rather than new graph machinery, so a dedicated read-only report surface delivers their value where operators and agents can find it, without burying it in doctor output as Variant 1 does. It stays additive and option-gated with typed errors and honest absent-data, preserving byte-identical default behavior per the constraints. It deliberately avoids Variant 3's new `crate_depends_on` schema edge and Graphify-as-dependency overreach, keeping the partner integration detection-only. The modest extra surface area is the right cost for a discoverable, versioned artifact that fits existing conventions.++## Final decision++Chosen variant: Variant 2, Dedicated operational-readability reporting layer.++I agree with the consultant recommendation. It best matches the locked scope by improving operator and agent visibility through additive report surfaces, while keeping partner integration optional and read-only. It also prevents the release from overreaching into new graph schema edges or LLM community labeling, both of which would increase risk beyond the two triage cards.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 0ec8969d..bfb5954b 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -219,7 +219,7 @@ The schema pack gains four additive ontology fields (`labels`, `link_constraints```texto2b brain bridges discover [--max N] [--min-similarity X] | list | accept <source> <target> | dismiss <source> <target> - embedding-near link proposals over the vec index, reviewable artifact, accept writes one related: wikilink-o2b brain clusters run [--min-size N] | list - graph-wide community detection; derived digests under Brain/clusters/, regenerated per run+o2b brain clusters run [--min-size N] [--batch-size N] | list - graph-wide community detection; derived digests under Brain/clusters/, regenerated per run; --batch-size materializes in chunks with isolated, reported per-batch failureso2b brain benchmark run --dataset <path> [--k N] [--expand] - hit@k + MRR against the live hybrid recall; records the recall_benchmark metrico2b brain tune run --dataset <path> [--k N] | status | reset - bounded self-tuning grid judged by the benchmark; persisted to Brain/search/tuning.jsono2b search <query> --expand deterministic lex/vec/hyde expansion of a bare query (stopword-stripped lex, entity-context vec line, template hyde passage)@@ -261,6 +261,14 @@ o2b discipline uninstall Remove the cron job; --weekly removes only the weeSee [`hermes-cron.md`](hermes-cron.md) for the cron envelope and Telegram delivery shape.+## Partner (read-only, since v1.12.0)++Reports on external code-project partners. Strictly read-only: never installs, initializes, extracts, or mutates a partner index or the vault.++```text+o2b partner codegraph report Resolve the in-scope code project and report the codegraph index state (no_project | absent | not_indexed | indexed with node/file/edge counts | error) plus a structural Cargo.toml workspace-member list. Non-Rust projects report cargo_workspace: null with a reason. --vault sharpens the scan scope; --json emits the schema-versioned report+```+## Search```textdiff --git a/docs/mcp.md b/docs/mcp.mdindex d373a831..4d45fec4 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -18,7 +18,7 @@ in Open Second Brain depends on the MCP server being running.## Tool Highlights-The full server currently advertises 78 tools; the 18 deprecated predecessor+The full server currently advertises 79 tools; the 18 deprecated predecessornames were removed in 1.0.0 and now answer a precise INVALID_PARAMS tombstone(see "Consolidated views and deprecated aliases" below). The table highlightsthe operator-facing core,@@ -37,6 +37,7 @@ flags for a narrower per-process full server.| `vault_health` | Run vault, config, and plugin manifest health checks. | — || `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | — || `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | — |+| `brain_codegraph_report` | Read-only codegraph partner report: in-scope code project, index state (`no_project`/`absent`/`not_indexed`/`indexed` with counts/`error`), and structural `Cargo.toml` workspace members. Never installs, extracts, or mutates; non-Rust projects report `cargo_workspace: null` with a reason. | — || `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | — || `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — || `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 424ea2b0..4da4d171 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": "1.11.0",+ "version": "1.12.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 2b27ad79..b60d874e 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.11.0",+ "version": "1.12.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 12300925..d6da66d0 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.11.0"+version: "1.12.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 639dd0b2..d52ac527 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.11.0",+ "version": "1.12.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 12300925..d6da66d0 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.11.0"+version: "1.12.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 a9ed5673..d0bc14c8 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 = "1.11.0"+version = "1.12.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/verbs/clusters.ts b/src/cli/brain/verbs/clusters.tsindex 8b3ff96c..b940eb38 100644--- a/src/cli/brain/verbs/clusters.ts+++ b/src/cli/brain/verbs/clusters.ts@@ -32,12 +32,14 @@ import { SearchError } from "../../../core/search/types.ts";import { parseFrontmatter } from "../../../core/vault.ts";import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";-const USAGE = "usage: o2b brain clusters run [--min-size N] | list [--vault <path>] [--json]";+const USAGE =+ "usage: o2b brain clusters run [--min-size N] [--batch-size N] | list [--vault <path>] [--json]";export async function cmdBrainClusters(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {vault: { type: "string" },"min-size": { type: "string" },+ "batch-size": { type: "string" },json: { type: "boolean" },});const asJson = flags["json"] === true;@@ -89,6 +91,11 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {process.stderr.write("brain clusters run: --min-size must be a positive integer\n");return 2;}+ const batchSize = parsePositiveInt(flags["batch-size"] as string | undefined);+ if (batchSize === false) {+ process.stderr.write("brain clusters run: --batch-size must be a positive integer\n");+ return 2;+ }const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });let store: Store;@@ -119,7 +126,12 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {// O(1) from the snapshot detectCommunities just built (same index// revision -> cache hit, no second graph rebuild).const stats = graphStats(store, { top: 5 });- const result = materializeClusterNotes(vault, communities, { store, now });+ const result = materializeClusterNotes(vault, communities, {+ store,+ now,+ ...(batchSize !== undefined ? { batchSize } : {}),+ });+ const failedBatches = result.batches?.filter((b) => b.error !== undefined) ?? [];try {appendMetric(vault, {surface: "communities",@@ -130,6 +142,9 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {written: result.written.length,removed: result.removed.length,min_size: minSize ?? COMMUNITY_DEFAULT_MIN_SIZE,+ ...(result.batches+ ? { batches: result.batches.length, failed_batches: failedBatches.length }+ : {}),},});} catch {@@ -151,6 +166,7 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {},written: result.written,removed: result.removed,+ ...(result.batches ? { batches: result.batches } : {}),});} else if (communities.length === 0) {ok("clusters run: no communities at the current threshold");@@ -161,6 +177,14 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {ok(` ${c.id}: ${c.size} notes, density ${c.density.toFixed(2)}`);}ok(` graph: ${stats.nodeCount} linked nodes, ${stats.edgeCount} edges`);+ if (result.batches) {+ ok(+ ` batches: ${result.batches.length} (${failedBatches.length} failed)` ++ (failedBatches.length > 0+ ? ` - failed: ${failedBatches.map((b) => `#${b.index} (${b.error})`).join(", ")}`+ : ""),+ );+ }if (result.removed.length > 0) ok(` removed stale: ${result.removed.join(", ")}`);}return 0;diff --git a/src/cli/main.ts b/src/cli/main.tsindex 07c4e6d6..ba98cea1 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -27,6 +27,7 @@ import { listVaultPages, writeFrontmatter } from "../core/vault.ts";import { CliError, parseFlags } from "./argparse.ts";import { handleBrainSubcommand } from "./brain.ts";import { handleDisciplineSubcommand } from "./discipline.ts";+import { handlePartnerSubcommand } from "./partner.ts";import { handleSearchSubcommand } from "./search.ts";import { handleVaultSubcommand } from "./vault.ts";import {@@ -696,6 +697,9 @@ Search:Vault scope:vault status Show how many files/dirs the active policy includes and which rules excludedvault inspect <relpath> Point-check one vault-relative path against the policy++Partner (read-only):+ partner codegraph report Report codegraph index status + structural Cargo workspace members (--json)`;export async function main(argv: ReadonlyArray<string>): Promise<number> {@@ -756,6 +760,7 @@ const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set(["search","vault","discipline",+ "partner",]);async function dispatchCommand(command: string, rest: string[]): Promise<number> {@@ -797,6 +802,8 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>return await handleSearchSubcommand(rest);case "vault":return await handleVaultSubcommand(rest);+ case "partner":+ return await handlePartnerSubcommand(rest);default:process.stderr.write(`error: unknown command: ${command}\n`);process.stderr.write(HELP);diff --git a/src/cli/partner.ts b/src/cli/partner.tsnew file mode 100644index 00000000..bc4bbf3e--- /dev/null+++ b/src/cli/partner.ts@@ -0,0 +1,80 @@+/**+ * `o2b partner` subcommand dispatcher.+ *+ * Reports on external code-project partners (currently codegraph). It is a+ * top-level command rather than a `brain` verb because it inspects an external+ * code project, not vault memory content. Every verb here is strictly+ * read-only: it never installs, initializes, extracts, or mutates a partner+ * index or the vault.+ */++import { CliError, parseFlags } from "./argparse.ts";+import { defaultConfigPath, resolveVault } from "../core/config.ts";+import { buildCodegraphReport, type CodegraphReport } from "../core/partner/codegraph-report.ts";++function resolveScopeVault(flagVal: string | undefined): string {+ // The report scans the cwd plus the vault parent's siblings. A configured+ // vault sharpens that scope; without one we fall back to the cwd so the+ // command still works inside a bare code checkout.+ return flagVal ?? resolveVault(defaultConfigPath() ?? undefined) ?? process.cwd();+}++function renderCodegraphReport(report: CodegraphReport): string {+ const lines: string[] = [];+ lines.push(`project: ${report.project ?? "(none in scope)"}`);+ lines.push(`codegraph CLI: ${report.cli.available ? report.cli.path : "not installed"}`);+ const idx = report.index;+ const detail = idx.reason ? ` (${idx.reason})` : "";+ if (idx.state === "indexed") {+ lines.push(+ `index: indexed (${idx.node_count ?? 0} nodes, ${idx.file_count ?? 0} files, ` ++ `${idx.edge_count ?? 0} edges)`,+ );+ } else {+ lines.push(`index: ${idx.state}${detail}`);+ }+ if (report.cargo_workspace) {+ const ws = report.cargo_workspace;+ lines.push(`cargo workspace: ${ws.memberCount} member(s)`);+ for (const m of ws.members) lines.push(` - ${m}`);+ } else {+ lines.push(`cargo workspace: none (${report.cargo_workspace_reason})`);+ }+ return lines.join("\n");+}++function codegraphReportVerb(argv: ReadonlyArray<string>): number {+ const { flags, positional } = parseFlags(argv, { vault: { type: "string" } });+ if (positional.length > 0) {+ throw new CliError(+ `partner codegraph report does not accept positional arguments: ${positional.join(" ")}`,+ );+ }+ const vaultFlag = flags["vault"] as string | undefined;+ const asJson = Boolean(flags["json"]);+ const report = buildCodegraphReport({ cwd: process.cwd(), vault: resolveScopeVault(vaultFlag) });+ if (asJson) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+ } else {+ process.stdout.write(renderCodegraphReport(report) + "\n");+ }+ return 0;+}++export async function handlePartnerSubcommand(argv: ReadonlyArray<string>): Promise<number> {+ const partner = argv[0];+ const verb = argv[1];+ const rest = argv.slice(2);++ if (partner === "codegraph" && verb === "report") {+ return codegraphReportVerb(rest);+ }+ if (partner === "codegraph") {+ process.stderr.write(`error: unknown partner codegraph subcommand: ${verb ?? "(none)"}\n`);+ process.stderr.write("usage: o2b partner codegraph report [--vault <path>] [--json]\n");+ return 2;+ }+ process.stderr.write(`error: unknown partner: ${partner ?? "(none)"}\n`);+ process.stderr.write("usage: o2b partner codegraph report [--vault <path>] [--json]\n");+ return 2;+}diff --git a/src/core/brain/link-graph/communities.ts b/src/core/brain/link-graph/communities.tsindex 9eee7059..0bb4bc06 100644--- a/src/core/brain/link-graph/communities.ts+++ b/src/core/brain/link-graph/communities.ts@@ -172,9 +172,51 @@ function communityId(relPath: string): string {const GENERATED_KIND = "brain-cluster";+/**+ * Per-batch outcome from a batched materialization run (t_a286135c,+ * Graphify-inspired). Present only when `batchSize` is supplied; the+ * unbatched path stays byte-identical and omits it.+ */+export interface ClusterBatch {+ /** 0-based batch position. */+ readonly index: number;+ /** Inclusive community offset this batch starts at. */+ readonly start: number;+ /** Exclusive community offset this batch ends at. */+ readonly end: number;+ /** Relative paths written by this batch (partial if it failed midway). */+ readonly written: ReadonlyArray<string>;+ /**+ * Stale notes removed. Removal is a single global reconciliation run+ * after all writes, attributed to the final batch.+ */+ readonly removed: ReadonlyArray<string>;+ /** Failure detail; present only when the batch threw. */+ readonly error?: string;+}+export interface MaterializeClusterNotesResult {readonly written: ReadonlyArray<string>;readonly removed: ReadonlyArray<string>;+ /** Per-batch results; present only when `batchSize` was supplied. */+ readonly batches?: ReadonlyArray<ClusterBatch>;+}++export interface MaterializeClusterNotesOptions {+ readonly store: Store;+ readonly now: Date;+ /**+ * Opt-in batching for large graphs (t_a286135c): materialize+ * communities in fixed-size, order-preserving chunks so one failed+ * batch is isolated and reported instead of dropping the whole pass.+ * Unset => single pass, errors propagate, byte-identical to before.+ */+ readonly batchSize?: number;+ /**+ * Injection seam for the per-note writer (defaults to the atomic+ * write); lets callers and tests force a deterministic batch fault.+ */+ readonly writeNote?: (path: string, content: string) => void;}function clustersDir(vault: string): string {@@ -185,26 +227,68 @@ function clustersDir(vault: string): string {* Regenerate one derived note per community and remove generated* notes whose community vanished. Hand-written files (no* `kind: brain-cluster`) are never touched.+ *+ * With `batchSize` set, communities are written in fixed-size chunks+ * and each batch is isolated: a batch that throws is recorded with an+ * `error` and the remaining batches continue. The stale sweep keys off+ * the full detected set, so a failed batch leaves its prior note in+ * place rather than deleting it.*/export function materializeClusterNotes(vault: string,communities: ReadonlyArray<Community>,- opts: { readonly store: Store; readonly now: Date },+ opts: MaterializeClusterNotesOptions,): MaterializeClusterNotesResult {const dir = clustersDir(vault);mkdirSync(dir, { recursive: true });+ const writeNote = opts.writeNote ?? atomicWriteFileSync;- const written: string[] = [];- const expected = new Set<string>();- for (const community of communities) {+ // The full detected set protects every community note from the stale+ // sweep regardless of batch success: a failed batch keeps its prior+ // note instead of having it deleted.+ const expected = new Set<string>(communities.map((c) => `cluster-${c.id}.md`));++ const writeOne = (community: Community): string => {const fileName = `cluster-${community.id}.md`;- expected.add(fileName);- const path = join(dir, fileName);- atomicWriteFileSync(path, renderClusterNote(community, opts));- written.push(`Brain/clusters/${fileName}`);+ writeNote(join(dir, fileName), renderClusterNote(community, opts));+ return `Brain/clusters/${fileName}`;+ };++ const written: string[] = [];+ let batches: ClusterBatch[] | undefined;+ if (opts.batchSize === undefined) {+ for (const community of communities) written.push(writeOne(community));+ } else {+ if (!Number.isInteger(opts.batchSize) || opts.batchSize < 1) {+ throw new Error("materializeClusterNotes: batchSize must be a positive integer");+ }+ const size = opts.batchSize;+ batches = [];+ for (let start = 0, index = 0; start < communities.length; start += size, index++) {+ const end = Math.min(start + size, communities.length);+ const batchWritten: string[] = [];+ let error: string | undefined;+ try {+ for (let i = start; i < end; i++) batchWritten.push(writeOne(communities[i]!));+ } catch (exc) {+ // Independent batches keep going; record stable bounds + detail.+ error = (exc as Error).message ?? String(exc);+ }+ written.push(...batchWritten);+ batches.push(+ Object.freeze({+ index,+ start,+ end,+ written: Object.freeze([...batchWritten]),+ removed: Object.freeze([] as string[]),+ ...(error !== undefined ? { error } : {}),+ }),+ );+ }}- // Stale sweep: only generated notes are eligible for removal.+ // Single global stale sweep: only generated notes are eligible.const removed: string[] = [];for (const file of readdirSync(dir).toSorted()) {if (!file.endsWith(".md") || expected.has(file)) continue;@@ -215,7 +299,18 @@ export function materializeClusterNotes(removed.push(`Brain/clusters/${file}`);}- return Object.freeze({ written: Object.freeze(written), removed: Object.freeze(removed) });+ // Attribute the single global sweep to the final batch so the+ // per-batch `removed` contract carries a real value.+ if (batches && batches.length > 0) {+ const last = batches[batches.length - 1]!;+ batches[batches.length - 1] = Object.freeze({ ...last, removed: Object.freeze([...removed]) });+ }++ return Object.freeze({+ written: Object.freeze(written),+ removed: Object.freeze(removed),+ ...(batches ? { batches: Object.freeze(batches) } : {}),+ });}function renderClusterNote(diff --git a/src/core/partner/codegraph-report.ts b/src/core/partner/codegraph-report.tsnew file mode 100644index 00000000..a1c1aafb--- /dev/null+++ b/src/core/partner/codegraph-report.ts@@ -0,0 +1,265 @@+/**+ * Read-only operational-readability report for the codegraph partner+ * (https://github.com/colbymchenry/codegraph).+ *+ * This surface answers "is a code project in scope, is codegraph indexing+ * it, and - for Rust - which Cargo workspace members were declared" WITHOUT+ * installing, initializing, extracting, or mutating anything. It composes the+ * existing code-project discovery and status helpers with a small structural+ * `Cargo.toml` reader.+ *+ * It deliberately does NOT run `codegraph`/`graphify` extraction and does NOT+ * fabricate `crate_depends_on` edges into the Open Second Brain graph: a missing+ * CLI, a missing index, or a non-Rust project are all honest report states, not+ * errors and not silent no-ops.+ */++import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";++import {+ defaultRunStatusJson,+ defaultWhichCodegraph,+ findCodeProjects,+ type CodegraphStatusResult,+} from "./codegraph.ts";++export interface CargoWorkspace {+ readonly manifestPath: string;+ readonly members: string[];+ readonly memberCount: number;+}++export interface CargoWorkspaceResult {+ readonly workspace: CargoWorkspace | null;+ readonly reason: string;+}++/**+ * Structural read of a project's `Cargo.toml` for workspace membership.+ *+ * Parses only the `[workspace]` table's `members = [...]` array - no full TOML+ * evaluation, no dependency resolution. Returns `workspace: null` with an+ * explicit reason when there is no `Cargo.toml` or no `[workspace]` table.+ */+export function readCargoWorkspace(projectDir: string): CargoWorkspaceResult {+ const manifestPath = join(projectDir, "Cargo.toml");+ if (!existsSync(manifestPath)) {+ return { workspace: null, reason: "no Cargo.toml in project root (not a Rust project)" };+ }++ let text: string;+ try {+ text = readFileSync(manifestPath, "utf8");+ } catch (exc) {+ return { workspace: null, reason: `Cargo.toml unreadable: ${(exc as Error).message}` };+ }++ const lines = text.split(/\r?\n/);+ let currentTable: string | null = null;+ let members: string[] | null = null;++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ const stripped = stripComment(line).trim();+ if (stripped.length === 0) continue;++ if (stripped.startsWith("[")) {+ // Any table header changes scope, including `[[array-of-tables]]`+ // (matchTableHeader returns null for those, never "workspace"). The+ // `members` key is only valid directly under the top-level `[workspace]`+ // table, so sub-tables like `[workspace.package]` must not collect it.+ currentTable = matchTableHeader(stripped);+ continue;+ }++ if (currentTable !== "workspace") continue;++ const key = matchKey(stripped);+ if (key !== "members") continue;++ // An unterminated array (malformed manifest) yields what we parsed so far+ // rather than scanning the rest of the file.+ members = collectArray(lines, i).values;+ break;+ }++ if (!inWorkspaceTablePresent(text)) {+ return {+ workspace: null,+ reason: "Cargo.toml present but has no [workspace] table (single-crate project)",+ };+ }++ return {+ workspace: {+ manifestPath,+ members: members ?? [],+ memberCount: (members ?? []).length,+ },+ reason: "ok",+ };+}++function inWorkspaceTablePresent(text: string): boolean {+ for (const raw of text.split(/\r?\n/)) {+ const stripped = stripComment(raw).trim();+ if (matchTableHeader(stripped) === "workspace") return true;+ }+ return false;+}++function stripComment(line: string): string {+ // Structural-only: a `#` outside a string starts a comment. Cargo workspace+ // member entries are simple quoted paths, so we honor quotes minimally.+ let inSingle = false;+ let inDouble = false;+ for (let i = 0; i < line.length; i++) {+ const ch = line[i];+ if (ch === '"' && !inSingle) inDouble = !inDouble;+ else if (ch === "'" && !inDouble) inSingle = !inSingle;+ else if (ch === "#" && !inSingle && !inDouble) return line.slice(0, i);+ }+ return line;+}++function matchTableHeader(stripped: string): string | null {+ if (!stripped.startsWith("[") || stripped.startsWith("[[")) return null;+ const end = stripped.indexOf("]");+ if (end < 0) return null;+ return stripped.slice(1, end).trim();+}++function matchKey(stripped: string): string | null {+ const eq = stripped.indexOf("=");+ if (eq < 0) return null;+ return stripped.slice(0, eq).trim();+}++/** Collect a possibly multi-line `members = [ "a", "b" ]` array as raw strings. */+function collectArray(+ lines: ReadonlyArray<string>,+ startIdx: number,+): { values: string[]; complete: boolean } {+ let buf = "";+ for (let i = startIdx; i < lines.length; i++) {+ buf += stripComment(lines[i]!);+ if (buf.includes("]")) {+ const open = buf.indexOf("[");+ const close = buf.indexOf("]", open + 1);+ if (open >= 0 && close > open) {+ return { values: extractStrings(buf.slice(open + 1, close)), complete: true };+ }+ }+ buf += "\n";+ }+ return { values: extractStrings(buf), complete: false };+}++function extractStrings(inner: string): string[] {+ const out: string[] = [];+ const re = /"([^"]*)"|'([^']*)'/g;+ let m: RegExpExecArray | null;+ while ((m = re.exec(inner)) !== null) {+ out.push(m[1] ?? m[2] ?? "");+ }+ return out;+}++export type CodegraphIndexState = "no_project" | "absent" | "not_indexed" | "indexed" | "error";++export interface CodegraphReport {+ readonly schema_version: 1;+ readonly project: string | null;+ readonly cli: { readonly available: boolean; readonly path: string | null };+ readonly index: {+ readonly state: CodegraphIndexState;+ readonly node_count?: number;+ readonly file_count?: number;+ readonly edge_count?: number;+ readonly reason?: string;+ };+ readonly cargo_workspace: CargoWorkspace | null;+ readonly cargo_workspace_reason: string;+}++export interface CodegraphReportOptions {+ readonly cwd: string;+ readonly vault: string;+ readonly scanExtraPaths?: ReadonlyArray<string>;+ readonly limit?: number;+}++export interface CodegraphReportDeps {+ readonly whichCodegraph?: () => string | null;+ readonly runStatusJson?: (projectPath: string) => CodegraphStatusResult;+ readonly readCargoWorkspace?: (projectDir: string) => CargoWorkspaceResult;+}++/**+ * Build a schema-versioned, read-only partner report. Never throws on the+ * normal "partner absent / not indexed / not Rust" states - those are values,+ * not failures - so CLI and MCP wrappers can render them directly.+ */+export function buildCodegraphReport(+ opts: CodegraphReportOptions,+ deps?: CodegraphReportDeps,+): CodegraphReport {+ const projects = findCodeProjects(opts);+ const whichFn = deps?.whichCodegraph ?? defaultWhichCodegraph;+ const cliPath = whichFn();+ const cli = { available: cliPath !== null, path: cliPath };++ if (projects.length === 0) {+ return {+ schema_version: 1,+ project: null,+ cli,+ index: { state: "no_project", reason: "no code project in scope" },+ cargo_workspace: null,+ cargo_workspace_reason: "no code project in scope",+ };+ }++ const project = projects[0]!;+ const cargoFn = deps?.readCargoWorkspace ?? readCargoWorkspace;+ const cargo = cargoFn(project);++ const index = resolveIndexState(project, cliPath, deps);++ return {+ schema_version: 1,+ project,+ cli,+ index,+ cargo_workspace: cargo.workspace,+ cargo_workspace_reason: cargo.reason,+ };+}++function resolveIndexState(+ project: string,+ cliPath: string | null,+ deps?: CodegraphReportDeps,+): CodegraphReport["index"] {+ if (cliPath === null) {+ return { state: "absent", reason: "codegraph CLI not on PATH (optional partner)" };+ }+ if (!existsSync(join(project, ".codegraph"))) {+ return { state: "not_indexed", reason: `run: codegraph init ${project}` };+ }+ const runFn = deps?.runStatusJson ?? defaultRunStatusJson;+ const status = runFn(project);+ if (!status.ok) {+ return { state: "error", reason: status.error };+ }+ if (!status.data.initialized) {+ return { state: "not_indexed", reason: `run: codegraph init ${project}` };+ }+ return {+ state: "indexed",+ node_count: status.data.nodeCount ?? 0,+ file_count: status.data.fileCount ?? 0,+ edge_count: status.data.edgeCount ?? 0,+ };+}diff --git a/src/core/partner/codegraph.ts b/src/core/partner/codegraph.tsindex 1f50d1e6..4634a6ab 100644--- a/src/core/partner/codegraph.ts+++ b/src/core/partner/codegraph.ts@@ -133,7 +133,7 @@ export interface CodegraphCheckOptions {readonly disabled?: boolean;}-function defaultWhichCodegraph(): string | null {+export function defaultWhichCodegraph(): string | null {if (typeof Bun !== "undefined" && typeof (Bun as { which?: unknown }).which === "function") {const found = (Bun as unknown as { which: (cmd: string) => string | null }).which("codegraph");return found ?? null;@@ -141,7 +141,7 @@ function defaultWhichCodegraph(): string | null {return null;}-function defaultRunStatusJson(projectPath: string): CodegraphStatusResult {+export function defaultRunStatusJson(projectPath: string): CodegraphStatusResult {try {const proc = Bun.spawnSync({cmd: ["codegraph", "status", "-j", projectPath],diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex fc9d7191..0ddc2107 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -35,6 +35,7 @@ import { isoSecond } from "../../core/brain/time.ts";import { normalizeAgentArgument } from "../../core/agent-identity.ts";import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";import { listDeadEnds, recordDeadEnd } from "../../core/brain/dead-ends.ts";+import { buildCodegraphReport } from "../../core/partner/codegraph-report.ts";import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../../core/brain/temporal/foresight.ts";import { aggregateQuantities } from "../../core/brain/truth/aggregate.ts";import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";@@ -217,6 +218,10 @@ async function toolBrainClusters(if (minSize !== undefined && (!Number.isInteger(minSize) || (minSize as number) < 2)) {throw new MCPError(INVALID_PARAMS, "brain_clusters run: min_size must be an integer >= 2");}+ const batchSize = args["batch_size"];+ if (batchSize !== undefined && (!Number.isInteger(batchSize) || (batchSize as number) < 1)) {+ throw new MCPError(INVALID_PARAMS, "brain_clusters run: batch_size must be an integer >= 1");+ }const searchConfig = resolveSearchConfig({vault: ctx.vault,configPath: ctx.configPath ?? undefined,@@ -231,7 +236,11 @@ async function toolBrainClusters(store,minSize !== undefined ? { minSize: minSize as number } : {},);- const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });+ const materialized = materializeClusterNotes(ctx.vault, communities, {+ store,+ now,+ ...(batchSize !== undefined ? { batchSize: batchSize as number } : {}),+ });try {appendMetric(ctx.vault, {surface: "communities",@@ -241,6 +250,12 @@ async function toolBrainClusters(sizes: communities.map((c) => c.size),written: materialized.written.length,removed: materialized.removed.length,+ ...(materialized.batches+ ? {+ batches: materialized.batches.length,+ failed_batches: materialized.batches.filter((b) => b.error !== undefined).length,+ }+ : {}),},});} catch {@@ -255,6 +270,7 @@ async function toolBrainClusters(})),written: materialized.written,removed: materialized.removed,+ ...(materialized.batches ? { batches: materialized.batches } : {}),};} finally {await store.close();@@ -517,9 +533,37 @@ function toolBrainDeadEnds(return { ok: true, id: result.entry.id, path: result.entry.path, archived: result.archived };}+// ----- brain_codegraph_report (t_a1e76788) -----------------------------------++/**+ * Read-only codegraph partner report: index status plus structural Cargo+ * workspace membership. Never installs, initializes, extracts, or mutates a+ * partner index or the vault - a missing CLI, missing index, or non-Rust+ * project are honest report states, not errors.+ */+function toolBrainCodegraphReport(+ ctx: ServerContext,+ _args: Record<string, unknown>,+): Record<string, unknown> {+ const report = buildCodegraphReport({ cwd: process.cwd(), vault: ctx.vault });+ return report as unknown as Record<string, unknown>;+}+// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([+ {+ name: "brain_codegraph_report",+ description:+ "Read-only codegraph partner report: resolves the in-scope code project, reports index state (no_project|absent|not_indexed|indexed|error, with counts), and structurally parses Cargo.toml for workspace members. Non-Rust projects report cargo_workspace: null. Never installs or mutates.",+ inputSchema: {+ type: "object",+ properties: {},+ additionalProperties: false,+ },+ handler: toolBrainCodegraphReport,+ previewBudget: MCP_PREVIEW_BUDGET,+ },{name: "brain_foresight",description:@@ -569,7 +613,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_clusters",description:- "Graph-wide community detection: run applies deterministic label propagation over the resolved link graph, materializes one derived note per community of size >= min_size under Brain/clusters/, removes stale generated notes, and records a metric; list reads the generated notes back.",+ "Graph-wide community detection: run applies deterministic label propagation, materializes one note per community of size >= min_size under Brain/clusters/, removes stale notes, records a metric; list reads them back. Optional batch_size chunks work with isolated, reported per-batch failures.",inputSchema: {type: "object",properties: {@@ -579,6 +623,12 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([minimum: 2,description: "Smallest community that materializes (run, default 4).",},+ batch_size: {+ type: "integer",+ minimum: 1,+ description:+ "Materialize communities in chunks of this size (run); each batch is isolated and reported in the batches array. Default: single pass.",+ },},required: ["operation"],additionalProperties: false,diff --git a/tests/cli/brain-clusters.test.ts b/tests/cli/brain-clusters.test.tsindex c9e33eaa..37eb497e 100644--- a/tests/cli/brain-clusters.test.ts+++ b/tests/cli/brain-clusters.test.ts@@ -111,9 +111,52 @@ test("maintenance lane executes the bridges and clusters tasks", async () => {expect(listMetrics(vault, { surface: "communities" })).toHaveLength(1);});+test("run --batch-size returns per-batch results", async () => {+ await index();+ const run = await runCli([+ "brain",+ "clusters",+ "run",+ "--batch-size",+ "1",+ "--vault",+ vault,+ "--json",+ ]);+ expect(run.returncode).toBe(0);+ const parsed = JSON.parse(run.stdout) as {+ communities: unknown[];+ batches: Array<{ index: number; start: number; end: number; error?: string }>;+ };+ expect(parsed.communities).toHaveLength(1);+ expect(parsed.batches).toHaveLength(1);+ expect(parsed.batches[0]).toMatchObject({ index: 0, start: 0, end: 1 });+ expect(parsed.batches[0]!.error).toBeUndefined();+ expect(listMetrics(vault, { surface: "communities" })[0]!.payload).toMatchObject({+ batches: 1,+ failed_batches: 0,+ });+});++test("run without --batch-size omits the batches field", async () => {+ await index();+ const run = await runCli(["brain", "clusters", "run", "--vault", vault, "--json"]);+ expect(JSON.parse(run.stdout)).not.toHaveProperty("batches");+});+test("usage errors exit 2", async () => {const r = await runCli(["brain", "clusters", "nope", "--vault", vault]);expect(r.returncode).toBe(2);const bad = await runCli(["brain", "clusters", "run", "--min-size", "0", "--vault", vault]);expect(bad.returncode).toBe(2);+ const badBatch = await runCli([+ "brain",+ "clusters",+ "run",+ "--batch-size",+ "0",+ "--vault",+ vault,+ ]);+ expect(badBatch.returncode).toBe(2);});diff --git a/tests/cli/partner-codegraph.test.ts b/tests/cli/partner-codegraph.test.tsnew file mode 100644index 00000000..06825de2--- /dev/null+++ b/tests/cli/partner-codegraph.test.ts@@ -0,0 +1,103 @@+/**+ * `o2b partner codegraph report` CLI surface (t_a1e76788).+ *+ * The command is strictly read-only: it reports codegraph index status plus+ * structural Cargo workspace membership without installing, initializing, or+ * mutating any partner index or the vault. codegraph presence on PATH is+ * environment-dependent, so the deterministic assertions target the Cargo+ * workspace parse and the report envelope, not the CLI-availability field.+ */++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;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-partner-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function makeWorkspaceRepo(): string {+ const repo = join(tmp, "ws");+ mkdirSync(join(repo, ".git"), { recursive: true });+ writeFileSync(+ join(repo, "Cargo.toml"),+ '[workspace]\nresolver = "2"\nmembers = ["crates/a", "crates/b"]\n',+ );+ return repo;+}++test("--json emits a schema-versioned report with Cargo members", async () => {+ const repo = makeWorkspaceRepo();+ const res = await runCli(+ ["partner", "codegraph", "report", "--vault", join(tmp, "vault"), "--json"],+ {+ cwd: repo,+ },+ );+ expect(res.returncode).toBe(0);+ const report = JSON.parse(res.stdout);+ expect(report.schema_version).toBe(1);+ expect(report.project).toBe(repo);+ expect(report.cargo_workspace).not.toBeNull();+ expect(report.cargo_workspace.members).toEqual(["crates/a", "crates/b"]);+ expect(report.cargo_workspace.memberCount).toBe(2);+});++test("human output lists workspace members", async () => {+ const repo = makeWorkspaceRepo();+ const res = await runCli(["partner", "codegraph", "report", "--vault", join(tmp, "vault")], {+ cwd: repo,+ });+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("cargo workspace: 2 member(s)");+ expect(res.stdout).toContain("crates/a");+});++test("non-Rust project reports no cargo workspace with a reason", async () => {+ const repo = join(tmp, "node");+ mkdirSync(join(repo, ".git"), { recursive: true });+ writeFileSync(join(repo, "package.json"), "{}\n");+ const res = await runCli(+ ["partner", "codegraph", "report", "--vault", join(tmp, "vault"), "--json"],+ {+ cwd: repo,+ },+ );+ expect(res.returncode).toBe(0);+ const report = JSON.parse(res.stdout);+ expect(report.cargo_workspace).toBeNull();+ expect(report.cargo_workspace_reason).toContain("no Cargo.toml");+});++test("unknown partner subcommand exits 2 with usage", async () => {+ const res = await runCli(["partner", "codegraph", "bogus"], { cwd: tmp });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("usage: o2b partner codegraph report");+});++test("unknown flag exits 2 instead of being silently ignored", async () => {+ const res = await runCli(["partner", "codegraph", "report", "--bogus"], { cwd: tmp });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("unknown flag: --bogus");+});++test("--vault without a value exits 2", async () => {+ const res = await runCli(["partner", "codegraph", "report", "--vault"], { cwd: tmp });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("--vault requires a value");+});++test("positional arguments are rejected", async () => {+ const res = await runCli(["partner", "codegraph", "report", "extra"], { cwd: tmp });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("does not accept positional arguments");+});diff --git a/tests/core/brain/communities.test.ts b/tests/core/brain/communities.test.tsindex 41c356ec..bbe5065a 100644--- a/tests/core/brain/communities.test.ts+++ b/tests/core/brain/communities.test.ts@@ -18,6 +18,7 @@ import {materializeClusterNotes,} from "../../../src/core/brain/link-graph/communities.ts";import { DEFAULT_TIER_MAP } from "../../../src/core/brain/frontmatter-tiers.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";import { indexVault } from "../../../src/core/search/indexer.ts";import { Store } from "../../../src/core/search/store.ts";import { parseFrontmatter } from "../../../src/core/vault.ts";@@ -182,3 +183,113 @@ describe("materializeClusterNotes", () => {expect(existsSync(join(vault, "Brain", "clusters", "hand-written.md"))).toBe(true);});});++describe("materializeClusterNotes batching (t_a286135c)", () => {+ test("default (no batchSize) keeps the original shape with no batches field", async () => {+ writeTwoCommunities();+ await indexVault(config);+ const communities = await withStore((store) => detectCommunities(store, { minSize: 4 }));+ const result = await withStore((store) =>+ materializeClusterNotes(vault, communities, { store, now: NOW }),+ );+ expect(result.written).toHaveLength(2);+ expect(result.batches).toBeUndefined();+ });++ test("batchSize splits materialization into bounded, ordered chunks", async () => {+ writeTwoCommunities();+ await indexVault(config);+ const communities = await withStore((store) => detectCommunities(store, { minSize: 4 }));+ expect(communities).toHaveLength(2);++ const result = await withStore((store) =>+ materializeClusterNotes(vault, communities, { store, now: NOW, batchSize: 1 }),+ );+ expect(result.written).toHaveLength(2);+ expect(result.batches).toHaveLength(2);+ expect(result.batches!.map((b) => b.index)).toEqual([0, 1]);+ expect(result.batches!.map((b) => [b.start, b.end])).toEqual([+ [0, 1],+ [1, 2],+ ]);+ expect(result.batches!.every((b) => b.error === undefined)).toBe(true);+ expect(result.batches!.flatMap((b) => b.written)).toEqual([...result.written]);++ // A batch size larger than the set yields a single batch.+ const single = await withStore((store) =>+ materializeClusterNotes(vault, communities, { store, now: NOW, batchSize: 100 }),+ );+ expect(single.batches).toHaveLength(1);+ expect(single.batches![0]).toMatchObject({ index: 0, start: 0, end: 2 });+ });++ test("a failed batch is isolated and reported while other batches still write", async () => {+ writeTwoCommunities();+ await indexVault(config);+ const communities = await withStore((store) => detectCommunities(store, { minSize: 4 }));+ const doomedId = communities[1]!.id;++ const result = await withStore((store) =>+ materializeClusterNotes(vault, communities, {+ store,+ now: NOW,+ batchSize: 1,+ writeNote: (path, content) => {+ if (path.includes(`cluster-${doomedId}.md`)) throw new Error("disk full");+ atomicWriteFileSync(path, content);+ },+ }),+ );++ expect(result.batches).toHaveLength(2);+ const okBatch = result.batches!.find((b) => b.error === undefined)!;+ const failed = result.batches!.find((b) => b.error !== undefined)!;+ expect(okBatch.written).toEqual([`Brain/clusters/cluster-${communities[0]!.id}.md`]);+ expect(failed.written).toEqual([]);+ expect(failed.error).toContain("disk full");+ expect(result.written).toEqual([`Brain/clusters/cluster-${communities[0]!.id}.md`]);+ expect(existsSync(join(vault, "Brain", "clusters", `cluster-${communities[0]!.id}.md`))).toBe(+ true,+ );+ expect(existsSync(join(vault, "Brain", "clusters", `cluster-${doomedId}.md`))).toBe(false);+ });++ test("a failed batch leaves a prior note intact instead of removing it", async () => {+ writeTwoCommunities();+ await indexVault(config);+ const communities = await withStore((store) => detectCommunities(store, { minSize: 4 }));+ await withStore((store) => materializeClusterNotes(vault, communities, { store, now: NOW }));+ const doomedId = communities[1]!.id;+ const doomedPath = join(vault, "Brain", "clusters", `cluster-${doomedId}.md`);+ expect(existsSync(doomedPath)).toBe(true);++ await withStore((store) =>+ materializeClusterNotes(vault, communities, {+ store,+ now: NOW,+ batchSize: 1,+ writeNote: (path, content) => {+ if (path.includes(`cluster-${doomedId}.md`)) throw new Error("disk full");+ atomicWriteFileSync(path, content);+ },+ }),+ );+ expect(existsSync(doomedPath)).toBe(true);+ });++ test("the stale sweep under batching removes a vanished community's note", async () => {+ writeTwoCommunities();+ await indexVault(config);+ const communities = await withStore((store) => detectCommunities(store, { minSize: 4 }));+ await withStore((store) => materializeClusterNotes(vault, communities, { store, now: NOW }));++ const onlyFirst = communities.slice(0, 1);+ const result = await withStore((store) =>+ materializeClusterNotes(vault, onlyFirst, { store, now: NOW, batchSize: 1 }),+ );+ expect(result.removed).toHaveLength(1);+ // The single global sweep is attributed to the final batch.+ expect(result.batches!.at(-1)!.removed).toEqual([...result.removed]);+ expect(readdirSync(join(vault, "Brain", "clusters"))).toHaveLength(1);+ });+});diff --git a/tests/core/partner/codegraph-report.test.ts b/tests/core/partner/codegraph-report.test.tsnew file mode 100644index 00000000..20df46d9--- /dev/null+++ b/tests/core/partner/codegraph-report.test.ts@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ buildCodegraphReport,+ readCargoWorkspace,+} from "../../../src/core/partner/codegraph-report.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-codegraph-report-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function makeRepo(dir: string, manifest = "package.json", body = "{}\n"): string {+ mkdirSync(dir, { recursive: true });+ mkdirSync(join(dir, ".git"));+ writeFileSync(join(dir, manifest), body);+ return dir;+}++function makeIndexed(dir: string): void {+ mkdirSync(join(dir, ".codegraph"), { recursive: true });+ writeFileSync(join(dir, ".codegraph", "codegraph.db"), "");+}++const WORKSPACE_TOML = `[workspace]+resolver = "2"+members = [+ "crates/core",+ "crates/cli",+ "tools/xtask",+]++[workspace.package]+version = "0.1.0"+`;++describe("readCargoWorkspace", () => {+ test("no Cargo.toml -> null with explicit reason", () => {+ const repo = makeRepo(join(tmp, "node-app"));+ const r = readCargoWorkspace(repo);+ expect(r.workspace).toBeNull();+ expect(r.reason).toContain("no Cargo.toml");+ });++ test("Cargo.toml without [workspace] -> null with reason", () => {+ const repo = makeRepo(join(tmp, "crate"), "Cargo.toml", '[package]\nname = "x"\n');+ const r = readCargoWorkspace(repo);+ expect(r.workspace).toBeNull();+ expect(r.reason.toLowerCase()).toContain("workspace");+ });++ test("structural [workspace] with members -> members reported", () => {+ const repo = makeRepo(join(tmp, "ws"), "Cargo.toml", WORKSPACE_TOML);+ const r = readCargoWorkspace(repo);+ expect(r.workspace).not.toBeNull();+ expect(r.workspace!.members).toEqual(["crates/core", "crates/cli", "tools/xtask"]);+ expect(r.workspace!.memberCount).toBe(3);+ expect(r.workspace!.manifestPath).toBe(join(repo, "Cargo.toml"));+ });++ test("inline members array on one line", () => {+ const repo = makeRepo(join(tmp, "ws2"), "Cargo.toml", '[workspace]\nmembers = ["a", "b"]\n');+ const r = readCargoWorkspace(repo);+ expect(r.workspace!.members).toEqual(["a", "b"]);+ });++ test("[workspace] table present but no members -> empty members, not null", () => {+ const repo = makeRepo(join(tmp, "ws3"), "Cargo.toml", '[workspace]\nresolver = "2"\n');+ const r = readCargoWorkspace(repo);+ expect(r.workspace).not.toBeNull();+ expect(r.workspace!.members).toEqual([]);+ expect(r.workspace!.memberCount).toBe(0);+ });++ test("members under [workspace.package] sub-table are not collected", () => {+ const body = '[workspace]\nresolver = "2"\n\n[workspace.package]\nmembers = ["nope"]\n';+ const repo = makeRepo(join(tmp, "ws-sub"), "Cargo.toml", body);+ const r = readCargoWorkspace(repo);+ expect(r.workspace).not.toBeNull();+ expect(r.workspace!.members).toEqual([]);+ });++ test("members under an array-of-tables after [workspace] are not collected", () => {+ const body = '[workspace]\nresolver = "2"\n\n[[bin]]\nmembers = ["nope"]\n';+ const repo = makeRepo(join(tmp, "ws-aot"), "Cargo.toml", body);+ const r = readCargoWorkspace(repo);+ expect(r.workspace).not.toBeNull();+ expect(r.workspace!.members).toEqual([]);+ });++ test("members of a later table are not mistaken for workspace members", () => {+ const body = '[workspace]\nresolver = "2"\n\n[some.other]\nmembers = ["nope"]\n';+ const repo = makeRepo(join(tmp, "ws4"), "Cargo.toml", body);+ const r = readCargoWorkspace(repo);+ expect(r.workspace!.members).toEqual([]);+ });+});++describe("buildCodegraphReport", () => {+ test("no code project in scope -> honest empty report", () => {+ mkdirSync(join(tmp, "vault"));+ const r = buildCodegraphReport(+ { cwd: tmp, vault: join(tmp, "vault") },+ { whichCodegraph: () => null },+ );+ expect(r.schema_version).toBe(1);+ expect(r.project).toBeNull();+ expect(r.index.state).toBe("no_project");+ expect(r.cargo_workspace).toBeNull();+ expect(r.cargo_workspace_reason.length).toBeGreaterThan(0);+ });++ test("code project, codegraph CLI absent -> index state absent (no throw)", () => {+ const repo = makeRepo(join(tmp, "repo"), "Cargo.toml", WORKSPACE_TOML);+ const r = buildCodegraphReport(+ { cwd: repo, vault: join(tmp, "vault") },+ { whichCodegraph: () => null },+ );+ expect(r.project).toBe(repo);+ expect(r.cli.available).toBe(false);+ expect(r.index.state).toBe("absent");+ expect(r.cargo_workspace).not.toBeNull();+ expect(r.cargo_workspace!.members).toEqual(["crates/core", "crates/cli", "tools/xtask"]);+ });++ test("code project + CLI + no .codegraph/ -> not_indexed", () => {+ const repo = makeRepo(join(tmp, "repo"), "Cargo.toml", WORKSPACE_TOML);+ const r = buildCodegraphReport(+ { cwd: repo, vault: join(tmp, "vault") },+ { whichCodegraph: () => "/usr/bin/codegraph" },+ );+ expect(r.cli.available).toBe(true);+ expect(r.cli.path).toBe("/usr/bin/codegraph");+ expect(r.index.state).toBe("not_indexed");+ });++ test("code project + CLI + indexed + status ok -> indexed with counts", () => {+ const repo = makeRepo(join(tmp, "repo"), "Cargo.toml", WORKSPACE_TOML);+ makeIndexed(repo);+ const r = buildCodegraphReport(+ { cwd: repo, vault: join(tmp, "vault") },+ {+ whichCodegraph: () => "/usr/bin/codegraph",+ runStatusJson: () => ({+ ok: true,+ data: { initialized: true, nodeCount: 12, fileCount: 3, edgeCount: 40 },+ }),+ },+ );+ expect(r.index.state).toBe("indexed");+ expect(r.index.node_count).toBe(12);+ expect(r.index.file_count).toBe(3);+ expect(r.index.edge_count).toBe(40);+ });++ test("status error surfaces as error state with reason", () => {+ const repo = makeRepo(join(tmp, "repo"), "Cargo.toml", WORKSPACE_TOML);+ makeIndexed(repo);+ const r = buildCodegraphReport(+ { cwd: repo, vault: join(tmp, "vault") },+ {+ whichCodegraph: () => "/usr/bin/codegraph",+ runStatusJson: () => ({ ok: false, error: "stale lock" }),+ },+ );+ expect(r.index.state).toBe("error");+ expect(r.index.reason).toContain("stale lock");+ });++ test("non-Rust project -> cargo_workspace null with reason", () => {+ const repo = makeRepo(join(tmp, "node-app"));+ const r = buildCodegraphReport(+ { cwd: repo, vault: join(tmp, "vault") },+ { whichCodegraph: () => null },+ );+ expect(r.cargo_workspace).toBeNull();+ expect(r.cargo_workspace_reason).toContain("no Cargo.toml");+ });+});diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.tsindex 54778fa2..93ba3977 100644--- a/tests/mcp/brain-tools-parity.test.ts+++ b/tests/mcp/brain-tools-parity.test.ts@@ -11,7 +11,8 @@* `brain_anticipatory_context` (continuity-hygiene-freshness suite); v1.7.0* added `brain_intake_entities`, `brain_ingest_source`,* `brain_research_report`, and `brain_derive_fact` (Knowledge Provenance- * suite).+ * suite); the codegraph-and-MCP operational-readability release added+ * `brain_codegraph_report` (read-only codegraph partner report).*/import { describe, expect, test } from "bun:test";@@ -30,6 +31,7 @@ const FROZEN_BRAIN_TOOL_NAMES = ["brain_bridges","brain_brief","brain_clusters",+ "brain_codegraph_report","brain_context","brain_context_pack","brain_context_presets",diff --git a/tests/mcp/codegraph-report-tool.test.ts b/tests/mcp/codegraph-report-tool.test.tsnew file mode 100644index 00000000..3c847760--- /dev/null+++ b/tests/mcp/codegraph-report-tool.test.ts@@ -0,0 +1,76 @@+/**+ * brain_codegraph_report MCP tool (t_a1e76788).+ *+ * Read-only partner report. Registered in the full (read) tool table, never+ * the writer table, and returns a schema-versioned envelope without mutating+ * the project or vault. codegraph presence and the resolved code project are+ * environment-dependent, so assertions target the stable report envelope.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-codegraph-report-tool-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "codegraph-report-test", version: "0" },+ },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+}++async function call(): Promise<{ result?: unknown; error?: unknown }> {+ const server = new MCPServer({ vault, configPath: null });+ await initialize(server);+ return (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name: "brain_codegraph_report", arguments: {} },+ })) as { result?: unknown; error?: unknown };+}++function payload(response: { result?: unknown }): Record<string, unknown> {+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };+ return JSON.parse(result.content[0]!.text);+}++describe("brain_codegraph_report tool", () => {+ test("registered in the full table only", () => {+ expect(buildToolTable("full").find((t) => t.name === "brain_codegraph_report")).toBeDefined();+ expect(+ buildToolTable("writer").find((t) => t.name === "brain_codegraph_report"),+ ).toBeUndefined();+ });++ test("returns a schema-versioned read-only report envelope", async () => {+ const response = await call();+ expect(response.error).toBeUndefined();+ const report = payload(response as { result?: unknown });+ expect(report["schema_version"]).toBe(1);+ expect(report).toHaveProperty("cli");+ expect(report).toHaveProperty("index");+ expect(report).toHaveProperty("cargo_workspace");+ expect(report).toHaveProperty("cargo_workspace_reason");+ });+});diff --git a/tests/mcp/link-recall-tools.test.ts b/tests/mcp/link-recall-tools.test.tsindex 9303a503..705ba599 100644--- a/tests/mcp/link-recall-tools.test.ts+++ b/tests/mcp/link-recall-tools.test.ts@@ -186,6 +186,36 @@ test("brain_clusters run materializes derived notes and the metric", async () =>expect(bad.code).toBe(-32602);});+test("brain_clusters run without batch_size has no batches field", async () => {+ writeGroup();+ await indexDefaultLocation();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const run = await call(server, "brain_clusters", { operation: "run" });+ expect(run["batches"]).toBeUndefined();+});++test("brain_clusters run with batch_size returns per-batch results", async () => {+ writeGroup();+ await indexDefaultLocation();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const run = await call(server, "brain_clusters", { operation: "run", batch_size: 1 });+ const batches = run["batches"] as Array<{ index: number; start: number; end: number }>;+ expect(batches).toHaveLength(1);+ expect(batches[0]).toMatchObject({ index: 0, start: 0, end: 1 });++ const badZero = await callError(server, "brain_clusters", { operation: "run", batch_size: 0 });+ expect(badZero.code).toBe(-32602);+ const badFraction = await callError(server, "brain_clusters", {+ operation: "run",+ batch_size: 1.5,+ });+ expect(badFraction.code).toBe(-32602);+});+test("brain_benchmark run scores an inline dataset and records the metric", async () => {writeGroup();await indexDefaultLocation();diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 90b1e6bd..98bff85b 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -272,6 +272,8 @@ describe("tool listing", () => {"brain_clusters","brain_benchmark","brain_tune",+ // CodeGraph & MCP Operational Readability (v1.12.0).+ "brain_codegraph_report",// Agent Write Contract Suite: provider-agnostic write sessions."brain_write_session",// Knowledge Provenance Suite (v1.7.0).@@ -544,7 +546,9 @@ describe("stdio loop", () => {// + brain_file_context (Recall & Working-Memory Quality Suite) = 78.// + brain_session_summary / brain_idea_lineage / brain_note_history// (Session Knowledge Synthesis Suite, v1.11.0) = 81.- expect(list.result.tools.length).toBe(81);+ // + brain_codegraph_report (CodeGraph & MCP Operational Readability,+ // v1.12.0) = 82.+ expect(list.result.tools.length).toBe(82);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.tsindex bb033720..dbc39a2a 100644--- a/tests/mcp/removed-tools.test.ts+++ b/tests/mcp/removed-tools.test.ts@@ -142,5 +142,6 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn// + brain_file_context (Recall & Working-Memory Quality Suite) = 78.// + brain_session_summary, brain_idea_lineage, brain_note_history// (Session Knowledge Synthesis Suite) = 81.- expect(list.result.tools.length).toBe(81);+ // + brain_codegraph_report (CodeGraph & MCP Operational Readability) = 82.+ expect(list.result.tools.length).toBe(82);});