Skip to content

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

TypeScript

feat: Recall & Working-Memory Quality Suite - selectable profiles, usage decay, co-occurrence, file-context (v1.10.0) (#99)

Sol Aitken35b824e0d660
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 214f4310..cf4c5c57 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.9.0",
+ "version": "1.10.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 1d3d82e1..8a40c366 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.9.0",
+ "version": "1.10.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4808b5cd..3aaec89b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,46 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.10.0] - 2026-06-14
+
+### Added
+
+- **Recall & Working-Memory Quality Suite.** Four additive, deterministic,
+ language-agnostic units on top of the mature search/recall subsystem. Every
+ unit is flag- or surface-gated; with no profile, flag, or new surface in use,
+ search and continuity reads are byte-identical to before.
+ - **Selectable recall profiles (`o2b search --profile`, `brain_search`
+ `profile` field).** Named presets `fast | balanced | thorough` expand to a
+ fixed knob tuple over the same bounded axes the self-tuning grid ranges over
+ (candidate pool, traversal depth, learned weights, query expansion) and are
+ applied through the same `applyTunedParameters` machinery, so a profile and
+ a learned grid point stay coherent. An explicitly selected profile takes
+ precedence over a persisted self-tuning grid point; an unknown profile name
+ fails loud with a typed `SearchError`. No profile selected leaves ranking on
+ the existing config path, bit-for-bit.
+ - **Usage-driven working-memory decay (`o2b brain continuity rank`).**
+ Continuity records are append-only and immutable, so decay is a pure
+ read-side weight in `(0, 1]`, never a mutation. `decayWeight` combines
+ record age (exponential half-life) with a usage signal derived only from
+ existing `recall_telemetry` surfaced-artifact references; a record whose
+ sources were never surfaced - such as a session-scoped `pre_compact_extract`
+ decision - has no usage and decays by age alone, with no fabricated coupling.
+ `rank` lists working-memory records freshest and most-recalled first.
+ - **Language-agnostic co-occurrence auto-relate (`o2b brain co-occurrence`).**
+ Entities repeatedly co-referenced from the same notes are scored with a
+ structural PMI / document-frequency metric over the wikilink graph - link
+ incidence only, no natural-language word list in any language, so a
+ non-Latin vault scores identically for the same structure. Output is a
+ derived, schema-versioned, hashed suggestion artifact (re-validated on read,
+ fail-soft); notes are never mutated and an already directly-linked pair is
+ never re-suggested. `--write` persists `Brain/link-graph/co-occurrence.json`.
+ - **File-context recall (`o2b brain file-context`, `brain_file_context` MCP
+ tool).** Given a file path, surface prior vault work that mentions it by
+ querying the existing index with terms derived structurally from the path
+ (basename + stem, no natural-language processing, no LLM). A size gate skips
+ trivial files (default 1500 bytes) and returns an explicit reason rather
+ than a fabricated empty hit.
+
## [1.9.0] - 2026-06-14
### Added
@@ -5428,6 +5468,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.10.0]: https://github.com/itechmeat/open-second-brain/compare/v1.9.0...v1.10.0
[1.9.0]: https://github.com/itechmeat/open-second-brain/compare/v1.8.0...v1.9.0
[1.8.0]: https://github.com/itechmeat/open-second-brain/compare/v1.7.0...v1.8.0
[1.7.0]: https://github.com/itechmeat/open-second-brain/compare/v1.6.0...v1.7.0
diff --git a/README.md b/README.md
index 7a00b90f..97878afb 100644
--- a/README.md
+++ b/README.md
@@ -89,6 +89,7 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra
- **Knowledge that knows where it came from.** Drop a source document and the agent's extraction becomes cross-referenced entity and concept pages plus a summary page that backlinks the source and lists its connections; N sources become one dated report whose every finding cites the source that flagged it; a derived fact carries a `deduced`/`inferred` provenance level and links back to its premises, and recall trusts an operator-stated rule above a machine-derived one. A fact can declare an `owner:` so multi-agent brains keep separate truth spaces, and a standing-query attention flow surfaces the open loops you declare. The plugin never runs a model itself - the agent owns generation, the vault owns the durable, provenanced record - and every behaviour is opt-in.
- **An index that survives interruption.** Stopping `o2b search watch` mid-sync finishes the in-flight pass at a file boundary before exiting (within `search_shutdown_grace_seconds`) instead of killing it mid-write; an incremental run is already resumable through the unchanged-file fastpath, and `search_resume_reindex` extends that to a full rebuild - an interrupted reindex resumes its staging build instead of starting over, guarded by a signature so a drifted build is discarded rather than trusted. Both default off, so behaviour is unchanged unless you ask for it.
- **A brain you can carry, hand off, and write to in process.** `o2b brain bank-export` serialises a whole vault - preferences, the page graph, a per-page interchange contract (path, kind, advisory confidence/provenance, citations, aliases, freshness), and the sources dashboard - into one deterministic, schema-versioned bundle for backup, migration, or downstream-tool ingest; `bank-import` reconstructs the page graph and reports the rest as carried-not-restored rather than faking a full restore. A `brain_create_note` MCP tool writes an actual vault note (path + frontmatter + content) atomically, refusing traversal, the Brain root, and clobbering. And `createBrain(vault)` is a thin in-process SDK over the same core functions - bank/graph export-import, preference export, source ingest plus list/get/delete, and note creation - so scripts and agents manage brain content without the CLI or MCP layer.
+- **Recall you can tune, and a working set that prunes itself.** `o2b search --profile fast|balanced|thorough` (and the `brain_search` `profile` field) pick a recall preset over the same bounded knobs the self-tuner uses - an explicit profile wins over a learned grid point, and no profile leaves ranking bit-for-bit unchanged. `o2b brain file-context <path>` surfaces prior vault work that mentions a file before you read it; `o2b brain co-occurrence` proposes relationship edges between entities repeatedly co-referenced from the same notes, scored structurally over the wikilink graph with no natural-language word list in any language; and `o2b brain continuity rank` weights working-memory records by a usage-driven decay derived only from real recall telemetry, so stale decisions fade while actively-recalled ones stay prominent. All deterministic, all read-only or suggestion-only.
That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.
diff --git a/docs/brainstorm/recall-working-memory-quality/cli-output/claude.md b/docs/brainstorm/recall-working-memory-quality/cli-output/claude.md
new file mode 100644
index 00000000..1664c67e
--- /dev/null
+++ b/docs/brainstorm/recall-working-memory-quality/cli-output/claude.md
@@ -0,0 +1,36 @@
+### Variant 1: Federated patches with a shared config block
+- **Approach**: Each unit ships as its own small, self-contained module. The only shared structure is a single nested optional block added to `ResolvedSearchConfig` (one sub-object per unit, all absent-by-default) plus one `resolveRecallProfile(name)` helper that expands `fast|balanced|thorough` into the exact knob tuple already enumerated by `tuning.ts`. Read-side weighting for decay and file-context biasing is written inline at the existing score-combination site in `search.ts`, guarded by per-unit flag checks.
+- **Trade-offs**:
+ - Pro: smallest possible diff and review surface; each unit independently testable and revertable.
+ - Pro: byte-identical OFF is trivial to assert because each guard is a single early branch returning the prior code path.
+ - Pro: no new abstraction to get wrong; no risk of drifting toward the deferred external-source registry.
+ - Con: read-side weighting logic for Unit 3 and Unit 4 is scattered and order-sensitive, with no single seam; a fifth future unit repeats the same inline boilerplate.
+ - Con: persistence conventions (version + hash + fail-soft) get re-implemented per unit (co-occurrence cache, decay-signal cache) instead of shared.
+ - Con: "four units, one release" reads as four patches that merely landed together, not a composed suite.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant 2: Two shared primitives - a profile/knob resolver and a composable read-side adjuster fed by signal readers
+- **Approach**: Introduce exactly two seams. First, a `resolveRecallProfile` that maps a profile name to the existing knob tuple (candidate-pool multiplier, depth, expansion, fusion mode), reusing `tuning.ts` axes so profiles and self-tuning stay coherent. Second, a read-side `ScoreAdjuster` composition point in `search.ts`: an ordered list of pure `(candidate, signals) -> weight` functions that Unit 3 (usage/recency decay) and Unit 4 (file-path bias, extending `session-focus.ts`) plug into, sourced by small `UsageSignalReader`s over `recall_telemetry` continuity records. Unit 2 (co-occurrence) is a dream-side producer that only shares the persistence convention (versioned, hashed, re-validated, fail-soft suggestion artifact, like `tuning.json`) and never touches the read path.
+- **Trade-offs**:
+ - Pro: genuine composition on the one axis that actually overlaps (read-side weighting), with decay and file-context funneling through a single, testable seam.
+ - Pro: signal readers and the persistence convention are shared by three units (decay cache, co-occurrence suggestions, and the existing tuning artifact) without forcing co-occurrence into the read path it does not belong in.
+ - Pro: identity-transform when every flag is off (empty adjuster list, default profile equals current knobs) gives a clean byte-identical assertion.
+ - Con: requires up-front design of the adjuster contract and ordering semantics; more test cases than Variant 1.
+ - Con: two seams to learn, a middle ground that neither minimizes diff nor maximizes future extensibility.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Unified RecallContext orchestrator with an internal signal/pass registry
+- **Approach**: A single `buildRecallContext(config, selection)` owns everything: profile expansion, registration of all signal sources, composition of every read-side adjuster, and the file-context query path all resolve through it; co-occurrence is registered as one entry in a shared maintenance-pass registry alongside other dream passes. One seam gates all four units and anticipates the deferred external recall-source registry.
+- **Trade-offs**:
+ - Pro: maximal uniformity and a single place for gating, config, and persistence wiring; most natural growth path toward future recall sources.
+ - Pro: the suite genuinely reads as one architecture rather than additive units.
+ - Con: heavy abstraction for four small additive units; the orchestrator sits directly on the hot `search()` public path, enlarging blast radius and making byte-identical OFF harder to prove.
+ - Con: a registry of recall sources/passes drifts toward the "pluggable external recall-source registry" that is explicitly out of scope.
+ - Con: highest review cost and the greatest chance of touching default behaviour by accident.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 2
+**Rationale**: It matches the stated goal of one or two shared primitives precisely - a profile/knob resolver plus a composable read-side adjuster fed by signal readers - so the units compose on the single axis they truly share (read-side weighting) while co-occurrence stays a dream-side producer behind only the shared persistence convention. It reuses the `tuning.ts` knob axes and `session-focus.ts` biasing rather than inventing parallel machinery, keeps the byte-identical-OFF guarantee cheap via an empty adjuster list and default profile, and deliberately stops short of the orchestrator/registry that would drift into the explicitly deferred external-source scope.
diff --git a/docs/brainstorm/recall-working-memory-quality/cli-output/prompt.md b/docs/brainstorm/recall-working-memory-quality/cli-output/prompt.md
new file mode 100644
index 00000000..bd765d29
--- /dev/null
+++ b/docs/brainstorm/recall-working-memory-quality/cli-output/prompt.md
@@ -0,0 +1,64 @@
+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 "Recall & Working-Memory Quality Suite" - one release bundling FOUR small, additive, related units on top of the mature search/recall subsystem. Each unit must be deterministic, language-agnostic (NO hardcoded natural-language word lists in any language), provider-agnostic (the kernel never calls an LLM), and byte-identical when its flag is off. The brainstorm should propose how the FOUR units share structure (config, gating, persistence, read-side weighting) so they compose cleanly rather than four disconnected patches.
+
+Unit 1 - Selectable recall profiles. Today `search()` consumes a fixed `ResolvedSearchConfig`. Add named presets `fast | balanced | thorough` that are tuples of EXISTING knobs (candidate-pool multiplier, traversal depth, query expansion on/off, fusion mode) - the same axes the self-tuning grid in `tuning.ts` already ranges over. Profile selected by a CLI flag and an MCP tool field; default selection reproduces today's behaviour bit-for-bit. Explicitly OUT OF SCOPE: pluggable external recall-source registry (deferred as architectural).
+
+Unit 2 - Language-agnostic co-occurrence auto-relate. Today links are suggested only by `findUnlinkedMentions` (raw title/alias string match). Add a statistical pass: canonical entities that repeatedly co-occur in the same notes get a co-occurrence relationship edge, scored by a document-frequency / PMI-style structural metric (NO NL keyword lists). Runs in dream/maintenance, emits derived link SUGGESTIONS, never mutates note bodies.
+
+Unit 3 - Usage-driven working-memory decay. Continuity records (`src/core/brain/continuity/store.ts`) are append-only, immutable JSONL deduped by a content `recordId()`; they cannot be mutated in place. Add a usage counter + recency signal sourced from existing `recall_telemetry` continuity records, and a deterministic decay-score computed READ-SIDE that down-weights stale decisions/commitments during recall while keeping frequently-referenced items prominent. Never deletes; only weights.
+
+Unit 4 - File-context recall. Give an agent "I have worked on this file before" awareness: a new CLI verb + MCP tool that, given a file path, queries the EXISTING search index (building on `src/core/search/session-focus.ts` path-prefix biasing) for prior work touching that path. No LLM. A file-size gate (like the mem0 source's >=1500 bytes) skips trivial files.
+
+# Project context
+
+Open Second Brain - TypeScript, Bun runtime, SQLite (bun:sqlite, FTS5 + sqlite-vec), MCP stdio server, `o2b` CLI, Obsidian/Markdown vault. Provider-agnostic kernel.
+
+Recent releases (each a themed multi-unit "Suite" shipped as one squash commit):
+- v1.9.0 Brain Portability & Interop
+- v1.8.0 Indexer Durability & Resilience
+- v1.7.0 Knowledge Provenance
+- v1.6.0 Vault Integrity & Trust
+- v1.5.0 Search & Recall Quality (explainable scores, trust, threshold, reinforce, eval)
+
+Related files:
+- src/core/search/types.ts (ResolvedSearchConfig at :543 - vault, weights, fusionMode, rrfK, recall, resumeReindex, shutdownGraceMs)
+- src/core/search/search.ts (search(); already applies opt-in self-tuning grid via applyTunedParameters)
+- src/core/search/tuning.ts (FIXED-grid deterministic self-tuning: candidate-pool {3,4,5}, depth {1,2}, learned-weights on/off, expansion on/off; persists Brain/search/tuning.json with dataset hash; re-validated on read, fail-soft to defaults)
+- src/core/search/session-focus.ts (query/path-prefix biasing with TTL; path safety via vault-relative normalisation)
+- src/core/search/benchmark.ts (runRecallBenchmark - MRR/hit@k objective)
+- src/core/brain/continuity/store.ts + types.ts (append-only JSONL, CONTINUITY_SCHEMA_VERSION o2b.continuity.v1, recordId dedupe, kinds incl. recall_telemetry, context_receipt, pre_compact_extract)
+- src/core/brain/link-graph/unlinked-mentions.ts (findUnlinkedMentions - string match), concept-cluster.ts, communities.ts, graph-index.ts
+- src/core/brain/entities/canonical.ts (canonical entity registry)
+- src/core/search/recall-telemetry.ts, recall-budget.ts
+
+Conventions:
+- Every feature is gated by a config field / env var; OFF reproduces prior behaviour byte-for-byte (asserted by tests).
+- Deterministic and replayable: persisted artifacts carry a version + hash; delete-to-reset; re-validate on read; fail-soft to defaults.
+- Errors are typed and loud (e.g. SearchError, BankImportError); NO misleading silent fallbacks that pretend success.
+- Language-agnostic: gating/classification/ranking derive from structural signals, frontmatter fields, document-frequency/IDF - never hardcoded word lists in any language.
+
+Constraints:
+- Do NOT change existing public API signatures or default behaviour.
+- No new external/heavy dependencies.
+- No `as`/`as unknown as` cast crutches; build values with the correct type from the start.
+- The four units share one release and ideally one or two shared primitives (e.g. a profile/knob resolver, a read-side weighting helper, a usage-signal reader) rather than four isolated implementations.
+
+# 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/recall-working-memory-quality/design.md b/docs/brainstorm/recall-working-memory-quality/design.md
new file mode 100644
index 00000000..48456bb7
--- /dev/null
+++ b/docs/brainstorm/recall-working-memory-quality/design.md
@@ -0,0 +1,131 @@
+# Recall & Working-Memory Quality Suite - composable recall tuning, graph densification, and self-pruning working memory
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain has a mature search/recall subsystem (explainable scores,
+trust, threshold, reinforce, self-tuning grid) but four small gaps remain: recall
+strategy is a single fixed point with no operator-selectable trade-off; link
+suggestions come only from raw string matching, so entities that statistically
+co-occur are never related; continuity working-memory records carry equal weight
+forever regardless of use; and an agent opening a file gets no automatic surfacing
+of prior work on that path. Each gap has a small, additive, deterministic fix that
+shares structure with the others.
+
+## Scope
+
+Four additive units, each gated so OFF reproduces current behaviour byte-for-byte:
+
+1. **Selectable recall profiles** - named presets `fast | balanced | thorough`
+ expanding to a tuple of EXISTING knobs (candidate-pool multiplier, traversal
+ depth, query expansion, fusion mode), reusing the axes `tuning.ts` already
+ ranges over. CLI flag + MCP field. No profile selected = today's config.
+2. **Language-agnostic co-occurrence auto-relate** - a dream/maintenance pass that
+ scores canonical-entity co-occurrence with a document-frequency / PMI-style
+ structural metric and emits derived link SUGGESTIONS. No NL word lists, no note
+ mutation.
+3. **Usage-driven working-memory decay** - a read-side deterministic decay weight
+ for continuity records, computed from usage signals already recorded as
+ `recall_telemetry` continuity records. Down-weights stale items at recall;
+ never deletes or mutates a record.
+4. **File-context recall** - a CLI verb + MCP tool that, given a file path, queries
+ the existing search index (reusing `session-focus.ts` path-prefix biasing) for
+ prior work touching that path, behind a file-size gate. No LLM.
+
+## Out of scope
+
+- Pluggable external recall-source registry (the other half of the prefetch-profile
+ upstream task) - deferred as architectural.
+- Mutating continuity records in place (they are append-only, immutable, deduped by
+ `recordId()`); decay is strictly read-side weighting.
+- Mutating note bodies to add co-occurrence links (suggestions only).
+- Any new RRF arm, relational parser, or fusion-order change (that is a separate
+ triage item, t_09b7ccea).
+
+## Chosen approach
+
+Consultant Variant 2 - two shared primitives, no orchestrator:
+
+- **Primitive A - `resolveRecallProfile(name)`** (`src/core/search/profiles.ts`):
+ maps a profile name to a knob tuple over the SAME axes as the self-tuning grid,
+ so profiles and self-tuning stay coherent. Applied in `search()` next to the
+ existing `applyTunedParameters` seam.
+- **Primitive B - a usage-signal reader + deterministic weight helper**
+ (`src/core/brain/continuity/usage-signal.ts` + a pure decay function): reads
+ `recall_telemetry` records, derives per-source access frequency/recency, and a
+ pure `decayWeight(signal, now) -> number in (0,1]` used by the continuity
+ read-model to weight surfaced working-memory records.
+
+Co-occurrence (Unit 2) is a dream-side PRODUCER that shares only the established
+persistence convention (versioned + dataset-hashed + re-validated-on-read +
+fail-soft, exactly like `tuning.json`); it never touches the read path. File-context
+recall (Unit 4) is a standalone surface that reuses the existing `session-focus.ts`
+path-prefix primitive rather than inventing biasing machinery.
+
+### Deliberate scoping refinement of the consultant recommendation
+
+The consultant placed the read-side adjuster for BOTH decay and file-context on the
+hot `search()` public path. We keep Variant 2's two-primitive philosophy but scope
+the read-side weight to where the candidates actually flow: decay weighting lives in
+the continuity read-model (where working-memory records are surfaced), and
+file-context recall is a separate surface over the search index. This keeps the
+`search()` default path untouched (cheaper byte-identical proof, smaller blast
+radius) - which directly addresses the consultant's own stated risk about widening
+the search hot path. This is a scoping decision within Variant 2, not a different
+variant.
+
+## Design decisions
+
+- **Profile vs self-tuning precedence.** When an explicit profile is selected it is
+ applied as the base config; the persisted self-tuning grid point (opt-in) does NOT
+ silently override an explicit operator profile - explicit intent wins over learned
+ default. With no profile, behaviour is exactly as today. Documented and tested.
+- **Profiles are fixed tuples, not free knobs.** Like the self-tuning grid, the
+ preset values live in one table; nothing learned or user-supplied can leave the
+ enumerated set. Unknown profile name = loud typed error, not a silent default.
+- **Co-occurrence metric is structural.** Score = co-document-frequency normalised by
+ per-entity document frequency (PMI-style), computed from the canonical-entity ->
+ note incidence already available; no tokens, no language assumptions. A minimum
+ co-document threshold and a top-N cap keep output bounded and deterministic.
+- **Decay is pure and replayable.** `decayWeight` is a pure function of
+ (access count, last-access age, now); identical inputs give identical output. The
+ usage signal is derived, never persisted as a new mutable counter on the record.
+- **File-context gate.** Size gate mirrors the mem0 source (default 1500 bytes),
+ exposed as a config field; below the gate the tool returns an explicit empty
+ result with a reason, not a fabricated hit.
+- **Every unit flag-gated.** New config fields default to the value that reproduces
+ prior behaviour; a byte-identical test asserts OFF == today for search and
+ continuity read.
+
+## File changes
+
+New:
+- `src/core/search/profiles.ts` - profile table + `resolveRecallProfile`.
+- `src/core/brain/continuity/usage-signal.ts` - usage-signal reader + `decayWeight`.
+- `src/core/brain/link-graph/co-occurrence.ts` - co-occurrence scorer + suggestion model.
+- `src/core/brain/file-recall.ts` - file-context recall surface (search + session-focus reuse).
+- CLI verbs under `src/cli/brain/verbs/` (recall profile passthrough on search; file-context; co-occurrence suggest).
+- MCP tool(s) for file-context recall (and profile field on the search tool).
+- Tests mirroring each module under `tests/core/...`, `tests/cli/...`, `tests/mcp/...`.
+
+Modified:
+- `src/core/search/types.ts` - add `recallProfile` resolved field (default null).
+- `src/core/search/search.ts` - apply `resolveRecallProfile` at the existing config seam.
+- `src/core/brain/continuity/read-model.ts` - apply decay weight when the flag is on.
+- `src/core/brain/dream.ts` (or maintenance entry) - register the co-occurrence pass.
+- `src/mcp/search-tools.ts` / tool registry - profile field + new tool; tool-count tests.
+- `README.md`, `CHANGELOG.md`, `docs/mcp.md`, version manifests.
+
+## Risks and open questions
+
+- **Profile/self-tuning interaction** must be unambiguous and tested both ways
+ (profile-only, self-tuning-only, both) - resolved by the precedence rule above.
+- **Decay surfacing site** - confirm during TDD which continuity read path surfaces
+ working-memory records (read-model.ts) so the weight is applied once, not twice.
+- **Co-occurrence cost** - bound by min-co-document threshold + top-N; verify it
+ stays within the dream-pass budget on a large vault.
+- **MCP tool count** - adding tools changes the frozen count/name-list tests; update
+ in lockstep (known from prior suites).
diff --git a/docs/brainstorm/recall-working-memory-quality/plan.md b/docs/brainstorm/recall-working-memory-quality/plan.md
new file mode 100644
index 00000000..3501d476
--- /dev/null
+++ b/docs/brainstorm/recall-working-memory-quality/plan.md
@@ -0,0 +1,82 @@
+# Recall & Working-Memory Quality Suite - implementation plan
+
+Four atomic units on ONE feature branch (`feat/recall-working-memory-quality`),
+each its own conventional commit, each TDD (failing test first). Order chosen so
+the two shared primitives land before their consumers.
+
+## Task 1: Selectable recall profiles (Primitive A)
+
+- **Files**: `src/core/search/profiles.ts` (new), `src/core/search/types.ts`
+ (+`recallProfile` resolved field, default null), `src/core/search/search.ts`
+ (apply at the `applyTunedParameters` seam), `src/cli/search.ts` (top-level
+ `o2b search`, add `--profile` flag - NOT a new verb; `verbs/profile.ts` is the
+ unrelated `o2b brain profile` digest), `src/mcp/search-tools.ts`
+ (+`profile` field on `SEARCH_INPUT_SCHEMA`), tests:
+ `tests/core/search/profiles.test.ts`, search byte-identical-OFF test.
+- **Acceptance**:
+ - `resolveRecallProfile("fast"|"balanced"|"thorough")` returns the fixed knob
+ tuple; unknown name throws a typed `SearchError("INVALID_INPUT", ...)`.
+ - With no profile, `search()` config is byte-identical to today (asserted).
+ - Explicit profile wins over a persisted self-tuning grid point; both-set and
+ each-alone cases tested.
+ - CLI `--profile` and MCP `profile` field thread through to the resolver.
+- **Depends on**: none.
+
+## Task 2: Usage-driven working-memory decay (Primitive B)
+
+- **Files**: `src/core/brain/continuity/usage-signal.ts` (new: usage-signal reader
+ over `recall_telemetry` records + pure `decayWeight(signal, now)`),
+ `src/core/brain/continuity/read-model.ts` (apply weight when flag on),
+ `src/core/brain/continuity/types.ts` (config/flag if needed), tests:
+ `tests/core/brain/continuity/usage-signal.test.ts`, read-model decay test +
+ byte-identical-OFF test.
+- **Acceptance**:
+ - `decayWeight` is pure: identical (count, lastAccessAge, now) -> identical value
+ in (0, 1]; frequently-/recently-accessed -> higher weight; stale -> lower.
+ - Usage signal derived only from existing `recall_telemetry` continuity records;
+ no new mutable counter written to records.
+ - Read-model OFF reproduces current ordering/weights byte-for-byte (asserted).
+ - No record is deleted or mutated; decay is weighting only.
+- **Depends on**: none.
+
+## Task 3: Language-agnostic co-occurrence auto-relate (dream producer)
+
+- **Files**: `src/core/brain/link-graph/co-occurrence.ts` (new: structural
+ co-occurrence scorer + versioned/hashed suggestion artifact, persistence
+ convention mirroring `tuning.json`), maintenance/dream entry registration,
+ `src/cli/brain/verbs/` co-occurrence-suggest verb, tests:
+ `tests/core/brain/link-graph/co-occurrence.test.ts` + language-agnostic test
+ (non-Latin entities scored identically by structure).
+- **Acceptance**:
+ - Score is document-frequency / PMI-style over canonical-entity -> note
+ incidence; NO natural-language word list anywhere (asserted by a non-Latin /
+ mixed-script fixture producing structurally-identical results).
+ - Min co-document threshold + top-N cap make output bounded and deterministic
+ (same vault -> same suggestions, hashed).
+ - Emits derived link suggestions only; note bodies are never modified.
+ - Re-validate-on-read + fail-soft to empty when the artifact is drifted/missing.
+- **Depends on**: none (independent producer).
+
+## Task 4: File-context recall (standalone surface)
+
+- **Files**: `src/core/brain/file-recall.ts` (new: path -> prior-work query reusing
+ `session-focus.ts` path-prefix biasing + size gate), `src/cli/brain/verbs/`
+ file-context verb, `src/mcp/` new tool + registry, tests:
+ `tests/core/brain/file-recall.test.ts`, `tests/mcp/` tool test + tool-count /
+ frozen-name-list updates.
+- **Acceptance**:
+ - Given a file path, returns prior-work hits from the existing search index
+ biased to that path; no LLM call.
+ - File below the size gate (default 1500 bytes, config field) returns an explicit
+ empty result WITH a reason, never a fabricated hit.
+ - Path safety: traversal / outside-vault path -> typed error (reuse vault-relative
+ normalisation), consistent with `session-focus.ts`.
+ - MCP tool registered; tool-count and frozen-name-list tests updated in lockstep.
+- **Depends on**: none (uses existing search + session-focus).
+
+## Cross-cutting (Phase 4/5)
+
+- Full suite: `bun test`, `bun run typecheck`, `bun run lint`, `bun run scripts/sync-version.ts --check`.
+- Version bump `package.json` 1.9.0 -> 1.10.0 + `bun run scripts/sync-version.ts`.
+- Docs: `CHANGELOG.md` (one `[1.10.0]` entry), `README.md`, `docs/mcp.md`.
+- Byte-identical-OFF assertions per unit are the gate for "additive, no behaviour change".
diff --git a/docs/brainstorm/recall-working-memory-quality/variants.md b/docs/brainstorm/recall-working-memory-quality/variants.md
new file mode 100644
index 00000000..8812e8b0
--- /dev/null
+++ b/docs/brainstorm/recall-working-memory-quality/variants.md
@@ -0,0 +1,63 @@
+# Recall & Working-Memory Quality Suite - brainstorm audit trail
+
+Primary consultant: Claude Code (`claude -p`), exit 0, three parseable variants
+plus a recommendation. Fallback consultant (Codex) NOT invoked - primary
+succeeded with >= 2 variants. Full verbatim output: `cli-output/claude.md`.
+
+## Variant 1: Federated patches with a shared config block (small / low)
+
+Each unit a self-contained module; only shared structure is one optional nested
+block on `ResolvedSearchConfig` plus `resolveRecallProfile`. Read-side weighting for
+decay and file-context written inline at the score-combination site in `search.ts`.
+
+- Pro: smallest diff; independently testable/revertable; trivial byte-identical OFF;
+ no new abstraction to get wrong.
+- Con: read-side logic for Units 3 and 4 scattered and order-sensitive, no single
+ seam; persistence conventions re-implemented per unit; reads as four patches that
+ merely landed together.
+
+## Variant 2: Two shared primitives - profile/knob resolver + composable read-side adjuster fed by signal readers (medium / medium) - RECOMMENDED
+
+A `resolveRecallProfile` reusing `tuning.ts` axes, plus a read-side `ScoreAdjuster`
+composition point fed by small `UsageSignalReader`s over `recall_telemetry`.
+Co-occurrence stays a dream-side producer sharing only the persistence convention.
+
+- Pro: genuine composition on the one axis that overlaps (read-side weighting);
+ shared signal readers + persistence convention; clean identity-transform OFF.
+- Con: needs up-front adjuster-contract/ordering design; two seams; a middle ground.
+
+## Variant 3: Unified RecallContext orchestrator with internal signal/pass registry (large / high)
+
+A single `buildRecallContext` owns profile expansion, signal registration, adjuster
+composition, file-context path, and a maintenance-pass registry for co-occurrence.
+
+- Pro: maximal uniformity; most natural growth toward future recall sources.
+- Con: heavy abstraction for four small units; sits on the hot `search()` public
+ path (enlarges blast radius, harder byte-identical proof); drifts toward the
+ explicitly-deferred external recall-source registry; highest review cost.
+
+## Consultant recommendation: Variant 2
+
+> It matches the stated goal of one or two shared primitives precisely ... the units
+> compose on the single axis they truly share (read-side weighting) while
+> co-occurrence stays a dream-side producer behind only the shared persistence
+> convention ... deliberately stops short of the orchestrator/registry that would
+> drift into the explicitly deferred external-source scope.
+
+## Orchestrator decision: ADOPT Variant 2, with one scoping refinement
+
+Accepted. Variant 2 fits the project's established conventions (flag-gated,
+deterministic, versioned+hashed persistence, byte-identical OFF) and the "one or two
+shared primitives" goal better than the minimal Variant 1 (which re-implements
+persistence per unit and scatters read-side logic) or the heavy Variant 3 (which
+puts an orchestrator on the hot search path and drifts toward the deferred
+external-source registry).
+
+Refinement (documented in `design.md`): the consultant placed the read-side adjuster
+for BOTH decay and file-context on the `search()` public path. We keep the
+two-primitive philosophy but scope the read-side weight to where candidates actually
+flow - decay weighting in the continuity read-model, file-context as a standalone
+surface reusing `session-focus.ts`. This leaves the `search()` default path
+untouched, making the byte-identical guarantee cheaper and the blast radius smaller -
+which addresses the consultant's own stated risk about widening the search hot path.
+This is a scoping choice within Variant 2, not a different variant.
diff --git a/docs/mcp.md b/docs/mcp.md
index 36428255..b219ff8b 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -18,7 +18,7 @@ in Open Second Brain depends on the MCP server being running.
## Tool Highlights
-The full server currently advertises 77 tools; the 18 deprecated predecessor
+The full server currently advertises 78 tools; the 18 deprecated predecessor
names were removed in 1.0.0 and now answer a precise INVALID_PARAMS tombstone
(see "Consolidated views and deprecated aliases" below). The table highlights
the operator-facing core,
@@ -42,7 +42,7 @@ flags for a narrower per-process full server.
| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest`. | `view` |
| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis`. | `view` |
-| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, and evidence-pack diagnostics. | `query` |
+| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, and a selectable recall `profile` (`fast \| balanced \| thorough`). | `query` |
| `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` |
| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. | `prompt` |
| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. | `max_tokens` |
@@ -57,6 +57,7 @@ flags for a narrower per-process full server.
| `brain_session_expand` | Expand a raw or summary session recall node to immediate sources and paginated raw turn content. | `id` |
| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — |
| `brain_create_note` | Write an actual vault note file (path + frontmatter + content) atomically inside the vault. Distinct from `brain_note` (log append); refuses traversal, the Brain root, excluded paths, and clobbering. | `path` |
+| `brain_file_context` | Given a file path, surface prior vault work that mentions it (decisions, bug notes, refactor history) by querying the index with path-derived terms. Size gate skips trivial files. Read-only; no LLM. | `file_path` |
| `schema_inspect` | Read-only schema inspection for any view: `view: graph \| lint \| stats \| orphans \| explain_type \| active_pack \| packs`. | `view` (`token` for `explain_type`) |
| `schema_apply_mutations` | Apply audited, locked schema mutations to `Brain/_brain.yaml`. | `mutations` |
| `brain_watchdog` | Probe Brain config, required dirs, and search-index health; optionally apply safe directory remediation. | — |
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 48a863c5..c4065e7d 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.9.0",
+ "version": "1.10.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 29e8870c..2223df44 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.9.0",
+ "version": "1.10.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index c2ab609e..59b1bfec 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.9.0"
+version: "1.10.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 9372d931..f12cd620 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.9.0",
+ "version": "1.10.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index c2ab609e..59b1bfec 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.9.0"
+version: "1.10.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index b2cafcaa..7a392f36 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.9.0"
+version = "1.10.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 4a013cfd..7f46712e 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -43,6 +43,8 @@ import {
cmdBrainLabel,
cmdBrainBridges,
cmdBrainClusters,
+ cmdBrainCoOccurrence,
+ cmdBrainFileContext,
cmdBrainBenchmark,
cmdBrainTune,
cmdBrainAttr,
@@ -205,6 +207,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainBridges(rest);
case "clusters":
return await cmdBrainClusters(rest);
+ case "co-occurrence":
+ return await cmdBrainCoOccurrence(rest);
+ case "file-context":
+ return await cmdBrainFileContext(rest);
case "benchmark":
return await cmdBrainBenchmark(rest);
case "tune":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 0a368c54..4385bb3e 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -50,6 +50,8 @@ Brain verbs (observing memory):
label Controlled-vocabulary classification: assign, remove, show note labels
bridges Embedding-near link proposals: discover, list, accept, dismiss
clusters Link-graph communities: detect and materialize cluster notes
+ co-occurrence Suggest edges between entities co-referenced from the same notes
+ file-context Surface prior vault work that mentions a file path
benchmark Recall quality benchmark: hit@k and MRR over a fixed dataset
tune Self-tuning recall: grid-evaluate, persist, inspect, reset
attr Typed-page attribute fields: assign, remove, show (schema-pack declared)
@@ -303,6 +305,20 @@ export const VERB_HELP: Record<string, string> = {
"by internal degree, shared entities, density, no LLM prose - removes\n" +
"stale generated notes, and records one communities metric. list reads\n" +
"the generated notes back. Fail-soft without an index.\n",
+ "co-occurrence":
+ "usage: o2b brain co-occurrence [--min-co N] [--min-score X] [--limit N] [--write] [--vault <path>] [--json]\n" +
+ "Suggest relationship edges between entities repeatedly co-referenced from\n" +
+ "the same notes, scored by a structural PMI / document-frequency metric over\n" +
+ "the wikilink graph (no natural-language word list, any script). Read-only\n" +
+ "by default; --write persists the Brain/link-graph/co-occurrence.json\n" +
+ "artifact. Already directly-linked pairs are never re-suggested; notes are\n" +
+ "never mutated.\n",
+ "file-context":
+ "usage: o2b brain file-context <file-path> [--limit N] [--min-bytes N] [--vault <path>] [--json]\n" +
+ "Surface prior vault work that mentions a file (decisions, bug notes, refactor\n" +
+ "history) by querying the existing index with terms derived structurally from\n" +
+ "the path (basename + stem, no natural-language processing). A size gate skips\n" +
+ "trivial files (default 1500 bytes) with an explicit reason. Read-only; no LLM.\n",
benchmark:
"usage: o2b brain benchmark run --dataset <path> [--k N] [--expand] [--vault <path>] [--json]\n" +
"Score the vault's live hybrid recall against a fixed query/expected-result\n" +
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index ad1032ef..727d0b06 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -96,6 +96,17 @@ export function parse(
export { CliError } from "../argparse.ts";
export { fail, info, ok, okJson } from "../output.ts";
+
+/**
+ * Usage / argument error: plain message to stderr, exit code 2. Distinct
+ * from `fail()` (exit 1), which is reserved for operational/runtime
+ * failures. Mirrors the exit-2 usage-error contract the brain verbs use
+ * (e.g. `tune`, `bridges`).
+ */
+export function usageError(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return 2;
+}
export { ISO_8601_RE, parseOptionalIsoDate } from "../coerce.ts";
export { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
diff --git a/src/cli/brain/verbs/co-occurrence.ts b/src/cli/brain/verbs/co-occurrence.ts
new file mode 100644
index 00000000..57e69d8f
--- /dev/null
+++ b/src/cli/brain/verbs/co-occurrence.ts
@@ -0,0 +1,94 @@
+import {
+ computeCoOccurrenceSuggestions,
+ writeCoOccurrenceSuggestions,
+} from "../../../core/brain/link-graph/co-occurrence.ts";
+import { brainVerbContext, parse, usageError } from "../helpers.ts";
+
+/**
+ * `o2b brain co-occurrence [--min-co N] [--min-score X] [--limit N] [--write] [--json]`
+ *
+ * Suggest relationship edges between entities that are repeatedly
+ * co-referenced from the same notes, scored by a structural PMI /
+ * document-frequency metric over the wikilink graph. Read-only by
+ * default; `--write` persists the suggestions artifact. Suggestions
+ * never mutate notes. The derivation is language-agnostic - it reads
+ * only link incidence, no natural-language word list.
+ */
+export async function cmdBrainCoOccurrence(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ "min-co": { type: "string" },
+ "min-score": { type: "string" },
+ limit: { type: "string" },
+ write: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const { vault } = brainVerbContext(flags);
+
+ const minCoDocuments = parsePositiveInt(flags["min-co"]);
+ if (minCoDocuments === "invalid") {
+ return usageError("brain co-occurrence: --min-co must be a positive integer");
+ }
+ const limit = parsePositiveInt(flags["limit"]);
+ if (limit === "invalid") {
+ return usageError("brain co-occurrence: --limit must be a positive integer");
+ }
+ let minScore: number | undefined;
+ if (typeof flags["min-score"] === "string") {
+ const parsed = Number(flags["min-score"]);
+ if (!Number.isFinite(parsed)) {
+ return usageError("brain co-occurrence: --min-score must be a finite number");
+ }
+ minScore = parsed;
+ }
+
+ const result = computeCoOccurrenceSuggestions(vault, {
+ ...(minCoDocuments !== undefined ? { minCoDocuments } : {}),
+ ...(minScore !== undefined ? { minScore } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+
+ let writtenPath: string | undefined;
+ if (flags["write"] === true) {
+ writtenPath = writeCoOccurrenceSuggestions(vault, result, {
+ generatedAt: new Date().toISOString(),
+ });
+ }
+
+ if (flags["json"] === true) {
+ process.stdout.write(
+ `${JSON.stringify(
+ {
+ document_count: result.documentCount,
+ suggestions: result.suggestions,
+ ...(writtenPath !== undefined ? { written: writtenPath } : {}),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ return 0;
+ }
+
+ if (result.suggestions.length === 0) {
+ process.stdout.write("no co-occurrence suggestions\n");
+ return 0;
+ }
+ process.stdout.write(
+ `${result.suggestions.length} co-occurrence suggestion(s) over ${result.documentCount} note(s)\n`,
+ );
+ for (const s of result.suggestions) {
+ process.stdout.write(
+ ` ${s.score.toFixed(3)} ${s.left} <-> ${s.right} (co=${s.coDocumentCount})\n`,
+ );
+ }
+ if (writtenPath !== undefined) process.stdout.write(` written: ${writtenPath}\n`);
+ return 0;
+}
+
+function parsePositiveInt(value: unknown): number | undefined | "invalid" {
+ if (typeof value !== "string" || value.length === 0) return undefined;
+ if (!/^[0-9]+$/.test(value)) return "invalid";
+ const parsed = Number.parseInt(value, 10);
+ return parsed >= 1 ? parsed : "invalid";
+}
diff --git a/src/cli/brain/verbs/continuity.ts b/src/cli/brain/verbs/continuity.ts
index 0dddc564..1c95fcaa 100644
--- a/src/cli/brain/verbs/continuity.ts
+++ b/src/cli/brain/verbs/continuity.ts
@@ -14,23 +14,29 @@ import { mkdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { loadNormalizedContinuityRecords } from "../../../core/brain/continuity/read-model.ts";
+import {
+ deriveUsageSignals,
+ rankByUsageDecay,
+} from "../../../core/brain/continuity/usage-signal.ts";
import { renderAtofEvents } from "../../../core/brain/continuity/export-atof.ts";
import {
countSessionlessRecords,
renderAtifTrajectories,
} from "../../../core/brain/continuity/export-atif.ts";
import packageJson from "../../../../package.json" with { type: "json" };
-import { brainVerbContext, fail, parse } from "../helpers.ts";
+import { brainVerbContext, fail, parse, usageError } from "../helpers.ts";
const CLI_VERSION: string = packageJson.version;
const USAGE =
- "usage: o2b brain continuity export --format atof|atif [--session <id>] [--month YYYY-MM] [--out <dir>] [--json]";
+ "usage: o2b brain continuity export --format atof|atif [--session <id>] [--month YYYY-MM] [--out <dir>] [--json]\n" +
+ " o2b brain continuity rank [--kind <kind>] [--limit N] [--json]";
export async function cmdBrainContinuity(argv: string[]): Promise<number> {
const subcommand = argv[0];
- if (subcommand !== "export") return fail(USAGE);
- return exportContinuity(argv.slice(1));
+ if (subcommand === "export") return exportContinuity(argv.slice(1));
+ if (subcommand === "rank") return rankContinuity(argv.slice(1));
+ return fail(USAGE);
}
function exportContinuity(argv: string[]): number {
@@ -97,6 +103,88 @@ function exportContinuity(argv: string[]): number {
return 0;
}
+const DEFAULT_RANK_KIND = "pre_compact_extract";
+const DEFAULT_RANK_LIMIT = 20;
+
+/**
+ * `o2b brain continuity rank`: list working-memory continuity records
+ * ordered by usage-driven decay weight (freshest and most-recalled
+ * first, stale and untouched last). Read-only; the store is never
+ * mutated. Default scope is the `pre_compact_extract` working-memory
+ * kind; `--kind <k>` narrows to another kind and `--all` ranks every
+ * kind.
+ */
+function rankContinuity(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ kind: { type: "string" },
+ limit: { type: "string" },
+ all: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+
+ const all = flags["all"] === true;
+ const kind = typeof flags["kind"] === "string" ? flags["kind"].trim() : DEFAULT_RANK_KIND;
+ let limit = DEFAULT_RANK_LIMIT;
+ if (typeof flags["limit"] === "string") {
+ const parsed = Number(flags["limit"]);
+ if (!Number.isInteger(parsed) || parsed < 1) {
+ return usageError("brain continuity rank: --limit must be a positive integer");
+ }
+ limit = parsed;
+ }
+
+ const vault = brainVerbContext(flags).vault;
+ const records = loadNormalizedContinuityRecords(vault, all ? {} : { kind });
+ const signals = deriveUsageSignals(vault);
+ const ranked = rankByUsageDecay(records, signals, Date.now()).slice(0, limit);
+
+ if (flags["json"] === true) {
+ process.stdout.write(
+ `${JSON.stringify(
+ {
+ scope: all ? "all" : kind,
+ total: records.length,
+ ranked: ranked.map((entry) => ({
+ id: entry.record.id,
+ kind: entry.record.kind,
+ created_at: entry.record.createdAt,
+ weight: entry.weight,
+ access_count: entry.accessCount,
+ last_access_at:
+ entry.lastAccessAtMs !== null ? new Date(entry.lastAccessAtMs).toISOString() : null,
+ })),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ return 0;
+ }
+
+ if (ranked.length === 0) {
+ process.stdout.write(`no ${all ? "" : `${kind} `}continuity records to rank\n`);
+ return 0;
+ }
+ process.stdout.write(`ranked ${ranked.length} of ${records.length} record(s) by usage decay\n`);
+ for (const entry of ranked) {
+ const lastAccess =
+ entry.lastAccessAtMs !== null ? new Date(entry.lastAccessAtMs).toISOString() : "never";
+ const preview = previewText(entry.record.payload);
+ process.stdout.write(
+ ` ${entry.weight.toFixed(3)} ${entry.record.kind} uses=${entry.accessCount} last=${lastAccess}${preview}\n`,
+ );
+ }
+ return 0;
+}
+
+function previewText(payload: Readonly<Record<string, unknown>>): string {
+ const text = payload["text"];
+ if (typeof text !== "string" || text.length === 0) return "";
+ const trimmed = text.length > 80 ? `${text.slice(0, 77)}...` : text;
+ return ` ${trimmed.replace(/\s+/g, " ")}`;
+}
+
function safeName(value: string): string {
return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120);
}
diff --git a/src/cli/brain/verbs/file-context.ts b/src/cli/brain/verbs/file-context.ts
new file mode 100644
index 00000000..83ed4b09
--- /dev/null
+++ b/src/cli/brain/verbs/file-context.ts
@@ -0,0 +1,85 @@
+import { resolveSearchConfig } from "../../../core/search/index.ts";
+import { fileContextRecall } from "../../../core/brain/file-recall.ts";
+import { brainVerbContext, parse, usageError } from "../helpers.ts";
+
+/**
+ * `o2b brain file-context <file-path> [--limit N] [--min-bytes N] [--vault PATH] [--json]`
+ *
+ * Surface prior vault work that mentions a file (decisions, bug notes,
+ * refactor history) by querying the existing index with terms derived
+ * structurally from the path. A size gate skips trivial files.
+ * Read-only; no LLM.
+ */
+export async function cmdBrainFileContext(argv: string[]): Promise<number> {
+ const { positional, flags } = parse(argv, {
+ vault: { type: "string" },
+ limit: { type: "string" },
+ "min-bytes": { type: "string" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+
+ const filePath = positional[0];
+ if (!filePath) {
+ return usageError("brain file-context requires a file path (e.g. src/foo.ts)");
+ }
+ const limit = parsePositiveInt(flags["limit"]);
+ if (limit === "invalid") {
+ return usageError("brain file-context: --limit must be a positive integer");
+ }
+ const minBytes = parseNonNegativeInt(flags["min-bytes"]);
+ if (minBytes === "invalid") {
+ return usageError("brain file-context: --min-bytes must be a non-negative integer");
+ }
+
+ const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });
+ const result = await fileContextRecall(searchConfig, {
+ filePath,
+ ...(limit !== undefined ? { limit } : {}),
+ ...(minBytes !== undefined ? { minBytes } : {}),
+ });
+
+ if (flags["json"] === true) {
+ process.stdout.write(
+ `${JSON.stringify(
+ {
+ file_path: result.filePath,
+ skipped: result.skipped,
+ reason: result.reason,
+ query: result.query,
+ results: result.results.map((r) => ({ path: r.path, title: r.title, score: r.score })),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ return 0;
+ }
+
+ if (result.skipped) {
+ process.stdout.write(`skipped (${result.reason}): ${result.filePath}\n`);
+ return 0;
+ }
+ if (result.results.length === 0) {
+ process.stdout.write(`no prior work found for ${result.filePath}\n`);
+ return 0;
+ }
+ process.stdout.write(`${result.results.length} prior-work hit(s) for ${result.filePath}\n`);
+ for (const r of result.results) {
+ process.stdout.write(` ${r.score.toFixed(3)} ${r.path}\n`);
+ }
+ return 0;
+}
+
+function parsePositiveInt(value: unknown): number | undefined | "invalid" {
+ if (typeof value !== "string" || value.length === 0) return undefined;
+ if (!/^[0-9]+$/.test(value)) return "invalid";
+ const parsed = Number.parseInt(value, 10);
+ return parsed >= 1 ? parsed : "invalid";
+}
+
+function parseNonNegativeInt(value: unknown): number | undefined | "invalid" {
+ if (typeof value !== "string" || value.length === 0) return undefined;
+ if (!/^[0-9]+$/.test(value)) return "invalid";
+ return Number.parseInt(value, 10);
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index fa3fed4e..c3f1c37c 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -27,6 +27,8 @@ export { cmdBrainForesight } from "./foresight.ts";
export { cmdBrainLabel } from "./label.ts";
export { cmdBrainBridges } from "./bridges.ts";
export { cmdBrainClusters } from "./clusters.ts";
+export { cmdBrainCoOccurrence } from "./co-occurrence.ts";
+export { cmdBrainFileContext } from "./file-context.ts";
export { cmdBrainBenchmark } from "./benchmark.ts";
export { cmdBrainTune } from "./tune.ts";
export { cmdBrainAttr } from "./attr.ts";
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 1bff5768..94043ed5 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -173,6 +173,11 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("links", "Normalize wikilink path format across Brain notes"),
command("bridges", "Propose, accept, or dismiss embedding-near bridge links"),
command("clusters", "Detect link-graph communities and materialize cluster notes"),
+ command(
+ "co-occurrence",
+ "Suggest edges between entities co-referenced from the same notes",
+ ),
+ command("file-context", "Surface prior vault work that mentions a file path"),
command("benchmark", "Score recall quality against a fixed query dataset"),
command("tune", "Grid-evaluate and persist self-tuning recall parameters"),
command("profile", "Materialize the compact Brain/profile.md digest"),
diff --git a/src/cli/search.ts b/src/cli/search.ts
index 5cc4c6a4..9df3e10f 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -435,6 +435,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
visibility: { type: "string-array" },
"query-doc": { type: "string" },
expand: { type: "boolean" },
+ profile: { type: "string" },
"evidence-pack": { type: "boolean" },
"include-superseded": { type: "boolean" },
since: { type: "string" },
@@ -498,6 +499,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
...(visibility !== undefined && visibility.length > 0 ? { visibility } : {}),
...(structuredQuery !== undefined ? { structuredQuery } : {}),
...(flags["expand"] === true ? { expand: true } : {}),
+ ...(typeof flags["profile"] === "string" ? { profile: flags["profile"] as string } : {}),
...(flags["evidence-pack"] === true ? { evidencePack: true } : {}),
...(flags["include-superseded"] === true ? { includeSuperseded: true } : {}),
...(typeof flags["since"] === "string" ? { since: flags["since"] as string } : {}),
diff --git a/src/core/brain/continuity/usage-signal.ts b/src/core/brain/continuity/usage-signal.ts
new file mode 100644
index 00000000..7ac24a41
--- /dev/null
+++ b/src/core/brain/continuity/usage-signal.ts
@@ -0,0 +1,227 @@
+/**
+ * Usage-driven working-memory decay (Recall & Working-Memory Quality
+ * Suite, t_c27e1c3f).
+ *
+ * Continuity records are append-only and immutable (deduped by a content
+ * `recordId()`), so they can never be mutated to carry a usage counter.
+ * Decay is therefore a pure, replayable READ-SIDE weight in (0, 1]
+ * derived from two signals:
+ *
+ * - AGE: how long ago the record was created (or last surfaced);
+ * - USAGE: how often and how recently the record's SOURCES were
+ * surfaced, read only from existing `recall_telemetry` records.
+ *
+ * The usage signal is keyed by the surfaced artifact identity (id and
+ * path). A record whose sources never appear in recall telemetry - e.g.
+ * a `pre_compact_extract` decision keyed by session/turn rather than a
+ * vault path - simply has no usage and decays by AGE alone. There is no
+ * fabricated coupling: absent usage is reported as absent, never guessed.
+ *
+ * Read-only by construction; this module never writes to the store.
+ */
+
+import { listRecallTelemetry } from "../recall-telemetry.ts";
+import type { NormalizedContinuityRecord } from "./read-model.ts";
+
+const DAY_MS = 86_400_000;
+
+/** Tunables for the decay curve. All have deterministic defaults. */
+export interface DecayWeightOptions {
+ /** Exponential half-life of the age decay, in days. Default 30. */
+ readonly halfLifeDays?: number;
+ /** Per-log-access multiplier gain on the age-decayed base. Default 0.25. */
+ readonly frequencyGain?: number;
+ /** Lower clamp so a weight is always strictly positive. Default 0.02. */
+ readonly minWeight?: number;
+}
+
+// Working-memory continuity decays faster than search activation
+// (`src/core/search/activation/decay.ts` uses 60 days): a decision or
+// commitment that has gone un-recalled for a month is already a weak
+// working-memory signal, whereas search activation tracks longer-lived
+// document relevance. The two half-lives are intentionally independent.
+const DEFAULT_HALF_LIFE_DAYS = 30;
+const DEFAULT_FREQUENCY_GAIN = 0.25;
+const DEFAULT_MIN_WEIGHT = 0.02;
+
+/** The age and usage signal a decay weight is computed from. */
+export interface UsageSignal {
+ /** Record creation time, epoch ms. */
+ readonly createdAtMs: number;
+ /** How many times the record's sources were surfaced in recall. */
+ readonly accessCount: number;
+ /** Most recent surfacing time, epoch ms, or null when never surfaced. */
+ readonly lastAccessAtMs: number | null;
+}
+
+/**
+ * Pure decay weight in (0, 1]. The reference age is measured from the
+ * last access when the record was ever surfaced, else from creation, so
+ * a recently-used old record stays fresh. Frequency raises the weight
+ * monotonically (bounded by the 1.0 cap); nothing here reads the clock
+ * or any external state, so identical inputs always give identical
+ * output.
+ */
+export function decayWeight(
+ signal: UsageSignal,
+ nowMs: number,
+ opts: DecayWeightOptions = {},
+): number {
+ const halfLifeMs = Math.max(1, (opts.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS) * DAY_MS);
+ const frequencyGain = Math.max(0, opts.frequencyGain ?? DEFAULT_FREQUENCY_GAIN);
+ const minWeight = clamp01(opts.minWeight ?? DEFAULT_MIN_WEIGHT);
+
+ const referenceMs = signal.lastAccessAtMs ?? signal.createdAtMs;
+ const ageMs = Math.max(0, nowMs - referenceMs);
+ const base = Math.pow(0.5, ageMs / halfLifeMs);
+ const frequencyMultiplier = 1 + frequencyGain * Math.log1p(Math.max(0, signal.accessCount));
+ const raw = base * frequencyMultiplier;
+ return Math.min(1, Math.max(minWeight, raw));
+}
+
+/** Aggregated surfacing signal for one artifact identity. */
+export interface SourceUsage {
+ readonly accessCount: number;
+ readonly lastAccessAtMs: number;
+}
+
+interface MutableUsage {
+ accessCount: number;
+ lastAccessAtMs: number;
+}
+
+/** Filter forwarded to the telemetry scan (time window). */
+export interface UsageSignalFilter {
+ readonly since?: string;
+ readonly until?: string;
+}
+
+/**
+ * Build the usage map from `recall_telemetry` records. Each surfaced
+ * artifact contributes one access; its `id` and `path` are registered
+ * against the SAME aggregate object, so a record referencing either key
+ * resolves to one usage entry (never double-counted). Last-access is the
+ * max telemetry timestamp that surfaced the artifact.
+ */
+export function deriveUsageSignals(
+ vault: string,
+ filter: UsageSignalFilter = {},
+): ReadonlyMap<string, SourceUsage> {
+ const byKey = new Map<string, MutableUsage>();
+ const telemetry = listRecallTelemetry(vault, {
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ });
+ for (const record of telemetry) {
+ const ts = Date.parse(record.createdAt);
+ if (Number.isNaN(ts)) continue;
+ for (const artifact of readArtifacts(record.payload["top_artifacts"])) {
+ const id = artifact.id;
+ const path = artifact.path;
+ const existing =
+ (id !== null ? byKey.get(id) : undefined) ?? (path !== null ? byKey.get(path) : undefined);
+ const usage: MutableUsage = existing ?? { accessCount: 0, lastAccessAtMs: 0 };
+ usage.accessCount += 1;
+ usage.lastAccessAtMs = Math.max(usage.lastAccessAtMs, ts);
+ if (id !== null) byKey.set(id, usage);
+ if (path !== null) byKey.set(path, usage);
+ }
+ }
+ return byKey;
+}
+
+/**
+ * Aggregate the usage of a record across its source refs. Refs are
+ * matched by `id` or `path`; the matched usage objects are deduped by
+ * identity so an artifact registered under both keys counts once.
+ * Returns zero access and null last-access when nothing matched - the
+ * age-only decay case.
+ */
+export function usageForRecord(
+ record: NormalizedContinuityRecord,
+ signals: ReadonlyMap<string, SourceUsage>,
+): { readonly accessCount: number; readonly lastAccessAtMs: number | null } {
+ const matched = new Set<SourceUsage>();
+ for (const ref of record.sourceRefs) {
+ const id = readString(ref["id"]);
+ const path = readString(ref["path"]);
+ const usage =
+ (id !== null ? signals.get(id) : undefined) ??
+ (path !== null ? signals.get(path) : undefined);
+ if (usage !== undefined) matched.add(usage);
+ }
+ if (matched.size === 0) return { accessCount: 0, lastAccessAtMs: null };
+ let accessCount = 0;
+ let lastAccessAtMs = 0;
+ for (const usage of matched) {
+ accessCount += usage.accessCount;
+ lastAccessAtMs = Math.max(lastAccessAtMs, usage.lastAccessAtMs);
+ }
+ return { accessCount, lastAccessAtMs };
+}
+
+/** A record paired with its computed decay weight and the usage behind it. */
+export interface DecayRankedRecord {
+ readonly record: NormalizedContinuityRecord;
+ readonly weight: number;
+ readonly accessCount: number;
+ readonly lastAccessAtMs: number | null;
+}
+
+/**
+ * Rank records by descending decay weight. Pure and stable: ties keep
+ * the input order, so a fixed store and `nowMs` always rank identically.
+ */
+export function rankByUsageDecay(
+ records: ReadonlyArray<NormalizedContinuityRecord>,
+ signals: ReadonlyMap<string, SourceUsage>,
+ nowMs: number,
+ opts: DecayWeightOptions = {},
+): ReadonlyArray<DecayRankedRecord> {
+ const ranked = records.map((record, index): DecayRankedRecord & { index: number } => {
+ const usage = usageForRecord(record, signals);
+ const createdAtMs = Date.parse(record.createdAt);
+ const signal: UsageSignal = {
+ createdAtMs: Number.isNaN(createdAtMs) ? nowMs : createdAtMs,
+ accessCount: usage.accessCount,
+ lastAccessAtMs: usage.lastAccessAtMs,
+ };
+ return {
+ index,
+ record,
+ weight: decayWeight(signal, nowMs, opts),
+ accessCount: usage.accessCount,
+ lastAccessAtMs: usage.lastAccessAtMs,
+ };
+ });
+ ranked.sort((a, b) => (b.weight !== a.weight ? b.weight - a.weight : a.index - b.index));
+ return Object.freeze(ranked.map(({ index: _index, ...rest }) => Object.freeze(rest)));
+}
+
+interface ArtifactRef {
+ readonly id: string | null;
+ readonly path: string | null;
+}
+
+function readArtifacts(value: unknown): ReadonlyArray<ArtifactRef> {
+ if (!Array.isArray(value)) return [];
+ const refs: ArtifactRef[] = [];
+ for (const entry of value) {
+ if (entry === null || typeof entry !== "object") continue;
+ const record = entry as Record<string, unknown>;
+ const id = readString(record["id"]);
+ const path = readString(record["path"]);
+ if (id === null && path === null) continue;
+ refs.push({ id, path });
+ }
+ return refs;
+}
+
+function readString(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+function clamp01(value: number): number {
+ if (!Number.isFinite(value)) return 0;
+ return Math.min(1, Math.max(0, value));
+}
diff --git a/src/core/brain/file-recall.ts b/src/core/brain/file-recall.ts
new file mode 100644
index 00000000..f4d1d5a8
--- /dev/null
+++ b/src/core/brain/file-recall.ts
@@ -0,0 +1,120 @@
+/**
+ * File-context recall (Recall & Working-Memory Quality Suite,
+ * t_4f420aca).
+ *
+ * Before an agent reads a file, it is useful to surface what the vault
+ * already knows about that file - prior decisions, bug notes, refactor
+ * history. This module answers that by querying the EXISTING search
+ * index with terms derived structurally from the file path (basename,
+ * stem, parent directory); no LLM, no natural-language processing. A
+ * file-size gate skips trivial files, mirroring the mem0 source's
+ * >= 1500-byte threshold, and returns an explicit reason rather than a
+ * fabricated empty hit.
+ *
+ * Read-only: this never writes to the vault or the index.
+ */
+
+import { statSync } from "node:fs";
+
+import { search } from "../search/search.ts";
+import type { BrainSearchResult, ResolvedSearchConfig } from "../search/types.ts";
+
+const DEFAULT_LIMIT = 5;
+const DEFAULT_MIN_BYTES = 1500;
+
+export interface FileContextOptions {
+ /** Path of the file the caller is about to read (absolute or relative). */
+ readonly filePath: string;
+ /** Maximum prior-work hits to return. Default 5. */
+ readonly limit?: number;
+ /** Skip files smaller than this many bytes. Default 1500. */
+ readonly minBytes?: number;
+}
+
+export interface FileContextResult {
+ readonly filePath: string;
+ /** True when the gate (or an empty query) suppressed the search. */
+ readonly skipped: boolean;
+ /** Why the search was suppressed, or null when it ran. */
+ readonly reason: string | null;
+ /** The query terms derived from the path. */
+ readonly query: string;
+ readonly results: ReadonlyArray<BrainSearchResult>;
+}
+
+/**
+ * Derive search terms from a file path, structurally: the basename and
+ * its extensionless stem, de-duplicated and space-joined. Separator- and
+ * language-agnostic, no word list. The parent directory is deliberately
+ * excluded: keyword retrieval ANDs terms, so a directory name a note
+ * does not mention would suppress an otherwise-relevant hit. The
+ * basename is the canonical "this exact file" signal.
+ */
+export function deriveFileQuery(filePath: string): string {
+ const normalized = filePath.replaceAll("\\", "/").normalize("NFC").trim();
+ const segments = normalized.split("/").filter((s) => s.length > 0);
+ if (segments.length === 0) return "";
+ const base = segments[segments.length - 1]!;
+ const dot = base.lastIndexOf(".");
+ const stem = dot > 0 ? base.slice(0, dot) : base;
+ const unique: string[] = [];
+ for (const term of [base, stem]) {
+ if (term.length > 0 && !unique.includes(term)) unique.push(term);
+ }
+ return unique.join(" ");
+}
+
+/**
+ * Surface prior vault work that mentions `filePath`. Returns an explicit
+ * skip (with a reason) when the file is below the size gate or the path
+ * yields no query terms; otherwise runs a read-only search and returns
+ * its hits.
+ */
+export async function fileContextRecall(
+ config: ResolvedSearchConfig,
+ opts: FileContextOptions,
+): Promise<FileContextResult> {
+ const limit = Math.max(1, Math.min(100, opts.limit ?? DEFAULT_LIMIT));
+ const minBytes = Math.max(0, opts.minBytes ?? DEFAULT_MIN_BYTES);
+ const query = deriveFileQuery(opts.filePath);
+
+ if (query.length === 0) {
+ return frozenResult(opts.filePath, true, "no_query_terms", query, []);
+ }
+
+ // Size gate: skip trivial files. Only applies when the file exists and
+ // can be measured; a missing path (e.g. an external reference) still
+ // searches, since the query is the path itself.
+ const size = fileSize(opts.filePath);
+ if (size !== null && size < minBytes) {
+ return frozenResult(opts.filePath, true, "below_size_gate", query, []);
+ }
+
+ const outcome = await search(config, { query, limit });
+ return frozenResult(opts.filePath, false, null, query, outcome.results);
+}
+
+function fileSize(filePath: string): number | null {
+ try {
+ const stat = statSync(filePath);
+ return stat.isFile() ? stat.size : null;
+ } catch {
+ return null;
+ }
+}
+
+function frozenResult(
+ filePath: string,
+ skipped: boolean,
+ reason: string | null,
+ query: string,
+ results: ReadonlyArray<BrainSearchResult>,
+): FileContextResult {
+ return Object.freeze({
+ filePath,
+ skipped,
+ reason,
+ query,
+ results: Object.freeze([...results]),
+ });
+}
diff --git a/src/core/brain/link-graph/co-occurrence.ts b/src/core/brain/link-graph/co-occurrence.ts
new file mode 100644
index 00000000..e3fbe9d1
--- /dev/null
+++ b/src/core/brain/link-graph/co-occurrence.ts
@@ -0,0 +1,288 @@
+/**
+ * Language-agnostic co-occurrence auto-relate (Recall & Working-Memory
+ * Quality Suite, t_7a632707).
+ *
+ * Entities that are repeatedly co-referenced from the same notes are
+ * statistically related even when no direct link connects them. This
+ * pass reads ONLY link structure - the wikilink targets and typed
+ * frontmatter relations each note already declares - and scores every
+ * co-referenced pair with a PMI / document-frequency metric. There is no
+ * natural-language word list in any language: the signal is purely the
+ * incidence of one canonical target alongside another, so a vault in any
+ * script scores identically for the same structure.
+ *
+ * Output is a derived SUGGESTION artifact, never a note mutation. It
+ * persists under the same convention as the self-tuning artifact:
+ * schema-versioned, dataset-hashed, re-validated on read, fail-soft to
+ * null. A pair already joined by a direct link is never re-suggested.
+ */
+
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+
+import { EXCLUDED_DIRS, extractWikilinks, listVaultPages, parseFrontmatter } from "../../vault.ts";
+import {
+ extractFrontmatterRelations,
+ normalizeRelationTarget,
+} from "../../graph/frontmatter-relations.ts";
+import type { FrontmatterMap } from "../../types.ts";
+import { BRAIN_ROOT_REL } from "../paths.ts";
+
+export const CO_OCCURRENCE_SCHEMA_VERSION = "o2b.cooccurrence.v1";
+
+const DEFAULT_MIN_CO_DOCUMENTS = 2;
+const DEFAULT_MIN_SCORE = 0;
+const DEFAULT_LIMIT = 100;
+const ARTIFACT_REL = join("Brain", "link-graph", "co-occurrence.json");
+
+/** One suggested relationship edge between two co-referenced entities. */
+export interface CoOccurrenceSuggestion {
+ /** Lexicographically smaller canonical entity key. */
+ readonly left: string;
+ /** Lexicographically larger canonical entity key. */
+ readonly right: string;
+ /** Number of notes that referenced both entities. */
+ readonly coDocumentCount: number;
+ /** PMI-style association score (higher = more surprising co-occurrence). */
+ readonly score: number;
+}
+
+export interface CoOccurrenceOptions {
+ /** Minimum notes co-referencing a pair for a suggestion. Default 2. */
+ readonly minCoDocuments?: number;
+ /** Minimum score to keep a suggestion. Default 0. */
+ readonly minScore?: number;
+ /** Maximum suggestions returned, after ranking. Default 100. */
+ readonly limit?: number;
+}
+
+export interface CoOccurrenceResult {
+ readonly schema: string;
+ /** Hash of the link incidence the suggestions were derived from. */
+ readonly vaultHash: string;
+ /** Number of notes that contributed at least one outbound reference. */
+ readonly documentCount: number;
+ readonly suggestions: ReadonlyArray<CoOccurrenceSuggestion>;
+}
+
+/**
+ * Reduce a raw wikilink / relation target to a canonical entity key:
+ * strip brackets/alias/heading (shared with the page contract), then the
+ * directory, the `.md` extension, normalise to NFC, and lowercase. Purely
+ * mechanical - no language assumptions.
+ */
+export function canonicalCoOccurrenceKey(raw: string): string | null {
+ const target = normalizeRelationTarget(raw);
+ if (target === null) return null;
+ const leaf = basename(target.replaceAll("\\", "/"));
+ const withoutExt = leaf.toLowerCase().endsWith(".md") ? leaf.slice(0, -3) : leaf;
+ const normalized = withoutExt.normalize("NFC").toLowerCase().trim();
+ return normalized.length > 0 ? normalized : null;
+}
+
+/**
+ * Compute co-occurrence suggestions over the vault's link structure.
+ * Deterministic for a fixed vault: identical incidence yields identical
+ * suggestions and order.
+ */
+export function computeCoOccurrenceSuggestions(
+ vault: string,
+ opts: CoOccurrenceOptions = {},
+): CoOccurrenceResult {
+ const minCoDocuments = Math.max(1, Math.floor(opts.minCoDocuments ?? DEFAULT_MIN_CO_DOCUMENTS));
+ const minScore = opts.minScore ?? DEFAULT_MIN_SCORE;
+ const limit = Math.max(0, Math.floor(opts.limit ?? DEFAULT_LIMIT));
+
+ const pages = listVaultPages(vault, { skipDirs: [...EXCLUDED_DIRS, BRAIN_ROOT_REL] });
+
+ // pageKey -> set of canonical targets it references (for direct-link
+ // exclusion). targetSets in stable insertion order for hashing.
+ const outboundByPage = new Map<string, Set<string>>();
+ const incidence: Array<{ readonly page: string; readonly targets: string[] }> = [];
+
+ for (const page of pages) {
+ const pageKey = canonicalCoOccurrenceKey(basename(page.path));
+ if (pageKey === null) continue;
+ const targets = referencedKeys(page.metadata, page.path, pageKey);
+ outboundByPage.set(pageKey, new Set(targets));
+ if (targets.length > 0) incidence.push({ page: pageKey, targets });
+ }
+
+ const documentFrequency = new Map<string, number>();
+ const coCount = new Map<string, number>();
+ for (const { targets } of incidence) {
+ const unique = [...new Set(targets)].toSorted();
+ for (const t of unique) documentFrequency.set(t, (documentFrequency.get(t) ?? 0) + 1);
+ for (let i = 0; i < unique.length; i++) {
+ for (let j = i + 1; j < unique.length; j++) {
+ const key = pairKey(unique[i]!, unique[j]!);
+ coCount.set(key, (coCount.get(key) ?? 0) + 1);
+ }
+ }
+ }
+
+ const documentCount = incidence.length;
+ const suggestions: CoOccurrenceSuggestion[] = [];
+ for (const [key, count] of coCount) {
+ if (count < minCoDocuments) continue;
+ const [left, right] = splitPairKey(key);
+ if (isDirectlyLinked(outboundByPage, left, right)) continue;
+ const dfLeft = documentFrequency.get(left) ?? 1;
+ const dfRight = documentFrequency.get(right) ?? 1;
+ const score = round6(Math.log2((count * documentCount) / (dfLeft * dfRight)));
+ if (score < minScore) continue;
+ suggestions.push({ left, right, coDocumentCount: count, score });
+ }
+
+ suggestions.sort(
+ (a, b) =>
+ b.score - a.score ||
+ (a.left < b.left ? -1 : a.left > b.left ? 1 : 0) ||
+ (a.right < b.right ? -1 : a.right > b.right ? 1 : 0),
+ );
+
+ return Object.freeze({
+ schema: CO_OCCURRENCE_SCHEMA_VERSION,
+ vaultHash: hashIncidence(incidence),
+ documentCount,
+ suggestions: Object.freeze(suggestions.slice(0, limit)),
+ });
+}
+
+/** Persist the suggestions artifact. Returns the absolute path written. */
+export function writeCoOccurrenceSuggestions(
+ vault: string,
+ result: CoOccurrenceResult,
+ opts: { readonly generatedAt: string },
+): string {
+ const path = join(vault, ARTIFACT_REL);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ JSON.stringify(
+ {
+ schema: result.schema,
+ generated_at: opts.generatedAt,
+ vault_hash: result.vaultHash,
+ document_count: result.documentCount,
+ suggestions: result.suggestions,
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return path;
+}
+
+/**
+ * Read the persisted suggestions, re-validated against the current
+ * schema version. Fail-soft: missing file, torn JSON, wrong schema, or a
+ * malformed payload all read as null.
+ */
+export function readCoOccurrenceSuggestions(vault: string): CoOccurrenceResult | null {
+ const path = join(vault, ARTIFACT_REL);
+ if (!existsSync(path)) return null;
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (parsed === null || typeof parsed !== "object") return null;
+ const record = parsed as Record<string, unknown>;
+ if (record["schema"] !== CO_OCCURRENCE_SCHEMA_VERSION) return null;
+ const rawSuggestions = record["suggestions"];
+ if (!Array.isArray(rawSuggestions)) return null;
+ const suggestions: CoOccurrenceSuggestion[] = [];
+ for (const raw of rawSuggestions) {
+ const parsedSuggestion = parseSuggestion(raw);
+ if (parsedSuggestion === null) return null;
+ suggestions.push(parsedSuggestion);
+ }
+ const vaultHash = typeof record["vault_hash"] === "string" ? record["vault_hash"] : "";
+ const documentCount =
+ typeof record["document_count"] === "number" ? record["document_count"] : 0;
+ return Object.freeze({
+ schema: CO_OCCURRENCE_SCHEMA_VERSION,
+ vaultHash,
+ documentCount,
+ suggestions: Object.freeze(suggestions),
+ });
+ } catch {
+ return null;
+ }
+}
+
+function referencedKeys(meta: FrontmatterMap, absPath: string, selfKey: string): string[] {
+ const targets = new Set<string>();
+ let body = "";
+ try {
+ [, body] = parseFrontmatter(absPath);
+ } catch {
+ body = "";
+ }
+ for (const raw of extractWikilinks(body)) {
+ const key = canonicalCoOccurrenceKey(raw);
+ if (key !== null && key !== selfKey) targets.add(key);
+ }
+ for (const edge of extractFrontmatterRelations(meta)) {
+ const key = canonicalCoOccurrenceKey(edge.target);
+ if (key !== null && key !== selfKey) targets.add(key);
+ }
+ return [...targets];
+}
+
+function isDirectlyLinked(
+ outboundByPage: ReadonlyMap<string, ReadonlySet<string>>,
+ left: string,
+ right: string,
+): boolean {
+ return (
+ (outboundByPage.get(left)?.has(right) ?? false) ||
+ (outboundByPage.get(right)?.has(left) ?? false)
+ );
+}
+
+// Canonical keys are lowercase NFC text and may contain spaces (a
+// multi-word note title like "Project Alpha" canonicalizes to
+// "project alpha"), so the pair separator must be a character that can
+// never appear in a key. The unit separator (U+001F) never occurs in a
+// note title or path, so it round-trips multi-word keys unambiguously.
+const PAIR_SEPARATOR = String.fromCharCode(0x1f);
+
+function pairKey(a: string, b: string): string {
+ return a < b ? `${a}${PAIR_SEPARATOR}${b}` : `${b}${PAIR_SEPARATOR}${a}`;
+}
+
+function splitPairKey(key: string): readonly [string, string] {
+ const idx = key.indexOf(PAIR_SEPARATOR);
+ return [key.slice(0, idx), key.slice(idx + PAIR_SEPARATOR.length)];
+}
+
+function round6(value: number): number {
+ return Math.round(value * 1_000_000) / 1_000_000;
+}
+
+function hashIncidence(
+ incidence: ReadonlyArray<{ readonly page: string; readonly targets: string[] }>,
+): string {
+ const stable = incidence
+ .map((entry) => [entry.page, [...entry.targets].toSorted()] as const)
+ .toSorted((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
+ return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
+}
+
+function parseSuggestion(raw: unknown): CoOccurrenceSuggestion | null {
+ if (raw === null || typeof raw !== "object") return null;
+ const record = raw as Record<string, unknown>;
+ const left = record["left"];
+ const right = record["right"];
+ const coDocumentCount = record["coDocumentCount"];
+ const score = record["score"];
+ if (
+ typeof left !== "string" ||
+ typeof right !== "string" ||
+ typeof coDocumentCount !== "number" ||
+ typeof score !== "number"
+ ) {
+ return null;
+ }
+ return Object.freeze({ left, right, coDocumentCount, score });
+}
diff --git a/src/core/search/profiles.ts b/src/core/search/profiles.ts
new file mode 100644
index 00000000..24b41497
--- /dev/null
+++ b/src/core/search/profiles.ts
@@ -0,0 +1,75 @@
+/**
+ * Selectable recall profiles (Recall & Working-Memory Quality Suite,
+ * t_98c39dd6 profile-half).
+ *
+ * A profile is a NAMED point in the same bounded parameter space the
+ * self-tuning grid (`tuning.ts`) already ranges over - candidate-pool
+ * multiplier, traversal depth, learned weights, query expansion. It is
+ * applied through the SAME `applyTunedParameters` machinery, so an
+ * operator-chosen profile and a learned grid point stay coherent and
+ * cannot diverge into a parallel knob set.
+ *
+ * Philosophy mirrors `tuning.ts`: the values live in ONE frozen table,
+ * nothing outside the enumerated names can be resolved, and an unknown
+ * name fails loud (a typed `SearchError`) rather than degrading to a
+ * silent default. No profile selected at all leaves `search()` on its
+ * existing config path, byte-for-byte.
+ */
+
+import type { TunedParameters } from "./tuning.ts";
+import { SearchError } from "./types.ts";
+
+/** The selectable profile names, narrowest-to-widest. */
+export const RECALL_PROFILE_NAMES = Object.freeze(["fast", "balanced", "thorough"] as const);
+
+export type RecallProfileName = (typeof RECALL_PROFILE_NAMES)[number];
+
+/**
+ * The fixed profile table. Every tuple stays within the self-tuning
+ * grid bounds (pool ∈ {3,4,5}, depth ∈ {1,2}) so profiles never reach a
+ * parameter the tuner could not also choose. `fast` is the narrowest
+ * point (smallest pool, single hop, no learned weights, no expansion);
+ * `thorough` is the widest; `balanced` sits between.
+ */
+const PROFILE_TABLE: Readonly<Record<RecallProfileName, TunedParameters>> = Object.freeze({
+ fast: Object.freeze({
+ poolMultiplier: 3,
+ traversalDepth: 1,
+ learnedWeights: false,
+ expansion: false,
+ }),
+ balanced: Object.freeze({
+ poolMultiplier: 4,
+ traversalDepth: 1,
+ learnedWeights: true,
+ expansion: false,
+ }),
+ thorough: Object.freeze({
+ poolMultiplier: 5,
+ traversalDepth: 2,
+ learnedWeights: true,
+ expansion: true,
+ }),
+});
+
+/** True only for the enumerated profile names. */
+export function isRecallProfileName(value: unknown): value is RecallProfileName {
+ return (
+ typeof value === "string" && (RECALL_PROFILE_NAMES as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/**
+ * Resolve a profile name to its frozen knob tuple. Unknown name throws a
+ * typed `SearchError("INVALID_INPUT")` whose message lists the valid
+ * names - never a silent fallback to a default profile.
+ */
+export function resolveRecallProfile(name: string): TunedParameters {
+ if (!isRecallProfileName(name)) {
+ throw new SearchError(
+ "INVALID_INPUT",
+ `unknown recall profile: ${name} (expected one of ${RECALL_PROFILE_NAMES.join(", ")})`,
+ );
+ }
+ return PROFILE_TABLE[name];
+}
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index f2c9717e..fd46a1ed 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -68,6 +68,7 @@ import type {
import type { StructuredRecallQueryDocument } from "./structured-query.ts";
import { expandQuery } from "./query-expansion.ts";
import { applyTunedParameters, loadTunedParameters } from "./tuning.ts";
+import { resolveRecallProfile } from "./profiles.ts";
interface SemanticPolicy {
/** caller asked for semantic on or off (true), or accepted the default (false). */
@@ -211,11 +212,16 @@ export async function search(
if (!query) {
throw new SearchError("INVALID_INPUT", "missing required argument: query");
}
- // Opt-in self-tuning (t_ae973491): apply the persisted, re-validated
- // grid point. applyTunedParameters disarms selfTuningEnabled, so the
- // applied config can never recurse. An explicit opts.expand always
- // wins over the tuned expansion default.
- const tuned = config.recall.selfTuningEnabled ? loadTunedParameters(config.vault) : null;
+ // Recall profile (Recall & Working-Memory Quality Suite, t_98c39dd6) and
+ // opt-in self-tuning (t_ae973491) resolve to the SAME knob tuple, applied
+ // through applyTunedParameters (which disarms selfTuningEnabled so the
+ // applied config can never recurse). An explicitly selected profile is an
+ // operator choice and takes precedence over the persisted grid point; with
+ // no profile, behaviour is unchanged - self-tuning applies iff enabled. An
+ // explicit opts.expand always wins over the resolved expansion default.
+ const profileParams = opts.profile !== undefined ? resolveRecallProfile(opts.profile) : null;
+ const tuned =
+ profileParams ?? (config.recall.selfTuningEnabled ? loadTunedParameters(config.vault) : null);
if (tuned !== null) config = applyTunedParameters(config, tuned);
const expandActive = opts.expand ?? (tuned !== null && tuned.expansion);
const limit = Math.max(1, Math.min(100, opts.limit ?? 10));
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 2bcb39a7..30f6e432 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -323,6 +323,15 @@ export interface SearchOptions {
* retrieval. Never silently active.
*/
readonly expand?: boolean;
+ /**
+ * Optional named recall profile (Recall & Working-Memory Quality Suite,
+ * t_98c39dd6): `fast | balanced | thorough` expand to a fixed knob tuple
+ * applied through the same machinery as the self-tuning grid. An explicit
+ * profile takes precedence over a persisted self-tuning grid point. Absent
+ * leaves ranking on the existing config path, byte-for-byte. An unknown
+ * name fails loud (`SearchError("INVALID_INPUT")`). See `profiles.ts`.
+ */
+ readonly profile?: string;
/** Optional per-query or persisted session focus steering. Undefined means load persisted focus. */
readonly sessionFocus?: SearchSessionFocus | null;
/**
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index ea68d8ee..d6705ea3 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -21,6 +21,8 @@ import {
import { normalizeSessionFocus, parseStructuredRecallQueryDocument } from "../core/search/index.ts";
import type { BrainSearchResult, SearchOutcome } from "../core/search/index.ts";
import { searchAcrossVaults } from "../core/search/cross-vault.ts";
+import { RECALL_PROFILE_NAMES } from "../core/search/profiles.ts";
+import { fileContextRecall } from "../core/brain/file-recall.ts";
import { withTimeout } from "../core/search/with-timeout.ts";
import { defaultConfigPath, resolveRecallGateTelemetry } from "../core/config.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
@@ -73,6 +75,12 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
limit: { type: "integer", minimum: 1, maximum: MCP_LIMIT_MAX },
semantic: { type: "boolean" },
keyword_only: { type: "boolean" },
+ profile: {
+ type: "string",
+ enum: [...RECALL_PROFILE_NAMES],
+ description:
+ "Named recall profile (fast|balanced|thorough): a fixed knob preset, preferred over persisted self-tuning. Absent leaves ranking unchanged.",
+ },
explain: {
type: "boolean",
description:
@@ -375,6 +383,7 @@ async function toolBrainSearch(
threshold = raw;
}
const globalSearch = coerceBoolOptional(args, "global") ?? false;
+ const profile = coerceStringOptional(args, "profile", 32);
const pathPrefix = coerceStringOptional(args, "path_prefix", 256);
const evidencePack = coerceBoolOptional(args, "evidence_pack") ?? false;
const includeSuperseded = coerceBoolOptional(args, "include_superseded") ?? false;
@@ -431,6 +440,7 @@ async function toolBrainSearch(
semantic: semantic ?? null,
keywordOnly,
pathPrefix,
+ ...(profile !== undefined ? { profile } : {}),
...(properties !== undefined ? { properties } : {}),
...(visibility !== undefined ? { visibility } : {}),
...(agentScope !== undefined ? { agentScope } : {}),
@@ -834,6 +844,101 @@ async function toolBrainEval(
};
}
+const FILE_CONTEXT_INPUT_SCHEMA: Record<string, unknown> = {
+ type: "object",
+ properties: {
+ file_path: { type: "string", minLength: 1, maxLength: 1024 },
+ limit: { type: "integer", minimum: 1, maximum: MCP_LIMIT_MAX },
+ min_bytes: { type: "integer", minimum: 0, maximum: 10_000_000 },
+ },
+ required: ["file_path"],
+ additionalProperties: false,
+};
+
+const FILE_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {
+ type: "object",
+ properties: {
+ file_path: { type: "string" },
+ skipped: { type: "boolean" },
+ // reason and title are string-or-null; the contract type is a single
+ // value, so the type check is omitted (both nullable shapes pass).
+ reason: {},
+ query: { type: "string" },
+ results: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ path: { type: "string" },
+ title: {},
+ score: { type: "number" },
+ },
+ },
+ },
+ },
+ required: ["file_path", "skipped", "reason", "query", "results"],
+};
+
+async function toolBrainFileContext(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const filePath = coerceStr(args, "file_path");
+ if (filePath === null || filePath.length > 1024) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "argument 'file_path' must be a non-empty string up to 1024 characters",
+ );
+ }
+ const limit = coerceIntInRange(args, "limit", 1, MCP_LIMIT_MAX);
+ const minBytes = coerceIntInRange(args, "min_bytes", 0, 10_000_000);
+
+ const config = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+
+ try {
+ const outcome = await fileContextRecall(config, {
+ filePath,
+ ...(limit !== undefined ? { limit } : {}),
+ ...(minBytes !== undefined ? { minBytes } : {}),
+ });
+ return {
+ file_path: outcome.filePath,
+ skipped: outcome.skipped,
+ reason: outcome.reason,
+ query: outcome.query,
+ results: outcome.results.map((r) => ({
+ path: r.path,
+ title: r.title,
+ score: r.score,
+ })),
+ };
+ } catch (e) {
+ if (e instanceof SearchError) throw searchErrorToMcp(e);
+ if (e instanceof MCPError) throw e;
+ throw new MCPError(INTERNAL_ERROR, e instanceof Error ? e.message : String(e));
+ }
+}
+
+function coerceIntInRange(
+ args: Record<string, unknown>,
+ key: string,
+ min: number,
+ max: number,
+): number | undefined {
+ if (!(key in args) || args[key] === undefined || args[key] === null) return undefined;
+ const raw = args[key];
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < min || raw > max) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument '${key}' must be an integer between ${min} and ${max}`,
+ );
+ }
+ return raw;
+}
+
export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_recall_feedback",
@@ -869,6 +974,15 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
previewBudget: MCP_PREVIEW_BUDGET,
handler: toolBrainEval,
},
+ {
+ name: "brain_file_context",
+ description:
+ "Given a file path, surface prior vault work that mentions it (decisions, bug notes, refactor history) by querying the index with terms derived from the path. A size gate skips trivial files. Read-only; no LLM.",
+ inputSchema: FILE_CONTEXT_INPUT_SCHEMA,
+ outputSchema: FILE_CONTEXT_OUTPUT_SCHEMA,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainFileContext,
+ },
]);
/**
diff --git a/tests/cli/brain-co-occurrence.test.ts b/tests/cli/brain-co-occurrence.test.ts
new file mode 100644
index 00000000..c5b159e0
--- /dev/null
+++ b/tests/cli/brain-co-occurrence.test.ts
@@ -0,0 +1,68 @@
+/**
+ * `o2b brain co-occurrence` (Recall & Working-Memory Quality Suite,
+ * t_7a632707): structural co-occurrence suggestions over the wikilink
+ * graph, read-only by default, optionally persisted with --write.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+function writeNote(rel: string, body: string): void {
+ const abs = join(vault, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, body, "utf8");
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cooccurrence-cli-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+ writeNote("notes/m1.md", "# M1\n\nSee [[alpha]] and [[beta]].\n");
+ writeNote("notes/m2.md", "# M2\n\nAlso [[alpha]] with [[beta]].\n");
+ writeNote("notes/m3.md", "# M3\n\nDifferent [[gamma]] and [[delta]].\n");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+describe("o2b brain co-occurrence", () => {
+ test("suggests the co-referenced pair as JSON", async () => {
+ const out = await runCli(["brain", "co-occurrence", "--min-co", "2", "--json"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ const parsed = JSON.parse(out.stdout) as {
+ suggestions: Array<{ left: string; right: string; coDocumentCount: number }>;
+ };
+ const pair = parsed.suggestions.find((s) => s.left === "alpha" && s.right === "beta");
+ expect(pair).toBeDefined();
+ expect(pair!.coDocumentCount).toBe(2);
+ });
+
+ test("--write persists the suggestions artifact", async () => {
+ const out = await runCli(["brain", "co-occurrence", "--min-co", "2", "--write", "--json"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ expect(existsSync(join(vault, "Brain", "link-graph", "co-occurrence.json"))).toBe(true);
+ });
+
+ test("a bad --min-co fails with a usage error", async () => {
+ const bad = await runCli(["brain", "co-occurrence", "--min-co", "-1"], { env: env() });
+ expect(bad.returncode).not.toBe(0);
+ });
+});
diff --git a/tests/cli/brain-continuity.test.ts b/tests/cli/brain-continuity.test.ts
index c941dbf7..db603a9d 100644
--- a/tests/cli/brain-continuity.test.ts
+++ b/tests/cli/brain-continuity.test.ts
@@ -10,6 +10,7 @@ import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { emitRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -98,3 +99,44 @@ describe("o2b brain continuity export", () => {
expect(badMonth.returncode).not.toBe(0);
});
});
+
+describe("o2b brain continuity rank", () => {
+ test("ranks records by usage decay, recalled source above untouched", async () => {
+ // A surfaced artifact gives its receipt a usage signal; an equally-aged
+ // receipt whose source was never surfaced has none and ranks lower.
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-06-13T00:00:00.000Z",
+ host: "t",
+ mode: "search",
+ status: "ok",
+ durationMs: 1,
+ resultCount: 1,
+ topArtifacts: [{ id: "fresh", path: "Brain/notes/fresh.md", score: 0.9 }],
+ });
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-01T00:00:00.000Z",
+ sourceRefs: [{ id: "fresh", path: "Brain/notes/fresh.md" }],
+ });
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-01T00:00:00.000Z",
+ sourceRefs: [{ id: "stale", path: "Brain/notes/stale.md" }],
+ });
+ const out = await runCli(["brain", "continuity", "rank", "--all", "--json"], { env: env() });
+ expect(out.returncode).toBe(0);
+ const parsed = JSON.parse(out.stdout) as {
+ scope: string;
+ ranked: Array<{ id: string; weight: number; access_count: number }>;
+ };
+ expect(parsed.scope).toBe("all");
+ const fresh = parsed.ranked.find((r) => r.access_count === 1)!;
+ const stale = parsed.ranked.find((r) => r.access_count === 0 && r.id !== fresh.id)!;
+ expect(fresh.weight).toBeGreaterThan(stale.weight);
+ });
+
+ test("a bad --limit fails with a usage error", async () => {
+ const bad = await runCli(["brain", "continuity", "rank", "--limit", "0"], { env: env() });
+ expect(bad.returncode).not.toBe(0);
+ });
+});
diff --git a/tests/core/brain/continuity/usage-signal.test.ts b/tests/core/brain/continuity/usage-signal.test.ts
new file mode 100644
index 00000000..8ffab0ec
--- /dev/null
+++ b/tests/core/brain/continuity/usage-signal.test.ts
@@ -0,0 +1,199 @@
+/**
+ * Usage-driven working-memory decay (Recall & Working-Memory Quality
+ * Suite, t_c27e1c3f).
+ *
+ * Continuity records are append-only and immutable, so decay is a pure
+ * READ-SIDE weight: never a mutation. The usage signal is derived only
+ * from existing `recall_telemetry` records (their surfaced artifacts);
+ * a record whose sources were never surfaced has no usage signal and
+ * decays by age alone - no fabricated coupling. The weight is a pure,
+ * replayable function of (age, access count, last-access age).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { emitRecallTelemetry } from "../../../../src/core/brain/recall-telemetry.ts";
+import { appendContinuityRecord } from "../../../../src/core/brain/continuity/store.ts";
+import { loadNormalizedContinuityRecords } from "../../../../src/core/brain/continuity/read-model.ts";
+import {
+ decayWeight,
+ deriveUsageSignals,
+ rankByUsageDecay,
+ usageForRecord,
+} from "../../../../src/core/brain/continuity/usage-signal.ts";
+
+const DAY = 86_400_000;
+const NOW = Date.parse("2026-06-14T00:00:00.000Z");
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-usage-signal-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("decayWeight (pure)", () => {
+ test("is bounded in (0, 1] and equals 1 for a just-touched record", () => {
+ const w = decayWeight({ createdAtMs: NOW, accessCount: 0, lastAccessAtMs: NOW }, NOW);
+ expect(w).toBeLessThanOrEqual(1);
+ expect(w).toBeGreaterThan(0);
+ expect(w).toBe(1);
+ });
+
+ test("decays monotonically as the reference age grows", () => {
+ const fresh = decayWeight(
+ { createdAtMs: NOW - 1 * DAY, accessCount: 0, lastAccessAtMs: null },
+ NOW,
+ );
+ const mid = decayWeight(
+ { createdAtMs: NOW - 30 * DAY, accessCount: 0, lastAccessAtMs: null },
+ NOW,
+ );
+ const stale = decayWeight(
+ { createdAtMs: NOW - 365 * DAY, accessCount: 0, lastAccessAtMs: null },
+ NOW,
+ );
+ expect(fresh).toBeGreaterThan(mid);
+ expect(mid).toBeGreaterThan(stale);
+ expect(stale).toBeGreaterThan(0);
+ });
+
+ test("a recent access outweighs old creation (recency of use wins)", () => {
+ const old = NOW - 200 * DAY;
+ const usedRecently = decayWeight(
+ { createdAtMs: old, accessCount: 5, lastAccessAtMs: NOW - 1 * DAY },
+ NOW,
+ );
+ const neverUsed = decayWeight({ createdAtMs: old, accessCount: 0, lastAccessAtMs: null }, NOW);
+ expect(usedRecently).toBeGreaterThan(neverUsed);
+ });
+
+ test("more accesses never lower the weight at equal recency", () => {
+ const ref = NOW - 60 * DAY;
+ const few = decayWeight({ createdAtMs: ref, accessCount: 1, lastAccessAtMs: ref }, NOW);
+ const many = decayWeight({ createdAtMs: ref, accessCount: 20, lastAccessAtMs: ref }, NOW);
+ expect(many).toBeGreaterThanOrEqual(few);
+ });
+
+ test("is deterministic: identical inputs give identical output", () => {
+ const sig = { createdAtMs: NOW - 17 * DAY, accessCount: 3, lastAccessAtMs: NOW - 5 * DAY };
+ expect(decayWeight(sig, NOW)).toBe(decayWeight(sig, NOW));
+ });
+});
+
+describe("deriveUsageSignals + usageForRecord", () => {
+ test("counts surfaced artifacts by id and path with last-access recency", () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-06-10T00:00:00.000Z",
+ host: "t",
+ mode: "search",
+ status: "ok",
+ durationMs: 1,
+ resultCount: 1,
+ topArtifacts: [{ id: "note-x", path: "Brain/notes/x.md", score: 0.9 }],
+ });
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-06-12T00:00:00.000Z",
+ host: "t",
+ mode: "search",
+ status: "ok",
+ durationMs: 1,
+ resultCount: 1,
+ topArtifacts: [{ id: "note-x", path: "Brain/notes/x.md", score: 0.8 }],
+ });
+ const signals = deriveUsageSignals(vault);
+ const byId = signals.get("note-x");
+ const byPath = signals.get("Brain/notes/x.md");
+ expect(byId).toBeDefined();
+ expect(byId!.accessCount).toBe(2);
+ expect(byId!.lastAccessAtMs).toBe(Date.parse("2026-06-12T00:00:00.000Z"));
+ // id and path resolve to the same aggregate (one artifact, not two).
+ expect(byPath).toBe(byId);
+ });
+
+ test("a record whose source was surfaced gets the aggregated usage", () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-06-12T00:00:00.000Z",
+ host: "t",
+ mode: "search",
+ status: "ok",
+ durationMs: 1,
+ resultCount: 1,
+ topArtifacts: [{ id: "note-x", path: "Brain/notes/x.md", score: 0.8 }],
+ });
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-06-01T00:00:00.000Z",
+ sourceRefs: [{ id: "note-x", path: "Brain/notes/x.md" }],
+ });
+ const signals = deriveUsageSignals(vault);
+ const records = loadNormalizedContinuityRecords(vault, { kind: "context_receipt" });
+ const usage = usageForRecord(records[0]!, signals);
+ expect(usage.accessCount).toBe(1);
+ expect(usage.lastAccessAtMs).toBe(Date.parse("2026-06-12T00:00:00.000Z"));
+ });
+
+ test("a session-scoped record with no surfaced source decays by age alone", () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-06-12T00:00:00.000Z",
+ host: "t",
+ mode: "search",
+ status: "ok",
+ durationMs: 1,
+ resultCount: 1,
+ topArtifacts: [{ id: "note-x", path: "Brain/notes/x.md", score: 0.8 }],
+ });
+ // Working-memory extracts reference session/turn ids, NOT vault paths,
+ // so they never match a surfaced artifact: usage is empty (no fabricated
+ // link), and the record decays purely by age.
+ appendContinuityRecord(vault, {
+ kind: "pre_compact_extract",
+ createdAt: "2026-06-01T00:00:00.000Z",
+ sourceRefs: [{ id: "sess-1" }],
+ payload: { extract_type: "decision", text: "ship the suite", session_id: "sess-1" },
+ });
+ const signals = deriveUsageSignals(vault);
+ const records = loadNormalizedContinuityRecords(vault, { kind: "pre_compact_extract" });
+ const usage = usageForRecord(records[0]!, signals);
+ expect(usage.accessCount).toBe(0);
+ expect(usage.lastAccessAtMs).toBeNull();
+ });
+});
+
+describe("rankByUsageDecay", () => {
+ test("a frequently and recently used record outranks a stale one", () => {
+ emitRecallTelemetry(vault, {
+ createdAt: "2026-06-13T00:00:00.000Z",
+ host: "t",
+ mode: "search",
+ status: "ok",
+ durationMs: 1,
+ resultCount: 1,
+ topArtifacts: [{ id: "fresh", path: "Brain/notes/fresh.md", score: 0.9 }],
+ });
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-01T00:00:00.000Z",
+ sourceRefs: [{ id: "fresh", path: "Brain/notes/fresh.md" }],
+ });
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-05-01T00:00:00.000Z",
+ sourceRefs: [{ id: "stale", path: "Brain/notes/stale.md" }],
+ });
+ const signals = deriveUsageSignals(vault);
+ const records = loadNormalizedContinuityRecords(vault, { kind: "context_receipt" });
+ const ranked = rankByUsageDecay(records, signals, NOW);
+ expect(ranked).toHaveLength(2);
+ expect(ranked[0]!.record.sourceRefs[0]!["id"]).toBe("fresh");
+ expect(ranked[0]!.weight).toBeGreaterThan(ranked[1]!.weight);
+ // Ranking is sorted descending by weight.
+ expect(ranked[0]!.weight).toBeGreaterThanOrEqual(ranked[1]!.weight);
+ });
+});
diff --git a/tests/core/brain/file-recall.test.ts b/tests/core/brain/file-recall.test.ts
new file mode 100644
index 00000000..bcb7805c
--- /dev/null
+++ b/tests/core/brain/file-recall.test.ts
@@ -0,0 +1,89 @@
+/**
+ * File-context recall (Recall & Working-Memory Quality Suite,
+ * t_4f420aca): given a file path, surface prior vault work that mentions
+ * it, by querying the existing search index with terms derived
+ * structurally from the path. No LLM. A file-size gate skips trivial
+ * files, mirroring the mem0 source's >= 1500-byte threshold.
+ */
+
+import { test, expect, beforeEach, afterEach, describe } from "bun:test";
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { fileContextRecall, deriveFileQuery } from "../../../src/core/brain/file-recall.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("file-recall"));
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("deriveFileQuery", () => {
+ test("derives basename and stem terms structurally", () => {
+ const q = deriveFileQuery("src/services/auth-token.ts");
+ expect(q).toContain("auth-token.ts");
+ expect(q).toContain("auth-token");
+ // The parent directory is intentionally excluded (it would AND-suppress hits).
+ expect(q).not.toContain("services");
+ });
+
+ test("is deterministic and separator-agnostic", () => {
+ expect(deriveFileQuery("a/b/c.ts")).toBe(deriveFileQuery("a\\b\\c.ts"));
+ });
+});
+
+describe("fileContextRecall", () => {
+ test("surfaces a note that documents prior work on the file", async () => {
+ writeMd(
+ vault,
+ "Brain/notes/auth-decision.md",
+ "# Auth decision\n\nWe refactored auth-token.ts to rotate keys hourly.\n",
+ );
+ writeMd(vault, "Brain/notes/unrelated.md", "# Unrelated\n\nMarsh cartography notes.\n");
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ await indexVault(config);
+
+ const result = await fileContextRecall(config, { filePath: "src/services/auth-token.ts" });
+ expect(result.skipped).toBe(false);
+ expect(result.results.some((r) => r.path === "Brain/notes/auth-decision.md")).toBe(true);
+ });
+
+ test("skips a file below the size gate with an explicit reason", async () => {
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ await indexVault(config);
+ const small = join(vault, "small.ts");
+ writeFileSync(small, "x\n");
+ const result = await fileContextRecall(config, { filePath: small, minBytes: 1500 });
+ expect(result.skipped).toBe(true);
+ expect(result.reason).toBe("below_size_gate");
+ expect(result.results).toHaveLength(0);
+ });
+
+ test("a file at or above the size gate is not skipped", async () => {
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ await indexVault(config);
+ const big = join(vault, "big.ts");
+ writeFileSync(big, "x".repeat(2000));
+ const result = await fileContextRecall(config, { filePath: big, minBytes: 1500 });
+ expect(result.skipped).toBe(false);
+ });
+
+ test("no matching prior work returns an empty, non-skipped result", async () => {
+ writeMd(vault, "Brain/notes/unrelated.md", "# Unrelated\n\nMarsh cartography notes.\n");
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ await indexVault(config);
+ const result = await fileContextRecall(config, {
+ filePath: "src/zzz/nonexistent-widget.ts",
+ });
+ expect(result.skipped).toBe(false);
+ expect(result.results).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/link-graph/co-occurrence.test.ts b/tests/core/brain/link-graph/co-occurrence.test.ts
new file mode 100644
index 00000000..61959dfa
--- /dev/null
+++ b/tests/core/brain/link-graph/co-occurrence.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Language-agnostic co-occurrence auto-relate (Recall & Working-Memory
+ * Quality Suite, t_7a632707).
+ *
+ * Entities that are repeatedly co-referenced from the same notes get a
+ * suggested relationship edge, scored by a structural PMI/document-
+ * frequency metric over the wikilink graph. The derivation reads only
+ * link structure - no natural-language word list in any language - so a
+ * vault written in a non-Latin script produces structurally identical
+ * scores. Suggestions never mutate notes; they persist to a versioned,
+ * hashed artifact that re-validates on read and fails soft.
+ */
+
+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 {
+ CO_OCCURRENCE_SCHEMA_VERSION,
+ computeCoOccurrenceSuggestions,
+ readCoOccurrenceSuggestions,
+ writeCoOccurrenceSuggestions,
+} from "../../../../src/core/brain/link-graph/co-occurrence.ts";
+
+let vault: string;
+
+function writeNote(rel: string, body: string): void {
+ const abs = join(vault, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, body, "utf8");
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-cooccurrence-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("computeCoOccurrenceSuggestions", () => {
+ test("two notes co-referencing the same pair yield one suggestion", () => {
+ writeNote("notes/m1.md", "# M1\n\nSee [[alpha]] and [[beta]].\n");
+ writeNote("notes/m2.md", "# M2\n\nAlso [[alpha]] with [[beta]] again.\n");
+ // An unrelated note enlarges the document universe so the alpha/beta
+ // co-occurrence is more than chance (PMI > 0).
+ writeNote("notes/m3.md", "# M3\n\nDifferent [[gamma]] and [[delta]].\n");
+ writeNote("notes/alpha.md", "# Alpha\n\nStandalone.\n");
+ writeNote("notes/beta.md", "# Beta\n\nStandalone.\n");
+ const result = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+ const pair = result.suggestions.find((s) => s.left === "alpha" && s.right === "beta");
+ expect(pair).toBeDefined();
+ expect(pair!.coDocumentCount).toBe(2);
+ expect(pair!.score).toBeGreaterThan(0);
+ });
+
+ test("a pair co-referenced only once is below the min-co-document floor", () => {
+ writeNote("notes/m1.md", "# M1\n\nSee [[alpha]] and [[beta]].\n");
+ const result = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+ expect(result.suggestions.some((s) => s.left === "alpha" && s.right === "beta")).toBe(false);
+ });
+
+ test("an already directly-linked pair is not re-suggested", () => {
+ // alpha links beta directly, so a co-reference must not re-propose them.
+ writeNote("notes/m1.md", "# M1\n\nSee [[alpha]] and [[beta]].\n");
+ writeNote("notes/alpha.md", "# Alpha\n\nLinks [[beta]] directly.\n");
+ writeNote("notes/beta.md", "# Beta\n\nStandalone.\n");
+ const result = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 1 });
+ expect(result.suggestions.some((s) => s.left === "alpha" && s.right === "beta")).toBe(false);
+ });
+
+ test("scores are language-agnostic: a non-Latin vault scores identically", () => {
+ writeNote("notes/m1.md", "# M1\n\nSee [[alpha]] and [[beta]].\n");
+ writeNote("notes/m2.md", "# M2\n\nAlso [[alpha]] with [[beta]].\n");
+ writeNote("notes/m3.md", "# M3\n\nDifferent [[gamma]] and [[delta]].\n");
+ const latin = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+
+ rmSync(vault, { recursive: true, force: true });
+ vault = mkdtempSync(join(tmpdir(), "o2b-cooccurrence-cjk-"));
+ writeNote("notes/m1.md", "# M1\n\nSee [[行列]] and [[共鳴]].\n");
+ writeNote("notes/m2.md", "# M2\n\nAlso [[行列]] with [[共鳴]].\n");
+ writeNote("notes/m3.md", "# M3\n\nDifferent [[勾配]] and [[時系列]].\n");
+ const cjk = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+
+ expect(latin.suggestions[0]!.score).toBeGreaterThan(0);
+ expect(cjk.suggestions).toHaveLength(latin.suggestions.length);
+ expect(cjk.suggestions[0]!.coDocumentCount).toBe(latin.suggestions[0]!.coDocumentCount);
+ expect(cjk.suggestions[0]!.score).toBe(latin.suggestions[0]!.score);
+ });
+
+ test("is deterministic: identical vault yields identical suggestions and order", () => {
+ writeNote("notes/m1.md", "# M1\n\n[[a]] [[b]] [[c]]\n");
+ writeNote("notes/m2.md", "# M2\n\n[[a]] [[b]] [[c]]\n");
+ const first = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+ const second = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+ expect(JSON.stringify(first.suggestions)).toBe(JSON.stringify(second.suggestions));
+ });
+
+ test("multi-word entity names round-trip through the pair key intact", () => {
+ // Canonical keys keep internal spaces; the pair key/split must not
+ // corrupt them (regression: a single-space separator split at the first
+ // space and mangled multi-word titles).
+ writeNote("notes/m1.md", "# M1\n\nSee [[Project Alpha]] and [[Meeting Notes]].\n");
+ writeNote("notes/m2.md", "# M2\n\nAlso [[Project Alpha]] with [[Meeting Notes]].\n");
+ writeNote("notes/m3.md", "# M3\n\nDifferent [[gamma]] and [[delta]].\n");
+ const result = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+ const pair = result.suggestions.find(
+ (s) => s.left === "meeting notes" && s.right === "project alpha",
+ );
+ expect(pair).toBeDefined();
+ expect(pair!.coDocumentCount).toBe(2);
+ });
+
+ test("the limit caps the number of suggestions", () => {
+ writeNote("notes/m1.md", "# M1\n\n[[a]] [[b]] [[c]] [[d]]\n");
+ writeNote("notes/m2.md", "# M2\n\n[[a]] [[b]] [[c]] [[d]]\n");
+ const result = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2, limit: 2 });
+ expect(result.suggestions.length).toBeLessThanOrEqual(2);
+ });
+});
+
+describe("persistence", () => {
+ test("write then read round-trips the suggestions", () => {
+ writeNote("notes/m1.md", "# M1\n\n[[alpha]] [[beta]]\n");
+ writeNote("notes/m2.md", "# M2\n\n[[alpha]] [[beta]]\n");
+ const result = computeCoOccurrenceSuggestions(vault, { minCoDocuments: 2 });
+ writeCoOccurrenceSuggestions(vault, result, { generatedAt: "2026-06-14T00:00:00.000Z" });
+ const reloaded = readCoOccurrenceSuggestions(vault);
+ expect(reloaded).not.toBeNull();
+ expect(reloaded!.schema).toBe(CO_OCCURRENCE_SCHEMA_VERSION);
+ expect(JSON.stringify(reloaded!.suggestions)).toBe(JSON.stringify(result.suggestions));
+ });
+
+ test("a missing artifact reads as null (fail-soft)", () => {
+ expect(readCoOccurrenceSuggestions(vault)).toBeNull();
+ });
+
+ test("a corrupt artifact reads as null (fail-soft)", () => {
+ mkdirSync(join(vault, "Brain", "link-graph"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "link-graph", "co-occurrence.json"), "{not json", "utf8");
+ expect(readCoOccurrenceSuggestions(vault)).toBeNull();
+ });
+
+ test("a drifted schema version reads as null", () => {
+ mkdirSync(join(vault, "Brain", "link-graph"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "link-graph", "co-occurrence.json"),
+ JSON.stringify({ schema: "o2b.cooccurrence.v999", suggestions: [] }),
+ "utf8",
+ );
+ expect(readCoOccurrenceSuggestions(vault)).toBeNull();
+ });
+});
diff --git a/tests/core/search/profiles.test.ts b/tests/core/search/profiles.test.ts
new file mode 100644
index 00000000..13379300
--- /dev/null
+++ b/tests/core/search/profiles.test.ts
@@ -0,0 +1,74 @@
+/**
+ * Selectable recall profiles (Recall & Working-Memory Quality Suite,
+ * t_98c39dd6 profile-half). A profile name expands to a knob tuple over
+ * the SAME bounded axes the self-tuning grid ranges over, so profiles
+ * and self-tuning stay coherent. Unknown names fail loud; no silent
+ * default.
+ */
+
+import { expect, test } from "bun:test";
+
+import {
+ RECALL_PROFILE_NAMES,
+ isRecallProfileName,
+ resolveRecallProfile,
+} from "../../../src/core/search/profiles.ts";
+import {
+ TUNING_POOL_MULTIPLIERS,
+ TUNING_TRAVERSAL_DEPTHS,
+} from "../../../src/core/search/tuning.ts";
+import { SearchError } from "../../../src/core/search/types.ts";
+
+test("the three profiles resolve to distinct knob tuples", () => {
+ const fast = resolveRecallProfile("fast");
+ const balanced = resolveRecallProfile("balanced");
+ const thorough = resolveRecallProfile("thorough");
+ // fast is the narrowest, thorough the widest, across every axis.
+ expect(fast.poolMultiplier).toBeLessThanOrEqual(balanced.poolMultiplier);
+ expect(balanced.poolMultiplier).toBeLessThanOrEqual(thorough.poolMultiplier);
+ expect(fast.traversalDepth).toBeLessThanOrEqual(thorough.traversalDepth);
+ expect(fast.expansion).toBe(false);
+ expect(thorough.expansion).toBe(true);
+ // The three are genuinely different points.
+ const serialized = new Set([fast, balanced, thorough].map((p) => JSON.stringify(p)));
+ expect(serialized.size).toBe(3);
+});
+
+test("every profile stays inside the self-tuning grid bounds", () => {
+ for (const name of RECALL_PROFILE_NAMES) {
+ const p = resolveRecallProfile(name);
+ expect(TUNING_POOL_MULTIPLIERS).toContain(p.poolMultiplier);
+ expect(TUNING_TRAVERSAL_DEPTHS).toContain(p.traversalDepth);
+ expect(typeof p.learnedWeights).toBe("boolean");
+ expect(typeof p.expansion).toBe("boolean");
+ }
+});
+
+test("an unknown profile name fails loud with a typed SearchError", () => {
+ expect(() => resolveRecallProfile("turbo")).toThrow(SearchError);
+ try {
+ resolveRecallProfile("turbo");
+ } catch (e) {
+ expect(e).toBeInstanceOf(SearchError);
+ expect((e as SearchError).code).toBe("INVALID_INPUT");
+ // The message lists the valid names so the caller can recover.
+ for (const name of RECALL_PROFILE_NAMES) {
+ expect((e as SearchError).message).toContain(name);
+ }
+ }
+});
+
+test("isRecallProfileName narrows only the three known names", () => {
+ expect(isRecallProfileName("fast")).toBe(true);
+ expect(isRecallProfileName("balanced")).toBe(true);
+ expect(isRecallProfileName("thorough")).toBe(true);
+ expect(isRecallProfileName("")).toBe(false);
+ expect(isRecallProfileName("FAST")).toBe(false);
+ expect(isRecallProfileName(null)).toBe(false);
+ expect(isRecallProfileName(42)).toBe(false);
+});
+
+test("the resolved tuple is frozen so callers cannot mutate the shared table", () => {
+ const p = resolveRecallProfile("balanced");
+ expect(Object.isFrozen(p)).toBe(true);
+});
diff --git a/tests/core/search/recall-profile.integration.test.ts b/tests/core/search/recall-profile.integration.test.ts
new file mode 100644
index 00000000..8452d3a3
--- /dev/null
+++ b/tests/core/search/recall-profile.integration.test.ts
@@ -0,0 +1,126 @@
+/**
+ * Selectable recall profiles end-to-end through `search()` (Recall &
+ * Working-Memory Quality Suite, t_98c39dd6 profile-half).
+ *
+ * A profile resolves to the same knob tuple the self-tuning grid ranges
+ * over and is applied through `applyTunedParameters`. The observable
+ * signal here is traversal depth (`maxHops`): `fast` is single-hop,
+ * `thorough` is two-hop, so a note two links away from the query anchor
+ * is reached under `thorough` but not under `fast`. An explicitly
+ * selected profile takes precedence over a persisted self-tuning grid
+ * point; an unknown profile fails loud before any store I/O.
+ */
+
+import { test, expect, beforeEach, afterEach, describe } from "bun:test";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { search } from "../../../src/core/search/search.ts";
+import { SearchError } from "../../../src/core/search/types.ts";
+import { TUNING_SCHEMA_VERSION } from "../../../src/core/search/tuning.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+const QUERY = "lattice resonance survey";
+const FAR = "Brain/notes/far.md";
+
+/**
+ * anchor (matches the query) -> mid -> far. `far` shares no query terms,
+ * so it can only surface via two hops of link traversal.
+ */
+async function seedChain(): Promise<void> {
+ // Wikilink targets are full vault-relative paths so they resolve to the
+ // linked document (the store resolves links by exact path equality).
+ writeMd(
+ vault,
+ "Brain/notes/anchor.md",
+ "# Anchor\n\nLattice resonance survey anchor. See [[Brain/notes/mid.md|mid]].\n",
+ );
+ writeMd(vault, "Brain/notes/mid.md", "# Mid\n\nBridge node. See [[Brain/notes/far.md|far]].\n");
+ writeMd(vault, "Brain/notes/far.md", "# Far\n\nDistant unrelated cartography.\n");
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ await indexVault(config);
+}
+
+function persistTunedDepthOne(): void {
+ const dir = join(vault, "Brain", "search");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "tuning.json"),
+ JSON.stringify({
+ schema: TUNING_SCHEMA_VERSION,
+ chosen: {
+ poolMultiplier: 5,
+ traversalDepth: 1,
+ learnedWeights: false,
+ expansion: false,
+ },
+ evaluated: [],
+ dataset_hash: "deadbeef",
+ evaluated_at: "2026-06-14T00:00:00.000Z",
+ }) + "\n",
+ );
+}
+
+beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("recall-profile"));
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("recall profiles through search()", () => {
+ test("the three profile names are all accepted and return the anchor hit", async () => {
+ await seedChain();
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ const outcomes = await Promise.all(
+ ["fast", "balanced", "thorough"].map((profile) =>
+ search(config, { query: QUERY, limit: 10, profile }),
+ ),
+ );
+ for (const outcome of outcomes) {
+ expect(outcome.results.some((r) => r.path === "Brain/notes/anchor.md")).toBe(true);
+ }
+ });
+
+ test("thorough (two-hop) reaches a note fast (one-hop) cannot", async () => {
+ await seedChain();
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ const fast = await search(config, { query: QUERY, limit: 10, profile: "fast" });
+ const thorough = await search(config, { query: QUERY, limit: 10, profile: "thorough" });
+ expect(fast.results.some((r) => r.path === FAR)).toBe(false);
+ expect(thorough.results.some((r) => r.path === FAR)).toBe(true);
+ });
+
+ test("an explicit profile takes precedence over a persisted self-tuning grid point", async () => {
+ await seedChain();
+ persistTunedDepthOne();
+ // Self-tuning is armed and the persisted grid point is depth-1, but the
+ // explicit thorough profile (depth-2) must win, so far is still reached.
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1, selfTuningEnabled: true });
+ const outcome = await search(config, { query: QUERY, limit: 10, profile: "thorough" });
+ expect(outcome.results.some((r) => r.path === FAR)).toBe(true);
+ });
+
+ test("with no profile and self-tuning off, the far note stays unreached (byte-identical default)", async () => {
+ await seedChain();
+ // Default maxHops in the fixture is 1, so the two-hop far note is out of
+ // reach when no profile widens traversal - the unchanged baseline.
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ const outcome = await search(config, { query: QUERY, limit: 10 });
+ expect(outcome.results.some((r) => r.path === FAR)).toBe(false);
+ });
+
+ test("an unknown profile fails loud with a typed SearchError", async () => {
+ await seedChain();
+ const config = makeConfig({ vault, dbPath, mmrLambda: 1 });
+ await expect(search(config, { query: QUERY, limit: 10, profile: "turbo" })).rejects.toThrow(
+ SearchError,
+ );
+ });
+});
diff --git a/tests/mcp/brain-file-context.test.ts b/tests/mcp/brain-file-context.test.ts
new file mode 100644
index 00000000..72731d42
--- /dev/null
+++ b/tests/mcp/brain-file-context.test.ts
@@ -0,0 +1,78 @@
+/**
+ * MCP integration test for `brain_file_context` (Recall & Working-Memory
+ * Quality Suite, t_4f420aca). Given a file path, the tool surfaces prior
+ * vault work that mentions it by querying the index, behind a size gate.
+ * Read-only; handler exercised directly with a minimal context.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";
+import { MCPError } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tools.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+let ctx: ServerContext;
+
+beforeEach(async () => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-file-context-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-file-context-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "auth-decision.md"),
+ "# Auth decision\n\nWe refactored auth-token.ts to rotate keys hourly.\n",
+ );
+ await indexVault(resolveSearchConfig({ vault, configPath }));
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+const tool = SEARCH_TOOLS.find((t) => t.name === "brain_file_context")!;
+const handler = tool.handler;
+
+describe("brain_file_context", () => {
+ test("is registered requiring file_path", () => {
+ expect(tool).toBeDefined();
+ expect(tool.inputSchema.required).toContain("file_path");
+ });
+
+ test("surfaces a note documenting prior work on the file", async () => {
+ const res = (await handler(ctx, { file_path: "src/services/auth-token.ts" })) as {
+ skipped: boolean;
+ results: Array<{ path: string }>;
+ };
+ expect(res.skipped).toBe(false);
+ expect(res.results.some((r) => r.path === "Brain/notes/auth-decision.md")).toBe(true);
+ });
+
+ test("skips a file below the size gate with an explicit reason", async () => {
+ const small = join(vault, "small.ts");
+ writeFileSync(small, "x\n");
+ const res = (await handler(ctx, { file_path: small, min_bytes: 1500 })) as {
+ skipped: boolean;
+ reason: string | null;
+ };
+ expect(res.skipped).toBe(true);
+ expect(res.reason).toBe("below_size_gate");
+ });
+
+ test("a missing file_path is rejected with INVALID_PARAMS", async () => {
+ await expect(handler(ctx, {})).rejects.toThrow(MCPError);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 57528f8d..c8eeee39 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -239,6 +239,7 @@ describe("tool listing", () => {
"brain_recall_gate",
"brain_search",
"brain_eval",
+ "brain_file_context",
// Schema admin + watchdog recovery probes.
"schema_apply_mutations",
"schema_inspect",
@@ -536,7 +537,8 @@ describe("stdio loop", () => {
// + brain_intake_entities / brain_ingest_source / brain_research_report
// / brain_derive_fact (Knowledge Provenance Suite, v1.7.0) = 76.
// + brain_create_note (Brain Portability & Interop Suite) = 77.
- expect(list.result.tools.length).toBe(77);
+ // + brain_file_context (Recall & Working-Memory Quality Suite) = 78.
+ expect(list.result.tools.length).toBe(78);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index 2266aeba..baa91d27 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -139,5 +139,6 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
params: {},
})) as { result: { tools: Array<{ name: string }> } };
// 76 + brain_create_note (Brain Portability & Interop Suite) = 77.
- expect(list.result.tools.length).toBe(77);
+ // + brain_file_context (Recall & Working-Memory Quality Suite) = 78.
+ expect(list.result.tools.length).toBe(78);
});