memoryrouter-claude 1.0.1 → 2.0.0

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0 — 2026-07-31
4
+
5
+ ### Fixed
6
+
7
+ - Replaced the lossy line high-water capture with byte-accurate transcript deltas.
8
+ - Capture now preserves meaningful intermediate assistant text, tool calls, commands, edited file paths/content summaries, tool outcomes, failures, and final decisions.
9
+ - Added write-ahead pending batches, deterministic retry payloads, content-key deduplication, partial-write blocking, legacy cursor migration, and per-session state locking.
10
+ - Stopped using Claude's ephemeral session UUID as the only memory scope.
11
+
12
+ ### Added
13
+
14
+ - Deterministic `ccp_…` project identity from explicit override, normalized Git remote, Git common directory, or canonical project directory.
15
+ - Hard project partitioning by stable MemoryRouter session vault, worktree sharing, isolated no-Git folders, and explicit global/global-plus-project modes.
16
+ - `StopFailure`, `PostCompact`, post-compact/resume/fork reinjection, and optional `SubagentStop` lifecycle handling.
17
+ - Async startup warmup, state TTL pruning, `.memoryrouterignore`, project-local `.memoryrouter.json`, and `MEMORYROUTER_DISABLE=1`.
18
+ - `--local` settings scope, versioned config migration, `doctor`, safer uninstall/purge behavior, and MCP install/status/remove helpers.
19
+ - Comprehensive regression fixtures/tests for full-turn capture, partial JSONL, crash recovery, duplicate capture, worktrees, scoping, compaction, subagents, offline behavior, migration, and installer preservation.
20
+
21
+ ### Changed
22
+
23
+ - Hooks are explicitly the automatic engine; the OAuth remote MCP server is the manual control surface.
24
+ - Canonical read-only setup uses the `:read` key suffix. `mk_ro_` is documented only as a legacy-compatible form.
25
+ - Package requires no runtime dependencies and remains Node.js 18+ compatible.
26
+
27
+ ### Known server dependencies
28
+
29
+ - `/v1/memory/ingest` acknowledges queue acceptance (`202`) before its background durable write completes. The hook never checkpoints before acceptance, but end-to-end post-acceptance confirmation requires a future server status/receipt API.
30
+ - The current public MCP server does not expose a project-handle argument or real ID-backed per-memory deletion. The package deliberately keeps automatic project memory isolated and does not fake `/forget`; scoped MCP operations require the corresponding server upgrade, and deletion remains a dashboard operation until then.
package/README.md CHANGED
@@ -1,106 +1,206 @@
1
1
  # memoryrouter-claude
2
2
 
3
- **Persistent memory for Claude Code.** One command installs hooks that give Claude Code a real long-term memory: relevant context injected into every turn, every conversation captured, and nothing lost to compaction — powered by [MemoryRouter](https://memoryrouter.ai).
3
+ **Deterministic, project-scoped persistent memory for Claude Code.** Automatic hooks retrieve relevant memory before every prompt, capture complete coding turns, flush before compaction, and restore memory after compaction or resume.
4
4
 
5
5
  ```bash
6
6
  npx memoryrouter-claude init
7
+ npx memoryrouter-claude doctor
7
8
  ```
8
9
 
9
- That's it. Paste your Memory Key (free at [app.memoryrouter.ai](https://app.memoryrouter.ai)), pick a scope, and your Claude Code sessions remember everything — across sessions, across machines, across every AI platform connected to your vault.
10
+ MemoryRouter complements Claude Code's local auto memory: it is semantic, cross-machine, cross-platform, and durable beyond one context window.
10
11
 
11
- ## Why
12
+ ## Architecture: hooks are automatic; MCP is explicit
12
13
 
13
- Claude Code's built-in auto memory is local notes per project on one machine. MemoryRouter is a different layer:
14
+ The integration deliberately uses two surfaces:
14
15
 
15
- - **Semantic search** over your full conversation history, not curated notes
16
- - **Cross-machine** — same memory on your laptop and your server
17
- - **Cross-platform** — the same vault works in ChatGPT, Claude.ai, OpenClaw, and your own apps
18
- - **Compaction-proof** — the full transcript is saved *before* Claude Code compacts it away
16
+ - **Hooks are the automatic memory engine.** They run at deterministic Claude Code lifecycle points whether or not the model chooses a tool.
17
+ - **The OAuth MCP server is the manual/control surface.** Claude can explicitly search or store memory when asked, and resources expose vault information.
19
18
 
20
- ## How it works
19
+ ```bash
20
+ npx memoryrouter-claude mcp install # local Claude MCP scope by default
21
+ claude mcp login memoryrouter # OAuth; select the same vault as the hook key
22
+ ```
23
+
24
+ Use `/mcp` in Claude Code to inspect the connection. The MCP endpoint is `https://mcp.memoryrouter.ai/mcp`; the Memory Key is never written into MCP or Claude settings. The explicit operations available today are:
25
+
26
+ - **Recall:** ask Claude to search MemoryRouter; it uses `search_memories`.
27
+ - **Remember:** ask Claude to remember durable content; it uses `store_memory`.
28
+ - **Status:** inspect `memory://vault/stats` in the MCP resource browser (or run `memoryrouter-claude status`).
29
+ - **Forget:** requires the real delete capability described below; use the dashboard until it ships.
21
30
 
22
- The installer adds five hooks to your Claude Code settings:
31
+ Teams that deliberately want MemoryRouter tools loaded up front rather than deferred by Claude Code tool search can commit this `.mcp.json` (Claude still asks each user to approve and authenticate it):
23
32
 
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "memoryrouter": {
37
+ "type": "http",
38
+ "url": "https://mcp.memoryrouter.ai/mcp",
39
+ "alwaysLoad": true
40
+ }
41
+ }
42
+ }
24
43
  ```
25
- ┌────────────────────────────────────────────────────────────────┐
26
- │ Claude Code session │
27
- │ │
28
- │ SessionStart ──────► POST /v1/memory/warmup │
29
- │ (pre-load your vault → fast first recall)│
30
- │ │
31
- │ UserPromptSubmit ──► POST /v1/memory/prepare │
32
- │ (every prompt) relevant memories injected as context │
33
- │ │
34
- │ Stop ──────────────► POST /v1/memory/ingest │
35
- │ (every turn) user prompt + assistant reply captured │
36
- │ │
37
- │ PreCompact ────────► POST /v1/memory/ingest │
38
- │ (before compaction) full un-saved transcript flushed │
39
- │ │
40
- │ SessionEnd ────────► POST /v1/memory/ingest │
41
- │ (session close) final flush │
42
- └────────────────────────────────────────────────────────────────┘
43
- api.memoryrouter.ai · Bearer mk_xxx
44
+
45
+ > Current server dependencies: the public MCP server exposes search/store plus stats/recent resources, but does not yet expose per-memory deletion or a project-handle argument. Automatic hook memory is hard-partitioned in the `ccp_…` project vault, while today's remote MCP tools operate on the personal/global surface. Full project-scoped MCP recall/remember requires the server to accept and enforce the same project handle. Do not represent `/forget` as working until the server ships a real ID-backed delete tool. Use the MemoryRouter dashboard for deletion today. The hook package does not weaken project isolation, fake IDs, or pretend deletion succeeded.
46
+
47
+ ## Lifecycle
48
+
49
+ | Claude Code event | Automatic action | Notes |
50
+ |---|---|---|
51
+ | `SessionStart` | Warm project vault | Async hook; does not block startup |
52
+ | `UserPromptSubmit` | Project-scoped semantic recall | Fails open; output capped below Claude's 10K hook limit |
53
+ | `Stop` | Capture the full transcript delta | Text, decisions, commands, changed files, tool outcomes; no raw thinking |
54
+ | `StopFailure` | Recovery flush | Preserves completed work when the turn ends on an API failure |
55
+ | `PreCompact` | Flush all accepted complete JSONL records | Cursor never advances over failed, malformed, or partial data |
56
+ | `PostCompact` | Store Claude's compact summary | `PostCompact` cannot inject context by platform contract |
57
+ | `SessionStart: compact` | Re-retrieve and inject memory | Official post-compaction reinjection path |
58
+ | `SessionStart: resume/fork` | Re-retrieve and inject memory | Restores external memory at session boundaries |
59
+ | `SubagentStop` | Optional subagent capture | Off by default; enable deliberately |
60
+ | `SessionEnd` | Final checkpointed flush | Session state retained for safe resume, then pruned by TTL |
61
+
62
+ Claude Code writes transcripts asynchronously. At `Stop`, `last_assistant_message` is used as a deduplicated fallback if the final response is not in JSONL yet. Tool activity already present in JSONL is captured in order.
63
+
64
+ ## Capture correctness and crash safety
65
+
66
+ Version 2 fixes the v1 data-loss bug. V1 sent only the cached prompt and final assistant message, then moved its high-water line to EOF, permanently skipping intermediate assistant messages, tool calls, and tool results.
67
+
68
+ V2 uses a byte cursor and a write-ahead pending batch:
69
+
70
+ 1. Read from the last **committed byte offset**.
71
+ 2. Stop before malformed/partially written JSON; never leapfrog it.
72
+ 3. Normalize every meaningful record into a bounded digest. Preserve decisions, commands, file paths/edits, failures, and tool outcomes; omit thinking blocks, reminders, and binary/noisy payloads.
73
+ 4. Save the deterministic batch and digest ID locally **before** network I/O.
74
+ 5. Send one assistant digest so the current ingest API does not discard earlier user records.
75
+ 6. Advance the cursor only after MemoryRouter returns a successful acceptance response.
76
+ 7. On a crash or ambiguous retry, resend the exact same digest. Server content hashing deduplicates an already-processed retry.
77
+
78
+ The ingest endpoint currently returns `202 Accepted` and performs durable storage in a server background task. The client can guarantee that it never marks an unaccepted batch complete; detecting a post-acceptance server background failure requires a future server acknowledgement/status API.
79
+
80
+ ## Deterministic project isolation
81
+
82
+ Automatic storage and recall use a stable project handle as the MemoryRouter `session_id`, rather than Claude Code's ephemeral session UUID. That gives hard server-side project partitioning and makes memory available to later Claude sessions in the same project.
83
+
84
+ Identity precedence:
85
+
86
+ 1. `MEMORYROUTER_PROJECT_ID` explicit environment override
87
+ 2. `.memoryrouter.json` `projectId` / `project`
88
+ 3. `~/.memoryrouter/config.json` `projectId` / `project`
89
+ 4. normalized Git remote (`git@host:Org/Repo.git` and HTTPS normalize identically)
90
+ 5. Git common directory (makes worktrees share identity when no remote exists)
91
+ 6. canonical `CLAUDE_PROJECT_DIR` / current directory for non-Git workspaces
92
+
93
+ Only `ccp_<24 hex>` is sent to MemoryRouter. Raw local paths, Git credentials, and remote URLs stay local. Worktrees of one repository share an ID; unrelated no-Git directories do not.
94
+
95
+ ### Project configuration
96
+
97
+ An optional non-secret `.memoryrouter.json` at the project root can be committed:
98
+
99
+ ```json
100
+ {
101
+ "projectId": "acme-api",
102
+ "memoryScope": "project",
103
+ "includeGlobal": false,
104
+ "captureSubagents": false,
105
+ "captureEnabled": true
106
+ }
44
107
  ```
45
108
 
46
- Every hook **fails open**: if the network or API is down, the hook exits 0 instantly and Claude Code continues as if nothing happened. Your prompts are never blocked, ever.
109
+ Create `.memoryrouterignore` at the project root, set `"enabled": false`, or export `MEMORYROUTER_DISABLE=1` to disable automatic recall/capture for a sensitive workspace without uninstalling hooks.
47
110
 
48
- ## Commands
111
+ ### Personal/global memory
49
112
 
50
- | Command | What it does |
51
- |---|---|
52
- | `npx memoryrouter-claude init` | Validate key, install hooks (interactive) |
53
- | `npx memoryrouter-claude init --key mk_xxx --user --yes` | Non-interactive install for all projects |
54
- | `npx memoryrouter-claude status` | Key validity + vault stats |
55
- | `npx memoryrouter-claude off` | Remove our hooks (only ours — your other hooks untouched) |
56
- | `npx memoryrouter-claude hook <kind>` | Internal — invoked by Claude Code |
113
+ Project memory is the secure default. To deliberately use one personal/global vault across projects:
114
+
115
+ ```bash
116
+ npx memoryrouter-claude init --global --yes
117
+ ```
118
+
119
+ To recall both isolated project memory and personal/global memory while continuing to write automatic captures only to the project:
57
120
 
58
- ### Scopes
121
+ ```bash
122
+ npx memoryrouter-claude init --include-global --yes
123
+ ```
59
124
 
60
- - `--project` (default): writes to `./.claude/settings.json` — this project only, committable
61
- - `--user`: writes to `~/.claude/settings.json` — every project on this machine
125
+ Global recall is opt-in because it can intentionally surface facts across projects.
62
126
 
63
- The installer **merges** with your existing settings. It never overwrites other hooks or settings, it's idempotent (run it twice, get one set of hooks), and `off` removes exactly what it added.
127
+ ## Install, upgrade, and scopes
64
128
 
65
- ## Configuration
129
+ ```bash
130
+ npx memoryrouter-claude init --project # .claude/settings.json; team/shareable
131
+ npx memoryrouter-claude init --local # .claude/settings.local.json; private project
132
+ npx memoryrouter-claude init --user # ~/.claude/settings.json; all projects
133
+ npx memoryrouter-claude init --key mk_xxx --local --yes
134
+ ```
135
+
136
+ Running `init` again is the upgrade path. It migrates config to the current schema, removes only older MemoryRouter-owned hook entries, and adds one current set. Foreign settings and hooks are preserved. Corrupt JSON is rejected without modification.
137
+
138
+ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mode `0700` directory. Project settings contain only the hook command.
66
139
 
67
- | What | Where |
140
+ ## Commands
141
+
142
+ | Command | Purpose |
68
143
  |---|---|
69
- | Memory Key | `~/.memoryrouter/config.json` (created with `0600` permissions) |
70
- | Per-session state | `~/.memoryrouter/state/<session_id>.json` |
71
- | Env override | `MEMORYROUTER_API_KEY` (takes priority over the config file) |
72
- | Debug logging | `MEMORYROUTER_DEBUG=1` (hooks log to stderr) |
73
- | API base override | `MEMORYROUTER_API_BASE` (testing) |
144
+ | `npx memoryrouter-claude init` | Install or upgrade automatic hooks |
145
+ | `npx memoryrouter-claude doctor` | Diagnose config, permissions, hooks, project ID, pending capture, API, and MCP |
146
+ | `npx memoryrouter-claude status` | Show key, vault stats, and active project scope |
147
+ | `npx memoryrouter-claude mcp install` | Add the OAuth MCP manual surface with current Claude CLI syntax |
148
+ | `npx memoryrouter-claude mcp status` | Inspect MCP configuration |
149
+ | `npx memoryrouter-claude mcp remove` | Remove MCP only; hooks stay installed |
150
+ | `npx memoryrouter-claude off` | Remove MemoryRouter hooks from local/project/user settings |
151
+ | `npx memoryrouter-claude off --purge` | Also delete private key/config/checkpoint state |
152
+
153
+ ## Configuration
74
154
 
75
- Optional knobs in `~/.memoryrouter/config.json`:
155
+ `~/.memoryrouter/config.json` is versioned and migrated non-destructively:
76
156
 
77
157
  ```json
78
158
  {
159
+ "configVersion": 2,
79
160
  "apiKey": "mk_...",
161
+ "memoryScope": "project",
162
+ "includeGlobal": false,
163
+ "captureEnabled": true,
164
+ "captureSubagents": false,
80
165
  "contextLimit": 2000,
81
- "density": "balanced"
166
+ "density": "balanced",
167
+ "maxContextChars": 9500,
168
+ "captureBatchChars": 32000,
169
+ "captureMaxBatches": 8,
170
+ "stateTtlDays": 30
82
171
  }
83
172
  ```
84
173
 
85
- ## Security notes
174
+ Environment overrides:
175
+
176
+ | Variable | Purpose |
177
+ |---|---|
178
+ | `MEMORYROUTER_API_KEY` | Key override; highest key precedence |
179
+ | `MEMORYROUTER_PROJECT_ID` | Explicit stable project identity |
180
+ | `MEMORYROUTER_DISABLE=1` | Disable automatic hooks without uninstalling |
181
+ | `MEMORYROUTER_API_BASE` | Test/self-hosted API base |
182
+ | `MEMORYROUTER_CONFIG_DIR` | Test/managed config location |
183
+ | `MEMORYROUTER_DEBUG=1` | Diagnostic stderr from hooks |
184
+
185
+ Read-only mode uses the canonical `:read` suffix, for example `mk_xxx:read`. The legacy `mk_ro_` form is still accepted by the API for compatibility but should not be used in new setup instructions. A read-only key retrieves normally and the server returns a successful `skipped` result for capture.
186
+
187
+ ## Local retention and failure behavior
86
188
 
87
- - Your Memory Key is stored **only** in `~/.memoryrouter/config.json` with `0600` permissions — never inside `.claude/settings.json`, so committing project settings never leaks your key.
88
- - All API traffic is HTTPS to `api.memoryrouter.ai` with `Authorization: Bearer` auth.
89
- - Want read-only injection with no capture? Use a key with the `:read` suffix (`mk_xxx:read`) — the server skips storage automatically.
90
- - Nothing is ever sent anywhere except your MemoryRouter vault.
189
+ - Checkpoints and the latest prompt are kept at `~/.memoryrouter/state/<session>.json`, mode `0600`, for safe resume and final-message deduplication.
190
+ - State files are pruned after 30 days by default.
191
+ - The latest prompt cache can contain sensitive text (up to 100,000 characters). Use `.memoryrouterignore`, `enabled: false`, or `MEMORYROUTER_DISABLE=1` for sensitive projects.
192
+ - Every hook exits successfully from Claude Code's perspective. Retrieval failures produce no injected context; write failures retain the pending batch and cursor for retry.
193
+ - Hook wall clocks are 8 seconds for retrieval and 27 seconds for capture paths, below their configured Claude Code timeouts.
91
194
 
92
- ## Uninstall
195
+ ## Development
93
196
 
94
197
  ```bash
95
- npx memoryrouter-claude off # removes hooks from project + user settings
96
- rm -rf ~/.memoryrouter # removes your key + local state
198
+ npm run check
199
+ npm test
200
+ npm pack --dry-run
97
201
  ```
98
202
 
99
- ## Requirements
100
-
101
- - Node.js ≥ 18
102
- - Claude Code
103
- - A MemoryRouter Memory Key — free at [app.memoryrouter.ai](https://app.memoryrouter.ai)
203
+ No runtime dependencies. Requires Node.js 18+ and Claude Code.
104
204
 
105
205
  ## License
106
206