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

v0.10.17 - link graph surfaces (aliases, anchors, mentions, synthesis, MOC audit, property filter, vault instruction) (#33)

Sol Aitkend0598affa141
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a3825e5f..7617f308 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.16",
+ "version": "0.10.17",
"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 4c1fd755..c858213e 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.16",
+ "version": "0.10.17",
"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 d12cbd32..df2ba8a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,132 @@ 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.10.17] - 2026-05-25
+
+Link graph surfaces: seven related features that expose the vault
+as a connected graph. A new `src/core/brain/link-graph/` subsystem
+holds pure helpers (rich wikilink parse, frontmatter alias index,
+unlinked-mentions scanner, concept-cluster assembler, per-MOC
+audit). The backlink index now resolves Obsidian-style frontmatter
+`aliases:` arrays and preserves `#heading` / `#^block-id` anchors
+on every `BacklinkRef`. Three new MCP tools
+(`brain_unlinked_mentions`, `brain_concept_synthesis`,
+`brain_moc_audit`) and three new CLI verbs (`o2b brain unlinked`,
+`synthesise`, `moc-audit`) surface the helpers; `brain_search`
+gains an optional `properties` argument and `o2b search` grows a
+repeatable `--property KEY=VALUE` flag for frontmatter-scalar
+filters; `brain_context` envelope optionally surfaces a vault-root
+instruction file (`VAULT.md` by default).
+
+### Added
+
+- `src/core/brain/link-graph/parse-wikilink.ts` -
+ `parseWikilinkRich(value)` returns
+ `{target, anchor, block, alias}` for any Obsidian wikilink
+ shape; existing `parseWikilink` / `normaliseWikilinkTarget`
+ string contracts are unchanged. Sibling helper
+ `extractWikilinkRichBodies(content)` yields full bracket bodies
+ so anchor info survives the body walk.
+- `src/core/brain/link-graph/alias-index.ts` -
+ `buildAliasIndex(vault)` walks `Brain/preferences/` +
+ `Brain/retired/` and returns a frozen
+ `Map<aliasLowerNFC, canonicalId>`. Collisions resolve first-wins
+ by sorted canonical id; aliases that would shadow an existing
+ on-disk basename are silently dropped (no backlink hijack).
+- `src/core/brain/link-graph/unlinked-mentions.ts` -
+ `findUnlinkedMentions(vault, targetId, opts)` returns raw-text
+ occurrences of the target's title / aliases that are NOT inside
+ `[[...]]` brackets and NOT inside code spans. **Language-agnostic
+ by construction** - matches only via Unicode codepoint classes
+ (`\p{L}`, `\p{N}`), rejects single-codepoint terms.
+- `src/core/brain/link-graph/concept-cluster.ts` -
+ `buildConceptCluster(vault, targetId, opts)` assembles a
+ deterministic envelope: target + every linker (depth-1) +
+ optional unlinked mentions. Pure assembler; no LLM call.
+- `src/core/brain/link-graph/moc-audit.ts` -
+ `auditMoc(vault, hubId, opts)` classifies cluster members into
+ `wellCovered`, `fragile`, `candidateMissing`, plus a
+ `suggestedNext` pick. MOC detection is purely structural -
+ outbound link count + non-whitespace link-density ratio. No
+ vocabulary detection of "this looks like a MOC".
+- `src/core/search/property-filter.ts` -
+ `filterByProperties(rows, filters, reader)` is a pure post-FTS
+ phase. Multi-value within a key = OR; multiple keys = AND.
+ Dependency-injected frontmatter reader keeps the helper testable
+ without I/O.
+- `src/core/brain/vault-instruction-file.ts` -
+ `readVaultInstructionFile(vault, name?)` reads a vault-root
+ user-authored instruction file (default `VAULT.md`,
+ configurable via `link_graph.vault_instruction_file`).
+ Rejects unsafe overrides at config time (absolute paths, `..`
+ segments). `brain_context` envelope grows an optional
+ `vault_instruction: {path, content, lines}` field; absent file
+ = field omitted.
+- New atoms on existing types:
+ - `BacklinkRef` (`src/core/brain/backlinks.ts`) gains optional
+ `targetAnchor`, `targetBlock`, `aliasSource` fields. Existing
+ consumers reading only the four legacy fields keep compiling.
+ - `SearchOptions.properties` (`src/core/search/types.ts`)
+ optional `ReadonlyMap<string, ReadonlyArray<string>>`.
+- New `link_graph:` block in `_brain.yaml`
+ (`src/core/brain/policy.ts`):
+ - `moc_min_outbound_links` (default 5)
+ - `moc_min_link_ratio` (default 0.3)
+ - `vault_instruction_file` (default `VAULT.md`)
+- Three new full-scope MCP tools (`src/mcp/brain-tools.ts`):
+ - `brain_unlinked_mentions(id, limit?)`
+ - `brain_concept_synthesis(id, include_unlinked?)`
+ - `brain_moc_audit(id)`
+- `brain_search` (`src/mcp/search-tools.ts`) accepts an optional
+ `properties` argument; the schema validates each key maps to
+ an array of strings.
+- Three new CLI verbs:
+ - `o2b brain unlinked <id> [--limit N] [--json]`
+ - `o2b brain synthesise <id> [--include-unlinked] [--json]`
+ - `o2b brain moc-audit <id> [--json]`
+- `o2b search` grows a repeatable `--property KEY=VALUE` flag
+ (`src/cli/search.ts`); malformed entries fail loudly with a
+ usage error before any I/O.
+
+### Changed
+
+- `buildBacklinkIndex` (`src/core/brain/backlinks.ts`) rewrites
+ its push helper to consult the alias index and call
+ `parseWikilinkRich` on every incoming target string, populating
+ the new `BacklinkRef.targetAnchor` / `targetBlock` /
+ `aliasSource` fields. Dedup key now includes the anchor/block
+ so two refs to different sections of the same target keep both
+ entries.
+- `brain_context` envelope additively grows the optional
+ `vault_instruction` field. Hosts that strip unknown fields stay
+ byte-identical.
+- README capability bullets describe the new link-graph surfaces,
+ property-filtered search, and vault-root instruction file. MCP
+ tool inventory bumps from 11 to 14 Brain tools.
+
+### Notes
+
+- **Language-agnostic by construction.** None of the new
+ helpers uses a vocabulary list, stopword set, per-language
+ regex table, or unit dictionary. Detectors rely on Unicode
+ codepoint classes and structural sigils only.
+- **Backward compatibility by construction.** New fields on
+ `BacklinkRef` are additive optionals. Existing consumers that
+ destructure only the four legacy fields keep compiling. The
+ `brain_context` envelope's `vault_instruction` field is absent
+ when the file is missing. `SearchOptions.properties` absent =
+ identical pre-v0.10.17 behaviour.
+- **No new external dependencies.** Helpers use only
+ `node:fs`, `node:path`, and existing internal utilities.
+- **No LLM calls in core helpers.** `buildConceptCluster` and
+ `auditMoc` are pure assemblers; downstream consumers can feed
+ the deterministic envelope to an LLM later.
+- Three new tools register in the full MCP scope only. The
+ writer-scope surface stays at four tools
+ (`brain_feedback`, `brain_apply_evidence`, `brain_note`,
+ `brain_context`); the last grows the additive
+ `vault_instruction` field on the existing envelope.
+
## [0.10.16] - 2026-05-25
Trust and operator surfaces: eight related self-reporting features
@@ -2553,6 +2679,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0
[0.9.1]: https://github.com/itechmeat/open-second-brain/compare/v0.9.0...v0.9.1
[0.9.0]: https://github.com/itechmeat/open-second-brain/compare/v0.8.1...v0.9.0
+[0.10.17]: https://github.com/itechmeat/open-second-brain/compare/v0.10.16...v0.10.17
[0.10.16]: https://github.com/itechmeat/open-second-brain/compare/v0.10.15...v0.10.16
[0.10.15]: https://github.com/itechmeat/open-second-brain/compare/v0.10.14...v0.10.15
[0.10.14]: https://github.com/itechmeat/open-second-brain/compare/v0.10.13...v0.10.14
diff --git a/README.md b/README.md
index 780c10ce..af9a78a3 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,29 @@ safety invariants are in [`docs/how-it-works.md`](docs/how-it-works.md).
(`o2b brain summary` / `brain_operator_summary`). The verdict
band (`clean | watch | investigate`) is computed from
structural signals only - no LLM, no per-language vocabulary.
+- Exposes the vault as a connected link graph: frontmatter
+ `aliases:` resolve transparently into the backlink index;
+ every `BacklinkRef` keeps `#heading` / `#^block-id` anchors so
+ consumers see paragraph-level intent; raw-text mentions outside
+ `[[...]]` surface via `o2b brain unlinked` /
+ `brain_unlinked_mentions`; a concept-scoped cluster (target +
+ linkers, optionally + unlinked mentions) lands as a
+ deterministic JSON envelope via `o2b brain synthesise` /
+ `brain_concept_synthesis`; per-MOC coverage audit classifies
+ cluster members into well-covered / fragile / candidate-missing
+ via `o2b brain moc-audit` / `brain_moc_audit`. Match boundaries
+ are Unicode-aware (codepoint class) and the MOC heuristic uses
+ link density only - no per-language vocabulary anywhere.
+- Layers structured property filters on top of full-text search
+ (`o2b search "<query>" --property type=decision --property
+ status=open`). The filter applies to frontmatter scalars as a
+ post-FTS phase; `additionalProperties` extension on
+ `brain_search` mirrors it at the MCP boundary.
+- Surfaces a user-authored vault-root instruction file
+ (`VAULT.md` by default, configurable via
+ `link_graph.vault_instruction_file`) through the `brain_context`
+ envelope. Absent file = field omitted; existing hosts stay
+ byte-identical.
- (Optional) Records paid agent actions through **Pay Memory**:
receipts, generated assets, spending policy decisions, human
approval state, and per-day reports — all as plain Markdown
@@ -204,10 +227,12 @@ exposes the same deterministic operations as MCP tools:
- **Core (3):** `second_brain_status`, `second_brain_query`,
`vault_health`.
-- **Brain (11):** `brain_feedback`, `brain_dream`,
+- **Brain (14):** `brain_feedback`, `brain_dream`,
`brain_apply_evidence`, `brain_note`, `brain_context`,
`brain_digest`, `brain_query`, `brain_doctor`, `brain_backlinks`,
- `brain_context_pack`, `brain_operator_summary`. See the
+ `brain_context_pack`, `brain_unlinked_mentions`,
+ `brain_concept_synthesis`, `brain_moc_audit`,
+ `brain_operator_summary`. See the
[Brain section](#brain-observing-memory) below.
- **Pay Memory (8):** `payment_memory_init`,
`payment_receipt_append`, `asset_capture`,
diff --git a/docs/brainstorm/link-graph-surfaces/cli-output/claude.md b/docs/brainstorm/link-graph-surfaces/cli-output/claude.md
new file mode 100644
index 00000000..624cd6ff
--- /dev/null
+++ b/docs/brainstorm/link-graph-surfaces/cli-output/claude.md
@@ -0,0 +1,37 @@
+### Variant 1: Single `link-graph` subsystem (strict precedent match)
+- **Approach**: Mint one new subsystem `src/core/brain/link-graph/` that hosts every pure helper for features 1-5 (alias resolver, anchor extractor, unlinked-mention scanner, concept-cluster assembler, MOC classifier). Atoms extend `BacklinkRef` (anchor + alias-source fields) in place under `backlinks.ts` and add `aliases` to the in-memory note record from `vault.ts`; consumers are new CLI verbs / MCP tools that import from `link-graph/`. Feature 6 lands as `src/core/search/property-filter.ts` inside the existing search layer, and feature 7 lands as a small extension to whichever loader already injects `active.md` into session context.
+- **Trade-offs**:
+ - Pro: Mirrors v0.10.15 / v0.10.16 exactly - one themed subdir, atoms/helpers/consumers DAG, predictable for reviewers.
+ - Pro: Helpers are co-located, so `synthesise` and `moc-audit` can re-use the alias / anchor / unlinked-mention helpers without cross-subsystem imports.
+ - Pro: Search and session-context changes stay in their natural layers instead of being dragged into a `brain/` subdir where they don't belong.
+ - Con: `link-graph/` becomes a relatively large bag (5 helpers) compared to the tighter v0.10.16 trust/ tree.
+ - Con: Two of seven features (property search, VAULT.md) sit outside the named release subsystem, so the release headline isn't quite "everything under one roof."
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Three small co-equal subsystems (one per concern)
+- **Approach**: Carve the release into three named subsystems - `src/core/brain/graph/` for link / backlink helpers (1-5), `src/core/brain/property-filter/` for the FTS-post property-filter phase (6), and `src/core/brain/vault-context/` for the VAULT.md loader (7). Each follows its own atoms/helpers/consumers DAG; the CHANGELOG groups them under one v0.10.17 header but the code tree is unambiguous about which file belongs to which feature cluster.
+- **Trade-offs**:
+ - Pro: Clean one-feature-cluster-per-subdir mapping; each subdir is small and individually testable.
+ - Pro: Property filter and VAULT.md are first-class members of the release, not "miscellaneous additions."
+ - Pro: Future bundles can grow any of the three without touching the others.
+ - Con: Breaks the "one new subsystem per release" precedent set by v0.10.15 and v0.10.16; three new subdirs in one PR is a noticeable convention drift.
+ - Con: `property-filter/` under `brain/` is awkward because the actual code is search-layer (FTS + chunks), not brain-layer; pulling it under `brain/` muddies the layering.
+ - Con: VAULT.md is a tiny addition that doesn't deserve its own subsystem; padding it out to atoms/helpers/consumers is ceremony for ~1 file of logic.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: In-place enrichment, single small subsystem only for read-views
+- **Approach**: Extend existing files directly for the structural plumbing: `wikilink.ts` keeps anchors instead of stripping them, `backlinks.ts` learns to resolve aliases when collecting refs, `search.ts` grows a property-filter post-phase, and the existing session-context loader learns about VAULT.md. Mint one small subsystem `src/core/brain/graph-views/` that only contains the higher-level read-only assemblers (unlinked-mentions scanner, concept-synthesis envelope builder, MOC audit classifier) - the things that genuinely need shared helpers and dedicated tests.
+- **Trade-offs**:
+ - Pro: Smallest blast radius - file count is well under 70, structural changes live next to the code they enrich, no orphan one-file subsystems.
+ - Pro: The new subdir holds only the genuinely novel logic (the three "views"), so its scope is crisp and its test directory is well-bounded.
+ - Pro: Property filter living inside `src/core/search/` matches the actual layer ownership, no awkward cross-tree imports.
+ - Con: Diverges from the recent two-release precedent where ALL new helpers landed inside the new subdir; reviewers used to that pattern may need orientation.
+ - Con: Atom-level extensions are scattered across `wikilink.ts`, `backlinks.ts`, and `search.ts` rather than visible in one diff stack, so the "what's the v0.10.17 shape change?" question takes more reading.
+ - Con: `graph-views/` doesn't capture the alias/anchor work in its name, so the release theme is split between "view helpers" and "graph plumbing upgrades."
+- **Complexity**: small
+- **Risk**: low
+
+### Recommended: Variant 1
+**Rationale**: It is the only variant that holds the line on the project's established two-release precedent (one named subsystem with the atoms / helpers / consumers DAG), which keeps reviewer mental model, test-directory layout, and CHANGELOG framing identical to v0.10.15 / v0.10.16. The two features that genuinely don't belong under `brain/link-graph/` (property search is search-layer, VAULT.md is session-context-layer) land in their natural layers without inventing ceremonial subsystems for them, avoiding Variant 2's drift while still keeping the headline "link-graph subsystem" intact - and unlike Variant 3, the foundational alias/anchor atoms remain visible as part of the new subsystem's shape rather than scattered across pre-existing files.
diff --git a/docs/brainstorm/link-graph-surfaces/cli-output/prompt.md b/docs/brainstorm/link-graph-surfaces/cli-output/prompt.md
new file mode 100644
index 00000000..445581da
--- /dev/null
+++ b/docs/brainstorm/link-graph-surfaces/cli-output/prompt.md
@@ -0,0 +1,92 @@
+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
+
+Open Second Brain v0.10.17 ships a bundle of seven related link-graph features. The thread tying them together: the vault is a connected graph, but Open Second Brain's link-graph layer (`src/core/brain/wikilink.ts`, `src/core/brain/backlinks.ts`) and search layer (`src/core/search/*`) currently throw away or never compute richer structure. Operators have to reconstruct that structure by hand.
+
+The seven kanban tasks bundled:
+
+1. **Frontmatter alias resolution for wikilink target index** - resolve Obsidian-style `aliases: [foo, bar]` frontmatter arrays when building the backlink index. Today, `[[foo]]` referring to an aliased note registers as a phantom node.
+
+2. **Block-link and heading-link granularity preservation in backlink index** - keep `#heading` and `#^block-id` anchor suffixes on every `BacklinkRef` instead of stripping them at parse time. Today `stripBasenameDecoration` drops anchor info before backlinks land in the index.
+
+3. **Unlinked-mentions surface for discovering missed connections** - for a target note, scan every other note for raw-text occurrences of the target's title (and any frontmatter alias) NOT inside `[[...]]` brackets. Return `(source, line, context)` tuples. Exposed as `o2b brain unlinked-mentions <id>` + `brain_unlinked_mentions` MCP. Depends on (1).
+
+4. **Concept-scoped synthesis over a note and its full backlink cluster** - given a target note id, gather the note + all notes that wikilink to it (depth=1). Emit a JSON envelope with consistent-thread / tensions / emergent-insight slots. Pure read-only assembly (no LLM call in the helper; consumers can feed the envelope to an LLM later). Exposed as `o2b brain synthesise <id>` + `brain_concept_synthesis` MCP.
+
+5. **Per-MOC topic-coverage gap analysis with fragile-vs-developed audit** - given a hub-note id whose outbound wikilinks form a cluster ("MOC"), classify each cluster member into well-covered / fragile / candidate-missing / suggested-next buckets. Heuristic MOC detection by link density. Exposed as `o2b brain moc-audit <id>` + `brain_moc_audit` MCP.
+
+6. **Intelligent property-filtered search across vault files** - layer property filters (`type`, `status`, `tags`, frontmatter scalars) on top of the existing FTS5 + semantic search. Today `search()` only accepts a query string + path prefix. Extend `SearchOptions` with a property filter map and run the property filter as a post-FTS phase.
+
+7. **Vault-root agent instruction file for session context** - read a configurable file at the vault root (e.g. `VAULT.md` - name TBD) at session start, alongside the existing active-preferences load. User-authored content; agents inject it into context. Distinct from `CLAUDE.md` / `AGENTS.md` which already exist as vault-root instruction files tracked by the v0.10.16 instruction-file-ceiling check - this one is OPEN-SECOND-BRAIN-specific and Brain-consumed.
+
+The bundle's DAG: alias resolution (1) is the foundation; (2) is independent atom; (3) depends on (1); (4) depends on (3) + backlinks; (5) depends on backlinks + outbound links; (6) is independent extension to search; (7) is independent small addition.
+
+# Project context
+
+Project name: Open Second Brain (full name in public artifacts; OSB acronym only in private notes)
+Language / runtime: TypeScript, Bun runtime
+Most recent releases:
+- v0.10.16 (just merged) - trust + operator surfaces: introduced `src/core/brain/trust/` subsystem (atoms / pure helpers / consumers DAG); language-agnostic preference quality gate; aggregate trust verdict; `brain_operator_summary` MCP + `o2b brain summary` CLI.
+- v0.10.15 - vault care bundle: `src/core/brain/page-meta/` and `src/core/brain/maintenance/` subsystems following the same atoms / helpers / consumers DAG.
+- v0.10.14 - index fastpath, redaction.
+- v0.10.13 - codegraph-partner skill + doctor.
+
+Recent commits (origin/main last 10):
+3b7dfe9 v0.10.16: trust and operator surfaces - verification, verdict, dashboard (#32)
+d045ea1 chore: bump version to 0.10.15 (#31)
+5755200 v0.10.15: vault care bundle - metadata, dedup, lint, context-pack, actions (#30)
+9d9636b feat: index fastpath, PEM/JWT redaction, vault connection health (v0.10.14) (#29)
+7d81f0b feat: codegraph-partner skill + o2b doctor check (v0.10.13) (#28)
+
+Related files:
+- `src/core/brain/wikilink.ts` - parsers: `normaliseWikilinkTarget`, `parseWikilink`, `stripBasenameDecoration`, `parseArtifactRef`. Anchor info dropped at line 64 (`s.slice(0, hash).trim()`).
+- `src/core/brain/backlinks.ts` - `BacklinkRef` interface (line 45); `buildBacklinkIndex` (line 68); collectors `collectPreferences`, `collectSignals`, `collectLog`.
+- `src/core/vault.ts` - `parseFrontmatter`, `extractWikilinks`. Frontmatter parser handles inline arrays (`[a, b]`).
+- `src/core/search/search.ts` - `search()` orchestrator (line 51).
+- `src/core/search/types.ts` - `SearchOptions` (line 109), `BrainSearchResult` (line 35).
+- `src/core/search/store.ts` - FTS5 store + chunk index.
+- `src/cli/brain/verbs/*.ts` - existing CLI verb structure: one file per verb, each implements `runVerb(args)`. 30 verbs today.
+- `src/mcp/brain-tools.ts` - MCP tool registry. Full scope vs writer scope split. After v0.10.16: 11 brain tools.
+- `src/core/brain/trust/` - precedent for "named subsystem per release" pattern. Atoms = data-shape additions on existing types; helpers = pure functions; consumers = existing tools call helpers.
+- `src/core/brain/page-meta/`, `src/core/brain/maintenance/` - same precedent, v0.10.15.
+
+Conventions:
+- Three-layer DAG per release: atoms (data-shape additions on existing summary types) → helpers (pure functions in a named subdir) → consumers (existing brain tools call helpers but keep public contract).
+- Each release ships ONE new subsystem subdirectory under `src/core/brain/<theme>/`.
+- All public surfaces (CLI verbs + MCP tools) are thin wrappers over pure helpers.
+- Atomic file writes everywhere - vault state must survive concurrent agents and crashes.
+- `vault-relative` paths in every public output (no leaked host absolute paths).
+- TDD: failing test first, then implementation, then commit per atomic unit.
+- One PR = one CHANGELOG version (may bundle several features under one version header).
+- Language-agnostic everywhere: no hardcoded vocabulary lists, no per-language regex tables, no stopword sets. If language differences must be handled, use codepoint-shape detection (Unicode property classes `\p{L}`, `\p{N}`, `\p{Script=...}`) only.
+- README is a flat capability description, not a migration story.
+- No `[Unreleased]` placeholder in CHANGELOG.
+- No AI authorship markers in public artifacts.
+- Backward compatibility by construction: new fields default to legacy behaviour; defaults strictly looser than every existing gate so existing tests stay byte-identical.
+
+Constraints:
+- Do NOT change any existing public API signature - extend with optional fields only.
+- Do NOT introduce new external dependencies. The project ships only `bun:sqlite`, `node:crypto`, `node:fs`, etc.
+- Do NOT hardcode any language-specific vocabulary in detectors. Anchor parsing is structural (the `#` sigil exists in the Obsidian link grammar, not in any natural language).
+- Do NOT add LLM calls inside core helpers. The concept-scoped synthesis helper assembles a deterministic JSON envelope; if a downstream tool wants LLM synthesis, it calls the LLM externally.
+- Each new feature must have its own dedicated tests under `tests/core/brain/<subsystem>/` or `tests/mcp/` or `tests/cli/`.
+- Each new MCP tool must be wired into the `full` scope only (not `writer`) unless it's a pure read with no quality-gate semantics.
+- Variant should fit in roughly 50-70 changed files total (precedent: v0.10.16 was 57 files).
+
+# 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/link-graph-surfaces/design.md b/docs/brainstorm/link-graph-surfaces/design.md
new file mode 100644
index 00000000..6e59e9f2
--- /dev/null
+++ b/docs/brainstorm/link-graph-surfaces/design.md
@@ -0,0 +1,283 @@
+# Link graph surfaces - design
+
+**Status:** draft
+**Author:** claude-vps-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain treats the vault as a connected graph but the
+link-graph layer (`src/core/brain/wikilink.ts`,
+`src/core/brain/backlinks.ts`) and the search layer
+(`src/core/search/*`) throw away or never compute the richer
+structure that operators need to act on connections. Anchor and
+block suffixes are stripped at parse time; frontmatter `aliases:` are
+unknown to the index so every aliased reference becomes a phantom
+node; raw-text mentions outside `[[...]]` are invisible; there is no
+read-only surface that assembles "this note plus everyone who links
+to it" into one structure; per-hub coverage gaps are invisible;
+property-aware search has no entry point; and a user-authored
+vault-root instruction file has no Brain-side reader.
+
+The v0.10.17 bundle closes those seven gaps as one coherent release.
+
+## Scope
+
+Seven features under one CHANGELOG entry, organised as the
+established three-layer DAG (atoms / helpers / consumers):
+
+- A1: Extend `BacklinkRef` with optional `targetAnchor`,
+ `targetBlock`, and `aliasSource` fields. Existing consumers stay
+ byte-identical (new fields are additive optionals).
+- A2: New `WikilinkParse` type for the rich-parse path. `target`,
+ `anchor`, `block`, `alias` slots. Existing `parseWikilink` /
+ `normaliseWikilinkTarget` keep their string contracts but delegate
+ to the rich parser.
+- A3: Extend `SearchOptions` with optional `properties` map
+ (`ReadonlyMap<string, ReadonlyArray<string>>`). Absent → existing
+ search behaviour.
+- A4: New `VaultInstructionEntry` type for the `brain_context`
+ envelope extension.
+- H1: `src/core/brain/link-graph/parse-wikilink.ts` -
+ `parseWikilinkRich(value)` returns `{target, anchor, block, alias}`
+ with the same case-preserving rules as the existing helpers.
+- H2: `src/core/brain/link-graph/alias-index.ts` -
+ `buildAliasIndex(vault)` walks all `Brain/` + vault notes, reads
+ frontmatter `aliases:` arrays (NFC-normalised, case-folded), and
+ returns a frozen `Map<alias, canonical-id>`. Collisions resolved
+ first-wins by sort order; a `brain_doctor` lint follows up
+ later (out of scope for this release).
+- H3: `src/core/brain/link-graph/unlinked-mentions.ts` -
+ `findUnlinkedMentions(vault, targetId, opts)` returns a frozen
+ `ReadonlyArray<MentionRef>` of `(source, line, contextSnippet)`
+ tuples. Skips text inside `[[...]]` spans and code spans. Uses the
+ alias index from H2 to expand the search-term set.
+- H4: `src/core/brain/link-graph/concept-cluster.ts` -
+ `buildConceptCluster(vault, targetId, opts)` returns a deterministic
+ envelope: `{target, linkers: [...refs], unlinkedMentions: [...]}`.
+ Pure assembler; no LLM call.
+- H5: `src/core/brain/link-graph/moc-audit.ts` -
+ `auditMoc(vault, hubId, opts)` returns
+ `{wellCovered: [...], fragile: [...], candidateMissing: [...],
+ suggestedNext: ...}`. Heuristic MOC detection is purely
+ structural (outbound link count and link-to-body ratio crossing
+ configured thresholds).
+- H6: `src/core/search/property-filter.ts` -
+ `filterByProperties(results, filters)` is a pure post-FTS phase
+ that walks each chunk's source frontmatter and drops rows whose
+ scalar values don't match the requested filter set. Multi-value
+ filter on the same key acts as logical OR; multiple keys act as
+ logical AND.
+- H7: `src/core/brain/vault-instruction-file.ts` -
+ `readVaultInstructionFile(vault, name)` reads
+ `<vault>/<name>` (default `VAULT.md`), returns `{content,
+ path, lines}` or null when absent. The filename is configurable
+ in `_brain.yaml` under `vault_instruction_file`; absent block
+ falls back to the `VAULT.md` default.
+- C1: `brain_unlinked_mentions` MCP tool (full scope) +
+ `o2b brain unlinked` CLI verb.
+- C2: `brain_concept_synthesis` MCP tool (full scope) +
+ `o2b brain synthesise` CLI verb.
+- C3: `brain_moc_audit` MCP tool (full scope) +
+ `o2b brain moc-audit` CLI verb.
+- C4: `brain_search` MCP tool extended to accept `properties`
+ argument; `o2b brain search` CLI verb extended with repeated
+ `--property KEY=VALUE` flag.
+- C5: `brain_context` MCP tool extended to optionally include
+ vault-instruction-file content under a new
+ `vault_instruction` envelope field (additive; absent file →
+ field omitted).
+- C6: `buildBacklinkIndex` consumer rewrite to populate the new
+ `BacklinkRef.targetAnchor` / `targetBlock` / `aliasSource`
+ fields. Existing callers (doctor, digest, explorer) keep their
+ current behaviour because they read by-target, not by-anchor.
+
+## Out of scope
+
+- LLM-driven synthesis. The `buildConceptCluster` helper assembles
+ a deterministic envelope; an external consumer can feed it to an
+ LLM later. The Brain layer never makes LLM calls.
+- Backlink collision lint (which alias-collision case escalates
+ through `brain_doctor`). Implementable in a follow-up release;
+ the first-wins resolution rule in H2 is enough to ship this
+ bundle safely.
+- Block-id heading auto-resolution (resolving `[[note#^abc]]` to a
+ line range inside `note`). H1 records the block id; resolving
+ it to a line range needs a chunk-aware reader and lands later.
+- New scheduled cron jobs. The vault-instruction file is read on
+ demand by `brain_context`, not pushed by a scheduler.
+- Two-stage signal review gate. Sibling cluster B from triage; not
+ bundled here.
+
+## Chosen approach
+
+Variant 1: one new subsystem `src/core/brain/link-graph/` hosts H1
+through H5 (parse, alias-index, unlinked-mentions, concept-cluster,
+moc-audit). H6 (property filter) lives in `src/core/search/` because
+that is its natural layer. H7 (vault-instruction file) lives at
+`src/core/brain/vault-instruction-file.ts` because `brain_context`
+consumes it directly and the file does not depend on the link graph.
+The decision rationale lives in `variants.md`.
+
+## Design decisions
+
+- **Three-layer DAG repeats the v0.10.16 precedent.** Atoms (A1-A4)
+ are additive optional fields on existing types; helpers (H1-H7)
+ are pure functions in named files; consumers (C1-C6) are existing
+ tools learning to read the helpers' output. Reviewers can map the
+ CHANGELOG section back to the file tree in one pass.
+- **Language-agnostic by construction.** No detector in this
+ release uses a vocabulary list, a stopword set, a per-language
+ regex table, or a unit dictionary. The anchor sigil `#` and the
+ block-id sigil `#^` are structural artifacts of the Obsidian link
+ grammar, not natural language. MOC detection uses link-density
+ (a structural metric). Unlinked-mention scanning matches the
+ target's literal title and its frontmatter alias strings as
+ opaque tokens.
+- **Backward compatibility by construction.** `BacklinkRef` gains
+ optional fields; existing callers that destructure
+ `{source, sourceKind, field, timestamp}` keep working unchanged.
+ `parseWikilink` / `normaliseWikilinkTarget` keep their string
+ return contracts. `SearchOptions.properties` defaults to absent.
+ `brain_context` envelope's `vault_instruction` field is absent
+ when the file is missing.
+- **Alias index is a single-pass pre-walk.** `buildAliasIndex`
+ reads frontmatter from every preference, retired, signal, and
+ vault note exactly once. The cost is bounded by vault size and
+ amortised by the existing `buildBacklinkIndex` walk, which can
+ feed alias data to the second pass without re-reading.
+- **Unlinked-mention scanner reuses the existing wikilink-masking
+ regex** from `extractWikilinks` (which already strips
+ `[[...]]` and code spans before yielding text). The scanner
+ inverts the operation: keep only the masked-out positions, then
+ match the candidate-term set against the remaining text.
+- **MOC heuristic is two thresholds.** A note qualifies as a MOC
+ candidate when its outbound link count is at least
+ `moc_min_outbound_links` (default 5) AND its body's
+ link-to-non-link ratio is at least `moc_min_link_ratio`
+ (default 0.3). Both are settable in `_brain.yaml` under
+ `link_graph.moc_*`. No vocabulary detection of "this looks like
+ a MOC because the title says 'MOC'" - that's a hardcoded-language
+ trap.
+- **Property filter applies as a post-FTS phase.** FTS5 and the
+ semantic ranker return candidate chunks first; the filter then
+ loads each candidate chunk's source frontmatter (cached per
+ document id within a single search call) and drops rows whose
+ scalars don't match. The frontmatter read is bounded by the
+ candidate set size (typically `limit * 3`), not the vault.
+- **`brain_context` envelope extension is additive.** A new
+ optional `vault_instruction?: VaultInstructionEntry` field on
+ the existing envelope. Absent block in `_brain.yaml` plus absent
+ file on disk = field omitted. Hosts that already strip unknown
+ envelope fields stay byte-identical.
+- **CLI verbs use the existing `o2b brain <verb>` dispatch.**
+ Each new verb is one file under `src/cli/brain/verbs/<name>.ts`,
+ wired through `src/cli/brain/verbs/index.ts` and
+ `src/cli/brain/help-text.ts`. Same precedent as v0.10.16's
+ `summary` verb.
+- **MCP tools land in the full scope only.** Three new tools
+ (`brain_unlinked_mentions`, `brain_concept_synthesis`,
+ `brain_moc_audit`) register in the full scope and never appear
+ in the writer scope. The writer-scope tool count stays at four
+ (`brain_feedback`, `brain_apply_evidence`, `brain_note`,
+ `brain_context`). `brain_context` is additively extended -
+ the `vault_instruction` envelope field is omitted when no file
+ is present, so writer-scope hosts that strip unknown fields stay
+ byte-identical. `brain_search` (registered in
+ `src/mcp/search-tools.ts`, full scope) grows an optional
+ `properties` argument; the writer scope does not expose
+ `brain_search`.
+
+## File changes
+
+New files:
+
+- `src/core/brain/link-graph/parse-wikilink.ts`
+- `src/core/brain/link-graph/alias-index.ts`
+- `src/core/brain/link-graph/unlinked-mentions.ts`
+- `src/core/brain/link-graph/concept-cluster.ts`
+- `src/core/brain/link-graph/moc-audit.ts`
+- `src/core/brain/vault-instruction-file.ts`
+- `src/core/search/property-filter.ts`
+- `src/cli/brain/verbs/unlinked.ts`
+- `src/cli/brain/verbs/synthesise.ts`
+- `src/cli/brain/verbs/moc-audit.ts`
+- `tests/core/brain/link-graph/parse-wikilink.test.ts`
+- `tests/core/brain/link-graph/alias-index.test.ts`
+- `tests/core/brain/link-graph/unlinked-mentions.test.ts`
+- `tests/core/brain/link-graph/concept-cluster.test.ts`
+- `tests/core/brain/link-graph/moc-audit.test.ts`
+- `tests/core/brain/vault-instruction-file.test.ts`
+- `tests/core/search/property-filter.test.ts`
+- `tests/cli/brain-unlinked-cli.test.ts`
+- `tests/cli/brain-synthesise-cli.test.ts`
+- `tests/cli/brain-moc-audit-cli.test.ts`
+- `tests/mcp/link-graph-mcp-fields.test.ts`
+- `tests/core/brain/backlinks-anchor-alias.test.ts`
+- `docs/brainstorm/link-graph-surfaces/{design.md,plan.md,variants.md,cli-output/}`
+- `.ai-notes/images/v0.10.17-link-graph.{excalidraw,png}`
+
+Modified files:
+
+- `src/core/brain/wikilink.ts` - export `parseWikilinkRich`;
+ `parseWikilink` / `normaliseWikilinkTarget` delegate.
+- `src/core/brain/backlinks.ts` - `BacklinkRef` extended;
+ `buildBacklinkIndex` populates new fields and consults
+ `buildAliasIndex`.
+- `src/core/brain/policy.ts` - add `link_graph` config section
+ with `moc_min_outbound_links`, `moc_min_link_ratio`,
+ `vault_instruction_file` defaults. `resolveLinkGraphConfig`
+ helper next to `resolveGuardrails`.
+- `src/core/search/types.ts` - extend `SearchOptions` with
+ `properties?`.
+- `src/core/search/search.ts` - wire `filterByProperties` post-FTS
+ phase when `opts.properties` is set.
+- `src/mcp/brain-tools.ts` - register three new full-scope tools
+ (`brain_unlinked_mentions`, `brain_concept_synthesis`,
+ `brain_moc_audit`); extend `brain_context` envelope.
+- `src/mcp/search-tools.ts` - extend `brain_search` schema and
+ handler with optional `properties` argument.
+- `src/mcp/tools.ts` - add the three tool names to the full-scope
+ set (writer scope unchanged).
+- `src/mcp/instructions.ts` - inventory bump to 14 tools (11 +
+ three new full-scope reads).
+- `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`,
+ `src/cli/brain/help-text.ts` - dispatch + help for the three
+ new verbs and the search property flag.
+- `README.md` - capability paragraph plus tool-count bump.
+- `CHANGELOG.md` - new `[0.10.17]` entry under a concrete
+ version header.
+- Version manifests: `package.json`, `pyproject.toml`,
+ `plugin.yaml`, `.claude-plugin/plugin.json`,
+ `.codex-plugin/plugin.json`, `openclaw.plugin.json`,
+ `plugins/codex/.codex-plugin/plugin.json`,
+ `plugins/hermes/plugin.yaml`.
+
+Expected total: ~60 files (within 50-70 budget).
+
+## Risks and open questions
+
+- **Risk: alias-index walk cost.** `buildAliasIndex` reads
+ frontmatter from every preference + retired + signal + vault
+ note. For a 10k-page vault this is a one-time
+ `readFileSync(frontmatter-only-prefix)` per file. Mitigation:
+ the index is built lazily inside `buildBacklinkIndex` and
+ passed as an in-memory `Map` to all downstream consumers; no
+ caller pays the walk twice. If profiling shows it's the new
+ bottleneck, a follow-up release can cache by `mtime`.
+- **Risk: unlinked-mention false positives.** The literal-token
+ matcher will hit prose mentions of common nouns. Mitigation:
+ the matcher requires whole-word boundaries (Unicode-aware
+ via `\p{L}\p{N}` codepoint classes), the title-token must be
+ at least two codepoints (avoids matching every "a" or "I"), and
+ the scanner explicitly skips text inside `[[...]]`. No vocabulary
+ filtering, no stopword set - the heuristic is purely structural.
+- **Open question: where to draw the MOC link-density threshold.**
+ Defaults (`moc_min_outbound_links: 5`,
+ `moc_min_link_ratio: 0.3`) are heuristic. The `_brain.yaml`
+ config lets operators override per-vault. Documented in README.
+- **Open question: how the `brain_context` envelope grows.**
+ The new `vault_instruction` field is opt-in via file presence,
+ but downstream hosts may need a CHANGELOG callout. Mitigation:
+ the field is absent when the file is missing, so existing hosts
+ that strip unknown fields stay byte-identical.
diff --git a/docs/brainstorm/link-graph-surfaces/plan.md b/docs/brainstorm/link-graph-surfaces/plan.md
new file mode 100644
index 00000000..c0288e87
--- /dev/null
+++ b/docs/brainstorm/link-graph-surfaces/plan.md
@@ -0,0 +1,129 @@
+# Link graph surfaces - implementation plan
+
+## DAG
+
+```
+A2 (rich wikilink parse) ──┐
+A1 (BacklinkRef +fields) ──┤
+ ├──> Unit 1 (parse + atom)
+ │
+H2 (alias-index) ──> Unit 2
+H1 + alias wiring ──> Unit 3 (BacklinkRef populated)
+H3 (unlinked-mentions) ──> Unit 4
+H4 (concept-cluster) ──> Unit 5
+H5 (moc-audit) ──> Unit 6
+H6 (property-filter) ──> Unit 7
+A4 + H7 (vault-instr) ──> Unit 8
+```
+
+Units 1-3 land sequentially (later units depend on earlier shape).
+Units 4-8 are siblings and can land in any internal order.
+
+## Tasks
+
+### Unit 1: Rich wikilink parse + `BacklinkRef` atom extension
+
+- **Files**:
+ - `src/core/brain/wikilink.ts` (modify) - export `parseWikilinkRich`
+ - `src/core/brain/link-graph/parse-wikilink.ts` (new) - canonical home of the rich-parse logic
+ - `src/core/brain/backlinks.ts` (modify) - `BacklinkRef` gains optional `targetAnchor?: string`, `targetBlock?: string`, `aliasSource?: string`
+ - `tests/core/brain/link-graph/parse-wikilink.test.ts` (new) - covers heading anchor, block anchor, alias, folder, `.md` suffix, and combination cases
+ - `tests/core/brain/backlinks-anchor-alias.test.ts` (new) - covers existing-consumer compatibility (legacy shape destructure still works) plus new-field populated cases
+- **Acceptance**: `parseWikilinkRich("[[Note#Heading]]")` returns `{target: "Note", anchor: "Heading", block: undefined, alias: undefined}`; `parseWikilinkRich("[[Note#^abc]]")` returns `{..., block: "abc"}`; `parseWikilink("[[Note#Heading]]")` still returns `"Note"`. `BacklinkRef` instances retain backward compat: code reading only `{source, sourceKind, field, timestamp}` continues to work.
+- **Depends on**: none
+
+### Unit 2: Alias index helper
+
+- **Files**:
+ - `src/core/brain/link-graph/alias-index.ts` (new) - `buildAliasIndex(vault)` returning frozen `Map<aliasLower, canonicalId>`
+ - `tests/core/brain/link-graph/alias-index.test.ts` (new) - frontmatter scanned across `preferences/`, `retired/`, `inbox/`, `processed/`; collisions resolved first-wins; case-insensitive; NFC normalised
+- **Acceptance**: Three notes, two declaring overlapping `aliases: [foo]`, the alphabetically-first wins; lookup is case-insensitive; result is `Object.isFrozen`.
+- **Depends on**: none
+
+### Unit 3: `buildBacklinkIndex` populates anchor + alias-source
+
+- **Files**:
+ - `src/core/brain/backlinks.ts` (modify) - rewrite collectors to push the rich parse and consult the alias index
+ - `tests/core/brain/backlinks-anchor-alias.test.ts` (extend) - new cases assert `targetAnchor`, `targetBlock`, `aliasSource` are populated when applicable
+- **Acceptance**: A signal referencing `[[FullName#Section]]` produces a `BacklinkRef` with `targetAnchor: "Section"`. A signal referencing `[[fooAlias]]` where note `bar.md` declares `aliases: [fooAlias]` produces a ref keyed on `"bar"` with `aliasSource: "fooAlias"`.
+- **Depends on**: Unit 1, Unit 2
+
+### Unit 4: Unlinked-mentions helper + MCP + CLI
+
+- **Files**:
+ - `src/core/brain/link-graph/unlinked-mentions.ts` (new) - `findUnlinkedMentions(vault, targetId, opts)` returning frozen `ReadonlyArray<MentionRef>`
+ - `src/mcp/brain-tools.ts` (modify) - register `brain_unlinked_mentions` in full scope
+ - `src/cli/brain/verbs/unlinked.ts` (new) - `runUnlinked(args)`
+ - `src/cli/brain/verbs/index.ts` + `src/cli/brain/help-text.ts` + `src/cli/brain.ts` (modify) - dispatch + help
+ - `tests/core/brain/link-graph/unlinked-mentions.test.ts` (new) - confirms `[[...]]` exclusion, alias expansion, multi-line context, codepoint-aware word boundaries
+ - `tests/cli/brain-unlinked-cli.test.ts` (new)
+ - `tests/mcp/link-graph-mcp-fields.test.ts` (new) - covers tool registration, JSON-RPC round trip, `INVALID_PARAMS` for malformed input
+- **Acceptance**: Given a target `Note` with frontmatter `aliases: [downstream]`, and a sibling note containing the prose `"the downstream effect of Note here"`, the scanner yields two `MentionRef` rows (one per match). A reference `[[Note]]` in the same sibling does NOT produce a mention. Tool registered in `full` scope only.
+- **Depends on**: Unit 2
+
+### Unit 5: Concept-cluster helper + MCP + CLI
+
+- **Files**:
+ - `src/core/brain/link-graph/concept-cluster.ts` (new) - `buildConceptCluster(vault, targetId, opts)` returning a frozen envelope `{target, linkers, unlinkedMentions, generatedAt}`
+ - `src/mcp/brain-tools.ts` (modify) - register `brain_concept_synthesis` in full scope
+ - `src/cli/brain/verbs/synthesise.ts` (new)
+ - `src/cli/brain.ts` + `src/cli/brain/verbs/index.ts` + `src/cli/brain/help-text.ts` (modify)
+ - `tests/core/brain/link-graph/concept-cluster.test.ts` (new) - envelope shape, frozen guarantees, `include_unlinked` flag toggles inclusion
+ - `tests/cli/brain-synthesise-cli.test.ts` (new)
+ - `tests/mcp/link-graph-mcp-fields.test.ts` (extend) - covers concept-synthesis registration + JSON-RPC
+- **Acceptance**: For a target `Note` with two linkers (`pref-a` body contains `[[Note]]`, `pref-b` evidenced_by `[[Note]]`), envelope reports both linkers with their `sourceKind` + `field`. When `include_unlinked: true`, envelope also contains the unlinked-mention rows. Helper does NOT make an LLM call.
+- **Depends on**: Unit 3, Unit 4
+
+### Unit 6: Per-MOC audit helper + MCP + CLI
+
+- **Files**:
+ - `src/core/brain/link-graph/moc-audit.ts` (new) - `auditMoc(vault, hubId, opts)` returning `{wellCovered, fragile, candidateMissing, suggestedNext}`
+ - `src/core/brain/policy.ts` (modify) - add `link_graph.moc_min_outbound_links` (default 5) and `link_graph.moc_min_link_ratio` (default 0.3) config slots
+ - `src/mcp/brain-tools.ts` (modify) - register `brain_moc_audit` in full scope
+ - `src/cli/brain/verbs/moc-audit.ts` (new)
+ - `src/cli/brain.ts` + `src/cli/brain/verbs/index.ts` + `src/cli/brain/help-text.ts` (modify)
+ - `tests/core/brain/link-graph/moc-audit.test.ts` (new) - heuristic threshold behaviour, bucket assignment, suggestedNext deterministic ordering
+ - `tests/cli/brain-moc-audit-cli.test.ts` (new)
+ - `tests/mcp/link-graph-mcp-fields.test.ts` (extend) - covers moc-audit registration + JSON-RPC
+- **Acceptance**: A hub note with 6 outbound links and link-ratio 0.5 qualifies as MOC; one linker with body-length above the well-covered floor + 3 inbound backlinks → `wellCovered`; one linker with 1 backlink and short body → `fragile`. MOC detection rejects a note with 4 outbound links (below the default threshold) regardless of title.
+- **Depends on**: Unit 1 (rich parse for outbound-link enumeration)
+
+### Unit 7: Property-filter helper + search wiring + MCP + CLI flag
+
+- **Files**:
+ - `src/core/search/property-filter.ts` (new) - `filterByProperties(results, filters, frontmatterReader)`; multi-value within a key = OR, multiple keys = AND
+ - `src/core/search/types.ts` (modify) - `SearchOptions.properties?: ReadonlyMap<string, ReadonlyArray<string>>` (or equivalent shape)
+ - `src/core/search/search.ts` (modify) - wire post-FTS phase when `opts.properties` set
+ - `src/mcp/search-tools.ts` (modify) - extend `brain_search` schema + handler to accept a `properties` argument
+ - `src/cli/search.ts` (modify) - repeated `--property KEY=VALUE` flag on `o2b search "<query>"`
+ - `tests/core/search/property-filter.test.ts` (new) - covers AND/OR logic, missing-key behaviour, malformed-filter rejection
+ - `tests/cli/search-property-cli.test.ts` (new)
+- **Acceptance**: `search({query: "foo", properties: new Map([["type", ["decision"]]]))` returns only chunks whose source frontmatter has `type: decision`. Multi-value filter on `tags` includes any chunk whose `tags` array intersects the requested set. Absent `properties` → identical to existing `search()` output (verified by snapshot).
+- **Depends on**: none (parallel to other units)
+
+### Unit 8: Vault-root instruction file reader + `brain_context` envelope extension
+
+- **Files**:
+ - `src/core/brain/vault-instruction-file.ts` (new) - `readVaultInstructionFile(vault, name)`
+ - `src/core/brain/policy.ts` (modify) - add `vault_instruction_file` config (default `VAULT.md`)
+ - `src/mcp/brain-tools.ts` (modify) - extend `brain_context` envelope with optional `vault_instruction` field
+ - `tests/core/brain/vault-instruction-file.test.ts` (new) - reads default name, configurable name, absent file → null, oversized file warning, vault-relative path emission
+ - `tests/mcp/brain-context-vault-instruction.test.ts` (new) - covers envelope extension + absent-file = field omitted
+- **Acceptance**: `<vault>/VAULT.md` containing `# My vault` → `readVaultInstructionFile` returns `{content: "# My vault", path: "VAULT.md", lines: 1}`. Configurable rename via `_brain.yaml` → `vault_instruction_file: GUIDE.md` reads `<vault>/GUIDE.md`. Absent file → returns `null`; envelope omits the field.
+- **Depends on**: none (parallel to other units)
+
+## Cross-cutting items (land alongside the final unit)
+
+- `src/mcp/instructions.ts` - inventory bump.
+- `src/mcp/tools.ts` - add the three full-scope tool names to the table.
+- `README.md` - one new capability paragraph + tool-count bump.
+- `CHANGELOG.md` - one new `[0.10.17]` entry under a concrete header.
+- Version manifests bump (one commit in Phase 6, not during implementation).
+- `.ai-notes/images/v0.10.17-link-graph.{excalidraw,png}` - release diagram.
+
+## Verification artifacts
+
+- Each unit's tests must pass in isolation (`bun test tests/core/brain/link-graph/<file>.test.ts`).
+- Full suite must pass at the end of every unit's commit (`bun test`).
+- `bun run typecheck` clean at every commit boundary.
+- `bun run sync-version:check` runs only after Phase 6 version bump.
diff --git a/docs/brainstorm/link-graph-surfaces/variants.md b/docs/brainstorm/link-graph-surfaces/variants.md
new file mode 100644
index 00000000..2d7aaa60
--- /dev/null
+++ b/docs/brainstorm/link-graph-surfaces/variants.md
@@ -0,0 +1,146 @@
+# Link graph surfaces - brainstorm audit trail
+
+Produced by the v0.10.17 brainstorm pass on 2026-05-25. Primary
+consultant: Claude Code CLI (`docs/brainstorm/link-graph-surfaces/cli-output/claude.md`).
+Fallback consultant: not invoked (primary returned three parseable
+variants + a clear recommendation on the first run).
+
+## Variant 1 - Single `link-graph` subsystem (strict precedent match)
+
+**Approach.** Mint one new subsystem `src/core/brain/link-graph/` that
+hosts every pure helper for features 1-5 (alias resolver, anchor
+extractor, unlinked-mention scanner, concept-cluster assembler, MOC
+classifier). Atoms extend `BacklinkRef` (anchor + alias-source
+fields) in place under `backlinks.ts` and add `aliases` to the
+in-memory note record from `vault.ts`; consumers are new CLI verbs /
+MCP tools that import from `link-graph/`. Feature 6 lands as
+`src/core/search/property-filter.ts` inside the existing search
+layer, and feature 7 lands as a small extension to whichever loader
+already injects `active.md` into session context.
+
+**Trade-offs.**
+
+- Pro: Mirrors v0.10.15 / v0.10.16 exactly - one themed subdir,
+ atoms/helpers/consumers DAG, predictable for reviewers.
+- Pro: Helpers are co-located, so `synthesise` and `moc-audit` can
+ re-use the alias / anchor / unlinked-mention helpers without
+ cross-subsystem imports.
+- Pro: Search and session-context changes stay in their natural
+ layers instead of being dragged into a `brain/` subdir where they
+ don't belong.
+- Con: `link-graph/` becomes a relatively large bag (5 helpers)
+ compared to the tighter v0.10.16 trust/ tree.
+- Con: Two of seven features (property search, VAULT.md) sit outside
+ the named release subsystem, so the release headline isn't quite
+ "everything under one roof."
+
+**Complexity.** medium
+**Risk.** low
+
+## Variant 2 - Three small co-equal subsystems (one per concern)
+
+**Approach.** Carve the release into three named subsystems -
+`src/core/brain/graph/` for link / backlink helpers (1-5),
+`src/core/brain/property-filter/` for the FTS-post property-filter
+phase (6), and `src/core/brain/vault-context/` for the VAULT.md
+loader (7). Each follows its own atoms/helpers/consumers DAG; the
+CHANGELOG groups them under one v0.10.17 header but the code tree is
+unambiguous about which file belongs to which feature cluster.
+
+**Trade-offs.**
+
+- Pro: Clean one-feature-cluster-per-subdir mapping; each subdir is
+ small and individually testable.
+- Pro: Property filter and VAULT.md are first-class members of the
+ release, not "miscellaneous additions."
+- Pro: Future bundles can grow any of the three without touching the
+ others.
+- Con: Breaks the "one new subsystem per release" precedent set by
+ v0.10.15 and v0.10.16; three new subdirs in one PR is a
+ noticeable convention drift.
+- Con: `property-filter/` under `brain/` is awkward because the
+ actual code is search-layer (FTS + chunks), not brain-layer;
+ pulling it under `brain/` muddies the layering.
+- Con: VAULT.md is a tiny addition that doesn't deserve its own
+ subsystem; padding it out to atoms/helpers/consumers is ceremony
+ for ~1 file of logic.
+
+**Complexity.** medium
+**Risk.** medium
+
+## Variant 3 - In-place enrichment, single small subsystem only for read-views
+
+**Approach.** Extend existing files directly for the structural
+plumbing: `wikilink.ts` keeps anchors instead of stripping them,
+`backlinks.ts` learns to resolve aliases when collecting refs,
+`search.ts` grows a property-filter post-phase, and the existing
+session-context loader learns about VAULT.md. Mint one small
+subsystem `src/core/brain/graph-views/` that only contains the
+higher-level read-only assemblers (unlinked-mentions scanner,
+concept-synthesis envelope builder, MOC audit classifier) - the
+things that genuinely need shared helpers and dedicated tests.
+
+**Trade-offs.**
+
+- Pro: Smallest blast radius - file count is well under 70,
+ structural changes live next to the code they enrich, no orphan
+ one-file subsystems.
+- Pro: The new subdir holds only the genuinely novel logic (the
+ three "views"), so its scope is crisp and its test directory is
+ well-bounded.
+- Pro: Property filter living inside `src/core/search/` matches the
+ actual layer ownership, no awkward cross-tree imports.
+- Con: Diverges from the recent two-release precedent where ALL new
+ helpers landed inside the new subdir; reviewers used to that
+ pattern may need orientation.
+- Con: Atom-level extensions are scattered across `wikilink.ts`,
+ `backlinks.ts`, and `search.ts` rather than visible in one diff
+ stack, so the "what's the v0.10.17 shape change?" question takes
+ more reading.
+- Con: `graph-views/` doesn't capture the alias/anchor work in its
+ name, so the release theme is split between "view helpers" and
+ "graph plumbing upgrades."
+
+**Complexity.** small
+**Risk.** low
+
+## Recommended: Variant 1
+
+**Consultant rationale.** It is the only variant that holds the
+line on the project's established two-release precedent (one named
+subsystem with the atoms / helpers / consumers DAG), which keeps
+reviewer mental model, test-directory layout, and CHANGELOG framing
+identical to v0.10.15 / v0.10.16. The two features that genuinely
+don't belong under `brain/link-graph/` (property search is
+search-layer, VAULT.md is session-context-layer) land in their
+natural layers without inventing ceremonial subsystems for them,
+avoiding Variant 2's drift while still keeping the headline
+"link-graph subsystem" intact - and unlike Variant 3, the
+foundational alias/anchor atoms remain visible as part of the new
+subsystem's shape rather than scattered across pre-existing files.
+
+## Orchestrator decision
+
+**Accept the consultant's recommendation without override.**
+
+The variant aligns with three live constraints not yet captured in
+the prompt:
+
+1. The `pref-no-hardcoded-languages` preference applies to every
+ helper in this bundle; co-locating the helpers under one named
+ subsystem makes the language-agnostic review pass cheaper
+ (one directory to audit, not three).
+2. The CodeRabbit reviewer historically lands more findings when
+ atoms drift across pre-existing files (Variant 3); concentrating
+ them in the new subsystem reduces that surface.
+3. The release-notes excalidraw / PNG (precedent: trust/) renders
+ as three layers (atoms / helpers / consumers). Variants 2 and 3
+ would require redrawing that layout to two or four bands. Variant
+ 1 reuses the same three-layer template directly.
+
+Property filter remains in `src/core/search/property-filter.ts`
+(search-layer, natural ownership). The vault-root instruction file
+lands in `src/core/brain/vault-instruction-file.ts` at brain-layer
+root (it is consumed by `brain_context`, not by the link-graph
+subsystem) - not under `link-graph/` even though it ships in the
+same release.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 2f9ce6e0..eef37bd0 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.10.16",
+ "version": "0.10.17",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 5fcde08d..fa374019 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.16",
+ "version": "0.10.17",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
diff --git a/plugin.yaml b/plugin.yaml
index a0778441..d0c0ca43 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.16"
+version: "0.10.17"
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 81163f80..6984de4b 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.10.16",
+ "version": "0.10.17",
"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 1507b9f8..2a0bb05d 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.16"
+version: "0.10.17"
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 fa26e7f1..7cca8ae5 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.10.16"
+version = "0.10.17"
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 cfdd2a8a..9ae76bf1 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -40,6 +40,9 @@ import {
cmdBrainLint,
cmdBrainActions,
cmdBrainSummary,
+ cmdBrainUnlinked,
+ cmdBrainSynthesise,
+ cmdBrainMocAudit,
} from "./brain/verbs/index.ts";
export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promise<number> {
@@ -90,6 +93,9 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
case "lint": return await cmdBrainLint(rest);
case "actions": return await cmdBrainActions(rest);
case "summary": return await cmdBrainSummary(rest);
+ case "unlinked": return await cmdBrainUnlinked(rest);
+ case "synthesise": return await cmdBrainSynthesise(rest);
+ case "moc-audit": return await cmdBrainMocAudit(rest);
default:
process.stderr.write(`error: unknown brain verb: ${verb}\n`);
process.stdout.write(BRAIN_HELP);
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 9fd1f280..b00d277a 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -42,6 +42,9 @@ Brain verbs (observing memory):
lint Self-healing structural checks (--consolidate); --apply to write
actions Ranked maintenance action list (dedup + lint + footprint)
summary Operator dashboard: trust verdict, doctor/dream counts, actions
+ unlinked Raw-text mentions of an artifact's title/aliases outside [[...]]
+ synthesise Concept cluster: target + linkers (depth-1), optionally + mentions
+ moc-audit Per-MOC coverage audit (well-covered/fragile/candidate-missing)
Common flags:
--vault <path> Override the configured vault
@@ -249,4 +252,24 @@ export const VERB_HELP: Record<string, string> = {
"dream uncertain/quarantined counts, verification delta, top maintenance\n" +
"actions, and instruction-file ceiling warnings into one report.\n" +
"Runs a dry-run dream pass by default; --skip-dream omits it. Read-only.\n",
+ unlinked:
+ "usage: o2b brain unlinked <id> [--limit <n>] [--vault <path>] [--json]\n" +
+ "Raw-text mentions of <id>'s title and frontmatter aliases that are NOT\n" +
+ "already inside a [[...]] wikilink. Match boundary is Unicode-aware\n" +
+ "(codepoint class), language-agnostic. Walks Brain/preferences/ and\n" +
+ "Brain/retired/. Read-only.\n",
+ synthesise:
+ "usage: o2b brain synthesise <id> [--include-unlinked] [--vault <path>] [--json]\n" +
+ "Assemble the concept-cluster envelope: target note + every artifact\n" +
+ "that wikilinks to it (depth-1). With --include-unlinked also include\n" +
+ "raw-text mentions outside [[...]]. Pure assembler, no LLM call. Output\n" +
+ "is a deterministic JSON envelope downstream consumers can feed to\n" +
+ "any synthesis prompt. Read-only.\n",
+ "moc-audit":
+ "usage: o2b brain moc-audit <hub-id> [--vault <path>] [--json]\n" +
+ "Per-MOC coverage audit. Given a hub note id, classifies cluster\n" +
+ "members into well-covered / fragile / candidate-missing buckets and\n" +
+ "surfaces a suggested-next candidate. MOC detection is purely\n" +
+ "structural (outbound link count + link density thresholds from\n" +
+ "_brain.yaml). Read-only.\n",
};
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index fda576f5..c20d1f6e 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -27,3 +27,6 @@ export { cmdBrainContextPack } from "./context-pack.ts";
export { cmdBrainLint } from "./lint.ts";
export { cmdBrainActions } from "./actions.ts";
export { cmdBrainSummary } from "./summary.ts";
+export { cmdBrainUnlinked } from "./unlinked.ts";
+export { cmdBrainSynthesise } from "./synthesise.ts";
+export { cmdBrainMocAudit } from "./moc-audit.ts";
diff --git a/src/cli/brain/verbs/moc-audit.ts b/src/cli/brain/verbs/moc-audit.ts
new file mode 100644
index 00000000..a71606c6
--- /dev/null
+++ b/src/cli/brain/verbs/moc-audit.ts
@@ -0,0 +1,77 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ auditMoc,
+ MocAuditError,
+} from "../../../core/brain/link-graph/moc-audit.ts";
+import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
+import { parse, fail, resolveBrainVault } from "../helpers.ts";
+
+/**
+ * `o2b brain moc-audit <hub-id> [--vault PATH] [--json]`
+ *
+ * Run the per-MOC coverage audit and print the bucketed report.
+ * Rejects non-MOC hubs (outbound count + link density below
+ * configured thresholds) with a usage error.
+ */
+export async function cmdBrainMocAudit(argv: string[]): Promise<number> {
+ const { positional, flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const id = positional[0];
+ if (!id) return fail("brain moc-audit requires a hub note id");
+ const hub = normaliseWikilinkTarget(id);
+
+ let report;
+ try {
+ report = auditMoc(vault, hub);
+ } catch (err) {
+ if (err instanceof MocAuditError) return fail(`brain moc-audit: ${err.message}`);
+ throw err;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ hub_id: report.hubId,
+ outbound_count: report.outboundCount,
+ well_covered: report.wellCovered,
+ fragile: report.fragile,
+ candidate_missing: report.candidateMissing,
+ ...(report.suggestedNext
+ ? { suggested_next: report.suggestedNext }
+ : {}),
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `MOC audit for ${report.hubId} (${report.outboundCount} outbound):\n`,
+ );
+ process.stdout.write(` well-covered: ${report.wellCovered.length}\n`);
+ for (const m of report.wellCovered) {
+ process.stdout.write(` ${m.id} (backlinks=${m.backlinkCount}, body=${m.bodyChars})\n`);
+ }
+ process.stdout.write(` fragile: ${report.fragile.length}\n`);
+ for (const m of report.fragile) {
+ process.stdout.write(` ${m.id} (backlinks=${m.backlinkCount}, body=${m.bodyChars})\n`);
+ }
+ process.stdout.write(` candidate-missing: ${report.candidateMissing.length}\n`);
+ for (const c of report.candidateMissing) {
+ process.stdout.write(` ${c.id} (refs=${c.referenceCount})\n`);
+ }
+ if (report.suggestedNext) {
+ process.stdout.write(
+ ` suggested-next: ${report.suggestedNext.id} (refs=${report.suggestedNext.referenceCount})\n`,
+ );
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/synthesise.ts b/src/cli/brain/verbs/synthesise.ts
new file mode 100644
index 00000000..7086e38a
--- /dev/null
+++ b/src/cli/brain/verbs/synthesise.ts
@@ -0,0 +1,69 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { buildConceptCluster } from "../../../core/brain/link-graph/concept-cluster.ts";
+import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
+import { parse, fail, resolveBrainVault } from "../helpers.ts";
+
+/**
+ * `o2b brain synthesise <id> [--include-unlinked] [--vault PATH] [--json]`
+ *
+ * Assemble the concept-cluster envelope (target + linkers
+ * [depth-1], optionally + unlinked mentions). Pure assembler; no
+ * LLM call. JSON output is the canonical surface for downstream
+ * consumers.
+ */
+export async function cmdBrainSynthesise(argv: string[]): Promise<number> {
+ const { positional, flags } = parse(argv, {
+ vault: { type: "string" },
+ "include-unlinked": { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const id = positional[0];
+ if (!id) return fail("brain synthesise requires a target id (e.g. pref-foo)");
+ const target = normaliseWikilinkTarget(id);
+
+ const cluster = buildConceptCluster(vault, target, {
+ includeUnlinked: flags["include-unlinked"] === true,
+ });
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ target_id: cluster.targetId,
+ target_title: cluster.targetTitle,
+ linkers: cluster.linkers,
+ unlinked_mentions: cluster.unlinkedMentions,
+ generated_at: cluster.generatedAt,
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `Concept cluster for ${cluster.targetId} (${cluster.targetTitle}):\n`,
+ );
+ process.stdout.write(` Linkers: ${cluster.linkers.length}\n`);
+ for (const l of cluster.linkers) {
+ const anchor = l.targetAnchor ? `#${l.targetAnchor}` : "";
+ const block = l.targetBlock ? `#^${l.targetBlock}` : "";
+ const alias = l.aliasSource ? ` via "${l.aliasSource}"` : "";
+ process.stdout.write(
+ ` ${l.source}${anchor}${block} (${l.sourceKind}, field: ${l.field})${alias}\n`,
+ );
+ }
+ if (cluster.unlinkedMentions.length > 0) {
+ process.stdout.write(
+ ` Unlinked mentions: ${cluster.unlinkedMentions.length}\n`,
+ );
+ for (const m of cluster.unlinkedMentions) {
+ process.stdout.write(` ${m.source}:${m.line} (${m.term})\n`);
+ }
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/unlinked.ts b/src/cli/brain/verbs/unlinked.ts
new file mode 100644
index 00000000..7813bb64
--- /dev/null
+++ b/src/cli/brain/verbs/unlinked.ts
@@ -0,0 +1,75 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { findUnlinkedMentions } from "../../../core/brain/link-graph/unlinked-mentions.ts";
+import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
+import { parse, fail, resolveBrainVault } from "../helpers.ts";
+
+/**
+ * `o2b brain unlinked <target-id> [--limit N] [--vault PATH] [--json]`
+ *
+ * Surface raw-text mentions of `<target-id>`'s title / aliases that
+ * are NOT already inside `[[...]]` wikilinks. Read-only; walks
+ * `Brain/preferences/` and `Brain/retired/` only. Match boundary is
+ * Unicode-aware (codepoint class), language-agnostic.
+ */
+export async function cmdBrainUnlinked(argv: string[]): Promise<number> {
+ const { positional, flags } = parse(argv, {
+ vault: { type: "string" },
+ limit: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const id = positional[0];
+ if (!id) {
+ return fail("brain unlinked requires a target id (e.g. pref-foo, ret-bar)");
+ }
+ const target = normaliseWikilinkTarget(id);
+
+ let limit: number | undefined;
+ const limitFlag = flags["limit"];
+ if (typeof limitFlag === "string" && limitFlag.length > 0) {
+ if (!/^[0-9]+$/.test(limitFlag)) {
+ return fail("brain unlinked: --limit must be a positive integer");
+ }
+ const parsed = Number.parseInt(limitFlag, 10);
+ if (parsed < 1) {
+ return fail("brain unlinked: --limit must be a positive integer");
+ }
+ limit = parsed;
+ }
+
+ const mentions = findUnlinkedMentions(vault, target, {
+ ...(limit !== undefined ? { limit } : {}),
+ });
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ id: target,
+ count: mentions.length,
+ mentions: mentions.map((m) => ({
+ source: m.source,
+ line: m.line,
+ term: m.term,
+ context: m.contextSnippet,
+ })),
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `Unlinked mentions of ${target}: ${mentions.length}\n`,
+ );
+ for (const m of mentions) {
+ process.stdout.write(
+ ` ${m.source}:${m.line} (${m.term}) ${m.contextSnippet.trim()}\n`,
+ );
+ }
+ return 0;
+}
diff --git a/src/cli/search.ts b/src/cli/search.ts
index e8e43dc6..8c4490be 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -119,6 +119,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
"keyword-weight": { type: "string" },
"semantic-weight": { type: "string" },
"auto-refresh": { type: "boolean" },
+ property: { type: "string-array" },
json: { type: "boolean" },
verbose: { type: "boolean" },
});
@@ -152,12 +153,15 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
const semanticOverride: boolean | undefined =
flags["semantic"] === true ? true : flags["keyword-only"] === true ? false : undefined;
+ const properties = parsePropertyFlags(flags["property"] as string[] | undefined);
+
const outcome = await search(cfg, {
query,
limit: limitNum,
semantic: semanticOverride,
keywordOnly: flags["keyword-only"] === true,
pathPrefix: typeof flags["path"] === "string" ? (flags["path"] as string) : undefined,
+ ...(properties !== undefined ? { properties } : {}),
});
if (flags["json"]) {
@@ -168,6 +172,36 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
return 0;
}
+/**
+ * Parse the repeatable `--property KEY=VALUE` flag into the
+ * `properties` map shape that `search()` consumes. Multiple
+ * `--property KEY=...` entries for the same KEY accumulate (OR).
+ * Different KEYs accumulate as separate entries (AND).
+ */
+function parsePropertyFlags(
+ raw: ReadonlyArray<string> | undefined,
+): ReadonlyMap<string, ReadonlyArray<string>> | undefined {
+ if (!raw || raw.length === 0) return undefined;
+ const acc = new Map<string, string[]>();
+ for (const entry of raw) {
+ const eq = entry.indexOf("=");
+ if (eq <= 0) {
+ throw new CliError(`--property must be KEY=VALUE, got: ${entry}`);
+ }
+ const key = entry.slice(0, eq).trim();
+ const value = entry.slice(eq + 1).trim();
+ if (key.length === 0 || value.length === 0) {
+ throw new CliError(`--property must be KEY=VALUE, got: ${entry}`);
+ }
+ const arr = acc.get(key) ?? [];
+ arr.push(value);
+ acc.set(key, arr);
+ }
+ const frozen = new Map<string, ReadonlyArray<string>>();
+ for (const [k, v] of acc) frozen.set(k, Object.freeze(v));
+ return frozen;
+}
+
function jsonForOutcome(o: SearchOutcome): unknown {
return {
results: o.results.map((r) => ({
diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.ts
index 18f993bd..1143789e 100644
--- a/src/core/brain/backlinks.ts
+++ b/src/core/brain/backlinks.ts
@@ -28,7 +28,12 @@
import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
-import { extractWikilinks, parseFrontmatter } from "../vault.ts";
+import { parseFrontmatter } from "../vault.ts";
+import { buildAliasIndex } from "./link-graph/alias-index.ts";
+import {
+ extractWikilinkRichBodies,
+ parseWikilinkRich,
+} from "./link-graph/parse-wikilink.ts";
import { parseLogDay } from "./log.ts";
import { brainDirs } from "./paths.ts";
import { normalizeDerivedKeys } from "./preference.ts";
@@ -51,6 +56,27 @@ export interface BacklinkRef {
readonly field: string;
/** ISO-8601 timestamp for log entries; absent for preference/retired sources. */
readonly timestamp?: string;
+ /**
+ * Heading-anchor text from `[[target#Heading]]` (v0.10.17+). Present
+ * only when the wikilink carried a heading anchor; absent for plain
+ * targets and for block references.
+ */
+ readonly targetAnchor?: string;
+ /**
+ * Block-id text from `[[target#^abc]]` (v0.10.17+). Present only
+ * when the wikilink carried a block anchor; absent otherwise. The
+ * `^` sigil is stripped; just the bare id is recorded.
+ */
+ readonly targetBlock?: string;
+ /**
+ * When the wikilink was written via an alias declared in the
+ * target's frontmatter `aliases:` array (v0.10.17+), the alias
+ * string the linker actually typed. `source` still keys against the
+ * canonical id; this field surfaces the alias spelling for
+ * downstream consumers (digest, doctor, concept synthesis) that
+ * want to show how the link was phrased.
+ */
+ readonly aliasSource?: string;
}
/** Frozen target → refs map. Keys are normalised wikilink targets. */
@@ -67,22 +93,47 @@ export type BacklinkIndex = ReadonlyMap<string, ReadonlyArray<BacklinkRef>>;
*/
export function buildBacklinkIndex(vault: string): BacklinkIndex {
const dirs = brainDirs(vault);
+ const aliasIndex = buildAliasIndex(vault);
const map = new Map<string, BacklinkRef[]>();
- // Dedup key: `<source>\x00<target>`. Preference body mirrors
- // frontmatter `evidenced_by` (rendered as "## Origin" bullets), so a
- // naive walk double-counts every pref→signal edge. We keep the
- // first-seen field (frontmatter) and drop later duplicates.
+ // Dedup key: `<source>\x00<canonical>\x00<anchor>\x00<block>`.
+ // Anchor + block are part of the dedup key so two refs to
+ // different anchors of the same target keep both entries (Unit 3
+ // requirement).
const seen = new Set<string>();
const push = (target: string, ref: BacklinkRef): void => {
- const norm = normaliseWikilinkTarget(target);
- if (!norm || norm === ref.source) return; // skip self-refs and empties
- const key = `${ref.source}\x00${norm}`;
+ const parsed = parseWikilinkRich(target);
+ const bare = parsed.target;
+ if (!bare) return;
+
+ // Resolve via the alias index. Lookup key is NFC + lower-case
+ // (matches the key normalisation `buildAliasIndex` emits). The
+ // alias resolves to a different canonical id only when the
+ // alias entry actually maps somewhere else.
+ const aliasKey = bare.normalize("NFC").toLowerCase();
+ let canonicalId = normaliseWikilinkTarget(bare);
+ let aliasSource: string | undefined;
+ const aliasHit = aliasIndex.get(aliasKey);
+ if (aliasHit && aliasHit !== canonicalId) {
+ aliasSource = bare;
+ canonicalId = aliasHit;
+ }
+ if (!canonicalId || canonicalId === ref.source) return;
+
+ const key = `${ref.source}\x00${canonicalId}\x00${parsed.anchor ?? ""}\x00${parsed.block ?? ""}`;
if (seen.has(key)) return;
seen.add(key);
- const arr = map.get(norm);
- if (arr) arr.push(ref);
- else map.set(norm, [ref]);
+
+ const enriched: BacklinkRef = {
+ ...ref,
+ ...(parsed.anchor !== undefined ? { targetAnchor: parsed.anchor } : {}),
+ ...(parsed.block !== undefined ? { targetBlock: parsed.block } : {}),
+ ...(aliasSource !== undefined ? { aliasSource } : {}),
+ };
+
+ const arr = map.get(canonicalId);
+ if (arr) arr.push(enriched);
+ else map.set(canonicalId, [enriched]);
};
collectPreferences(dirs.preferences, "preference", push);
@@ -161,8 +212,8 @@ function collectPreferences(
push(retiredBy, { source, sourceKind: kind, field: "retired_by" });
}
}
- for (const target of extractWikilinks(body)) {
- push(target, { source, sourceKind: kind, field: "body" });
+ for (const body0 of extractWikilinkRichBodies(body)) {
+ push(body0, { source, sourceKind: kind, field: "body" });
}
}
}
@@ -182,8 +233,8 @@ function collectSignals(
const sources = meta["source"];
const list = Array.isArray(sources) ? sources : sources ? [String(sources)] : [];
for (const t of list) push(t, { source, sourceKind: "signal", field: "source" });
- for (const target of extractWikilinks(body)) {
- push(target, { source, sourceKind: "signal", field: "body" });
+ for (const body0 of extractWikilinkRichBodies(body)) {
+ push(body0, { source, sourceKind: "signal", field: "body" });
}
} catch {
continue;
diff --git a/src/core/brain/link-graph/alias-index.ts b/src/core/brain/link-graph/alias-index.ts
new file mode 100644
index 00000000..6adf4c9a
--- /dev/null
+++ b/src/core/brain/link-graph/alias-index.ts
@@ -0,0 +1,114 @@
+/**
+ * Alias index over the Brain artifact set.
+ *
+ * Obsidian-flavoured frontmatter allows a note to declare extra
+ * lookup names via `aliases: [foo, bar]`. The backlink index, the
+ * unlinked-mentions scanner, and the concept-cluster assembler all
+ * need to resolve a wikilink target `[[foo]]` to the canonical
+ * artifact id even when `foo` is an alias rather than the bare
+ * basename.
+ *
+ * `buildAliasIndex` is a single-pass read over
+ * `Brain/preferences/` + `Brain/retired/`. Each declared alias is
+ * NFC-normalised and lower-cased to form the lookup key; the value
+ * is the canonical artifact id (file basename without `.md`).
+ *
+ * Collisions (two artifacts claim the same alias) resolve
+ * first-wins by sorted canonical id - deterministic without an
+ * extra timestamp lookup. A follow-up `brain_doctor` lint can
+ * later surface colliding aliases for operator attention; this
+ * helper is intentionally tolerant so the index keeps building.
+ *
+ * Empty / non-array `aliases` values are silently skipped. Malformed
+ * frontmatter (parse failure) is silently skipped - `brain_doctor`
+ * surfaces those separately.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../../vault.ts";
+import { brainDirs } from "../paths.ts";
+
+/**
+ * Frozen `aliasLowerNFC → canonicalId` map. Keys are pre-normalised
+ * so callers should normalise their lookup key the same way (NFC +
+ * lower-case) before consulting the map.
+ */
+export type AliasIndex = ReadonlyMap<string, string>;
+
+/**
+ * Walk Brain preferences + retired artifacts, collect their
+ * frontmatter `aliases:` arrays, and return the inverted lookup.
+ *
+ * The returned map is frozen. Re-call to refresh; there is no
+ * incremental update path on purpose.
+ */
+export function buildAliasIndex(vault: string): AliasIndex {
+ const dirs = brainDirs(vault);
+ const map = new Map<string, string>();
+
+ // Collect every on-disk canonical id (lower-cased + NFC) in one
+ // pass so the alias-collection phase can skip any alias that
+ // collides with a real basename. Without this guard, an alias
+ // entry can hijack an existing artifact's backlinks.
+ const reservedCanonical = new Set<string>();
+ collectCanonicalNames(dirs.preferences, reservedCanonical);
+ collectCanonicalNames(dirs.retired, reservedCanonical);
+
+ // Single sorted pass yields deterministic first-wins resolution
+ // when two artifacts claim the same alias. Sorting by `(kind,
+ // basename)` puts `pref-*` before `ret-*`; within each kind,
+ // alphabetical basename order wins.
+ collect(dirs.preferences, reservedCanonical, map);
+ collect(dirs.retired, reservedCanonical, map);
+
+ return Object.freeze(map) as AliasIndex;
+}
+
+function collectCanonicalNames(dir: string, into: Set<string>): void {
+ if (!existsSync(dir)) return;
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md")) continue;
+ const canonicalId = name.slice(0, -".md".length);
+ into.add(canonicalId.normalize("NFC").toLowerCase());
+ }
+}
+
+function collect(
+ dir: string,
+ reservedCanonical: ReadonlySet<string>,
+ into: Map<string, string>,
+): void {
+ if (!existsSync(dir)) return;
+ // Sort the directory listing so the first-wins rule is
+ // deterministic across filesystems that don't enumerate in
+ // stable order.
+ const entries = readdirSync(dir).sort();
+ for (const name of entries) {
+ if (!name.endsWith(".md")) continue;
+ const canonicalId = name.slice(0, -".md".length);
+ let meta: Record<string, unknown>;
+ try {
+ const [m] = parseFrontmatter(join(dir, name));
+ meta = m as Record<string, unknown>;
+ } catch {
+ continue;
+ }
+ const aliases = meta["aliases"];
+ if (!Array.isArray(aliases)) continue;
+ for (const alias of aliases) {
+ if (typeof alias !== "string") continue;
+ const trimmed = alias.trim();
+ if (trimmed.length === 0) continue;
+ const key = trimmed.normalize("NFC").toLowerCase();
+ // Skip aliases that would shadow an existing on-disk id.
+ // The canonical artifact wins; the alias is silently dropped
+ // to avoid hijacking its backlinks. A follow-up brain_doctor
+ // lint surfaces these collisions for operator attention.
+ if (reservedCanonical.has(key)) continue;
+ // First-wins: only set when the key isn't taken yet.
+ if (!into.has(key)) into.set(key, canonicalId);
+ }
+ }
+}
diff --git a/src/core/brain/link-graph/concept-cluster.ts b/src/core/brain/link-graph/concept-cluster.ts
new file mode 100644
index 00000000..02b6b482
--- /dev/null
+++ b/src/core/brain/link-graph/concept-cluster.ts
@@ -0,0 +1,127 @@
+/**
+ * Concept-cluster assembler.
+ *
+ * Given a target Brain artifact id, gather every preference / retired
+ * note that wikilinks to it (depth-1) and emit a deterministic
+ * envelope. Optionally also include unlinked-mention rows so
+ * downstream consumers see latent connections as well as formalised
+ * ones.
+ *
+ * The helper is pure: no LLM call, no network I/O. The envelope is
+ * stable enough to commit to a JSON schema; an external LLM consumer
+ * can feed it through a synthesis prompt later without re-prompting
+ * the structure.
+ */
+
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../../vault.ts";
+import { buildBacklinkIndex, type BacklinkRef } from "../backlinks.ts";
+import { brainDirs } from "../paths.ts";
+import { isoSecond } from "../time.ts";
+import { normaliseWikilinkTarget } from "../wikilink.ts";
+import {
+ findUnlinkedMentions,
+ type MentionRef,
+} from "./unlinked-mentions.ts";
+
+/** One linker pointing at the target. */
+export interface ConceptLinker {
+ readonly source: string;
+ readonly sourceKind: BacklinkRef["sourceKind"];
+ readonly field: string;
+ readonly timestamp?: string;
+ readonly targetAnchor?: string;
+ readonly targetBlock?: string;
+ readonly aliasSource?: string;
+}
+
+/** Concept-cluster envelope returned by {@link buildConceptCluster}. */
+export interface ConceptClusterEnvelope {
+ readonly targetId: string;
+ readonly targetTitle: string;
+ readonly linkers: ReadonlyArray<ConceptLinker>;
+ readonly unlinkedMentions: ReadonlyArray<MentionRef>;
+ readonly generatedAt: string;
+}
+
+export interface BuildConceptClusterOptions {
+ /** When true, populate `unlinkedMentions[]`. Default `false`. */
+ readonly includeUnlinked?: boolean;
+ /** Cap on unlinked-mention rows when included. Default `100`. */
+ readonly unlinkedLimit?: number;
+}
+
+/**
+ * Assemble the concept-cluster envelope for `targetId`.
+ *
+ * Linkers are sorted by `(source asc, field asc)` so the output is
+ * deterministic across filesystems that don't enumerate in a stable
+ * order. Returns a frozen object.
+ */
+export function buildConceptCluster(
+ vault: string,
+ targetId: string,
+ opts: BuildConceptClusterOptions = {},
+): ConceptClusterEnvelope {
+ const normalised = normaliseWikilinkTarget(targetId);
+ const targetTitle = resolveTitle(vault, normalised);
+
+ const index = buildBacklinkIndex(vault);
+ const refs = index.get(normalised) ?? [];
+ const linkers: ConceptLinker[] = refs
+ .map((r) =>
+ Object.freeze({
+ source: r.source,
+ sourceKind: r.sourceKind,
+ field: r.field,
+ ...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),
+ ...(r.targetAnchor !== undefined ? { targetAnchor: r.targetAnchor } : {}),
+ ...(r.targetBlock !== undefined ? { targetBlock: r.targetBlock } : {}),
+ ...(r.aliasSource !== undefined ? { aliasSource: r.aliasSource } : {}),
+ }),
+ )
+ .sort((a, b) => {
+ const sa = a.source.localeCompare(b.source);
+ if (sa !== 0) return sa;
+ return a.field.localeCompare(b.field);
+ });
+
+ const unlinkedMentions = opts.includeUnlinked
+ ? findUnlinkedMentions(vault, normalised, {
+ ...(opts.unlinkedLimit !== undefined
+ ? { limit: opts.unlinkedLimit }
+ : {}),
+ })
+ : Object.freeze([] as MentionRef[]);
+
+ return Object.freeze({
+ targetId: normalised,
+ targetTitle,
+ linkers: Object.freeze(linkers) as ReadonlyArray<ConceptLinker>,
+ unlinkedMentions,
+ generatedAt: isoSecond(),
+ });
+}
+
+function resolveTitle(vault: string, targetId: string): string {
+ const dirs = brainDirs(vault);
+ const candidates = [
+ join(dirs.preferences, `${targetId}.md`),
+ join(dirs.retired, `${targetId}.md`),
+ ];
+ for (const c of candidates) {
+ if (!existsSync(c)) continue;
+ try {
+ const [meta] = parseFrontmatter(c);
+ const titleRaw = (meta as Record<string, unknown>)["title"];
+ if (typeof titleRaw === "string" && titleRaw.trim().length > 0) {
+ return titleRaw.trim();
+ }
+ } catch {
+ continue;
+ }
+ }
+ return targetId;
+}
diff --git a/src/core/brain/link-graph/moc-audit.ts b/src/core/brain/link-graph/moc-audit.ts
new file mode 100644
index 00000000..532ecd26
--- /dev/null
+++ b/src/core/brain/link-graph/moc-audit.ts
@@ -0,0 +1,242 @@
+/**
+ * Per-MOC topic-coverage audit.
+ *
+ * Given a hub note id, classify each member of the hub's outbound
+ * cluster into:
+ * - `wellCovered` - many inbound backlinks + body above floor
+ * - `fragile` - one inbound backlink OR short body
+ * - `candidateMissing` - target referenced via `[[…]]` but no
+ * on-disk artifact exists
+ * - `suggestedNext` - the highest-leverage candidate-missing,
+ * measured by reference count across hub +
+ * cluster members
+ *
+ * MOC detection is purely structural: outbound link count + ratio
+ * of link characters to non-whitespace body characters must cross
+ * the thresholds in `link_graph` config. No vocabulary detection
+ * of "this looks like a MOC because the title says so".
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { buildBacklinkIndex } from "../backlinks.ts";
+import { brainDirs } from "../paths.ts";
+import { loadBrainConfig, resolveLinkGraph } from "../policy.ts";
+import { normaliseWikilinkTarget } from "../wikilink.ts";
+import { extractWikilinkRichBodies, parseWikilinkRich } from "./parse-wikilink.ts";
+
+/** Inclusive minimum backlink count for the `wellCovered` bucket. */
+const WELL_COVERED_MIN_BACKLINKS = 2;
+/** Inclusive minimum body-character count for the `wellCovered` bucket. */
+const WELL_COVERED_MIN_BODY_CHARS = 200;
+/** Maximum backlink count that still qualifies for the `fragile` bucket. */
+const FRAGILE_MAX_BACKLINKS = 1;
+
+export class MocAuditError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "MocAuditError";
+ }
+}
+
+export interface MocClusterMember {
+ readonly id: string;
+ readonly backlinkCount: number;
+ readonly bodyChars: number;
+}
+
+export interface MocAuditReport {
+ readonly hubId: string;
+ readonly outboundCount: number;
+ readonly wellCovered: ReadonlyArray<MocClusterMember>;
+ readonly fragile: ReadonlyArray<MocClusterMember>;
+ readonly candidateMissing: ReadonlyArray<{
+ readonly id: string;
+ readonly referenceCount: number;
+ }>;
+ readonly suggestedNext?: {
+ readonly id: string;
+ readonly referenceCount: number;
+ };
+}
+
+export interface AuditMocOptions {
+ /** When set, skip the `link_graph` config lookup and use this. */
+ readonly minOutboundLinks?: number;
+ /** When set, skip the `link_graph` config lookup and use this. */
+ readonly minLinkRatio?: number;
+}
+
+export function auditMoc(
+ vault: string,
+ hubId: string,
+ opts: AuditMocOptions = {},
+): MocAuditReport {
+ const hubCanonical = normaliseWikilinkTarget(hubId);
+ const hubPath = locateArtifact(vault, hubCanonical);
+ if (!hubPath) {
+ throw new MocAuditError(`hub note not found: ${hubCanonical}`);
+ }
+
+ const hubBody = stripFrontmatter(readFileSync(hubPath, "utf8"));
+ const outboundBodies = extractWikilinkRichBodies(hubBody);
+ const outboundTargets = uniq(
+ outboundBodies
+ .map((b) => parseWikilinkRich(b).target)
+ .filter((t) => t.length > 0 && t !== hubCanonical),
+ );
+
+ const { minOutbound, minRatio } = resolveThresholds(vault, opts);
+ if (outboundTargets.length < minOutbound) {
+ throw new MocAuditError(
+ `not a MOC: outbound link count ${outboundTargets.length} < threshold ${minOutbound}`,
+ );
+ }
+
+ // Link-ratio: total characters inside `[[…]]` over non-whitespace
+ // body characters. Whitespace is excluded from the denominator so
+ // a heavily-indented link list isn't penalised against a compact
+ // one. Numerator includes the four bracket characters (`[[]]`)
+ // per link so a bracket-heavy body counts proportionally.
+ const linkChars = outboundBodies.reduce((sum, b) => sum + b.length + 4, 0);
+ const bodyChars = hubBody.replace(/\s+/g, "").length;
+ const ratio = bodyChars > 0 ? linkChars / bodyChars : 0;
+ if (ratio < minRatio) {
+ throw new MocAuditError(
+ `not a MOC: link ratio ${ratio.toFixed(2)} < threshold ${minRatio}`,
+ );
+ }
+
+ // Backlink index + cluster member metadata.
+ const index = buildBacklinkIndex(vault);
+ const wellCovered: MocClusterMember[] = [];
+ const fragile: MocClusterMember[] = [];
+ const candidateMissing: { id: string; referenceCount: number }[] = [];
+ const missingCounts = new Map<string, number>();
+
+ for (const target of outboundTargets) {
+ const memberPath = locateArtifact(vault, target);
+ if (!memberPath) {
+ missingCounts.set(target, (missingCounts.get(target) ?? 0) + 1);
+ continue;
+ }
+ const memberBody = stripFrontmatter(readFileSync(memberPath, "utf8"));
+ const backlinks = index.get(target) ?? [];
+ // Don't count the hub's own outbound reference toward the
+ // bucket assignment; the bucket measures coverage by OTHER
+ // notes, not by the hub itself.
+ const inboundFromOthers = backlinks.filter(
+ (r) => r.source !== hubCanonical,
+ ).length;
+ const member: MocClusterMember = Object.freeze({
+ id: target,
+ backlinkCount: inboundFromOthers,
+ bodyChars: memberBody.length,
+ });
+ if (
+ inboundFromOthers >= WELL_COVERED_MIN_BACKLINKS &&
+ memberBody.length >= WELL_COVERED_MIN_BODY_CHARS
+ ) {
+ wellCovered.push(member);
+ } else if (inboundFromOthers <= FRAGILE_MAX_BACKLINKS) {
+ fragile.push(member);
+ }
+ // Members between the two buckets (e.g. high backlinks but short
+ // body) fall through; future releases can expose them under a
+ // "developing" bucket if profile shows it pays.
+ }
+
+ // Walk cluster member bodies to find additional references to
+ // missing targets (for the `referenceCount` field).
+ for (const target of outboundTargets) {
+ if (!missingCounts.has(target)) continue;
+ for (const member of outboundTargets) {
+ const path = locateArtifact(vault, member);
+ if (!path) continue;
+ const body = stripFrontmatter(readFileSync(path, "utf8"));
+ for (const bracketBody of extractWikilinkRichBodies(body)) {
+ const t = parseWikilinkRich(bracketBody).target;
+ if (t === target) {
+ missingCounts.set(target, (missingCounts.get(target) ?? 0) + 1);
+ }
+ }
+ }
+ }
+
+ for (const [id, count] of missingCounts) {
+ candidateMissing.push(Object.freeze({ id, referenceCount: count }));
+ }
+ candidateMissing.sort((a, b) => b.referenceCount - a.referenceCount);
+
+ const suggestedNext = candidateMissing[0];
+
+ return Object.freeze({
+ hubId: hubCanonical,
+ outboundCount: outboundTargets.length,
+ wellCovered: Object.freeze(wellCovered) as ReadonlyArray<MocClusterMember>,
+ fragile: Object.freeze(fragile) as ReadonlyArray<MocClusterMember>,
+ candidateMissing: Object.freeze(candidateMissing) as ReadonlyArray<{
+ id: string;
+ referenceCount: number;
+ }>,
+ ...(suggestedNext ? { suggestedNext } : {}),
+ });
+}
+
+function locateArtifact(vault: string, id: string): string | null {
+ const dirs = brainDirs(vault);
+ const candidates = [
+ join(dirs.preferences, `${id}.md`),
+ join(dirs.retired, `${id}.md`),
+ ];
+ for (const c of candidates) if (existsSync(c)) return c;
+ return null;
+}
+
+function stripFrontmatter(text: string): string {
+ const m = /^---\s*\n([\s\S]*?)\n---\s*\n?/.exec(text);
+ if (!m) return text;
+ return text.slice(m[0].length);
+}
+
+function uniq<T>(values: ReadonlyArray<T>): T[] {
+ const seen = new Set<T>();
+ const out: T[] = [];
+ for (const v of values) {
+ if (seen.has(v)) continue;
+ seen.add(v);
+ out.push(v);
+ }
+ return out;
+}
+
+function resolveThresholds(
+ vault: string,
+ opts: AuditMocOptions,
+): { minOutbound: number; minRatio: number } {
+ if (
+ opts.minOutboundLinks !== undefined &&
+ opts.minLinkRatio !== undefined
+ ) {
+ return {
+ minOutbound: opts.minOutboundLinks,
+ minRatio: opts.minLinkRatio,
+ };
+ }
+ let cfg;
+ try {
+ cfg = loadBrainConfig(vault);
+ } catch {
+ cfg = null;
+ }
+ const lg = cfg ? resolveLinkGraph(cfg) : null;
+ return {
+ minOutbound:
+ opts.minOutboundLinks ??
+ (lg ? lg.moc_min_outbound_links : 5),
+ minRatio:
+ opts.minLinkRatio ?? (lg ? lg.moc_min_link_ratio : 0.3),
+ };
+}
+
diff --git a/src/core/brain/link-graph/parse-wikilink.ts b/src/core/brain/link-graph/parse-wikilink.ts
new file mode 100644
index 00000000..50797b2e
--- /dev/null
+++ b/src/core/brain/link-graph/parse-wikilink.ts
@@ -0,0 +1,181 @@
+/**
+ * Rich wikilink parse helper.
+ *
+ * The Obsidian wikilink grammar supports four pieces of metadata in
+ * one bracket pair:
+ *
+ * - target (`[[NoteName]]`) - the canonical id; required.
+ * - anchor (`[[Note#Heading]]`) - heading reference; optional.
+ * - block (`[[Note#^abc]]`) - block-id reference; optional. Same
+ * `#` delimiter as the anchor but
+ * distinguished by the `^` sigil.
+ * - alias (`[[Note|display]]`) - human-readable display text;
+ * optional.
+ *
+ * The legacy `parseWikilink` / `normaliseWikilinkTarget` helpers in
+ * `wikilink.ts` return just the bare `target` string. This rich
+ * variant returns the same target plus the additional slots so
+ * downstream consumers (backlink index, unlinked-mentions scanner,
+ * concept-cluster assembler) can see paragraph-level intent without
+ * losing it at the parser boundary.
+ *
+ * The helper is intentionally tolerant: any input that doesn't look
+ * like a wikilink (no surrounding `[[…]]`) is treated as a bare
+ * target body and run through the same decoration-stripping pipeline.
+ * Callers that need a "this is literally a wikilink?" predicate
+ * should keep using `parseWikilink` (which returns `null` for
+ * non-wikilink input).
+ */
+
+import { basename } from "node:path";
+
+/**
+ * Local regex for the rich extractor. Captures the full bracket
+ * body (everything between `[[` and `]]`), so anchor / alias / block
+ * info survives for downstream `parseWikilinkRich` consumption.
+ *
+ * Bracketed by `]]` and forbidding embedded `]` so nested brackets
+ * don't collapse two adjacent wikilinks into one match. Anchored to
+ * non-newline so a link that spans lines is not silently joined.
+ */
+const RICH_WIKILINK_RE = /\[\[([^\]\n]+)\]\]/g;
+
+/**
+ * Local mask for fenced and inline code spans. Mirrors the constant
+ * used by `extractWikilinks` in `vault.ts` so a wikilink that lives
+ * inside a code block does not pollute the index.
+ */
+const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;
+
+/**
+ * Inclusive list of file-extension suffixes (lower-case) that
+ * disqualify a wikilink from the backlink index. Mirrors the media
+ * filter in `vault.ts:extractWikilinks` so embed-style links don't
+ * register as backlinks.
+ */
+const MEDIA_EXTENSIONS: ReadonlySet<string> = new Set([
+ ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff",
+ ".avif", ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi", ".mp3",
+ ".wav", ".ogg", ".flac", ".m4a", ".pdf",
+]);
+
+export interface WikilinkParse {
+ /** Canonical bare id - same shape `normaliseWikilinkTarget` returns. */
+ readonly target: string;
+ /**
+ * Heading-anchor text (`#Heading`), present only when the link
+ * carries a heading anchor (no leading `^`). Absent for block
+ * references and for plain targets.
+ */
+ readonly anchor?: string;
+ /**
+ * Block-id text (`#^block-id`), present only when the link carries
+ * a block anchor. The `^` sigil is stripped; just the bare id.
+ */
+ readonly block?: string;
+ /**
+ * Display alias from `[[target|alias]]`. The alias text is
+ * preserved verbatim minus surrounding whitespace.
+ */
+ readonly alias?: string;
+}
+
+/**
+ * Parse an Obsidian wikilink into its four-slot decomposition.
+ *
+ * Tolerant of:
+ * - bracketed and bare forms (`[[foo]]` and `foo`)
+ * - alias suffix (`[[foo|display]]`)
+ * - heading anchor (`[[foo#Heading]]`)
+ * - block anchor (`[[foo#^abc]]`)
+ * - folder prefix (`[[Folder/foo]]`)
+ * - trailing `.md` extension (`[[foo.md]]`)
+ * - any combination of the above (alias may follow either anchor
+ * shape; folder prefix may sit on the target side)
+ *
+ * Returns a frozen object so callers can't mutate shared state. Empty
+ * input returns `{target: ""}` (no anchor / block / alias).
+ */
+export function parseWikilinkRich(value: string): WikilinkParse {
+ let s = value.trim();
+
+ // Strip surrounding wikilink brackets when present. Bare-text input
+ // skips this branch and goes straight to the decoration-strip
+ // pipeline.
+ const wm = /^\[\[([^\]]+)\]\]/.exec(s);
+ if (wm) s = wm[1]!.trim();
+
+ // Pull alias FIRST. The pipe separator binds tighter than the hash
+ // separator in the Obsidian grammar - `[[foo#Heading|alias]]` means
+ // target `foo`, anchor `Heading`, alias `alias`. Locating the pipe
+ // first lets us safely scan for `#` in just the target+anchor span.
+ let alias: string | undefined;
+ const pipeIdx = s.indexOf("|");
+ if (pipeIdx >= 0) {
+ const aliasText = s.slice(pipeIdx + 1).trim();
+ if (aliasText.length > 0) alias = aliasText;
+ s = s.slice(0, pipeIdx).trim();
+ }
+
+ // Pull anchor / block. The `#^` block sigil is structural (Obsidian
+ // grammar), not language-specific. The `#` heading sigil is
+ // likewise structural - this branch never inspects the anchor
+ // text's vocabulary.
+ let anchor: string | undefined;
+ let block: string | undefined;
+ const hashIdx = s.indexOf("#");
+ if (hashIdx >= 0) {
+ const afterHash = s.slice(hashIdx + 1);
+ if (afterHash.startsWith("^")) {
+ const blockText = afterHash.slice(1).trim();
+ if (blockText.length > 0) block = blockText;
+ } else {
+ const anchorText = afterHash.trim();
+ if (anchorText.length > 0) anchor = anchorText;
+ }
+ s = s.slice(0, hashIdx).trim();
+ }
+
+ // Normalise the bare target: folder collapse + `.md` strip. Empty
+ // input falls through cleanly.
+ let target = basename(s);
+ if (target.endsWith(".md")) target = target.slice(0, -".md".length);
+
+ return Object.freeze({
+ target,
+ ...(anchor !== undefined ? { anchor } : {}),
+ ...(block !== undefined ? { block } : {}),
+ ...(alias !== undefined ? { alias } : {}),
+ });
+}
+
+/**
+ * Yield every wikilink bracket-body from a Markdown content string,
+ * preserving anchor / alias / block decoration so callers can run
+ * each through {@link parseWikilinkRich}.
+ *
+ * Skips text inside fenced or inline code blocks (mirrors the
+ * masking pass in `extractWikilinks` from `vault.ts`). Media-extension
+ * targets (`.png`, `.pdf`, …) are dropped so an embed-style link
+ * does not pollute the backlink index.
+ *
+ * Returns the bare bracket body (no surrounding `[[`/`]]`). Empty
+ * input yields an empty array.
+ */
+export function extractWikilinkRichBodies(content: string): ReadonlyArray<string> {
+ const masked = content.replace(CODE_BLOCK_RE, " ");
+ const out: string[] = [];
+ for (const m of masked.matchAll(RICH_WIKILINK_RE)) {
+ const body = m[1]!;
+ // Drop embed-style media links - same filter as
+ // `extractWikilinks` in `vault.ts`. The check inspects the
+ // bare-target portion (before `#`/`|`) to avoid false-positives
+ // on aliases that happen to end in a media-shaped extension.
+ const targetSide = body.split(/[#|]/, 1)[0]!.trim();
+ const dot = targetSide.lastIndexOf(".");
+ const ext = dot >= 0 ? targetSide.slice(dot).toLowerCase() : "";
+ if (MEDIA_EXTENSIONS.has(ext)) continue;
+ out.push(body);
+ }
+ return out;
+}
diff --git a/src/core/brain/link-graph/unlinked-mentions.ts b/src/core/brain/link-graph/unlinked-mentions.ts
new file mode 100644
index 00000000..421a810c
--- /dev/null
+++ b/src/core/brain/link-graph/unlinked-mentions.ts
@@ -0,0 +1,216 @@
+/**
+ * Unlinked-mentions scanner.
+ *
+ * Given a target Brain artifact id, walk every other preference /
+ * retired note and emit each raw-text occurrence of the target's
+ * title (or any frontmatter alias) that is NOT already inside a
+ * `[[...]]` wikilink and NOT inside a fenced / inline code span.
+ *
+ * The matcher is purely structural:
+ *
+ * - Word boundaries use Unicode codepoint classes (`\p{L}`,
+ * `\p{N}`); both edges of the match must sit against a
+ * non-letter, non-digit codepoint (or string edge).
+ * - Single-codepoint terms are rejected as too noisy.
+ * - No vocabulary list, no stopword set, no per-language data.
+ *
+ * The scanner is read-only and bounded by vault size; pure helper,
+ * no I/O beyond the directory walk + per-file read.
+ */
+
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../../vault.ts";
+import { brainDirs } from "../paths.ts";
+
+/** One unlinked-mention occurrence. */
+export interface MentionRef {
+ /** Source artifact id (basename without `.md`). */
+ readonly source: string;
+ /** 1-based line number in the source body. */
+ readonly line: number;
+ /** The literal term that matched (title or alias spelling). */
+ readonly term: string;
+ /** Line content with the match in situ (single line, untrimmed). */
+ readonly contextSnippet: string;
+}
+
+export interface FindUnlinkedMentionsOptions {
+ /**
+ * Maximum number of mentions returned. Default `100`. Pagination is
+ * not exposed; callers needing more should call with a larger cap.
+ */
+ readonly limit?: number;
+}
+
+const DEFAULT_LIMIT = 100;
+
+/** Minimum codepoint count for a search term to count as a match. */
+const MIN_TERM_CODEPOINTS = 2;
+
+/** Replacement char used to mask brackets / code spans. */
+const MASK_CHAR = " ";
+
+const BRACKET_RE = /\[\[[^\]\n]+\]\]/g;
+const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;
+const WORD_CHAR_RE = /[\p{L}\p{N}]/u;
+
+/**
+ * Walk `Brain/preferences/` and `Brain/retired/` for unlinked
+ * mentions of the target. Returns a frozen array capped at
+ * `opts.limit`.
+ */
+export function findUnlinkedMentions(
+ vault: string,
+ targetId: string,
+ opts: FindUnlinkedMentionsOptions = {},
+): ReadonlyArray<MentionRef> {
+ const limit = opts.limit ?? DEFAULT_LIMIT;
+ const dirs = brainDirs(vault);
+
+ // Resolve the target's title + aliases from frontmatter.
+ const terms = resolveSearchTerms(vault, targetId);
+ if (terms.length === 0) return Object.freeze([]) as ReadonlyArray<MentionRef>;
+
+ const collected: MentionRef[] = [];
+ scanDir(dirs.preferences, targetId, terms, collected, limit);
+ if (collected.length < limit) {
+ scanDir(dirs.retired, targetId, terms, collected, limit);
+ }
+
+ return Object.freeze(collected) as ReadonlyArray<MentionRef>;
+}
+
+function resolveSearchTerms(vault: string, targetId: string): ReadonlyArray<string> {
+ const dirs = brainDirs(vault);
+ const candidates = [
+ join(dirs.preferences, `${targetId}.md`),
+ join(dirs.retired, `${targetId}.md`),
+ ];
+ let metaSource: Record<string, unknown> | null = null;
+ for (const c of candidates) {
+ if (!existsSync(c)) continue;
+ try {
+ const [meta] = parseFrontmatter(c);
+ metaSource = meta as Record<string, unknown>;
+ break;
+ } catch {
+ continue;
+ }
+ }
+
+ const terms: string[] = [];
+ const seen = new Set<string>();
+ const push = (raw: unknown): void => {
+ if (typeof raw !== "string") return;
+ const trimmed = raw.trim();
+ if (trimmed.length === 0) return;
+ if (Array.from(trimmed).length < MIN_TERM_CODEPOINTS) return;
+ const key = trimmed.normalize("NFC").toLowerCase();
+ if (seen.has(key)) return;
+ seen.add(key);
+ terms.push(trimmed);
+ };
+
+ if (metaSource) {
+ push(metaSource["title"]);
+ const aliases = metaSource["aliases"];
+ if (Array.isArray(aliases)) for (const a of aliases) push(a);
+ }
+ // Fall back to the id itself when no title is declared. The id
+ // already has at least two codepoints in every realistic case
+ // (`pref-x`, `ret-y`).
+ if (terms.length === 0) push(targetId);
+
+ return terms;
+}
+
+function scanDir(
+ dir: string,
+ targetId: string,
+ terms: ReadonlyArray<string>,
+ out: MentionRef[],
+ limit: number,
+): void {
+ if (!existsSync(dir)) return;
+ for (const name of readdirSync(dir)) {
+ if (out.length >= limit) return;
+ if (!name.endsWith(".md")) continue;
+ const source = name.slice(0, -".md".length);
+ if (source === targetId) continue;
+ let text: string;
+ try {
+ text = readFileSync(join(dir, name), "utf8");
+ } catch {
+ continue;
+ }
+ // Strip frontmatter before scanning the body.
+ const body = stripFrontmatter(text);
+ scanBody(body, source, terms, out, limit);
+ }
+}
+
+function stripFrontmatter(text: string): string {
+ const m = /^---\s*\n([\s\S]*?)\n---\s*\n?/.exec(text);
+ if (!m) return text;
+ return text.slice(m[0].length);
+}
+
+function scanBody(
+ body: string,
+ source: string,
+ terms: ReadonlyArray<string>,
+ out: MentionRef[],
+ limit: number,
+): void {
+ // Mask wikilinks and code spans so matches inside them are
+ // ignored. The mask preserves character offsets so line/column
+ // bookkeeping stays exact - replace each masked region with a
+ // run of MASK_CHAR of identical length.
+ const masked = maskRegions(body, [BRACKET_RE, CODE_BLOCK_RE]);
+ const lines = masked.split("\n");
+ const originalLines = body.split("\n");
+
+ for (let i = 0; i < lines.length; i++) {
+ if (out.length >= limit) return;
+ const maskedLine = lines[i]!;
+ const original = originalLines[i] ?? "";
+ for (const term of terms) {
+ const lowerLine = maskedLine.toLowerCase();
+ const lowerTerm = term.toLowerCase();
+ let from = 0;
+ while (from <= lowerLine.length) {
+ const idx = lowerLine.indexOf(lowerTerm, from);
+ if (idx < 0) break;
+ const before = idx > 0 ? maskedLine[idx - 1] : undefined;
+ const after = maskedLine[idx + lowerTerm.length];
+ if (isWordEdge(before) && isWordEdge(after)) {
+ out.push(
+ Object.freeze({
+ source,
+ line: i + 1,
+ term,
+ contextSnippet: original,
+ }),
+ );
+ if (out.length >= limit) return;
+ }
+ from = idx + Math.max(1, lowerTerm.length);
+ }
+ }
+ }
+}
+
+function isWordEdge(ch: string | undefined): boolean {
+ if (ch === undefined) return true;
+ return !WORD_CHAR_RE.test(ch);
+}
+
+function maskRegions(text: string, regexes: ReadonlyArray<RegExp>): string {
+ let masked = text;
+ for (const re of regexes) {
+ masked = masked.replace(re, (s) => MASK_CHAR.repeat(s.length));
+ }
+ return masked;
+}
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index a3ba0e61..d1f59bd5 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -25,10 +25,12 @@ import type {
BrainActiveConfig,
BrainConfig,
BrainGuardrailConfig,
+ BrainLinkGraphConfig,
BrainMostAppliedConfig,
BrainVaultConfig,
DisciplineReportConfig,
ResolvedBrainGuardrailConfig,
+ ResolvedBrainLinkGraphConfig,
} from "./types.ts";
// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to
// break the module-init cycle: the resolver lives in `index.ts` and
@@ -117,6 +119,52 @@ export function resolveGuardrails(
};
}
+/**
+ * Default `link_graph` block (v0.10.17). Absent from `_brain.yaml`
+ * (or with absent individual keys) falls back here via
+ * `resolveLinkGraph`. Both knobs are purely structural - no
+ * vocabulary detection of "this looks like a MOC".
+ *
+ * Defaults:
+ * - `moc_min_outbound_links: 5` - the heuristic floor for "this
+ * is a hub note", chosen to filter out prose notes with a few
+ * inline references.
+ * - `moc_min_link_ratio: 0.3` - 30 % of the body's non-whitespace
+ * characters must sit inside `[[…]]` for the audit to accept
+ * the note as a MOC. Prose notes typically score below 0.1.
+ * - `vault_instruction_file: "VAULT.md"` - the user-authored
+ * vault-root instruction file `brain_context` surfaces when
+ * present. Configurable per vault.
+ */
+export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig =
+ Object.freeze({
+ moc_min_outbound_links: 5,
+ moc_min_link_ratio: 0.3,
+ vault_instruction_file: "VAULT.md",
+ }) as ResolvedBrainLinkGraphConfig;
+
+/**
+ * Merge a parsed `link_graph` block (or `undefined`) with
+ * `BRAIN_LINK_GRAPH_DEFAULTS`.
+ */
+export function resolveLinkGraph(
+ cfg: BrainConfig,
+): ResolvedBrainLinkGraphConfig {
+ const lg = cfg.link_graph;
+ if (lg === undefined) return BRAIN_LINK_GRAPH_DEFAULTS;
+ return {
+ moc_min_outbound_links:
+ lg.moc_min_outbound_links ??
+ BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,
+ moc_min_link_ratio:
+ lg.moc_min_link_ratio ??
+ BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,
+ vault_instruction_file:
+ lg.vault_instruction_file ??
+ BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,
+ };
+}
+
/**
* Default `_brain.yaml` content. Mirrors §10 of the design doc. Used by
* `brain init` and as the fallback inside `loadBrainConfig` when callers
@@ -833,6 +881,95 @@ export function validateBrainConfigDetailed(
}
}
+ // Optional `link_graph` block (v0.10.17). Shape:
+ // link_graph:
+ // moc_min_outbound_links: 5 # positive integer
+ // moc_min_link_ratio: 0.3 # number in (0, 1]
+ // vault_instruction_file: VAULT.md # vault-relative path
+ // Absent block → `cfg.link_graph` undefined; resolveLinkGraph
+ // returns the bit-identical defaults.
+ let linkGraph: BrainLinkGraphConfig | undefined;
+ if ("link_graph" in obj) {
+ const rawLg = obj["link_graph"];
+ if (typeof rawLg !== "object" || rawLg === null || Array.isArray(rawLg)) {
+ throw new BrainConfigError(
+ "link_graph must be a mapping",
+ "link_graph",
+ source,
+ );
+ }
+ const lgObj = rawLg as Record<string, unknown>;
+ const partialLg: Record<string, unknown> = {};
+ if ("moc_min_outbound_links" in lgObj) {
+ const v = lgObj["moc_min_outbound_links"];
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {
+ throw new BrainConfigError(
+ "must be a positive integer",
+ "link_graph.moc_min_outbound_links",
+ source,
+ );
+ }
+ partialLg["moc_min_outbound_links"] = v;
+ }
+ if ("moc_min_link_ratio" in lgObj) {
+ const v = lgObj["moc_min_link_ratio"];
+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) {
+ throw new BrainConfigError(
+ "must be a number in (0, 1]",
+ "link_graph.moc_min_link_ratio",
+ source,
+ );
+ }
+ partialLg["moc_min_link_ratio"] = v;
+ }
+ if ("vault_instruction_file" in lgObj) {
+ const v = lgObj["vault_instruction_file"];
+ if (typeof v !== "string" || v.trim().length === 0) {
+ throw new BrainConfigError(
+ "must be a non-empty string",
+ "link_graph.vault_instruction_file",
+ source,
+ );
+ }
+ // Trim BEFORE the path-shape check so a value like
+ // `" VAULT.md "` doesn't survive validation and fail at
+ // read time as a missing file.
+ const trimmed = v.trim();
+ // Reject absolute paths and `..` traversal at load time so
+ // the config surface fails loudly instead of silently
+ // omitting the envelope field at read time.
+ if (
+ trimmed.startsWith("/") ||
+ trimmed.startsWith("\\") ||
+ trimmed.includes("..")
+ ) {
+ throw new BrainConfigError(
+ "must be a vault-relative path without '..' segments",
+ "link_graph.vault_instruction_file",
+ source,
+ );
+ }
+ partialLg["vault_instruction_file"] = trimmed;
+ }
+ // Forward-compat: unknown sub-keys under `link_graph:` → warning.
+ for (const key of Object.keys(lgObj)) {
+ if (
+ key !== "moc_min_outbound_links" &&
+ key !== "moc_min_link_ratio" &&
+ key !== "vault_instruction_file"
+ ) {
+ warnings.push({
+ path: source ?? "<config>",
+ message: `link_graph.${key}: unknown field ignored (forward-compat)`,
+ });
+ }
+ }
+ linkGraph =
+ Object.keys(partialLg).length > 0
+ ? (partialLg as BrainLinkGraphConfig)
+ : {};
+ }
+
// Forward-compat: unknown top-level keys → warning, not error.
const known = new Set([
"schema_version",
@@ -845,6 +982,7 @@ export function validateBrainConfigDetailed(
"active",
"discipline_report",
"guardrails",
+ "link_graph",
]);
for (const key of Object.keys(obj)) {
if (!known.has(key)) {
@@ -880,6 +1018,7 @@ export function validateBrainConfigDetailed(
...(active !== undefined ? { active } : {}),
...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),
...(guardrails !== undefined ? { guardrails } : {}),
+ ...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),
};
return { config, warnings };
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 0b5d91db..c805d791 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -770,6 +770,13 @@ export interface BrainConfig {
* via `resolveGuardrails`, keeping current behaviour bit-identical.
*/
readonly guardrails?: BrainGuardrailConfig;
+ /**
+ * Optional `link_graph:` block (v0.10.17). Tunes the MOC audit
+ * thresholds and names the vault-root instruction file the
+ * `brain_context` envelope surfaces. Absent: callers fall back to
+ * `BRAIN_LINK_GRAPH_DEFAULTS` via `resolveLinkGraph`.
+ */
+ readonly link_graph?: BrainLinkGraphConfig;
}
/**
@@ -784,3 +791,39 @@ export interface ResolvedBrainGuardrailConfig {
readonly promotion_min_age_days: number;
readonly instruction_file_max_lines: number;
}
+
+/**
+ * Optional `link_graph:` block (v0.10.17). Drives the MOC audit
+ * threshold heuristics. Absent: callers fall back to
+ * `BRAIN_LINK_GRAPH_DEFAULTS` via `resolveLinkGraph`.
+ *
+ * Both knobs are purely structural - link counts and ratios over
+ * body length. No vocabulary detection of "this looks like a MOC".
+ */
+export interface BrainLinkGraphConfig {
+ /**
+ * Minimum number of outbound wikilinks a note must have for
+ * `auditMoc` to treat it as a MOC candidate. Below this the audit
+ * throws so callers don't misinterpret a thin note as a hub.
+ */
+ readonly moc_min_outbound_links?: number;
+ /**
+ * Minimum ratio of wikilink characters to non-whitespace body
+ * characters. A high-density link-list note crosses this; a prose
+ * note with a few inline references does not.
+ */
+ readonly moc_min_link_ratio?: number;
+ /**
+ * Vault-relative path of the user-authored instruction file the
+ * `brain_context` envelope optionally surfaces. Defaults to
+ * `VAULT.md`. The file is read on demand, NOT injected by a
+ * scheduler.
+ */
+ readonly vault_instruction_file?: string;
+}
+
+export interface ResolvedBrainLinkGraphConfig {
+ readonly moc_min_outbound_links: number;
+ readonly moc_min_link_ratio: number;
+ readonly vault_instruction_file: string;
+}
diff --git a/src/core/brain/vault-instruction-file.ts b/src/core/brain/vault-instruction-file.ts
new file mode 100644
index 00000000..7d6f8fc9
--- /dev/null
+++ b/src/core/brain/vault-instruction-file.ts
@@ -0,0 +1,115 @@
+/**
+ * Vault-root instruction file reader.
+ *
+ * Reads a user-authored Markdown file at the vault root (default
+ * `VAULT.md`) and returns its content plus a vault-relative path.
+ * `brain_context` surfaces this alongside the auto-generated
+ * `active.md` so agents see operator-curated session context.
+ *
+ * Distinct from `CLAUDE.md` / `AGENTS.md` / `GEMINI.md` which the
+ * v0.10.16 instruction-file-ceiling check tracks - those are
+ * runtime-injected by tools; this one is Open Second Brain's own
+ * surface.
+ */
+
+import {
+ existsSync,
+ lstatSync,
+ readFileSync,
+ realpathSync,
+ statSync,
+} from "node:fs";
+import { isAbsolute, join, relative, sep } from "node:path";
+
+import { loadBrainConfig, resolveLinkGraph } from "./policy.ts";
+
+/** Frozen result of {@link readVaultInstructionFile}. */
+export interface VaultInstructionEntry {
+ /** Vault-relative path of the file that was read. */
+ readonly path: string;
+ /** Full file content. */
+ readonly content: string;
+ /** Newline-delimited line count. Empty file = 0; trailing newline does not double-count. */
+ readonly lines: number;
+}
+
+/**
+ * Read the vault-root instruction file. Name defaults to the
+ * `link_graph.vault_instruction_file` config slot (or `VAULT.md`
+ * when not configured). Caller may override by passing `name`.
+ *
+ * Returns `null` when the file is absent. Throws on a relative
+ * path that escapes the vault or an absolute-path name (we never
+ * resolve outside the vault root).
+ */
+export function readVaultInstructionFile(
+ vault: string,
+ name?: string,
+): VaultInstructionEntry | null {
+ const resolvedName = resolveName(vault, name);
+ if (isAbsolute(resolvedName)) {
+ throw new Error(
+ `vault_instruction_file must be vault-relative, got absolute path: ${resolvedName}`,
+ );
+ }
+ if (resolvedName.length === 0) {
+ throw new Error("vault_instruction_file must not be empty");
+ }
+ if (resolvedName.split(/[\\/]/).includes("..")) {
+ throw new Error(
+ `vault_instruction_file must not contain '..' segments: ${resolvedName}`,
+ );
+ }
+ const full = join(vault, resolvedName);
+ if (!existsSync(full)) return null;
+ let content: string;
+ try {
+ // Resolve the vault root once so the boundary check is
+ // immune to the vault path itself being a symlink.
+ const vaultReal = realpathSync(vault);
+ // Reject symlinks at the candidate path - a symlink at
+ // `<vault>/VAULT.md` pointing outside the vault would
+ // otherwise bypass the relative-path guards via the
+ // symlink-following `statSync` + `readFileSync` below.
+ if (lstatSync(full).isSymbolicLink()) return null;
+ const fullReal = realpathSync(full);
+ const rel = relative(vaultReal, fullReal);
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
+ return null;
+ }
+ const st = statSync(fullReal);
+ if (!st.isFile()) return null;
+ content = readFileSync(fullReal, "utf8");
+ } catch {
+ return null;
+ }
+ const lines = countLines(content);
+ return Object.freeze({
+ path: resolvedName,
+ content,
+ lines,
+ });
+}
+
+function resolveName(vault: string, override?: string): string {
+ if (override !== undefined) return override.trim();
+ try {
+ const cfg = loadBrainConfig(vault);
+ return resolveLinkGraph(cfg).vault_instruction_file;
+ } catch {
+ return "VAULT.md";
+ }
+}
+
+function countLines(content: string): number {
+ if (content.length === 0) return 0;
+ // `\n` count == line count for both trailing-newline and
+ // no-trailing-newline files. "line\nline\n" → 2; "line\nline" → 2.
+ let count = 0;
+ for (let i = 0; i < content.length; i++) {
+ if (content.charCodeAt(i) === 0x0a) count++;
+ }
+ // Trailing chunk without `\n` still counts as a line.
+ if (content.charCodeAt(content.length - 1) !== 0x0a) count++;
+ return count;
+}
diff --git a/src/core/search/property-filter.ts b/src/core/search/property-filter.ts
new file mode 100644
index 00000000..97139050
--- /dev/null
+++ b/src/core/search/property-filter.ts
@@ -0,0 +1,74 @@
+/**
+ * Property-based post-FTS filter.
+ *
+ * Drops rows whose source frontmatter does not match a requested
+ * `key → values[]` filter map.
+ *
+ * Semantics:
+ * - Within one key: OR across requested values.
+ * - Across keys: AND.
+ * - Missing key in a row's frontmatter excludes the row.
+ * - Frontmatter array values are matched element-wise: if any
+ * element of the frontmatter array matches any requested value
+ * for that key, the row passes.
+ *
+ * The reader is dependency-injected so this helper has no I/O of
+ * its own; the search orchestrator wires the live `parseFrontmatter`
+ * reader, tests can pass an in-memory map.
+ */
+
+export type PropertyFilterMap = ReadonlyMap<string, ReadonlyArray<string>>;
+export type PropertyFrontmatterReader = (
+ path: string,
+) => Record<string, unknown> | null;
+
+export function filterByProperties<T extends { readonly path: string }>(
+ results: ReadonlyArray<T>,
+ filters: PropertyFilterMap,
+ read: PropertyFrontmatterReader,
+): ReadonlyArray<T> {
+ if (filters.size === 0) return Object.freeze([...results]) as ReadonlyArray<T>;
+
+ const out: T[] = [];
+ for (const row of results) {
+ const fm = read(row.path);
+ if (fm === null) continue;
+ if (matchesAll(fm, filters)) out.push(row);
+ }
+ return Object.freeze(out) as ReadonlyArray<T>;
+}
+
+function matchesAll(
+ fm: Record<string, unknown>,
+ filters: PropertyFilterMap,
+): boolean {
+ for (const [key, accepted] of filters) {
+ if (!Object.prototype.hasOwnProperty.call(fm, key)) return false;
+ const value = fm[key];
+ if (value === undefined || value === null) return false;
+ if (!matchesAny(value, accepted)) return false;
+ }
+ return true;
+}
+
+function matchesAny(
+ value: unknown,
+ accepted: ReadonlyArray<string>,
+): boolean {
+ const acceptedSet = new Set(accepted);
+ if (Array.isArray(value)) {
+ for (const v of value) {
+ if (typeof v !== "string") continue;
+ if (acceptedSet.has(v)) return true;
+ }
+ return false;
+ }
+ if (typeof value === "string") return acceptedSet.has(value);
+ // Numeric / boolean frontmatter scalars: compare against the string
+ // form so a filter `priority=3` works even when the parser kept the
+ // value as a number.
+ if (typeof value === "number" || typeof value === "boolean") {
+ return acceptedSet.has(String(value));
+ }
+ return false;
+}
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index 9c797104..a54df74a 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -9,8 +9,12 @@
* the store but the public surface stays uniform.
*/
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../vault.ts";
import { makeProvider } from "./embeddings/provider.ts";
import { runFtsQuery } from "./fts.ts";
+import { filterByProperties } from "./property-filter.ts";
import { rankResults } from "./ranker.ts";
import { Store } from "./store.ts";
import { SearchError } from "./types.ts";
@@ -100,6 +104,16 @@ export async function search(
const inboundLinkSources = store.inboundLinkSources(idsList);
const tagsByDoc = store.tagsByChunkDocument(idsList);
+ // When a property filter is active, overfetch the ranked
+ // candidates so the post-filter result set still has a chance
+ // of producing `limit` matching rows. Without this, the
+ // top-`limit` ranked hits can lose all their property-matching
+ // 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;
+ const rankLimit = hasPropertyFilter ? Math.max(limit * 5, 50) : limit;
+
const ranked = rankResults(
{
keyword: kwHits,
@@ -111,21 +125,53 @@ export async function search(
{
keywordWeight: opts.keywordWeight ?? config.keywordWeight,
semanticWeight: opts.semanticWeight ?? config.semanticWeight,
- limit,
+ limit: rankLimit,
semanticEnabled: policy.wantSemantic && semanticAttempted,
},
);
+ // 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);
+
return Object.freeze({
- results: Object.freeze(ranked),
+ results: Object.freeze(filtered),
warnings: Object.freeze(warnings),
- total: ranked.length,
+ total: filtered.length,
});
} finally {
await store.close();
}
}
+function applyPropertyFilter(
+ ranked: ReadonlyArray<BrainSearchResult>,
+ filters: ReadonlyMap<string, ReadonlyArray<string>>,
+ vault: string,
+): ReadonlyArray<BrainSearchResult> {
+ const cache = new Map<string, Record<string, unknown> | null>();
+ const reader = (path: string): Record<string, unknown> | null => {
+ if (cache.has(path)) return cache.get(path) ?? null;
+ try {
+ const [meta] = parseFrontmatter(join(vault, path));
+ cache.set(path, meta as Record<string, unknown>);
+ return meta as Record<string, unknown>;
+ } catch {
+ cache.set(path, null);
+ return null;
+ }
+ };
+ return filterByProperties(ranked, filters, reader);
+}
+
interface SemanticPhaseOutcome {
readonly attempted: boolean;
readonly hits: ReturnType<Store["semanticTopK"]>;
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index c761ab35..647b80ba 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -114,6 +114,14 @@ export interface SearchOptions {
readonly pathPrefix?: string;
readonly keywordWeight?: number;
readonly semanticWeight?: number;
+ /**
+ * Property filter map (v0.10.17). Each key maps to one or more
+ * accepted scalar values. Within one key the match is OR; across
+ * keys it is AND. The filter is applied as a post-rank phase
+ * against the source frontmatter of each result. Absent map = no
+ * filter (existing behaviour).
+ */
+ readonly properties?: ReadonlyMap<string, ReadonlyArray<string>>;
}
export interface SearchOutcome {
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 8cd01cd8..79c9151b 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -53,6 +53,10 @@ import {
type AppendApplyEvidenceInput,
} from "../core/brain/apply-evidence.ts";
import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
+import { findUnlinkedMentions } from "../core/brain/link-graph/unlinked-mentions.ts";
+import { buildConceptCluster } from "../core/brain/link-graph/concept-cluster.ts";
+import { auditMoc, MocAuditError } from "../core/brain/link-graph/moc-audit.ts";
+import { readVaultInstructionFile } from "../core/brain/vault-instruction-file.ts";
import { packContext } from "../core/brain/context-pack.ts";
import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";
import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
@@ -461,6 +465,17 @@ async function toolBrainContext(
}
}
+ // Optional vault-root instruction file (v0.10.17). Absent file =
+ // field omitted so hosts that strip unknown fields stay
+ // byte-identical. Read errors are silently swallowed - this is a
+ // best-effort enrichment, not a hard contract.
+ let vaultInstruction: ReturnType<typeof readVaultInstructionFile> = null;
+ try {
+ vaultInstruction = readVaultInstructionFile(ctx.vault);
+ } catch {
+ vaultInstruction = null;
+ }
+
return {
vault_path: ctx.vault,
present: true,
@@ -469,6 +484,15 @@ async function toolBrainContext(
counts,
generated_at: generatedAt,
...(error ? { error } : {}),
+ ...(vaultInstruction
+ ? {
+ vault_instruction: {
+ path: vaultInstruction.path,
+ content: vaultInstruction.content,
+ lines: vaultInstruction.lines,
+ },
+ }
+ : {}),
};
}
@@ -855,6 +879,162 @@ async function toolBrainOperatorSummary(
};
}
+// ----- brain_unlinked_mentions (v0.10.17) ----------------------------------
+
+/**
+ * Raw-text mentions of a target's title / aliases that are NOT
+ * already inside `[[...]]` wikilinks. Read-only walker over
+ * `Brain/preferences/` and `Brain/retired/`. Match boundary is
+ * Unicode-aware (`\p{L}`, `\p{N}`), language-agnostic.
+ */
+async function toolBrainUnlinkedMentions(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: id must be a non-empty string",
+ );
+ }
+ const targetId = normaliseWikilinkTarget(idRaw);
+ // Limit coercion mirrors the v0.10.16 `brain_operator_summary`
+ // precedent: accept either a number or a strict integer-literal
+ // string (`"5"` ok; `"abc"`, `"3abc"`, `"2.5"` rejected). This
+ // keeps the MCP boundary uniform across new tools.
+ const limitRaw = args["limit"];
+ let limit: number | undefined;
+ if (limitRaw !== undefined && limitRaw !== null) {
+ if (typeof limitRaw === "number") {
+ if (!Number.isInteger(limitRaw) || limitRaw < 1) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ limit = limitRaw;
+ } else if (typeof limitRaw === "string") {
+ const trimmed = limitRaw.trim();
+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ const parsed = Number.parseInt(trimmed, 10);
+ if (parsed < 1) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ limit = parsed;
+ } else {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_unlinked_mentions: limit must be a positive integer",
+ );
+ }
+ }
+ const mentions = findUnlinkedMentions(ctx.vault, targetId, {
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ return {
+ vault_path: ctx.vault,
+ target_id: targetId,
+ mentions: mentions.map((m) => ({
+ source: m.source,
+ line: m.line,
+ term: m.term,
+ context: m.contextSnippet,
+ })),
+ };
+}
+
+// ----- brain_concept_synthesis (v0.10.17) ----------------------------------
+
+/**
+ * Concept-scoped cluster envelope: target + all linkers (depth-1)
+ * plus optionally unlinked mentions. Pure assembler; no LLM call.
+ */
+async function toolBrainConceptSynthesis(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_concept_synthesis: id must be a non-empty string",
+ );
+ }
+ const includeUnlinkedRaw = args["include_unlinked"];
+ let includeUnlinked = false;
+ if (includeUnlinkedRaw !== undefined && includeUnlinkedRaw !== null) {
+ if (typeof includeUnlinkedRaw !== "boolean") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_concept_synthesis: include_unlinked must be a boolean",
+ );
+ }
+ includeUnlinked = includeUnlinkedRaw;
+ }
+ const targetId = normaliseWikilinkTarget(idRaw);
+ const cluster = buildConceptCluster(ctx.vault, targetId, {
+ includeUnlinked,
+ });
+ return {
+ vault_path: ctx.vault,
+ target_id: cluster.targetId,
+ target_title: cluster.targetTitle,
+ linkers: cluster.linkers,
+ unlinked_mentions: cluster.unlinkedMentions,
+ generated_at: cluster.generatedAt,
+ };
+}
+
+// ----- brain_moc_audit (v0.10.17) ------------------------------------------
+
+/**
+ * Per-MOC coverage audit. Classifies cluster members into
+ * `wellCovered` / `fragile` / `candidateMissing` and surfaces a
+ * `suggestedNext` candidate. MOC detection is purely structural -
+ * outbound link count + link density.
+ */
+async function toolBrainMocAudit(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_moc_audit: id must be a non-empty string",
+ );
+ }
+ const targetId = normaliseWikilinkTarget(idRaw);
+ try {
+ const report = auditMoc(ctx.vault, targetId);
+ return {
+ vault_path: ctx.vault,
+ hub_id: report.hubId,
+ outbound_count: report.outboundCount,
+ well_covered: report.wellCovered,
+ fragile: report.fragile,
+ candidate_missing: report.candidateMissing,
+ ...(report.suggestedNext
+ ? { suggested_next: report.suggestedNext }
+ : {}),
+ };
+ } catch (err) {
+ if (err instanceof MocAuditError) {
+ throw new MCPError(INVALID_PARAMS, `brain_moc_audit: ${err.message}`);
+ }
+ throw err;
+ }
+}
+
// ----- brain_context_pack (v0.10.15) ---------------------------------------
/**
@@ -1176,6 +1356,71 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainContextPack,
},
+ {
+ name: "brain_unlinked_mentions",
+ description:
+ "Raw-text mentions of a target's title / aliases that are NOT already inside `[[...]]`. Walks Brain/preferences and Brain/retired; match boundary is Unicode-aware (codepoint class), language-agnostic. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Target id (e.g. `pref-foo`, `ret-bar`). Wikilink decoration is stripped if present.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Maximum number of mentions to return. Defaults to 100; the scanner stops as soon as the cap is hit.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainUnlinkedMentions,
+ },
+ {
+ name: "brain_concept_synthesis",
+ description:
+ "Concept-scoped cluster: target note + every artifact that wikilinks to it (depth-1), optionally including unlinked-mention rows. Deterministic JSON envelope, no LLM call inside. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
+ },
+ include_unlinked: {
+ type: "boolean",
+ description:
+ "When true, also populate `unlinked_mentions` (raw-text mentions outside `[[...]]`). Defaults to false.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainConceptSynthesis,
+ },
+ {
+ name: "brain_moc_audit",
+ description:
+ "Per-MOC coverage audit. Given a hub note id, classifies its outbound cluster into well-covered / fragile / candidate-missing and surfaces a suggested-next candidate. MOC detection is purely structural (outbound link count + link density). Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainMocAudit,
+ },
{
name: "brain_operator_summary",
description:
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index ad0a8033..06cc513e 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -37,6 +37,15 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
semantic: { type: "boolean" },
keyword_only: { type: "boolean" },
path_prefix: { type: "string", maxLength: 256 },
+ properties: {
+ type: "object",
+ description:
+ "Optional frontmatter property filter (v0.10.17). Each key maps to one or more accepted scalar values; multi-value within a key is OR, multiple keys is AND.",
+ additionalProperties: {
+ type: "array",
+ items: { type: "string" },
+ },
+ },
},
required: ["query"],
additionalProperties: false,
@@ -46,6 +55,51 @@ function searchTimeoutError(ms: number): MCPError {
return new MCPError(INTERNAL_ERROR, `search timeout after ${ms}ms`);
}
+/**
+ * Validate + normalise the `properties` argument shape. Returns
+ * `undefined` when the argument is absent. Throws INVALID_PARAMS
+ * on a malformed shape so callers get a clear error rather than a
+ * silently-ignored filter.
+ */
+function parsePropertiesArgument(
+ raw: unknown,
+): ReadonlyMap<string, ReadonlyArray<string>> | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "object" || Array.isArray(raw)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "argument 'properties' must be an object mapping key → array of strings",
+ );
+ }
+ const map = new Map<string, ReadonlyArray<string>>();
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
+ if (!Array.isArray(v)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'properties.${k}' must be an array of strings`,
+ );
+ }
+ const accepted: string[] = [];
+ for (const item of v) {
+ if (typeof item !== "string") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'properties.${k}' must contain only strings`,
+ );
+ }
+ accepted.push(item);
+ }
+ if (accepted.length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'properties.${k}' must not be empty`,
+ );
+ }
+ map.set(k, Object.freeze(accepted));
+ }
+ return map;
+}
+
function truncateContent(c: string, max: number): string {
if (c.length <= max) return c;
return c.slice(0, max - 1) + "…";
@@ -101,6 +155,7 @@ async function toolBrainSearch(
const semantic = coerceBoolOptional(args, "semantic");
const keywordOnly = coerceBoolOptional(args, "keyword_only") ?? false;
const pathPrefix = coerceStringOptional(args, "path_prefix", 256);
+ const properties = parsePropertiesArgument(args["properties"]);
const config = resolveSearchConfig({
vault: ctx.vault,
@@ -116,6 +171,7 @@ async function toolBrainSearch(
semantic: semantic ?? null,
keywordOnly,
pathPrefix,
+ ...(properties !== undefined ? { properties } : {}),
}),
SEARCH_TIMEOUT_MS,
searchTimeoutError,
diff --git a/tests/cli/brain-moc-audit-cli.test.ts b/tests/cli/brain-moc-audit-cli.test.ts
new file mode 100644
index 00000000..95b01e35
--- /dev/null
+++ b/tests/cli/brain-moc-audit-cli.test.ts
@@ -0,0 +1,93 @@
+/**
+ * CLI smoke test for `o2b brain moc-audit` (v0.10.17).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+function writePref(
+ slug: string,
+ frontmatter: Record<string, string>,
+ body = "",
+): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-moc-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+
+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-moc-cli-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("o2b brain moc-audit", () => {
+ test("missing id arg exits with usage error", async () => {
+ const r = await runCli(["brain", "moc-audit"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("hub note id");
+ });
+
+ test("non-MOC hub is rejected with a usage error", async () => {
+ writePref(
+ "pref-thin",
+ { kind: "preference", topic: "t", status: "confirmed", principle: "p" },
+ "Just [[pref-a]] and [[pref-b]] here.",
+ );
+ const r = await runCli(["brain", "moc-audit", "pref-thin"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("not a MOC");
+ });
+
+ test("MOC hub: --json prints bucketed envelope", async () => {
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]] [[pref-missing]]",
+ );
+ const r = await runCli(["brain", "moc-audit", "pref-hub", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ hub_id: string;
+ outbound_count: number;
+ candidate_missing: Array<{ id: string }>;
+ };
+ expect(payload.hub_id).toBe("pref-hub");
+ expect(payload.outbound_count).toBe(6);
+ expect(payload.candidate_missing.some((c) => c.id === "pref-missing")).toBe(true);
+ });
+});
diff --git a/tests/cli/brain-synthesise-cli.test.ts b/tests/cli/brain-synthesise-cli.test.ts
new file mode 100644
index 00000000..fb9f58ba
--- /dev/null
+++ b/tests/cli/brain-synthesise-cli.test.ts
@@ -0,0 +1,118 @@
+/**
+ * CLI smoke test for `o2b brain synthesise` (v0.10.17).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+function writePref(
+ slug: string,
+ frontmatter: Record<string, string>,
+ body = "",
+): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-synth-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+
+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-synth-cli-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("o2b brain synthesise", () => {
+ test("missing id arg exits with usage error", async () => {
+ const r = await runCli(["brain", "synthesise"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("target id");
+ });
+
+ test("--json prints envelope with target + linkers", async () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "Refers to [[pref-tgt]] in body.",
+ );
+ const r = await runCli(["brain", "synthesise", "pref-tgt", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ target_id: string;
+ target_title: string;
+ linkers: Array<{ source: string }>;
+ };
+ expect(payload.target_id).toBe("pref-tgt");
+ expect(payload.target_title).toBe("Subject");
+ expect(payload.linkers.length).toBe(1);
+ expect(payload.linkers[0]!.source).toBe("pref-linker");
+ });
+
+ test("--include-unlinked also populates unlinked_mentions", async () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ });
+ writePref(
+ "pref-prose",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "I mention Subject Line in prose.",
+ );
+ const r = await runCli(
+ ["brain", "synthesise", "pref-tgt", "--include-unlinked", "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ unlinked_mentions: Array<{ source: string }>;
+ };
+ expect(payload.unlinked_mentions.length).toBe(1);
+ expect(payload.unlinked_mentions[0]!.source).toBe("pref-prose");
+ });
+});
diff --git a/tests/cli/brain-unlinked-cli.test.ts b/tests/cli/brain-unlinked-cli.test.ts
new file mode 100644
index 00000000..877e2475
--- /dev/null
+++ b/tests/cli/brain-unlinked-cli.test.ts
@@ -0,0 +1,110 @@
+/**
+ * CLI smoke test for `o2b brain unlinked` (v0.10.17).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+function writePref(
+ slug: string,
+ frontmatter: Record<string, string>,
+ body = "",
+): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-unlinked-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+
+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-unlinked-cli-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("o2b brain unlinked", () => {
+ test("missing id arg exits with usage error", async () => {
+ const r = await runCli(["brain", "unlinked"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("target id");
+ });
+
+ test("clean vault returns zero count", async () => {
+ const r = await runCli(["brain", "unlinked", "pref-missing"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("Unlinked mentions of pref-missing: 0");
+ });
+
+ test("--json prints structured envelope with count + mentions", async () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "Subject Line appears here.",
+ );
+ const r = await runCli(["brain", "unlinked", "pref-tgt", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ id: string;
+ count: number;
+ mentions: Array<{ source: string; line: number; term: string; context: string }>;
+ };
+ expect(payload.id).toBe("pref-tgt");
+ expect(payload.count).toBe(1);
+ expect(payload.mentions[0]!.source).toBe("pref-linker");
+ expect(payload.mentions[0]!.term).toBe("Subject Line");
+ });
+
+ test("rejects --limit=0", async () => {
+ const r = await runCli(["brain", "unlinked", "pref-x", "--limit", "0"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(1);
+ });
+
+ test("rejects --limit=abc", async () => {
+ const r = await runCli(["brain", "unlinked", "pref-x", "--limit", "abc"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(1);
+ });
+});
diff --git a/tests/cli/search-property-cli.test.ts b/tests/cli/search-property-cli.test.ts
new file mode 100644
index 00000000..8beeded9
--- /dev/null
+++ b/tests/cli/search-property-cli.test.ts
@@ -0,0 +1,68 @@
+/**
+ * CLI smoke test for `o2b search --property KEY=VALUE`.
+ *
+ * The full search pipeline needs an indexed vault to return real
+ * results; this test focuses on the property-flag parsing surface
+ * (rejection of malformed values) so it stays fast and does not
+ * require sqlite-vec.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-search-property-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+
+ configHome = mkdtempSync(join(tmpdir(), "o2b-search-property-cli-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("o2b search --property", () => {
+ test("malformed --property without '=' is rejected", async () => {
+ const r = await runCli(
+ ["search", "foo", "--property", "no-equals-here"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("--property must be KEY=VALUE");
+ });
+
+ test("--property KEY= rejects empty value", async () => {
+ const r = await runCli(
+ ["search", "foo", "--property", "type="],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("KEY=VALUE");
+ });
+
+ test("--property =VALUE rejects empty key", async () => {
+ const r = await runCli(
+ ["search", "foo", "--property", "=decision"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("KEY=VALUE");
+ });
+});
diff --git a/tests/core/brain/backlinks-anchor-alias.test.ts b/tests/core/brain/backlinks-anchor-alias.test.ts
new file mode 100644
index 00000000..b9482fe0
--- /dev/null
+++ b/tests/core/brain/backlinks-anchor-alias.test.ts
@@ -0,0 +1,240 @@
+/**
+ * v0.10.17 coverage for the anchor / block / alias-source slots on
+ * `BacklinkRef`.
+ *
+ * First block locks the additive shape so legacy consumers reading
+ * only the four pre-v0.10.17 fields keep compiling. The remaining
+ * blocks exercise `buildBacklinkIndex` after Unit 3 wires the rich
+ * parse + alias index into the collectors.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ buildBacklinkIndex,
+ type BacklinkRef,
+} from "../../../src/core/brain/backlinks.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+
+describe("BacklinkRef atom shape (additive)", () => {
+ test("accepts ref with only legacy fields populated", () => {
+ const legacy: BacklinkRef = {
+ source: "pref-foo",
+ sourceKind: "preference",
+ field: "evidenced_by",
+ };
+ expect(legacy.source).toBe("pref-foo");
+ expect(legacy.targetAnchor).toBeUndefined();
+ expect(legacy.targetBlock).toBeUndefined();
+ expect(legacy.aliasSource).toBeUndefined();
+ });
+
+ test("accepts ref with anchor populated", () => {
+ const ref: BacklinkRef = {
+ source: "pref-foo",
+ sourceKind: "preference",
+ field: "body",
+ targetAnchor: "Section 1",
+ };
+ expect(ref.targetAnchor).toBe("Section 1");
+ });
+
+ test("accepts ref with block populated", () => {
+ const ref: BacklinkRef = {
+ source: "pref-foo",
+ sourceKind: "preference",
+ field: "body",
+ targetBlock: "abc123",
+ };
+ expect(ref.targetBlock).toBe("abc123");
+ });
+
+ test("accepts ref with alias-source populated", () => {
+ const ref: BacklinkRef = {
+ source: "pref-foo",
+ sourceKind: "preference",
+ field: "body",
+ aliasSource: "downstream effects",
+ };
+ expect(ref.aliasSource).toBe("downstream effects");
+ });
+});
+
+// ---------------------------------------------------------------------
+// buildBacklinkIndex populated-behaviour suite (Unit 3 wiring).
+// ---------------------------------------------------------------------
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-backlinks-anchor-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("buildBacklinkIndex - anchor / block populated from body wikilinks", () => {
+ test("heading anchor lands on the ref", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-foo.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "status: confirmed",
+ "principle: example",
+ "---",
+ "",
+ "References [[bar#Section A]] in the body.",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("bar") ?? [];
+ expect(refs.length).toBe(1);
+ expect(refs[0]?.targetAnchor).toBe("Section A");
+ expect(refs[0]?.targetBlock).toBeUndefined();
+ });
+
+ test("block id lands on the ref", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-foo.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "status: confirmed",
+ "principle: example",
+ "---",
+ "",
+ "Refers to [[bar#^block-id-x]] specifically.",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("bar") ?? [];
+ expect(refs.length).toBe(1);
+ expect(refs[0]?.targetBlock).toBe("block-id-x");
+ expect(refs[0]?.targetAnchor).toBeUndefined();
+ });
+
+ test("two refs to different anchors of the same target keep separate entries", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-foo.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "status: confirmed",
+ "principle: example",
+ "---",
+ "",
+ "First [[bar#Alpha]] then [[bar#Beta]].",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("bar") ?? [];
+ expect(refs.length).toBe(2);
+ const anchors = refs.map((r) => r.targetAnchor).sort();
+ expect(anchors).toEqual(["Alpha", "Beta"]);
+ });
+});
+
+describe("buildBacklinkIndex - alias resolution", () => {
+ test("link via frontmatter alias resolves to canonical id with aliasSource recorded", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-second-order.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: second-order",
+ "status: confirmed",
+ "principle: thinking ahead",
+ "aliases: [downstream]",
+ "---",
+ "",
+ "Body.",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-linker.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: linker",
+ "status: confirmed",
+ "principle: example",
+ "---",
+ "",
+ "I rely on [[downstream]] reasoning.",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("pref-second-order") ?? [];
+ expect(refs.length).toBe(1);
+ expect(refs[0]?.source).toBe("pref-linker");
+ expect(refs[0]?.aliasSource).toBe("downstream");
+ });
+
+ test("link by canonical id does not populate aliasSource", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-canonical.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: c",
+ "status: confirmed",
+ "principle: x",
+ "aliases: [other-name]",
+ "---",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-linker.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: l",
+ "status: confirmed",
+ "principle: y",
+ "---",
+ "",
+ "Links to [[pref-canonical]].",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("pref-canonical") ?? [];
+ expect(refs.length).toBe(1);
+ expect(refs[0]?.aliasSource).toBeUndefined();
+ });
+
+ test("legacy callers reading only legacy fields are unaffected", () => {
+ // Smoke check: existing collectors still produce refs with
+ // populated `source`, `sourceKind`, `field`. Used to be the
+ // entire BacklinkRef contract; v0.10.17 only added optional
+ // fields so this destructure must keep working.
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-a.md"),
+ [
+ "---",
+ "kind: preference",
+ "topic: a",
+ "status: confirmed",
+ "principle: x",
+ "---",
+ "",
+ "Mentions [[b]] in body.",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("b") ?? [];
+ expect(refs.length).toBe(1);
+ const { source, sourceKind, field } = refs[0]!;
+ expect(source).toBe("pref-a");
+ expect(sourceKind).toBe("preference");
+ expect(field).toBe("body");
+ });
+});
diff --git a/tests/core/brain/link-graph/alias-index.test.ts b/tests/core/brain/link-graph/alias-index.test.ts
new file mode 100644
index 00000000..d6b7798f
--- /dev/null
+++ b/tests/core/brain/link-graph/alias-index.test.ts
@@ -0,0 +1,318 @@
+/**
+ * Unit tests for `buildAliasIndex`. The helper walks Brain
+ * preferences + retired artifacts, reads their frontmatter
+ * `aliases:` arrays, and returns a frozen Map keyed by NFC-normalised
+ * lowercase alias text, valued at the canonical artifact id.
+ *
+ * Collisions (two artifacts claiming the same alias) resolve
+ * first-wins by sorted canonical id - deterministic without an
+ * extra timestamp lookup. Empty / non-array aliases are skipped.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildAliasIndex } from "../../../../src/core/brain/link-graph/alias-index.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+
+let vault: string;
+
+function writePref(slug: string, body: string): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `${slug}.md`),
+ `${body}\n`,
+ );
+}
+
+function writeRetired(slug: string, body: string): void {
+ writeFileSync(
+ join(vault, "Brain", "retired", `${slug}.md`),
+ `${body}\n`,
+ );
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-alias-index-"));
+ bootstrapBrain(vault);
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("buildAliasIndex - happy path", () => {
+ test("registers single alias", () => {
+ writePref(
+ "pref-second-order",
+ [
+ "---",
+ "kind: preference",
+ "topic: second-order",
+ "status: confirmed",
+ "principle: thinking ahead",
+ "aliases: [downstream]",
+ "---",
+ "",
+ "Body.",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("downstream")).toBe("pref-second-order");
+ });
+
+ test("registers multiple aliases per artifact", () => {
+ writePref(
+ "pref-second-order",
+ [
+ "---",
+ "kind: preference",
+ "topic: second-order",
+ "status: confirmed",
+ "principle: thinking ahead",
+ "aliases: [downstream, knock-on, second-order-effects]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("downstream")).toBe("pref-second-order");
+ expect(idx.get("knock-on")).toBe("pref-second-order");
+ expect(idx.get("second-order-effects")).toBe("pref-second-order");
+ });
+
+ test("collects aliases from retired artifacts", () => {
+ writeRetired(
+ "ret-old",
+ [
+ "---",
+ "kind: retired",
+ "topic: old",
+ "principle: superseded",
+ "aliases: [legacy-rule]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("legacy-rule")).toBe("ret-old");
+ });
+});
+
+describe("buildAliasIndex - normalisation", () => {
+ test("case-insensitive lookup", () => {
+ writePref(
+ "pref-foo",
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "status: confirmed",
+ "principle: bar",
+ "aliases: [Downstream]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("downstream")).toBe("pref-foo");
+ // Original casing also accessible via the lower-case key only;
+ // callers normalise the lookup key themselves.
+ expect(idx.get("Downstream")).toBeUndefined();
+ });
+
+ test("NFC normalisation collapses pre-composed and decomposed forms", () => {
+ // "café" composed (U+00E9) vs decomposed (U+0065 U+0301).
+ const composed = "café";
+ const decomposed = "café";
+ writePref(
+ "pref-cafe",
+ [
+ "---",
+ "kind: preference",
+ "topic: cafe",
+ "status: confirmed",
+ "principle: x",
+ `aliases: [${decomposed}]`,
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ // Lookup with composed form should hit (NFC normalises both
+ // sides).
+ expect(idx.get(composed.normalize("NFC").toLowerCase())).toBe(
+ "pref-cafe",
+ );
+ });
+
+ test("trims whitespace from alias entries", () => {
+ writePref(
+ "pref-trim",
+ [
+ "---",
+ "kind: preference",
+ "topic: trim",
+ "status: confirmed",
+ "principle: x",
+ "aliases: [ spaced , another ]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("spaced")).toBe("pref-trim");
+ expect(idx.get("another")).toBe("pref-trim");
+ });
+
+ test("skips empty alias strings", () => {
+ writePref(
+ "pref-empty",
+ [
+ "---",
+ "kind: preference",
+ "topic: empty",
+ "status: confirmed",
+ "principle: x",
+ "aliases: [valid, '', ok]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("valid")).toBe("pref-empty");
+ expect(idx.get("ok")).toBe("pref-empty");
+ expect(idx.get("")).toBeUndefined();
+ });
+});
+
+describe("buildAliasIndex - collision handling", () => {
+ test("first-wins by sorted canonical id", () => {
+ writePref(
+ "pref-aaa",
+ [
+ "---",
+ "kind: preference",
+ "topic: a",
+ "status: confirmed",
+ "principle: x",
+ "aliases: [shared]",
+ "---",
+ ].join("\n"),
+ );
+ writePref(
+ "pref-bbb",
+ [
+ "---",
+ "kind: preference",
+ "topic: b",
+ "status: confirmed",
+ "principle: x",
+ "aliases: [shared]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("shared")).toBe("pref-aaa");
+ });
+
+ test("alias that shadows an existing canonical id is silently dropped (no hijack)", () => {
+ // pref-foo declares alias "pref-bar"; pref-bar exists on disk.
+ // Without the on-disk-collision guard, [[pref-bar]] backlinks
+ // would re-route to pref-foo and the real pref-bar would lose
+ // every inbound reference. The alias-index drops the offending
+ // entry so the canonical artifact keeps owning its id.
+ writePref(
+ "pref-foo",
+ [
+ "---",
+ "kind: preference",
+ "topic: foo",
+ "status: confirmed",
+ "principle: x",
+ "aliases: [pref-bar]",
+ "---",
+ ].join("\n"),
+ );
+ writePref(
+ "pref-bar",
+ [
+ "---",
+ "kind: preference",
+ "topic: bar",
+ "status: confirmed",
+ "principle: y",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("pref-bar")).toBeUndefined();
+ });
+});
+
+describe("buildAliasIndex - degenerate inputs", () => {
+ test("empty vault returns empty frozen map", () => {
+ const idx = buildAliasIndex(vault);
+ expect(idx.size).toBe(0);
+ expect(Object.isFrozen(idx)).toBe(true);
+ });
+
+ test("artifact without aliases is skipped", () => {
+ writePref(
+ "pref-noalias",
+ [
+ "---",
+ "kind: preference",
+ "topic: x",
+ "status: confirmed",
+ "principle: y",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.size).toBe(0);
+ });
+
+ test("non-array aliases value is skipped without throwing", () => {
+ writePref(
+ "pref-scalar",
+ [
+ "---",
+ "kind: preference",
+ "topic: x",
+ "status: confirmed",
+ "principle: y",
+ "aliases: not-an-array",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.size).toBe(0);
+ });
+
+ test("malformed frontmatter row is silently skipped", () => {
+ writePref(
+ "pref-bad",
+ [
+ "no frontmatter here",
+ "just body content",
+ ].join("\n"),
+ );
+ writePref(
+ "pref-good",
+ [
+ "---",
+ "kind: preference",
+ "topic: g",
+ "status: confirmed",
+ "principle: y",
+ "aliases: [ok]",
+ "---",
+ ].join("\n"),
+ );
+ const idx = buildAliasIndex(vault);
+ expect(idx.get("ok")).toBe("pref-good");
+ });
+});
diff --git a/tests/core/brain/link-graph/concept-cluster.test.ts b/tests/core/brain/link-graph/concept-cluster.test.ts
new file mode 100644
index 00000000..82ac5cb0
--- /dev/null
+++ b/tests/core/brain/link-graph/concept-cluster.test.ts
@@ -0,0 +1,217 @@
+/**
+ * Unit tests for `buildConceptCluster`. The helper assembles a
+ * deterministic, LLM-free envelope describing a target note plus
+ * every artifact that wikilinks to it. Optionally includes
+ * unlinked-mention rows for downstream consumers that want richer
+ * coverage.
+ *
+ * The output is read-only and frozen.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildConceptCluster } from "../../../../src/core/brain/link-graph/concept-cluster.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+
+let vault: string;
+
+function writePref(slug: string, fm: Record<string, string>, body = ""): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(fm)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-concept-cluster-"));
+ bootstrapBrain(vault);
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("buildConceptCluster - shape", () => {
+ test("clean vault returns envelope with empty linkers + frozen", () => {
+ const r = buildConceptCluster(vault, "pref-missing");
+ expect(r.targetId).toBe("pref-missing");
+ expect(r.linkers).toEqual([]);
+ expect(r.unlinkedMentions).toEqual([]);
+ expect(Object.isFrozen(r)).toBe(true);
+ expect(Object.isFrozen(r.linkers)).toBe(true);
+ expect(Object.isFrozen(r.unlinkedMentions)).toBe(true);
+ });
+
+ test("resolves title from frontmatter when present", () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ });
+ const r = buildConceptCluster(vault, "pref-tgt");
+ expect(r.targetTitle).toBe("Subject Line");
+ });
+
+ test("falls back to id when no title is declared", () => {
+ writePref("pref-titleless", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ });
+ const r = buildConceptCluster(vault, "pref-titleless");
+ expect(r.targetTitle).toBe("pref-titleless");
+ });
+});
+
+describe("buildConceptCluster - linkers", () => {
+ test("collects body wikilink linker", () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "I reference [[pref-tgt]] in this body.",
+ );
+ const r = buildConceptCluster(vault, "pref-tgt");
+ expect(r.linkers.length).toBe(1);
+ expect(r.linkers[0]?.source).toBe("pref-linker");
+ expect(r.linkers[0]?.sourceKind).toBe("preference");
+ expect(r.linkers[0]?.field).toBe("body");
+ });
+
+ test("collects multiple linkers from different fields", () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ });
+ writePref("pref-a", {
+ kind: "preference",
+ topic: "a",
+ status: "confirmed",
+ principle: "p",
+ evidenced_by: "[pref-tgt]",
+ });
+ writePref(
+ "pref-b",
+ {
+ kind: "preference",
+ topic: "b",
+ status: "confirmed",
+ principle: "p",
+ },
+ "Mentions [[pref-tgt]] in body.",
+ );
+ const r = buildConceptCluster(vault, "pref-tgt");
+ expect(r.linkers.length).toBe(2);
+ const sources = r.linkers.map((l: { source: string }) => l.source).sort();
+ expect(sources).toEqual(["pref-a", "pref-b"]);
+ });
+
+ test("preserves anchor info on linkers (Unit 3 enrichment)", () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "See [[pref-tgt#Important]] for details.",
+ );
+ const r = buildConceptCluster(vault, "pref-tgt");
+ expect(r.linkers[0]?.targetAnchor).toBe("Important");
+ });
+});
+
+describe("buildConceptCluster - unlinked mentions toggle", () => {
+ test("default does NOT include unlinked mentions", () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "I mention Subject Line in prose.",
+ );
+ const r = buildConceptCluster(vault, "pref-tgt");
+ expect(r.unlinkedMentions.length).toBe(0);
+ });
+
+ test("includeUnlinked=true populates unlinked mentions", () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "I mention Subject Line in prose.",
+ );
+ const r = buildConceptCluster(vault, "pref-tgt", { includeUnlinked: true });
+ expect(r.unlinkedMentions.length).toBe(1);
+ expect(r.unlinkedMentions[0]?.source).toBe("pref-linker");
+ });
+});
+
+describe("buildConceptCluster - determinism", () => {
+ test("does NOT make an LLM call (helper is pure)", () => {
+ // Smoke: helper runs with no network access. If it ever tried to
+ // call an LLM the test sandbox would surface it. No-op assertion
+ // - the test passes iff the helper completes without throwing.
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ });
+ const r = buildConceptCluster(vault, "pref-tgt");
+ expect(r).toBeDefined();
+ });
+});
diff --git a/tests/core/brain/link-graph/moc-audit.test.ts b/tests/core/brain/link-graph/moc-audit.test.ts
new file mode 100644
index 00000000..59a68ee2
--- /dev/null
+++ b/tests/core/brain/link-graph/moc-audit.test.ts
@@ -0,0 +1,172 @@
+/**
+ * Unit tests for `auditMoc`. Given a hub note id whose outbound
+ * wikilinks form a cluster, classify each member into well-covered /
+ * fragile / candidate-missing / suggested-next buckets.
+ *
+ * The MOC heuristic is purely structural: outbound link count + body
+ * link-density must cross configured thresholds. No vocabulary
+ * detection of "this looks like a MOC because the title says so".
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { auditMoc, MocAuditError } from "../../../../src/core/brain/link-graph/moc-audit.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+
+let vault: string;
+
+function writePref(slug: string, fm: Record<string, string>, body = ""): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(fm)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-moc-audit-"));
+ bootstrapBrain(vault);
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("auditMoc - MOC detection threshold", () => {
+ test("note with too few outbound links is rejected as non-MOC", () => {
+ writePref(
+ "pref-not-moc",
+ {
+ kind: "preference",
+ topic: "n",
+ status: "confirmed",
+ principle: "p",
+ },
+ "Just [[pref-a]] and [[pref-b]] here.",
+ );
+ expect(() => auditMoc(vault, "pref-not-moc")).toThrow(MocAuditError);
+ });
+
+ test("note with high outbound link count + link density qualifies", () => {
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref("pref-f", { kind: "preference", topic: "f", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ {
+ kind: "preference",
+ topic: "hub",
+ status: "confirmed",
+ principle: "p",
+ },
+ "[[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]] [[pref-f]]",
+ );
+ const r = auditMoc(vault, "pref-hub");
+ expect(r.hubId).toBe("pref-hub");
+ expect(r.outboundCount).toBe(6);
+ });
+});
+
+describe("auditMoc - bucket classification", () => {
+ test("well-covered: cluster member with multiple backlinks + body above floor", () => {
+ // Hub references pref-popular. Two other prefs also reference pref-popular.
+ // Body of pref-popular is long.
+ const longBody = "Long body content. ".repeat(20);
+ writePref("pref-popular", { kind: "preference", topic: "p", status: "confirmed", principle: "p" }, longBody);
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" }, "Refers to [[pref-popular]].");
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" }, "Also [[pref-popular]].");
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-popular]] [[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]]",
+ );
+ const r = auditMoc(vault, "pref-hub");
+ const wellNames = r.wellCovered.map((c) => c.id);
+ expect(wellNames).toContain("pref-popular");
+ });
+
+ test("fragile: cluster member with only one backlink and short body", () => {
+ writePref("pref-thin", { kind: "preference", topic: "t", status: "confirmed", principle: "p" }, "short");
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-thin]] [[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]]",
+ );
+ const r = auditMoc(vault, "pref-hub");
+ const fragileNames = r.fragile.map((c) => c.id);
+ expect(fragileNames).toContain("pref-thin");
+ });
+
+ test("candidate-missing: hub references a target with no on-disk artifact", () => {
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]] [[pref-missing]]",
+ );
+ const r = auditMoc(vault, "pref-hub");
+ const missingNames = r.candidateMissing.map((c) => c.id);
+ expect(missingNames).toContain("pref-missing");
+ });
+
+ test("suggested-next: highest-leverage candidate-missing (most mentions across cluster)", () => {
+ // pref-popular-missing referenced from hub + 2 cluster members.
+ // pref-rare-missing referenced from hub only.
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" }, "see [[pref-popular-missing]]");
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" }, "again [[pref-popular-missing]]");
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]] [[pref-popular-missing]] [[pref-rare-missing]]",
+ );
+ const r = auditMoc(vault, "pref-hub");
+ expect(r.suggestedNext?.id).toBe("pref-popular-missing");
+ });
+});
+
+describe("auditMoc - shape", () => {
+ test("returned object is frozen", () => {
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]] [[pref-a]]",
+ );
+ const r = auditMoc(vault, "pref-hub");
+ expect(Object.isFrozen(r)).toBe(true);
+ expect(Object.isFrozen(r.wellCovered)).toBe(true);
+ expect(Object.isFrozen(r.fragile)).toBe(true);
+ expect(Object.isFrozen(r.candidateMissing)).toBe(true);
+ });
+});
diff --git a/tests/core/brain/link-graph/parse-wikilink.test.ts b/tests/core/brain/link-graph/parse-wikilink.test.ts
new file mode 100644
index 00000000..743a9342
--- /dev/null
+++ b/tests/core/brain/link-graph/parse-wikilink.test.ts
@@ -0,0 +1,111 @@
+/**
+ * Unit tests for `parseWikilinkRich` - the rich-parse helper that
+ * returns `{target, anchor, block, alias}` from any Obsidian wikilink
+ * shape. The existing `parseWikilink` / `normaliseWikilinkTarget`
+ * (string-returning) helpers keep their contracts; this test set
+ * locks in the additive richer surface introduced by v0.10.17.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { parseWikilinkRich } from "../../../../src/core/brain/link-graph/parse-wikilink.ts";
+
+describe("parseWikilinkRich - bare target", () => {
+ test("bare target inside brackets", () => {
+ const r = parseWikilinkRich("[[Note]]");
+ expect(r.target).toBe("Note");
+ expect(r.anchor).toBeUndefined();
+ expect(r.block).toBeUndefined();
+ expect(r.alias).toBeUndefined();
+ });
+
+ test("bare target without brackets", () => {
+ const r = parseWikilinkRich("Note");
+ expect(r.target).toBe("Note");
+ });
+
+ test("trailing .md extension stripped", () => {
+ const r = parseWikilinkRich("[[Note.md]]");
+ expect(r.target).toBe("Note");
+ });
+
+ test("folder prefix collapses to basename", () => {
+ const r = parseWikilinkRich("[[Folder/Note]]");
+ expect(r.target).toBe("Note");
+ });
+
+ test("empty input returns empty target", () => {
+ const r = parseWikilinkRich("");
+ expect(r.target).toBe("");
+ });
+});
+
+describe("parseWikilinkRich - heading anchor", () => {
+ test("simple heading", () => {
+ const r = parseWikilinkRich("[[Note#Heading]]");
+ expect(r.target).toBe("Note");
+ expect(r.anchor).toBe("Heading");
+ expect(r.block).toBeUndefined();
+ });
+
+ test("heading with spaces", () => {
+ const r = parseWikilinkRich("[[Note#Section Two]]");
+ expect(r.target).toBe("Note");
+ expect(r.anchor).toBe("Section Two");
+ });
+
+ test("heading with non-ASCII characters", () => {
+ const r = parseWikilinkRich("[[Note#Раздел]]");
+ expect(r.target).toBe("Note");
+ expect(r.anchor).toBe("Раздел");
+ });
+
+ test("anchor on folder-prefixed target", () => {
+ const r = parseWikilinkRich("[[Folder/Note#Heading]]");
+ expect(r.target).toBe("Note");
+ expect(r.anchor).toBe("Heading");
+ });
+});
+
+describe("parseWikilinkRich - block anchor", () => {
+ test("block id detected via caret sigil", () => {
+ const r = parseWikilinkRich("[[Note#^abc123]]");
+ expect(r.target).toBe("Note");
+ expect(r.block).toBe("abc123");
+ expect(r.anchor).toBeUndefined();
+ });
+
+ test("block id with hyphens preserved", () => {
+ const r = parseWikilinkRich("[[Note#^block-id-x]]");
+ expect(r.block).toBe("block-id-x");
+ });
+});
+
+describe("parseWikilinkRich - alias", () => {
+ test("alias preserved separately from target", () => {
+ const r = parseWikilinkRich("[[Note|display name]]");
+ expect(r.target).toBe("Note");
+ expect(r.alias).toBe("display name");
+ });
+
+ test("alias plus anchor", () => {
+ const r = parseWikilinkRich("[[Note#Heading|display]]");
+ expect(r.target).toBe("Note");
+ expect(r.anchor).toBe("Heading");
+ expect(r.alias).toBe("display");
+ });
+
+ test("alias plus block id", () => {
+ const r = parseWikilinkRich("[[Note#^abc|display]]");
+ expect(r.target).toBe("Note");
+ expect(r.block).toBe("abc");
+ expect(r.alias).toBe("display");
+ });
+});
+
+describe("parseWikilinkRich - immutability", () => {
+ test("returned object is frozen", () => {
+ const r = parseWikilinkRich("[[Note#H|alias]]");
+ expect(Object.isFrozen(r)).toBe(true);
+ });
+});
diff --git a/tests/core/brain/link-graph/unlinked-mentions.test.ts b/tests/core/brain/link-graph/unlinked-mentions.test.ts
new file mode 100644
index 00000000..7e40e842
--- /dev/null
+++ b/tests/core/brain/link-graph/unlinked-mentions.test.ts
@@ -0,0 +1,296 @@
+/**
+ * Unit tests for `findUnlinkedMentions`. The scanner finds raw-text
+ * occurrences of a target's title (and any frontmatter alias)
+ * outside of `[[...]]` brackets and outside fenced/inline code
+ * spans. The matcher is language-agnostic - it uses Unicode
+ * codepoint classes (`\p{L}`, `\p{N}`) for word boundaries, never a
+ * vocabulary list.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { findUnlinkedMentions } from "../../../../src/core/brain/link-graph/unlinked-mentions.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-unlinked-"));
+ bootstrapBrain(vault);
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, frontmatter: Record<string, string>, body = ""): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+describe("findUnlinkedMentions - title matching", () => {
+ test("plain title hit yields one mention", () => {
+ writePref("pref-second-order", {
+ kind: "preference",
+ topic: "second-order",
+ status: "confirmed",
+ principle: "thinking ahead",
+ title: "Second-Order Thinking",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "linker",
+ status: "confirmed",
+ principle: "example",
+ },
+ "I value Second-Order Thinking for decisions.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-second-order");
+ expect(out.length).toBe(1);
+ expect(out[0]?.source).toBe("pref-linker");
+ expect(out[0]?.term).toBe("Second-Order Thinking");
+ });
+
+ test("bracketed link does NOT produce a mention", () => {
+ writePref("pref-second-order", {
+ kind: "preference",
+ topic: "second-order",
+ status: "confirmed",
+ principle: "thinking ahead",
+ title: "Second-Order Thinking",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "linker",
+ status: "confirmed",
+ principle: "example",
+ },
+ "I use [[pref-second-order|Second-Order Thinking]] for decisions.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-second-order");
+ expect(out.length).toBe(0);
+ });
+
+ test("title falls back to id when frontmatter has no title", () => {
+ writePref("pref-canonical-id-only", {
+ kind: "preference",
+ topic: "x",
+ status: "confirmed",
+ principle: "x",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "y",
+ },
+ "I rely on pref-canonical-id-only every day.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-canonical-id-only");
+ expect(out.length).toBe(1);
+ });
+});
+
+describe("findUnlinkedMentions - alias expansion", () => {
+ test("alias mention is detected via frontmatter aliases", () => {
+ writePref("pref-second-order", {
+ kind: "preference",
+ topic: "second-order",
+ status: "confirmed",
+ principle: "x",
+ title: "Second-Order Thinking",
+ aliases: "[downstream, knock-on]",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "linker",
+ status: "confirmed",
+ principle: "x",
+ },
+ "Always consider downstream effects of a decision.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-second-order");
+ expect(out.length).toBe(1);
+ expect(out[0]?.term).toBe("downstream");
+ });
+});
+
+describe("findUnlinkedMentions - word-boundary discipline", () => {
+ test("substring inside another word is NOT a mention", () => {
+ // Target alias `cat`. Sibling note has `catastrophe`. Without
+ // word boundaries this would false-positive.
+ writePref("pref-cat", {
+ kind: "preference",
+ topic: "cat",
+ status: "confirmed",
+ principle: "x",
+ title: "Catalog",
+ aliases: "[cat]",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "linker",
+ status: "confirmed",
+ principle: "x",
+ },
+ "The catastrophe was avoided.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-cat");
+ expect(out.length).toBe(0);
+ });
+
+ test("non-ASCII title boundary is respected", () => {
+ writePref("pref-ru", {
+ kind: "preference",
+ topic: "ru",
+ status: "confirmed",
+ principle: "x",
+ title: "Раздел",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "x",
+ },
+ "В этом тексте есть Раздел вне ссылки.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-ru");
+ expect(out.length).toBe(1);
+ expect(out[0]?.term).toBe("Раздел");
+ });
+
+ test("single-codepoint term is rejected (too noisy)", () => {
+ writePref("pref-x", {
+ kind: "preference",
+ topic: "x",
+ status: "confirmed",
+ principle: "x",
+ title: "X",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "y",
+ },
+ "X marks the spot. X is the variable. X is everywhere.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-x");
+ expect(out.length).toBe(0);
+ });
+});
+
+describe("findUnlinkedMentions - code block exclusion", () => {
+ test("fenced code block content does not register", () => {
+ writePref("pref-foo", {
+ kind: "preference",
+ topic: "foo",
+ status: "confirmed",
+ principle: "x",
+ title: "Token Bucket",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "y",
+ },
+ "Example:\n\n```\nfunction TokenBucket() {}\n```\n\nUse Token Bucket in real prose.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-foo");
+ expect(out.length).toBe(1); // only the prose mention, code block skipped
+ });
+
+ test("inline code span does not register", () => {
+ writePref("pref-foo", {
+ kind: "preference",
+ topic: "foo",
+ status: "confirmed",
+ principle: "x",
+ title: "Token Bucket",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "y",
+ },
+ "Use `Token Bucket` literally in code; otherwise Token Bucket in prose.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-foo");
+ expect(out.length).toBe(1);
+ });
+});
+
+describe("findUnlinkedMentions - shape", () => {
+ test("returns frozen array with line + context snippet", () => {
+ writePref("pref-foo", {
+ kind: "preference",
+ topic: "foo",
+ status: "confirmed",
+ principle: "x",
+ title: "Bar",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "y",
+ },
+ "First line.\nSecond line about Bar happens here.\nThird line.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-foo");
+ expect(Object.isFrozen(out)).toBe(true);
+ expect(out.length).toBe(1);
+ expect(out[0]?.line).toBe(2);
+ expect(out[0]?.contextSnippet).toContain("Bar");
+ });
+
+ test("ignores the target's own note", () => {
+ writePref(
+ "pref-self",
+ {
+ kind: "preference",
+ topic: "s",
+ status: "confirmed",
+ principle: "p",
+ title: "MyConcept",
+ },
+ "MyConcept self-reference here.",
+ );
+ const out = findUnlinkedMentions(vault, "pref-self");
+ expect(out.length).toBe(0);
+ });
+});
diff --git a/tests/core/brain/vault-instruction-file.test.ts b/tests/core/brain/vault-instruction-file.test.ts
new file mode 100644
index 00000000..60d75dff
--- /dev/null
+++ b/tests/core/brain/vault-instruction-file.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Unit tests for `readVaultInstructionFile` - reads a vault-root
+ * user-authored instruction file (default `VAULT.md`) and returns
+ * its content plus a vault-relative path. `brain_context` consumes
+ * this so agents see operator-curated context alongside the
+ * preference-derived active block.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { readVaultInstructionFile } from "../../../src/core/brain/vault-instruction-file.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-vault-instruction-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("readVaultInstructionFile - default name", () => {
+ test("returns null when VAULT.md is absent", () => {
+ const r = readVaultInstructionFile(vault);
+ expect(r).toBeNull();
+ });
+
+ test("reads VAULT.md content with line count and vault-relative path", () => {
+ const body = "# Vault\n\nI work on X.\nDeadlines matter.\n";
+ writeFileSync(join(vault, "VAULT.md"), body);
+ const r = readVaultInstructionFile(vault);
+ expect(r).not.toBeNull();
+ expect(r!.content).toBe(body);
+ expect(r!.path).toBe("VAULT.md");
+ expect(r!.lines).toBe(4);
+ });
+});
+
+describe("readVaultInstructionFile - configurable name", () => {
+ test("reads GUIDE.md when caller passes name override", () => {
+ writeFileSync(join(vault, "GUIDE.md"), "# Custom\n");
+ const r = readVaultInstructionFile(vault, "GUIDE.md");
+ expect(r).not.toBeNull();
+ expect(r!.path).toBe("GUIDE.md");
+ });
+
+ test("returns null for an override pointing at a nonexistent file", () => {
+ const r = readVaultInstructionFile(vault, "MISSING.md");
+ expect(r).toBeNull();
+ });
+
+ test("rejects absolute-path override with an error", () => {
+ expect(() => readVaultInstructionFile(vault, "/etc/passwd")).toThrow();
+ });
+
+ test("rejects relative path with .. traversal", () => {
+ expect(() => readVaultInstructionFile(vault, "../leak.md")).toThrow();
+ });
+
+ test("rejects empty override", () => {
+ expect(() => readVaultInstructionFile(vault, "")).toThrow();
+ });
+});
+
+describe("readVaultInstructionFile - shape", () => {
+ test("frozen result object", () => {
+ writeFileSync(join(vault, "VAULT.md"), "single line");
+ const r = readVaultInstructionFile(vault);
+ expect(Object.isFrozen(r!)).toBe(true);
+ });
+
+ test("counts newlines correctly for trailing-newline file", () => {
+ writeFileSync(join(vault, "VAULT.md"), "line one\nline two\n");
+ const r = readVaultInstructionFile(vault);
+ expect(r!.lines).toBe(2);
+ });
+
+ test("counts newlines correctly for no-trailing-newline file", () => {
+ writeFileSync(join(vault, "VAULT.md"), "line one\nline two");
+ const r = readVaultInstructionFile(vault);
+ expect(r!.lines).toBe(2);
+ });
+
+ test("empty file is treated as zero lines", () => {
+ writeFileSync(join(vault, "VAULT.md"), "");
+ const r = readVaultInstructionFile(vault);
+ expect(r!.lines).toBe(0);
+ expect(r!.content).toBe("");
+ });
+});
diff --git a/tests/core/search/property-filter.test.ts b/tests/core/search/property-filter.test.ts
new file mode 100644
index 00000000..b423fe7d
--- /dev/null
+++ b/tests/core/search/property-filter.test.ts
@@ -0,0 +1,113 @@
+/**
+ * Unit tests for `filterByProperties`. Pure post-FTS phase that
+ * drops rows whose frontmatter scalars don't match a requested
+ * filter map. Multi-value filter on the same key = OR; multiple
+ * keys = AND.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { filterByProperties } from "../../../src/core/search/property-filter.ts";
+
+interface Row {
+ readonly path: string;
+ readonly score: number;
+}
+
+const FM = new Map<string, Record<string, unknown>>([
+ ["a.md", { type: "decision", status: "open", tags: ["urgent"] }],
+ ["b.md", { type: "decision", status: "closed", tags: ["normal"] }],
+ ["c.md", { type: "note", status: "open", tags: ["urgent", "fyi"] }],
+ ["d.md", { type: "note", status: "draft" }],
+]);
+
+function reader(path: string): Record<string, unknown> | null {
+ return FM.get(path) ?? null;
+}
+
+const ROWS: ReadonlyArray<Row> = [
+ { path: "a.md", score: 1 },
+ { path: "b.md", score: 1 },
+ { path: "c.md", score: 1 },
+ { path: "d.md", score: 1 },
+];
+
+describe("filterByProperties - shape", () => {
+ test("empty filter map returns rows unchanged", () => {
+ const r = filterByProperties(ROWS, new Map(), reader);
+ expect(r.length).toBe(4);
+ });
+
+ test("returned array is frozen", () => {
+ const r = filterByProperties(ROWS, new Map([["type", ["decision"]]]), reader);
+ expect(Object.isFrozen(r)).toBe(true);
+ });
+});
+
+describe("filterByProperties - single-key filter", () => {
+ test("scalar match: type=decision", () => {
+ const r = filterByProperties(
+ ROWS,
+ new Map([["type", ["decision"]]]),
+ reader,
+ );
+ expect(r.map((x) => x.path).sort()).toEqual(["a.md", "b.md"]);
+ });
+
+ test("multi-value filter (OR within key): status=open|closed", () => {
+ const r = filterByProperties(
+ ROWS,
+ new Map([["status", ["open", "closed"]]]),
+ reader,
+ );
+ expect(r.map((x) => x.path).sort()).toEqual(["a.md", "b.md", "c.md"]);
+ });
+
+ test("array frontmatter value intersects requested set: tags=urgent", () => {
+ const r = filterByProperties(ROWS, new Map([["tags", ["urgent"]]]), reader);
+ expect(r.map((x) => x.path).sort()).toEqual(["a.md", "c.md"]);
+ });
+});
+
+describe("filterByProperties - multi-key filter (AND across keys)", () => {
+ test("type=decision AND status=open returns only a.md", () => {
+ const r = filterByProperties(
+ ROWS,
+ new Map([
+ ["type", ["decision"]],
+ ["status", ["open"]],
+ ]),
+ reader,
+ );
+ expect(r.map((x) => x.path)).toEqual(["a.md"]);
+ });
+
+ test("contradictory filter returns empty list", () => {
+ const r = filterByProperties(
+ ROWS,
+ new Map([
+ ["type", ["decision"]],
+ ["status", ["draft"]],
+ ]),
+ reader,
+ );
+ expect(r).toEqual([]);
+ });
+});
+
+describe("filterByProperties - missing keys + null frontmatter", () => {
+ test("missing key in row's frontmatter excludes the row", () => {
+ const r = filterByProperties(ROWS, new Map([["tags", ["urgent"]]]), reader);
+ // d.md has no `tags`, should be dropped.
+ expect(r.map((x) => x.path).sort()).toEqual(["a.md", "c.md"]);
+ });
+
+ test("frontmatter reader returning null excludes the row", () => {
+ const r = filterByProperties(
+ [{ path: "missing.md", score: 1 }],
+ new Map([["type", ["decision"]]]),
+ () => null,
+ );
+ expect(r).toEqual([]);
+ });
+});
diff --git a/tests/mcp/brain-context-vault-instruction.test.ts b/tests/mcp/brain-context-vault-instruction.test.ts
new file mode 100644
index 00000000..fcd120de
--- /dev/null
+++ b/tests/mcp/brain-context-vault-instruction.test.ts
@@ -0,0 +1,131 @@
+/**
+ * MCP integration coverage for the v0.10.17 `brain_context` envelope
+ * extension. When a vault-root instruction file (`VAULT.md` by
+ * default) exists, the envelope grows a `vault_instruction` field;
+ * absent file = field omitted so hosts that strip unknown fields
+ * stay byte-identical.
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-vault-instr-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-vault-instr-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const k of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "vault-instr-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callContext(server: MCPServer): Promise<Record<string, unknown>> {
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_context", arguments: {} },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(r.result.content[0]!.text);
+}
+
+describe("brain_context envelope vault_instruction extension (v0.10.17)", () => {
+ test("absent VAULT.md: envelope OMITS vault_instruction field", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callContext(server);
+ expect("vault_instruction" in out).toBe(false);
+ });
+
+ test("present VAULT.md: envelope includes path + content + lines", async () => {
+ writeFileSync(
+ join(vault, "VAULT.md"),
+ "# Project context\n\nI work on Open Second Brain.\n",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callContext(server);
+ expect(out["vault_instruction"]).toBeDefined();
+ const vi = out["vault_instruction"] as {
+ path: string;
+ content: string;
+ lines: number;
+ };
+ expect(vi.path).toBe("VAULT.md");
+ expect(vi.content).toContain("Open Second Brain");
+ expect(vi.lines).toBe(3);
+ });
+
+ test("configurable name: GUIDE.md picked up via _brain.yaml link_graph block", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nlink_graph:\n vault_instruction_file: GUIDE.md\n",
+ );
+ writeFileSync(join(vault, "GUIDE.md"), "# Guide\n");
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callContext(server);
+ const vi = out["vault_instruction"] as { path: string };
+ expect(vi.path).toBe("GUIDE.md");
+ });
+});
diff --git a/tests/mcp/link-graph-mcp-fields.test.ts b/tests/mcp/link-graph-mcp-fields.test.ts
new file mode 100644
index 00000000..97fd5889
--- /dev/null
+++ b/tests/mcp/link-graph-mcp-fields.test.ts
@@ -0,0 +1,331 @@
+/**
+ * MCP integration coverage for the v0.10.17 link-graph tools.
+ * Verifies registration in the full tool scope, JSON-RPC round-trip
+ * shape, and INVALID_PARAMS rejection of malformed input.
+ *
+ * Tools covered (extended as new v0.10.17 consumers ship):
+ * - brain_unlinked_mentions
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-link-graph-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-link-graph-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const k of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "link-graph-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function callTool(
+ server: MCPServer,
+ name: string,
+ args: Record<string, unknown>,
+ id = 9,
+): Promise<{ result?: { content: ReadonlyArray<{ type: string; text: string }> }; error?: { code: number; message: string } }> {
+ return server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id,
+ method: "tools/call",
+ params: { name, arguments: args },
+ }) as Promise<{ result?: { content: ReadonlyArray<{ type: string; text: string }> }; error?: { code: number; message: string } }>;
+}
+
+function writePref(
+ slug: string,
+ frontmatter: Record<string, string>,
+ body = "",
+): void {
+ const lines = ["---"];
+ for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ lines.push("---", "", body);
+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
+}
+
+describe("brain_unlinked_mentions registration", () => {
+ test("registered in the full tool table", () => {
+ const tools = buildToolTable("full");
+ expect(tools.find((t) => t.name === "brain_unlinked_mentions")).toBeDefined();
+ });
+
+ test("NOT in the writer-only scope", () => {
+ const tools = buildToolTable("writer");
+ expect(tools.find((t) => t.name === "brain_unlinked_mentions")).toBeUndefined();
+ });
+});
+
+describe("brain_moc_audit registration", () => {
+ test("registered in the full tool table", () => {
+ const tools = buildToolTable("full");
+ expect(tools.find((t) => t.name === "brain_moc_audit")).toBeDefined();
+ });
+
+ test("NOT in the writer-only scope", () => {
+ const tools = buildToolTable("writer");
+ expect(tools.find((t) => t.name === "brain_moc_audit")).toBeUndefined();
+ });
+});
+
+describe("brain_moc_audit round trip", () => {
+ test("returns bucketed envelope for a qualifying hub", async () => {
+ writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });
+ writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });
+ writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });
+ writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });
+ writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });
+ writePref(
+ "pref-hub",
+ { kind: "preference", topic: "hub", status: "confirmed", principle: "p" },
+ "[[pref-a]] [[pref-b]] [[pref-c]] [[pref-d]] [[pref-e]] [[pref-missing]]",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_moc_audit", { id: "pref-hub" });
+ const out = JSON.parse(r.result!.content[0]!.text);
+ expect(out["hub_id"]).toBe("pref-hub");
+ expect(out["outbound_count"]).toBe(6);
+ expect(
+ (out["candidate_missing"] as Array<{ id: string }>).some(
+ (c) => c.id === "pref-missing",
+ ),
+ ).toBe(true);
+ });
+
+ test("non-MOC hub returns INVALID_PARAMS", async () => {
+ writePref(
+ "pref-thin",
+ { kind: "preference", topic: "t", status: "confirmed", principle: "p" },
+ "Just [[pref-a]] and [[pref-b]] here.",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_moc_audit", { id: "pref-thin" });
+ expect(r.error?.code).toBe(-32602);
+ });
+});
+
+describe("brain_concept_synthesis registration", () => {
+ test("registered in the full tool table", () => {
+ const tools = buildToolTable("full");
+ expect(tools.find((t) => t.name === "brain_concept_synthesis")).toBeDefined();
+ });
+
+ test("NOT in the writer-only scope", () => {
+ const tools = buildToolTable("writer");
+ expect(tools.find((t) => t.name === "brain_concept_synthesis")).toBeUndefined();
+ });
+});
+
+describe("brain_concept_synthesis round trip", () => {
+ test("returns envelope with linkers", async () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subj",
+ });
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "I see [[pref-tgt]] here.",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_concept_synthesis", {
+ id: "pref-tgt",
+ });
+ const out = JSON.parse(r.result!.content[0]!.text);
+ expect(out["target_id"]).toBe("pref-tgt");
+ expect(out["target_title"]).toBe("Subj");
+ expect(out["linkers"].length).toBe(1);
+ expect(out["unlinked_mentions"]).toEqual([]);
+ });
+
+ test("include_unlinked=true populates unlinked_mentions", async () => {
+ writePref("pref-tgt", {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ });
+ writePref(
+ "pref-prose",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "Subject Line shows up here.",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_concept_synthesis", {
+ id: "pref-tgt",
+ include_unlinked: true,
+ });
+ const out = JSON.parse(r.result!.content[0]!.text);
+ expect(out["unlinked_mentions"].length).toBe(1);
+ });
+
+ test("rejects empty id with INVALID_PARAMS", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_concept_synthesis", { id: "" });
+ expect(r.error?.code).toBe(-32602);
+ });
+
+ test("rejects non-boolean include_unlinked", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_concept_synthesis", {
+ id: "pref-x",
+ include_unlinked: "yes",
+ });
+ expect(r.error?.code).toBe(-32602);
+ });
+});
+
+describe("brain_unlinked_mentions round trip", () => {
+ test("returns mention list for matching prose", async () => {
+ writePref(
+ "pref-target",
+ {
+ kind: "preference",
+ topic: "t",
+ status: "confirmed",
+ principle: "p",
+ title: "Subject Line",
+ },
+ );
+ writePref(
+ "pref-linker",
+ {
+ kind: "preference",
+ topic: "l",
+ status: "confirmed",
+ principle: "p",
+ },
+ "I think about Subject Line often.",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_unlinked_mentions", {
+ id: "pref-target",
+ });
+ const out = JSON.parse(r.result!.content[0]!.text);
+ expect(out["target_id"]).toBe("pref-target");
+ expect(Array.isArray(out["mentions"])).toBe(true);
+ expect(out["mentions"].length).toBe(1);
+ expect(out["mentions"][0]["source"]).toBe("pref-linker");
+ expect(out["mentions"][0]["term"]).toBe("Subject Line");
+ });
+
+ test("empty vault returns empty mentions array", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_unlinked_mentions", {
+ id: "pref-missing",
+ });
+ const out = JSON.parse(r.result!.content[0]!.text);
+ expect(out["mentions"]).toEqual([]);
+ });
+
+ test("rejects empty id with INVALID_PARAMS", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_unlinked_mentions", { id: "" });
+ expect(r.error?.code).toBe(-32602);
+ });
+
+ test("rejects negative limit with INVALID_PARAMS", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_unlinked_mentions", {
+ id: "pref-foo",
+ limit: -1,
+ });
+ expect(r.error?.code).toBe(-32602);
+ });
+
+ test("rejects non-numeric limit with INVALID_PARAMS", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callTool(server, "brain_unlinked_mentions", {
+ id: "pref-foo",
+ limit: "many",
+ });
+ expect(r.error?.code).toBe(-32602);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 51a73d37..4294ee21 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -158,7 +158,9 @@ describe("tool listing", () => {
// Brain (brain_note added in v0.10.8 §32B,
// brain_context added in v0.10.10,
// brain_context_pack added in v0.10.15,
- // brain_operator_summary added in v0.10.16).
+ // brain_operator_summary added in v0.10.16,
+ // brain_unlinked_mentions / brain_concept_synthesis /
+ // brain_moc_audit added in v0.10.17).
"brain_feedback",
"brain_dream",
"brain_apply_evidence",
@@ -169,6 +171,9 @@ describe("tool listing", () => {
"brain_doctor",
"brain_backlinks",
"brain_context_pack",
+ "brain_unlinked_mentions",
+ "brain_concept_synthesis",
+ "brain_moc_audit",
"brain_operator_summary",
// Pay Memory (unchanged).
"payment_memory_init",
@@ -369,9 +374,10 @@ describe("stdio loop", () => {
const list = JSON.parse(lines[1]!);
expect(init.id).toBe(1);
expect(list.id).toBe(2);
- // v0.10.16: 3 core + 11 Brain (brain_operator_summary added v0.10.16)
- // + 8 Pay Memory + 1 Search = 23.
- expect(list.result.tools.length).toBe(23);
+ // v0.10.17: 3 core + 14 Brain (brain_unlinked_mentions /
+ // brain_concept_synthesis / brain_moc_audit added v0.10.17)
+ // + 8 Pay Memory + 1 Search = 26.
+ expect(list.result.tools.length).toBe(26);
});
test("returns parse error for invalid JSON", async () => {