recallhook 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ .pytest_cache/
8
+ .headroom/
9
+ .recallhook/
10
+ .env
11
+ bench/out/
12
+ mem0_ollama.py
13
+ *.whl
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 recallhook contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.5
2
+ Name: recallhook
3
+ Version: 0.1.0
4
+ Summary: Private, local long-term memory for Claude Code (desktop app, VS Code, terminal): a hook that recalls and stores facts with mem0 + Ollama.
5
+ Project-URL: Homepage, https://github.com/DEVPARMAR06/recallhook
6
+ Project-URL: Repository, https://github.com/DEVPARMAR06/recallhook
7
+ Project-URL: Issues, https://github.com/DEVPARMAR06/recallhook/issues
8
+ Author: DEVPARMAR06
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: claude,claude-code,hooks,llm,local-first,mem0,memory,ollama
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: fastapi
22
+ Requires-Dist: httpx
23
+ Requires-Dist: mem0ai>=2.2
24
+ Requires-Dist: ollama
25
+ Requires-Dist: qdrant-client
26
+ Requires-Dist: uvicorn
27
+ Provides-Extra: dev
28
+ Requires-Dist: anyio; extra == 'dev'
29
+ Requires-Dist: pytest; extra == 'dev'
30
+ Provides-Extra: headroom
31
+ Requires-Dist: headroom-ai[proxy]; extra == 'headroom'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # recallhook
35
+
36
+ [![tests](https://github.com/DEVPARMAR06/recallhook/actions/workflows/test.yml/badge.svg)](https://github.com/DEVPARMAR06/recallhook/actions/workflows/test.yml) ![python](https://img.shields.io/badge/python-3.10%2B-blue) ![license](https://img.shields.io/badge/license-MIT-green)
37
+
38
+ **Private, local long-term memory for Claude Code.** Tell Claude something once, like *"I use pnpm"* or *"Atlas deploys to Fly.io"*, and every future session already knows it, in the **Claude desktop app, the VS Code extension and the terminal**.
39
+
40
+ No cloud, no proxy, no API key: a Claude Code hook + [mem0](https://github.com/mem0ai/mem0) + your own [Ollama](https://ollama.com) models. In our tests it **costs the same as retyping the context yourself, and nothing at all on prompts that don't need it.**
41
+
42
+ ![recallhook dashboard](https://raw.githubusercontent.com/DEVPARMAR06/recallhook/main/docs/dashboard.jpg)
43
+
44
+ ```text
45
+ You: What port does the Atlas dev server use, and how do I run its tests?
46
+
47
+ without recallhook "I don't know. Let me search your files..." (0/9 correct, wasted tool calls)
48
+ with recallhook "pnpm test:unit, port 4310." (9/9 correct, 57% cheaper than the search)
49
+ ```
50
+
51
+ ## Why
52
+
53
+ - Every new Claude Code session starts blank: your stack, conventions, ports, deploy targets, "never force-push to main"... you re-explain them, or maintain a `CLAUDE.md` by hand.
54
+ - Hosted memory services send your conversations to someone else's cloud.
55
+ - Memory tools that rely on the model *choosing* to call a tool are unreliable; this one injects relevant facts deterministically before the model sees your prompt.
56
+
57
+ recallhook watches what you tell Claude, stores the durable facts locally, and quietly adds the relevant few lines to future prompts.
58
+
59
+ ## How it works
60
+
61
+ ```text
62
+ you type a prompt ──▶ Claude Code UserPromptSubmit hook ──▶ local gateway (:8788) ──▶ mem0 + Ollama
63
+ ▲ relevant memories added as context (~30-150 tokens, ~50 ms)
64
+ └── durable statements queued for background fact extraction
65
+ ```
66
+
67
+ - **Recall** (~50 ms): the closest memories above a relevance cutoff are added to your prompt. Each memory is injected once per session (it stays in the transcript), so it doesn't repeat and burn tokens.
68
+ - **Capture** (background): a local model extracts lasting facts from statements like *"my project X uses..."*, *"I always..."*, *"remember..."*. Questions and one-off tasks ("write a one-liner...") are **not** stored.
69
+ - **Fail-open**: if anything is down or slow, the hook does nothing and your prompt goes through untouched.
70
+ - Everything is stored in `~/.recallhook` (Qdrant + SQLite). Nothing leaves your machine except what you type to Claude as usual.
71
+
72
+ | Surface | Status |
73
+ |---|---|
74
+ | Claude desktop app (Code tab) | works, tested |
75
+ | Terminal `claude` | works, tested |
76
+ | VS Code extension | uses the same `~/.claude/settings.json`, so it should work; independent testing welcome |
77
+
78
+ ## Quickstart
79
+
80
+ Requirements: Python 3.10+, [Ollama](https://ollama.com), Claude Code. An 8B model wants roughly 6 GB of VRAM/RAM.
81
+
82
+ ```bash
83
+ ollama pull nomic-embed-text
84
+ ollama pull qwen3:8b # extraction model (any chat model works)
85
+
86
+ pip install recallhook
87
+ recallhook install # Windows: start at logon + add the hook
88
+ recallhook status
89
+ recallhook ui # open the dashboard
90
+ ```
91
+
92
+ macOS/Linux: run `recallhook serve` yourself (systemd/launchd unit welcome as a PR) and `recallhook hooks on`.
93
+ Hooks load when a session starts, so open a new session after installing. Undo everything with `recallhook uninstall`.
94
+
95
+ Try it: say *"My project Atlas runs its tests with `pnpm test:unit` and its dev server listens on port 4310."* In a **new** session ask *"how do I run the Atlas tests?"*
96
+
97
+ ## Does it save anything? (we measured)
98
+
99
+ Billed usage from `claude -p --output-format json`, Haiku, 3 rounds × 6 prompts. Three facts about a made-up project were stored; prompts either needed them or were unrelated. Interleaved runs, warm prompt cache.
100
+
101
+ | | no memory | **recallhook** | you retyping the facts |
102
+ |---|---|---|---|
103
+ | prompts needing the facts: correct | 0 / 9 | **9 / 9** | 9 / 9 |
104
+ | cost per call | $0.0061 | **$0.0026** | $0.0026 |
105
+ | time per call | 5.0 s | **4.0 s** | 3.4 s |
106
+ | unrelated prompts: cost per call | $0.0030 | **$0.0029** | n/a |
107
+
108
+ How to read this honestly:
109
+
110
+ - Without memory the model can't know the answer, so it burns turns searching files and still fails; that is where the extra cost comes from.
111
+ - **Against typing the facts yourself the cost is identical.** What you save is the typing, and not forgetting. The value is convenience and correctness, not a discount.
112
+ - On unrelated prompts nothing is injected (cutoff 0.5), so there is no overhead. Our first version used a 0.3 cutoff and injected ~170 tokens of unrelated memories per prompt, which cost +24% on those calls. We measured it, found it, and fixed it.
113
+ - Small sample, one synthetic project, one cheap model. Reproduce or extend it: [`bench/`](https://github.com/DEVPARMAR06/recallhook/tree/main/bench).
114
+
115
+ ### What we tried that did *not* pay off
116
+
117
+ We first built this as a proxy in front of the [Headroom](https://github.com/chopratejas/headroom) compression proxy. Billed cost for a 5-prompt tool-heavy session: direct $0.060, Headroom default **+14%**, Headroom lossless **+16%**, and routing through even a bare pass-through gateway **+27%** (cause not found). Rewriting requests breaks prompt-cache reuse, so short sessions pay more than they save. We dropped the proxy for the hook. (Headroom's own dashboard "savings" are estimates; billed usage is what counts.) The optional proxy mode is still in the code (`serve --spawn-headroom`) but off by default and not recommended.
118
+
119
+ ## Dashboard
120
+
121
+ `recallhook ui` or `http://127.0.0.1:8788/_recallhook/ui`
122
+
123
+ Live stats (memories, recalls, hit rate, latency, tokens injected), a 14-day chart, a live activity feed showing which memories were recalled or stored, and search / delete for every memory. Localhost-only; writes need a custom header and a foreign `Host` header is rejected, so web pages can't reach it. Prompt text is never logged, only counts, timings and the memory snippets involved.
124
+
125
+ ## Lessons baked in
126
+
127
+ - **Strip the wrapper.** A new desktop session's first message starts with thousands of characters of app boilerplate. Naively searching on the start of the prompt missed the real question; recallhook strips it and searches the start *and* end of long prompts.
128
+ - **Ignore automated turns.** Harness notifications arrive as "user" messages; they are never recalled for or stored.
129
+ - **Don't store questions.** Capturing "what port does X use?" made mem0 write near-duplicate facts.
130
+ - **Tune Ollama.** mem0 exposes none of Ollama's options, so the gateway sets them: 4k context (the 32k default spilled a 7B model onto the CPU), thinking off (`qwen3`: 150 s → ~7 s per extraction), models kept loaded, embeddings on the CPU so recall never waits behind the LLM. Extraction 15-150 s → 5-8 s; recall max 0.05 s during writes.
131
+
132
+ ## Privacy & safety
133
+
134
+ - Stored locally and **unredacted**. Don't type secrets you wouldn't want remembered. Delete any memory in the dashboard, or remove `~/.recallhook`.
135
+ - Recalled memories are added to your prompt, so those few lines reach Anthropic like anything else you type.
136
+ - Only *your* prompts are captured, never assistant replies or tool output.
137
+
138
+ ## Limits
139
+
140
+ - Built and used on Windows 11. The unit tests also pass on Linux in CI, but the full Ollama + hook flow is untested off Windows. Autostart is Windows Task Scheduler only for now.
141
+ - One shared memory per user id (no per-project scoping yet).
142
+ - Small local models sometimes miss a fact on the first try (the writer retries once); extraction quality follows your model.
143
+ - The capture filter is heuristic: it favours "I always / my project / X uses / remember" phrasing. Durable facts phrased as bare commands may be skipped.
144
+
145
+ ## Configuration
146
+
147
+ `RECALLHOOK_*` env vars: `PORT`, `OLLAMA_URL`, `LLM_MODEL`, `EMBED_MODEL`, `NUM_CTX`, `KEEP_ALIVE`, `EMBED_ON_CPU`, `STORE`, `USER_ID`, `TOP_K`, `MIN_SCORE`, `SEARCH_TIMEOUT`. Compare extraction models: `python scripts/bench_models.py qwen3:8b llama3.2:3b`.
148
+
149
+ ## Develop
150
+
151
+ ```bash
152
+ pip install -e ".[dev]" && pytest
153
+ ```
154
+
155
+ Issues and PRs welcome, especially Linux/macOS autostart, per-project scoping and more benchmarks. MIT licensed.
@@ -0,0 +1,122 @@
1
+ # recallhook
2
+
3
+ [![tests](https://github.com/DEVPARMAR06/recallhook/actions/workflows/test.yml/badge.svg)](https://github.com/DEVPARMAR06/recallhook/actions/workflows/test.yml) ![python](https://img.shields.io/badge/python-3.10%2B-blue) ![license](https://img.shields.io/badge/license-MIT-green)
4
+
5
+ **Private, local long-term memory for Claude Code.** Tell Claude something once, like *"I use pnpm"* or *"Atlas deploys to Fly.io"*, and every future session already knows it, in the **Claude desktop app, the VS Code extension and the terminal**.
6
+
7
+ No cloud, no proxy, no API key: a Claude Code hook + [mem0](https://github.com/mem0ai/mem0) + your own [Ollama](https://ollama.com) models. In our tests it **costs the same as retyping the context yourself, and nothing at all on prompts that don't need it.**
8
+
9
+ ![recallhook dashboard](https://raw.githubusercontent.com/DEVPARMAR06/recallhook/main/docs/dashboard.jpg)
10
+
11
+ ```text
12
+ You: What port does the Atlas dev server use, and how do I run its tests?
13
+
14
+ without recallhook "I don't know. Let me search your files..." (0/9 correct, wasted tool calls)
15
+ with recallhook "pnpm test:unit, port 4310." (9/9 correct, 57% cheaper than the search)
16
+ ```
17
+
18
+ ## Why
19
+
20
+ - Every new Claude Code session starts blank: your stack, conventions, ports, deploy targets, "never force-push to main"... you re-explain them, or maintain a `CLAUDE.md` by hand.
21
+ - Hosted memory services send your conversations to someone else's cloud.
22
+ - Memory tools that rely on the model *choosing* to call a tool are unreliable; this one injects relevant facts deterministically before the model sees your prompt.
23
+
24
+ recallhook watches what you tell Claude, stores the durable facts locally, and quietly adds the relevant few lines to future prompts.
25
+
26
+ ## How it works
27
+
28
+ ```text
29
+ you type a prompt ──▶ Claude Code UserPromptSubmit hook ──▶ local gateway (:8788) ──▶ mem0 + Ollama
30
+ ▲ relevant memories added as context (~30-150 tokens, ~50 ms)
31
+ └── durable statements queued for background fact extraction
32
+ ```
33
+
34
+ - **Recall** (~50 ms): the closest memories above a relevance cutoff are added to your prompt. Each memory is injected once per session (it stays in the transcript), so it doesn't repeat and burn tokens.
35
+ - **Capture** (background): a local model extracts lasting facts from statements like *"my project X uses..."*, *"I always..."*, *"remember..."*. Questions and one-off tasks ("write a one-liner...") are **not** stored.
36
+ - **Fail-open**: if anything is down or slow, the hook does nothing and your prompt goes through untouched.
37
+ - Everything is stored in `~/.recallhook` (Qdrant + SQLite). Nothing leaves your machine except what you type to Claude as usual.
38
+
39
+ | Surface | Status |
40
+ |---|---|
41
+ | Claude desktop app (Code tab) | works, tested |
42
+ | Terminal `claude` | works, tested |
43
+ | VS Code extension | uses the same `~/.claude/settings.json`, so it should work; independent testing welcome |
44
+
45
+ ## Quickstart
46
+
47
+ Requirements: Python 3.10+, [Ollama](https://ollama.com), Claude Code. An 8B model wants roughly 6 GB of VRAM/RAM.
48
+
49
+ ```bash
50
+ ollama pull nomic-embed-text
51
+ ollama pull qwen3:8b # extraction model (any chat model works)
52
+
53
+ pip install recallhook
54
+ recallhook install # Windows: start at logon + add the hook
55
+ recallhook status
56
+ recallhook ui # open the dashboard
57
+ ```
58
+
59
+ macOS/Linux: run `recallhook serve` yourself (systemd/launchd unit welcome as a PR) and `recallhook hooks on`.
60
+ Hooks load when a session starts, so open a new session after installing. Undo everything with `recallhook uninstall`.
61
+
62
+ Try it: say *"My project Atlas runs its tests with `pnpm test:unit` and its dev server listens on port 4310."* In a **new** session ask *"how do I run the Atlas tests?"*
63
+
64
+ ## Does it save anything? (we measured)
65
+
66
+ Billed usage from `claude -p --output-format json`, Haiku, 3 rounds × 6 prompts. Three facts about a made-up project were stored; prompts either needed them or were unrelated. Interleaved runs, warm prompt cache.
67
+
68
+ | | no memory | **recallhook** | you retyping the facts |
69
+ |---|---|---|---|
70
+ | prompts needing the facts: correct | 0 / 9 | **9 / 9** | 9 / 9 |
71
+ | cost per call | $0.0061 | **$0.0026** | $0.0026 |
72
+ | time per call | 5.0 s | **4.0 s** | 3.4 s |
73
+ | unrelated prompts: cost per call | $0.0030 | **$0.0029** | n/a |
74
+
75
+ How to read this honestly:
76
+
77
+ - Without memory the model can't know the answer, so it burns turns searching files and still fails; that is where the extra cost comes from.
78
+ - **Against typing the facts yourself the cost is identical.** What you save is the typing, and not forgetting. The value is convenience and correctness, not a discount.
79
+ - On unrelated prompts nothing is injected (cutoff 0.5), so there is no overhead. Our first version used a 0.3 cutoff and injected ~170 tokens of unrelated memories per prompt, which cost +24% on those calls. We measured it, found it, and fixed it.
80
+ - Small sample, one synthetic project, one cheap model. Reproduce or extend it: [`bench/`](https://github.com/DEVPARMAR06/recallhook/tree/main/bench).
81
+
82
+ ### What we tried that did *not* pay off
83
+
84
+ We first built this as a proxy in front of the [Headroom](https://github.com/chopratejas/headroom) compression proxy. Billed cost for a 5-prompt tool-heavy session: direct $0.060, Headroom default **+14%**, Headroom lossless **+16%**, and routing through even a bare pass-through gateway **+27%** (cause not found). Rewriting requests breaks prompt-cache reuse, so short sessions pay more than they save. We dropped the proxy for the hook. (Headroom's own dashboard "savings" are estimates; billed usage is what counts.) The optional proxy mode is still in the code (`serve --spawn-headroom`) but off by default and not recommended.
85
+
86
+ ## Dashboard
87
+
88
+ `recallhook ui` or `http://127.0.0.1:8788/_recallhook/ui`
89
+
90
+ Live stats (memories, recalls, hit rate, latency, tokens injected), a 14-day chart, a live activity feed showing which memories were recalled or stored, and search / delete for every memory. Localhost-only; writes need a custom header and a foreign `Host` header is rejected, so web pages can't reach it. Prompt text is never logged, only counts, timings and the memory snippets involved.
91
+
92
+ ## Lessons baked in
93
+
94
+ - **Strip the wrapper.** A new desktop session's first message starts with thousands of characters of app boilerplate. Naively searching on the start of the prompt missed the real question; recallhook strips it and searches the start *and* end of long prompts.
95
+ - **Ignore automated turns.** Harness notifications arrive as "user" messages; they are never recalled for or stored.
96
+ - **Don't store questions.** Capturing "what port does X use?" made mem0 write near-duplicate facts.
97
+ - **Tune Ollama.** mem0 exposes none of Ollama's options, so the gateway sets them: 4k context (the 32k default spilled a 7B model onto the CPU), thinking off (`qwen3`: 150 s → ~7 s per extraction), models kept loaded, embeddings on the CPU so recall never waits behind the LLM. Extraction 15-150 s → 5-8 s; recall max 0.05 s during writes.
98
+
99
+ ## Privacy & safety
100
+
101
+ - Stored locally and **unredacted**. Don't type secrets you wouldn't want remembered. Delete any memory in the dashboard, or remove `~/.recallhook`.
102
+ - Recalled memories are added to your prompt, so those few lines reach Anthropic like anything else you type.
103
+ - Only *your* prompts are captured, never assistant replies or tool output.
104
+
105
+ ## Limits
106
+
107
+ - Built and used on Windows 11. The unit tests also pass on Linux in CI, but the full Ollama + hook flow is untested off Windows. Autostart is Windows Task Scheduler only for now.
108
+ - One shared memory per user id (no per-project scoping yet).
109
+ - Small local models sometimes miss a fact on the first try (the writer retries once); extraction quality follows your model.
110
+ - The capture filter is heuristic: it favours "I always / my project / X uses / remember" phrasing. Durable facts phrased as bare commands may be skipped.
111
+
112
+ ## Configuration
113
+
114
+ `RECALLHOOK_*` env vars: `PORT`, `OLLAMA_URL`, `LLM_MODEL`, `EMBED_MODEL`, `NUM_CTX`, `KEEP_ALIVE`, `EMBED_ON_CPU`, `STORE`, `USER_ID`, `TOP_K`, `MIN_SCORE`, `SEARCH_TIMEOUT`. Compare extraction models: `python scripts/bench_models.py qwen3:8b llama3.2:3b`.
115
+
116
+ ## Develop
117
+
118
+ ```bash
119
+ pip install -e ".[dev]" && pytest
120
+ ```
121
+
122
+ Issues and PRs welcome, especially Linux/macOS autostart, per-project scoping and more benchmarks. MIT licensed.
@@ -0,0 +1,17 @@
1
+ # Benchmark
2
+
3
+ Reproduces the table in the main README: does the memory hook change what a Claude call costs?
4
+
5
+ ```bash
6
+ recallhook status # gateway must be running
7
+ bash bench/seed.sh # stores 3 made-up facts about a project called "Atlas"
8
+ bash bench/run.sh 3 # 3 rounds x 6 prompts x (no hook | hook | retyped facts), ~8 min
9
+ ```
10
+
11
+ - Uses `claude -p --output-format json`, so numbers are **billed usage** reported by Claude Code, not estimates.
12
+ - Setups are interleaved so the shared prompt cache is equally warm for each; the first call is a discarded warm-up.
13
+ - `no hook` and `hook` runs differ only by `--settings bench/settings_hook.json`.
14
+ - The prompts that need the facts are checked for the right answer; the unrelated ones measure overhead.
15
+ - Delete the made-up memories afterwards in the dashboard (`recallhook ui`).
16
+
17
+ It is a small, synthetic test on a cheap model. If you run it on your own project and models, please share the numbers.
@@ -0,0 +1,40 @@
1
+ """Summarise bench/run.sh output: cost, tokens, time and correctness per condition."""
2
+ import collections
3
+ import glob
4
+ import json
5
+ import os
6
+ import statistics as st
7
+ import sys
8
+
9
+ out = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "out")
10
+ rows = collections.defaultdict(list)
11
+ for f in sorted(glob.glob(os.path.join(out, "[ABC]_*_*.json"))):
12
+ cond, _rep, i = os.path.basename(f)[:-5].split("_")
13
+ i = int(i)
14
+ try:
15
+ d = json.load(open(f, encoding="utf-8"))
16
+ except (OSError, ValueError):
17
+ continue
18
+ u = d.get("usage", {})
19
+ res = (d.get("result") or "").lower()
20
+ ok = None
21
+ if i == 0:
22
+ ok = "pnpm test:unit" in res and "4310" in res
23
+ elif i == 1:
24
+ ok = "feat/abc-123" in res and ("fly" in res or "fra" in res)
25
+ elif i == 2:
26
+ ok = "postgres" in res and "5433" in res
27
+ rows[(cond, "needs facts" if i < 3 else "unrelated")].append(dict(
28
+ cost=d.get("total_cost_usd", 0),
29
+ tokens=u.get("input_tokens", 0) + u.get("cache_creation_input_tokens", 0) + u.get("cache_read_input_tokens", 0),
30
+ ms=d.get("duration_ms", 0), ok=ok))
31
+
32
+ names = {"A": "no memory", "B": "recallhook", "C": "retyped facts"}
33
+ print(f"{'setup':14s} {'prompts':12s} {'n':>2s} {'$/call':>9s} {'tokens in':>10s} {'secs':>5s} correct")
34
+ for key in sorted(rows, key=lambda k: (k[1], k[0])):
35
+ r = rows[key]
36
+ m = lambda a: st.mean(x[a] for x in r)
37
+ c = [x["ok"] for x in r if x["ok"] is not None]
38
+ print(f"{names[key[0]]:14s} {key[1]:12s} {len(r):2d} {m('cost'):9.5f} {m('tokens'):10.0f} {m('ms')/1000:5.1f} "
39
+ f"{sum(c)}/{len(c)}" if c else
40
+ f"{names[key[0]]:14s} {key[1]:12s} {len(r):2d} {m('cost'):9.5f} {m('tokens'):10.0f} {m('ms')/1000:5.1f} -")
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env bash
2
+ # A/B/C benchmark of the memory hook, measured in billed usage.
3
+ # A = no hook B = recallhook C = no hook, facts retyped into the prompt
4
+ # Requires: the recallhook gateway running (`recallhook status`), `claude` on PATH,
5
+ # and the three facts stored first (`bash bench/seed.sh`).
6
+ # Usage: bash bench/run.sh [rounds] (default 3; ~45 calls, ~8 minutes)
7
+ set -u
8
+ HERE="$(cd "$(dirname "$0")" && pwd)"
9
+ OUT="$HERE/out"; mkdir -p "$OUT"; rm -f "$OUT"/[ABC]_*.json
10
+ cd "$(mktemp -d)" # neutral cwd: no project CLAUDE.md or files to find
11
+ export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
12
+ F="--strict-mcp-config --disable-slash-commands --model haiku --max-turns 2 --output-format json --setting-sources project"
13
+ CTX="Context: my project Atlas runs unit tests with pnpm test:unit and its dev server listens on port 4310; I name branches like feat/ABC-123-short-slug and deploy to Fly.io in the fra region; it uses PostgreSQL 16 on port 5433 in development; I use tabs, never spaces."
14
+ P=(
15
+ "What command runs the tests for Atlas, and which port does its dev server listen on? Answer in one sentence."
16
+ "Which branch naming convention do I use for Atlas, and where do I deploy it? Answer in one sentence."
17
+ "Which database does Atlas use in development and on what port? Answer in one sentence."
18
+ "Explain in two sentences what a mutex is."
19
+ "Write a Python one-liner that reverses a string. Just the code."
20
+ "What is the difference between TCP and UDP? Three sentences max."
21
+ )
22
+ claude -p "Reply with just: ok" $F < /dev/null > /dev/null 2>&1 # warm the prompt cache, discarded
23
+ for rep in $(seq 1 "${1:-3}"); do
24
+ for i in 0 1 2 3 4 5; do
25
+ claude -p "${P[$i]}" $F < /dev/null > "$OUT/A_${rep}_$i.json" 2>/dev/null
26
+ claude -p "${P[$i]}" $F --settings "$HERE/settings_hook.json" < /dev/null > "$OUT/B_${rep}_$i.json" 2>/dev/null
27
+ if [ "$i" -lt 3 ]; then claude -p "$CTX ${P[$i]}" $F < /dev/null > "$OUT/C_${rep}_$i.json" 2>/dev/null; fi
28
+ done
29
+ done
30
+ python "$HERE/analyze.py" "$OUT"
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env bash
2
+ # Store the benchmark's facts through the running gateway and wait for extraction to finish.
3
+ set -u
4
+ PORT="${RECALLHOOK_PORT:-8788}"
5
+ BASE="http://127.0.0.1:$PORT/_recallhook/api"
6
+ post() {
7
+ curl -s -X POST -H "x-hm-client: bench" -H "content-type: application/json" \
8
+ -d "{\"text\":\"$1\",\"session\":\"seed\"}" "$BASE/prompt" > /dev/null
9
+ }
10
+ post "My project Atlas runs its unit tests with the command pnpm test:unit and its dev server listens on port 4310."
11
+ post "For Atlas I name git branches like feat/ABC-123-short-slug and I deploy it to Fly.io in the fra region."
12
+ post "Atlas uses PostgreSQL 16 on port 5433 in development, and I always use tabs rather than spaces for indentation in Atlas."
13
+ echo "waiting for extraction (the local model works in the background)..."
14
+ for _ in $(seq 1 60); do
15
+ s=$(curl -s "$BASE/summary")
16
+ q=$(echo "$s" | python -c "import sys,json;d=json.load(sys.stdin);print(d['capture_queue'],d['memories'])")
17
+ set -- $q
18
+ [ "$1" = "0" ] && [ "$2" -ge 3 ] && break
19
+ sleep 4
20
+ done
21
+ echo "queue/memories: $q"
22
+ curl -s "$BASE/memories" | python -c "import sys,json;[print(' -',m['memory']) for m in json.load(sys.stdin)]"
@@ -0,0 +1 @@
1
+ {"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"recallhook hook","timeout":8}]}]}}
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "recallhook"
7
+ version = "0.1.0"
8
+ description = "Private, local long-term memory for Claude Code (desktop app, VS Code, terminal): a hook that recalls and stores facts with mem0 + Ollama."
9
+ keywords = ["claude-code", "claude", "memory", "mem0", "ollama", "hooks", "local-first", "llm"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.10",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Topic :: Software Development",
19
+ ]
20
+ readme = "README.md"
21
+ authors = [{ name = "DEVPARMAR06" }]
22
+ license = { text = "MIT" }
23
+ requires-python = ">=3.10"
24
+ dependencies = ["mem0ai>=2.2", "ollama", "qdrant-client", "fastapi", "uvicorn", "httpx"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/DEVPARMAR06/recallhook"
28
+ Repository = "https://github.com/DEVPARMAR06/recallhook"
29
+ Issues = "https://github.com/DEVPARMAR06/recallhook/issues"
30
+
31
+ [project.optional-dependencies]
32
+ headroom = ["headroom-ai[proxy]"]
33
+ dev = ["pytest", "anyio"]
34
+
35
+ [project.scripts]
36
+ recallhook = "recallhook.cli:main"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/recallhook"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+
44
+ [tool.hatch.build.targets.sdist]
45
+ include = ["src", "tests", "bench", "scripts", "README.md", "LICENSE", "pyproject.toml"]
@@ -0,0 +1,32 @@
1
+ """Compare Ollama models for mem0 fact extraction. Usage:
2
+ python scripts/bench_models.py qwen2.5-coder:latest llama3.2:3b [--num-ctx 4096]
3
+ Reports seconds per message and how many expected facts were extracted."""
4
+ import argparse, tempfile, time
5
+
6
+ from recallhook.config import Config
7
+ from recallhook.memory import EXTRACT_RULES, build_mem0
8
+
9
+ CASES = [ # (message, keywords that must appear in the extracted facts)
10
+ ("My side project is called Nimbus. Its staging database is PostgreSQL 16 on port 5433, "
11
+ "and in all my JavaScript projects I always use pnpm, never npm.", ["nimbus", "5433", "pnpm"]),
12
+ ("Can you refactor the auth module? By the way I deploy everything on Fly.io and my team "
13
+ "does trunk-based development.", ["fly", "trunk"]),
14
+ ("Fix the failing test in utils.py", []), # no durable facts: should extract nothing
15
+ ]
16
+
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("models", nargs="+")
19
+ ap.add_argument("--num-ctx", type=int, default=4096)
20
+ a = ap.parse_args()
21
+ for model in a.models:
22
+ m = build_mem0(Config(store_path=tempfile.mkdtemp(), llm_model=model, num_ctx=a.num_ctx))
23
+ m.add([{"role": "user", "content": "warm up the model"}], user_id="w") # exclude cold load
24
+ tot, hit, want = 0.0, 0, 0
25
+ for text, kws in CASES:
26
+ t = time.time()
27
+ facts = [r["memory"].lower() for r in m.add([{"role": "user", "content": text}], user_id="b", prompt=EXTRACT_RULES)["results"]]
28
+ dt = time.time() - t
29
+ found = sum(any(k in f for f in facts) for k in kws)
30
+ tot, hit, want = tot + dt, hit + found, want + len(kws)
31
+ print(f" {model:28s} {dt:5.1f}s keywords {found}/{len(kws)} facts={len(facts)}")
32
+ print(f"{model}: total {tot:.0f}s, keywords {hit}/{want}\n")
@@ -0,0 +1,2 @@
1
+ """mem0 long-term memory, local via Ollama, in front of the Headroom proxy."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,72 @@
1
+ """JSON API used by the Claude Code hook and the dashboard."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from collections import OrderedDict
6
+
7
+ from fastapi import APIRouter, Request
8
+ from pydantic import BaseModel
9
+
10
+ from .inject import clean_prompt, format_block, is_automated, is_question, looks_durable, recall_query
11
+ from .security import make_guard
12
+
13
+
14
+ class PromptIn(BaseModel):
15
+ text: str
16
+ user: str | None = None
17
+ session: str | None = None
18
+
19
+
20
+ def build_api_router(cfg, memory) -> APIRouter:
21
+ r = APIRouter(prefix="/_recallhook/api")
22
+ guard = make_guard(cfg)
23
+ # memories already injected per Claude session: injecting the same fact on every
24
+ # prompt would just burn tokens, since earlier injections stay in the transcript.
25
+ seen: OrderedDict[str, set[str]] = OrderedDict()
26
+
27
+ @r.post("/prompt")
28
+ async def prompt(request: Request, body: PromptIn):
29
+ """One round trip for the hook: recall relevant memories, then queue capture."""
30
+ guard(request, mutating=True)
31
+ user = body.user or cfg.user_id
32
+ if is_automated(body.text): # app/harness messages, not the user
33
+ return {"block": "", "hits": 0}
34
+ text = clean_prompt(body.text)
35
+ if len(text) < cfg.min_chars or text.startswith("/"):
36
+ return {"block": "", "hits": 0}
37
+ items = await memory.recall(recall_query(text), user, source="hook") if cfg.inject else []
38
+ items = items or []
39
+ sid = body.session or ""
40
+ known = seen.setdefault(sid, set())
41
+ seen.move_to_end(sid)
42
+ while len(seen) > 200:
43
+ seen.popitem(last=False)
44
+ fresh = [i for i in items if i["id"] not in known]
45
+ known.update(i["id"] for i in fresh)
46
+ if not is_question(text) and looks_durable(text):
47
+ memory.capture(text, user)
48
+ return {"block": format_block([i["memory"] for i in fresh]) if fresh else "", "hits": len(fresh)}
49
+
50
+ @r.get("/activity")
51
+ async def activity(request: Request, limit: int = 40):
52
+ guard(request)
53
+ return memory.events.recent(min(limit, 200))
54
+
55
+ @r.get("/series")
56
+ async def series(request: Request, days: int = 14):
57
+ guard(request)
58
+ return memory.events.series(min(days, 90))
59
+
60
+ @r.get("/summary")
61
+ async def summary(request: Request):
62
+ guard(request)
63
+ t = memory.events.totals()
64
+ try:
65
+ t["memories"] = len(await asyncio.to_thread(memory.list_all, cfg.user_id))
66
+ except Exception: # noqa: BLE001
67
+ t["memories"] = None
68
+ t["capture_queue"] = memory._q.qsize()
69
+ t["failures"] = memory.stats.get("search_failures", 0)
70
+ return t
71
+
72
+ return r