Source: https://velofy.co/research/papers/trove-hierarchical-memory-and-retrieval-evals/

Published: 2026-10-24T00:00:00.000Z
Updated: 2026-11-20T16:10:07.000Z

[RESEARCH](https://velofy.co/research/) / [PAPERS](https://velofy.co/research/papers/)

published

# Trove: hierarchical repository memory, read-only MCP boundaries, and retrieval baselines

Architecture, read-only MCP threat model, and measured 16-query retrieval baselines for Trove's L4-to-L1 repository memory and BM25 ask paths.

Dexter, Anish Kr Singh · 24 Oct 2026

Coding agents lose session state between runs and cannot fit large repositories into a single prompt without diluting signal. [Trove](https://velofy.co/trove/) addresses both failure modes with a local, file-backed memory system built from two cooperating layers: a plain-file engineering memory plugin for durable decisions and conventions, and a Rust indexing and retrieval engine that compresses a codebase into a seven-level memory hierarchy under explicit token budgets.

This report documents the storage layout, progressive retrieval pipeline, read-only Model Context Protocol (MCP) specification, and first measured retrieval baseline across Trove’s `ask` and `query` paths. Every figure, schema constraint, and invariant below is taken directly from the repository design docs, crate sources, MCP specification, and the S4 retrieval evaluation baseline run on 2026-10-23. For a broader walkthrough of how Trove fits into Dexter’s skill stack, see [Deep Dexter skills: Gource, Trove, and Vortex](https://velofy.co/journal/deep-dexter-skills-gource-trove-and-vortex/).

Facts at a glance:

*   **Two-layer split:** plain-markdown plugin memory (`./.claude/trove` or `~/.claude/trove`) paired with a Rust engine (`.trove/`) written across `trove-core`, `trove-index`, `trove-retrieve`, `trove-cli`, `trove-tools`, `trove-ship`, and `trove-mcp`.
*   **Memory hierarchy:** L0 Working through L6 Repository, with default per-level token budgets and five progressive compression tiers (`Raw` to `Embedding`).
*   **MCP surface:** `trove mcp serve`, stdio-only newline-delimited JSON-RPC 2.0, read-only by construction, four tools, four allowlisted markdown resources, and two prompts.
*   **Evaluation suite:** 16 golden queries across four classes (`exact`, `synonym`, `symbol`, `why`), run via `cargo test -p trove-retrieve --test eval -- --nocapture` against a 46-document `ask` corpus and 10 imported historical `query` objects.
*   **Headline baseline:** `ask` achieves `0.812` recall@5 (`0.328` MRR, `0.444` nDCG@5, 14 ms) with `0.000` recall@1 across every class; `query` achieves `0.000` recall@5 (`0.068` MRR, 84 ms) because its level-major output places L5 historical entries at ranks 12–15 behind L4–L1 structural objects.

## Two layers and on-disk storage

Trove separates _what was decided and why_ from _what exists in the codebase and where_. Both layers store plain files on disk, run locally without telemetry or outbound network calls, and remain inspectable under version control.

### Engineering memory plugin and project troves

The v0.1 Claude Code plugin (`trove@velofy-trove` under `plugins/trove/`) has no background daemon. It ships markdown skills and a single `SessionStart` hook (`hooks/hooks.json`, matcher `startup|resume`) backed by a dependency-free shell helper (`trove.sh`). Location resolution follows one rule shared by `trove.sh`, `load-trove.sh`, and every `SKILL.md`: project scope (`./.claude/trove`) wins whenever it contains an `INDEX.md`; otherwise Trove falls back to user scope (`~/.claude/trove`).

Each fact lives in its own file under `entries/<slug>.md` with YAML frontmatter (`title`, `slug`, `type`, `created`, `tags`), a short body, a `Why it matters` line, and `[[slug]]` cross-links. The v0.1 entry `type` enum defines `decision`, `gotcha`, `preference`, `reference`, `project`, and `snippet`, expanded in v0.3 with `convention` and `context` (and JSON entries for structured tables). `INDEX.md` holds one bullet per entry, newest first (`- [Title](entries/slug.md) - one-line hook`). One file per fact keeps diffs atomic, deduplication straightforward, and git history legible.

Auto-loading is intentionally narrow and defensive:

*   `load-trove.sh` is read-only, omits `set -e`, guards every file read, exits `0` unconditionally, and prints nothing when no trove exists.
*   Only `INDEX.md` is injected at session start; full entries load on demand through `recall`.
*   Each skill restricts its `allowed-tools` list: `init` and `remember` declare `Bash, Read, Write, Edit`, whereas `recall` declares only `Bash, Read, Grep` and cannot mutate files.

In v0.3, project troves partition `.claude/trove/` into three intent-mapped sections rendered into Claude Code skills under `.claude/skills/` plus an `AGENTS.md` block for other coding agents:

| Section | Contents | Rendered skill | Load trigger |
| --- | --- | --- | --- |
| `conventions/` | Style, structure, naming, testing, commit and PR rules, prohibitions | `<project>-conventions` | Writing, editing, reviewing, or committing code |
| `memory/` | Decisions, gotchas, and history with rationale | `<project>-memory` | Changing behavior, selecting approaches, debugging, asking why |
| `context/` | Architecture, subsystems, and key modules generated by the engine | `<project>-context` | Orienting, locating code, planning cross-module changes |

A mechanical secret guard (`trove.sh guard`) runs before writes and scans for credential prefixes and patterns (`sk-`, `AKIA`, `ghp_`, `shpat_`, `xox?-`, private key blocks, and `key=`/`token=`/`password:` assignments). Hits refuse the entry unless `--redact` is passed, and skill rendering scrubs matching patterns before writing generated `SKILL.md` files.

### Engine store and L0–L6 memory hierarchy

The Rust engine writes repository indexes to `.trove/` (gitignored) through `TroveStore` in `crates/trove-core/src/store.rs`. The store records `manifest.json` (`TroveManifest` with `version`, `repo_root`, `indexed_at`, `symbol_count`, `module_count`, and `subsystem_count`), `graph.json`, `symbols.json`, `execution.json`, and `patches.json`, alongside per-kind directories (`architecture/`, `subsystems/`, `modules/`, `symbols/`, `historical/`, `repository/`, `working/`, `patches/`, `execution/`) holding sanitized `<id>.json` `MemoryObject` records hashed with SHA-256 (`content_hash`).

`MemoryLevel` in `crates/trove-core/src/hierarchy.rs` defines seven levels from ephemeral task state to global repository norms:

| Level | Enum variant | Scope | Default token budget |
| --- | --- | --- | --- |
| L0 | `L0Working` | Current task, edits, objective, reasoning | 20,000 |
| L1 | `L1ActiveSymbols` | Functions, classes, structs, traits, routes, queries, tests | 30,000 |
| L2 | `L2Module` | Per-file summaries: exports, dependencies, assumptions, side effects | 40,000 |
| L3 | `L3Subsystem` | Package-level clusters (e.g. authentication, billing) | 30,000 |
| L4 | `L4Architecture` | Repo-wide design map, data flow, ownership, boundaries | 30,000 |
| L5 | `L5Historical` | Imported engineering decisions, rejected approaches, migrations | 20,000 |
| L6 | `L6Repository` | Glossary, naming conventions, coding standards | 10,000 |

Every `MemoryObject` carries multi-resolution text (`CompressedText` in `crates/trove-core/src/compression.rs`) across five `CompressionTier` values: `Raw` (unbounded), `Summary` (400-token target), `UltraSummary` (100-token target), `Keywords` (20-token target), and `Embedding` (0-token target). When no LLM is used, `compress_heuristic` constructs 400-character and 100-character non-comment summaries and frequency-ranked keyword fingerprints directly from raw text.

## Progressive retrieval and budget allocation

Trove’s retrieval engine is built around the premise that unused context is healthy: models should earn deeper detail rather than ingest raw files upfront. `ContextBudget::for_total(total)` in `crates/trove-retrieve/src/budget.rs` partitions any total token budget into six fixed slices, estimating token cost at `text.len() / 4 + 1`:

| Budget slice | Share of total | Example at 200,000 tokens |
| --- | --- | --- |
| Working memory | 10% | 20,000 |
| Architecture | 15% | 30,000 |
| Active files | 20% | 40,000 |
| Dependency expansion | 20% | 40,000 |
| Code | 20% | 40,000 |
| Tool output | 15% | 30,000 |

### Level-major assembly in RetrievalPipeline

`RetrievalPipeline::query` in `crates/trove-retrieve/src/pipeline.rs` executes a strict top-down walk from L4 down to L1, followed by graph expansion and L5 historical lookup:

1.  **L4 Architecture:** calls `best_match` over `MemoryKind::Architecture` against `budget.architecture`. If the `Summary` exceeds `budget.architecture`, it falls back to `UltraSummary`.
2.  **L3 Subsystems:** ranks `MemoryKind::Subsystem` objects and emits up to 3 `Summary` items while cumulative tokens remain within `budget.architecture + (budget.active_files / 2)`.
3.  **L2 Modules:** ranks `MemoryKind::Module` objects and emits up to 8 `Summary` items while cumulative tokens remain within `budget.architecture + budget.active_files + subsystem_budget`.
4.  **L1 Active Symbols:** filters `symbols.json` where `score_text` on `<name> <path>` is positive and emits up to 20 symbol signatures (or `<kind> <name>` fallbacks) within `budget.code`.
5.  **Dependency expansion:** takes the object IDs of retrieved L2 modules as seeds, expands 1 hop in `graph.json` (`graph.expand(&seeds, 1)`), and emits up to 10 neighboring symbols as L1 `UltraSummary` items within `budget.dependency_expansion`.
6.  **L5 Historical:** ranks `MemoryKind::Historical` objects (imported from `.claude/trove` via `import_historical`) and emits up to 3 `Summary` items while under `budget.total_tokens`.

Query tokenization splits on non-alphanumeric characters, drops tokens of length 2 or less, and lowercases the remainder. `score_object` applies unweighted substring matching across four haystacks (`id`, `path`, `summary`, `raw`) at `+3` points per matching haystack per term, plus `+2` points per matching keyword.

This architecture explains two properties observed later in the evaluation harness: the pipeline is completely deterministic and offline, and its output list is ordered strictly by hierarchy level (L4, L3, L2, L1, then L5) regardless of a historical entry’s lexical score.

### Offline BM25 retrieval in trove ask

Alongside `RetrievalPipeline`, `trove ask` builds a flat BM25 search corpus combining project trove entries (`trove_entries`), repository markdown docs (`repo_docs`), and indexed engine objects (`engine_index`). Its production search defaults are `SearchOptions::default()` with `limit: 12` and `per_kind: 6`, and an offline context budget default of `1,500` tokens (`ask::DEFAULT_BUDGET`).

## Read-only MCP specification and threat model

`crates/trove-mcp/SPEC.md` specifies `trove mcp serve`, a read-only Model Context Protocol server designed so MCP-capable agents can query Trove without opening a write surface or reimplementing retrieval logic.

### Crate boundary, transport, and lifecycle

A single architectural rule governs the server: `crates/trove-mcp` contains only protocol framing, dispatch, and error shapes, and depends on no other Trove crate. All repository and retrieval behavior lives in `trove-cli` (exposed as a library target) behind one `Handler` trait. Protocol tests run against stub handlers while integration tests exercise the real `trove` binary, ensuring `trove mcp serve` executes the exact production code paths of `trove ask`, `trove query`, `trove status`, and `trove tools search` without drift.

Transport constraints are deliberately strict:

*   **Stdio only:** no TCP listener, no Unix socket, no outbound network access.
*   **Line-delimited JSON-RPC 2.0:** one request or notification per line, one response per line. Batching is rejected (a JSON array line is an invalid request).
*   **Stdout purity:** stdout carries only protocol responses; surviving diagnostics and errors go to stderr, and any handler library that could write to stdout is wrapped.
*   **Non-interactive offline execution:** exits cleanly on stdin EOF, never prompts, never reads a TTY, never spawns subprocesses, and never invokes an LLM provider (`trove_ask` runs permanently in offline `provider: none` mode).

During initialization, the server echoes the client’s `protocolVersion` if it is `2024-11-05` or `2025-03-26` (defaulting to `2024-11-05` if absent or unsupported), replies with `{protocolVersion, capabilities: {tools: {}, resources: {}, prompts: {}}, serverInfo: {name: "trove", version}}`, accepts `notifications/initialized` with no response, and then serves `tools/list`, `tools/call`, `resources/list`, `resources/read`, `prompts/list`, `prompts/get`, and `ping` in any order.

### Tools, allowlisted resources, prompts, and freshness

Repository resolution matches `trove ask`: `--repo` (defaulting to an upward search from the current working directory for `.trove` or `.git`) plus `$HOME/.claude/trove`. Paths resolve once at startup, but every `tools/call` re-runs `Knowledge::load` (and `TroveStore::open` for `trove_query`) and every `resources/read` reads from disk so entries written by the CLI between two MCP requests become visible immediately.

| MCP surface | Identifier | Contract and bounds |
| --- | --- | --- |
| Tool | `trove_ask` | Required `question`; `limit` 1–50 (default 12); `budget` 100–100,000 (default 1,500). Returns `mode: offline retrieval`, `N of M matches | ~T/B tokens`, and cited source lines with snippets. |
| Tool | `trove_query` | Required `question`; `budget` 100–1,000,000 (default 200,000). Returns `Query: <q>`, `N items | ~T tokens`, and `## <level> [<tier>] <object_id>` blocks. |
| Tool | `trove_status` | No parameters. Returns `Trove v…`, `Repo:`, `Indexed:`, and symbol/module/subsystem counts, or `No index found. Run: trove index`. |
| Tool | `trove_tools_search` | Required `query`. Returns `- <name> (<pair>)` lines or `no tools found`. |
| Resource | `trove://index` | Project `INDEX.md` plus personal `INDEX.md` as `text/markdown`. |
| Resource | `trove://skills/{conventions,memory,context}` | Rendered section skill if present, else that section’s `INDEX.md`; missing sections return empty text. |
| Prompt | `remember`, `reflect` | User-role text prompts summarizing single-fact capture rules (guard, routing, newest-first index, no secrets) and session reflection (at most three proposed entries, no secrets). |

Protocol and handler errors are cleanly separated: malformed JSON lines return `-32700` (`id: null`), unknown methods return `-32601`, invalid parameters or unknown tools/resource URIs return `-32602`, internal failures return `-32603`, notifications never elicit responses, and handler-level tool failures (such as an unreadable trove) return a tool result with `isError: true` so the session stays alive.

### Threat model

`trove-mcp` treats all client-supplied strings (questions, tool arguments, resource URIs) as untrusted input and enforces five boundaries:

1.  **Read-only:** no tool writes to disk and no `tools/call` mutates repository or trove state; write tools (`remember`/`reflect`) are explicitly out of scope for this slice.
2.  **No arbitrary file reads:** `resources/read` matches URIs against the four-entry allowlist before opening any path; any other URI fails with `-32602`, preventing traversal outside `.claude/trove` or `.claude/skills`.
3.  **No code execution:** query strings pass solely to the tokenizer and retrieval corpus; nothing is handed to `sh -c` or a subprocess.
4.  **No network:** no listeners, no outbound sockets, and LLM providers are permanently disabled.
5.  **Stdout isolation:** protocol framing cannot be corrupted by stray library prints.

## Retrieval evaluation methodology

The evaluation harness in `evals/` (`evals/README.md` and `evals/BASELINE.md`) establishes a pre-tuning reference point on branch S4 (`feat/retrieval-evals`, post PR #33). It is strictly measurement-only: tests fail on harness or fixture breakage (missing expected items, out-of-range metrics, or `ask` exact-term recall@5 dropping below `1.0`), never on weak ranking scores.

Both retrieval systems run through their real production loaders against one committed fixture (`fixture/`, a miniature JavaScript/Python service with docs, architectural decision records, and a sectioned trove containing invented data and no secrets):

*   **`ask` corpus (46 docs):** 10 Project trove entries, 3 Doc files, 1 Architecture object, 2 Subsystem objects, 20 Module objects, and 10 Symbol objects built by running a real `Indexer` in a temporary copy of the fixture under `SearchOptions::default()` (`limit: 12`, `per_kind: 6`).
*   **`query` corpus (10 Historical objects):** the fixture’s structural `.trove/` index plus 10 Historical objects imported via `import_historical`, run at the production CLI default `ContextBudget::for_total(200_000)` (ranks were verified identical at `1,500`, since the small fixture never triggers either stop threshold).

Sixteen golden queries (`queries.json`) are divided evenly into four classes of four queries each:

| Query class | Count | What the class tests |
| --- | --- | --- |
| `exact` | 4 | Literal term overlap retrieves the target (control) |
| `synonym` | 4 | Retrieval without literal overlap; the harness asserts the expected entry contains no whole-word query token of 4 or more characters |
| `symbol` | 4 | Code identifiers retrieve their definitions |
| `why` | 4 | Natural-language rationale questions (no current tuning target) |

Each query specifies an expected target for both systems (`ask_expected` corpus path and `query_expected` memory object ID `historical:<slug>`). Let `r` be the 1-based rank of the expected item in the system’s own output list (search hits for `ask`; level-ordered assembled `items` for `query`). A miss contributes `0` to every metric:

*   **recall@k:** `1` if `r <= k`, else `0` (averaged per class).
*   **MRR:** mean of `1 / r`.
*   **nDCG@5:** mean of `1 / log2(r + 1)` for `r <= 5`, else `0` (binary relevance with a single relevant item, so `IDCG = 1`).

## Measured retrieval baseline and failure findings

Running `cargo test -p trove-retrieve --test eval -- --nocapture` on 2026-10-23 produced the following reference baseline across all 16 queries (`ask` completed in 14 ms; `query` completed in 84 ms):

| system/class | n | recall@1 | recall@3 | recall@5 | MRR | nDCG@5 |
| --- | --- | --- | --- | --- | --- | --- |
| `ask/exact` | 4 | 0.000 | 1.000 | 1.000 | 0.458 | 0.598 |
| `ask/synonym` | 4 | 0.000 | 0.500 | 0.500 | 0.208 | 0.283 |
| `ask/symbol` | 4 | 0.000 | 1.000 | 1.000 | 0.417 | 0.565 |
| `ask/why` | 4 | 0.000 | 0.250 | 0.750 | 0.227 | 0.329 |
| `ask/ALL` | 16 | 0.000 | 0.688 | 0.812 | 0.328 | 0.444 |
| `query/exact` | 4 | 0.000 | 0.000 | 0.000 | 0.077 | 0.000 |
| `query/synonym` | 4 | 0.000 | 0.000 | 0.000 | 0.042 | 0.000 |
| `query/symbol` | 4 | 0.000 | 0.000 | 0.000 | 0.076 | 0.000 |
| `query/why` | 4 | 0.000 | 0.000 | 0.000 | 0.076 | 0.000 |
| `query/ALL` | 16 | 0.000 | 0.000 | 0.000 | 0.068 | 0.000 |

Per-query 1-based rank vectors from the same run make the failure modes concrete:

*   **`ask` ranks:** `[Some(2), Some(2), Some(2), Some(3), Some(3), None, Some(2), None, Some(3), Some(3), Some(2), Some(2), Some(4), Some(3), Some(8), Some(5)]`
*   **`query` ranks:** `[Some(14), Some(13), Some(12), Some(13), Some(12), None, Some(12), None, Some(13), Some(13), Some(12), Some(15), Some(14), Some(12), Some(12), Some(15)]`

### Four baseline failure findings

`BASELINE.md` records four structural findings from this un-tuned run, each pointing to a distinct architectural cause rather than random noise:

1.  **`ask` recall@1 is 0.000 across every class.** Not a single expected document reaches rank 1, even on exact-term control queries (`ask/exact` lands at ranks 2, 2, 2, 3). In the small 46-doc fixture, BM25 score ties are frequent and repository `Doc`/`SectionDoc` bodies overlap trove entry prose—for example, an ADR discussing write-ahead logging outranks the corresponding trove entry.
2.  **Synonym queries halve `ask` recall (`0.500` recall@5 vs `1.000` on `exact`).** Two of the four synonym queries return `None` (`ask` ranks `[Some(3), None, Some(2), None]`), which is the expected ceiling of purely lexical BM25 when the fixture asserts zero whole-word token overlap of four characters or more.
3.  **Rationale (`why`) queries are weak at tight cutoffs (`0.250` recall@3, `0.750` recall@5, `0.227` MRR).** Without a semantic or embedding retrieval path, natural-language rationale questions scatter across ranks 3, 4, 5, and 8.
4.  **`query` traps every historical hit at ranks 12–15 (`0.000` recall@5, `0.068` MRR).** Because `RetrievalPipeline::query` emits items in strict level-major order (`L4 -> L3 -> L2 -> L1 -> L5`), `Historical` memory objects are appended after Architecture, Subsystem, Module, and Symbol items regardless of how strongly they match the query. On top of that structural floor, the same two zero-overlap synonym queries score `0` under substring matching and drop out completely (`None`).

## Architectural takeaways

Measuring both paths side by side clarifies what Trove already guarantees and where future ranking slices must focus. On the safety and operational axis, the separation between plain-file storage, defensive read-only hooks, allowlisted MCP resources, and offline `trove-mcp` transport gives agents a reproducible, zero-mutation read boundary over repository memory. On the retrieval axis, the S4 baseline exposes two clear improvement levers: tie-breaking and source-kind weighting in `ask` (where `recall@3` is already `1.000` on `exact` and `symbol` but `recall@1` is `0.000`), and rethinking either lexical expansion or cross-level ranking in `query` whenever a user asks directly for historical rationale rather than top-down code orientation. Every subsequent ranking change in Trove will be judged as a class-level delta against the 2026-10-23 table above.

[← Previous](https://velofy.co/research/papers/decision-bench-near-miss-temperature-shortlist/)[Next →](https://velofy.co/research/papers/troy-agent-browser-architecture/)

[← All papers](https://velofy.co/research/papers/)
