Skip to content

Commit 29eb72b

Browse files
authored
Replace docs-mcp-server and Ollama with qmd for memory search (#27)
* Replace docs-mcp-server and Ollama with qmd for memory search - Ships a single 610 MB embedding model and no daemon; reranking and query expansion are disabled by pointing their model slots at the embedder, so a search with default arguments cannot trigger a mid-query model download. - Uses a named qmd index under .claude/.kb-index/ instead of a project-local .qmd/, which is trust-gated and silently substitutes a weaker embedding model for non-interactive callers. - Records KB searches sent as typed searches[] rather than only a bare query field, so the delegation gate still sees them. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Enforce the qmd version pin and shrink the per-result search context - qmd-install now carries a single doctor check that asserts version 2.8.3. A second, broader check made isAlreadyInstalled short-circuit, so the pinned install was skipped on any machine that already had a different qmd — which then ignored QMD_CONFIG_DIR and read the wrong index config. - Both memory-loop doctor checks harden PATH the way the MCP launcher already did, and stay quiet when qmd is missing rather than reporting a second failure. - global_context is now three lines: qmd echoes it into every search result, so the long version was over half of a ten-result response. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Tell Claude how to phrase a KB search and cap it at 5 results - Searches now ask for limit:5. Ranks past 5 never contributed a hit on the retrieval fixture, and the default of 10 nearly doubled the response size. - The lex and vec lines are described by what they take — keywords versus prose — since each is the only one that finds a whole class of memory. - States that result scores are 1/rank rather than confidence, so a poor match still scores 1.00 and the snippets have to be judged on their own. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Stop the maintainer notes pointing at a benchmark that is not in the repo - Drops the retrieval-bench row from the command table; the harness is kept outside the repo, so the command was unrunnable from a clean checkout. - Says where the quoted retrieval numbers came from, since removing the row left them with no visible source and nothing re-checks them. - Records limit:5 as part of the search call shape the four copies must share. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Drop the redundant kb-index entry from the repo gitignore - The pack's gitignore component already contributes .claude/.kb-index/, so the repo-level copy only duplicated what mcs sync installs. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Close four review findings and trim the manifest comments - The gate no longer treats `intent` as evidence of a search. It never retrieves on its own, so a request that returned nothing could satisfy the barrier. - The indexer writes the memories path as a quoted YAML scalar, and detects deletions inside subdirectories — a nested memory could stay searchable after being removed, and a project path containing "#" indexed the wrong directory. - The version check is anchored, so 2.8.30 and 12.8.3 no longer pass as 2.8.3. Comments that restated invariants already owned by CLAUDE.md are gone; the ones explaining a specific line stayed. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Stop the indexer marking work done that never happened - Serialises reindexing and confirms nothing is left pending before touching the freshness timestamp. Overlapping async runs hit qmd's embed lock, which reports contention as success, so the index could be marked fresh with zero vectors and then skipped indefinitely. - The install check probes a throwaway index. A bare `qmd status` adopts a project-local .qmd/ by walking up from the working directory, so it was editing the user's own qmd config and creating their index. - The MCP server starts in projects with no memories yet, and the collection is registered on the first hook run, so a first memory is searchable without waiting for the next session. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs * Leave the reason on disk when indexing fails - A failed or incomplete run keeps its output in .claude/.kb-index/memory-loop.log and deletes it on success, so the file's presence is the signal and it holds the reason. Gating the timestamp alone stopped failures concealing themselves, but left a retry every prompt with no way to see why. - A new doctor check reports that log, since a broken index is otherwise visible only as searches quietly returning nothing. - Records the hook/check coupling through that file, and corrects the project-root invariant, which named three copies of a ladder that now appears six times. Claude-Session: https://claude.ai/code/session_01M2kgbNZQeStEs1E8PjBWLs
1 parent 78fee39 commit 29eb72b

16 files changed

Lines changed: 677 additions & 158 deletions

‎.github/workflows/kb-gate-test.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ jobs:
2323
test:
2424
runs-on: ubuntu-latest
2525
steps:
26-
- uses: actions/checkout@v6
26+
- uses: actions/checkout@v7
2727

2828
# Twice, deliberately: the barrier is scoped by a monotonic turn counter
2929
# rather than by wall-clock time, and a regression to timestamps would show

‎.github/workflows/sync-blocks.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ jobs:
2525
check:
2626
runs-on: ubuntu-latest
2727
steps:
28-
- uses: actions/checkout@v6
28+
- uses: actions/checkout@v7
2929

3030
- name: Verify SYNC blocks exist and agree across both skills + SYNC-BLOCKS.md
3131
run: |
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
name: sync-memories-test
2+
3+
on:
4+
pull_request:
5+
paths:
6+
- "hooks/sync-memories.sh"
7+
- "tests/sync-memories-test.sh"
8+
- ".github/workflows/sync-memories-test.yml"
9+
push:
10+
branches: [main]
11+
paths:
12+
- "hooks/sync-memories.sh"
13+
- "tests/sync-memories-test.sh"
14+
15+
permissions:
16+
contents: read
17+
18+
concurrency:
19+
group: sync-memories-test-${{ github.ref }}
20+
cancel-in-progress: true
21+
22+
jobs:
23+
test:
24+
runs-on: ubuntu-latest
25+
steps:
26+
- uses: actions/checkout@v7
27+
28+
# qmd is stubbed, so no model or index is needed.
29+
- name: Run the sync-memories suite
30+
run: bash tests/sync-memories-test.sh

‎.gitignore‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
# Thumbnails
66
._*
77

8+
.maestri
9+
810
# Custom folder icons
911
Icon
1012

@@ -15,4 +17,4 @@ Icon
1517
.TemporaryItems
1618
.Trashes
1719
.VolumeIcon.icns
18-
.com.apple.timemachine.donotpresent
20+
.com.apple.timemachine.donotpresent

‎CLAUDE.md‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ The consequence that matters most: **nothing here executes from the repo.** Edit
1212

1313
| Task | Command |
1414
|---|---|
15-
| Run the hook test suite | `bash tests/kb-gate-test.sh` |
15+
| Run the KB gate suite | `bash tests/kb-gate-test.sh` |
16+
| Run the indexer suite | `bash tests/sync-memories-test.sh` (stubs qmd; no model needed) |
1617
| Verify the SYNC blocks agree | the snippet below (full version at the bottom of `SYNC-BLOCKS.md`) |
17-
| Check the manifest parses | `python3 -c "import yaml;yaml.safe_load(open('techpack.yaml'))"` |
18+
| Check the manifest | `mcs pack validate` — validates structure and component references, not just YAML syntax. A raw parse needs a Python that has PyYAML, which is not guaranteed to be `/usr/bin/python3` |
1819
| Install a change locally | `mcs sync --global`, or `mcs sync` inside a project |
1920
| Check installed health | `mcs doctor` |
2021

@@ -38,22 +39,38 @@ Two harness details are load-bearing rather than incidental:
3839
- It runs from a temp dir **outside any git repo**, because the hook resolves its project root with `git rev-parse --show-toplevel` first. Run from the checkout, the harness would write state into the working tree and read your real session files.
3940
- The fixture project must contain `.claude/memories/`, or every `PreToolUse` call takes the `no_memories_dir` skip and nothing is gated. The denial count asserted at the end is what turns that into a loud failure instead of a green run that asserted nothing.
4041

42+
`tests/sync-memories-test.sh` shares the outside-a-git-repo rule and stubs `qmd` on `PATH`, so it needs no model. Its own trap: a first run reindexes under any version of the hook, because the config file does not exist yet. The assertions that mean anything are the **second** runs, and they only discriminate because the stub creates `$INDEX_PATH` — a staleness gate guarded on that file falls through without it.
43+
4144
## Invariants that span files
4245

4346
**Placeholders are baked at sync time, not read at runtime.** `prompts:` in `techpack.yaml` declares `KB_GATE_MODE`; `hooks/kb-gate.sh` carries `MODE="__KB_GATE_MODE__"`, substituted during install. Changing the mode means re-running `mcs sync` — there is no runtime setting. The test suite injects modes the same way (`sed s/__KB_GATE_MODE__/$m/`).
4447

4548
**One dispatcher, four hook events.** `hooks/kb-gate.sh` is registered four times in `techpack.yaml` (UserPromptSubmit, PostToolUse, PreToolUse, SubagentStart) and branches on `hook_event_name`. Matchers are broad on purpose; which agent types count as "discovery" is decided in exactly one place, `GATED_AGENTS`. `hooks/sync-memories.sh` is likewise registered twice, on SessionStart and UserPromptSubmit.
4649

47-
**That dispatcher deliberately omits `set -e` and `set -u`**, unlike `sync-memories.sh` which uses `set -uo pipefail`. Its file header explains why and lists rules that are load-bearing: fail open, never `exit 2`, never call `docs-mcp-server` (too slow for `PreToolUse`), log every evaluation. Read that header before editing it.
50+
**That dispatcher deliberately omits `set -e` and `set -u`**, unlike `sync-memories.sh` which uses `set -uo pipefail`. Its file header explains why and lists rules that are load-bearing: fail open, never `exit 2`, never call `qmd` (it loads an embedding model; far too slow for `PreToolUse`), log every evaluation. Read that header before editing it.
51+
52+
**Project-root derivation must be byte-identical everywhere it appears.** Both hooks and every shell string in `techpack.yaml` — the `memory-loop` launcher and each of its doctor checks — resolve git toplevel → `CLAUDE_PROJECT_DIR` → `$PWD`. The hooks must agree on which project they are looking at; the manifest must additionally agree with `sync-memories.sh` on `.claude/.kb-index/`, because one writes the index the others read. `commandExists` runs every check in its own process with no way to share a value, so the duplication is forced; keeping the copies textually identical is the only thing that makes a future edit obviously propagatable. Do not abbreviate one of them, and do not "simplify" the ladder to `$PWD` — a shortened copy that dropped the `CLAUDE_PROJECT_DIR` rung shipped once already, and made those checks silently pass without checking anything in non-git projects.
53+
54+
**The indexing hook and a doctor check are coupled through a file.** `sync-memories.sh` writes `.claude/.kb-index/memory-loop.log` when a run fails or leaves documents unembedded, and deletes it on success; the "Memory indexing completed" check reports the file's existence. Move or rename it on one side and the check passes forever without testing anything.
55+
56+
**The index is reached by `--index`, never by a project-local `.qmd/`.** Two reasons, and the second is the dangerous one. A user may keep their own `.qmd/` at the project root for their own code, which this pack must not touch. And a project-local `.qmd/index.yml` falls under qmd's trust gate, which covers a non-default `models.embed` — for a non-interactive caller the gate does not prompt or fail, it *skips*, silently substituting a much weaker default model. Named indexes are never gated. `QMD_CONFIG_DIR` and `INDEX_PATH` are what move a named index back under the project directory.
57+
58+
**Reranking and query expansion are disabled by pointing their model slots at the embedding model.** The MCP `query` tool hard-defaults `rerank: true` with no server-side way to turn it off, and a *missing* model is downloaded mid-query with no progress output. An embedding model has no ranking head, so qmd fails to build a ranking context, warns, and falls back to RRF — measured at MRR 0.792 against 0.800 for an explicit `rerank: false`, and it buys back zero R@5 versus a real reranker. Those numbers come from a 20-query fixture over this project's own memories, kept outside the repo — nothing here reproduces them, so treat them as recorded measurements rather than something CI re-checks. The fallback is not a *strict* no-op: on a later fixture, a document RRF ranked 9th was dropped entirely when `rerank: true` was passed. Top ranks were unaffected, which is why this is a safe structural disable, but do not describe it as "reranking is off and nothing changes".
59+
60+
To measure any of this, `qmd bench <fixture.json> -c memories` is usable as shipped. Its fixture `query` field accepts the structured multi-line form (`intent:`/`lex:`/`vec:`), and a fixture written that way is passed through **unexpanded** — only a bare query string goes down the expansion path. So its `hybrid` row measures the pack's real configuration, not a degraded one. This depends on qmd's graceful-degradation path rather than a documented switch, which is why `@tobilu/qmd` is pinned to an exact version and why one doctor check issues a *default-argument* query: that check is what would catch the behaviour changing under an upgrade.
61+
62+
**The search call shape is stated in three places, deliberately.** "Typed `lex`+`vec` lines, `rerank: false`, `limit: 6`" appears in `templates/continuous-learning.md` (the only thing that reaches a user's `CLAUDE.md`), `skills/continuous-learning/SKILL.md`, and the `SubagentStart` briefing in `hooks/kb-gate.sh`. No single mechanism reaches all three consumers, so this is three copies rather than one source — change one and check the other two. It matters because the unguided path is measurably worse, not just slower.
63+
64+
**The index's `global_context` is deliberately not a fourth copy.** qmd serves that one string two ways: as the MCP server's `instructions`, once per connection, and as the `context` field of *every* search result. Guidance placed there is therefore paid for per result — at 342 characters it was 38% of a six-result response — while the only consumer it uniquely reaches is a client with no installed `CLAUDE.md` section, which cannot happen because the template is `isRequired`. So it carries identity only ("this is a project memory KB, not external documentation") and the guidance lives in the three copies that are not echoed. Resist putting the call shape back into it.
4865

49-
**Project-root and library derivation must match across two hooks.** `sync-memories.sh` and `resolve_paths()` in `kb-gate.sh` both resolve git toplevel → `CLAUDE_PROJECT_DIR` → `$PWD`, and derive the library name as the root directory's basename. kb-gate quotes that name back to Claude, and it has to be the one sync-memories indexed. Both files carry "keep in sync" comments.
66+
**The same three copies carry "retrieve before relying on a result", and the reason is only recorded here.** qmd's MCP snippet is at most five lines and 300 characters (`extractSnippet` in `store.js`, called with a hardcoded `300` from `mcp/server.js`), and it is anchored by literal substring matching of the first `lex` sub-query. When those terms are not in the matched text it falls back to the top of the chunk — in practice the file's first three lines, which for a memory is its title and `Applies to:`. Measured on a 527-document corpus, 28% of results came back title-only. So a search result is a lead, and answering from it is guessing; `get`/`multi_get` is the step that makes the answer real. The instruction is phrased as an absolute in all three copies on purpose — stating the failure condition invites the reader to decide a snippet looks complete this time. Do not "simplify" it back into step 2's old wording (`Read matching memories`), which worked only because the previous backend returned a whole chunk.
5067

5168
**Three text blocks must stay byte-identical across three files.** `capture-rules`, `strip-the-anchors`, and `applies-to` appear in both `SKILL.md`s and in `SYNC-BLOCKS.md`, enforced by `.github/workflows/sync-blocks.yml`. Two rules when touching them:
5269

5370
- Blocks are verdict-neutral. Each skill adds its own verb *outside* the fence — capture says "skip", audit says "DROP". Never move an action verb inside the locked block.
5471
- Never write a real tag name in prose. The drift check's `awk` range grabs the first matching opener, so a literal mention would shadow the canonical block and make it invisible to the verifier. `SYNC-BLOCKS.md` uses a placeholder form for exactly this reason.
5572

56-
**Templates are installed as marked sections inside someone's `CLAUDE.md`, not as files.** The `templates:` block in `techpack.yaml` maps `templates/continuous-learning.md` to a section fenced by `<!-- mcs:begin memory.continuous-learning -->`. On a global sync it lands in `~/.claude/CLAUDE.md`; on a project sync, in that project's `CLAUDE.local.md`. Edit the template here and re-sync, because editing inside the markers drifts and is overwritten. `__PROJECT_DIR_NAME__` is substituted at install time, like the hook's mode.
73+
**Templates are installed as marked sections inside someone's `CLAUDE.md`, not as files.** The `templates:` block in `techpack.yaml` maps `templates/continuous-learning.md` to a section fenced by `<!-- mcs:begin memory.continuous-learning -->`. On a global sync it lands in `~/.claude/CLAUDE.md`; on a project sync, in that project's `CLAUDE.local.md`. Edit the template here and re-sync, because editing inside the markers drifts and is overwritten. The template has no placeholders of its own; only `hooks/kb-gate.sh` carries one, `KB_GATE_MODE`.
5774

5875
**Installed artifacts are content-hash verified.** `mcs doctor` compares hashes of installed files, so hand-editing an installed copy registers as drift and the next `mcs sync` restores the packaged version. This is why a skill can never write to its own files: anything saved that way is destroyed on the next sync.
5976

‎README.md‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ mcs sync --global # 3. install globally (~/.claude)
1818
mcs doctor # 4. verify everything is healthy
1919
```
2020

21-
**Prerequisites:** macOS, [Claude Code](https://docs.anthropic.com/en/docs/claude-code), and [Ollama](https://ollama.com) (local embeddings runtime). `mcs` installs the rest (Node, `gh`, `jq`) automatically.
21+
**Prerequisites:** macOS, [Claude Code](https://docs.anthropic.com/en/docs/claude-code), and Node 22 or newer. `mcs` installs the rest (Node, `gh`, `jq`, [qmd](https://github.com/tobi/qmd)) automatically, and downloads a ~610 MB embedding model once on first sync — shared by every project, with no daemon left running afterwards.
2222

2323
Global is the recommended scope — this pack has no per-project config, so installing once makes memory available in every project automatically. To scope it to a single repo instead, run `mcs sync` from inside that repo.
2424

@@ -32,11 +32,11 @@ flowchart LR
3232
B --> C[Work session]
3333
C --> D[Capture learnings & decisions]
3434
D --> E[(.claude/memories/)]
35-
E --> F["Ollama embeddings<br/>semantic index"]
35+
E --> F["local embeddings<br/>semantic index"]
3636
F -. re-index on session start / change .-> B
3737
```
3838

39-
1. **Session starts** — a hook re-indexes `.claude/memories/` into a local vector store (Ollama `nomic-embed-text`), in the background.
39+
1. **Session starts** — a hook re-indexes `.claude/memories/` into a local vector store in the background. Embeddings are computed in-process by `qmd`, so there is no service to start and nothing left running between sessions.
4040
2. **Before any task** — Claude is instructed to search the knowledge base first, surfacing relevant past learnings and decisions.
4141
3. **Before delegating** — sub-agents can't see the parent's KB results, so they'd rediscover everything from scratch. A gate hook closes that gap from both ends: it requires the findings to be pasted into the sub-agent's prompt, and tells any discovery agent to search the KB itself if they weren't. Configurable per project, from a reminder up to a hard block.
4242
4. **During work** — a prompt-submit hook reminds Claude to notice when the current interaction produces knowledge worth saving.
@@ -66,7 +66,7 @@ To change the answer later, re-run `mcs sync` — the mode is baked into the ins
6666

6767
| Component | What it does |
6868
|---|---|
69-
| **docs-mcp-server** (MCP) | Read-only semantic search over `.claude/memories/`, backed by local Ollama embeddings |
69+
| **memory-loop** (MCP) | Semantic search over `.claude/memories/`, backed by a local embedding model |
7070
| **continuous-learning** (skill) | Extracts learnings and decisions from a session into structured memory files |
7171
| **memory-audit** (skill) | Reviews existing memories and flags stale or duplicate entries to keep the KB lean |
7272
| **sync-memories.sh** (hook) | Indexes/re-indexes memories on session start and when they change mid-session |
@@ -81,14 +81,44 @@ Memories come in two flavors, both stored as version-controlled, human-readable
8181

8282
---
8383

84+
## Upgrading from the Ollama version
85+
86+
Earlier releases indexed memories through `docs-mcp-server` backed by an Ollama daemon. `mcs sync`
87+
converges on its own: the old MCP server is deregistered for you, and the new index is built on the
88+
next session start. Nothing below is required.
89+
90+
What `mcs` cannot clean up is what the old release installed through plain shell commands. If you
91+
want the disk space back, and **only if nothing else on your machine uses these**:
92+
93+
```bash
94+
npm uninstall -g @arabold/docs-mcp-server
95+
rm -rf ~/Library/Application\ Support/docs-mcp-server # see the warning below
96+
ollama rm nomic-embed-text
97+
```
98+
99+
Three things to check before running any of them:
100+
101+
- **`docs-mcp-server` indexes external documentation too.** If you ever pointed it at a library's
102+
docs, that is what you would be uninstalling.
103+
- **Its store is shared across every library you indexed with it**, not just your memories. Deleting
104+
the directory deletes all of them. Run `docs-mcp-server list` first and see what is in there.
105+
- **Ollama may be serving something else.** `ollama list` shows what it holds; if
106+
`nomic-embed-text` is the only entry and nothing else here needs the runtime, you can also remove
107+
the app and its data — `/Applications/Ollama.app` and `~/.ollama`. Removing the app clears the
108+
macOS Login Item it registers.
109+
110+
This pack no longer installs or manages any of them.
111+
112+
---
113+
84114
## Directory structure
85115

86116
```
87117
memory/
88118
├── techpack.yaml # Manifest — defines all components
89119
├── config/settings.json # Disables built-in auto-memory
90120
├── hooks/
91-
│ ├── sync-memories.sh # Ollama health + memory indexing/reindexing
121+
│ ├── sync-memories.sh # Memory indexing/reindexing
92122
│ ├── continuous-learning-activator.sh # Knowledge extraction reminder
93123
│ └── kb-gate.sh # Keeps KB lookups ahead of delegated discovery
94124
├── skills/

‎SYNC-BLOCKS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ Locations:
5151

5252
```markdown
5353
<!-- SYNC:applies-to -->
54-
**The `Applies to:` field.** Place `**Applies to:**` on the line immediately after the `# Title` heading of every memory; it declares which project(s) the memory targets. Use the **git repo name** — the last path segment of `git remote get-url origin`, with `.git` stripped (e.g. `git@github.com:org/repo.git` → `repo`; `https://github.com/owner/my-app.git` → `my-app`). Fall back to the working directory's basename only when the repo has no remote configured. Use the repo name — not the directory basename — because folder names vary across clones while the repo name is stable. This is also why `Applies to:` may differ from the `library:` parameter used for `search_docs`, which is folder-based and set automatically by the indexing hook.
54+
**The `Applies to:` field.** Place `**Applies to:**` on the line immediately after the `# Title` heading of every memory; it declares which project(s) the memory targets. Use the **git repo name** — the last path segment of `git remote get-url origin`, with `.git` stripped (e.g. `git@github.com:org/repo.git` → `repo`; `https://github.com/owner/my-app.git` → `my-app`). Fall back to the working directory's basename only when the repo has no remote configured. Use the repo name — not the directory basename — because folder names vary across clones while the repo name is stable. This is also why `Applies to:` may differ from the set of memories the search index actually covers, which is folder-based and set automatically by the indexing hook.
5555

5656
When a memory genuinely applies to multiple projects, list them comma-separated (e.g. `**Applies to:** web-dashboard, ios-app, api-backend`); the content must stay true in every listed project. When a memory is only partially relevant to one listed project, split it into separate memories instead of mixing.
5757
<!-- /SYNC -->

0 commit comments

Comments
 (0)