dsh-verbatim 0.1.0 → 0.1.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 (74) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +1 -1
  3. package/README.en.md +24 -22
  4. package/README.md +24 -22
  5. package/bin/cli.mjs +2 -1
  6. package/bin/mcp-memory.mjs +130 -62
  7. package/client.js +8880 -8857
  8. package/cordis.patch.yml +1 -1
  9. package/docs/ARCHITECTURE.md +1 -1
  10. package/icon.svg +1 -1
  11. package/index.js +613 -2558
  12. package/locale/en.json +1 -1
  13. package/locale/zh.json +1 -1
  14. package/package.json +2 -3
  15. package/src/config/exclude-range.js +1 -1
  16. package/src/config/global-config.js +3 -1
  17. package/src/config/session-config.js +12 -10
  18. package/src/config/session-config.test.js +375 -375
  19. package/src/derive/fact.js +6 -6
  20. package/src/derive/gist.js +2 -1
  21. package/src/host/config-views.js +2 -0
  22. package/src/host/db-admin.js +78 -15
  23. package/src/host/panel-api.js +1109 -0
  24. package/src/host/panel-http.js +322 -0
  25. package/src/host/panel-search.js +236 -0
  26. package/src/host/panel-session-store.js +411 -0
  27. package/src/host/rebuild.js +11 -3
  28. package/src/host/scene-ops.js +75 -6
  29. package/src/host/session-sync.js +91 -0
  30. package/src/index.js +2 -1
  31. package/src/ingest/cli.js +8 -7
  32. package/src/ingest/export.js +28 -18
  33. package/src/ingest/package.json +1 -1
  34. package/src/ingest/reader.js +181 -7
  35. package/src/model/embedding.js +3 -2
  36. package/src/model/llm.js +3 -2
  37. package/src/model/rerank.js +7 -4
  38. package/src/pipeline.js +159 -763
  39. package/src/scene/link.js +4 -4
  40. package/src/scene/package.json +1 -1
  41. package/src/scene/split.js +11 -11
  42. package/src/search/_fixtures.js +1 -0
  43. package/src/search/bench.js +4 -2
  44. package/src/search/chunk.js +6 -4
  45. package/src/search/dedupe.js +8 -8
  46. package/src/search/indexer.js +889 -879
  47. package/src/search/note-rank.js +64 -12
  48. package/src/search/regression.test.js +2 -1
  49. package/src/search/rrf.js +11 -11
  50. package/src/search/session-shape.js +3 -1
  51. package/src/search/thread.js +8 -8
  52. package/src/search/vector-fallback.js +509 -0
  53. package/src/search/vector-hydrate.js +309 -0
  54. package/src/search/vector-math.js +125 -0
  55. package/src/search/vector-store.js +1065 -1598
  56. package/src/search/vector-store.test.js +30 -0
  57. package/src/search/window.js +8 -8
  58. package/src/store/db.js +803 -715
  59. package/src/store/repo-extras-meta.js +430 -0
  60. package/src/store/repo-extras-search.js +580 -0
  61. package/src/store/repo.js +1024 -2133
  62. package/src/store/repo.test.js +39 -1
  63. package/src/store/schema.sql +15 -1
  64. package/src/tools/format.js +594 -503
  65. package/src/tools/index.js +7 -15
  66. package/src/tools/memory-forget.js +43 -32
  67. package/src/tools/memory-remember.js +11 -7
  68. package/src/tools/memory-search.js +721 -2206
  69. package/src/tools/remember-forget.test.js +19 -0
  70. package/src/tools/scope.js +7 -6
  71. package/src/tools/search-render.js +502 -0
  72. package/src/tools/time-route.js +71 -66
  73. package/src/tools/vector-route.js +655 -0
  74. package/sessions/qqb-p-0000000000-00000000000000000000000000000000.json +0 -12
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to `dsh-verbatim` are documented here.
4
4
 
5
+ ## [0.1.1] - 2026-11-25
6
+
7
+ ### Performance & Indexing
8
+ - **CJK 2-Char FTS5 Bigram Index (`msg_cjk2_fts`)**: Added schema v17 FTS5 bigram index for 2-character CJK queries so short Chinese searches avoid full-table `LIKE` scans.
9
+ - **Bounded LRU Streaming Fallback Vectors**: Added per-kind lazy loading and LRU eviction backed by SQLite streaming (`vec_fallback_*`) when `sqlite-vec` is unavailable, preventing unbounded memory growth.
10
+ - **Chunked SQLite Batch Operations**: Chunked `media.byMsgIds` and `window.clearForScenes` to stay safely within `SQLITE_MAX_VARIABLE_NUMBER`.
11
+
12
+ ### Reliability, Security & Bug Fixes
13
+ - **Read-Only SQL Timeout Fuse & RPC Hygiene**: Added execution time bounds to `dbQuery`, fixed `readRequestBody` stream error handling, and suppressed JSON-RPC replies to MCP notifications.
14
+ - **Ingest & Store Hardening**: Fixed SQLite handle leaks on error in `importSession` / `rebuildDerived`, stack overflow in `Math.min(...times)` on large sessions, rewind speaker counters, and atomic note restore + audit logging.
15
+ - **Indexer, Search & Scene Consistency**: Fixed `mergeScene` cascade-deleting windows before vector cleanup, `mergeNotes` stale note vectors, `refineSessionGists` excluded message filtering, chunker infinite-loop/oversized-chunk guards, `AbortError` retry short-circuiting, and `02-29` leap-day parsing.
16
+ - **Client UI & Build**: Enabled project-wide `checkJs` + client scope checks, fixed task polling concurrency races, unmount/sequence guards in `DshLlmPicker` and timeline/search loaders, expanded scene refresh after edits, and reliable blob downloads.
17
+ - **Configurable `aboutLabels`**: Added customizable `me` / `him` / `us` note ownership labels.
18
+
5
19
  ## [0.1.0] - 2026-11-23
6
20
 
7
21
  ### Companion-First Memory & Retrieval
package/LICENSE CHANGED
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
21
+ SOFTWARE.
package/README.en.md CHANGED
@@ -7,11 +7,12 @@
7
7
  <p align="center">Every word kept intact · Companion-first verbatim long-term memory plugin for DeepSeek Harness.</p>
8
8
 
9
9
  <p align="center">
10
- <img src="https://img.shields.io/badge/version-0.1.0-0F172A" alt="Version 0.1.0">
10
+ <a href="https://www.npmjs.com/package/dsh-verbatim"><img src="https://img.shields.io/npm/v/dsh-verbatim?label=npm&color=CB3837" alt="npm version"></a>
11
+ <a href="https://www.npmjs.com/package/dsh-verbatim"><img src="https://img.shields.io/npm/dt/dsh-verbatim?label=downloads&color=2563EB" alt="npm downloads"></a>
11
12
  <img src="https://img.shields.io/badge/node-%3E%3D24-339933?logo=node.js&logoColor=white" alt="Node >=24">
12
13
  <img src="https://img.shields.io/badge/storage-node%3Asqlite%20%2B%20FTS5-003B57?logo=sqlite&logoColor=white" alt="node:sqlite + FTS5">
13
- <a href=".github/workflows/ci.yml"><img src="https://img.shields.io/badge/CI-GitHub%20Actions-2088FF?logo=github-actions&logoColor=white" alt="CI"></a>
14
- <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-2563EB" alt="MIT License"></a>
14
+ <a href="https://github.com/saya-ch/dsh-verbatim/actions/workflows/ci.yml"><img src="https://github.com/saya-ch/dsh-verbatim/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
15
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-0F172A" alt="MIT License"></a>
15
16
  </p>
16
17
 
17
18
  <p align="center">
@@ -29,7 +30,7 @@
29
30
 
30
31
  > `dsh-verbatim` is a community plugin for DeepSeek Harness (also providing a CLI and stdio MCP Server) built for AI companion conversations, without modifying DeepSeek Harness source files.
31
32
  >
32
- > **Current version: 0.1.0**. Powered by Node.js `>=24` built-in `node:sqlite` and FTS5. All verbatim messages, derived indexes, and settings stay local in `$DSH_HOME/verbatim/`.
33
+ > **Current version: 0.1.1**. Powered by Node.js `>=24` built-in `node:sqlite` and FTS5. All verbatim messages, derived indexes, and settings stay local in `$DSH_HOME/verbatim/`.
33
34
 
34
35
  `dsh-verbatim` keeps every conversation message word for word in a local SQLite database, automatically organizes exchanges and micro-topics, and brings back full original context through hybrid keyword + vector retrieval and optional reranking even after context compaction.
35
36
 
@@ -37,10 +38,10 @@
37
38
 
38
39
  - **Verbatim source of truth, rebuildable derived layers**: The `msg` table is append-only (rewinds/deletes physically remove the message and its vectors); past conversations remain intact after context compaction.
39
40
  - **Companion-first dual granularity (`exchange` → `thread`)**: Automatically segments natural chats into single exchanges and micro-topics, with 30-minute idle scene boundaries, scene merge/split locking, and timeline cluster folding.
40
- - **Always-hybrid retrieval + optional reranking**: Runs FTS5 trigram / 2-character CJK `LIKE` in parallel with multi-granularity vector search (`vec_msg`, `vec_chunk`, `vec_scene`, `vec_note`), fused via RRF with optional `/rerank` rescoring (and automatic fallback).
41
+ - **Always-hybrid retrieval + optional reranking**: Runs FTS5 trigram / 2-character CJK bigram (`msg_cjk2_fts`) in parallel with multi-granularity vector search (`vec_msg`, `vec_chunk`, `vec_scene`, `vec_note`), fused via RRF with optional `/rerank` rescoring (and automatic fallback).
41
42
  - **Image attachments & captions**: Records image attachments and resolved local paths, supports inline preview and caption editing in the sidebar panel, and returns both paths and captions to the model.
42
43
  - **Strict session isolation & privacy boundaries**: Settings and data are isolated per `session_id`; user-configured private exclude time ranges and per-message "do not recall" flags are completely invisible to Agent tools and cannot be bypassed via parameters.
43
- - **Material 3 companion UI**: Includes **6 sidebar views** (Overview, Search, Timeline, Notes, Audit, Library) and **5 global settings tabs** (3-step setup guide, local model probing, session data management, and read-only SQL diagnostics).
44
+ - **Material 3 companion UI**: Includes **6 sidebar views** (Overview, Search, Timeline, Notes, Audit, Library) and **5 global settings tabs** (3-step setup guide, local model probing, session data management, customizable note `aboutLabels`, and timeout-guarded read-only SQL diagnostics).
44
45
 
45
46
  ## Retrieval Example
46
47
 
@@ -63,37 +64,38 @@ Make sure **Node.js `>=24`** is installed (uses built-in `node:sqlite`, no nativ
63
64
 
64
65
  ### 1. Install & Mount
65
66
 
66
- ```powershell
67
- git clone https://github.com/saya-ch/dsh-verbatim.git
68
- cd dsh-verbatim
69
- npm install --no-audit --no-fund
70
- ```
71
-
72
67
  #### Official DSH Desktop
73
68
 
74
- Point to and enable the local `dsh-verbatim` directory from the **Plugins** page in DSH Desktop (the repository includes [cordis.patch.yml](cordis.patch.yml) and [package.json](package.json) manifests). Desktop profiles are managed by the app and do not use `--profile web` commands.
69
+ Install and enable `dsh-verbatim` from the **Plugins** page in DSH Desktop. Desktop profiles are managed by the app and do not use `--profile web` commands.
75
70
 
76
71
  #### DSH Web
77
72
 
78
- Mount this repository in your Web profile plugin configuration and start DSH:
73
+ If `dsh` is installed globally, run:
79
74
 
80
75
  ```powershell
76
+ dsh plugin --profile web add dsh-verbatim@latest
81
77
  dsh --profile web
82
78
  ```
83
79
 
84
80
  <details>
85
- <summary>Using DeepSeek Harness from source or standalone CLI / MCP Server</summary>
81
+ <summary>Mount from source (git clone / pnpm dsh) or run CLI / MCP Server standalone</summary>
82
+
83
+ ```powershell
84
+ git clone https://github.com/saya-ch/dsh-verbatim.git
85
+ cd dsh-verbatim
86
+ npm install --no-audit --no-fund
87
+ ```
86
88
 
87
- In a DeepSeek Harness source checkout, run `pnpm dsh --profile web` with this plugin directory mounted.
89
+ In a DeepSeek Harness source checkout, you can run `pnpm dsh plugin --profile web add dsh-verbatim@latest` or point directly to this repository (which includes [cordis.patch.yml](cordis.patch.yml) and [package.json](package.json) manifests).
88
90
 
89
- You can also use the CLI or run a standard stdio MCP Server standalone:
91
+ You can also use the CLI or run a standard stdio MCP Server standalone (either via global bin or from source):
90
92
 
91
93
  ```powershell
92
94
  # CLI tool (ingest, search, stats, verify)
93
- node bin/cli.mjs --help
95
+ dsh-verbatim --help # or node bin/cli.mjs --help
94
96
 
95
97
  # Start stdio MCP Server
96
- node bin/mcp-memory.mjs
98
+ dsh-verbatim-mcp # or node bin/mcp-memory.mjs
97
99
  ```
98
100
 
99
101
  </details>
@@ -117,11 +119,11 @@ flowchart LR
117
119
  Chat["DSH Messages & Attachments"] -->|"Verbatim ingest"| Msg["msg table"]
118
120
  Msg -->|"Companion split"| Gran["exchange / thread"]
119
121
  Gran -->|"Hybrid index"| Index["FTS5 + Multi-granularity Vectors"]
120
- Index -->|"RRF + Optional Rerank"| Tools["Agent Tools (search / around / timeline)"]
122
+ Index -->|"RRF + Optional Rerank"| Tools["Agent Tools (search / remember / forget)"]
121
123
  Tools -->|"Privacy-filtered"| Model["Active Chat Model"]
122
124
  ```
123
125
 
124
- The plugin registers the ingest pipeline, search service, and 3 read-only Agent tools (`memory_search`, `memory_around`, `memory_timeline`) on the Host side, and injects the 6-view sidebar panel and 5-tab settings page on the Client side—without modifying DeepSeek Harness core files. See [Architecture](docs/ARCHITECTURE.md) for schema and lock details.
126
+ The plugin registers the ingest pipeline, search service, and 3 Agent tools (`memory_search`, `memory_remember`, `memory_forget`; verbatim conversation rows remain strictly append-only/read-only to all tools) on the Host side, and injects the 6-view sidebar panel and 5-tab settings page on the Client side—without modifying DeepSeek Harness core files. See [Architecture](docs/ARCHITECTURE.md) for schema and lock details.
125
127
 
126
128
  ## Privacy & Security
127
129
 
@@ -133,7 +135,7 @@ The plugin registers the ingest pipeline, search service, and 3 read-only Agent
133
135
  ## Compatibility
134
136
 
135
137
  - **Node.js**: Requires `>=24` (relies on built-in `node:sqlite`).
136
- - **`sqlite-vec`**: Listed in `optionalDependencies`. If unavailable on the host platform, vector search automatically falls back to pure-SQLite cosine similarity with equivalent recall results.
138
+ - **`sqlite-vec`**: Listed in `optionalDependencies`. If unavailable on the host platform, vector search automatically falls back to a bounded LRU + streaming SQLite cosine similarity index with equivalent recall results and bounded memory usage.
137
139
 
138
140
  ## Uninstall
139
141
 
package/README.md CHANGED
@@ -7,11 +7,12 @@
7
7
  <p align="center">Every word kept intact · 为 DeepSeek Harness 打造的陪伴向长期逐字记忆插件。</p>
8
8
 
9
9
  <p align="center">
10
- <img src="https://img.shields.io/badge/version-0.1.0-0F172A" alt="版本 0.1.0">
10
+ <a href="https://www.npmjs.com/package/dsh-verbatim"><img src="https://img.shields.io/npm/v/dsh-verbatim?label=npm&color=CB3837" alt="npm 版本"></a>
11
+ <a href="https://www.npmjs.com/package/dsh-verbatim"><img src="https://img.shields.io/npm/dt/dsh-verbatim?label=downloads&color=2563EB" alt="npm 总下载量"></a>
11
12
  <img src="https://img.shields.io/badge/node-%3E%3D24-339933?logo=node.js&logoColor=white" alt="Node >=24">
12
13
  <img src="https://img.shields.io/badge/storage-node%3Asqlite%20%2B%20FTS5-003B57?logo=sqlite&logoColor=white" alt="node:sqlite + FTS5">
13
- <a href=".github/workflows/ci.yml"><img src="https://img.shields.io/badge/CI-GitHub%20Actions-2088FF?logo=github-actions&logoColor=white" alt="CI"></a>
14
- <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-2563EB" alt="MIT License"></a>
14
+ <a href="https://github.com/saya-ch/dsh-verbatim/actions/workflows/ci.yml"><img src="https://github.com/saya-ch/dsh-verbatim/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
15
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-0F172A" alt="MIT License"></a>
15
16
  </p>
16
17
 
17
18
  <p align="center">
@@ -29,7 +30,7 @@
29
30
 
30
31
  > `dsh-verbatim` 是面向 AI 陪伴场景的 DeepSeek Harness 社区插件(同时提供 CLI 与 MCP Server),不修改 DeepSeek Harness 源码。
31
32
  >
32
- > **当前版本:0.1.0**。基于 Node.js `>=24` 内置 `node:sqlite` 与 FTS5,所有对话原文、索引与设置均保存在本机 `$DSH_HOME/verbatim/`,无外部记忆托管服务。
33
+ > **当前版本:0.1.1**。基于 Node.js `>=24` 内置 `node:sqlite` 与 FTS5,所有对话原文、索引与设置均保存在本机 `$DSH_HOME/verbatim/`,无外部记忆托管服务。
33
34
 
34
35
  `dsh-verbatim` 把每一次对话的原话一字不改地留存在本地 SQLite 中,按问答与微话题自动组织结构;当上下文被压缩或时间跨度拉长后,模型仍可通过关键词、向量语义与可选精排找回完整原话与当时语境。
35
36
 
@@ -37,10 +38,10 @@
37
38
 
38
39
  - **原文一字不改,派生层随时可重建**:`msg` 表作为单一事实来源只增不改(撤回消息会物理删除原文与对应向量);即使经历多次上下文压缩,过往对话依然完整留存。
39
40
  - **陪伴优先的双粒度组织(`exchange` → `thread`)**:面向日常闲聊自动切分单轮问答与微话题,配合 30 分钟静默成场、场景合并/拆分锁定与时间线聚簇折叠,召回连贯而不碎片。
40
- - **始终混合检索 + 可选精排**:并行执行 FTS5 trigram / 2 字中文 `LIKE` 与多粒度向量检索(`vec_msg` / `vec_chunk` / `vec_scene` / `vec_note`),经 RRF 融合排序,并支持 `/rerank` 二次精排(异常自动回退)。
41
+ - **始终混合检索 + 可选精排**:并行执行 FTS5 trigram / 2 字中文 bigram(`msg_cjk2_fts`)与多粒度向量检索(`vec_msg` / `vec_chunk` / `vec_scene` / `vec_note`),经 RRF 融合排序,并支持 `/rerank` 二次精排(异常自动回退)。
41
42
  - **图片附件与备注回想**:入库记录对话中的图片附件与本地解析路径,支持在侧栏内联预览与编辑图片备注(`caption`),检索结果会一并把图片路径与备注交还给模型。
42
43
  - **严格会话隔离与隐私边界**:开关与数据按 `session_id` 独立隔离;用户设置的「私密排除时段」与单句「暂不回想」对 Agent 工具完全不可见,杜绝任何参数绕过。
43
- - **Material 3 陪伴向前端**:提供 **6 个侧栏视图**(概览、搜索、时间轴、笔记、核对、库)与 **5 个全局设置页**(含 3 步快速上手引导、本地模型服务探测、会话数据管理与只读 SQL 诊断)。
44
+ - **Material 3 陪伴向前端**:提供 **6 个侧栏视图**(概览、搜索、时间轴、笔记、核对、库)与 **5 个全局设置页**(含 3 步快速上手引导、本地模型服务探测、会话数据管理、自定义称呼标签 `aboutLabels` 与带超时熔断的只读 SQL 诊断)。
44
45
 
45
46
  ## 检索返回示例
46
47
 
@@ -63,37 +64,38 @@
63
64
 
64
65
  ### 1. 安装与挂载
65
66
 
66
- ```powershell
67
- git clone https://github.com/saya-ch/dsh-verbatim.git
68
- cd dsh-verbatim
69
- npm install --no-audit --no-fund
70
- ```
71
-
72
67
  #### 官方 DSH Desktop
73
68
 
74
- 在应用的 **插件** 页面中指向并启用本地 `dsh-verbatim` 目录(仓库已包含 [cordis.patch.yml](cordis.patch.yml) 与 [package.json](package.json) 声明)。Desktop 的 profile 由应用管理,不适用下面的 `--profile web` 命令。
69
+ 在应用的 **插件** 页面中安装并启用 `dsh-verbatim`。Desktop 的 profile 由应用管理,不适用下面的 `--profile web` 命令。
75
70
 
76
71
  #### DSH Web
77
72
 
78
- 将本仓库挂载到 Web profile 的插件配置后启动:
73
+ 已安装 `dsh` 命令时,在终端执行:
79
74
 
80
75
  ```powershell
76
+ dsh plugin --profile web add dsh-verbatim@latest
81
77
  dsh --profile web
82
78
  ```
83
79
 
84
80
  <details>
85
- <summary>使用 DeepSeek Harness 源码模式或独立 CLI / MCP Server</summary>
81
+ <summary>从源码挂载(git clone / pnpm dsh)或独立使用 CLI / MCP Server</summary>
82
+
83
+ ```powershell
84
+ git clone https://github.com/saya-ch/dsh-verbatim.git
85
+ cd dsh-verbatim
86
+ npm install --no-audit --no-fund
87
+ ```
86
88
 
87
- 在 DeepSeek Harness 源码目录中使用 `pnpm dsh --profile web` 启动并加载本插件目录。
89
+ 在 DeepSeek Harness 源码目录中可使用 `pnpm dsh plugin --profile web add dsh-verbatim@latest` 或指向本仓库目录挂载(仓库已包含 [cordis.patch.yml](cordis.patch.yml) 与 [package.json](package.json) 声明)。
88
90
 
89
- 如果你希望脱离插件界面单独导入、检索或作为标准 MCP Server(stdio)挂载到其他客户端:
91
+ 如果希望脱离插件界面单独使用 CLI 或作为标准 MCP Server(stdio)挂载到其他客户端,全局安装或源码下均可直接运行:
90
92
 
91
93
  ```powershell
92
94
  # CLI 工具(导入、检索、统计、校验)
93
- node bin/cli.mjs --help
95
+ dsh-verbatim --help # 或 node bin/cli.mjs --help
94
96
 
95
97
  # 启动标准 MCP Server(stdio)
96
- node bin/mcp-memory.mjs
98
+ dsh-verbatim-mcp # 或 node bin/mcp-memory.mjs
97
99
  ```
98
100
 
99
101
  </details>
@@ -117,11 +119,11 @@ flowchart LR
117
119
  Chat["DSH 对话与附件"] -->|"逐字留存"| Msg["msg 原文表"]
118
120
  Msg -->|"陪伴切分"| Gran["exchange / thread"]
119
121
  Gran -->|"混合索引"| Index["FTS5 + 多粒度向量"]
120
- Index -->|"RRF + 可选 Rerank"| Tools["Agent 工具 (search / around / timeline)"]
122
+ Index -->|"RRF + 可选 Rerank"| Tools["Agent 工具 (search / remember / forget)"]
121
123
  Tools -->|"隐私过滤后回传"| Model["当前对话模型"]
122
124
  ```
123
125
 
124
- 插件通过 Host 服务挂载入库管线、检索服务与 3 个 Agent 只读工具(`memory_search`、`memory_around`、`memory_timeline`),并通过 Client 入口注入侧栏 6 视图与设置页 5 个标签页;不改写 DeepSeek Harness 安装目录中的源码。详细表结构与写入锁设计见 [系统架构说明](docs/ARCHITECTURE.md)。
126
+ 插件通过 Host 服务挂载入库管线、检索服务与 3 个 Agent 工具(`memory_search`、`memory_remember`、`memory_forget`,其中对话原文对所有工具保持只读不可删改),并通过 Client 入口注入侧栏 6 视图与设置页 5 个标签页;不改写 DeepSeek Harness 安装目录中的源码。详细表结构与写入锁设计见 [系统架构说明](docs/ARCHITECTURE.md)。
125
127
 
126
128
  ## 隐私与安全
127
129
 
@@ -133,7 +135,7 @@ flowchart LR
133
135
  ## 兼容性
134
136
 
135
137
  - **Node.js**:要求 `>=24`(依赖内置 `node:sqlite`)。
136
- - **`sqlite-vec`**:作为 `optionalDependencies` 安装;若当前平台未加载成功,系统会自动降级为纯 SQLite 余弦检索,功能与召回结果等价,仅在大库全量扫描时略慢。
138
+ - **`sqlite-vec`**:作为 `optionalDependencies` 安装;若当前平台未加载成功,系统会自动降级为带 LRU 上界流式扫描的 SQLite 余弦检索,功能与召回结果等价,同时控制大库内存占用。
137
139
 
138
140
  ## 卸载
139
141
 
package/bin/cli.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @ts-check
2
3
  /**
3
4
  * 命令行入口。日常只做三件事:导入、重建、查库概况。
4
5
  *
@@ -55,4 +56,4 @@ if (cmd === 'import') {
55
56
  console.error(`未知命令:${cmd}`);
56
57
  usage();
57
58
  process.exit(1);
58
- }
59
+ }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @ts-check
2
3
  /**
3
4
  * MCP server —— 三个记忆工具的唯一对外出口。
4
5
  *
@@ -30,53 +31,69 @@ import os from 'node:os';
30
31
  import { openDb, defaultDbPath } from '../src/store/db.js';
31
32
  import { createRepo, createExtras } from '../src/store/repo.js';
32
33
  import { createToolSet } from '../src/tools/index.js';
33
- import { loadSessionConfig } from '../src/config/session-config.js';
34
+ import { loadGlobalConfig } from '../src/config/global-config.js';
35
+ import { loadSessionConfig, sessionConfigPath } from '../src/config/session-config.js';
34
36
  import { importSession } from '../src/pipeline.js';
37
+ import { createSessionLock } from '../src/host/session-lock.js';
38
+ import { discoverSessionLogs } from '../src/host/session-sync.js';
35
39
 
36
40
  const VERSION = '0.1.0';
37
41
  const log = (...args) => console.error('[verbatim-mcp]', ...args);
38
42
 
39
43
  /* ───────────────────────── 找会话日志 ───────────────────────── */
40
44
 
41
- /** 在 $DSH_HOME/sessions 下找最近修改的 session.v4.jsonl.zstd */
42
- function findLatestSession() {
43
- const root = path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'sessions');
44
- if (!fs.existsSync(root)) return null;
45
+ /** 在 $DSH_HOME/sessions 下收集全部 session.v4.jsonl.zstd 并按 mtime 倒序排列 */
46
+ function discoverSessions() {
47
+ const dshHome = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
48
+ return discoverSessionLogs(dshHome);
49
+ }
45
50
 
46
- let best = null;
47
- let bestAt = 0;
48
- const walk = (dir, depth) => {
49
- if (depth > 3) return;
50
- let entries;
51
- try {
52
- entries = fs.readdirSync(dir, { withFileTypes: true });
53
- } catch {
54
- return;
55
- }
56
- for (const e of entries) {
57
- const p = path.join(dir, e.name);
58
- if (e.isDirectory()) walk(p, depth + 1);
59
- else if (e.name === 'session.v4.jsonl.zstd') {
60
- try {
61
- const at = fs.statSync(p).mtimeMs;
62
- if (at > bestAt) { bestAt = at; best = p; }
63
- } catch { /* 读不到就跳过 */ }
64
- }
51
+ function resolvePinnedSession() {
52
+ if (process.env.VERBATIM_SESSION) return process.env.VERBATIM_SESSION;
53
+ const targetId = process.env.VERBATIM_SESSION_ID?.trim();
54
+ if (!targetId) return null;
55
+ const match = discoverSessions().find((s) => s.sessionId === targetId);
56
+ if (!match) log(`未找到 VERBATIM_SESSION_ID=${targetId} 对应的会话日志`);
57
+ return match?.file ?? null;
58
+ }
59
+
60
+ const pinnedSessionFile = resolvePinnedSession();
61
+ const isPinned = Boolean(process.env.VERBATIM_SESSION || process.env.VERBATIM_SESSION_ID);
62
+
63
+ function pickActiveSession({ warnMultiple = false } = {}) {
64
+ if (pinnedSessionFile) return pinnedSessionFile;
65
+ if (isPinned) return null;
66
+ const all = discoverSessions();
67
+ if (all.length === 0) return null;
68
+ if (warnMultiple && all.length > 1) {
69
+ const dayAgo = Date.now() - 24 * 60 * 60 * 1000;
70
+ const active = all.filter((s) => s.mtimeMs >= dayAgo);
71
+ if (active.length > 1) {
72
+ log(
73
+ `注意:检测到 ${active.length} 个近 24 小时活跃会话(当前暂绑 ${all[0].sessionId});`
74
+ + `如需锁定请设置 VERBATIM_SESSION_ID。`,
75
+ );
65
76
  }
66
- };
67
- try { walk(root, 0); } catch { /* 权限问题当没找到 */ }
68
- return best;
77
+ }
78
+ return all[0].file;
69
79
  }
70
80
 
71
- const sessionFile = process.env.VERBATIM_SESSION || findLatestSession();
81
+ const sessionFile = pickActiveSession({ warnMultiple: true });
72
82
  const autoSync = process.env.VERBATIM_AUTOSYNC !== '0';
73
83
  const dbPath = process.env.VERBATIM_DB || defaultDbPath();
74
84
 
85
+ let configuredVecDim;
86
+ try {
87
+ const gCfg = loadGlobalConfig({ dshHome: process.env.DSH_HOME ?? undefined }).config;
88
+ const rawDim = Number(gCfg?.embedding?.dim);
89
+ if (Number.isInteger(rawDim) && rawDim > 0) configuredVecDim = rawDim;
90
+ } catch { /* ignore */ }
91
+
75
92
  /* ───────────────────────── 启动 ───────────────────────── */
76
93
 
77
94
  let ctx = null;
78
95
  try {
79
- const handle = openDb({ dbPath, logger: { warn: (m) => log(m) } });
96
+ const handle = openDb({ dbPath, vecDim: configuredVecDim, logger: { warn: (m) => log(m) } });
80
97
  ctx = {
81
98
  handle,
82
99
  repo: createRepo(handle),
@@ -86,72 +103,121 @@ try {
86
103
  };
87
104
  log(`库已打开:${dbPath}${handle.hasVec ? '(向量索引可用)' : '(降级为暴力余弦,功能等价)'}`);
88
105
  if (sessionFile) log(`同步会话:${sessionFile}`);
89
- else log('没找到任何会话日志。设置 VERBATIM_SESSION 指向一个 session.v4.jsonl.zstd。');
106
+ else log('没找到任何会话日志。设置 VERBATIM_SESSION 或 VERBATIM_SESSION_ID 指向目标会话。');
90
107
  } catch (e) {
91
108
  log(`打开记忆库失败:${e.message}`);
92
109
  ctx = null;
93
110
  }
94
111
 
95
- /* ───────────────────────── 增量同步 ───────────────────────── */
112
+ /* ───────────────────────── 增量同步与会话配置热重载 ───────────────────────── */
96
113
 
97
- let lastMtime = 0;
114
+ const syncedMtimes = new Map();
115
+ const failedSyncAt = new Map();
116
+ const readerCache = new Map();
117
+ const mcpSessionLock = createSessionLock();
118
+ const RETRY_COOLDOWN_MS = 5000;
98
119
  let syncing = null;
120
+ let activeConfigKey = null;
121
+
122
+ function sessionIdOfFile(filePath) {
123
+ return filePath ? path.basename(path.dirname(filePath)) : '';
124
+ }
125
+
126
+ function readConfigKey(filePath) {
127
+ const sid = sessionIdOfFile(filePath);
128
+ if (!sid) return `${filePath}|`;
129
+ const dshHome = process.env.DSH_HOME ?? undefined;
130
+ let cfgMtime = 0;
131
+ try {
132
+ const cfgPath = sessionConfigPath(sid, { dshHome });
133
+ if (fs.existsSync(cfgPath)) cfgMtime = fs.statSync(cfgPath).mtimeMs;
134
+ } catch { /* ignore */ }
135
+ return `${filePath}|${cfgMtime}`;
136
+ }
137
+
138
+ function buildToolsForSession(filePath) {
139
+ if (!ctx) return { tools: [], close: () => {} };
140
+ const sid = sessionIdOfFile(filePath);
141
+ try {
142
+ const cfg = loadSessionConfig(sid, { dshHome: process.env.DSH_HOME ?? undefined });
143
+ return createToolSet({ ...ctx, config: cfg, sessionId: sid });
144
+ } catch (e) {
145
+ log(`读取会话配置失败,按默认开关注册工具:${e.message}`);
146
+ return createToolSet({ ...ctx, sessionId: sid });
147
+ }
148
+ }
149
+
150
+ let TOOL_SET = buildToolsForSession(sessionFile);
151
+ let TOOLS = TOOL_SET.tools ?? [];
152
+ activeConfigKey = readConfigKey(sessionFile);
153
+
154
+ function refreshActiveSessionIfNeeded() {
155
+ if (!ctx) return;
156
+ const target = isPinned ? ctx.sessionFile : (pickActiveSession() || ctx.sessionFile);
157
+ if (!target) return;
158
+ const nextKey = readConfigKey(target);
159
+ if (target !== ctx.sessionFile || nextKey !== activeConfigKey) {
160
+ if (target !== ctx.sessionFile) {
161
+ log(`检测到当前活跃会话切换:${ctx.sessionFile ?? '(none)'} → ${target}`);
162
+ } else {
163
+ log(`检测到会话配置变更,热重载工具集:${sessionIdOfFile(target)}`);
164
+ }
165
+ try { TOOL_SET?.close?.(); } catch { /* ignore */ }
166
+ ctx.sessionFile = target;
167
+ TOOL_SET = buildToolsForSession(target);
168
+ TOOLS = TOOL_SET.tools ?? [];
169
+ activeConfigKey = nextKey;
170
+ }
171
+ }
99
172
 
100
173
  /**
101
174
  * 保证库和会话日志一致。
102
- * 按 mtime 判断,避免每次调用都重读整个日志(大文件要一两秒)。
103
- * 并发调用共用同一个 promise,不会重复导入。
175
+ * 结合 mtime 与尾部增量解压(readerCache)避免每次全量重解大文件;
176
+ * 同步遇到瞬时错误(如 SQLITE_BUSY)时仅做短暂冷却,不永久跳过。
104
177
  */
105
178
  async function ensureFresh() {
179
+ refreshActiveSessionIfNeeded();
106
180
  if (!autoSync || !ctx?.sessionFile) return;
181
+ const targetFile = ctx.sessionFile;
182
+ const sid = sessionIdOfFile(targetFile);
107
183
  let stat;
108
184
  try {
109
- stat = fs.statSync(ctx.sessionFile);
185
+ stat = fs.statSync(targetFile);
110
186
  } catch {
111
187
  return; // 日志没了就跑现状,不要因为同步失败让工具挂掉
112
188
  }
113
- if (stat.mtimeMs === lastMtime) return;
189
+ if (syncedMtimes.get(targetFile) === stat.mtimeMs) return;
190
+ const lastFail = failedSyncAt.get(targetFile);
191
+ if (lastFail && lastFail.mtimeMs === stat.mtimeMs && Date.now() - lastFail.at < RETRY_COOLDOWN_MS) {
192
+ return;
193
+ }
114
194
  if (syncing) return syncing;
115
195
 
116
- syncing = (async () => {
196
+ syncing = mcpSessionLock.withLock(sid || targetFile, async () => {
117
197
  const t0 = Date.now();
118
198
  try {
119
- const r = await importSession(ctx.sessionFile, {
199
+ const r = await importSession(targetFile, {
120
200
  handle: ctx.handle,
121
201
  dshHome: process.env.DSH_HOME ?? undefined,
202
+ readerCache,
122
203
  quiet: true,
123
204
  });
124
- lastMtime = stat.mtimeMs;
205
+ syncedMtimes.set(targetFile, stat.mtimeMs);
206
+ failedSyncAt.delete(targetFile);
125
207
  log(`同步完成 ${Date.now() - t0}ms:入库 ${r?.ingest?.inserted ?? '?'} 条`);
126
208
  } catch (e) {
127
- // 同步失败不阻塞查询:查到的可能是稍旧的数据,但比报错好
128
- log(`同步失败(继续用现有数据):${e.message}`);
129
- lastMtime = stat.mtimeMs; // 别在同一个坏状态上反复重试
209
+ // 同步失败不阻塞查询,保留短暂冷却后允许自动重试
210
+ failedSyncAt.set(targetFile, { mtimeMs: stat.mtimeMs, at: Date.now() });
211
+ log(`同步失败(继续用现有数据,稍后自动重试):${e.message}`);
130
212
  } finally {
131
213
  syncing = null;
132
214
  }
133
- })();
215
+ });
134
216
  return syncing;
135
217
  }
136
218
 
137
219
  /* ───────────────────────── 工具集 ───────────────────────── */
138
220
 
139
- function buildTools() {
140
- if (!ctx) return { tools: [], close: () => {} };
141
- try {
142
- const sid = ctx.sessionFile ? path.basename(path.dirname(ctx.sessionFile)) : '';
143
- const cfg = loadSessionConfig(sid, { dshHome: process.env.DSH_HOME ?? undefined });
144
- return createToolSet({ ...ctx, config: cfg, sessionId: sid });
145
- } catch (e) {
146
- log(`读取会话配置失败,按默认开关注册工具:${e.message}`);
147
- const sid = ctx.sessionFile ? path.basename(path.dirname(ctx.sessionFile)) : '';
148
- return createToolSet({ ...ctx, sessionId: sid });
149
- }
150
- }
151
-
152
- const TOOL_SET = buildTools();
153
- const TOOLS = TOOL_SET.tools ?? [];
154
-
155
221
  /* ───────────────────────── JSON-RPC ───────────────────────── */
156
222
 
157
223
  function send(payload) {
@@ -175,6 +241,7 @@ async function handleRequest(msg) {
175
241
  return undefined;
176
242
 
177
243
  case 'tools/list':
244
+ refreshActiveSessionIfNeeded();
178
245
  return reply(id, {
179
246
  tools: TOOLS.map((t) => ({
180
247
  name: t.name,
@@ -184,13 +251,12 @@ async function handleRequest(msg) {
184
251
  });
185
252
 
186
253
  case 'tools/call': {
254
+ // 每次调用前同步并刷新活跃会话,保证"边聊边查得到"
255
+ await ensureFresh();
187
256
  const name = params?.name;
188
257
  const tool = TOOLS.find((t) => t.name === name);
189
258
  if (!tool) return replyError(id, -32602, `未知工具:${name}`);
190
259
 
191
- // 每次调用前同步,保证"边聊边查得到"
192
- await ensureFresh();
193
-
194
260
  try {
195
261
  const text = await tool.handler(params?.arguments ?? {}, ctx ?? {});
196
262
  return reply(id, { content: [{ type: 'text', text: String(text) }] });
@@ -205,6 +271,7 @@ async function handleRequest(msg) {
205
271
  }
206
272
 
207
273
  default:
274
+ if (id === undefined) return undefined;
208
275
  return replyError(id, -32601, `不支持的方法:${method}`);
209
276
  }
210
277
  }
@@ -230,6 +297,7 @@ rl.on('line', (line) => {
230
297
  });
231
298
 
232
299
  rl.on('close', () => {
300
+ try { TOOL_SET?.close?.(); } catch { /* ignore */ }
233
301
  try { ctx?.handle?.close?.(); } catch { /* 关不上也没关系,进程要退了 */ }
234
302
  process.exit(0);
235
303
  });