Skip to content

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

TypeScript

feat: typed graph semantics - typed relations, visibility scoping, MCP landscape (#46)

Sol Aitkencbbe18f7736b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 7b22a411..3f223062 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.18.0",
+ "version": "0.19.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 94a160bc..49eeaa97 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.18.0",
+ "version": "0.19.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b419c10..3cbb986e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,52 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.19.0] - 2026-05-28
+
+Typed graph semantics. The vault's link graph and page frontmatter gain
+typed, machine-readable meaning that the search and query layers honor:
+edges can carry a semantic relation, pages can declare typed
+relationships and a visibility scope, and the Model Context Protocol
+servers configured around the vault become a queryable landscape.
+
+### Added
+
+- Relation vocabulary as a single validation boundary
+ (`src/core/graph/relation-vocab.ts`) plus a nullable `relation` column
+ on the search `links` table (schema migration v3), orthogonal to the
+ syntactic `link_type`. The vocabulary is data-driven and carries no
+ SQL CHECK, so adding a relation type is a one-line change rather than a
+ migration.
+- Typed frontmatter relationships. Any page can declare `related`,
+ `extends`, `contradicts`, or `superseded_by` in frontmatter; these
+ become typed edges in the graph, are recorded with a relation type in
+ the backlink index, and surface inline on `brain_search` results
+ (structured output and CLI render). The result `relations` field is
+ computed at query time and never stored.
+- Content visibility scoping. A page may declare a `visibility:`
+ frontmatter field; `brain_search` honors a requested visibility scope
+ (`visibility` MCP argument, `--visibility` CLI flag). Untagged pages
+ are always returned; a tagged page only when the caller's scope
+ includes one of its values.
+- `brain_mcp_landscape` MCP tool and `o2b brain mcp-landscape` CLI verb:
+ list the MCP servers configured across the vault - each server's name,
+ source config file, packages, and required env-var names. Environment
+ values are never read. Recognises `.mcp.json`, `mcp.json`,
+ `mcp_servers.json`, and `claude_desktop_config.json`.
+
+### Changed
+
+- Vaults that adopt frontmatter relations: those typed edges are written
+ as wikilink-type edges, so `related`/`extends`/etc. now also
+ contribute to link-boost and traversal recall. Additive; vaults
+ without relation frontmatter are unaffected.
+
+### Notes
+
+- The schema migration is additive and reindex-safe; existing link rows
+ keep a NULL relation until a reindex repopulates frontmatter-derived
+ edges. All-untagged vaults see byte-identical search results.
+
## [0.18.0] - 2026-05-28
MCP context economy. Large tool results no longer flood the calling
@@ -3215,6 +3261,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.19.0]: https://github.com/itechmeat/open-second-brain/compare/v0.18.0...v0.19.0
[0.18.0]: https://github.com/itechmeat/open-second-brain/compare/v0.17.0...v0.18.0
[0.17.0]: https://github.com/itechmeat/open-second-brain/compare/v0.16.0...v0.17.0
[0.16.0]: https://github.com/itechmeat/open-second-brain/compare/v0.15.0...v0.16.0
diff --git a/README.md b/README.md
index bf403e99..402ceaab 100644
--- a/README.md
+++ b/README.md
@@ -112,7 +112,7 @@ The capabilities you actually feel day to day:
| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` β€” SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |
| 10 | Pay Memory β€” audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |
-These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
+These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
## CLI
diff --git a/docs/brainstorm/typed-graph-semantics/cli-output/claude.md b/docs/brainstorm/typed-graph-semantics/cli-output/claude.md
new file mode 100644
index 00000000..5db39198
--- /dev/null
+++ b/docs/brainstorm/typed-graph-semantics/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Layered extension of existing surfaces
+- **Approach**: Each of the four units extends its nearest existing surface independently. Add a `relation` column to the `links` table (migration β†’ schema v3); generalize the backlink index's existing per-field tracking (which already handles `supersedes`/`superseded_by`/`evidenced_by`) to cover `related`/`extends`/`contradicts`/`superseded_by` for arbitrary pages; treat `visibility:` as a reserved key inside the existing post-rank `properties` filter with a scoping rule; and add a standalone MCP-config extractor that emits server/package/env edges into the `links` table with a node-kind tag.
+- **Trade-offs**:
+ - Pro: smallest blast radius β€” every unit lands on code that already exists (links table, backlink index, property filter), maximizing KISS and reindex-safety.
+ - Pro: low risk to public MCP output contracts since each change is additive and local.
+ - Pro: ships incrementally; units are independently testable.
+ - Con: the relation/visibility vocabulary gets validated in several places (link parse, frontmatter parse, MCP extractor), violating the "single validation boundary" constraint.
+ - Con: no unified way to query "all semantic edges regardless of origin"; relation meaning is spread across links + backlink index.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Unified edge-semantics layer over the links table
+- **Approach**: Add a single `relation` column (plus a `visibility` column or reserved target convention) to the existing `links` table, and route every edge source β€” wikilinks, markdown links, tags, typed frontmatter fields, and MCP config β€” through one data-driven relation/visibility vocabulary module that classifies and validates at a single ingestion boundary. Non-file entities (MCP servers, npm/pip packages, env-var requirements) reuse the same synthetic-target pattern that `tag` edges already use, so they live as edges in the one table. Search/query/dream read relation + visibility from this one column set.
+- **Trade-offs**:
+ - Pro: satisfies "open/extensible vocabulary validated at exactly one boundary" cleanly β€” one registry, one classify function, one migration.
+ - Pro: maximally DRY; reuses the established "target need not be a file" precedent (tags) for MCP nodes.
+ - Pro: one place for search/dream to consume relations, so contradiction/supersession surfacing and dream auto-population share a single read path.
+ - Con: overloads the `links` table with semantically heterogeneous edges (syntactic links + frontmatter relations + MCP infra), so queries must always filter by relation/kind.
+ - Con: MCP server/package "nodes" as synthetic link targets is workable but slightly awkward β€” no first-class node attributes beyond the target string.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Dedicated typed graph subsystem (nodes + semantic edges tables)
+- **Approach**: Introduce a new typed-graph store β€” a `graph_nodes` table (files, preferences, MCP servers, packages, env requirements) and a `graph_edges` table carrying `relation` and `visibility` columns β€” alongside the existing `links` table, with `links` becoming one feeder into it. A central vocabulary registry validates relation/visibility at ingestion. Frontmatter relations, MCP config, and wikilinks all normalize into this uniform node/edge model that search, query, and dream traverse.
+- **Trade-offs**:
+ - Pro: cleanest conceptual model β€” first-class non-file nodes (MCP servers/packages) with real attributes, clean split between syntactic links and semantic edges.
+ - Pro: most future-proof for arbitrary typed-graph reasoning and cross-entity queries.
+ - Con: directly violates "prefer extending existing surfaces over new parallel subsystems" β€” two graph representations to keep synchronized and reindex coherently.
+ - Con: largest migration and highest risk to reindex correctness and to existing link-traversal queries that target the `links` table.
+ - Con: most code to test for a release whose four units don't yet demand full node-attribute richness.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 2
+**Rationale**: It is the only variant that fully honors the binding constraints β€” an open, data-driven relation/visibility vocabulary validated at a *single* boundary (Variant 1 scatters that validation) while still extending the existing `links` table rather than standing up a parallel graph subsystem (Variant 3's main violation and risk). The synthetic-target convention that `tag` edges already established gives MCP server/package/env edges a home without new tables, keeping the schema change to one appended migration and giving search/query/dream a single relation read-path for surfacing contradictions, supersession, and dream auto-population.
diff --git a/docs/brainstorm/typed-graph-semantics/cli-output/prompt.md b/docs/brainstorm/typed-graph-semantics/cli-output/prompt.md
new file mode 100644
index 00000000..4a3448fd
--- /dev/null
+++ b/docs/brainstorm/typed-graph-semantics/cli-output/prompt.md
@@ -0,0 +1,70 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Ship "typed graph semantics" for Open Second Brain: the brain's link/backlink graph and page frontmatter gain typed, machine-readable semantic meaning that the search, query, and dream layers honor. Four atomic units share one release:
+
+1. **Typed edge classification.** Today `LinkType = "wikilink" | "markdown_link" | "tag"` (src/core/search/links.ts:15) and the `links` SQLite table constrains `link_type` to those three (src/core/search/schema.ts:84-91). There is no way to record WHAT KIND of relationship a link represents. Add a semantic relation dimension to edges so the graph is queryable by relationship meaning, not just by link syntax.
+
+2. **Typed frontmatter relationships.** Pages/preferences should be able to declare typed relationships in frontmatter: `related:`, `extends:`, `contradicts:`, `superseded_by:`. These become typed edges in the graph. `brain_search` / `brain_query` should surface contradictions and supersession inline in results, and `brain_dream` could auto-populate `superseded_by:` / `contradicts:` during consolidation. Note: the preference domain already tracks `supersedes` / `superseded_by` / `evidenced_by` as backlink fields (src/core/brain/backlinks.ts:194-207) β€” this generalizes typed relations to arbitrary pages.
+
+3. **Content visibility tags.** A typed frontmatter field (e.g. `visibility:`) that scopes which content is reachable by which consumer/agent. The search layer already has a post-rank `properties` frontmatter filter (SearchOptions.properties, v0.10.17, src/core/search/types.ts:116-130) β€” visibility is an orthogonal scoping axis layered over that. No content-visibility control exists today; all notes/preferences are equally visible to any agent via MCP.
+
+4. **MCP config extraction into the graph.** Parse `.mcp.json`, `mcp.json`, `mcp_servers.json`, `claude_desktop_config.json` found in the vault into typed graph nodes/edges: server nodes, npm/pip package references, env-var requirements. Env VALUES are discarded to prevent secret leakage. This lets agents reason about the MCP/tool landscape of a project from the brain graph.
+
+# Project context
+
+Open Second Brain: TypeScript, Bun runtime. An Obsidian-native plain-Markdown memory layer for AI agents. MCP server (JSON-RPC 2.0) + `o2b` CLI. Plain `.md` files under `Brain/` in the user's vault. No daemon, no vector black box, no hidden state outside the vault.
+
+Recent shipped releases (most recent first):
+- v0.18.0 MCP context economy (preview budget + artifact fetch + recall hint)
+- v0.17.0 Brain Lifecycle Review Suite (intent review, retention, monthly synthesis)
+- v0.16.0 Agent boundary control (pinned context, Markdown links, MCP output contracts)
+- v0.13.0 Hybrid Search and Recall Quality (explainable recall, MMR, link traversal, entity boost, header anchoring)
+- v0.11.0 Brain-centric vault layout: one agent-owned `Brain/` root, opt-in user notes
+- v0.10.17 link graph surfaces (aliases, anchors, mentions, synthesis, MOC audit, property filter)
+
+Related files:
+- src/core/search/links.ts (LinkType, extractLinks β€” strips code fences, extracts wikilink/markdown_link/tag)
+- src/core/search/schema.ts (DDL + versioned MIGRATIONS array, LATEST_SCHEMA_VERSION=2, links table with link_type CHECK constraint)
+- src/core/search/store.ts (replaceLinks INSERT into links; link traversal queries filter `link_type IN ('wikilink','markdown_link')`)
+- src/core/search/types.ts (SearchOptions.properties post-rank frontmatter filter; BrainSearchResult shape)
+- src/core/brain/backlinks.ts (buildBacklinkIndex β€” inverts the reference graph; already records `field` per ref incl. supersedes/superseded_by/evidenced_by)
+- src/core/brain/explorer.ts (ExplorerNode, backlink_count)
+- src/core/brain/dream.ts (deterministic consolidation pass β€” clusters signals, promotes/retires preferences; NO LLM inside the algorithm)
+- src/core/types.ts (FrontmatterValue = string|number|boolean|ReadonlyArray<string>; FrontmatterMap)
+- src/mcp/brain-tools.ts, src/mcp/tools.ts, src/mcp/server.ts (MCP tool table; OSB's own MCP server)
+- src/cli/brain/verbs/ (57 CLI verb files)
+
+Conventions:
+- Plain Markdown is the source of truth. Frontmatter is YAML; FrontmatterMap supports string arrays already.
+- The search index (SQLite) is a derived cache β€” it can be reindexed from the vault at any time (`o2b search reindex`). Schema changes ship as an appended migration that bumps LATEST_SCHEMA_VERSION; a stale index errors and asks the user to reindex.
+- `dream` is strictly deterministic β€” no LLM calls inside the consolidation algorithm.
+- Read-only graph builders recompute on demand (no on-disk backlink cache); they skip unparseable files rather than throwing (doctor flags malformed files).
+- MCP tools have machine-readable `structuredContent` + an `outputSchema` contract; large tools carry a preview budget (v0.18.0).
+- TDD is mandatory (bun:test). oxlint + oxfmt + tsc --noEmit must stay green. `bun run validate` = typecheck && lint && test.
+
+Constraints:
+- Do NOT hardcode natural-language phrases in any specific human language. All identifiers/templates are English; if any text must vary by language, keep it abstract/data-driven, never a hardcoded per-language string.
+- Do NOT break existing public MCP tool output contracts or outputSchemas.
+- Do NOT add an LLM call inside the deterministic `dream` algorithm.
+- Prefer extending existing surfaces (links table, backlink index, properties filter, frontmatter conventions) over new parallel subsystems. SOLID/KISS/DRY.
+- No new heavyweight external dependencies without strong justification.
+- The vocabulary of relation types and visibility values must be open/extensible, not a closed hardcoded enum baked into many call sites β€” but validated at a single boundary.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/typed-graph-semantics/design.md b/docs/brainstorm/typed-graph-semantics/design.md
new file mode 100644
index 00000000..1d59fa7b
--- /dev/null
+++ b/docs/brainstorm/typed-graph-semantics/design.md
@@ -0,0 +1,70 @@
+# Typed graph semantics - typed edges, frontmatter relationships, visibility, MCP-config nodes
+
+**Status:** draft
+**Author:** claude-vps-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain's graph records only link *syntax* (`LinkType = wikilink | markdown_link | tag`) and has no notion of what a link *means*. Pages cannot declare typed relationships (`related`, `extends`, `contradicts`, `superseded_by`), there is no content-visibility scoping (every note is equally visible to every agent), and the MCP/tool landscape configured around a vault is invisible to the brain. Agents therefore cannot ask "what supersedes this?", "what contradicts this?", "show only content visible to me", or "which MCP servers does this project configure?".
+
+## Scope
+
+- A single, data-driven **relation/visibility vocabulary** module validated at exactly one boundary (the foundation shared by every other unit).
+- A **typed edge** dimension (`relation`) on the existing search `links` table (schema migration v3), orthogonal to the existing `link_type` syntax dimension.
+- **Typed frontmatter relationships** (`related` / `extends` / `contradicts` / `superseded_by`) on *arbitrary vault pages* ingested as typed edges in the search graph, recorded with a relation type in the Brain-layer backlink index, and surfaced inline by `brain_search` / `brain_query`. (Note: preference-domain supersession is already a typed relation written deterministically by `merge.ts` / `dream.ts` and tracked by the backlink index per `field` - this unit generalizes typed relations to *any* page and makes them first-class graph edges; it does not re-implement preference supersession.)
+- **Content visibility** (`visibility:` frontmatter) honored as a reserved key in the existing post-rank `properties` filter and respected by the MCP read surface.
+- **MCP-config extraction**: parse `.mcp.json` / `mcp.json` / `mcp_servers.json` / `claude_desktop_config.json` found in the vault into typed edges (server / package / env-requirement), discarding env *values*.
+
+## Out of scope
+
+- A new parallel graph subsystem (separate `graph_nodes` / `graph_edges` tables). Rejected variant 3 - OSB deliberately extends existing surfaces.
+- Any LLM call inside the deterministic `dream` algorithm. Auto-population is derived from supersession decisions dream already computes deterministically.
+- AST-level typed-edge extraction from code blocks (the upstream graphify origin of unit 1). Adapted to a Markdown vault: relation types come from frontmatter and the vocabulary module, not from parsing code.
+- Cross-machine / per-agent identity enforcement of visibility (visibility is a scoping *filter*, not an auth boundary).
+- Migrating the Brain-layer backlink index into the search `links` table. The two graph surfaces stay separate and both read the one vocabulary module.
+
+## Chosen approach
+
+Variant 2 (unified edge-semantics over the existing `links` table), refined for OSB's two-surface reality.
+
+A single module owns the open/extensible relation and visibility vocabularies and the one `classify` / validate function. Every edge producer (frontmatter relations in the indexer, MCP-config extractor) and every consumer (search traversal, result surfacing, dream, backlink index) reads relation/visibility names from this one module - no relation string is hardcoded across call sites, and validation happens at one boundary.
+
+The search `links` table gains a nullable `relation` column (migration to schema v3). Typed frontmatter relationships and MCP-config edges are written there; MCP server/package/env entities reuse the synthetic-target convention already established by `tag` edges (no first-class node table needed). The Brain-layer backlink index - which already records a `field` per reference and already tracks `supersedes` / `superseded_by` / `evidenced_by` - is generalized to map known relation fields to a relation type, so preference-domain typed relations surface through the existing on-demand index without being forced into the derived search cache.
+
+Visibility is a document-scoped axis, not an edge property. It is honored through the existing `SearchOptions.properties` post-rank filter as a reserved `visibility` key plus a default scoping rule, and respected by the MCP read tools.
+
+## Design decisions
+
+- **One vocabulary module, two graph surfaces.** The single-validation-boundary win of variant 2 is preserved by a shared vocabulary module, *not* by collapsing the two existing graph representations into one table. Collapsing them was variant 3's main risk.
+- **`relation` is orthogonal to `link_type`.** `link_type` stays the syntax dimension (wikilink/markdown_link/tag) with its existing CHECK; `relation` is a new nullable dimension validated in the application layer against the vocabulary module (not a SQL CHECK, so the vocabulary stays open/extensible without a migration per new relation).
+- **Vocabulary is data-driven.** A default relation/visibility set lives in the module; adding a relation type is a one-line change there, never a schema migration (the `relation` column carries no SQL CHECK). The frontmatter ingest path only emits relations whose field name is in the vocabulary, so an unrecognised key is simply not treated as a relation. No closed enum baked into many call sites.
+- **MCP entities as synthetic targets.** Reuse the `tag` precedent (`targetPath = null`, identity in `link_text`, or a `mcp:server/<name>` synthetic path) rather than a new node table - smallest migration, reindex-safe.
+- **Env values discarded at parse time.** The MCP-config extractor records env-var *names* (requirement edges) only; values never enter the graph, matching the no-secrets-in-vault rule and the redaction posture.
+- **No new dream behaviour.** Preference-domain supersession is already written deterministically (`merge.ts`, `dream.ts:531`) and tracked by the backlink index. This release does not touch the dream algorithm; extending deterministic auto-population to `contradicts:` would require judgement that does not belong in the LLM-free dream, so it is explicitly out of scope.
+- **Visibility default is permissive.** Absent `visibility:` = visible everywhere (current behaviour preserved). A scoping rule excludes non-default visibility unless the caller opts in, layered onto the existing property filter - zero behaviour change for vaults that never set the field.
+- **No hardcoded natural-language strings.** Relation/visibility identifiers are English tokens (data, not prose); any human-facing rendering is templated from the token, never a per-language literal.
+
+## File changes
+
+New:
+- `src/core/graph/relation-vocab.ts` - the single relation/visibility vocabulary + validation boundary.
+- `src/core/graph/mcp-config.ts` - MCP-config file parser β†’ typed edges (env values discarded).
+- tests under `tests/core/graph/` and `tests/mcp/` for each unit.
+
+Modified:
+- `src/core/search/schema.ts` - migration v3: nullable `relation` column on `links`; `LATEST_SCHEMA_VERSION = 3`.
+- `src/core/search/links.ts` / `src/core/search/store.ts` - carry `relation` through `ExtractedLink` and `replaceLinks`; relation-aware traversal.
+- `src/core/search/indexer.ts` - emit typed edges from frontmatter relation fields and from discovered MCP-config files.
+- `src/core/search/types.ts` - `BrainSearchResult.relations?` (computed, never stored); reserved `visibility` handling in `SearchOptions.properties`.
+- `src/core/brain/backlinks.ts` - record a `relation` per `BacklinkRef` derived from the known relation fields.
+- `src/mcp/brain-tools.ts` / `src/mcp/tools.ts` - surface relations + visibility scoping; expose the MCP-config landscape (read-only).
+- `src/cli/brain/verbs/query-render.ts` and related CLI verbs - render typed relations / visibility in human output.
+- `README.md`, `CHANGELOG.md`, `docs/` - user-facing docs.
+
+## Risks and open questions
+
+- **Reindex coherence.** Adding the `relation` column must round-trip cleanly: a vault reindex from scratch must reproduce identical typed edges. Mitigated by treating the index as derived and testing reindex idempotency.
+- **Vocabulary creep.** Keeping the vocabulary open risks divergent ad-hoc relations. Mitigated by a `brain_doctor` check that lists unknown relations rather than failing.
+- **Visibility semantics.** The exact default scoping rule (what "private"/non-default visibility excludes, and how a caller opts in) needs to be pinned in the plan so it is one rule, not per-tool. Resolved in plan Task 3.
+- **MCP-config discovery scope.** Which paths under the vault are scanned (avoid scanning the whole filesystem). Resolved in plan Task 4 - vault-relative discovery only.
diff --git a/docs/brainstorm/typed-graph-semantics/plan.md b/docs/brainstorm/typed-graph-semantics/plan.md
new file mode 100644
index 00000000..c039bcbe
--- /dev/null
+++ b/docs/brainstorm/typed-graph-semantics/plan.md
@@ -0,0 +1,60 @@
+# Typed graph semantics - implementation plan
+
+Four atomic units on one feature branch (`feat/typed-graph-semantics`), each a separate conventional commit, each TDD (failing test first). Task 1 is the shared foundation and lands first; Tasks 2-4 depend on it.
+
+## Tasks
+
+### Task 1: Relation/visibility vocabulary + typed-edge column (foundation)
+- **Maps to**: t_d3c017f2 (typed edge classification)
+- **Files**:
+ - new `src/core/graph/relation-vocab.ts` - default relation set (`related`, `extends`, `contradicts`, `superseded_by`) + visibility set, one `isKnownRelation` / `isKnownVisibility` / `normalizeRelation` validation function; vocabulary is a data constant + documented open-extension rule (unknown values preserved, not rejected).
+ - `src/core/search/schema.ts` - migration `{version: 3, up}` adding nullable `relation TEXT` to `links`; bump `LATEST_SCHEMA_VERSION` to 3.
+ - `src/core/search/store.ts` + `src/core/search/links.ts` - add `relation?: string | null` to `ExtractedLink`; `replaceLinks` writes the column.
+ - new `tests/core/graph/relation-vocab.test.ts`, `tests/core/search/schema-migration-v3.test.ts`.
+- **Acceptance**:
+ - Vocabulary module: known/unknown relation + visibility classification, and a single exported boundary; no relation literal duplicated elsewhere (asserted by a wiring test).
+ - Migration: a v2 index migrates to v3 with the new column present and existing rows intact; a fresh index builds at v3; reindex is idempotent.
+ - `relation` round-trips through `replaceLinks` and back.
+- **Depends on**: none
+
+### Task 2: Typed frontmatter relationships (ingest + surface + dream)
+- **Maps to**: t_812695ec (typed semantic relationships)
+- **Files**:
+ - `src/core/search/indexer.ts` - parse document frontmatter (the indexer already holds raw `content`) and emit typed edges from relation fields (`related`/`extends`/`contradicts`/`superseded_by`, each string or string[]) with `relation` set via the vocabulary module. Frontmatter edges attach at document level (first chunk).
+ - `src/core/brain/backlinks.ts` - add `relation?` to `BacklinkRef`, derived from the known relation fields (generalizing the existing `supersedes`/`superseded_by`/`evidenced_by` field mapping to arbitrary pages).
+ - `src/core/search/types.ts` + result builder - `BrainSearchResult.relations?` (computed per result page: inbound/outbound contradicts + superseded_by), never stored.
+ - `src/mcp/brain-tools.ts` + `src/cli/brain/verbs/query-render.ts` - surface `relations` inline in `brain_search` / `brain_query` output (structured + human render).
+ - tests: `tests/core/search/typed-relations.test.ts`, `tests/core/brain/backlinks-relation.test.ts`, `tests/mcp/search-relations.test.ts`.
+- **Acceptance**:
+ - A page with `contradicts: [[X]]` / `superseded_by: [[Y]]` produces typed edges and the relation surfaces in search/query results for the involved pages.
+ - Backlink index reports the relation type per ref.
+ - No public outputSchema broken: `relations` is additive/optional.
+- **Explicitly NOT in this task**: dream / merge supersession writing - already implemented (`merge.ts:216`, `dream.ts:531`) and tracked by the backlink index. The dream algorithm is not touched (no LLM-free judgement extension to `contradicts:`).
+- **Depends on**: Task 1
+
+### Task 3: Content visibility scoping
+- **Maps to**: t_acf962a8 (content visibility tag system)
+- **Files**:
+ - `src/core/graph/relation-vocab.ts` - visibility default + the single scoping rule: absent `visibility:` = visible everywhere; a `visibility:` value restricts the page to callers that opt into that value. One rule, data-driven.
+ - `src/core/search/types.ts` + search pipeline - honor a reserved `visibility` key inside the existing `SearchOptions.properties` post-rank filter; default query excludes non-default-visibility pages unless `visibility` is explicitly requested.
+ - `src/mcp/brain-tools.ts` / `src/mcp/tools.ts` - MCP read tools accept/forward the visibility scope; default-permissive.
+ - tests: `tests/core/search/visibility-filter.test.ts`, `tests/mcp/visibility-scope.test.ts`.
+- **Acceptance**:
+ - A page with `visibility: [private]` is excluded from a default search and included only when the caller requests that visibility.
+ - Pages with no `visibility:` behave exactly as today (zero regression - asserted).
+ - The scoping rule lives in one place, consumed by both CLI and MCP.
+- **Depends on**: Task 1
+
+### Task 4: MCP-config extraction into the graph
+- **Maps to**: t_711215c1 (MCP config file extraction into knowledge graph)
+- **Files**:
+ - new `src/core/graph/mcp-config.ts` - parse `.mcp.json` / `mcp.json` / `mcp_servers.json` / `claude_desktop_config.json` into typed edges: server, package (npm/pip ref), env-requirement (name only - values discarded). Synthetic-target convention reused from `tag` edges.
+ - `src/core/search/indexer.ts` - discover those config files within the vault scope and feed their edges through the same typed-edge path (relation via vocabulary module).
+ - `src/mcp/brain-tools.ts` / `src/mcp/tools.ts` - a read-only surface to query the MCP landscape (servers + their package/env requirements) from the graph.
+ - tests: `tests/core/graph/mcp-config.test.ts` (incl. env-value-discard assertion), `tests/mcp/mcp-landscape.test.ts`.
+- **Acceptance**:
+ - Each supported config filename parses into the expected server/package/env edges.
+ - Env *values* never appear in any edge (explicit test).
+ - Discovery is vault-relative only (no filesystem-wide scan).
+ - The read tool returns the configured MCP servers and their requirements.
+- **Depends on**: Task 1
diff --git a/docs/brainstorm/typed-graph-semantics/variants.md b/docs/brainstorm/typed-graph-semantics/variants.md
new file mode 100644
index 00000000..b64b0584
--- /dev/null
+++ b/docs/brainstorm/typed-graph-semantics/variants.md
@@ -0,0 +1,36 @@
+# Typed graph semantics - brainstorm audit trail
+
+Primary consultant: Claude Code (`claude -p`), exit 0, three parseable variants returned. Fallback (Codex) not invoked - primary succeeded. Raw output in `cli-output/claude.md`; prompt in `cli-output/prompt.md`.
+
+## Variants (verbatim from the consultant)
+
+### Variant 1: Layered extension of existing surfaces
+- **Approach**: Each of the four units extends its nearest existing surface independently. Add a `relation` column to the `links` table (migration β†’ schema v3); generalize the backlink index's existing per-field tracking (which already handles `supersedes`/`superseded_by`/`evidenced_by`) to cover `related`/`extends`/`contradicts`/`superseded_by` for arbitrary pages; treat `visibility:` as a reserved key inside the existing post-rank `properties` filter with a scoping rule; and add a standalone MCP-config extractor that emits server/package/env edges into the `links` table with a node-kind tag.
+- **Trade-offs**: Pro: smallest blast radius, KISS, reindex-safe; additive (low contract risk); independently testable. Con: relation/visibility vocabulary validated in several places (violates single-boundary constraint); no unified "all semantic edges" query path.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Unified edge-semantics layer over the links table
+- **Approach**: One `relation` column (plus visibility convention) on the existing `links` table, with every edge source routed through one data-driven relation/visibility vocabulary module that classifies and validates at a single ingestion boundary. Non-file entities (MCP servers/packages/env) reuse the synthetic-target pattern that `tag` edges already use. Search/query/dream read relation + visibility from this one column set.
+- **Trade-offs**: Pro: open/extensible vocabulary validated at exactly one boundary; maximally DRY; one read-path for surfacing + dream auto-population. Con: overloads `links` with heterogeneous edges (queries must filter by relation/kind); synthetic MCP "nodes" have no first-class attributes.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Dedicated typed graph subsystem (nodes + semantic edges tables)
+- **Approach**: New `graph_nodes` + `graph_edges` tables carrying `relation` and `visibility`, alongside `links` (which becomes a feeder). Central vocabulary registry validates at ingestion. All edge sources normalize into one node/edge model.
+- **Trade-offs**: Pro: cleanest model, first-class non-file nodes, most future-proof. Con: violates "extend existing surfaces, don't add parallel subsystems"; two graph representations to keep coherent; largest migration + highest reindex risk; most code for richness the four units don't yet need.
+- **Complexity**: large
+- **Risk**: high
+
+### Consultant recommendation: Variant 2
+Rationale (verbatim): the only variant that fully honors the binding constraints - open, data-driven vocabulary validated at a *single* boundary (V1 scatters it) while extending the existing `links` table rather than a parallel subsystem (V3's violation/risk). The synthetic-target convention from `tag` edges gives MCP entities a home without new tables, keeping the schema change to one appended migration and giving search/query/dream a single relation read-path.
+
+## Final decision: Variant 2, refined
+
+Agree with the consultant's choice of Variant 2 over 1 and 3, with two project-grounded refinements that the consultant could not know from outside:
+
+1. **Two graph surfaces stay separate; one vocabulary module unifies them.** OSB already has two graph representations by design - the search `links` table (a derived, reindexable SQLite cache) and the Brain-layer backlink index (`src/core/brain/backlinks.ts`, recomputed on demand over preferences/retired/signals/log, no cache). Variant 2's "one table" would force preference-domain relations into the derived cache, which is exactly the representation-merging risk that made Variant 3 dangerous. The single-validation-boundary value of Variant 2 is preserved instead by a shared `relation-vocab` module consumed by both surfaces - DRY at the vocabulary, not at the storage.
+
+2. **Visibility is a document axis, not an edge column.** The consultant suggested a `visibility` column on `links`. Visibility scopes a *page*, not a *relationship*, so it belongs in the existing `SearchOptions.properties` post-rank frontmatter filter as a reserved key plus one default scoping rule, honored identically by CLI and MCP - not on the edge row.
+
+These refinements keep the spirit of Variant 2 (extend existing surfaces, one open vocabulary, one validation boundary, synthetic targets for MCP entities) while fitting OSB's actual architecture. Variant 1 was rejected for scattering validation; Variant 3 for standing up a parallel subsystem against the project's explicit "extend, don't fork" convention and its reindex-risk.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index ce25b0f4..0944f04c 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -50,6 +50,7 @@ o2b brain doctor Check Brain-specific invariants (status-vs-folder,
o2b brain health Semantic-health report (since v0.14.0): contradictory confirmed preferences, recurring concepts with no dedicated preference, stale claims, plus a clean | watch | investigate verdict
o2b brain history Render a preference's edit-history timeline (since v0.14.0): one entry per content mutation (principle / scope / status before -> after)
o2b brain backlinks List inbound references to a Brain artifact id
+o2b brain mcp-landscape List MCP servers configured across the vault (since v0.19.0): name, source file, packages, required env-var names (values never read)
o2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yaml
o2b brain import-session Replay signals from a registered agent session .jsonl (or directory)
o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence
diff --git a/docs/mcp.md b/docs/mcp.md
index 23959443..880cf1c8 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -31,6 +31,7 @@ writer split below for the always-loaded writer subset.
| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | β€” |
| `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_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. | β€” |
| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | β€” |
@@ -258,7 +259,7 @@ server to your Codex MCP config the same way as Hermes.
The plugin's `.mcp.json` ships **two** MCP-server entries:
-- `open-second-brain` - the full surface (36 tools, including `brain_health`, `brain_agent_query`, `brain_agent_diff`, and `brain_pinned_context`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
+- `open-second-brain` - the full surface (41 tools, including `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, and `brain_pinned_context`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.
Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 576335e9..51f02225 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.18.0",
+ "version": "0.19.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 8766a758..e86fc63e 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -2675,6 +2675,9 @@ function parseFrontmatter(path) {
} catch {
return [{}, ""];
}
+ return parseFrontmatterText(text);
+}
+function parseFrontmatterText(text) {
const match = FRONTMATTER_RE.exec(text);
if (!match) {
return [{}, text.trim()];
diff --git a/package.json b/package.json
index 1d42dca4..a60249fb 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.18.0",
+ "version": "0.19.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 852ba174..92b89fc2 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.18.0"
+version: "0.19.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 355fc741..2b79be5b 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.18.0",
+ "version": "0.19.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 11afb390..13d9c57a 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.18.0"
+version: "0.19.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index eb08905a..ac53ac33 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.18.0"
+version = "0.19.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index c3f3bd7c..7158bb12 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -32,6 +32,7 @@ import {
cmdBrainHealth,
cmdBrainHistory,
cmdBrainBacklinks,
+ cmdBrainMcpLandscape,
cmdBrainMerge,
cmdBrainExplorer,
cmdBrainExport,
@@ -126,6 +127,8 @@ export async function handleBrainSubcommand(
return await cmdBrainHistory(rest);
case "backlinks":
return await cmdBrainBacklinks(rest);
+ case "mcp-landscape":
+ return await cmdBrainMcpLandscape(rest);
case "scan-inline":
return await cmdBrainScanInline(rest);
case "import-session":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 2472a06b..8e6e9a91 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -39,6 +39,7 @@ Brain verbs (observing memory):
health Semantic-health report: contradictions, concept gaps, stale claims
history Render a preference's edit-history timeline
backlinks List inbound references to a Brain artifact id
+ mcp-landscape List MCP servers configured across the vault (packages, env names)
scan-inline Capture @osb markers from folders listed under notes.read_paths in _brain.yaml
import-session Replay signals from a registered agent session .jsonl (or directory)
import-claude-memory Import metadata.type:feedback MEMORY entries as confirmed preferences
@@ -167,6 +168,11 @@ export const VERB_HELP: Record<string, string> = {
backlinks:
"usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +
"List inbound references to the given Brain artifact id (preference, retired, signal).\n",
+ "mcp-landscape":
+ "usage: o2b brain mcp-landscape [--vault <path>] [--json]\n" +
+ "List the Model Context Protocol servers configured across the vault: each\n" +
+ "server's name, the config file that declares it, the packages it pulls, and\n" +
+ "the env-var NAMES it requires. Environment values are never read. Read-only.\n",
"set-primary":
"usage: o2b brain set-primary <name> [--vault <path>] [--json]\n" +
" o2b brain set-primary --clear [--vault <path>] [--json]\n" +
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index a1631ee1..48fea059 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -19,6 +19,7 @@ export { cmdBrainDoctor } from "./doctor.ts";
export { cmdBrainHealth } from "./health.ts";
export { cmdBrainHistory } from "./history.ts";
export { cmdBrainBacklinks } from "./backlinks.ts";
+export { cmdBrainMcpLandscape } from "./mcp-landscape.ts";
export { cmdBrainMerge } from "./merge.ts";
export { cmdBrainExplorer } from "./explorer.ts";
export { cmdBrainExport } from "./export.ts";
diff --git a/src/cli/brain/verbs/mcp-landscape.ts b/src/cli/brain/verbs/mcp-landscape.ts
new file mode 100644
index 00000000..32405955
--- /dev/null
+++ b/src/cli/brain/verbs/mcp-landscape.ts
@@ -0,0 +1,27 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { buildMcpLandscape } from "../../../core/graph/mcp-config.ts";
+import { parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainMcpLandscape(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const landscape = buildMcpLandscape(vault);
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ servers: landscape.servers }, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`MCP servers configured in vault: ${landscape.servers.length}\n`);
+ for (const s of landscape.servers) {
+ process.stdout.write(` ${s.name} (${s.source})\n`);
+ if (s.packages.length > 0) process.stdout.write(` packages: ${s.packages.join(", ")}\n`);
+ if (s.env.length > 0) process.stdout.write(` env: ${s.env.join(", ")}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/search.ts b/src/cli/search.ts
index 1f29817a..d4279a13 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -119,6 +119,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
"semantic-weight": { type: "string" },
"auto-refresh": { type: "boolean" },
property: { type: "string-array" },
+ visibility: { type: "string-array" },
json: { type: "boolean" },
verbose: { type: "boolean" },
});
@@ -153,6 +154,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
flags["semantic"] === true ? true : flags["keyword-only"] === true ? false : undefined;
const properties = parsePropertyFlags(flags["property"] as string[] | undefined);
+ const visibility = flags["visibility"] as string[] | undefined;
const outcome = await search(cfg, {
query,
@@ -161,6 +163,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
keywordOnly: flags["keyword-only"] === true,
pathPrefix: typeof flags["path"] === "string" ? (flags["path"] as string) : undefined,
...(properties !== undefined ? { properties } : {}),
+ ...(visibility !== undefined && visibility.length > 0 ? { visibility } : {}),
});
if (flags["json"]) {
@@ -218,6 +221,7 @@ function jsonForOutcome(o: SearchOutcome): unknown {
reasons: r.reasons,
document_id: r.documentId,
chunk_id: r.chunkId,
+ ...(r.relations && r.relations.length > 0 ? { relations: r.relations } : {}),
})),
warnings: o.warnings,
total: o.total,
@@ -243,6 +247,10 @@ function renderOutcomeHuman(o: SearchOutcome, verbose: boolean): string {
if (verbose && r.reasons.length > 0) {
lines.push(` why: ${r.reasons.join(", ")}`);
}
+ if (r.relations && r.relations.length > 0) {
+ const rel = r.relations.map((x) => `${x.relation} ${x.target}`).join(", ");
+ lines.push(` relations: ${rel}`);
+ }
lines.push("");
});
for (const w of o.warnings) lines.push(`warning: ${w}`);
diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.ts
index 6b45910c..e1cd1909 100644
--- a/src/core/brain/backlinks.ts
+++ b/src/core/brain/backlinks.ts
@@ -29,6 +29,8 @@ import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { parseFrontmatter } from "../vault.ts";
+import { relationFromFrontmatterField } from "../graph/relation-vocab.ts";
+import { normalizeRelationTarget } from "../graph/frontmatter-relations.ts";
import { buildAliasIndex } from "./link-graph/alias-index.ts";
import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";
import { parseLogDay } from "./log.ts";
@@ -70,6 +72,15 @@ export interface BacklinkRef {
* want to show how the link was phrased.
*/
readonly aliasSource?: string;
+ /**
+ * Semantic relation type (v3 / typed graph semantics) when the
+ * carrying frontmatter field is a known relation
+ * (`related` / `extends` / `contradicts` / `superseded_by`). Absent
+ * for body wikilinks and non-relation fields (`evidenced_by`,
+ * `supersedes`, `retired_by`, …). Classified via the single
+ * vocabulary boundary in src/core/graph/relation-vocab.ts.
+ */
+ readonly relation?: string;
}
/** Frozen target β†’ refs map. Keys are normalised wikilink targets. */
@@ -196,15 +207,30 @@ function collectPreferences(
push(supersedes, { source, sourceKind: kind, field: "supersedes" });
}
if (kind === "retired") {
- const supersededBy = meta["superseded_by"];
- if (typeof supersededBy === "string" && supersededBy.length > 0) {
- push(supersededBy, { source, sourceKind: kind, field: "superseded_by" });
- }
const retiredBy = meta["retired_by"];
if (typeof retiredBy === "string" && retiredBy.length > 0) {
push(retiredBy, { source, sourceKind: kind, field: "retired_by" });
}
}
+ // Typed semantic relations (v3): map known relation frontmatter
+ // fields (related / extends / contradicts / superseded_by) to a
+ // relation type via the single vocabulary boundary. Covers any
+ // preference or retired artifact, generalising the prior
+ // retired-only `superseded_by` handling. Runs before the body
+ // wikilink pass so the relation-tagged ref wins dedup over a bare
+ // body reference to the same target.
+ for (const [field, value] of Object.entries(meta)) {
+ const relation = relationFromFrontmatterField(field);
+ if (!relation) continue;
+ const list = Array.isArray(value) ? value : typeof value === "string" && value ? [value] : [];
+ for (const t of list) {
+ if (typeof t !== "string" || t.length === 0) continue;
+ // The lightweight frontmatter parser can mangle `[[id]]` into
+ // `[id]`; recover the bare target before pushing.
+ const target = normalizeRelationTarget(t);
+ if (target) push(target, { source, sourceKind: kind, field, relation });
+ }
+ }
for (const body0 of extractWikilinkRichBodies(body)) {
push(body0, { source, sourceKind: kind, field: "body" });
}
diff --git a/src/core/graph/frontmatter-relations.ts b/src/core/graph/frontmatter-relations.ts
new file mode 100644
index 00000000..8c2a71da
--- /dev/null
+++ b/src/core/graph/frontmatter-relations.ts
@@ -0,0 +1,58 @@
+/**
+ * Extract typed relation edges from a page's frontmatter.
+ *
+ * A frontmatter field whose name is a known relation (`related`,
+ * `extends`, `contradicts`, `superseded_by` - see relation-vocab.ts)
+ * declares one edge per target. Targets may be written as Obsidian
+ * wikilinks (`[[id]]`), quoted (`"[[id]]"`), or bare ids, and the
+ * lightweight frontmatter parser sometimes mangles `[[id]]` into `[id]`;
+ * `normalizeRelationTarget` recovers the bare id from every shape.
+ */
+
+import type { FrontmatterMap } from "../types.ts";
+import { relationFromFrontmatterField } from "./relation-vocab.ts";
+
+export interface RelationEdge {
+ readonly relation: string;
+ readonly target: string;
+}
+
+/**
+ * Recover the bare link target from a frontmatter value, peeling any
+ * combination of wrapping `[[ ]]`, `[ ]`, and quotes, then dropping an
+ * alias (`|`) or heading/block anchor (`#`). Returns `null` when nothing
+ * usable remains.
+ */
+export function normalizeRelationTarget(raw: string): string | null {
+ let s = raw.trim();
+ let prev = "";
+ while (s !== prev) {
+ prev = s;
+ if (s.startsWith("[[") && s.endsWith("]]")) s = s.slice(2, -2).trim();
+ else if (s.startsWith("[") && s.endsWith("]")) s = s.slice(1, -1).trim();
+ else if (
+ (s.startsWith('"') && s.endsWith('"')) ||
+ (s.startsWith("'") && s.endsWith("'"))
+ ) {
+ s = s.slice(1, -1).trim();
+ }
+ }
+ const cuts = [s.indexOf("|"), s.indexOf("#")].filter((i) => i >= 0);
+ if (cuts.length > 0) s = s.slice(0, Math.min(...cuts)).trim();
+ return s.length > 0 ? s : null;
+}
+
+/** Every typed relation edge declared by this frontmatter, in field order. */
+export function extractFrontmatterRelations(meta: FrontmatterMap): RelationEdge[] {
+ const out: RelationEdge[] = [];
+ for (const [key, value] of Object.entries(meta)) {
+ const relation = relationFromFrontmatterField(key);
+ if (!relation) continue;
+ const items = Array.isArray(value) ? value : value === "" ? [] : [value];
+ for (const item of items) {
+ const target = normalizeRelationTarget(String(item));
+ if (target) out.push({ relation, target });
+ }
+ }
+ return out;
+}
diff --git a/src/core/graph/mcp-config.ts b/src/core/graph/mcp-config.ts
new file mode 100644
index 00000000..3ae10652
--- /dev/null
+++ b/src/core/graph/mcp-config.ts
@@ -0,0 +1,179 @@
+/**
+ * MCP-config extraction into the graph (typed graph semantics, unit 4).
+ *
+ * Parses Model Context Protocol server config files found in the vault
+ * into a typed landscape - which servers are configured, the packages
+ * they pull, and the env-var names they require. Environment VALUES are
+ * never read, so no secret can leak into the graph.
+ *
+ * Discovery is vault-relative and recompute-on-demand (no cache),
+ * matching the Brain-layer backlink index. It is NOT folded into the
+ * search `links` table: a `.json` config file is not a Markdown
+ * document, and the links table keys edges to a `documents` row.
+ *
+ * Identifiers (server / package / env names) are opaque tokens; nothing
+ * here hardcodes a natural-language phrase.
+ */
+
+import { readFileSync, readdirSync, statSync, type Dirent } from "node:fs";
+import { join } from "node:path";
+
+/** The config filenames recognised across common MCP hosts. */
+export const MCP_CONFIG_FILENAMES: ReadonlyArray<string> = Object.freeze([
+ ".mcp.json",
+ "mcp.json",
+ "mcp_servers.json",
+ "claude_desktop_config.json",
+]);
+
+const FILENAME_SET = new Set<string>(MCP_CONFIG_FILENAMES);
+
+/** Directories never descended into during discovery. */
+const SKIP_DIRS = new Set<string>([
+ ".git",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "node_modules",
+ ".open-second-brain",
+]);
+
+/** Commands that take a package reference as their first non-flag argument. */
+const PACKAGE_RUNNERS = new Set<string>(["npx", "bunx", "pnpx", "uvx", "pipx"]);
+/** Sub-command runners (`<tool> dlx <pkg>`, `<tool> exec <pkg>`). */
+const SUBCOMMAND_RUNNERS = new Set<string>(["pnpm", "yarn", "bun", "deno", "uv"]);
+const RUNNER_SUBCOMMANDS = new Set<string>(["dlx", "exec", "run", "x"]);
+
+export interface McpServerEntry {
+ /** Server key from the config object. */
+ readonly name: string;
+ /** Vault-relative path of the config file that declared it. */
+ readonly source: string;
+ /** Package references the server pulls (npm/pip style). Names only. */
+ readonly packages: string[];
+ /** Env-var NAMES the server requires. Values are never read. */
+ readonly env: string[];
+}
+
+/** True when `path`'s basename is a recognised MCP config filename. */
+export function isMcpConfigFile(path: string): boolean {
+ const base = path.split("/").pop() ?? path;
+ return FILENAME_SET.has(base);
+}
+
+function serversObject(parsed: unknown): Record<string, unknown> {
+ if (typeof parsed !== "object" || parsed === null) return {};
+ const obj = parsed as Record<string, unknown>;
+ const block = obj["mcpServers"] ?? obj["servers"];
+ if (typeof block !== "object" || block === null) return {};
+ return block as Record<string, unknown>;
+}
+
+function isFlag(arg: string): boolean {
+ return arg.startsWith("-");
+}
+
+/**
+ * A token that is not a package reference: a flag, or an inline
+ * `KEY=value` env assignment (whose value could be a secret). Both are
+ * skipped when selecting the package argument.
+ */
+function isNonPackageToken(arg: string): boolean {
+ return isFlag(arg) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(arg);
+}
+
+/** First non-flag argument from a runner's args (the package reference). */
+function packageFromArgs(command: string, args: string[]): string[] {
+ let rest = args;
+ if (SUBCOMMAND_RUNNERS.has(command)) {
+ // `pnpm dlx <pkg>`, `yarn dlx <pkg>`, `uv tool run <pkg>`, …
+ const first = args.find((a) => !isFlag(a));
+ if (first === undefined || !RUNNER_SUBCOMMANDS.has(first)) return [];
+ rest = args.slice(args.indexOf(first) + 1);
+ } else if (!PACKAGE_RUNNERS.has(command)) {
+ // A bare binary (node, python, docker, a local path) - no package.
+ return [];
+ }
+ const pkg = rest.find((a) => !isNonPackageToken(a));
+ return pkg ? [pkg] : [];
+}
+
+function parseServer(name: string, def: unknown, source: string): McpServerEntry {
+ const packages: string[] = [];
+ const env: string[] = [];
+ if (typeof def === "object" && def !== null) {
+ const d = def as Record<string, unknown>;
+ const command = typeof d["command"] === "string" ? (d["command"] as string) : null;
+ const args = Array.isArray(d["args"]) ? d["args"].filter((a): a is string => typeof a === "string") : [];
+ if (command) packages.push(...packageFromArgs(command, args));
+ const envObj = d["env"];
+ if (typeof envObj === "object" && envObj !== null) {
+ // Keys only - values are deliberately never read.
+ env.push(...Object.keys(envObj as Record<string, unknown>));
+ }
+ }
+ return { name, source, packages, env };
+}
+
+/** Parse one MCP config file's text into its declared server entries. */
+export function parseMcpConfig(jsonText: string, source: string): McpServerEntry[] {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(jsonText);
+ } catch {
+ return [];
+ }
+ const servers = serversObject(parsed);
+ return Object.entries(servers).map(([name, def]) => parseServer(name, def, source));
+}
+
+function findConfigFiles(vault: string): string[] {
+ const found: string[] = [];
+ const walk = (absDir: string, relDir: string): void => {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(absDir, { withFileTypes: true, encoding: "utf8" });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const rel = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name)) continue;
+ walk(join(absDir, entry.name), rel);
+ } else if (entry.isFile() && FILENAME_SET.has(entry.name)) {
+ found.push(rel);
+ }
+ }
+ };
+ try {
+ if (!statSync(vault).isDirectory()) return [];
+ } catch {
+ return [];
+ }
+ walk(vault, "");
+ return found.toSorted();
+}
+
+export interface McpLandscape {
+ readonly servers: McpServerEntry[];
+}
+
+/**
+ * Scan the vault for MCP config files and return the configured server
+ * landscape. Recompute-on-demand; never throws on a malformed or
+ * unreadable file (those contribute nothing).
+ */
+export function buildMcpLandscape(vault: string): McpLandscape {
+ const servers: McpServerEntry[] = [];
+ for (const rel of findConfigFiles(vault)) {
+ let text: string;
+ try {
+ text = readFileSync(join(vault, rel), "utf8");
+ } catch {
+ continue;
+ }
+ servers.push(...parseMcpConfig(text, rel));
+ }
+ return { servers };
+}
diff --git a/src/core/graph/relation-vocab.ts b/src/core/graph/relation-vocab.ts
new file mode 100644
index 00000000..865e705a
--- /dev/null
+++ b/src/core/graph/relation-vocab.ts
@@ -0,0 +1,59 @@
+/**
+ * Relation vocabulary - the single validation boundary for typed graph
+ * semantics (design: docs/brainstorm/typed-graph-semantics/design.md).
+ *
+ * Every edge producer (the indexer reading frontmatter relation fields,
+ * the MCP-config extractor) and every consumer (search surfacing, the
+ * Brain-layer backlink index) reads relation names from here. No
+ * relation string is hardcoded across call sites, and classification
+ * happens at this one boundary.
+ *
+ * The vocabulary is data-driven: a default set lives here, and adding a
+ * relation type is a one-line change to that set - never a schema
+ * migration, because the `links.relation` column carries no SQL CHECK.
+ * The frontmatter ingest path only emits relations whose field name is
+ * in this set (`relationFromFrontmatterField` returns `null` otherwise),
+ * so an unrecognised frontmatter key is simply not treated as a
+ * relation. `isKnownRelation` is the predicate callers use to validate a
+ * relation token against the vocabulary. Identifiers are language-neutral
+ * tokens, never human-facing prose, so nothing here hardcodes a
+ * natural-language phrase.
+ */
+
+/**
+ * The default semantic relation types. A frontmatter relation field
+ * name is identical to the relation it produces (`contradicts:` β†’
+ * `contradicts`), so this set doubles as the recognised frontmatter
+ * relation-field set.
+ */
+export const DEFAULT_RELATION_TYPES = Object.freeze([
+ "related",
+ "extends",
+ "contradicts",
+ "superseded_by",
+] as const);
+
+export type DefaultRelationType = (typeof DEFAULT_RELATION_TYPES)[number];
+
+const KNOWN = new Set<string>(DEFAULT_RELATION_TYPES);
+
+/** NFC-normalise, trim, and lower-case a relation token for comparison. */
+export function normalizeRelation(raw: string): string {
+ return raw.normalize("NFC").trim().toLowerCase();
+}
+
+/** True when `rel` (after normalisation) is part of the known vocabulary. */
+export function isKnownRelation(rel: string): boolean {
+ return KNOWN.has(normalizeRelation(rel));
+}
+
+/**
+ * Map a frontmatter field name to the relation it declares, or `null`
+ * when the field is not a relation field. The field name and the
+ * relation token are the same string; this helper is the one place that
+ * asserts that mapping so call sites don't re-derive it.
+ */
+export function relationFromFrontmatterField(field: string): string | null {
+ const norm = normalizeRelation(field);
+ return KNOWN.has(norm) ? norm : null;
+}
diff --git a/src/core/graph/visibility.ts b/src/core/graph/visibility.ts
new file mode 100644
index 00000000..43dcca06
--- /dev/null
+++ b/src/core/graph/visibility.ts
@@ -0,0 +1,57 @@
+/**
+ * Content visibility scoping (typed graph semantics, unit 3).
+ *
+ * A page may carry a `visibility:` frontmatter field (string or string
+ * array) that scopes which consumers can reach it. The rule, defined
+ * once here and consumed identically by the CLI and the MCP read
+ * surface:
+ *
+ * - A page with no `visibility:` is at DEFAULT visibility and is
+ * always reachable (zero behaviour change for vaults that never set
+ * the field).
+ * - A page that declares visibility values is reachable only when the
+ * caller's requested scope includes at least one of those values.
+ *
+ * Visibility values are opaque, language-neutral tokens (e.g. `private`,
+ * `team`, `agent:foo`); nothing here hardcodes a natural-language
+ * phrase or a closed enum.
+ */
+
+import type { FrontmatterMap } from "../types.ts";
+
+/** Lower-case + NFC + trim a single visibility token. */
+function normToken(raw: string): string {
+ return raw.normalize("NFC").trim().toLowerCase();
+}
+
+/**
+ * The visibility tokens a page declares. Empty array = default
+ * visibility (reachable by every consumer).
+ */
+export function pageVisibility(meta: FrontmatterMap): string[] {
+ const v = meta["visibility"];
+ const list = Array.isArray(v) ? v : typeof v === "string" && v.length > 0 ? [v] : [];
+ return list.map((s) => normToken(String(s))).filter((s) => s.length > 0);
+}
+
+/** Normalise a caller's requested visibility scope into a token set. */
+export function normalizeVisibilityScope(values: ReadonlyArray<string>): Set<string> {
+ const out = new Set<string>();
+ for (const v of values) {
+ const t = normToken(v);
+ if (t) out.add(t);
+ }
+ return out;
+}
+
+/**
+ * Is a page with `pageTags` reachable by a caller requesting `scope`?
+ * Default-visibility pages (no tags) are always reachable; a tagged
+ * page is reachable only when one of its tags is in the requested
+ * scope (an empty scope reaches default pages only).
+ */
+export function isVisible(pageTags: ReadonlyArray<string>, scope: ReadonlySet<string>): boolean {
+ if (pageTags.length === 0) return true;
+ for (const t of pageTags) if (scope.has(t)) return true;
+ return false;
+}
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index 82618e3a..72a6729c 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -28,6 +28,8 @@ import { basename, dirname } from "node:path";
import { chunkMarkdown } from "./chunker.ts";
import { makeProvider } from "./embeddings/provider.ts";
import { extractLinks } from "./links.ts";
+import { extractFrontmatterRelations } from "../graph/frontmatter-relations.ts";
+import { parseFrontmatterText } from "../vault.ts";
import { extractEntities } from "./entities.ts";
import { Store } from "./store.ts";
import { SearchError } from "./types.ts";
@@ -217,6 +219,21 @@ async function indexInto(
// deterministic entity set alongside its links.
store.replaceEntities(cid, extractEntities(content));
}
+ // Typed graph semantics (v3): frontmatter relation fields
+ // (related / extends / contradicts / superseded_by) become typed
+ // edges. They belong to the document, not a chunk, so anchor them
+ // on the first chunk (or null when the doc produced no chunks).
+ const [frontmatter] = parseFrontmatterText(content);
+ const relationChunkId = chunkIds[0] ?? null;
+ for (const edge of extractFrontmatterRelations(frontmatter)) {
+ links.push({
+ sourceChunkId: relationChunkId,
+ targetPath: edge.target,
+ linkText: null,
+ linkType: "wikilink",
+ relation: edge.relation,
+ });
+ }
store.replaceLinks(docId, links);
stats.chunksTotal += chunkInputs.length;
diff --git a/src/core/search/schema.ts b/src/core/search/schema.ts
index 9be3acaf..8fdc8114 100644
--- a/src/core/search/schema.ts
+++ b/src/core/search/schema.ts
@@ -16,7 +16,7 @@ import { SearchError } from "./types.ts";
* this raises `SCHEMA_MISMATCH` on open β€” the operator must reindex
* with a newer binary.
*/
-export const LATEST_SCHEMA_VERSION = 2;
+export const LATEST_SCHEMA_VERSION = 3;
const DDL_V1 = `
CREATE TABLE IF NOT EXISTS documents (
@@ -184,6 +184,22 @@ export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([
db.exec(DDL_V2_FTS);
},
},
+ {
+ // v3 (typed graph semantics) - a nullable `relation` column on
+ // `links` so an edge can carry a semantic relation type orthogonal
+ // to its syntactic `link_type`. No CHECK constraint: the relation
+ // vocabulary lives in the application layer
+ // (src/core/graph/relation-vocab.ts), so adding a relation type is a
+ // one-line change, never a migration. Existing rows keep a NULL
+ // relation until a reindex repopulates frontmatter-derived edges.
+ version: 3,
+ up(db) {
+ const cols = db.query<{ name: string }, []>("PRAGMA table_info(links)").all();
+ if (!cols.some((c) => c.name === "relation")) {
+ db.exec("ALTER TABLE links ADD COLUMN relation TEXT");
+ }
+ },
+ },
]);
/** Read the current schema version from `index_state`. Returns 0 if not yet recorded. */
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index d2a7c4dd..339c1955 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -12,6 +12,7 @@
import { join } from "node:path";
import { parseFrontmatter } from "../vault.ts";
+import { isVisible, normalizeVisibilityScope, pageVisibility } from "../graph/visibility.ts";
import { makeProvider } from "./embeddings/provider.ts";
import { extractEntities } from "./entities.ts";
import { runFtsQuery } from "./fts.ts";
@@ -118,6 +119,15 @@ export async function search(
// candidates to the filter and surface zero results even when
// matches exist deeper in the rank.
const hasPropertyFilter = opts.properties !== undefined && opts.properties.size > 0;
+ // An explicit visibility scope can also drop ranked rows, so it
+ // shares the property filter's overfetch. The default (no scope)
+ // path does NOT overfetch up front - all-untagged vaults stay
+ // byte-identical to prior behaviour - and instead relies on the
+ // one-shot backfill below when tagged pages actually shrink the
+ // window.
+ const visibilityScope = normalizeVisibilityScope(opts.visibility ?? []);
+ const hasVisibilityRequest = (opts.visibility?.length ?? 0) > 0;
+ const hasFrontmatterFilter = hasPropertyFilter || hasVisibilityRequest;
// MMR and traversal both need a candidate pool wider than `limit`:
// MMR diversifies from it, and traversal seeds expansion from it (a
@@ -128,60 +138,93 @@ export async function search(
const mmrActive = mmrLambda < 1;
const maxHops = opts.maxHops ?? config.recall.maxHops;
const traversalActive = maxHops > 0;
- const baseRankLimit = hasPropertyFilter ? Math.max(limit * 5, 50) : limit;
+ const baseRankLimit = hasFrontmatterFilter ? Math.max(limit * 5, 50) : limit;
const rankLimit =
mmrActive || traversalActive ? Math.max(baseRankLimit, limit * 3, 30) : baseRankLimit;
- let ranked = rankResults(
- {
- keyword: kwHits,
- semantic: semHits,
- hydrated,
- inboundLinkSources,
- tagsByDoc,
- ...(entityMatchByChunk !== undefined ? { entityMatchByChunk } : {}),
- },
- {
- keywordWeight: opts.keywordWeight ?? config.keywordWeight,
- semanticWeight: opts.semanticWeight ?? config.semanticWeight,
- limit: rankLimit,
- semanticEnabled: policy.wantSemantic && semanticAttempted,
- },
- );
-
- // Link-graph traversal (v0.13.0): walk outbound links from the top
- // hits and surface related documents not already matched, scored by
- // decay. No-op when maxHops == 0. Runs before MMR so expansions are
- // subject to the same diversity pass.
- if (traversalActive && ranked.length > 0) {
- ranked = applyTraversal(store, ranked, {
- maxHops,
- hopDecay: config.recall.hopDecay,
- maxExpansionPerHit: config.recall.maxExpansionPerHit,
- });
- }
+ // Rank β†’ traverse β†’ diversify β†’ property filter β†’ visibility scope,
+ // for a given candidate cap. Returns the pre-visibility count, the
+ // post-visibility list, and whether the cap was actually hit (so the
+ // caller can tell "the pool ran out" from "the cap truncated more").
+ const assemble = (
+ rankCap: number,
+ ): { preVisibility: number; visible: ReadonlyArray<BrainSearchResult>; capHit: boolean } => {
+ let ranked = rankResults(
+ {
+ keyword: kwHits,
+ semantic: semHits,
+ hydrated,
+ inboundLinkSources,
+ tagsByDoc,
+ ...(entityMatchByChunk !== undefined ? { entityMatchByChunk } : {}),
+ },
+ {
+ keywordWeight: opts.keywordWeight ?? config.keywordWeight,
+ semanticWeight: opts.semanticWeight ?? config.semanticWeight,
+ limit: rankCap,
+ semanticEnabled: policy.wantSemantic && semanticAttempted,
+ },
+ );
+ const capHit = ranked.length >= rankCap;
+ // Link-graph traversal (v0.13.0): walk outbound links from the top
+ // hits and surface related documents not already matched, scored by
+ // decay. No-op when maxHops == 0. Runs before MMR so expansions are
+ // subject to the same diversity pass.
+ if (traversalActive && ranked.length > 0) {
+ ranked = applyTraversal(store, ranked, {
+ maxHops,
+ hopDecay: config.recall.hopDecay,
+ maxExpansionPerHit: config.recall.maxExpansionPerHit,
+ });
+ }
+ // Diversity rerank (v0.13.0). No-op when lambda >= 1 or < 2 results.
+ if (mmrActive) {
+ ranked = mmrRerank(ranked, { lambda: mmrLambda });
+ }
+ // Optional post-rank property filter (v0.10.17). Reads each
+ // result's source frontmatter and drops rows whose scalars do not
+ // match the requested key/value pairs, then visibility scoping (v3)
+ // drops pages outside the requested visibility scope. Caching by
+ // document path bounds the read cost to the result set.
+ const propFiltered = hasPropertyFilter
+ ? applyPropertyFilter(ranked, opts.properties!, config.vault)
+ : ranked;
+ const visible = applyVisibilityScope(propFiltered, visibilityScope, config.vault);
+ return { preVisibility: propFiltered.length, visible, capHit };
+ };
- // Diversity rerank (v0.13.0). No-op when lambda >= 1 or < 2 results.
- if (mmrActive) {
- ranked = mmrRerank(ranked, { lambda: mmrLambda });
+ let assembled = assemble(rankLimit);
+ // Default-scope visibility (no explicit filter, so no overfetch above)
+ // can drop tagged pages and leave fewer than `limit` rows while more
+ // untagged matches sit deeper in the candidate pool. When that happens
+ // and the narrow cap was actually hit, re-assemble once at the wider
+ // cap from the same in-memory candidates - no extra DB fetch. Untagged
+ // vaults never drop rows, so this never fires and their results stay
+ // byte-identical.
+ if (
+ !hasFrontmatterFilter &&
+ assembled.visible.length < limit &&
+ assembled.visible.length < assembled.preVisibility &&
+ assembled.capHit
+ ) {
+ const wideCap = Math.max(limit * 5, 50, limit * 3, 30);
+ if (wideCap > rankLimit) assembled = assemble(wideCap);
}
+ const filtered = assembled.visible.slice(0, limit);
- // Optional post-rank property filter (v0.10.17). Reads each
- // result's source frontmatter and drops rows whose scalars do
- // not match the requested key/value pairs. Caching by document
- // path keeps the read cost bounded by the result set, not the
- // vault. After filtering we truncate back to the caller's
- // declared `limit` so the property-filter overfetch above
- // doesn't leak through.
- const filteredAll = hasPropertyFilter
- ? applyPropertyFilter(ranked, opts.properties!, config.vault)
- : ranked;
- const filtered = filteredAll.slice(0, limit);
+ // Typed graph semantics (v3): surface the typed relations each
+ // result page declares in its frontmatter. Computed here from the
+ // links table, never stored on the result row. One batched query.
+ const relByDoc = store.typedRelationsForDocuments(filtered.map((r) => r.documentId));
+ const withRelations = filtered.map((r) => {
+ const rels = relByDoc.get(r.documentId);
+ return rels && rels.length > 0 ? { ...r, relations: Object.freeze(rels) } : r;
+ });
return Object.freeze({
- results: Object.freeze(filtered),
+ results: Object.freeze(withRelations),
warnings: Object.freeze(warnings),
- total: filtered.length,
+ total: withRelations.length,
});
} finally {
await store.close();
@@ -268,6 +311,28 @@ function applyPropertyFilter(
return filterByProperties(ranked, filters, reader);
}
+function applyVisibilityScope(
+ ranked: ReadonlyArray<BrainSearchResult>,
+ scope: ReadonlySet<string>,
+ vault: string,
+): ReadonlyArray<BrainSearchResult> {
+ const cache = new Map<string, string[]>();
+ const tagsFor = (path: string): string[] => {
+ const cached = cache.get(path);
+ if (cached) return cached;
+ let tags: string[] = [];
+ try {
+ const [meta] = parseFrontmatter(join(vault, path));
+ tags = pageVisibility(meta);
+ } catch {
+ tags = [];
+ }
+ cache.set(path, tags);
+ return tags;
+ };
+ return ranked.filter((r) => isVisible(tagsFor(r.path), scope));
+}
+
interface SemanticPhaseOutcome {
readonly attempted: boolean;
readonly hits: ReturnType<Store["semanticTopK"]>;
diff --git a/src/core/search/store.ts b/src/core/search/store.ts
index 841d01cb..cf9c5c5f 100644
--- a/src/core/search/store.ts
+++ b/src/core/search/store.ts
@@ -85,6 +85,13 @@ export interface LinkInput {
readonly targetPath: string | null;
readonly linkText: string | null;
readonly linkType: "wikilink" | "markdown_link" | "tag";
+ /**
+ * Semantic relation type for this edge (v3 / typed graph semantics),
+ * orthogonal to `linkType`. `null`/absent for plain syntactic links;
+ * set for frontmatter-relation and MCP-config edges. Validated
+ * against the open vocabulary in src/core/graph/relation-vocab.ts.
+ */
+ readonly relation?: string | null;
}
export interface KeywordHit {
@@ -717,14 +724,22 @@ export class Store {
if (links.length > 0) {
const insert = this.db.prepare<
undefined,
- [number, number | null, string | null, string | null, string, string]
+ [number, number | null, string | null, string | null, string, string | null, string]
>(
- "INSERT INTO links(source_document_id, source_chunk_id, target_path, link_text, link_type, created_at) " +
- "VALUES (?, ?, ?, ?, ?, ?)",
+ "INSERT INTO links(source_document_id, source_chunk_id, target_path, link_text, link_type, relation, created_at) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
);
const now = nowIso();
for (const l of links) {
- insert.run(sourceDocumentId, l.sourceChunkId, l.targetPath, l.linkText, l.linkType, now);
+ insert.run(
+ sourceDocumentId,
+ l.sourceChunkId,
+ l.targetPath,
+ l.linkText,
+ l.linkType,
+ l.relation ?? null,
+ now,
+ );
}
}
this.db.exec("COMMIT");
@@ -741,6 +756,36 @@ export class Store {
);
}
+ /**
+ * For each document id, the typed relation edges it declares
+ * (v3 / typed graph semantics): rows whose `relation` is set, in
+ * insertion order. The target is the edge's `target_path` as written.
+ * Documents with no typed edges are absent from the returned map.
+ */
+ typedRelationsForDocuments(
+ documentIds: ReadonlyArray<number>,
+ ): Map<number, Array<{ relation: string; target: string }>> {
+ const out = new Map<number, Array<{ relation: string; target: string }>>();
+ if (documentIds.length === 0) return out;
+ const placeholders = documentIds.map(() => "?").join(",");
+ const rows = this.db
+ .query<{ source_document_id: number; relation: string; target_path: string | null }, number[]>(
+ "SELECT source_document_id, relation, target_path FROM links " +
+ `WHERE source_document_id IN (${placeholders}) AND relation IS NOT NULL ` +
+ "ORDER BY id",
+ )
+ .all(...(documentIds as number[]));
+ for (const r of rows) {
+ const target = r.target_path ?? "";
+ if (target === "") continue;
+ const arr = out.get(r.source_document_id);
+ const edge = { relation: r.relation, target };
+ if (arr) arr.push(edge);
+ else out.set(r.source_document_id, [edge]);
+ }
+ return out;
+ }
+
// ── search ─────────────────────────────────────────────────────────────────
/**
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 775ad12b..b2e31fc6 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -53,6 +53,14 @@ export interface BrainSearchResult {
* never empty for a result that surfaced.
*/
readonly reasons: ReadonlyArray<string>;
+ /**
+ * Typed semantic relations this result's page declares in its
+ * frontmatter (v3 / typed graph semantics): `related` / `extends` /
+ * `contradicts` / `superseded_by` and any other vocabulary relation.
+ * Computed at query time from the links table, never stored on the
+ * result row. Absent when the page declares no typed relations.
+ */
+ readonly relations?: ReadonlyArray<{ readonly relation: string; readonly target: string }>;
}
export interface IndexStats {
@@ -139,6 +147,14 @@ export interface SearchOptions {
* resolved config default; `0` disables traversal for this query.
*/
readonly maxHops?: number;
+ /**
+ * Requested content-visibility scope (v3 / typed graph semantics).
+ * Pages with no `visibility:` frontmatter are always returned;
+ * a page that declares visibility values is returned only when this
+ * scope includes one of them. Absent/empty = default scope (reaches
+ * untagged pages only). See src/core/graph/visibility.ts.
+ */
+ readonly visibility?: ReadonlyArray<string>;
}
export interface SearchOutcome {
diff --git a/src/core/vault.ts b/src/core/vault.ts
index b4a7198c..ad02a966 100644
--- a/src/core/vault.ts
+++ b/src/core/vault.ts
@@ -62,7 +62,15 @@ export function parseFrontmatter(path: string): readonly [FrontmatterMap, string
} catch {
return [{}, ""];
}
+ return parseFrontmatterText(text);
+}
+/**
+ * Same parse as {@link parseFrontmatter} but over an in-memory string,
+ * so a caller that already holds the file content (e.g. the search
+ * indexer) does not pay a second `readFileSync`.
+ */
+export function parseFrontmatterText(text: string): readonly [FrontmatterMap, string] {
const match = FRONTMATTER_RE.exec(text);
if (!match) {
return [{}, text.trim()];
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 4e5dc473..044869db 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -102,6 +102,7 @@ import {
import { appendLogEvent } from "../core/brain/log.ts";
import type { BrainLogEntry } from "../core/brain/log.ts";
import { appendBrainNote } from "../core/brain/note.ts";
+import { buildMcpLandscape } from "../core/graph/mcp-config.ts";
import {
appendPinnedContext,
clearPinnedContext,
@@ -1628,6 +1629,19 @@ async function toolBrainContextPack(
};
}
+async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {
+ const landscape = buildMcpLandscape(ctx.vault);
+ return {
+ vault_path: ctx.vault,
+ servers: landscape.servers.map((s) => ({
+ name: s.name,
+ source: s.source,
+ packages: s.packages,
+ env: s.env,
+ })),
+ };
+}
+
export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_feedback",
@@ -2043,6 +2057,37 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainHealth,
},
+ {
+ name: "brain_mcp_landscape",
+ description:
+ "List the Model Context Protocol servers configured across the vault: each server's name, the config file that declares it, the packages it pulls, and the env-var NAMES it requires. Environment values are never read. Discovery is vault-relative. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
+ outputSchema: {
+ type: "object",
+ required: ["vault_path", "servers"],
+ properties: {
+ vault_path: { type: "string" },
+ servers: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["name", "source", "packages", "env"],
+ properties: {
+ name: { type: "string" },
+ source: { type: "string" },
+ packages: { type: "array", items: { type: "string" } },
+ env: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ },
+ },
+ handler: toolMcpLandscape,
+ },
{
name: "brain_backlinks",
description:
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index d9621601..b2ea7977 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -40,6 +40,12 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
items: { type: "string" },
},
},
+ visibility: {
+ type: "array",
+ description:
+ "Optional content-visibility scope (v3). Pages with no `visibility:` frontmatter are always returned; a page that declares visibility values is returned only when this scope includes one of them. Absent = default scope (untagged pages only).",
+ items: { type: "string" },
+ },
},
required: ["query"],
additionalProperties: false,
@@ -72,6 +78,17 @@ const SEARCH_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
endLine: { type: "integer" },
searchType: { type: "string" },
reasons: { type: "array", items: { type: "string" } },
+ relations: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["relation", "target"],
+ properties: {
+ relation: { type: "string" },
+ target: { type: "string" },
+ },
+ },
+ },
},
},
},
@@ -121,6 +138,21 @@ function parsePropertiesArgument(
return map;
}
+function parseVisibilityArgument(raw: unknown): string[] | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (!Array.isArray(raw)) {
+ throw new MCPError(INVALID_PARAMS, "argument 'visibility' must be an array of strings");
+ }
+ const out: string[] = [];
+ for (const item of raw) {
+ if (typeof item !== "string") {
+ throw new MCPError(INVALID_PARAMS, "argument 'visibility' must contain only strings");
+ }
+ if (item.length > 0) out.push(item);
+ }
+ return out;
+}
+
function truncateContent(c: string, max: number): string {
if (c.length <= max) return c;
return c.slice(0, max - 1) + "…";
@@ -177,6 +209,7 @@ async function toolBrainSearch(
const keywordOnly = coerceBoolOptional(args, "keyword_only") ?? false;
const pathPrefix = coerceStringOptional(args, "path_prefix", 256);
const properties = parsePropertiesArgument(args["properties"]);
+ const visibility = parseVisibilityArgument(args["visibility"]);
const config = resolveSearchConfig({
vault: ctx.vault,
@@ -193,6 +226,7 @@ async function toolBrainSearch(
keywordOnly,
pathPrefix,
...(properties !== undefined ? { properties } : {}),
+ ...(visibility !== undefined ? { visibility } : {}),
}),
SEARCH_TIMEOUT_MS,
searchTimeoutError,
@@ -214,6 +248,7 @@ async function toolBrainSearch(
endLine: r.endLine,
searchType: r.searchType,
reasons: r.reasons,
+ ...(r.relations && r.relations.length > 0 ? { relations: r.relations } : {}),
})),
warnings: outcome.warnings,
total: outcome.total,
diff --git a/tests/cli/search.test.ts b/tests/cli/search.test.ts
index 1c087474..fdeae552 100644
--- a/tests/cli/search.test.ts
+++ b/tests/cli/search.test.ts
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
+import { LATEST_SCHEMA_VERSION } from "../../src/core/search/schema.ts";
let tmp: string;
let vault: string;
@@ -63,7 +64,7 @@ test("search status --json after an index returns documents count", async () =>
const obj = JSON.parse(out.stdout);
expect(obj.exists).toBe(true);
expect(obj.documents).toBe(2);
- expect(obj.schema_version).toBe(2);
+ expect(obj.schema_version).toBe(LATEST_SCHEMA_VERSION);
});
test("search query returns a human-readable hit for indexed content", async () => {
diff --git a/tests/core/brain/backlinks-relation.test.ts b/tests/core/brain/backlinks-relation.test.ts
new file mode 100644
index 00000000..6476fac3
--- /dev/null
+++ b/tests/core/brain/backlinks-relation.test.ts
@@ -0,0 +1,92 @@
+/**
+ * Typed graph semantics (unit 2) - the Brain-layer backlink index
+ * records a `relation` per ref when the carrying frontmatter field is a
+ * known relation, generalising the prior `superseded_by` handling to the
+ * full vocabulary via the single relation-vocab boundary.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildBacklinkIndex } from "../../../src/core/brain/backlinks.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-backlinks-relation-"));
+ bootstrapBrain(vault);
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("a contradicts frontmatter field tags its ref with relation 'contradicts'", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-foo.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "_status: confirmed",
+ "principle: example",
+ "contradicts: [[pref-bar]]",
+ "---",
+ "",
+ "body",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("pref-bar") ?? [];
+ expect(refs.length).toBe(1);
+ expect(refs[0]?.relation).toBe("contradicts");
+ expect(refs[0]?.field).toBe("contradicts");
+});
+
+test("a retired pref's superseded_by ref carries relation 'superseded_by'", () => {
+ writeFileSync(
+ join(vault, "Brain", "retired", "ret-old.md"),
+ [
+ "---",
+ "kind: retired",
+ "topic: old",
+ "_status: retired",
+ "principle: stale rule",
+ "superseded_by: [[pref-new]]",
+ "---",
+ "",
+ "body",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("pref-new") ?? [];
+ const superseded = refs.find((r) => r.field === "superseded_by");
+ expect(superseded).toBeDefined();
+ expect(superseded?.relation).toBe("superseded_by");
+});
+
+test("a non-vocabulary field (supersedes) carries no relation", () => {
+ // `supersedes` is the inverse of `superseded_by` and is deliberately
+ // NOT part of the relation vocabulary, so its ref must stay untyped.
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-foo.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "_status: confirmed",
+ "principle: example",
+ "supersedes: pref-old",
+ "---",
+ "",
+ "body",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("pref-old") ?? [];
+ expect(refs.length).toBe(1);
+ expect(refs[0]?.field).toBe("supersedes");
+ expect(refs[0]?.relation).toBeUndefined();
+});
diff --git a/tests/core/graph/mcp-config.test.ts b/tests/core/graph/mcp-config.test.ts
new file mode 100644
index 00000000..a556d441
--- /dev/null
+++ b/tests/core/graph/mcp-config.test.ts
@@ -0,0 +1,133 @@
+/**
+ * MCP-config extraction into the graph (typed graph semantics, unit 4).
+ *
+ * Parses MCP server config files found in the vault into a typed
+ * landscape (server / package / env-requirement), discarding env
+ * VALUES. Discovery is vault-relative only.
+ */
+
+import { test, expect, beforeEach, afterEach, describe } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ buildMcpLandscape,
+ isMcpConfigFile,
+ MCP_CONFIG_FILENAMES,
+ parseMcpConfig,
+} from "../../../src/core/graph/mcp-config.ts";
+
+describe("parseMcpConfig (pure)", () => {
+ test("extracts server, package (npx) and env-requirement names", () => {
+ const json = JSON.stringify({
+ mcpServers: {
+ memory: {
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-memory"],
+ env: { MEMORY_TOKEN: "tok-123", REGION: "eu" },
+ },
+ },
+ });
+ const servers = parseMcpConfig(json, ".mcp.json");
+ expect(servers).toHaveLength(1);
+ const s = servers[0]!;
+ expect(s.name).toBe("memory");
+ expect(s.source).toBe(".mcp.json");
+ expect(s.packages).toEqual(["@modelcontextprotocol/server-memory"]);
+ expect(s.env.toSorted()).toEqual(["MEMORY_TOKEN", "REGION"]);
+ });
+
+ test("env VALUES are discarded - only names survive", () => {
+ const json = JSON.stringify({
+ mcpServers: {
+ secretful: {
+ command: "uvx",
+ args: ["some-mcp-package"],
+ env: { API_KEY: "sk-DO-NOT-LEAK-abc123", PASSWORD: "hunter2" },
+ },
+ },
+ });
+ const servers = parseMcpConfig(json, "mcp.json");
+ const blob = JSON.stringify(servers);
+ expect(blob).not.toContain("sk-DO-NOT-LEAK-abc123");
+ expect(blob).not.toContain("hunter2");
+ expect(servers[0]!.env.toSorted()).toEqual(["API_KEY", "PASSWORD"]);
+ expect(servers[0]!.packages).toEqual(["some-mcp-package"]);
+ });
+
+ test("an inline KEY=value positional is never captured as a package", () => {
+ const json = JSON.stringify({
+ mcpServers: {
+ inlined: { command: "npx", args: ["TOKEN=sk-inline-leak-xyz", "@scope/pkg"] },
+ },
+ });
+ const servers = parseMcpConfig(json, ".mcp.json");
+ expect(servers[0]!.packages).toEqual(["@scope/pkg"]);
+ expect(JSON.stringify(servers)).not.toContain("sk-inline-leak-xyz");
+ });
+
+ test("a local-binary command yields no package edge", () => {
+ const json = JSON.stringify({
+ mcpServers: { local: { command: "node", args: ["./server.js"] } },
+ });
+ const servers = parseMcpConfig(json, ".mcp.json");
+ expect(servers[0]!.packages).toEqual([]);
+ });
+
+ test("the `servers` key is accepted as well as `mcpServers`", () => {
+ const json = JSON.stringify({ servers: { x: { command: "npx", args: ["pkg-x"] } } });
+ expect(parseMcpConfig(json, ".mcp.json")).toHaveLength(1);
+ });
+
+ test("malformed JSON yields an empty list, never throws", () => {
+ expect(parseMcpConfig("{ not json", ".mcp.json")).toEqual([]);
+ });
+});
+
+describe("isMcpConfigFile", () => {
+ test("recognises the four supported filenames, by basename", () => {
+ for (const name of MCP_CONFIG_FILENAMES) {
+ expect(isMcpConfigFile(name)).toBe(true);
+ expect(isMcpConfigFile(`nested/dir/${name}`)).toBe(true);
+ }
+ expect(isMcpConfigFile("package.json")).toBe(false);
+ expect(isMcpConfigFile("notes/foo.md")).toBe(false);
+ });
+});
+
+describe("buildMcpLandscape (vault-relative discovery)", () => {
+ let vault: string;
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-mcp-config-"));
+ });
+ afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+ test("discovers config files across the vault and groups by server", () => {
+ writeFileSync(
+ join(vault, ".mcp.json"),
+ JSON.stringify({ mcpServers: { a: { command: "npx", args: ["-y", "pkg-a"] } } }),
+ );
+ mkdirSync(join(vault, "tools"), { recursive: true });
+ writeFileSync(
+ join(vault, "tools", "claude_desktop_config.json"),
+ JSON.stringify({ mcpServers: { b: { command: "uvx", args: ["pkg-b"], env: { B_KEY: "x" } } } }),
+ );
+ const land = buildMcpLandscape(vault);
+ const names = land.servers.map((s) => s.name).toSorted();
+ expect(names).toEqual(["a", "b"]);
+ const b = land.servers.find((s) => s.name === "b")!;
+ expect(b.packages).toEqual(["pkg-b"]);
+ expect(b.env).toEqual(["B_KEY"]);
+ });
+
+ test("does not scan ignored directories like .git", () => {
+ mkdirSync(join(vault, ".git"), { recursive: true });
+ writeFileSync(
+ join(vault, ".git", "mcp.json"),
+ JSON.stringify({ mcpServers: { ghost: { command: "npx", args: ["ghost"] } } }),
+ );
+ const land = buildMcpLandscape(vault);
+ expect(land.servers.map((s) => s.name)).not.toContain("ghost");
+ });
+});
diff --git a/tests/core/graph/relation-vocab.test.ts b/tests/core/graph/relation-vocab.test.ts
new file mode 100644
index 00000000..a9e88d3c
--- /dev/null
+++ b/tests/core/graph/relation-vocab.test.ts
@@ -0,0 +1,45 @@
+/**
+ * The relation vocabulary is the single validation boundary for typed
+ * graph semantics. It owns the open/extensible set of semantic relation
+ * names and the one normalize/classify function every edge producer and
+ * consumer reads from - no relation string is hardcoded across call
+ * sites.
+ */
+
+import { test, expect } from "bun:test";
+
+import {
+ DEFAULT_RELATION_TYPES,
+ isKnownRelation,
+ normalizeRelation,
+ relationFromFrontmatterField,
+} from "../../../src/core/graph/relation-vocab.ts";
+
+test("the default vocabulary covers the four declared relation types", () => {
+ const actual: string[] = [...DEFAULT_RELATION_TYPES];
+ expect(actual.toSorted()).toEqual(["contradicts", "extends", "related", "superseded_by"]);
+});
+
+test("normalizeRelation is NFC + trimmed + lower-cased", () => {
+ expect(normalizeRelation(" Superseded_By ")).toBe("superseded_by");
+ expect(normalizeRelation("CONTRADICTS")).toBe("contradicts");
+});
+
+test("isKnownRelation accepts the vocabulary and rejects anything else", () => {
+ for (const r of DEFAULT_RELATION_TYPES) expect(isKnownRelation(r)).toBe(true);
+ expect(isKnownRelation("Contradicts")).toBe(true); // normalized before lookup
+ expect(isKnownRelation("supersedes")).toBe(false); // not a frontmatter relation field
+ expect(isKnownRelation("bogus")).toBe(false);
+ expect(isKnownRelation("")).toBe(false);
+});
+
+test("relationFromFrontmatterField maps a known relation field to its relation, else null", () => {
+ expect(relationFromFrontmatterField("contradicts")).toBe("contradicts");
+ expect(relationFromFrontmatterField("Superseded_By")).toBe("superseded_by");
+ expect(relationFromFrontmatterField("title")).toBeNull();
+ expect(relationFromFrontmatterField("aliases")).toBeNull();
+});
+
+test("DEFAULT_RELATION_TYPES is frozen so the vocabulary can't drift at runtime", () => {
+ expect(Object.isFrozen(DEFAULT_RELATION_TYPES)).toBe(true);
+});
diff --git a/tests/core/search/indexer.test.ts b/tests/core/search/indexer.test.ts
index 149cb720..f8d622dd 100644
--- a/tests/core/search/indexer.test.ts
+++ b/tests/core/search/indexer.test.ts
@@ -9,6 +9,7 @@ import {
indexCheck,
} from "../../../src/core/search/indexer.ts";
import { Store } from "../../../src/core/search/store.ts";
+import { LATEST_SCHEMA_VERSION } from "../../../src/core/search/schema.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
let vault: string;
@@ -101,7 +102,7 @@ test("indexStatus reports accurate counts after an index run", async () => {
const status = await indexStatus(cfg);
expect(status.exists).toBe(true);
- expect(status.schemaVersion).toBe(2);
+ expect(status.schemaVersion).toBe(LATEST_SCHEMA_VERSION);
expect(status.documents).toBe(2);
expect(status.chunks).toBeGreaterThanOrEqual(2);
expect(status.lastIndexedAt).toBeTruthy();
diff --git a/tests/core/search/schema-migration-v2.test.ts b/tests/core/search/schema-migration-v2.test.ts
index 31a0ae37..c9f00d1c 100644
--- a/tests/core/search/schema-migration-v2.test.ts
+++ b/tests/core/search/schema-migration-v2.test.ts
@@ -37,10 +37,10 @@ function hasTable(db: Database, name: string): boolean {
);
}
-test("fresh migration reaches v2 and creates chunk_entities", () => {
+test("fresh migration reaches the latest version and creates chunk_entities", () => {
const db = new Database(dbPath);
- expect(applyMigrations(db)).toBe(2);
- expect(LATEST_SCHEMA_VERSION).toBe(2);
+ expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
+ expect(LATEST_SCHEMA_VERSION).toBeGreaterThanOrEqual(2);
expect(hasTable(db, "chunk_entities")).toBe(true);
db.close();
});
@@ -62,7 +62,7 @@ test("a v1 index upgrades to v2, adding chunk_entities and preserving data", ()
db.run("UPDATE index_state SET value = '1' WHERE key = 'schema_version'");
expect(readSchemaVersion(db)).toBe(1);
- expect(applyMigrations(db)).toBe(2);
+ expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(hasTable(db, "chunk_entities")).toBe(true);
// Pre-existing rows survive the upgrade.
const docs = db.query<{ c: number }, []>("SELECT count(*) AS c FROM documents").get();
diff --git a/tests/core/search/schema-migration-v3.test.ts b/tests/core/search/schema-migration-v3.test.ts
new file mode 100644
index 00000000..63dad1b8
--- /dev/null
+++ b/tests/core/search/schema-migration-v3.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Schema migration v2 -> v3 (typed graph semantics). v3 adds a nullable
+ * `relation` column to the `links` table so an edge can carry a semantic
+ * relation type (related / extends / contradicts / superseded_by / ...)
+ * orthogonal to its syntactic `link_type`. A fresh index lands at v3; an
+ * existing v2 index upgrades cleanly without losing link rows.
+ */
+
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { Database } from "bun:sqlite";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ applyMigrations,
+ LATEST_SCHEMA_VERSION,
+ readSchemaVersion,
+} from "../../../src/core/search/schema.ts";
+
+let tmp: string;
+let dbPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-mig-v3-"));
+ dbPath = join(tmp, "test.sqlite");
+});
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function linksColumns(db: Database): string[] {
+ return db
+ .query<{ name: string }, []>("PRAGMA table_info(links)")
+ .all()
+ .map((r) => r.name);
+}
+
+test("fresh migration reaches v3 and links carries a relation column", () => {
+ const db = new Database(dbPath);
+ expect(applyMigrations(db)).toBe(3);
+ expect(LATEST_SCHEMA_VERSION).toBe(3);
+ expect(linksColumns(db)).toContain("relation");
+ db.close();
+});
+
+test("applyMigrations is idempotent at the latest version", () => {
+ const db = new Database(dbPath);
+ expect(applyMigrations(db)).toBe(3);
+ // Re-running must not throw and must not double-add the column.
+ expect(applyMigrations(db)).toBe(3);
+ expect(linksColumns(db).filter((c) => c === "relation")).toHaveLength(1);
+ db.close();
+});
+
+test("a v2 index upgrades to v3, adding relation and preserving link rows", () => {
+ const db = new Database(dbPath);
+ applyMigrations(db); // -> v3
+ db.run(
+ "INSERT INTO documents(id, path, title, content_hash, mtime, size, created_at, updated_at, indexed_at) " +
+ "VALUES (1, 'a.md', 'A', 'h', 1, 1, 't', 't', 't')",
+ );
+ db.run(
+ "INSERT INTO links(id, source_document_id, source_chunk_id, target_path, link_text, link_type, created_at) " +
+ "VALUES (1, 1, NULL, 'b.md', 'B', 'wikilink', 't')",
+ );
+ // Simulate an older v2 index: drop the new column and rewind the version.
+ db.run("ALTER TABLE links DROP COLUMN relation");
+ db.run("UPDATE index_state SET value = '2' WHERE key = 'schema_version'");
+ expect(readSchemaVersion(db)).toBe(2);
+ expect(linksColumns(db)).not.toContain("relation");
+
+ expect(applyMigrations(db)).toBe(3);
+ expect(linksColumns(db)).toContain("relation");
+ // The pre-existing link row survives, with a NULL relation.
+ const row = db
+ .query<{ c: number; relation: string | null }, []>(
+ "SELECT count(*) AS c, relation FROM links WHERE id = 1",
+ )
+ .get();
+ expect(row?.c).toBe(1);
+ expect(row?.relation).toBeNull();
+ db.close();
+});
diff --git a/tests/core/search/store.test.ts b/tests/core/search/store.test.ts
index 3442cb90..dec37d42 100644
--- a/tests/core/search/store.test.ts
+++ b/tests/core/search/store.test.ts
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { Store } from "../../../src/core/search/store.ts";
+import { LATEST_SCHEMA_VERSION } from "../../../src/core/search/schema.ts";
import { SearchError } from "../../../src/core/search/types.ts";
import type {
ResolvedSearchConfig,
@@ -51,7 +52,7 @@ afterEach(() => {
test("open in write mode creates file and applies migrations", async () => {
const store = await Store.open(makeConfig(), { mode: "write", loadVec: false });
expect(existsSync(dbPath)).toBe(true);
- expect(store.schemaVersion()).toBe(2);
+ expect(store.schemaVersion()).toBe(LATEST_SCHEMA_VERSION);
await store.close();
});
@@ -69,7 +70,7 @@ test("open in read mode succeeds after writer creates the file", async () => {
const w = await Store.open(makeConfig(), { mode: "write", loadVec: false });
await w.close();
const r = await Store.open(makeConfig(), { mode: "read", loadVec: false });
- expect(r.schemaVersion()).toBe(2);
+ expect(r.schemaVersion()).toBe(LATEST_SCHEMA_VERSION);
await r.close();
});
diff --git a/tests/core/search/typed-relations.test.ts b/tests/core/search/typed-relations.test.ts
new file mode 100644
index 00000000..7033b47f
--- /dev/null
+++ b/tests/core/search/typed-relations.test.ts
@@ -0,0 +1,87 @@
+/**
+ * Typed frontmatter relationships (typed graph semantics, unit 2).
+ *
+ * A page declares semantic relationships in frontmatter
+ * (`related` / `extends` / `contradicts` / `superseded_by`). The indexer
+ * turns those into typed edges in the links table (relation set via the
+ * single vocabulary boundary), and a search result for the declaring
+ * page surfaces them inline.
+ */
+
+import { test, expect, beforeEach, afterEach } from "bun:test";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { search } from "../../../src/core/search/search.ts";
+import { Store } from "../../../src/core/search/store.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("typed-relations"));
+});
+afterEach(() => cleanup());
+
+const PAGE_A = [
+ "---",
+ "title: Alpha",
+ "contradicts: [[b]]",
+ 'superseded_by: "[[c]]"',
+ "related: [d, e]",
+ "---",
+ "# Alpha",
+ "",
+ "A note about quantum foxes and their habits.",
+].join("\n");
+
+test("frontmatter relation fields become typed edges in the links table", async () => {
+ writeMd(vault, "a.md", PAGE_A);
+ writeMd(vault, "b.md", "# Beta\n\nunrelated body");
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+
+ const store = await Store.open(cfg, { mode: "read", loadVec: false });
+ try {
+ const aId = store.getDocumentIdByPath("a.md");
+ expect(aId).not.toBeNull();
+ const rels = store.typedRelationsForDocuments([aId!]).get(aId!) ?? [];
+ const got = rels.map((r) => `${r.relation}:${r.target}`).toSorted();
+ // The lightweight frontmatter parser mangles `[[b]]` -> `[b]`; the
+ // target normaliser must recover the bare id either way.
+ expect(got).toEqual(
+ ["contradicts:b", "related:d", "related:e", "superseded_by:c"].toSorted(),
+ );
+ } finally {
+ await store.close();
+ }
+});
+
+test("a plain page with no relation frontmatter produces no typed edges", async () => {
+ writeMd(vault, "plain.md", "# Plain\n\njust prose, links to [[other]] in body");
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+
+ const store = await Store.open(cfg, { mode: "read", loadVec: false });
+ try {
+ const id = store.getDocumentIdByPath("plain.md")!;
+ const rels = store.typedRelationsForDocuments([id]).get(id) ?? [];
+ expect(rels).toHaveLength(0); // the body wikilink is a plain edge, no relation
+ } finally {
+ await store.close();
+ }
+});
+
+test("search surfaces a result page's declared relations inline", async () => {
+ writeMd(vault, "a.md", PAGE_A);
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+
+ const out = await search(cfg, { query: "quantum foxes", limit: 5 });
+ const hit = out.results.find((r) => r.path === "a.md");
+ expect(hit).toBeDefined();
+ const summary = (hit!.relations ?? []).map((r) => `${r.relation}:${r.target}`).toSorted();
+ expect(summary).toContain("contradicts:b");
+ expect(summary).toContain("superseded_by:c");
+});
diff --git a/tests/core/search/visibility-filter.test.ts b/tests/core/search/visibility-filter.test.ts
new file mode 100644
index 00000000..77063ae9
--- /dev/null
+++ b/tests/core/search/visibility-filter.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Content visibility scoping (typed graph semantics, unit 3).
+ *
+ * A page tagged with a non-default `visibility:` is hidden from a
+ * default search and reachable only when the caller requests that
+ * visibility. Untagged pages are unaffected (zero regression).
+ */
+
+import { test, expect, beforeEach, afterEach, describe } from "bun:test";
+
+import { isVisible, normalizeVisibilityScope, pageVisibility } from "../../../src/core/graph/visibility.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { search } from "../../../src/core/search/search.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+describe("visibility rule (pure)", () => {
+ test("a page with no visibility tag is always reachable", () => {
+ expect(pageVisibility({ title: "x" })).toEqual([]);
+ expect(isVisible([], normalizeVisibilityScope([]))).toBe(true);
+ expect(isVisible([], normalizeVisibilityScope(["private"]))).toBe(true);
+ });
+
+ test("a tagged page is reachable only when its tag is in scope", () => {
+ const tags = pageVisibility({ visibility: ["Private"] });
+ expect(tags).toEqual(["private"]); // normalised
+ expect(isVisible(tags, normalizeVisibilityScope([]))).toBe(false);
+ expect(isVisible(tags, normalizeVisibilityScope(["private"]))).toBe(true);
+ expect(isVisible(tags, normalizeVisibilityScope(["team"]))).toBe(false);
+ });
+});
+
+describe("visibility scoping in search", () => {
+ let vault: string;
+ let dbPath: string;
+ let cleanup: () => void;
+
+ beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("visibility"));
+ });
+ afterEach(() => cleanup());
+
+ test("a private page is excluded by default and included when requested", async () => {
+ writeMd(vault, "public.md", "# Public\n\nshared lattice notes about widgets");
+ writeMd(
+ vault,
+ "secret.md",
+ "---\nvisibility: [private]\n---\n# Secret\n\nclassified lattice notes about widgets",
+ );
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+
+ const def = await search(cfg, { query: "lattice widgets", limit: 10 });
+ const defPaths = def.results.map((r) => r.path).toSorted();
+ expect(defPaths).toEqual(["public.md"]);
+
+ const scoped = await search(cfg, { query: "lattice widgets", limit: 10, visibility: ["private"] });
+ const scopedPaths = scoped.results.map((r) => r.path).toSorted();
+ expect(scopedPaths).toEqual(["public.md", "secret.md"]);
+ });
+
+ test("default scope backfills untagged matches when tagged pages crowd a narrow pool", async () => {
+ // Recall layers off (mmrLambda=1, maxHops=0) -> the narrow rank cap
+ // would otherwise let tagged pages truncate the window below `limit`.
+ // The backfill must still surface `limit` untagged matches.
+ for (let i = 0; i < 6; i++) {
+ writeMd(vault, `secret-${i}.md`, "---\nvisibility: [private]\n---\nlattice widget secret " + i);
+ }
+ for (let i = 0; i < 4; i++) {
+ writeMd(vault, `public-${i}.md`, "# Public " + i + "\n\nlattice widget public " + i);
+ }
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+
+ const out = await search(cfg, { query: "lattice widget", limit: 4, mmrLambda: 1, maxHops: 0 });
+ const paths = out.results.map((r) => r.path).toSorted();
+ expect(paths).toEqual(["public-0.md", "public-1.md", "public-2.md", "public-3.md"]);
+ expect(out.results.every((r) => r.path.startsWith("public-"))).toBe(true);
+ });
+
+ test("an all-untagged vault is unaffected by the default scope", async () => {
+ writeMd(vault, "a.md", "# A\n\nlattice alpha");
+ writeMd(vault, "b.md", "# B\n\nlattice beta");
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+
+ const out = await search(cfg, { query: "lattice", limit: 10 });
+ expect(out.results.map((r) => r.path).toSorted()).toEqual(["a.md", "b.md"]);
+ });
+});
diff --git a/tests/mcp/mcp-landscape.test.ts b/tests/mcp/mcp-landscape.test.ts
new file mode 100644
index 00000000..0aff4030
--- /dev/null
+++ b/tests/mcp/mcp-landscape.test.ts
@@ -0,0 +1,58 @@
+/**
+ * `brain_mcp_landscape` exposes the configured MCP servers across the
+ * vault (typed graph semantics, unit 4), through the same handler path
+ * the MCP server uses. Env values never appear in the output.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";
+
+let vault: string;
+let ctx: { vault: string };
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-landscape-"));
+ ctx = { vault };
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+describe("brain_mcp_landscape", () => {
+ test("returns configured servers with packages and env names, no env values", async () => {
+ writeFileSync(
+ join(vault, ".mcp.json"),
+ JSON.stringify({
+ mcpServers: {
+ memory: {
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-memory"],
+ env: { MEMORY_SECRET: "sk-leak-me-please-987" },
+ },
+ },
+ }),
+ );
+ const tool = BRAIN_TOOLS.find((t) => t.name === "brain_mcp_landscape");
+ expect(tool).toBeDefined();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const out = (await tool!.handler(ctx as any, {})) as {
+ servers: Array<{ name: string; source: string; packages: string[]; env: string[] }>;
+ };
+ expect(out.servers).toHaveLength(1);
+ expect(out.servers[0]!.name).toBe("memory");
+ expect(out.servers[0]!.packages).toEqual(["@modelcontextprotocol/server-memory"]);
+ expect(out.servers[0]!.env).toEqual(["MEMORY_SECRET"]);
+ expect(JSON.stringify(out)).not.toContain("sk-leak-me-please-987");
+ });
+
+ test("a vault with no MCP config files yields an empty server list", async () => {
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(join(vault, "notes", "x.md"), "# X");
+ const tool = BRAIN_TOOLS.find((t) => t.name === "brain_mcp_landscape")!;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const out = (await tool.handler(ctx as any, {})) as { servers: unknown[] };
+ expect(out.servers).toEqual([]);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 1b8239b0..ff095692 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -205,6 +205,7 @@ describe("tool listing", () => {
"brain_agent_diff",
"brain_doctor",
"brain_health",
+ "brain_mcp_landscape",
"brain_backlinks",
"brain_context_pack",
"brain_unlinked_mentions",
@@ -464,7 +465,8 @@ describe("stdio loop", () => {
// v0.15.0; brain_pinned_context added in v0.16.0; lifecycle review
// tools added in v0.17.0) + 8 Pay Memory + 1 Search
// + brain_artifact_get (v0.18.0) = 40.
- expect(list.result.tools.length).toBe(40);
+ // + brain_mcp_landscape (typed graph semantics) = 41.
+ expect(list.result.tools.length).toBe(41);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/search-relations.test.ts b/tests/mcp/search-relations.test.ts
new file mode 100644
index 00000000..f396bb4f
--- /dev/null
+++ b/tests/mcp/search-relations.test.ts
@@ -0,0 +1,79 @@
+/**
+ * `brain_search` surfaces a result page's typed frontmatter relations
+ * (typed graph semantics, unit 2). Exercises the tool through the same
+ * handler path the MCP server uses, against a freshly indexed vault.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";
+import { indexVault, resolveSearchConfig } from "../../src/core/search/index.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let ctx: { vault: string; configPath: string };
+
+beforeEach(async () => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-rel-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-rel-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "notes", "alpha.md"),
+ [
+ "---",
+ "title: Alpha",
+ "contradicts: [[beta]]",
+ 'superseded_by: "[[gamma]]"',
+ "---",
+ "",
+ "The quick brown fox jumps over the lazy dog.",
+ ].join("\n"),
+ );
+ ctx = { vault, configPath };
+ const config = resolveSearchConfig({ vault, configPath });
+ await indexVault(config, {});
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("brain_search typed relations", () => {
+ test("a result page's declared relations surface inline", async () => {
+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search");
+ expect(tool).toBeDefined();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const out = (await tool!.handler(ctx as any, { query: "quick fox" })) as {
+ results: Array<{ path: string; relations?: Array<{ relation: string; target: string }> }>;
+ };
+ const hit = out.results.find((r) => r.path.endsWith("alpha.md"));
+ expect(hit).toBeDefined();
+ const summary = (hit!.relations ?? []).map((r) => `${r.relation}:${r.target}`).toSorted();
+ expect(summary).toEqual(["contradicts:beta", "superseded_by:gamma"]);
+ });
+
+ test("a result page with no relations omits the field", async () => {
+ writeFileSync(
+ join(vault, "notes", "plain.md"),
+ "---\ntitle: Plain\n---\n\nThe quick brown fox again, plainly.",
+ );
+ const config = resolveSearchConfig({ vault, configPath: ctx.configPath });
+ await indexVault(config, {});
+
+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search")!;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const out = (await tool.handler(ctx as any, { query: "plainly" })) as {
+ results: Array<{ path: string; relations?: unknown }>;
+ };
+ const hit = out.results.find((r) => r.path.endsWith("plain.md"));
+ expect(hit).toBeDefined();
+ expect(hit!.relations).toBeUndefined();
+ });
+});
diff --git a/tests/mcp/search.test.ts b/tests/mcp/search.test.ts
index 0143ae30..4e12556b 100644
--- a/tests/mcp/search.test.ts
+++ b/tests/mcp/search.test.ts
@@ -15,6 +15,7 @@ import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { indexVault } from "../../src/core/search/indexer.ts";
import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import { LATEST_SCHEMA_VERSION } from "../../src/core/search/schema.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
let tmp: string;
@@ -181,7 +182,7 @@ test("second_brain_status includes search block after indexing", async () => {
expect(search).toBeDefined();
expect(search!["exists"]).toBe(true);
expect(search!["documents"]).toBe(1);
- expect(search!["schema_version"]).toBe(2);
+ expect(search!["schema_version"]).toBe(LATEST_SCHEMA_VERSION);
});
test("second_brain_status reports search.exists=false when index missing", async () => {
diff --git a/tests/mcp/visibility-scope.test.ts b/tests/mcp/visibility-scope.test.ts
new file mode 100644
index 00000000..d6ea8f6d
--- /dev/null
+++ b/tests/mcp/visibility-scope.test.ts
@@ -0,0 +1,74 @@
+/**
+ * `brain_search` honours the content-visibility scope (typed graph
+ * semantics, unit 3) through the same handler path the MCP server uses.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";
+import { indexVault, resolveSearchConfig } from "../../src/core/search/index.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let ctx: { vault: string; configPath: string };
+
+beforeEach(async () => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-vis-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-vis-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "notes", "public.md"),
+ "---\ntitle: Public\n---\n\nshared lattice notes about widgets",
+ );
+ writeFileSync(
+ join(vault, "notes", "secret.md"),
+ "---\nvisibility: [private]\n---\n# Secret\n\nclassified lattice notes about widgets",
+ );
+ ctx = { vault, configPath };
+ const config = resolveSearchConfig({ vault, configPath });
+ await indexVault(config, {});
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function paths(out: { results: Array<{ path: string }> }): string[] {
+ return out.results.map((r) => r.path).toSorted();
+}
+
+describe("brain_search visibility scope", () => {
+ test("a private page is hidden by default", async () => {
+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search")!;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const out = (await tool.handler(ctx as any, { query: "lattice widgets" })) as {
+ results: Array<{ path: string }>;
+ };
+ expect(paths(out)).toEqual(["notes/public.md"]);
+ });
+
+ test("the private page appears when its visibility is requested", async () => {
+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search")!;
+ const out = (await tool.handler(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ctx as any,
+ { query: "lattice widgets", visibility: ["private"] },
+ )) as { results: Array<{ path: string }> };
+ expect(paths(out)).toEqual(["notes/public.md", "notes/secret.md"]);
+ });
+
+ test("a non-array visibility argument is rejected", async () => {
+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search")!;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await expect(tool.handler(ctx as any, { query: "lattice", visibility: "private" })).rejects.toThrow(
+ /visibility/,
+ );
+ });
+});