dsh-recall-rebuild 0.1.2 → 0.1.4
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 +38 -9
- package/dist/config.d.ts +68 -0
- package/dist/config.js +11 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +53 -2
- package/dist/namespace.d.ts +31 -0
- package/dist/namespace.js +193 -0
- package/dist/observability.d.ts +69 -0
- package/dist/observability.js +119 -0
- package/dist/recall.d.ts +3 -1
- package/dist/recall.js +44 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,16 +31,18 @@
|
|
|
31
31
|
|
|
32
32
|
- **只读增强,零污染**:以 `readOnly` 打开现有记忆库(`$DSH_HOME/memory/memory.db`),不重写捕获管线、不写任何数据,装/卸都不影响原插件;
|
|
33
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
|
- **永不阻塞对话**:无记忆库/无模型路由/超时/重建失败,一律静默跳过本轮;
|
|
38
|
+
- **重建质量可观测**:每轮在 `~/.dsh/recall-rebuild/logs/recall-YYYY-MM-DD.log` 写一条 JSONL 审计日志,「原始检索碎片 ↔ 重建后片段」同屏对比 + 注入方式/耗时/跳过原因,附带 `stats.json` 统计——零额外注入、零 token 成本,自己判断重建效果;
|
|
37
39
|
- **零部署硬件成本**:不买显卡、不租 GPU,重建调用走宿主已有的 LLM 路由,每轮只消耗百级 token;
|
|
38
40
|
- **零额外运行时依赖**:用 Node 22+ 内置 `node:sqlite` 读库,安装即用。
|
|
39
41
|
|
|
40
42
|
## 适合谁
|
|
41
43
|
|
|
42
44
|
- DSH **桌宠 / 虚拟角色 / 陪伴型 AI** 玩家——想要"像人一样记着你",而不是"查到你的档案";
|
|
43
|
-
- 已把角色接入 **QQ / 微信** 等 IM 的 DSH
|
|
45
|
+
- 已把角色接入 **QQ / 微信** 等 IM 的 DSH 用户——角色同时服务多个人的私聊/群聊时,希望**每个用户的记忆互不串味**,同一人跨会话记忆共享;
|
|
44
46
|
- 觉得现有记忆插件"注入的原文太生硬、像在念记录"的开发者与用户。
|
|
45
47
|
|
|
46
48
|
## 安装
|
|
@@ -75,18 +77,22 @@ dsh plugin --profile <你的配置文件名> add dsh-recall-rebuild
|
|
|
75
77
|
|
|
76
78
|
```mermaid
|
|
77
79
|
flowchart LR
|
|
78
|
-
U["
|
|
80
|
+
U["IM 用户新消息<br/>(带 <dsh_im_source> sender)"] --> P["agent/pre-step<br/>(本插件 prepend)"]
|
|
81
|
+
P --> K["提取当前用户键<br/>(senderId / chatId)"]
|
|
79
82
|
P --> Q["构造召回查询<br/>(会话末尾消息)"]
|
|
80
83
|
Q --> S[("记忆库<br/>prime(SQLite)/ dsh-memory(JSON)/ palace(Markdown)")]
|
|
81
|
-
S -->
|
|
84
|
+
S --> F["用户命名空间过滤<br/>(auto/strict/off)"]
|
|
85
|
+
F --> R["LLM 重建式回忆<br/>(碎片 → 带语境的回忆片段)"]
|
|
82
86
|
R --> I["注入回忆片段<br/>source.kind = plugin:recall-rebuild"]
|
|
87
|
+
F --> N[("归属索引<br/>~/.dsh/recall-rebuild/namespaces")]
|
|
88
|
+
F -. 命中候选归属当前用户 .-> N
|
|
83
89
|
P --> M["模型推理"]
|
|
84
90
|
I --> M
|
|
85
91
|
M --> A["回复"]
|
|
86
92
|
R -. "失败/超时 → 静默跳过" .-> M
|
|
87
93
|
```
|
|
88
94
|
|
|
89
|
-
|
|
95
|
+
一句话流程:**提取用户 → 检索 → 用户隔离过滤 → 重建 → 注入**,而不是**检索 → 注入**。
|
|
90
96
|
|
|
91
97
|
## 与现有插件的错开与共存
|
|
92
98
|
|
|
@@ -113,20 +119,41 @@ flowchart LR
|
|
|
113
119
|
| `inject.includeSources` | `true` | 注入时附记忆来源 id 标注 |
|
|
114
120
|
| `query.tailMessages` | `8` | 召回查询取会话末尾消息条数 |
|
|
115
121
|
| `query.maxChars` | `1200` | 召回查询字符上限 |
|
|
122
|
+
| `user.isolation` | `auto` | IM 用户隔离模式:`auto` 剔除「明确属于其他用户」的记忆(无主记忆默认可见,命中后归位);`strict` 只注入「已归属当前用户」的记忆(新用户零记忆起步);`off` 不过滤。桌面直接对话自动不隔离 |
|
|
123
|
+
| `user.isolationDir` | `''` | 归属索引目录;空 = `<DSH_HOME>/recall-rebuild/namespaces` |
|
|
124
|
+
| `user.sourceTagPattern` | `''` | 覆盖内置 `<dsh_im_source>` 解析正则;不同桥接插件字段不同时可自定义(需含一个捕获组取用户 id) |
|
|
125
|
+
| `observability.logEnabled` | `true` | 每轮重建审计日志开关(JSON Lines,按天滚动) |
|
|
126
|
+
| `observability.logDir` | `''` | 日志目录;空 = `<DSH_HOME>/recall-rebuild/logs` |
|
|
127
|
+
| `observability.includeFragments` | `true` | 日志是否记录原始检索碎片(与重建片段同屏对比);`false` 只记重建结果 |
|
|
128
|
+
| `observability.statsEnabled` | `true` | 是否写统计文件 `stats.json`(30s 节流) |
|
|
129
|
+
|
|
130
|
+
## 观测:怎么判断重建是否真的更好
|
|
131
|
+
|
|
132
|
+
每轮运行后,打开日志目录(`~/.dsh/recall-rebuild/logs/`):
|
|
133
|
+
|
|
134
|
+
- **`recall-YYYY-MM-DD.log`**:每轮一行 JSON,同一轮里 `fragments`(原始检索碎片)与 `rebuilt`(重建后片段)并排——直接对比同一份记忆的两种呈现,自己判断哪种更"像人";
|
|
135
|
+
- **`stats.json`**:累计轮数 / 命中轮 / 重建成功 / 注入 / 替换数,看重建的覆盖面和替换率。
|
|
136
|
+
|
|
137
|
+
字段速览:`round` 轮次、`userKey` 当前 IM 用户、`hitCount` 命中数、`memoryIds` 依据记忆 id、`fragments` 原始碎片、`rebuilt` 重建片段、`injection` 注入方式(`replaced` 替换了对方原文召回 / `appended` 追加 / `none` 未注入)、`latencyMs` 耗时、`error` 跳过原因。
|
|
138
|
+
|
|
139
|
+
> 想运行时真·对比(同一轮同时看到原文召回与重建片段),把 `inject.strategy` 设为 `append`;想零成本对比,看日志即可。
|
|
116
140
|
|
|
117
141
|
## Roadmap
|
|
118
142
|
|
|
119
143
|
- [ ] 更多记忆源 adapter(`dsh-memory-vault`、`dsh-auto-memory`、`dsh-memory-gate` 等变体);
|
|
120
|
-
- [
|
|
121
|
-
- [
|
|
144
|
+
- [x] IM 用户级命名空间隔离(跨 QQ/微信的同一人记忆共享)—— v0.1.3 已实现;
|
|
145
|
+
- [x] 重建质量可观测(每轮 JSONL 日志 + stats)—— v0.1.4 已实现;
|
|
122
146
|
- [ ] 睡眠巩固 / 联想扩散(更接近人脑的长期记忆子系统的后续阶段)。
|
|
123
147
|
|
|
124
148
|
## 局限(如实声明)
|
|
125
149
|
|
|
126
150
|
1. **只增强召回/呈现层**:底层库捕获了什么,重建就基于什么;库缺字段(如没有情绪标注)时,重建不会凭空造出它。
|
|
127
|
-
2.
|
|
128
|
-
3.
|
|
129
|
-
4.
|
|
151
|
+
2. **用户隔离是观察式启发式,非底层强隔离**:底层记忆库(prime 等)没有 IM 用户字段,本插件靠「谁在会话中命中过这条记忆,它就归谁」建立归属。因此:`auto` 模式防得住「已明确归属他人」的记忆,防不住「从未被命中过的无主记忆」(它们默认可见,命中后归位);`strict` 模式从零记忆起步,聊过的话题才开始归位。需要强隐私隔离且不介意冷启动时用 `strict`。
|
|
152
|
+
3. **用户识别依赖桥接插件约定**:优先解析 `<dsh_im_source>` JSON(senderId/chatId/threadId/botId),兜底常见字段(senderId/userId/openid/fromUser);不同桥接字段不同时用 `user.sourceTagPattern` 覆盖。识别不到用户(桌面会话)时不做隔离。
|
|
153
|
+
4. **幻觉受控但非零**:重建 prompt 明确禁止编造碎片外事实,但 LLM 仍有漂移概率;注入标注记忆依据 id 便于审计。需要强事实的场景可关掉重建(`rebuild.enabled=false`)。
|
|
154
|
+
5. **token 消耗**:每轮召回命中即产生一次重建调用(通常百级 token),由宿主模型路由计费。
|
|
155
|
+
6. **日志零成本但非自动诊断**:日志只记录事实(碎片/重建/耗时/跳过原因),不做好坏判定;用户可对比判断,或切换 `inject.strategy=append` 运行时对比。
|
|
156
|
+
7. **未覆盖**:LoRA 权重内化等权重级记忆不在本插件范围(见 Roadmap)。
|
|
130
157
|
|
|
131
158
|
## 开发与验证
|
|
132
159
|
|
|
@@ -152,8 +179,10 @@ This plugin upgrades the **recall/presentation layer**:
|
|
|
152
179
|
|
|
153
180
|
- Opens the existing memory store (`$DSH_HOME/memory/memory.db`) **read-only**, never writes, never touches the capture pipeline;
|
|
154
181
|
- 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);
|
|
182
|
+
- **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
183
|
- 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
184
|
- **Never blocks a conversation**: missing store, missing model route, timeout or rebuild failure all silently skip the step;
|
|
185
|
+
- **Observable rebuild quality**: every round appends one JSONL audit line to `~/.dsh/recall-rebuild/logs/recall-YYYY-MM-DD.log` — raw fragments vs rebuilt snippet side by side, injection mode / latency / skip reason, plus a throttled `stats.json` — zero extra injection, zero token cost, so you can judge for yourself whether rebuilding beats raw recall;
|
|
157
186
|
- **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`.
|
|
158
187
|
|
|
159
188
|
**Who it's for**: DSH desktop-pet / virtual-character / companion users who want the bot to "remember like a person" rather than "quote a file", including characters bridged to QQ/WeChat.
|
package/dist/config.d.ts
CHANGED
|
@@ -41,6 +41,32 @@ 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
|
+
}
|
|
59
|
+
/** 重建质量可观测选项。 */
|
|
60
|
+
export interface ObservabilityOptions {
|
|
61
|
+
/** 每轮重建审计日志开关(JSON Lines,按天滚动)。 */
|
|
62
|
+
logEnabled: boolean;
|
|
63
|
+
/** 日志目录;空 = <DSH_HOME>/recall-rebuild/logs。 */
|
|
64
|
+
logDir: string;
|
|
65
|
+
/** 日志是否记录原始检索碎片(与重建片段同屏对比);false 只记重建结果。 */
|
|
66
|
+
includeFragments: boolean;
|
|
67
|
+
/** 是否写统计文件 stats.json(30s 节流)。 */
|
|
68
|
+
statsEnabled: boolean;
|
|
69
|
+
}
|
|
44
70
|
export interface RecallRebuildConfig {
|
|
45
71
|
/** 总开关。 */
|
|
46
72
|
enabled: boolean;
|
|
@@ -57,6 +83,8 @@ export interface RecallRebuildConfig {
|
|
|
57
83
|
rebuild: RebuildOptions;
|
|
58
84
|
inject: InjectOptions;
|
|
59
85
|
query: QueryOptions;
|
|
86
|
+
user: UserIsolationOptions;
|
|
87
|
+
observability: ObservabilityOptions;
|
|
60
88
|
}
|
|
61
89
|
export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
62
90
|
enabled: Schema<boolean, boolean, "defined">;
|
|
@@ -97,6 +125,26 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
97
125
|
tailMessages: Schema<number, number, "defined">;
|
|
98
126
|
maxChars: Schema<number, number, "defined">;
|
|
99
127
|
}>>, "defined">;
|
|
128
|
+
user: Schema<Schemastery.ObjectS<NoInfer<{
|
|
129
|
+
isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
|
|
130
|
+
isolationDir: Schema<string, string, "defined">;
|
|
131
|
+
sourceTagPattern: Schema<string, string, "defined">;
|
|
132
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
133
|
+
isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
|
|
134
|
+
isolationDir: Schema<string, string, "defined">;
|
|
135
|
+
sourceTagPattern: Schema<string, string, "defined">;
|
|
136
|
+
}>>, "defined">;
|
|
137
|
+
observability: Schema<Schemastery.ObjectS<NoInfer<{
|
|
138
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
139
|
+
logDir: Schema<string, string, "defined">;
|
|
140
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
141
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
142
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
143
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
144
|
+
logDir: Schema<string, string, "defined">;
|
|
145
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
146
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
147
|
+
}>>, "defined">;
|
|
100
148
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
101
149
|
enabled: Schema<boolean, boolean, "defined">;
|
|
102
150
|
dataDir: Schema<string, string, "defined">;
|
|
@@ -136,4 +184,24 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
136
184
|
tailMessages: Schema<number, number, "defined">;
|
|
137
185
|
maxChars: Schema<number, number, "defined">;
|
|
138
186
|
}>>, "defined">;
|
|
187
|
+
user: Schema<Schemastery.ObjectS<NoInfer<{
|
|
188
|
+
isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
|
|
189
|
+
isolationDir: Schema<string, string, "defined">;
|
|
190
|
+
sourceTagPattern: Schema<string, string, "defined">;
|
|
191
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
192
|
+
isolation: Schema<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
|
|
193
|
+
isolationDir: Schema<string, string, "defined">;
|
|
194
|
+
sourceTagPattern: Schema<string, string, "defined">;
|
|
195
|
+
}>>, "defined">;
|
|
196
|
+
observability: Schema<Schemastery.ObjectS<NoInfer<{
|
|
197
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
198
|
+
logDir: Schema<string, string, "defined">;
|
|
199
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
200
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
201
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
202
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
203
|
+
logDir: Schema<string, string, "defined">;
|
|
204
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
205
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
206
|
+
}>>, "defined">;
|
|
139
207
|
}>>, "defined">;
|
package/dist/config.js
CHANGED
|
@@ -29,4 +29,15 @@ 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({}),
|
|
37
|
+
observability: Schema.object({
|
|
38
|
+
logEnabled: Schema.boolean().default(true),
|
|
39
|
+
logDir: Schema.string().default(''),
|
|
40
|
+
includeFragments: Schema.boolean().default(true),
|
|
41
|
+
statsEnabled: Schema.boolean().default(true),
|
|
42
|
+
}).default({}),
|
|
32
43
|
}).default({});
|
package/dist/index.d.ts
CHANGED
|
@@ -41,6 +41,26 @@ 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">;
|
|
53
|
+
observability: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
|
|
54
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
55
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
56
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
57
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
58
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
59
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
60
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
61
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
62
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
63
|
+
}>>, "defined">;
|
|
44
64
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
45
65
|
enabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
46
66
|
dataDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
@@ -80,5 +100,25 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
|
|
|
80
100
|
tailMessages: import("@deepseek-ai/schemastery").default<number, number, "defined">;
|
|
81
101
|
maxChars: import("@deepseek-ai/schemastery").default<number, number, "defined">;
|
|
82
102
|
}>>, "defined">;
|
|
103
|
+
user: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
|
|
104
|
+
isolation: import("@deepseek-ai/schemastery").default<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
|
|
105
|
+
isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
106
|
+
sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
107
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
108
|
+
isolation: import("@deepseek-ai/schemastery").default<"off" | "auto" | "strict", "off" | "auto" | "strict", "defined">;
|
|
109
|
+
isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
110
|
+
sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
111
|
+
}>>, "defined">;
|
|
112
|
+
observability: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
|
|
113
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
114
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
115
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
116
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
117
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
118
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
119
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
120
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
121
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
122
|
+
}>>, "defined">;
|
|
83
123
|
}>>, "defined">;
|
|
84
124
|
export declare function apply(ctx: Context, config: RecallRebuildConfig): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -12,6 +12,8 @@ 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';
|
|
16
|
+
import { RebuildLogger } from './observability.js';
|
|
15
17
|
export const name = 'recall-rebuild';
|
|
16
18
|
export const inject = ['llm'];
|
|
17
19
|
export const Config = recallRebuildSchema;
|
|
@@ -33,6 +35,44 @@ function resolveDataDir(config, logger) {
|
|
|
33
35
|
}
|
|
34
36
|
return fallback;
|
|
35
37
|
}
|
|
38
|
+
/** 用户隔离归属目录:<DSH_HOME>/recall-rebuild/namespaces(缺省 ~/.dsh/recall-rebuild/namespaces)。 */
|
|
39
|
+
function resolveIsolationDir(config, logger) {
|
|
40
|
+
if (config.user.isolationDir)
|
|
41
|
+
return config.user.isolationDir;
|
|
42
|
+
try {
|
|
43
|
+
const home = dshHomePath();
|
|
44
|
+
if (home)
|
|
45
|
+
return path.join(home, 'recall-rebuild', 'namespaces');
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
/* 落到兜底 */
|
|
49
|
+
}
|
|
50
|
+
const base = process.env.HOME || process.env.USERPROFILE || '';
|
|
51
|
+
const fallback = base ? path.join(base, '.dsh', 'recall-rebuild', 'namespaces') : '';
|
|
52
|
+
if (!fallback) {
|
|
53
|
+
logger.warn(`[recall-rebuild] 无法确定用户隔离目录,请在 config.user.isolationDir 显式指定`);
|
|
54
|
+
}
|
|
55
|
+
return fallback;
|
|
56
|
+
}
|
|
57
|
+
/** 重建日志目录:<DSH_HOME>/recall-rebuild/logs(缺省 ~/.dsh/recall-rebuild/logs)。 */
|
|
58
|
+
function resolveLogDir(config, logger) {
|
|
59
|
+
if (config.observability.logDir)
|
|
60
|
+
return config.observability.logDir;
|
|
61
|
+
try {
|
|
62
|
+
const home = dshHomePath();
|
|
63
|
+
if (home)
|
|
64
|
+
return path.join(home, 'recall-rebuild', 'logs');
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
/* 落到兜底 */
|
|
68
|
+
}
|
|
69
|
+
const base = process.env.HOME || process.env.USERPROFILE || '';
|
|
70
|
+
const fallback = base ? path.join(base, '.dsh', 'recall-rebuild', 'logs') : '';
|
|
71
|
+
if (!fallback) {
|
|
72
|
+
logger.warn(`[recall-rebuild] 无法确定日志目录,请在 config.observability.logDir 显式指定`);
|
|
73
|
+
}
|
|
74
|
+
return fallback;
|
|
75
|
+
}
|
|
36
76
|
export async function apply(ctx, config) {
|
|
37
77
|
const logger = ctx.logger;
|
|
38
78
|
const dataDir = resolveDataDir(config, logger);
|
|
@@ -41,6 +81,16 @@ export async function apply(ctx, config) {
|
|
|
41
81
|
// 可插拔记忆源:prime(SQLite FTS5)| palace(Markdown 文件)| auto(自动探测)
|
|
42
82
|
const store = openMemorySource(config.source, { dataDir, cwd, logger });
|
|
43
83
|
ctx.effect(() => () => store.close());
|
|
84
|
+
// IM 用户级命名空间隔离(自己的目录,绝不写底层记忆库)
|
|
85
|
+
const namespaces = new NamespaceStore(resolveIsolationDir(config, logger), logger);
|
|
86
|
+
namespaces.ensureDir();
|
|
87
|
+
// 重建质量可观测:每轮 JSONL 日志 + 统计(自己的目录)
|
|
88
|
+
const obsLog = new RebuildLogger({
|
|
89
|
+
logDir: resolveLogDir(config, logger),
|
|
90
|
+
enabled: config.observability.logEnabled,
|
|
91
|
+
includeFragments: config.observability.includeFragments,
|
|
92
|
+
logger,
|
|
93
|
+
});
|
|
44
94
|
if (store.ok) {
|
|
45
95
|
logger.info(`[recall-rebuild] 已只读挂载记忆库: ${store.label}`);
|
|
46
96
|
}
|
|
@@ -48,7 +98,8 @@ export async function apply(ctx, config) {
|
|
|
48
98
|
logger.warn(`[recall-rebuild] 记忆库不可用(${store.label}),插件按只观察模式运行(不注入)。` +
|
|
49
99
|
`请先安装并运行 dsh-prime-memory / dsh-memory-palace,或确认 config.dataDir / cwd 正确`);
|
|
50
100
|
}
|
|
51
|
-
registerRecallRebuild(ctx, store, config, logger);
|
|
101
|
+
registerRecallRebuild(ctx, store, config, logger, namespaces, obsLog);
|
|
52
102
|
logger.info(`[recall-rebuild] 重建式回忆增强就绪 ` +
|
|
53
|
-
`(rebuild=${config.rebuild.enabled}, inject=${config.inject.strategy}, source=${config.source}
|
|
103
|
+
`(rebuild=${config.rebuild.enabled}, inject=${config.inject.strategy}, source=${config.source}, ` +
|
|
104
|
+
`isolation=${config.user.isolation}, log=${config.observability.logEnabled})`);
|
|
54
105
|
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { LoggerLike } from './store.js';
|
|
2
|
+
export interface RebuildLogEntry {
|
|
3
|
+
ts: string;
|
|
4
|
+
round: number;
|
|
5
|
+
userKey: string | null;
|
|
6
|
+
isolation: string;
|
|
7
|
+
query: string;
|
|
8
|
+
hitCount: number;
|
|
9
|
+
memoryIds: string[];
|
|
10
|
+
fragments: string[];
|
|
11
|
+
rebuilt: string;
|
|
12
|
+
rebuiltChars: number;
|
|
13
|
+
injection: 'replaced' | 'appended' | 'none';
|
|
14
|
+
latencyMs: number;
|
|
15
|
+
error?: string;
|
|
16
|
+
}
|
|
17
|
+
interface Stats {
|
|
18
|
+
rounds: number;
|
|
19
|
+
hits: number;
|
|
20
|
+
rebuilt: number;
|
|
21
|
+
injected: number;
|
|
22
|
+
replaced: number;
|
|
23
|
+
errors: number;
|
|
24
|
+
lastRoundAt: string;
|
|
25
|
+
}
|
|
26
|
+
export declare class RebuildLogger {
|
|
27
|
+
private readonly logDir;
|
|
28
|
+
private readonly enabled;
|
|
29
|
+
private readonly includeFragments;
|
|
30
|
+
private readonly logger;
|
|
31
|
+
private roundNo;
|
|
32
|
+
private stats;
|
|
33
|
+
private lastStatsWrite;
|
|
34
|
+
private readonly statsIntervalMs;
|
|
35
|
+
constructor(opts: {
|
|
36
|
+
logDir: string;
|
|
37
|
+
enabled: boolean;
|
|
38
|
+
includeFragments: boolean;
|
|
39
|
+
logger: LoggerLike;
|
|
40
|
+
});
|
|
41
|
+
/** 当前轮日志文件名(按天滚动)。 */
|
|
42
|
+
private todayFile;
|
|
43
|
+
/**
|
|
44
|
+
* 记录一轮。
|
|
45
|
+
* @param partial 必填字段之外的内容;fragments 仅 includeFragments 时保留
|
|
46
|
+
*/
|
|
47
|
+
log(partial: {
|
|
48
|
+
userKey: string | null;
|
|
49
|
+
isolation: string;
|
|
50
|
+
query: string;
|
|
51
|
+
hitCount: number;
|
|
52
|
+
memoryIds: string[];
|
|
53
|
+
rebuilt: string;
|
|
54
|
+
injection: 'replaced' | 'appended' | 'none';
|
|
55
|
+
latencyMs: number;
|
|
56
|
+
error?: string;
|
|
57
|
+
fragments?: string[];
|
|
58
|
+
}): void;
|
|
59
|
+
/** 原子写 stats.json(节流外也可主动调用)。 */
|
|
60
|
+
flushStats(): void;
|
|
61
|
+
/** 当前累计统计(读给宿主用)。 */
|
|
62
|
+
snapshot(): Stats;
|
|
63
|
+
}
|
|
64
|
+
/** 给 verify 用的纯函数:从日志条目提取碎片对比段(原文 vs 重建)。 */
|
|
65
|
+
export declare function fragmentSample(entry: RebuildLogEntry): {
|
|
66
|
+
original: string[];
|
|
67
|
+
rebuilt: string;
|
|
68
|
+
};
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 重建质量可观测:每轮重建的完整审计日志 + 轻量统计。
|
|
3
|
+
*
|
|
4
|
+
* 目的:让用户直接看到「同一批记忆,原文检索碎片 ↔ 重建后片段」的差异,
|
|
5
|
+
* 自己判断重建式回忆是否真的更好(注入效果对比,零额外注入、零 token 成本)。
|
|
6
|
+
*
|
|
7
|
+
* 日志:按天滚动 JSON Lines(<logDir>/recall-YYYY-MM-DD.log),
|
|
8
|
+
* 每轮 pre-step 写一条;目录自动创建,写失败静默(不阻塞对话)。
|
|
9
|
+
* 统计:<logDir>/stats.json,内存累计 + 30s 节流原子写。
|
|
10
|
+
*/
|
|
11
|
+
import * as fs from 'node:fs';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
function truncate(s, max) {
|
|
14
|
+
if (!s)
|
|
15
|
+
return '';
|
|
16
|
+
return s.length > max ? `${s.slice(0, max)}…` : s;
|
|
17
|
+
}
|
|
18
|
+
export class RebuildLogger {
|
|
19
|
+
logDir;
|
|
20
|
+
enabled;
|
|
21
|
+
includeFragments;
|
|
22
|
+
logger;
|
|
23
|
+
roundNo = 0;
|
|
24
|
+
stats = {
|
|
25
|
+
rounds: 0,
|
|
26
|
+
hits: 0,
|
|
27
|
+
rebuilt: 0,
|
|
28
|
+
injected: 0,
|
|
29
|
+
replaced: 0,
|
|
30
|
+
errors: 0,
|
|
31
|
+
lastRoundAt: '',
|
|
32
|
+
};
|
|
33
|
+
lastStatsWrite = 0;
|
|
34
|
+
statsIntervalMs = 30_000;
|
|
35
|
+
constructor(opts) {
|
|
36
|
+
this.logDir = opts.logDir;
|
|
37
|
+
this.enabled = opts.enabled;
|
|
38
|
+
this.includeFragments = opts.includeFragments;
|
|
39
|
+
this.logger = opts.logger;
|
|
40
|
+
}
|
|
41
|
+
/** 当前轮日志文件名(按天滚动)。 */
|
|
42
|
+
todayFile() {
|
|
43
|
+
const d = new Date();
|
|
44
|
+
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
45
|
+
const dd = String(d.getDate()).padStart(2, '0');
|
|
46
|
+
return `recall-${d.getFullYear()}-${mm}-${dd}.log`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* 记录一轮。
|
|
50
|
+
* @param partial 必填字段之外的内容;fragments 仅 includeFragments 时保留
|
|
51
|
+
*/
|
|
52
|
+
log(partial) {
|
|
53
|
+
this.roundNo += 1;
|
|
54
|
+
this.stats.rounds += 1;
|
|
55
|
+
if (partial.hitCount > 0)
|
|
56
|
+
this.stats.hits += 1;
|
|
57
|
+
// rebuilt = 实际发生重建流程且成功的轮数(零命中/报错不计)
|
|
58
|
+
if (!partial.error && partial.hitCount > 0)
|
|
59
|
+
this.stats.rebuilt += 1;
|
|
60
|
+
if (partial.injection !== 'none')
|
|
61
|
+
this.stats.injected += 1;
|
|
62
|
+
if (partial.injection === 'replaced')
|
|
63
|
+
this.stats.replaced += 1;
|
|
64
|
+
if (partial.error)
|
|
65
|
+
this.stats.errors += 1;
|
|
66
|
+
this.stats.lastRoundAt = new Date().toISOString();
|
|
67
|
+
if (!this.enabled)
|
|
68
|
+
return;
|
|
69
|
+
const entry = {
|
|
70
|
+
ts: new Date().toISOString(),
|
|
71
|
+
round: this.roundNo,
|
|
72
|
+
userKey: partial.userKey,
|
|
73
|
+
isolation: partial.isolation,
|
|
74
|
+
query: truncate(partial.query, 300),
|
|
75
|
+
hitCount: partial.hitCount,
|
|
76
|
+
memoryIds: partial.memoryIds.slice(0, 10),
|
|
77
|
+
fragments: this.includeFragments
|
|
78
|
+
? (partial.fragments ?? []).slice(0, 5).map((f) => truncate(f, 200))
|
|
79
|
+
: [],
|
|
80
|
+
rebuilt: truncate(partial.rebuilt, 600),
|
|
81
|
+
rebuiltChars: partial.rebuilt.length,
|
|
82
|
+
injection: partial.injection,
|
|
83
|
+
latencyMs: partial.latencyMs,
|
|
84
|
+
...(partial.error ? { error: truncate(partial.error, 300) } : {}),
|
|
85
|
+
};
|
|
86
|
+
try {
|
|
87
|
+
fs.mkdirSync(this.logDir, { recursive: true });
|
|
88
|
+
fs.appendFileSync(path.join(this.logDir, this.todayFile()), `${JSON.stringify(entry)}\n`, 'utf8');
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
this.logger.warn(`[recall-rebuild] 写重建日志失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
92
|
+
}
|
|
93
|
+
// 统计节流落盘
|
|
94
|
+
if (Date.now() - this.lastStatsWrite > this.statsIntervalMs)
|
|
95
|
+
this.flushStats();
|
|
96
|
+
}
|
|
97
|
+
/** 原子写 stats.json(节流外也可主动调用)。 */
|
|
98
|
+
flushStats() {
|
|
99
|
+
this.lastStatsWrite = Date.now();
|
|
100
|
+
try {
|
|
101
|
+
fs.mkdirSync(this.logDir, { recursive: true });
|
|
102
|
+
const p = path.join(this.logDir, 'stats.json');
|
|
103
|
+
const tmp = `${p}.tmp`;
|
|
104
|
+
fs.writeFileSync(tmp, JSON.stringify(this.stats, null, 2), 'utf8');
|
|
105
|
+
fs.renameSync(tmp, p);
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
this.logger.warn(`[recall-rebuild] 写统计文件失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** 当前累计统计(读给宿主用)。 */
|
|
112
|
+
snapshot() {
|
|
113
|
+
return { ...this.stats };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** 给 verify 用的纯函数:从日志条目提取碎片对比段(原文 vs 重建)。 */
|
|
117
|
+
export function fragmentSample(entry) {
|
|
118
|
+
return { original: entry.fragments ?? [], rebuilt: entry.rebuilt };
|
|
119
|
+
}
|
package/dist/recall.d.ts
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
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';
|
|
19
|
+
import type { RebuildLogger } from './observability.js';
|
|
18
20
|
interface MsgLike {
|
|
19
21
|
source?: {
|
|
20
22
|
kind?: string;
|
|
@@ -25,5 +27,5 @@ interface MsgLike {
|
|
|
25
27
|
}
|
|
26
28
|
/** 判断一条消息是否为其它插件(prime-memory 等)注入的原文召回。 */
|
|
27
29
|
export declare function isOtherPluginRecall(m: MsgLike): boolean;
|
|
28
|
-
export declare function registerRecallRebuild(ctx: Context, store: MemoryStore, cfg: RecallRebuildConfig, logger: LoggerLike): void;
|
|
30
|
+
export declare function registerRecallRebuild(ctx: Context, store: MemoryStore, cfg: RecallRebuildConfig, logger: LoggerLike, namespaces?: NamespaceStore, obsLog?: RebuildLogger): void;
|
|
29
31
|
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, obsLog) {
|
|
67
68
|
if (!cfg.enabled)
|
|
68
69
|
return;
|
|
69
70
|
const emitter = ctx;
|
|
@@ -78,24 +79,63 @@ export function registerRecallRebuild(ctx, store, cfg, logger) {
|
|
|
78
79
|
if (!hasNewUser)
|
|
79
80
|
return decision;
|
|
80
81
|
try {
|
|
82
|
+
const startedAt = Date.now();
|
|
81
83
|
const query = buildRecallQuery(payload.messages, cfg);
|
|
82
84
|
if (!query)
|
|
83
85
|
return decision;
|
|
84
|
-
|
|
85
|
-
|
|
86
|
+
// 提取当前 IM 用户键(桌面/无法识别 → null → 不做隔离)
|
|
87
|
+
const userKey = namespaces
|
|
88
|
+
? extractUserKey(decision.messages.map(blocksToText), cfg.user.sourceTagPattern)
|
|
89
|
+
: null;
|
|
90
|
+
let memories = store.search(query, cfg.rebuild.maxResults);
|
|
91
|
+
const logBase = () => ({
|
|
92
|
+
userKey,
|
|
93
|
+
isolation: cfg.user.isolation,
|
|
94
|
+
query,
|
|
95
|
+
hitCount: memories.length,
|
|
96
|
+
memoryIds: memories.map((m) => m.id),
|
|
97
|
+
fragments: memories.map((m) => m.content),
|
|
98
|
+
rebuilt: '',
|
|
99
|
+
injection: 'none',
|
|
100
|
+
latencyMs: Date.now() - startedAt,
|
|
101
|
+
});
|
|
102
|
+
if (memories.length === 0) {
|
|
103
|
+
if (obsLog)
|
|
104
|
+
obsLog.log({ ...logBase() });
|
|
86
105
|
return decision;
|
|
106
|
+
}
|
|
107
|
+
// 用户级命名空间隔离:过滤"明确属于其他用户"的记忆
|
|
108
|
+
if (namespaces) {
|
|
109
|
+
memories = namespaces.filter(memories, userKey, cfg.user.isolation);
|
|
110
|
+
if (memories.length === 0) {
|
|
111
|
+
if (obsLog)
|
|
112
|
+
obsLog.log({ ...logBase(), error: '隔离过滤后无可用记忆' });
|
|
113
|
+
return decision;
|
|
114
|
+
}
|
|
115
|
+
// 只把"本轮实际保留"的候选记为当前用户归属(无主记忆随命中归位)
|
|
116
|
+
namespaces.recordHits(userKey, memories);
|
|
117
|
+
}
|
|
87
118
|
const rebuilt = await rebuildMemory(ctx, memories, query, cfg.rebuild, payload.signal, logger);
|
|
88
|
-
if (!rebuilt || !rebuilt.text)
|
|
119
|
+
if (!rebuilt || !rebuilt.text) {
|
|
120
|
+
if (obsLog)
|
|
121
|
+
obsLog.log({ ...logBase(), error: '重建返回空,跳过注入' });
|
|
89
122
|
return decision;
|
|
123
|
+
}
|
|
90
124
|
const injection = buildInjectionMessage(rebuilt.text, rebuilt.sourceIds, cfg);
|
|
125
|
+
let injectionKind = 'appended';
|
|
91
126
|
if (cfg.inject.strategy === 'replace') {
|
|
92
127
|
const idx = decision.messages.findIndex(isOtherPluginRecall);
|
|
93
128
|
if (idx >= 0) {
|
|
94
129
|
const msgs = [...decision.messages];
|
|
95
130
|
msgs[idx] = injection;
|
|
131
|
+
injectionKind = 'replaced';
|
|
132
|
+
if (obsLog)
|
|
133
|
+
obsLog.log({ ...logBase(), rebuilt: rebuilt.text, injection: injectionKind, latencyMs: Date.now() - startedAt });
|
|
96
134
|
return { kind: 'enter', messages: msgs };
|
|
97
135
|
}
|
|
98
136
|
}
|
|
137
|
+
if (obsLog)
|
|
138
|
+
obsLog.log({ ...logBase(), rebuilt: rebuilt.text, injection: injectionKind, latencyMs: Date.now() - startedAt });
|
|
99
139
|
return { kind: 'enter', messages: [injection, ...decision.messages] };
|
|
100
140
|
}
|
|
101
141
|
catch (err) {
|