dsh-recall-rebuild 0.1.2 → 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
@@ -31,6 +31,7 @@
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
  - **永不阻塞对话**:无记忆库/无模型路由/超时/重建失败,一律静默跳过本轮;
@@ -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
  ## 安装
@@ -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
82
  Q --> S[("记忆库<br/>prime(SQLite)/ dsh-memory(JSON)/ palace(Markdown)")]
81
- S --> R["LLM 重建式回忆<br/>(碎片 → 带语境的回忆片段)"]
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
 
@@ -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
127
  - [ ] 更多记忆源 adapter(`dsh-memory-vault`、`dsh-auto-memory`、`dsh-memory-gate` 等变体);
120
- - [ ] IM 用户级命名空间隔离(跨 QQ/微信的同一人记忆共享);
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
 
@@ -152,6 +162,7 @@ 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;
@@ -57,6 +72,7 @@ export interface RecallRebuildConfig {
57
72
  rebuild: RebuildOptions;
58
73
  inject: InjectOptions;
59
74
  query: QueryOptions;
75
+ user: UserIsolationOptions;
60
76
  }
61
77
  export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
62
78
  enabled: Schema<boolean, boolean, "defined">;
@@ -97,6 +113,15 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
97
113
  tailMessages: Schema<number, number, "defined">;
98
114
  maxChars: Schema<number, number, "defined">;
99
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">;
100
125
  }>>, Schemastery.ObjectT<NoInfer<{
101
126
  enabled: Schema<boolean, boolean, "defined">;
102
127
  dataDir: Schema<string, string, "defined">;
@@ -136,4 +161,13 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
136
161
  tailMessages: Schema<number, number, "defined">;
137
162
  maxChars: Schema<number, number, "defined">;
138
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">;
139
173
  }>>, "defined">;
package/dist/config.js CHANGED
@@ -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
@@ -41,6 +41,15 @@ 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">;
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-recall-rebuild",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "access": "public",