memoryrouter-claude 1.0.1 → 2.1.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,50 @@
1
+ # Changelog
2
+
3
+ ## 2.1.0 (2026-08-05)
4
+
5
+ ### Fixed
6
+
7
+ - Replaced full transcript-delta ingestion with one typed `user_prompt` and one typed `assistant_final` per Claude Code turn.
8
+ - Made `/prepare` recall a separate read-only operation after local prompt-event creation.
9
+ - Added durable request-level idempotency before conversation buffering: D1 reserves and pins the event target, then the Durable Object atomically records the receipt and appends once.
10
+ - Added lost-`202` recovery. Repeated delivery returns durable `duplicate` success without a second buffer append.
11
+ - Made `last_assistant_message` authoritative and added a conservative transcript fallback that rejects partial JSON, tool-last records, and sidechains.
12
+ - Removed automatic tool, intermediate assistant, tool result/failure, compaction summary, `StopFailure`, and subagent transcript capture.
13
+
14
+ ### Compatibility and operations
15
+
16
+ - Untyped legacy `messages[]` ingest requests retain their existing behavior.
17
+ - Typed capture requires additive D1 migration `0029_capture_event_receipts.sql` before Worker deployment.
18
+ - Completed D1 receipts are retained for 90 days; local turn state remains 30 days by default.
19
+ - Added durable pending-chunk leases so background embedding/mirroring can resume after a crash without losing accepted buffer content.
20
+
21
+ ## 2.0.0 (2026-07-31)
22
+
23
+ > Superseded by 2.1.0. The transcript-delta/full-turn capture and local content-key deduplication described below were audited as semantically incorrect and are no longer used.
24
+
25
+ ### Fixed
26
+
27
+ - Replaced the lossy line high-water capture with byte-accurate transcript deltas.
28
+ - Capture now preserves meaningful intermediate assistant text, tool calls, commands, edited file paths/content summaries, tool outcomes, failures, and final decisions.
29
+ - Added write-ahead pending batches, deterministic retry payloads, content-key deduplication, partial-write blocking, legacy cursor migration, and per-session state locking.
30
+ - Stopped using Claude's ephemeral session UUID as the only memory scope.
31
+
32
+ ### Added
33
+
34
+ - Deterministic `ccp_…` project identity from explicit override, normalized Git remote, Git common directory, or canonical project directory.
35
+ - Hard project partitioning by stable MemoryRouter session vault, worktree sharing, isolated no-Git folders, and explicit global/global-plus-project modes.
36
+ - `StopFailure`, `PostCompact`, post-compact/resume/fork reinjection, and optional `SubagentStop` lifecycle handling.
37
+ - Async startup warmup, state TTL pruning, `.memoryrouterignore`, project-local `.memoryrouter.json`, and `MEMORYROUTER_DISABLE=1`.
38
+ - `--local` settings scope, versioned config migration, `doctor`, safer uninstall/purge behavior, and MCP install/status/remove helpers.
39
+ - Comprehensive regression fixtures/tests for full-turn capture, partial JSONL, crash recovery, duplicate capture, worktrees, scoping, compaction, subagents, offline behavior, migration, and installer preservation.
40
+
41
+ ### Changed
42
+
43
+ - Hooks are explicitly the automatic engine; the OAuth remote MCP server is the manual control surface.
44
+ - Canonical read-only setup uses the `:read` key suffix. `mk_ro_` is documented only as a legacy-compatible form.
45
+ - Package requires no runtime dependencies and remains Node.js 18+ compatible.
46
+
47
+ ### Known server dependencies
48
+
49
+ - `/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.
50
+ - 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,231 @@
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 durably capture one user prompt and one final user-visible response per turn, retrieve relevant memory through a separate read-only request, 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` | Create one local typed `user_prompt`, then deliver it and run semantic recall in parallel | Capture and `/prepare` recall are separate requests; recall stays read-only |
53
+ | `Stop` | Durably accept one typed `assistant_final` | Uses `last_assistant_message`; conservative transcript fallback accepts only a complete, main-chain, text-only final record |
54
+ | `StopFailure` | Retry an unacknowledged prompt | Marks the local turn failed; never invents or stores a final response |
55
+ | `PreCompact` / `PostCompact` | Retry already-created pending events | Compaction summaries and transcript deltas are not captured |
56
+ | `SessionStart: compact` | Re-retrieve and inject memory | Official post-compaction reinjection path |
57
+ | `SessionStart: resume/fork` | Re-retrieve and inject memory | Restores external memory at session boundaries |
58
+ | `SubagentStop` | No capture | Subagent and delegated chatter is always excluded |
59
+ | `SessionEnd` | Retry pending typed events | Does not scan or ingest the transcript |
60
+
61
+ ## Deterministic capture and durable retry safety
62
+
63
+ Each Claude Code turn has a crash-safe local record under `~/.memoryrouter/state/` with a stable client session ID, monotonic turn ID, and two stable idempotency keys. The client writes that record before network I/O and marks an event accepted only when the typed server contract returns `durable: true` with `status: accepted` or `duplicate`.
64
+
65
+ The typed request is opt-in through `capture_event` on `POST /v1/memory/ingest`:
66
+
67
+ ```json
68
+ {
69
+ "session_id": "ccp_project_partition",
70
+ "capture_event": {
71
+ "version": 1,
72
+ "source": "claude-code-hooks",
73
+ "event_type": "user_prompt",
74
+ "idempotency_key": "cce_stable_event_key",
75
+ "project_id": "ccp_project_partition",
76
+ "client_session_id": "claude-session-id",
77
+ "turn_id": "cct_stable_turn_id",
78
+ "occurred_at": 1785990000000,
79
+ "content": "the exact user prompt"
80
+ }
81
+ }
44
82
  ```
45
83
 
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.
84
+ Server acceptance is ordered for lost-response safety:
47
85
 
48
- ## Commands
86
+ 1. D1 reserves `(memory_key, idempotency_key)` and pins the target Durable Object shard before any conversation buffer is touched.
87
+ 2. The pinned Durable Object atomically inserts its local event receipt, appends the typed content, updates the pending buffer, and persists any complete chunks to a durable embedding outbox.
88
+ 3. D1 marks the receipt buffered.
89
+ 4. Only then does the endpoint return `202` with `durable: true`.
90
+ 5. A retry after a lost response follows the pinned shard, sees the existing receipt, returns `duplicate`, and cannot append again.
49
91
 
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 |
92
+ The two accepted event types map server-side to `user` and `assistant`. Legacy clients that send `messages[]` without `capture_event` retain the existing fire-and-forget behavior; this release does not silently change their contract.
57
93
 
58
- ### Scopes
94
+ ### What automatic capture excludes
59
95
 
60
- - `--project` (default): writes to `./.claude/settings.json` — this project only, committable
61
- - `--user`: writes to `~/.claude/settings.json` — every project on this machine
96
+ Automatic capture never ingests intermediate assistant text, tool calls, commands, file edits, tool results, tool failures, injected memory, thinking/signature blocks, compaction summaries, `StopFailure` error text, or subagent transcripts. For a normal `Stop`, `last_assistant_message` is authoritative. The transcript fallback refuses malformed/partial JSON, sidechains, or a tool-use record as the last assistant record. An empty or uncertain final remains locally open for a later retry rather than guessing.
62
97
 
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.
98
+ ### Retry, interruption, and retention behavior
64
99
 
65
- ## Configuration
100
+ - On the first 2.1 hook run, any v2.0 `pendingCapture` transcript digest is discarded rather than replayed, because it may contain tool/intermediate/subagent chatter. Only the legacy batch ID and discard reason remain locally for diagnosis.
101
+ - Repeated `UserPromptSubmit` delivery while a turn is open resumes the same prompt event. The same text submitted after a completed final creates a new turn and new idempotency keys.
102
+ - Repeated `Stop` delivery retries the same final event or becomes a no-op after acceptance.
103
+ - A lost `202` leaves the local event pending. The next applicable hook sends byte-for-byte identical typed event identity; server receipts prevent a second append.
104
+ - A different prompt arriving before the prior final marks the prior local turn interrupted and starts a new turn. Any unacknowledged event remains retryable; no synthetic final is created.
105
+ - Before a new prompt is appended, older pending prompt/final events are retried in original turn order. If an older event is still unavailable, the new prompt remains locally pending rather than reordering the server buffer.
106
+ - Local state is retained for 30 days by default. Server idempotency receipts are retained for 90 days, then bounded cleanup may remove completed receipts. Replaying an event after both retention windows is outside the retry guarantee.
107
+ - Read-only keys can recall but cannot durably accept capture. Pending local events are retained rather than falsely marked committed.
108
+
109
+ ## Deterministic project isolation
110
+
111
+ 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.
112
+
113
+ Identity precedence:
114
+
115
+ 1. `MEMORYROUTER_PROJECT_ID` explicit environment override
116
+ 2. `.memoryrouter.json` `projectId` / `project`
117
+ 3. `~/.memoryrouter/config.json` `projectId` / `project`
118
+ 4. normalized Git remote (`git@host:Org/Repo.git` and HTTPS normalize identically)
119
+ 5. Git common directory (makes worktrees share identity when no remote exists)
120
+ 6. canonical `CLAUDE_PROJECT_DIR` / current directory for non-Git workspaces
121
+
122
+ 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.
123
+
124
+ ### Project configuration
125
+
126
+ An optional non-secret `.memoryrouter.json` at the project root can be committed:
127
+
128
+ ```json
129
+ {
130
+ "projectId": "acme-api",
131
+ "memoryScope": "project",
132
+ "includeGlobal": false,
133
+ "captureEnabled": true
134
+ }
135
+ ```
136
+
137
+ 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.
138
+
139
+ ### Personal/global memory
140
+
141
+ Project memory is the secure default. To deliberately use one personal/global vault across projects:
142
+
143
+ ```bash
144
+ npx memoryrouter-claude init --global --yes
145
+ ```
146
+
147
+ To recall both isolated project memory and personal/global memory while continuing to write automatic captures only to the project:
148
+
149
+ ```bash
150
+ npx memoryrouter-claude init --include-global --yes
151
+ ```
152
+
153
+ Global recall is opt-in because it can intentionally surface facts across projects.
154
+
155
+ ## Install, upgrade, and scopes
66
156
 
67
- | What | Where |
157
+ ```bash
158
+ npx memoryrouter-claude init --project # .claude/settings.json; team/shareable
159
+ npx memoryrouter-claude init --local # .claude/settings.local.json; private project
160
+ npx memoryrouter-claude init --user # ~/.claude/settings.json; all projects
161
+ npx memoryrouter-claude init --key mk_xxx --local --yes
162
+ ```
163
+
164
+ 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.
165
+
166
+ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mode `0700` directory. Project settings contain only the hook command.
167
+
168
+ ## Commands
169
+
170
+ | Command | Purpose |
68
171
  |---|---|
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) |
172
+ | `npx memoryrouter-claude init` | Install or upgrade automatic hooks |
173
+ | `npx memoryrouter-claude doctor` | Diagnose config, permissions, hooks, project ID, pending capture, API, and MCP |
174
+ | `npx memoryrouter-claude status` | Show key, vault stats, and active project scope |
175
+ | `npx memoryrouter-claude mcp install` | Add the OAuth MCP manual surface with current Claude CLI syntax |
176
+ | `npx memoryrouter-claude mcp status` | Inspect MCP configuration |
177
+ | `npx memoryrouter-claude mcp remove` | Remove MCP only; hooks stay installed |
178
+ | `npx memoryrouter-claude off` | Remove MemoryRouter hooks from local/project/user settings |
179
+ | `npx memoryrouter-claude off --purge` | Also delete private key/config/checkpoint state |
74
180
 
75
- Optional knobs in `~/.memoryrouter/config.json`:
181
+ ## Configuration
182
+
183
+ `~/.memoryrouter/config.json` is versioned and migrated non-destructively:
76
184
 
77
185
  ```json
78
186
  {
187
+ "configVersion": 2,
79
188
  "apiKey": "mk_...",
189
+ "memoryScope": "project",
190
+ "includeGlobal": false,
191
+ "captureEnabled": true,
80
192
  "contextLimit": 2000,
81
- "density": "balanced"
193
+ "density": "balanced",
194
+ "maxContextChars": 9500,
195
+ "stateTtlDays": 30
82
196
  }
83
197
  ```
84
198
 
85
- ## Security notes
199
+ Environment overrides:
200
+
201
+ | Variable | Purpose |
202
+ |---|---|
203
+ | `MEMORYROUTER_API_KEY` | Key override; highest key precedence |
204
+ | `MEMORYROUTER_PROJECT_ID` | Explicit stable project identity |
205
+ | `MEMORYROUTER_DISABLE=1` | Disable automatic hooks without uninstalling |
206
+ | `MEMORYROUTER_API_BASE` | Test/self-hosted API base |
207
+ | `MEMORYROUTER_CONFIG_DIR` | Test/managed config location |
208
+ | `MEMORYROUTER_DEBUG=1` | Diagnostic stderr from hooks |
86
209
 
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.
210
+ 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.
91
211
 
92
- ## Uninstall
212
+ ## Local retention and failure behavior
213
+
214
+ - Typed turn records, stable event keys, acceptance status, and the latest prompt are kept at `~/.memoryrouter/state/<session>.json`, mode `0600`, for safe retry and reinjection.
215
+ - State files are pruned after 30 days by default.
216
+ - Local typed turn records can contain prompt and final-response text (up to 100,000 characters per event). Use `.memoryrouterignore`, `enabled: false`, or `MEMORYROUTER_DISABLE=1` for sensitive projects.
217
+ - Every hook exits successfully from Claude Code's perspective. Retrieval failures produce no injected context; write failures retain pending typed events for retry.
218
+ - Hook wall clocks are 8 seconds for retrieval and 27 seconds for capture paths, below their configured Claude Code timeouts.
219
+
220
+ ## Development
93
221
 
94
222
  ```bash
95
- npx memoryrouter-claude off # removes hooks from project + user settings
96
- rm -rf ~/.memoryrouter # removes your key + local state
223
+ npm run check
224
+ npm test
225
+ npm pack --dry-run
97
226
  ```
98
227
 
99
- ## Requirements
100
-
101
- - Node.js ≥ 18
102
- - Claude Code
103
- - A MemoryRouter Memory Key — free at [app.memoryrouter.ai](https://app.memoryrouter.ai)
228
+ No runtime dependencies. Requires Node.js 18+ and Claude Code.
104
229
 
105
230
  ## License
106
231