dsh-recall-rebuild 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -30,7 +30,8 @@
30
30
  ## 特性
31
31
 
32
32
  - **只读增强,零污染**:以 `readOnly` 打开现有记忆库(`$DSH_HOME/memory/memory.db`),不重写捕获管线、不写任何数据,装/卸都不影响原插件;
33
- - **多记忆源可插拔**:`source` 支持 dsh-prime-memory(SQLite FTS5)与 dsh-memory-palace(Markdown 文件)两种底层记忆,`auto` 自动探测,后续可继续扩展;
33
+ - **多记忆源可插拔**:`source` 支持 dsh-prime-memory(SQLite FTS5)、@max-null/dsh-memory(JSON 记忆库)与 dsh-memory-palace(Markdown 文件)三种底层记忆,`auto` 自动探测,后续可继续扩展;
34
+ - **IM 用户级命名空间隔离**:QQ/微信 多人共用角色时,自动解析桥接插件注入的 `<dsh_im_source>` sender 信息,把记忆按用户隔离——「用户 A 的记忆」不会注入给「用户 B」;同一人多会话记忆共享;隔离索引写在插件自己的目录,仍不碰底层记忆库;
34
35
  - **生成式重建**:在 `agent/pre-step` 用会话末尾消息召回碎片,LLM 重建为带语境/情绪/时间感的回忆片段,替代生硬原文注入;
35
36
  - **与生态共存不错位**:注入消息 `source.kind='plugin:recall-rebuild'`,不会被 prime-memory 当作新用户消息再次捕获/蒸馏;`replace` 策略原位替换对方的原文召回,`append` 策略追加,不重复注入;
36
37
  - **永不阻塞对话**:无记忆库/无模型路由/超时/重建失败,一律静默跳过本轮;
@@ -40,7 +41,7 @@
40
41
  ## 适合谁
41
42
 
42
43
  - DSH **桌宠 / 虚拟角色 / 陪伴型 AI** 玩家——想要"像人一样记着你",而不是"查到你的档案";
43
- - 已把角色接入 **QQ / 微信** 等 IM 的 DSH 用户——记忆需要跨会话"想得起来";
44
+ - 已把角色接入 **QQ / 微信** 等 IM 的 DSH 用户——角色同时服务多个人的私聊/群聊时,希望**每个用户的记忆互不串味**,同一人跨会话记忆共享;
44
45
  - 觉得现有记忆插件"注入的原文太生硬、像在念记录"的开发者与用户。
45
46
 
46
47
  ## 安装
@@ -49,7 +50,7 @@
49
50
 
50
51
  - DeepSeek Harness `0.1.0-rc.2 … 0.2.1-rc.3`;
51
52
  - Node ≥ 22.5(需要内置 `node:sqlite`);
52
- - 已安装并运行过 `dsh-prime-memory`(0.26.x,SQLite 记忆库)**或** `dsh-memory-palace`(Markdown 记忆文件),且已有记忆数据。
53
+ - 已安装并运行过 `dsh-prime-memory`(0.26.x,SQLite 记忆库)、`dsh-memory`(@max-null,JSON 记忆库)**或** `dsh-memory-palace`(Markdown 记忆文件),且已有记忆数据。
53
54
 
54
55
  ```bash
55
56
  dsh plugin --profile <你的配置文件名> add dsh-recall-rebuild
@@ -75,18 +76,22 @@ dsh plugin --profile <你的配置文件名> add dsh-recall-rebuild
75
76
 
76
77
  ```mermaid
77
78
  flowchart LR
78
- U["用户新消息"] --> P["agent/pre-step<br/>(本插件 prepend)"]
79
+ U["IM 用户新消息<br/>(带 &lt;dsh_im_source&gt; sender)"] --> P["agent/pre-step<br/>(本插件 prepend)"]
80
+ P --> K["提取当前用户键<br/>(senderId / chatId)"]
79
81
  P --> Q["构造召回查询<br/>(会话末尾消息)"]
80
- Q --> S[("记忆库<br/>prime(SQLite FTS5)/ palace(Markdown)")]
81
- S --> R["LLM 重建式回忆<br/>(碎片 → 带语境的回忆片段)"]
82
+ Q --> S[("记忆库<br/>prime(SQLite)/ dsh-memory(JSON)/ palace(Markdown)")]
83
+ S --> F["用户命名空间过滤<br/>(auto/strict/off)"]
84
+ F --> R["LLM 重建式回忆<br/>(碎片 → 带语境的回忆片段)"]
82
85
  R --> I["注入回忆片段<br/>source.kind = plugin:recall-rebuild"]
86
+ F --> N[("归属索引<br/>~/.dsh/recall-rebuild/namespaces")]
87
+ F -. 命中候选归属当前用户 .-> N
83
88
  P --> M["模型推理"]
84
89
  I --> M
85
90
  M --> A["回复"]
86
91
  R -. "失败/超时 → 静默跳过" .-> M
87
92
  ```
88
93
 
89
- 一句话流程:**检索 → 重建 → 注入**,而不是**检索 → 注入**。
94
+ 一句话流程:**提取用户 → 检索 → 用户隔离过滤 → 重建 → 注入**,而不是**检索 → 注入**。
90
95
 
91
96
  ## 与现有插件的错开与共存
92
97
 
@@ -99,7 +104,7 @@ flowchart LR
99
104
  | --- | --- | --- |
100
105
  | `enabled` | `true` | 总开关 |
101
106
  | `dataDir` | `''` | 记忆库目录;空 = `$DSH_HOME/memory` |
102
- | `source` | `auto` | 记忆来源:`auto` 自动探测(prime → palace);`prime` = dsh-prime-memory SQLite 库;`palace` = dsh-memory-palace Markdown 文件 |
107
+ | `source` | `auto` | 记忆来源:`auto` 自动探测(prime → dsh-memory → palace);`prime` = dsh-prime-memory SQLite 库;`dsh-memory` = @max-null/dsh-memory JSON 记忆库;`palace` = dsh-memory-palace Markdown 文件 |
103
108
  | `rebuild.enabled` | `true` | 重建式回忆开关;`false` 退化为原文检索注入 |
104
109
  | `rebuild.maxResults` | `5` | 每轮检索条数 |
105
110
  | `rebuild.maxMemoryChars` | `400` | 单条记忆进重建 prompt 的字符上限 |
@@ -113,20 +118,25 @@ flowchart LR
113
118
  | `inject.includeSources` | `true` | 注入时附记忆来源 id 标注 |
114
119
  | `query.tailMessages` | `8` | 召回查询取会话末尾消息条数 |
115
120
  | `query.maxChars` | `1200` | 召回查询字符上限 |
121
+ | `user.isolation` | `auto` | IM 用户隔离模式:`auto` 剔除「明确属于其他用户」的记忆(无主记忆默认可见,命中后归位);`strict` 只注入「已归属当前用户」的记忆(新用户零记忆起步);`off` 不过滤。桌面直接对话自动不隔离 |
122
+ | `user.isolationDir` | `''` | 归属索引目录;空 = `<DSH_HOME>/recall-rebuild/namespaces` |
123
+ | `user.sourceTagPattern` | `''` | 覆盖内置 `<dsh_im_source>` 解析正则;不同桥接插件字段不同时可自定义(需含一个捕获组取用户 id) |
116
124
 
117
125
  ## Roadmap
118
126
 
119
- - [ ] 更多记忆源 adapter(`@max-null/dsh-memory`、`dsh-memory-gate` 等 SQLite/文件变体);
120
- - [ ] IM 用户级命名空间隔离(跨 QQ/微信的同一人记忆共享);
127
+ - [ ] 更多记忆源 adapter(`dsh-memory-vault`、`dsh-auto-memory`、`dsh-memory-gate` 等变体);
128
+ - [x] IM 用户级命名空间隔离(跨 QQ/微信的同一人记忆共享)—— v0.1.3 已实现;
121
129
  - [ ] 重建质量可观测:注入效果对比开关 + 每轮重建日志;
122
130
  - [ ] 睡眠巩固 / 联想扩散(更接近人脑的长期记忆子系统的后续阶段)。
123
131
 
124
132
  ## 局限(如实声明)
125
133
 
126
134
  1. **只增强召回/呈现层**:底层库捕获了什么,重建就基于什么;库缺字段(如没有情绪标注)时,重建不会凭空造出它。
127
- 2. **幻觉受控但非零**:重建 prompt 明确禁止编造碎片外事实,但 LLM 仍有漂移概率;注入标注记忆依据 id 便于审计。需要强事实的场景可关掉重建(`rebuild.enabled=false`)。
128
- 3. **token 消耗**:每轮召回命中即产生一次重建调用(通常百级 token),由宿主模型路由计费。
129
- 4. **未覆盖**:LoRA 权重内化等权重级记忆不在本插件范围(见 Roadmap)。
135
+ 2. **用户隔离是观察式启发式,非底层强隔离**:底层记忆库(prime 等)没有 IM 用户字段,本插件靠「谁在会话中命中过这条记忆,它就归谁」建立归属。因此:`auto` 模式防得住「已明确归属他人」的记忆,防不住「从未被命中过的无主记忆」(它们默认可见,命中后归位);`strict` 模式从零记忆起步,聊过的话题才开始归位。需要强隐私隔离且不介意冷启动时用 `strict`。
136
+ 3. **用户识别依赖桥接插件约定**:优先解析 `<dsh_im_source>` JSON(senderId/chatId/threadId/botId),兜底常见字段(senderId/userId/openid/fromUser);不同桥接字段不同时用 `user.sourceTagPattern` 覆盖。识别不到用户(桌面会话)时不做隔离。
137
+ 4. **幻觉受控但非零**:重建 prompt 明确禁止编造碎片外事实,但 LLM 仍有漂移概率;注入标注记忆依据 id 便于审计。需要强事实的场景可关掉重建(`rebuild.enabled=false`)。
138
+ 5. **token 消耗**:每轮召回命中即产生一次重建调用(通常百级 token),由宿主模型路由计费。
139
+ 6. **未覆盖**:LoRA 权重内化等权重级记忆不在本插件范围(见 Roadmap)。
130
140
 
131
141
  ## 开发与验证
132
142
 
@@ -134,7 +144,7 @@ flowchart LR
134
144
  npm install
135
145
  npm run typecheck # tsc --noEmit
136
146
  npm run build # 编译到 dist/
137
- node scripts/verify.mjs # 运行时验证:导出/Config/prime FTS+LIKE/palace Markdown/降级
147
+ node scripts/verify.mjs # 运行时验证:导出/Config/prime FTS+LIKE/palace Markdown/dsh-memory JSON/降级
138
148
  npm pack --dry-run # 检查发布包内容
139
149
  ```
140
150
 
@@ -146,12 +156,13 @@ MIT
146
156
 
147
157
  ## English Overview
148
158
 
149
- **dsh-recall-rebuild** is an *enhancer* for memory plugins in [DeepSeek Harness](https://github.com/deepseek-ai/DeepSeek-Harness) (DSH). Existing memory plugins such as `dsh-prime-memory` (SQLite) or `dsh-memory-palace` (Markdown) already handle *storage* very well — cross-session capture, distillation and persistence are mature, so install one first. This plugin does **not** duplicate that work; it enhances a single layer: **how memories are recalled** — instead of injecting raw snippets as-is, it has the LLM reconstruct them into contextual recollections, so "remembering" feels natural rather than like quoting a file.
159
+ **dsh-recall-rebuild** is an *enhancer* for memory plugins in [DeepSeek Harness](https://github.com/deepseek-ai/DeepSeek-Harness) (DSH). Existing memory plugins such as `dsh-prime-memory` (SQLite), `@max-null/dsh-memory` (JSON) or `dsh-memory-palace` (Markdown) already handle *storage* very well — cross-session capture, distillation and persistence are mature, so install one first. This plugin does **not** duplicate that work; it enhances a single layer: **how memories are recalled** — instead of injecting raw snippets as-is, it has the LLM reconstruct them into contextual recollections, so "remembering" feels natural rather than like quoting a file.
150
160
 
151
161
  This plugin upgrades the **recall/presentation layer**:
152
162
 
153
163
  - Opens the existing memory store (`$DSH_HOME/memory/memory.db`) **read-only**, never writes, never touches the capture pipeline;
154
164
  - Before every model step, it retrieves memory fragments and asks the LLM to **reconstruct** them into contextual, emotionally-toned recollection snippets (using only in-fragment facts — no fabrication);
165
+ - **Per-user memory isolation for IM (QQ/WeChat…)**: it parses the `<dsh_im_source>` block that IM bridge plugins attach to messages, extracts `senderId`/`chatId`, and keeps each user's memories out of other users' recalls via an ownership index it maintains in its **own** directory (`<DSH_HOME>/recall-rebuild/namespaces`) — the underlying memory DB is still never written. Modes: `auto` (drop memories clearly owned by others; ownerless memories are conservatively visible until claimed), `strict` (only inject memories already owned by the current user), `off` (no filtering). Desktop chats with no detectable user are never filtered;
155
166
  - Injects via `agent/pre-step` with `source.kind='plugin:recall-rebuild'`, so it is never re-captured by the underlying memory plugin; `replace` strategy swaps out the other plugin's raw-text recall in place, `append` adds alongside;
156
167
  - **Never blocks a conversation**: missing store, missing model route, timeout or rebuild failure all silently skip the step;
157
168
  - **Zero infra cost**: no GPU/VM — rebuild calls go through the host's existing LLM routing, ~hundreds of tokens per hit; uses only Node's built-in `node:sqlite`.
package/dist/config.d.ts CHANGED
@@ -41,6 +41,21 @@ export interface QueryOptions {
41
41
  /** 召回查询字符上限。 */
42
42
  maxChars: number;
43
43
  }
44
+ /** IM 用户级命名空间隔离选项。 */
45
+ export interface UserIsolationOptions {
46
+ /**
47
+ * 隔离模式:
48
+ * - 'off':不过滤(所有用户共享全部记忆,旧行为);
49
+ * - 'auto':剔除「明确属于其他用户」的记忆,无主记忆默认可见(命中后归位);
50
+ * - 'strict':只注入「已归属当前用户」的记忆,新用户零记忆起步(随会话命中逐渐归位)。
51
+ * 桌面直接对话(识别不到 IM 用户)时任何模式都不过滤。
52
+ */
53
+ isolation: 'off' | 'auto' | 'strict';
54
+ /** 归属索引目录;空 = <DSH_HOME>/recall-rebuild/namespaces(缺省 ~/.dsh/...)。 */
55
+ isolationDir: string;
56
+ /** 覆盖内置 <dsh_im_source> 解析正则(不同桥接插件字段不同时可自定义);空 = 内置。 */
57
+ sourceTagPattern: string;
58
+ }
44
59
  export interface RecallRebuildConfig {
45
60
  /** 总开关。 */
46
61
  enabled: boolean;
@@ -48,19 +63,21 @@ export interface RecallRebuildConfig {
48
63
  dataDir: string;
49
64
  /**
50
65
  * 记忆来源:
51
- * - 'auto':自动探测 —— prime-memory 库存在则读它,否则尝试 memory-palace 文件;
66
+ * - 'auto':自动探测 —— prime-memory 库存在则读它,否则依次尝试 dsh-memory(JSON)与 memory-palace(Markdown);
52
67
  * - 'prime':只读 dsh-prime-memory 的 SQLite 库($dataDir/memory.db);
68
+ * - 'dsh-memory':只读 @max-null/dsh-memory 的 JSON 记忆(~/.dsh/storages/memory.json 与 <cwd>/.dsh/storages/);
53
69
  * - 'palace':只读 dsh-memory-palace 的 Markdown 文件(~/.deepseek-harness/MEMORY.md 与 <cwd>/.deepseek-harness/memory/)。
54
70
  */
55
- source: 'auto' | 'prime' | 'palace';
71
+ source: 'auto' | 'prime' | 'dsh-memory' | 'palace';
56
72
  rebuild: RebuildOptions;
57
73
  inject: InjectOptions;
58
74
  query: QueryOptions;
75
+ user: UserIsolationOptions;
59
76
  }
60
77
  export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
61
78
  enabled: Schema<boolean, boolean, "defined">;
62
79
  dataDir: Schema<string, string, "defined">;
63
- source: Schema<"auto" | "prime" | "palace", "auto" | "prime" | "palace", "defined">;
80
+ source: Schema<"auto" | "prime" | "dsh-memory" | "palace", "auto" | "prime" | "dsh-memory" | "palace", "defined">;
64
81
  rebuild: Schema<Schemastery.ObjectS<NoInfer<{
65
82
  enabled: Schema<boolean, boolean, "defined">;
66
83
  maxResults: Schema<number, number, "defined">;
@@ -96,10 +113,19 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
96
113
  tailMessages: Schema<number, number, "defined">;
97
114
  maxChars: Schema<number, number, "defined">;
98
115
  }>>, "defined">;
116
+ user: Schema<Schemastery.ObjectS<NoInfer<{
117
+ isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
118
+ isolationDir: Schema<string, string, "defined">;
119
+ sourceTagPattern: Schema<string, string, "defined">;
120
+ }>>, Schemastery.ObjectT<NoInfer<{
121
+ isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
122
+ isolationDir: Schema<string, string, "defined">;
123
+ sourceTagPattern: Schema<string, string, "defined">;
124
+ }>>, "defined">;
99
125
  }>>, Schemastery.ObjectT<NoInfer<{
100
126
  enabled: Schema<boolean, boolean, "defined">;
101
127
  dataDir: Schema<string, string, "defined">;
102
- source: Schema<"auto" | "prime" | "palace", "auto" | "prime" | "palace", "defined">;
128
+ source: Schema<"auto" | "prime" | "dsh-memory" | "palace", "auto" | "prime" | "dsh-memory" | "palace", "defined">;
103
129
  rebuild: Schema<Schemastery.ObjectS<NoInfer<{
104
130
  enabled: Schema<boolean, boolean, "defined">;
105
131
  maxResults: Schema<number, number, "defined">;
@@ -135,4 +161,13 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
135
161
  tailMessages: Schema<number, number, "defined">;
136
162
  maxChars: Schema<number, number, "defined">;
137
163
  }>>, "defined">;
164
+ user: Schema<Schemastery.ObjectS<NoInfer<{
165
+ isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
166
+ isolationDir: Schema<string, string, "defined">;
167
+ sourceTagPattern: Schema<string, string, "defined">;
168
+ }>>, Schemastery.ObjectT<NoInfer<{
169
+ isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
170
+ isolationDir: Schema<string, string, "defined">;
171
+ sourceTagPattern: Schema<string, string, "defined">;
172
+ }>>, "defined">;
138
173
  }>>, "defined">;
package/dist/config.js CHANGED
@@ -9,7 +9,7 @@ import Schema from '@deepseek-ai/schemastery';
9
9
  export const recallRebuildSchema = Schema.object({
10
10
  enabled: Schema.boolean().default(true),
11
11
  dataDir: Schema.string().default(''),
12
- source: Schema.union(['auto', 'prime', 'palace']).default('auto'),
12
+ source: Schema.union(['auto', 'prime', 'dsh-memory', 'palace']).default('auto'),
13
13
  rebuild: Schema.object({
14
14
  enabled: Schema.boolean().default(true),
15
15
  maxResults: Schema.number().min(1).max(20).default(5),
@@ -29,4 +29,9 @@ export const recallRebuildSchema = Schema.object({
29
29
  tailMessages: Schema.number().min(1).max(30).default(8),
30
30
  maxChars: Schema.number().min(100).max(4000).default(1200),
31
31
  }).default({}),
32
+ user: Schema.object({
33
+ isolation: Schema.union(['off', 'auto', 'strict']).default('auto'),
34
+ isolationDir: Schema.string().default(''),
35
+ sourceTagPattern: Schema.string().default(''),
36
+ }).default({}),
32
37
  }).default({});
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export declare const inject: string[];
5
5
  export declare const Config: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
6
6
  enabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
7
7
  dataDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
8
- source: import("@deepseek-ai/schemastery").default<"auto" | "prime" | "palace", "auto" | "prime" | "palace", "defined">;
8
+ source: import("@deepseek-ai/schemastery").default<"auto" | "prime" | "dsh-memory" | "palace", "auto" | "prime" | "dsh-memory" | "palace", "defined">;
9
9
  rebuild: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
10
10
  enabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
11
11
  maxResults: import("@deepseek-ai/schemastery").default<number, number, "defined">;
@@ -41,10 +41,19 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
41
41
  tailMessages: import("@deepseek-ai/schemastery").default<number, number, "defined">;
42
42
  maxChars: import("@deepseek-ai/schemastery").default<number, number, "defined">;
43
43
  }>>, "defined">;
44
+ user: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
45
+ isolation: import("@deepseek-ai/schemastery").default<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
46
+ isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
47
+ sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
48
+ }>>, Schemastery.ObjectT<NoInfer<{
49
+ isolation: import("@deepseek-ai/schemastery").default<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
50
+ isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
51
+ sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
52
+ }>>, "defined">;
44
53
  }>>, Schemastery.ObjectT<NoInfer<{
45
54
  enabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
46
55
  dataDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
47
- source: import("@deepseek-ai/schemastery").default<"auto" | "prime" | "palace", "auto" | "prime" | "palace", "defined">;
56
+ source: import("@deepseek-ai/schemastery").default<"auto" | "prime" | "dsh-memory" | "palace", "auto" | "prime" | "dsh-memory" | "palace", "defined">;
48
57
  rebuild: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
49
58
  enabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
50
59
  maxResults: import("@deepseek-ai/schemastery").default<number, number, "defined">;
@@ -80,5 +89,14 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
80
89
  tailMessages: import("@deepseek-ai/schemastery").default<number, number, "defined">;
81
90
  maxChars: import("@deepseek-ai/schemastery").default<number, number, "defined">;
82
91
  }>>, "defined">;
92
+ user: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
93
+ isolation: import("@deepseek-ai/schemastery").default<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
94
+ isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
95
+ sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
96
+ }>>, Schemastery.ObjectT<NoInfer<{
97
+ isolation: import("@deepseek-ai/schemastery").default<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
98
+ isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
99
+ sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
100
+ }>>, "defined">;
83
101
  }>>, "defined">;
84
102
  export declare function apply(ctx: Context, config: RecallRebuildConfig): Promise<void>;
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import { dshHomePath } from '@deepseek-ai/dsh-home-paths';
12
12
  import { recallRebuildSchema } from './config.js';
13
13
  import { openMemorySource } from './store.js';
14
14
  import { registerRecallRebuild } from './recall.js';
15
+ import { NamespaceStore } from './namespace.js';
15
16
  export const name = 'recall-rebuild';
16
17
  export const inject = ['llm'];
17
18
  export const Config = recallRebuildSchema;
@@ -33,6 +34,25 @@ function resolveDataDir(config, logger) {
33
34
  }
34
35
  return fallback;
35
36
  }
37
+ /** 用户隔离归属目录:<DSH_HOME>/recall-rebuild/namespaces(缺省 ~/.dsh/recall-rebuild/namespaces)。 */
38
+ function resolveIsolationDir(config, logger) {
39
+ if (config.user.isolationDir)
40
+ return config.user.isolationDir;
41
+ try {
42
+ const home = dshHomePath();
43
+ if (home)
44
+ return path.join(home, 'recall-rebuild', 'namespaces');
45
+ }
46
+ catch {
47
+ /* 落到兜底 */
48
+ }
49
+ const base = process.env.HOME || process.env.USERPROFILE || '';
50
+ const fallback = base ? path.join(base, '.dsh', 'recall-rebuild', 'namespaces') : '';
51
+ if (!fallback) {
52
+ logger.warn(`[recall-rebuild] 无法确定用户隔离目录,请在 config.user.isolationDir 显式指定`);
53
+ }
54
+ return fallback;
55
+ }
36
56
  export async function apply(ctx, config) {
37
57
  const logger = ctx.logger;
38
58
  const dataDir = resolveDataDir(config, logger);
@@ -41,6 +61,9 @@ export async function apply(ctx, config) {
41
61
  // 可插拔记忆源:prime(SQLite FTS5)| palace(Markdown 文件)| auto(自动探测)
42
62
  const store = openMemorySource(config.source, { dataDir, cwd, logger });
43
63
  ctx.effect(() => () => store.close());
64
+ // IM 用户级命名空间隔离(自己的目录,绝不写底层记忆库)
65
+ const namespaces = new NamespaceStore(resolveIsolationDir(config, logger), logger);
66
+ namespaces.ensureDir();
44
67
  if (store.ok) {
45
68
  logger.info(`[recall-rebuild] 已只读挂载记忆库: ${store.label}`);
46
69
  }
@@ -48,7 +71,8 @@ export async function apply(ctx, config) {
48
71
  logger.warn(`[recall-rebuild] 记忆库不可用(${store.label}),插件按只观察模式运行(不注入)。` +
49
72
  `请先安装并运行 dsh-prime-memory / dsh-memory-palace,或确认 config.dataDir / cwd 正确`);
50
73
  }
51
- registerRecallRebuild(ctx, store, config, logger);
74
+ registerRecallRebuild(ctx, store, config, logger, namespaces);
52
75
  logger.info(`[recall-rebuild] 重建式回忆增强就绪 ` +
53
- `(rebuild=${config.rebuild.enabled}, inject=${config.inject.strategy}, source=${config.source})`);
76
+ `(rebuild=${config.rebuild.enabled}, inject=${config.inject.strategy}, source=${config.source}, ` +
77
+ `isolation=${config.user.isolation})`);
54
78
  }
@@ -0,0 +1,31 @@
1
+ import type { MemoryRecord } from './store.js';
2
+ import type { LoggerLike } from './store.js';
3
+ export type IsolationMode = 'off' | 'auto' | 'strict';
4
+ /** 从消息文本中提取当前 IM 用户键;识别不到返回 null。pattern 可覆盖内置 <dsh_im_source> 正则。 */
5
+ export declare function extractUserKey(texts: string[], pattern?: string): string | null;
6
+ export declare class NamespaceStore {
7
+ private readonly dir;
8
+ private readonly logger;
9
+ /** 目录缓存:userKey → memoryId 集;cacheTtlMs 内复用,避免每轮扫描磁盘。 */
10
+ private cache;
11
+ private cacheAt;
12
+ private readonly cacheTtlMs;
13
+ constructor(dir: string, logger: LoggerLike);
14
+ /** 确保目录存在(只建本插件自己的目录)。 */
15
+ ensureDir(): void;
16
+ /** 重建缓存(遍历 namespaces 下所有归属文件)。 */
17
+ private refresh;
18
+ /** 全部用户归属集:memoryId → [userKey...](cache 内复用)。 */
19
+ private ownersOf;
20
+ /** 当前用户已归属的记忆 id 集。 */
21
+ private userIds;
22
+ /**
23
+ * 按隔离模式过滤候选记忆。
24
+ * @param memories 检索候选(已按相关性排序)
25
+ * @param userKey 当前用户键;null = 桌面/无法识别 → 不过滤
26
+ * @param mode off / auto / strict
27
+ */
28
+ filter(memories: MemoryRecord[], userKey: string | null, mode: IsolationMode): MemoryRecord[];
29
+ /** 把"本轮实际保留的候选"记为当前用户归属(增量、原子写)。 */
30
+ recordHits(userKey: string | null, memories: MemoryRecord[]): void;
31
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * IM 用户级命名空间隔离。
3
+ *
4
+ * 背景:prime-memory 的检索只按 workspace(项目路径)+ scope 过滤,IM 场景(QQ/微信桥接)
5
+ * 的记忆全部落在 scope='global',跨用户必然串味。底层记忆库没有 IM 用户字段,
6
+ * 本插件在**自己的目录**(<DSH_HOME>/recall-rebuild/namespaces,缺省 ~/.dsh/recall-rebuild/namespaces)
7
+ * 维护「记忆记录 id → 归属用户」的观察式索引,检索时按隔离模式过滤。
8
+ *
9
+ * 归属语义(启发式,诚实声明局限):
10
+ * - 一条记忆 id 在哪个用户的会话里被检索命中并保留,就归属哪个用户;
11
+ * - 多用户会话都命中过的记忆 → 多归属 → 对这些用户都可见(群聊共享场景自然成立);
12
+ * - 从未被任何用户会话命中过的"无主"记忆(auto 模式)默认可见,命中后归位;
13
+ * - 隔离索引只写本插件的目录,绝不写底层记忆库。
14
+ *
15
+ * userKey 提取:优先解析 IM 桥接(@xmanrui/dsh-im 等)注入消息的
16
+ * `<dsh_im_source>{json}</dsh_im_source>` 文本块(senderId/chatId/threadId/botId),
17
+ * 兜底匹配常见字段(senderId/userId/user_id/openid/fromUser);桌面直接对话识别不到
18
+ * 用户时返回 null —— 不做隔离(保持现行为),绝不猜测。
19
+ */
20
+ import * as fs from 'node:fs';
21
+ import * as path from 'node:path';
22
+ /** 内置 <dsh_im_source> 块:JSON 内 < > & 被转义为 \u003c 等。 */
23
+ const SOURCE_BLOCK = /<dsh_im_source>\s*(\{[\s\S]*?\})\s*<\/dsh_im_source>/;
24
+ /** 兜底字段(QQ openid / senderId / userId / fromUser 等)。 */
25
+ const FALLBACK_FIELD = /(?:senderId|userId|user_id|openid|fromUser|from_openid)["':=\s]*([A-Za-z0-9_@.\-]{6,64})/;
26
+ /** 从消息文本中提取当前 IM 用户键;识别不到返回 null。pattern 可覆盖内置 <dsh_im_source> 正则。 */
27
+ export function extractUserKey(texts, pattern) {
28
+ const custom = pattern ? new RegExp(pattern, 'i') : null;
29
+ for (const t of texts) {
30
+ if (!t)
31
+ continue;
32
+ const block = SOURCE_BLOCK.exec(t);
33
+ if (block) {
34
+ try {
35
+ const j = JSON.parse(block[1] ?? '{}');
36
+ const id = j.senderId ?? j.chatId ?? j.threadId ?? j.botId;
37
+ if (typeof id === 'string' && id) {
38
+ const channel = typeof j.channel === 'string' && j.channel ? j.channel : 'im';
39
+ return `im:${channel}:${id.slice(0, 128)}`;
40
+ }
41
+ }
42
+ catch {
43
+ /* 块解析失败 → 尝试兜底字段 */
44
+ }
45
+ }
46
+ const fb = FALLBACK_FIELD.exec(t);
47
+ if (fb && fb[1])
48
+ return `im-fallback:${fb[1].slice(0, 128)}`;
49
+ if (custom) {
50
+ const cm = custom.exec(t);
51
+ if (cm && cm[1])
52
+ return `im-custom:${cm[1].slice(0, 128)}`;
53
+ }
54
+ }
55
+ return null;
56
+ }
57
+ /** 用户键 → 文件名(只留安全字符,避免路径穿越/非法字符)。 */
58
+ function fileFor(userKey) {
59
+ const safe = userKey.replace(/[^A-Za-z0-9_.@-]/g, '_');
60
+ return `${safe}.json`;
61
+ }
62
+ export class NamespaceStore {
63
+ dir;
64
+ logger;
65
+ /** 目录缓存:userKey → memoryId 集;cacheTtlMs 内复用,避免每轮扫描磁盘。 */
66
+ cache = new Map();
67
+ cacheAt = 0;
68
+ cacheTtlMs = 5000;
69
+ constructor(dir, logger) {
70
+ this.dir = dir;
71
+ this.logger = logger;
72
+ }
73
+ /** 确保目录存在(只建本插件自己的目录)。 */
74
+ ensureDir() {
75
+ try {
76
+ fs.mkdirSync(this.dir, { recursive: true });
77
+ }
78
+ catch (err) {
79
+ this.logger.warn(`[recall-rebuild] 无法创建用户隔离目录 ${this.dir}: ${err instanceof Error ? err.message : String(err)}`);
80
+ }
81
+ }
82
+ /** 重建缓存(遍历 namespaces 下所有归属文件)。 */
83
+ refresh() {
84
+ this.cache.clear();
85
+ this.cacheAt = Date.now();
86
+ let names = [];
87
+ try {
88
+ names = fs.readdirSync(this.dir).filter((n) => n.endsWith('.json'));
89
+ }
90
+ catch {
91
+ return; // 目录不存在/不可读 → 空索引(不隔离)
92
+ }
93
+ for (const n of names) {
94
+ const p = path.join(this.dir, n);
95
+ try {
96
+ const doc = JSON.parse(fs.readFileSync(p, 'utf8'));
97
+ const ids = doc.memoryIds ?? {};
98
+ const set = new Set(Object.keys(ids));
99
+ if (set.size > 0)
100
+ this.cache.set(n, set);
101
+ }
102
+ catch {
103
+ /* 单个文件损坏不影响其它用户 */
104
+ }
105
+ }
106
+ }
107
+ /** 全部用户归属集:memoryId → [userKey...](cache 内复用)。 */
108
+ ownersOf() {
109
+ if (this.cache.size === 0 || Date.now() - this.cacheAt > this.cacheTtlMs)
110
+ this.refresh();
111
+ const owners = new Map();
112
+ for (const [file, ids] of this.cache) {
113
+ for (const id of ids) {
114
+ const arr = owners.get(id);
115
+ if (arr)
116
+ arr.push(file);
117
+ else
118
+ owners.set(id, [file]);
119
+ }
120
+ }
121
+ return owners;
122
+ }
123
+ /** 当前用户已归属的记忆 id 集。 */
124
+ userIds(userKey) {
125
+ if (this.cache.size === 0 || Date.now() - this.cacheAt > this.cacheTtlMs)
126
+ this.refresh();
127
+ return this.cache.get(fileFor(userKey)) ?? new Set();
128
+ }
129
+ /**
130
+ * 按隔离模式过滤候选记忆。
131
+ * @param memories 检索候选(已按相关性排序)
132
+ * @param userKey 当前用户键;null = 桌面/无法识别 → 不过滤
133
+ * @param mode off / auto / strict
134
+ */
135
+ filter(memories, userKey, mode) {
136
+ if (!userKey || mode === 'off' || memories.length === 0)
137
+ return memories;
138
+ const owners = this.ownersOf();
139
+ const mine = this.userIds(userKey);
140
+ if (mode === 'strict') {
141
+ // 只保留"已归属给当前用户"的记忆;无主记忆一律不注入(新用户记忆随命中逐渐归位)
142
+ return memories.filter((m) => m.id && mine.has(m.id));
143
+ }
144
+ // auto:剔除"明确属于其他用户"的记忆;无主记忆保留(保守可见,命中后归位)
145
+ return memories.filter((m) => {
146
+ if (!m.id)
147
+ return true;
148
+ const who = owners.get(m.id);
149
+ if (!who || who.length === 0)
150
+ return true; // 无主 → 保留
151
+ return who.some((f) => f === fileFor(userKey));
152
+ });
153
+ }
154
+ /** 把"本轮实际保留的候选"记为当前用户归属(增量、原子写)。 */
155
+ recordHits(userKey, memories) {
156
+ if (!userKey || memories.length === 0)
157
+ return;
158
+ const file = fileFor(userKey);
159
+ const p = path.join(this.dir, file);
160
+ const now = Date.now();
161
+ let doc = { memoryIds: {} };
162
+ try {
163
+ if (fs.existsSync(p))
164
+ doc = JSON.parse(fs.readFileSync(p, 'utf8'));
165
+ }
166
+ catch {
167
+ doc = { memoryIds: {} };
168
+ }
169
+ let changed = false;
170
+ for (const m of memories) {
171
+ if (!m.id)
172
+ continue;
173
+ if (typeof doc.memoryIds[m.id] !== 'number') {
174
+ doc.memoryIds[m.id] = now;
175
+ changed = true;
176
+ }
177
+ }
178
+ if (!changed)
179
+ return;
180
+ try {
181
+ fs.mkdirSync(this.dir, { recursive: true });
182
+ const tmp = `${p}.tmp`;
183
+ fs.writeFileSync(tmp, JSON.stringify(doc, null, 2), 'utf8');
184
+ fs.renameSync(tmp, p); // 原子替换,避免半写
185
+ // 写归属会改变反向索引(ownersOf),整体失效缓存,下次读取重新扫描
186
+ this.cache.clear();
187
+ this.cacheAt = 0;
188
+ }
189
+ catch (err) {
190
+ this.logger.warn(`[recall-rebuild] 写用户归属失败(${file}): ${err instanceof Error ? err.message : String(err)}`);
191
+ }
192
+ }
193
+ }
package/dist/recall.d.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  import type { Context } from '@deepseek-ai/cordis';
16
16
  import type { RecallRebuildConfig } from './config.js';
17
17
  import type { LoggerLike, MemoryStore } from './store.js';
18
+ import { type NamespaceStore } from './namespace.js';
18
19
  interface MsgLike {
19
20
  source?: {
20
21
  kind?: string;
@@ -25,5 +26,5 @@ interface MsgLike {
25
26
  }
26
27
  /** 判断一条消息是否为其它插件(prime-memory 等)注入的原文召回。 */
27
28
  export declare function isOtherPluginRecall(m: MsgLike): boolean;
28
- export declare function registerRecallRebuild(ctx: Context, store: MemoryStore, cfg: RecallRebuildConfig, logger: LoggerLike): void;
29
+ export declare function registerRecallRebuild(ctx: Context, store: MemoryStore, cfg: RecallRebuildConfig, logger: LoggerLike, namespaces?: NamespaceStore): void;
29
30
  export {};
package/dist/recall.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
2
2
  import { rebuildMemory } from './rebuild.js';
3
+ import { extractUserKey } from './namespace.js';
3
4
  /** 消息文本提取(text 块拼接),用于召回查询。 */
4
5
  function blocksToText(content) {
5
6
  if (!Array.isArray(content))
@@ -63,7 +64,7 @@ function buildInjectionMessage(text, sourceIds, cfg) {
63
64
  source,
64
65
  });
65
66
  }
66
- export function registerRecallRebuild(ctx, store, cfg, logger) {
67
+ export function registerRecallRebuild(ctx, store, cfg, logger, namespaces) {
67
68
  if (!cfg.enabled)
68
69
  return;
69
70
  const emitter = ctx;
@@ -81,9 +82,21 @@ export function registerRecallRebuild(ctx, store, cfg, logger) {
81
82
  const query = buildRecallQuery(payload.messages, cfg);
82
83
  if (!query)
83
84
  return decision;
84
- const memories = store.search(query, cfg.rebuild.maxResults);
85
+ // 提取当前 IM 用户键(桌面/无法识别 → null → 不做隔离)
86
+ const userKey = namespaces
87
+ ? extractUserKey(decision.messages.map(blocksToText), cfg.user.sourceTagPattern)
88
+ : null;
89
+ let memories = store.search(query, cfg.rebuild.maxResults);
85
90
  if (memories.length === 0)
86
91
  return decision;
92
+ // 用户级命名空间隔离:过滤"明确属于其他用户"的记忆
93
+ if (namespaces) {
94
+ memories = namespaces.filter(memories, userKey, cfg.user.isolation);
95
+ if (memories.length === 0)
96
+ return decision;
97
+ // 只把"本轮实际保留"的候选记为当前用户归属(无主记忆随命中归位)
98
+ namespaces.recordHits(userKey, memories);
99
+ }
87
100
  const rebuilt = await rebuildMemory(ctx, memories, query, cfg.rebuild, payload.signal, logger);
88
101
  if (!rebuilt || !rebuilt.text)
89
102
  return decision;
package/dist/store.d.ts CHANGED
@@ -32,8 +32,13 @@ export declare function sanitizeFts(query: string): string;
32
32
  export declare function openPrimeMemoryStore(dataDir: string, logger: LoggerLike): MemoryStore;
33
33
  /** 打开 dsh-memory-palace 的只读记忆源(cwd = DSH 工作目录,用于定位工作区记忆)。 */
34
34
  export declare function openPalaceStore(cwd: string, logger: LoggerLike): MemoryStore;
35
- /** 记忆来源路由:auto 探测 prime → palace,或按 source 显式指定。 */
36
- export declare function openMemorySource(source: 'auto' | 'prime' | 'palace', opts: {
35
+ /**
36
+ * 打开 @max-null/dsh-memory 的只读记忆源。
37
+ * @param cwd DSH 工作目录(用于定位 project 记忆)
38
+ */
39
+ export declare function openDshMemoryStore(cwd: string, logger: LoggerLike): MemoryStore;
40
+ /** 记忆来源路由:auto 探测 prime → dsh-memory → palace,或按 source 显式指定。 */
41
+ export declare function openMemorySource(source: 'auto' | 'prime' | 'dsh-memory' | 'palace', opts: {
37
42
  dataDir: string;
38
43
  cwd: string;
39
44
  logger: LoggerLike;
package/dist/store.js CHANGED
@@ -284,23 +284,146 @@ export function openPalaceStore(cwd, logger) {
284
284
  },
285
285
  };
286
286
  }
287
- /** 记忆来源路由:auto 探测 prime → palace,或按 source 显式指定。 */
287
+ /** epoch ms → 本地时区 YYYY-MM-DD;非法值返回空串。 */
288
+ function epochToDate(ms) {
289
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0)
290
+ return '';
291
+ const d = new Date(ms);
292
+ const mm = String(d.getMonth() + 1).padStart(2, '0');
293
+ const dd = String(d.getDate()).padStart(2, '0');
294
+ return `${d.getFullYear()}-${mm}-${dd}`;
295
+ }
296
+ /** 解析单个 dsh-memory JSON 库文件为生效记录(只读;跳过 suggested/隔离/prompt/结构异常)。 */
297
+ function parseDshMemoryFile(file, rel) {
298
+ let doc;
299
+ try {
300
+ doc = JSON.parse(fs.readFileSync(file, 'utf8'));
301
+ }
302
+ catch {
303
+ return [];
304
+ }
305
+ const blocks = doc?.unit?.tables?.blocks;
306
+ if (!Array.isArray(blocks))
307
+ return [];
308
+ const out = [];
309
+ for (const raw of blocks) {
310
+ const b = raw;
311
+ if (!b || typeof b !== 'object')
312
+ continue;
313
+ if (b.status !== 'approved')
314
+ continue; // suggested 未生效
315
+ if (b.quarantined === true)
316
+ continue; // 隔离记录不进检索
317
+ if (b.kind === 'prompt')
318
+ continue; // 模板索引非用户记忆
319
+ const content = typeof b.content === 'string' ? b.content.trim() : '';
320
+ if (!content)
321
+ continue;
322
+ out.push({
323
+ id: typeof b.id === 'string' ? b.id : '',
324
+ content,
325
+ namespace: b.namespace === 'project' ? 'project' : 'global',
326
+ keywords: Array.isArray(b.keywords) ? b.keywords.filter((k) => typeof k === 'string') : [],
327
+ updatedAt: typeof b.updatedAt === 'number' ? b.updatedAt : 0,
328
+ rel,
329
+ });
330
+ }
331
+ return out;
332
+ }
333
+ /**
334
+ * 打开 @max-null/dsh-memory 的只读记忆源。
335
+ * @param cwd DSH 工作目录(用于定位 project 记忆)
336
+ */
337
+ export function openDshMemoryStore(cwd, logger) {
338
+ // global:join(DSH_HOME ?? ~/.dsh, 'storages', 'memory.json')
339
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
340
+ const globalFile = path.join(home, 'storages', 'memory.json');
341
+ // project:<cwd>/.dsh/storages/*.json(每个 backend 一个文件)
342
+ const projectDir = path.join(cwd, '.dsh', 'storages');
343
+ const entries = [];
344
+ if (fs.existsSync(globalFile)) {
345
+ entries.push(...parseDshMemoryFile(globalFile, '<DSH_HOME>/storages/memory.json'));
346
+ }
347
+ let projectNames = [];
348
+ try {
349
+ projectNames = fs.readdirSync(projectDir).filter((n) => n.endsWith('.json'));
350
+ }
351
+ catch {
352
+ /* 无 project 记忆 */
353
+ }
354
+ for (const n of projectNames) {
355
+ if (n === 'query-log.json')
356
+ continue; // 查询日志非记忆库
357
+ const f = path.join(projectDir, n);
358
+ entries.push(...parseDshMemoryFile(f, `<cwd>/.dsh/storages/${n}`));
359
+ }
360
+ if (entries.length === 0) {
361
+ logger.warn(`[recall-rebuild] 未找到 dsh-memory 记忆文件(检查 <DSH_HOME>/storages/memory.json 或 ` +
362
+ `<cwd>/.dsh/storages/*.json),记忆读取停用`);
363
+ return disabledStore('未找到 dsh-memory 记忆文件');
364
+ }
365
+ const sources = [...new Set(entries.map((e) => e.rel))];
366
+ return {
367
+ ok: true,
368
+ label: `@max-null/dsh-memory (${sources.join(', ')})`,
369
+ search(query, limit) {
370
+ const words = tokenizeQuery(query);
371
+ if (words.length === 0)
372
+ return [];
373
+ const scored = [];
374
+ for (const e of entries) {
375
+ const cNorm = palaceNorm(e.content);
376
+ let hits = 0;
377
+ for (const w of words) {
378
+ if (cNorm.includes(w))
379
+ hits += 1;
380
+ // keywords 命中更精准,权重 ×2
381
+ for (const k of e.keywords)
382
+ if (palaceNorm(k).includes(w))
383
+ hits += 2;
384
+ }
385
+ if (hits > 0)
386
+ scored.push({ e, hits });
387
+ }
388
+ // 命中权重优先,其次更新时间倒序(最近优先)
389
+ scored.sort((a, b) => b.hits - a.hits || (a.e.updatedAt < b.e.updatedAt ? 1 : a.e.updatedAt > b.e.updatedAt ? -1 : 0));
390
+ return scored.slice(0, limit).map(({ e, hits }) => ({
391
+ id: `${e.rel}#${e.id}`,
392
+ content: e.content,
393
+ type: 'dsh-memory',
394
+ sceneName: e.namespace === 'project' ? 'project 记忆' : 'global 记忆',
395
+ family: e.rel,
396
+ priority: hits,
397
+ timestampStr: epochToDate(e.updatedAt),
398
+ }));
399
+ },
400
+ close() {
401
+ /* 无资源 */
402
+ },
403
+ };
404
+ }
405
+ /** 记忆来源路由:auto 探测 prime → dsh-memory → palace,或按 source 显式指定。 */
288
406
  export function openMemorySource(source, opts) {
289
407
  const { dataDir, cwd, logger } = opts;
290
408
  if (source === 'prime')
291
409
  return openPrimeMemoryStore(dataDir, logger);
410
+ if (source === 'dsh-memory')
411
+ return openDshMemoryStore(cwd, logger);
292
412
  if (source === 'palace')
293
413
  return openPalaceStore(cwd, logger);
294
- // auto:prime-memory 库存在则优先(打开失败再落 palace),否则尝试 palace
414
+ // auto:prime-memory 库存在则优先(打开失败依次落 dsh-memory / palace),否则尝试后两者
295
415
  const primeDb = path.join(dataDir, 'memory.db');
296
416
  if (fs.existsSync(primeDb)) {
297
417
  const s = openPrimeMemoryStore(dataDir, logger);
298
418
  if (s.ok)
299
419
  return s;
300
- logger.warn(`[recall-rebuild] prime-memory 库存在但打不开,尝试 memory-palace 记忆源`);
420
+ logger.warn(`[recall-rebuild] prime-memory 库存在但打不开,尝试 dsh-memory / memory-palace 记忆源`);
301
421
  }
422
+ const dm = openDshMemoryStore(cwd, logger);
423
+ if (dm.ok)
424
+ return dm;
302
425
  const p = openPalaceStore(cwd, logger);
303
426
  if (p.ok)
304
427
  return p;
305
- return disabledStore('未检测到 prime-memory 或 memory-palace 记忆库');
428
+ return disabledStore('未检测到 prime-memory / dsh-memory / memory-palace 记忆库');
306
429
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-recall-rebuild",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "access": "public",