dsh-memvault 0.9.12 → 0.10.1

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.
Files changed (48) hide show
  1. package/README.md +52 -397
  2. package/README.zh.md +51 -325
  3. package/cordis.patch.yml +18 -20
  4. package/docs/CORE-DESIGN.md +277 -0
  5. package/docs/DETAIL.md +1 -0
  6. package/docs/DETAIL.zh.md +1 -0
  7. package/docs/DEVLOG.md +752 -0
  8. package/docs/images/relation-graph-2026-11-02.png +0 -0
  9. package/docs/preview.svg +41 -0
  10. package/icon.svg +9 -0
  11. package/lib/blocks.js +11 -2
  12. package/lib/client.js +705 -168
  13. package/lib/config.js +46 -87
  14. package/lib/core/adjudicate.js +94 -0
  15. package/lib/core/backfill.js +32 -0
  16. package/lib/core/block-write.js +85 -0
  17. package/lib/core/decide.js +159 -0
  18. package/lib/core/embed.js +122 -0
  19. package/lib/core/env.js +72 -0
  20. package/lib/core/extract.js +151 -0
  21. package/lib/core/host.js +81 -0
  22. package/lib/core/importers.js +261 -0
  23. package/lib/core/llm.js +49 -0
  24. package/lib/{memories.js → core/panel-read.js} +80 -136
  25. package/lib/core/pipeline.js +95 -0
  26. package/lib/core/schema.js +123 -0
  27. package/lib/core/search.js +191 -0
  28. package/lib/core/store.js +347 -0
  29. package/lib/core/tools.js +182 -0
  30. package/lib/core/write.js +89 -0
  31. package/lib/extract.js +1 -39
  32. package/lib/index.js +194 -128
  33. package/lib/panel.js +13 -11
  34. package/lib/review.js +5 -1
  35. package/lib/structure.js +6 -1
  36. package/locale/en.json +7 -0
  37. package/locale/zh.json +7 -0
  38. package/package.json +11 -8
  39. package/scripts/backfill-core.mjs +53 -0
  40. package/scripts/import-core.mjs +56 -0
  41. package/scripts/smoke-config.mjs +12 -14
  42. package/scripts/smoke-extract.mjs +19 -40
  43. package/scripts/smoke-package.mjs +105 -27
  44. package/scripts/smoke-panel.mjs +293 -162
  45. package/src/client/index.js +703 -166
  46. package/lib/blocks-write.js +0 -121
  47. package/lib/cli.js +0 -90
  48. package/lib/reindex.js +0 -32
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  # dsh-memvault
4
4
 
5
5
  <p align="center">
6
- <strong>Push MemVault's core memory into the DeepSeek Harness system prompt — and let every finished turn flow back.</strong><br>
7
- With a memory panel in the GUI · zero runtime dependencies · no bundler · no second server
6
+ <strong>Long-term memory for DeepSeek Harness.</strong><br>
7
+ blocks in the prompt · turns extracted into one SQLite file · two tools · one panel
8
8
  </p>
9
9
 
10
10
  <p align="center">
@@ -12,443 +12,98 @@
12
12
  </p>
13
13
 
14
14
  <p align="center">
15
- <img alt="version" src="https://img.shields.io/badge/version-0.9.12-4a6cf7">
16
- <img alt="npm" src="https://img.shields.io/npm/v/dsh-memvault?color=cb3837">
15
+ <img alt="version" src="https://img.shields.io/badge/version-0.10.1-4a6cf7">
17
16
  <img alt="license" src="https://img.shields.io/badge/license-MIT-30a46c">
18
- <img alt="platform" src="https://img.shields.io/badge/platform-DeepSeek%20Harness-f76b15">
19
17
  <img alt="runtime deps" src="https://img.shields.io/badge/runtime%20deps-zero-888">
20
- <img alt="node" src="https://img.shields.io/badge/node-%E2%89%A522.13-339933">
21
- <img alt="panel" src="https://img.shields.io/badge/panel-conversation%20tab%20%2B%20settings-8957e5">
18
+ <img alt="node" src="https://img.shields.io/badge/node-%E2%89%A524.9-339933">
22
19
  <img alt="stars" src="https://img.shields.io/github/stars/zhang66633/dsh-memvault?style=flat&color=e3b341">
23
20
  </p>
24
21
 
25
22
  ---
26
23
 
27
- **dsh-memvault** is the missing half of a memory system that already exists. **[MemVault](https://github.com/zhang66633/memvault)** (a local long-term-memory service: a SQLite store, a FastAPI/CLI pipeline and a stdio MCP server) stores facts, embeds them and retrieves them — but it is a **stdio MCP server**, and MCP is a *pull* protocol: the server can only be *called*, it has no channel to put anything into the model's context. So "memory is already loaded" can never be achieved from the MCP side. It has to be done by the client, which is this plugin.
24
+ MCP is pull-only, so "memory is already loaded" can never come from a server. This plugin does it inside DSH — and since 0.9.x it owns the store too: no Python, no second process.
28
25
 
29
- The two halves are deliberately separable: **MemVault alone is a general MCP service** any client can use (Claude Code, Cursor, Cline, a script), and **this plugin is the DSH-specific layer** — prompt injection, windowed turn extraction through MemVault's own pipeline, and the panel. Installing the plugin is what makes memory *already there* instead of something the model has to remember to look up.
30
-
31
- The plugin does three things:
32
-
33
- | Half | What it does | Mechanism |
26
+ | Half | What | How |
34
27
  |---|---|---|
35
- | **Inject** (read) | Core memory blocks enter the system prompt, visible on **every** step without the model calling a tool | `ctx.systemPrompt.context()` — a dynamic runtime-context contribution (the same channel as `skill-catalog`) |
36
- | **Extract** (write) | Finished turns accumulate into a window, and the window is handed to MemVault's extraction/embedding pipeline as **one** conversation | `ctx.on('session/event')` → `turn/end` → window → `python -m memvault.cli add --stdin` (idle-triggered) |
37
- | **Show** (panel) | What is injected right now, what extraction has been doing, **editing the core blocks**, and **browsing what is actually stored** | five exact host routes (`/memvault/api/*`) + a browser half rendered as a conversation tab and a Plugins settings page |
28
+ | **Inject** | core blocks in the system prompt, every step | `ctx.systemPrompt.context()` |
29
+ | **Extract** | finished turns → one window → one LLM pass | `session/event` → window → `add`/`supersede`/`none` |
30
+ | **Recall** | `memory_search` / `memory_add` | FTS5 trigram + vectors, RRF, answerability guard |
31
+ | **Show** | overview / memories / structure, block editing, replay | host routes + conversation tab / settings page |
38
32
 
39
33
  ## ✨ Features
40
34
 
41
35
  | | |
42
36
  |---|---|
43
- | 🧠 **Injection without tool calls** | Core blocks land in a dynamic runtime context, so they are re-evaluated on every `assemble()` and the model simply *has* them |
44
- | 🗄️ **Direct read-only SQLite** | Node's built-in `node:sqlite` opens `memvault.db` read-only — no HTTP hop, no subprocess, no third-party dependency, no server that must be up |
45
- | 💾 **TTL-cached rendering** | The system prompt *is* the KV-cache prefix; re-reading and re-rendering every step is wasted work and any byte change invalidates reuse — so the render is cached (`refreshMs`, default 30 s) |
46
- | 🧩 **Turn-boundary slicing** | The write half slices the turn from its own bounded event log by `turn/end` boundaries: idempotent, restart-proof, no watermark arithmetic to go stale |
47
- | ⏱️ **Cost-aware extraction** | The window is a knob: `everyNTurns` decides when extraction becomes worth considering, `idleMs` waits for a pause, `windowTurns` caps it, `minTranscriptChars` skips trivia, `endReasons` decides which turn endings count, `timeoutMs` kills a stuck child |
48
- | 🌙 **Background, not on the critical path** | Extraction runs when the session goes quiet — during a pause, not while you are waiting for an answer — and one call covers up to `windowTurns` turns instead of one call per turn |
49
- | 💾 **Restart-safe window** | The waiting window (its rendered transcript, bounded) is written to the state file on every turn, so a restart between turns does not silently drop memories; anything still pending is extracted on mount and marked as recovered |
50
- | 🎭 **Role filtering** | Assistant prose and tool traffic are excluded by default — shipping them stored the model's own words as "facts about the user" |
51
- | 🪶 **Zero runtime dependencies** | Plain ESM over the harness plugin protocol: `node:sqlite`, `node:child_process`, `node:fs`. Nothing to install, and the browser half is hand-written against the ModuleLoader envelope instead of being bundled |
52
- | 🧾 **Every knob described once** | One spec (`lib/config.js`) produces the code defaults, the `Config` schema DSH validates against, and the settings the Plugins page renders — so a default cannot drift between them, and a typo in a patch shows up in the panel instead of only in the log |
53
- | 🎛️ **A real panel** | A **记忆** tab in the conversation ring and a page under Settings → Plugins: the blocks currently injected (label, scope, characters against their stored limit, text), the read budget and cache age, the extraction knobs, sessions with a watermark, and the last five extraction outcomes — plus a **立即重读** button that ignores the 30 s render TTL |
54
- | ✏️ **Editable core blocks** | 编辑 / 删除 on any block, and a form to create one. A write is an upsert keyed by `(scope_type, scope_id, label)`, it drops the render cache so the next step already sees it, and `panel.writes: false` turns the whole thing read-only |
55
- | 🧭 **Know your paths at setup** | The panel shows which store file, plugin state file, Python and project directory are in play, whether the store file exists (and its size), and which scopes are **read** versus **written** — plus the only two places to change any of it: the DSH plugin config or MemVault's `.env`. A missing store file is called out as "created on the first write", because a wrong path and an empty store look identical in a row count The paths in the shipped `cordis.patch.yml` are one machine's example rather than defaults: change them, or change nothing and let discovery find your checkout |
56
- | 🔭 **See the structure** | A third view answers what a list cannot: which scope **dimensions** hold what (and that one row counts under both `user` and `agent` — scopes are dimensions, not a partition), which core blocks are actually injected versus merely stored, and how the relation graph is shaped — nodes sized by degree, edges by weight, plus how many memories have **no** edge at all. Clicking a node opens its full audit chain |
57
- | 🔎 **Browse what is stored** | A second view searches the `memories` table by substring with type/scope filters and paging, showing type, scope, age and the id (one click to copy, so a tool call can act on it). Rows the store **retyped** on its own carry a badge, and "only retyped" lists exactly those — a heuristic verdict should not be silent, so a wrong one can be marked for review right there. It is a **browse**, not retrieval — semantic recall stays with the model's `memory_search` — and it never selects the embedding blob |
58
- | 🧾 **Trace and review** | Every extraction records **which memories it produced**, so a window links to its rows ("看这 2 条产出"). Each row can open its provenance — MemVault's own audit trail (`history`: ADD/UPDATE/DELETE with old and new text) and the contradictions it takes part in (`relations`) — and can be **marked for review**. Flags are plugin state: the store is never touched |
59
- | ♻️ **A review loop that can act** | The queue resolves each flagged memory with its window and retained input, and a mark can be **cleared right there**. Two actions: **复制修正请求** hands the model the ids, texts and provenance (it proposes; DSH's approval is the gate), and **重抽** sends that window's text through MemVault's own pipeline again — optionally edited, optionally with the other extractor. Replay is the panel's one store-writing action, and it writes through `add()`, never around it |
60
- | 🖥️ **Host half needs no browser** | The panel is optional: `webServer` is taken with `ctx.inject`, so a headless composition still injects memory and simply never registers the routes |
61
- | 🛟 **Fail-soft by design** | An unreadable store serves the last good text and warns once; a broken extraction never fails a turn and never poisons the next one |
62
- | 🔍 **Observable from outside** | Watermarks and the last five extraction diagnostics are written atomically to one JSON file, so "hook never fired" is distinguishable from "turn too short" from "ran and found nothing" |
63
-
64
- ## 🧭 Compatibility
65
-
66
- | Question | Answer |
67
- |---|---|
68
- | **DSH Desktop** | ✅ Verified live on **0.2.1-rc.5** with the reserved `desktop` profile: the bundle (`dsh.bundle.patch`) loads, the plugin row is `active`, `/memvault/api/status` answers 200, and the injected blocks appear in the runtime-context snapshot. |
69
- | **DSH versions** | Supports the 0.1.x and 0.2.x lines, including 0.2.1 prereleases. `engines.dsh` and both DSH peer declarations carry **one range**; its `>=0.2.1-0 <0.3.0-0` arm exists for **strict** readers that do not pass `includePrerelease` (npm/pnpm peer resolution, the market's discovery preflight) — without it they reject `0.2.1-rc.5`. |
70
- | **Do I need a client half?** | Only for the panel. `dsh.client.platform: 'web'` serves the browser half; the memory bridge itself runs entirely host-side, so disabling the client half costs visibility, never injection. |
71
- | **DSH Web / headless / SDK profiles** | ✅ The same bundle works wherever the host runs. Headless compositions simply have no `webServer`, and the panel's child fiber waits for it instead of failing. `systemPrompt` is the only *required* service. |
72
- | **Is the panel visible?** | ✅ Two seats: a **记忆** tab beside 聊天 / 轨迹 in the conversation ring, and a **MemVault 记忆桥** page under Settings → Plugins. Both are read-only views over the injected blocks and the extraction state. |
73
- | **Windows / macOS / Linux** | ✅ Windows works out of the box with the author's layout; on other platforms point `MEMVAULT_DIR` / `MEMVAULT_PYTHON` at the checkout (a POSIX venv uses `.venv/bin/python`), or set the three paths in `cordis.patch.yml`. |
74
- | **Node** | `>= 22.13` (flag-free `node:sqlite`). DSH ships its own Node, so this is only a statement about the plugin's API floor. |
75
- | **Other harnesses (Claude Code, Codex, …)** | ❌ Not this plugin. It is written against the cordis/DSH surface (`ctx.systemPrompt.context`, `session/event`). Those harnesses reach the same store through MemVault's own MCP tools, CLI, or API. |
76
-
77
- ## 🚀 Quick start
37
+ | 🗄️ **One store** | prompt, extraction, tools and panel read `~/.dsh/memvault/memvault.db` |
38
+ | 🧠 **No tool call needed** | blocks ride the runtime context, TTL-cached |
39
+ | ⏱️ **Off the critical path** | queued windows, one call per `N` turns / idle / cap |
40
+ | 🔎 **Hybrid recall** | substring truth (trigram) + paraphrase (vectors), fused |
41
+ | 🛠️ **Two tools** | scoped by `user_id` / `agent_id` / `run_id` |
42
+ | 🎛️ **A real panel** | diagnostics, vector backfill, provenance, relation graph |
43
+ | 🃏 **Native tool cards** | `memory_search` / `memory_add` render their own conversation cards |
44
+ | 🪶 **Zero deps** | `node:sqlite` + hand-written client bundle |
78
45
 
79
- **Prerequisite:** a working MemVault checkout — its virtualenv and its `memvault.db` (the store is shared with the MemVault service and MCP clients; this plugin only ever `SELECT`s from it).
80
-
81
- Install from npm (0.9.12 and newer):
46
+ ## 🚀 Install
82
47
 
83
48
  ```powershell
84
49
  dsh plugin --profile desktop add dsh-memvault
85
50
  ```
86
51
 
87
- Self-owned install (what this repo does on the author's machine):
88
-
89
- ```jsonc
90
- // ~/.dsh/profiles/<profile>/package.json
91
- {
92
- "dependencies": { "dsh-memvault": "link:D:/_Projects/skill_mcp/dsh-memvault" },
93
- "dsh": { "profile": { "bundles": ["…", "dsh-memvault", "…"] } }
94
- }
95
- ```
96
-
97
- ```powershell
98
- # make the module resolvable from the profile
99
- New-Item -ItemType Junction `
100
- -Path "$env:USERPROFILE\.dsh\profiles\desktop\node_modules\dsh-memvault" `
101
- -Target "D:\_Projects\skill_mcp\dsh-memvault"
102
- ```
103
-
104
- **Restart DSH after adding a bundle** — an already-loaded patch file hot-reloads, a newly added bundle does not.
105
-
106
- > ⚠️ Two known traps. `dsh plugin add` rewrites the profile's `package.json`, and the `dsh.profile.bundles` array can silently lose *other* plugins' entries — always re-read the whole list afterwards. And pnpm can replace the `link:` junction; recreate it if the bundle suddenly stops loading.
107
-
108
- Installing from npm or a git spec is the same operation through `dsh plugin` or the Web sidebar's **Plugins** page (see `@deepseek-ai/dsh-plugin-manager`).
109
-
110
- The browser half is committed as `lib/client.js`, so a fresh clone needs no build. After editing `src/client/index.js`:
111
-
112
- ```bash
113
- npm run build # wraps the client source in the ModuleLoader envelope
114
- npm test # fails when lib/client.js is stale
115
- ```
52
+ Self-owned install links a checkout in the profile's `package.json` (`dsh-memvault: link:…`) plus a junction under `node_modules` — see `docs/DEVLOG.md`. A new bundle needs a **DSH restart**; after editing the client run `npm run build`.
116
53
 
117
- A brand-new client half is picked up by a **restart** plus a page reload: the boot graph is rendered into the index response.
54
+ Requires DSH **0.2.1+**, verified against **0.2.2-rc.5** (`engines.dsh` names the 0.2.2 line explicitly, because a bare `>=0.2.1-0 <0.3.0-0` does not admit `0.2.2-rc.5` for strict semver readers; the `>=0.2.2-0` arm covers the whole 0.2.2 pre-release line, rc.1 through rc.5). Node **24.9+** is required: that is the runtime floor of DSH 0.2.2, and this plugin uses Node 24's `DatabaseSync` busy-timeout option. The tool cards, the non-interpolated injection and the session-close extraction are 0.2.2 features; on 0.2.1 they degrade to the previous behaviour.
118
55
 
119
56
  ## ⚙️ Configuration
120
57
 
121
- Every knob is described **once**, in `lib/config.js`: type, bounds, default and a
122
- description. From that one description come the code defaults (`DEFAULT_EXTRACT`
123
- and friends), the `Config` schema DSH validates the entry against and projects for
124
- the Plugins page, and the panel's view of what is configured. The tables below are
125
- that description in prose.
126
-
127
- Setting values is unchanged — a `config` block in `cordis.patch.yml`. What changed
128
- is what happens when one is wrong: a value that does not type-check is reported
129
- (and the default is used), an undeclared key is reported, and both surface as a
130
- warning banner in the panel rather than only in the host log.
131
-
132
- ### Read half
133
-
134
- | Field | Default | Meaning |
135
- |---|---|---|
136
- | `enabled` | `true` | `false` injects the empty string forever |
137
- | `dbPath` | `$MEMVAULT_DB_PATH` else `D:/Claude_code/memory/data/memvault.db` | Path to `memvault.db` |
138
- | `scopes` | `[{user,lenovo},{agent,claude-code-memory}]` | Blocks are keyed by `(scope_type, scope_id)`; **both halves must be given explicitly** — a foreign process has no "current scope" |
139
- | `labels` | `[]` | Only these labels; empty means every block in the scopes |
140
- | `maxChars` | `4000` | Budget for the **whole rendered string**, header included |
141
- | `refreshMs` | `30000` | TTL for the cached render |
142
- | `order` | `210` | Position among runtime-context contributions (e.g. relative to `skill-catalog`) |
143
- | `name` | `memvault:core` | The name shown in the trajectory's injected-context list |
144
-
145
- ### Write half (`config.extract`)
146
-
147
- | Field | Default | Meaning |
148
- |---|---|---|
149
- | `enabled` | `true` | `false` makes the plugin read-only |
150
- | `everyNTurns` | `3` | Turns that must accumulate before an extraction is considered; `1` = every turn (still windowed) |
151
- | `idleMs` | `20000` | Quiet time that hands the window over. A new finished turn re-arms it |
152
- | `windowTurns` | `8` | Hard cap: reaching this many turns extracts immediately, so a session that never pauses still gets extracted |
153
- | `endReasons` | `['completed','max-tokens']` | Which `turn/end` reasons count. `aborted` / `error` / `interrupted` / `blocked` are skipped — but `max-tokens` is not, because a truncated turn still holds the user's message |
154
- | `includeAssistant` / `includeTools` | `false` / `false` | The extractor does not separate roles; the assistant's own prose became stored "facts", so it is off by default |
155
- | `maxInputChars` | `6000` | Transcript budget; newest lines win, oldest are dropped |
156
- | `minTranscriptChars` | `40` | Below this a turn is not worth a process plus an LLM call — it is skipped, and the watermark still advances |
157
- | `timeoutMs` | `120000` | Timeout kills the child and records one warning |
158
- | `pythonPath` | `$MEMVAULT_PYTHON` else `<MEMVAULT_DIR>/.venv/{Scripts/python.exe,bin/python}` | Interpreter that can `import memvault` |
159
- | `projectDir` | `$MEMVAULT_DIR` else `D:/Claude_code/memory` | Working directory of the child |
160
- | `user` / `agent` / `run` | `lenovo` / `claude-code-memory` / unset | The three axes are orthogonal; any combination is allowed |
161
- | `env` | `{PYTHONUTF8:'1', PYTHONIOENCODING:'utf-8'}` | Child environment. Removing these reintroduces the cp936/emoji bug below |
162
- | `statePath` | `~/.dsh/storages/dsh-memvault-state.json` | Watermarks + the last five diagnostics; atomic write |
163
-
164
- ### Panel routes
165
-
166
- The browser half has no knobs of its own; it reads the two routes the host half registers. They exist only when the composition provides `webServer`.
167
-
168
- | Route | Method | Answers |
169
- |---|---|---|
170
- | `/memvault/api/status` | `GET` | Injected blocks (label, scope, characters, stored limit, value clamped to 2000), read config, cache age, extraction config, watermark session count, last five diagnostics, and whether writes are enabled |
171
- | `/memvault/api/refresh` | `POST` | The same payload after dropping the render TTL — the 立即重读 button |
172
- | `/memvault/api/blocks` | `POST` | One block action through MemVault's CLI: `{ action: 'set', type, id, label, value, limit? }` (upsert) or `{ action: 'delete', type, id, label }` |
173
- | `/memvault/api/flush` | `POST` | Extract every pending window now (the 立即抽取 button). The answer says how many sessions were handed over; the work stays queued. Answers 405 when extraction is disabled |
174
- | `/memvault/api/memories` | `GET` | Browse stored memories: `q` (substring), `type`, `user`, `agent`, `run`, `ids` (an explicit id list, how a diagnostic's output is looked up), `flagged=1` (only marked rows), `retyped=1` (only rows the store's own type refinement moved out of `user`), `limit` (default 20, capped at 200), `offset`. Answers `{ rows, total, limit, offset, order, applied, mode, flags, flaggedCount, retypedCount, produced }` — `applied` echoes what was actually used, and `mode: 'substring'` says out loud that this is not ranked retrieval |
175
- | `/memvault/api/memory` | `GET` | One memory's provenance (`?id=`): the row, `history` (every audited decision with old/new text) and `relations` (the contradictions, with the other side's text and weight). 404 for an unknown id, `missing: true` in the body |
176
- | `/memvault/api/flag` | `POST` | Mark or clear one memory for review: `{ id, flagged: true \| false, note? }`. Writes the plugin's **own state file** — MemVault is untouched — and answers with the whole bounded flag map. 403 when `panel.writes: false` |
177
- | `/memvault/api/review` | `GET` | The review queue: every flagged memory with its provenance, the window that produced it, whether that window's input is still retained (`replayable`), the retained `inputText` when it is, and `request` — a ready-to-paste instruction listing ids, texts and provenance for a model to propose fixes |
178
- | `/memvault/api/replay` | `POST` | Replay one retained input: `{ key, text?, extractor?: 'inherit' \| 'rule' \| 'llm' }`. Answers **202** because the work is queued; the outcome appears as a diagnostic with `replayOf`. Writes the store through MemVault's own `add()`; 403 when `panel.writes: false` |
179
- | `/memvault/api/structure` | `GET` | The store's shape: memories and type split per scope dimension, core blocks with their occupancy (`chars / value_limit`) and whether each is actually injected, the relation graph's nodes and edges (capped at 120 each, `sampled` reported when truncated), the ten heaviest relations, and how many memories have no edge at all. A store file that does not exist yet answers 200 with `initialized: false` — a fresh install is a state, not an error |
180
-
181
- The handlers refuse anything that is not a loopback `Host` with a matching `Origin` (when the browser sends one) and a same-site `Sec-Fetch-Site`, answering 403 otherwise. They are `exact` routes, so they match before the shell's index/`/api` handlers. A bad action, an unknown scope type, an empty value or an over-long value is a 400 before anything is spawned; a CLI failure is a 502.
182
-
183
- ### Panel
184
-
185
- | Field | Default | Meaning |
186
- |---|---|---|
187
- | `panel.writes` | `true` | `false` makes the panel read-only: `/memvault/api/blocks` answers 403 instead of running the CLI |
58
+ | Field | Default |
59
+ |---|---|
60
+ | `scopes` | `[{user,lenovo},{agent,claude-code-memory}]` |
61
+ | `labels` / `maxChars` / `refreshMs` | `[]` / `4000` / `30000` |
62
+ | `extract.everyNTurns` / `idleMs` / `windowTurns` | `3` / `20000` / `8` |
63
+ | `extract.timeoutMs` | `60000` (wired as `MEMVAULT_EXTRACT_TIMEOUT_MS`) |
64
+ | `extract.minTranscriptChars` / `maxInputChars` | `40` / `6000` |
65
+ | `extract.projectDir` / `env` | discovered `.env` directory / `{}` |
66
+ | `panel.writes` | `true` |
188
67
 
189
- ### Config schema
68
+ The store path is not configurable through this plugin (`~/.dsh/memvault/memvault.db`, or `DSH_MEMVAULT_CORE_DB`). `projectDir` is only where `.env` is read — nothing is spawned, so a machine without a Python checkout still works, and the panel lists the directories it checked. The pipeline reads the usual `.env` keys (`OPENAI_*`, `MEMVAULT_EXTRACTOR=rule|llm`, `MEMVAULT_EMBEDDER=local|openai`, `MEMVAULT_ADJUDICATOR=off`).
190
69
 
191
- `lib/schema.js` builds a native Schemastery schema from the same spec and exports
192
- it as `Config`, which is what DSH reads off a plugin module. Two consequences:
70
+ The old `dbPath`, `extract.pythonPath` and `extract.user/agent/run` keys are gone: a stale patch that still sets one is reported as an ignored key in the panel instead of silently doing nothing. The write scope is derived from `scopes` (first user → `user_id`, first agent → `agent_id`).
193
71
 
194
- - **validation.** A config that fails the schema keeps the entry from activating
195
- (DSH's documented behaviour), so the schema is stricter than the resolver on
196
- purpose: bounds and types are enforced before the plugin runs.
197
- - **a settings page.** `dsh --dump-config-schema` and the Plugins page project the
198
- same schema into JSON Schema, which is what renders the fields.
72
+ ## 🗄️ Store & migration
199
73
 
200
- `@deepseek-ai/schemastery` comes from the DSH runtime and is declared as a peer.
201
- The import is attempted once and tolerated when absent, because the bundled smoke
202
- tests run on plain Node: outside DSH the plugin exports no `Config`, still loads,
203
- and warns that it has no settings page. In DSH it always resolves.
74
+ `~/.dsh/memvault/memvault.db` (override `DSH_MEMVAULT_CORE_DB`). From the Python store, once:
204
75
 
205
- ![Architecture: one engine, three adapters](docs/architecture.svg)
76
+ ```bash
77
+ memvault export --from data/memvault.db --out export.json
78
+ node scripts/import-core.mjs export.json ~/.dsh/memvault/memvault.db --apply
79
+ node scripts/backfill-core.mjs ~/.dsh/memvault/memvault.db --project-dir <checkout> --apply
80
+ ```
206
81
 
207
82
  ## 🏗️ How it works
208
83
 
209
84
  ```mermaid
210
85
  flowchart LR
211
- subgraph HOST["DSH host process"]
212
- LOOP["Agent loop"]
213
- ASM["systemPrompt.assemble()"]
214
- CTX["ctx.systemPrompt.context('memvault:core')"]
215
- HOOK["ctx.on('session/event')"]
216
- BUFF["bounded event log<br/>400/session · 32 sessions"]
217
- end
218
-
219
- subgraph BROWSER["Web / Desktop client"]
220
- TAB["记忆 tab<br/>Settings → Plugins page"]
221
- end
222
-
223
- DB[("memvault.db<br/>blocks · memories")]
224
- PY["python -m memvault.cli add --stdin"]
225
- STATE["dsh-memvault-state.json"]
226
-
227
- DB -->|"read-only SELECT ~1 ms"| CTX
228
- CTX -->|"dynamic runtime context, TTL 30 s"| ASM
229
- ASM --> LOOP
230
-
231
- LOOP --> HOOK
232
- HOOK --> BUFF
233
- BUFF -->|"turn/end boundary slice"| PY
234
- PY -->|"extract · embed · upsert"| DB
235
- HOOK --> STATE
236
-
237
- STATE -->|"loadState (watermarks + last 5)"| API["exact routes<br/>/memvault/api/status · /refresh"]
238
- DB -->|"same read as the prompt gets"| API
239
- API --> TAB
86
+ T[turn/end] --> W[window] --> X[extractor] --> D[decide] --> S[(store)]
87
+ S --> P[system prompt]
88
+ S --> M[tools]
89
+ S --> U[panel]
240
90
  ```
241
91
 
242
- Read path, per step:
243
-
244
- 1. `assemble()` asks every dynamic context for its text.
245
- 2. `memvault:core` returns the cached render unless the TTL expired; on expiry it opens the store read-only and re-renders.
246
- 3. Blocks are rendered as `- [scope_type/scope_id/label] value`, headed by one attribution line, bounded by `maxChars`.
247
- 4. An empty render returns `''`, the assembler drops the empty contribution, and nothing appears in the trajectory — that is the intended behaviour for an empty store, not a fault.
248
-
249
- Write path, per finished turn:
250
-
251
- 1. Every appended session event is buffered per session (bounded on both axes).
252
- 2. On `turn/end` with an accepted reason, the turn is sliced **by turn boundary** from that buffer and pushed onto the session's window.
253
- 3. The window decides: below `everyNTurns` it keeps waiting; at `everyNTurns` it arms an idle timer; at `windowTurns` — or when the timer fires — it hands the whole window over, as the newest lines of one bounded, user-only transcript.
254
- 4. The window is persisted on every push, so a restart between turns loses nothing; a window still waiting at mount is extracted and marked `recovered`.
255
- 5. Extractions are serialized: one child at a time, and a failure in one window cannot poison the next.
256
- 6. MemVault does the rest — LLM extraction, ADD/UPDATE/DELETE decisions, embeddings, relations — so written rows are actually *retrievable*.
257
-
258
- Panel path, on open and every 15 s:
259
-
260
- 1. The browser half fetches `/memvault/api/status` from the same origin.
261
- 2. The handler re-reads only when the TTL says so, so a polling panel never becomes a per-second SQLite read; 立即重读 forces the read instead.
262
- 3. The payload reports the blocks **the prompt is getting**, not a second interpretation of the store — same reader, same scope/label filters, same budget.
263
-
264
- ## 📸 What it looks like
265
-
266
- **Injection is the headline.** Every step, the core blocks are assembled into the system
267
- prompt — no tool call, no round trip, no "did the model remember to look". The panel
268
- shows the rendered budget, the scopes it read, and the blocks themselves:
269
-
270
- ![The injection view: 3 blocks, 852 of 4000 characters, scopes user/lenovo and agent/claude-code-memory](docs/screenshots/panel-inject.jpg)
271
-
272
- **Memory structure** — scope dimensions, which blocks actually reach the prompt, and the
273
- relation graph (only the 40 heaviest edges, or 120 nodes become an unreadable ring):
274
-
275
- ![The structure view: scope dimension counts, block occupancy, and the contradiction graph](docs/screenshots/panel-structure-graph.jpg)
276
-
277
- **Browsing** is a substring browse, not retrieval — with review marks and a flag on rows
278
- the store retyped on its own:
279
-
280
- ![The browse view with type filters, review marks and a retyped-row flag](docs/screenshots/panel-browse-filters.jpg)
281
-
282
92
  ## 🧪 Verification
283
93
 
284
- No DSH and no browser needed:
285
-
286
- ```bash
287
- npm test # all five suites
288
- npm run smoke:package # package/bundle contract: manifest, patch row, exports, peers, bundle id
289
- npm run smoke:config # the config spec, the resolver, and the native schema built from it
290
- npm run smoke # reader + formatter + budget contract, against the real db (read-only)
291
- npm run smoke:extract # transcript, boundary slicing, event buffer, watermarks, and a REAL end-to-end write into a throwaway db
292
- npm run smoke:panel # mounts the plugin on a stub context, drives every route against a throwaway db, and runs the shipped client bundle under a stub ModuleLoader
293
- ```
294
-
295
- `smoke:config` is the one that keeps the three copies of a default from existing:
296
- it asserts that `DEFAULT_EXTRACT` *is* the spec default, that the native schema
297
- validated against `{}` returns exactly those defaults, and that the **shipped
298
- `cordis.patch.yml`** resolves with nothing unknown and nothing mistyped. It has
299
- already earned its keep — see §9 of the [DEVLOG](docs/DEVLOG.md).
300
-
301
- `smoke:panel` is where the panel's behaviour is actually pinned down: the TTL must serve a stale render while a row written in between exists, `POST /refresh` must pick that row up, an untrusted `Host`/`Origin` must get 403, a throwing handler must become a 500 rather than reject, an unreadable store must still answer 200 with the blocks it last knew, and the shipped `lib/client.js` must equal what `src/client/index.js` builds to. Its write half runs **real CLI writes against a throwaway store**: the route creates a block, an upsert of the same label must not create a second one, a delete removes it, `panel.writes: false` turns the route into a 403, and a value that looks like an option (`--not-a-flag`) must survive argv parsing as data.
302
-
303
- The end-to-end step forces the offline embedder and rule extractor in a temporary database: it never touches the real store and never calls the configured gateway. `smoke:panel` goes one step further for the window: it feeds two finished turns through the real `session/event` handler, checks the waiting window is reported and persisted, flushes it through the route, and asserts the result is **one** call covering both turns whose two facts land in the store.
304
-
305
- **Live check.** After a restart, the trajectory's *injected context* list gains a `memvault:core` entry whose content is your actual blocks, the Plugins page shows the bundle's row (`memvault-core-context`) as active, and the **记忆** tab renders those same blocks with their character counts and the last extraction outcomes.
306
-
307
- ## 🧠 Design decisions
308
-
309
- **Why a direct SQLite read rather than HTTP or the CLI.** `GET /api/v1/blocks` needs the FastAPI server alive on 8780 — if it is down, the prompt silently loses memory. Spawning the CLI costs ~200–300 ms per refresh. `node:sqlite` costs ~1 ms and depends on nothing running. The store is shared with the MemVault service, but this only `SELECT`s, and a `timeout: 2000` busy timeout keeps a concurrent writer from surfacing `SQLITE_BUSY` to the prompt assembler. `node:sqlite` is still *experimental* in Node 24 — a documented risk, and the reason the write half deliberately does not depend on it.
310
-
311
- **Why the render is cached.** The system prompt is the KV-cache prefix. Re-reading and re-rendering on every step is wasted work, and any byte change invalidates cache reuse from that point on. Core blocks are edited by a human on the scale of hours; a 30 s TTL is both cheap and cache-friendly.
312
-
313
- **Why the write half is a CLI call rather than a direct insert.** Writing rows straight into SQLite would skip extraction and embedding — the rows would exist and be unretrievable. `--stdin` rather than argv because a turn transcript blows past the command-line length limit. The cost is one Python process per extracted turn, which is exactly what `everyNTurns` and `minTranscriptChars` exist to control.
314
-
315
- **Why only core blocks are injected, and not per-turn semantic recall.** Recall results change every turn; putting them in the system-prompt prefix would invalidate the cache on every step. That content belongs in a user message with its provenance, not in the prompt prefix.
316
-
317
- **Why `turn/end` reasons are configurable.** The agent loop emits `completed`, `max-tokens`, `blocked`, `aborted`, `error`, plus `interrupted` from the repair path. Accepting only `completed` silently drops turns that ended on `max-tokens` — which still contain real user content.
318
-
319
- **Why the browser half is hand-written instead of bundled.** A client bundle is served in the ModuleLoader envelope — `window.__ModuleLoader__.load({ id, factory })` — and resolving `require('react')` against the shell's platform seed table is all the "bundling" this panel needs. So `scripts/build-client.mjs` wraps the source in those two lines, and the package keeps zero dependencies: no esbuild, no `node_modules`, no build toolchain to keep alive. `src/client/index.js` is the readable source; `lib/client.js` is the committed artifact (the host serves built bundles and fails loudly when one is missing), and a test fails if the two ever drift.
320
-
321
- **Why the panel registers with `ctx.inject`.** `webServer` is a *wanted* service, not a required one: a headless composition has no browser to render into, and a memory bridge that stopped injecting because nothing could paint a panel would be a bug, not a safety feature. `ctx.inject(['webServer'], …)` starts a child fiber that simply waits in that case.
94
+ `npm test` (6 smokes + 56 unit). Live: `/memvault/api/status` shows the last five outcomes (`[rule]|[llm] ok added=N`); replay via `POST /memvault/api/replay`; recall via `memory_search`.
322
95
 
323
- **Why the panel routes check the caller themselves.** A route registered through `webServer` is not admitted by `dsh-client-connection` — that gate guards the index exchange and the `/api` bridge. The panel answers with the same request-trust rule the bridge documents (loopback host, matching `Origin` when present, no cross-site `Sec-Fetch-Site`) so a DNS-rebinding page cannot read **or write** the store. It is a boundary, not identity; the server still binds loopback only.
96
+ ## 🧠 Decisions
324
97
 
325
- **Why extraction is windowed and idle-triggered.** One call per turn was both expensive (a Python process plus an LLM call each time) and noisy: a single "yes, do it" turn carries almost no signal, while the three or four turns around a decision carry all of it. Waiting for quiet costs nothing — the work happens while you are reading, not while you are waiting — and `windowTurns` keeps a session that never pauses from postponing it forever. The whole policy is a pure function of pushes and timers (`window.js`), which is why it is tested with a fake clock rather than by waiting.
98
+ - **One store, not two** — no "tool saw it, panel didn't".
99
+ - **Supersede, never delete** — history keeps the audit.
100
+ - **Only user text is extracted** — short windows are skipped (`docs/DEVLOG.md` §35).
326
101
 
327
- **Why the waiting window is written to disk.** Windowed extraction lengthens the "in flight" period from one turn to up to eight plus an idle timer, so anything held only in memory is exactly what a restart drops. Only the rendered transcript is stored, bounded by `maxInputChars`, and only for the newest few sessions — the file stays small, and recovery is marked `recovered: true` in the diagnostics so it is visible rather than mysterious.
102
+ ## ⚠️ Limits
328
103
 
329
- **Why the config is a spec rather than just a schema.** A schema alone would have
330
- to be the fourth place a default lives (constants, patch file, README, schema).
331
- Describing each knob once — kind, bounds, default, description — lets the code
332
- defaults, the validation and the settings page all be derived, and gives the
333
- resolver something dependency-free to work from. The one thing that must stay in
334
- step by hand is `window.js`'s standalone defaults, so a test asserts they match.
335
-
336
- **Why the schema import is optional.** `@deepseek-ai/schemastery` is provided by
337
- the DSH runtime, not by this package. A static import would make the module — and
338
- therefore every smoke test — unloadable on plain Node, which is exactly where the
339
- read, window, panel and contract tests run. So the import is attempted once,
340
- `Config` is exported only when it succeeds, and `apply()` warns when it did not.
341
- DSH never hits that path; the tests do, and they verify the schema with the real
342
- Schemastery whenever the machine has one.
343
-
344
- **Why replay goes through MemVault's `add()` instead of around it.** MemVault already
345
- owns the write policy: `_decide` compares a new fact against the most similar
346
- in-scope memory and picks ADD (below 0.55 similarity), DELETE (a negation), UPDATE
347
- (same attribute slot, or ≥ 0.82 similarity), or ADD again for a paraphrase — that
348
- 0.55–0.82 band is *deliberately* allowed to coexist and is what `consolidate`
349
- (≥ 0.92) later folds together. Routing a replay through the same door inherits all
350
- of that, plus the `history` audit and the `relations` bookkeeping, for free; a
351
- private "replace this row" rule in the panel would be a second, silently divergent
352
- policy. Measured consequence: replaying a window whose text is unchanged updates
353
- the **same rows in place** (identical ids before and after, no duplicates) because
354
- the decision lands on UPDATE. A paraphrase the store decides to ADD stays until
355
- `consolidate` runs — that is the trade, not a bug.
356
-
357
- **Why the panel keeps the inputs it sent.** A replay needs the text, and after an
358
- extraction the text used to be gone (only counts survived). The last five inputs
359
- are retained, clamped, in the same state file — which also makes a *failed*
360
- extraction replayable, and lets a human fix the input ("the extractor misread this
361
- sentence") before sending it again.
362
-
363
- **Why "the model proposes, the human approves" lives outside the plugin.** The
364
- model already has MemVault's write tools, and DSH already gates tool calls with an
365
- approval prompt. A second approval queue inside the plugin would duplicate that
366
- gate and add a way for the panel to edit memories — exactly what it promises never
367
- to do. So the plugin's half is the *evidence*: a request that carries ids, texts,
368
- windows and provenance, plus a queue that shows what is flagged. Replay is the one
369
- exception, because re-running the pipeline is extraction, not editing.
370
-
371
- **Why a review flag is plugin state rather than a memory edit.** The one thing only
372
- a human can supply is "this extracted fact is wrong", and recording it is useful;
373
- acting on it is dangerous. So a flag is a timestamped note in the plugin's own
374
- state file (bounded to 200, newest kept) — visible in the browse view, filterable,
375
- and exportable later by a refine pass — while deleting or rewriting a memory stays
376
- with `memory_delete` / `memory_update` / the CLI. That is what keeps the panel's
377
- promise ("it never modifies your memories") literally true, and it is why flagging
378
- is gated by the same `panel.writes` switch as block editing: read-only means
379
- read-only.
380
-
381
- **Why extraction records its output.** The CLI answers with every row it wrote
382
- (`memory._public`, embeddings removed); keeping the ids turns "ok added=2" into
383
- something auditable — the diagnostic links to the rows, and the panel can jump
384
- straight from a window to what it produced. Twenty entries at 200 characters each
385
- is enough to recognise a bad extraction and small enough to live in the state
386
- file.
387
-
388
- **Why the memory view is a substring browse.** Semantic ranking needs the embedder, and `memory_search`'s hybrid mode needs the keyword index too — that is the model's retrieval tool, and a panel that polled it would cost a retrieval per refresh. A `LIKE` over the text column is honest about being a browse: there is no index on `memories.memory`, so it is a scan, which is why the page is bounded (200 rows), the count is reported, and the payload says `mode: 'substring'`. Every value goes through a placeholder and `%`/`_` are escaped, so a query is a query and never a pattern or a statement.
389
-
390
- **Why the browse never selects `*`.** `memories.embedding` is a blob per row; MemVault's own maintenance paths use an explicit column list for exactly that reason (`storage.iter_memory_meta`). Selecting the nine columns the panel displays keeps a browse cheap no matter how large the store is — it reads 289 rows on the author's store without touching a single embedding.
391
-
392
- **Why the panel writes through the CLI too.** A core block is cheap to write — no LLM call, no embedding, unlike a memory — but it still has to go through MemVault's own `core_append`, which is what owns the upsert semantics, the `block.updated` event and `value_limit`. A direct SQLite `INSERT` would skip all three. The CLI takes the value as an argv positional, so the panel caps it at 8000 characters and puts `--` before the positionals: a value of `--not-a-flag` has to stay data.
393
-
394
- **Why the panel's validation is stricter than MemVault's.** Two extra refusals, both about failures that would otherwise be invisible: an empty value (the prompt reader skips empty blocks, so such a write would look like nothing happened) and a value over 8000 characters (argv limits are real). Everything else is left to MemVault, which stays the source of truth.
395
-
396
- ## ⚠️ Known limits
397
-
398
- - **Extraction lands after a pause, not instantly.** That is the point (the LLM call stays off the critical path), but it means a memory written now is normally visible after the session goes quiet for `idleMs` — or immediately via the panel's 立即抽取.
399
- - **A window is text, not a log.** Recovery re-sends the rendered transcript, so it cannot re-derive turns that were not rendered (assistant prose and tool traffic are off by default anyway).
400
- - **Replay re-sends text; it does not rewrite facts.** The stored transcript is what was sent, and MemVault decides what to do with it. A paraphrase the store chooses to ADD stays until `consolidate` (or the model, with your approval) removes it.
401
- - **Only the last five extraction inputs are retained**, so older windows cannot be replayed; the queue says so per item (`replayable: false`).
402
- - **The panel still never edits a memory.** It flags, traces, exports a request and replays extraction. Deleting or rewriting stays with the model's MemVault tools, behind DSH's approval — or with the CLI.
403
- - **Source changes need a real host restart.** Editing the plugin's own `lib/*.js` (or its config) is only picked up by a genuine process restart — "refresh the UI" is not enough, and the symptom is simply *no change*. A **newly added client half additionally needs a page reload**, because the boot graph is rendered into the index response.
404
- - **The panel edits core blocks, not memories.** Create / replace / delete on the stable `(scope_type, scope_id, label)` blocks only. It never writes a memory (that goes through extraction, embeddings included) and it never triggers an extraction by hand.
405
- - **`node:sqlite` is experimental** in the Node versions DSH currently ships.
406
- - **Machine-specific defaults.** `scopes` defaults to the author's `(user, lenovo)` / `(agent, claude-code-memory)` pairs, and the shipped patch points at the author's checkout. Both are meant to be edited.
407
-
408
- ## 🔌 Adding the MCP server (one paste)
409
-
410
- Injection, extraction and the panel need **nothing** extra: install the bundle and they
411
- work. Model-invoked recall (`memory_search`, relations, consolidate …) is a separate MCP
412
- connection — not because of packaging, but because an external MCP server cannot inject
413
- anything into the prompt, and this plugin cannot serve other clients.
414
-
415
- The MCP connector imports an `mcpServers` block, so the whole setup is one paste
416
-
417
- The same block lives in this repository as [`docs/mcp/memvault.mcp.json`](docs/mcp/memvault.mcp.json), ready to import.
418
-
419
- (DSH → 🧩 MCP 连接器 → add → paste, or the `mcp_connector_import_json` tool):
420
-
421
- ```json
422
- {
423
- "mcpServers": {
424
- "memvault": {
425
- "type": "stdio",
426
- "command": "D:/Claude_code/memory/.venv/Scripts/python.exe",
427
- "args": ["-m", "memvault.mcp_server"],
428
- "cwd": "D:/Claude_code/memory",
429
- "env": { "MEMVAULT_DB_PATH": "D:/Claude_code/memory/data/memvault.db" }
430
- }
431
- }
432
- }
433
- ```
434
-
435
- - **Keep the store path the same** as the plugin's `dbPath`. The plugin passes
436
- `MEMVAULT_DB_PATH` to every child process it spawns, so stating it here too makes both
437
- halves provably share one file instead of relying on two defaults agreeing.
438
- - **Adjust `command` / `cwd`** to your checkout (and on Linux/macOS use
439
- `.venv/bin/python`).
440
- - **Already running a `memvault` server?** Replace it rather than adding a second one:
441
- two connections with the same `serverName` collide on tool names.
442
- - **Skipping the connector entirely?** Then skip this section — injection, extraction and
443
- the panel are unaffected; only on-demand search over the long tail is missing.
444
-
445
- ## 🗺️ Roadmap
446
-
447
- - **Let the model consume the review request directly** — today it is copied and pasted; a tool that hands the queue over (still behind DSH's approval) would close the loop on the model's side.
448
- - **A relations view** — the whole contradiction graph, clustered, rather than one memory's neighbourhood.
104
+ - Single machine, single store: no sync, no encryption.
105
+ - Extraction quality depends on the extractor (rule is deterministic but narrow; LLM depends on the endpoint).
449
106
 
450
107
  ## 📄 License
451
108
 
452
- [MIT](./LICENSE) © 2026 zhang66633
453
-
454
- Development notes, every dead end and every measured pitfall live in [docs/DEVLOG.md](docs/DEVLOG.md).
109
+ MIT