dsh-cross-memory 0.2.12 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +55 -16
  2. package/docs/DETAIL.md +13 -10
  3. package/docs/DETAIL.zh.md +13 -10
  4. package/lib/backfill.js +32 -1
  5. package/lib/client.js +3 -3
  6. package/lib/consolidate.js +41 -39
  7. package/lib/dense.js +47 -15
  8. package/lib/extract.js +39 -11
  9. package/lib/gate.js +35 -19
  10. package/lib/index.js +221 -131
  11. package/lib/mcp.js +330 -0
  12. package/lib/notify.js +10 -5
  13. package/lib/persona.js +99 -1
  14. package/lib/raw-recall.js +18 -7
  15. package/lib/reflection.js +10 -1
  16. package/lib/state.js +19 -7
  17. package/lib/storage.js +11 -1
  18. package/lib/sync.js +36 -14
  19. package/lib/test/archive.test.js +19 -0
  20. package/lib/test/consolidate.test.js +48 -10
  21. package/lib/test/extract.test.js +30 -1
  22. package/lib/test/loops.test.js +3 -2
  23. package/lib/test/mcp.test.js +103 -0
  24. package/lib/test/notices.test.js +67 -0
  25. package/lib/test/persona.test.js +40 -1
  26. package/lib/test/recall.test.js +54 -1
  27. package/lib/test/reflection.test.js +60 -1
  28. package/lib/test/subagent-contract.test.js +18 -12
  29. package/lib/test/sync.test.js +4 -0
  30. package/lib/tool.js +4 -3
  31. package/lib/types/backfill.d.ts +5 -0
  32. package/lib/types/consolidate.d.ts +34 -51
  33. package/lib/types/dense.d.ts +7 -2
  34. package/lib/types/extract.d.ts +14 -0
  35. package/lib/types/gate.d.ts +4 -0
  36. package/lib/types/index.d.ts +10 -0
  37. package/lib/types/mcp.d.ts +184 -0
  38. package/lib/types/notify.d.ts +3 -2
  39. package/lib/types/persona.d.ts +17 -0
  40. package/lib/types/raw-recall.d.ts +1 -0
  41. package/lib/types/sync.d.ts +7 -5
  42. package/lib/types/test/mcp.test.d.ts +1 -0
  43. package/package.json +14 -7
package/README.md CHANGED
@@ -9,6 +9,7 @@ dsh plugin --profile <profile> add dsh-cross-memory
9
9
 
10
10
  - **两种作用域**:`global`(所有项目共享)与 `project`(按工作区隔离)。
11
11
  - **三条协同路径**:模型可调用的 `memory` 工具、空闲时的后台抽取、有界的摘要注入与按需召回。
12
+ - **跨客户端共用**:内置零依赖 stdio MCP 服务(`dsh-cross-memory-mcp`),可供 Antigravity、Claude Code、Cursor、Codex、VS Code 等外部客户端共用同一 `$DSH_HOME/memories` 记忆库与画像。
12
13
  - **只写本机**:记忆库默认在 `$DSH_HOME/memories`,不上传任何服务;多机同步需要你自己配置一个 Git 仓库。
13
14
  - **可审计**:每条记忆带来源、时间与(自动抽取时的)会话证据;归档可恢复,不静默删除。
14
15
 
@@ -56,14 +57,15 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
56
57
  | 能力 | 说明 |
57
58
  | --- | --- |
58
59
  | 显式写入 | 模型调用 `memory` 工具写入/更新/检索/读取/遗忘;标题即身份,同名再写是更新。 |
59
- | 后台抽取 | 会话空闲或按周期被扫描,用一次辅助模型调用抽取可复用的事实;落盘前做密钥擦除。 |
60
- | 合并重整 | 受限子代理对一批记忆去重、改写、退役;有风险的决定进入「待裁决」由你决定。 |
61
- | 分层注入 | 每个会话注入一次有界摘要;另有按需补注(当前这轮明显相关时)、标题轮转与增量块。 |
62
- | 按需召回 | BM25 排序 + 词法证据门控 + 时间衰减 + 一跳扩展;命中原因可在日志里核对。 |
63
- | 原始片段(可选) | 补注块可附带来源会话的原文片段,默认关闭,因为它会把别的会话的原文带进当前上下文。 |
60
+ | 后台抽取 | 会话空闲或按周期扫描,用一次辅助模型调用抽取可复用事实;支持 `recordScope`(默认 `both`,可切 `work`)、巡检日报噪点过滤、自动关闭已完成开放承诺(`closedLoops`)、中英文密钥/口令擦除,以及追平会话短路与事件循环切片让出。 |
61
+ | 合并重整 | 受限子代理对一批记忆去重、改写、退役;已适配新版扁平 `SubagentActivationSpec` 并释放子激活、传入已有技能草稿防重名、对画像条目标去重,失败堆栈按 `warn` 级前 6 帧落盘;有风险的决定进入「待裁决」。 |
62
+ | 分层注入 | 每个会话注入一次有界摘要:合并排序后按 `project` 优先渲染,再渲染受限额约束的 `global` 段;另有按需补注、标题轮转与增量块。 |
63
+ | 按需召回 | BM25 词法排序 + 词法证据门控 + 时间衰减 + 一跳扩展,命中原因可在日志核对;可选本机向量通道 `denseEnabled`(Ollama `qwen3-embedding:0.6b` 与 BM25 做 RRF 融合,不可达时静默退回词法)。 |
64
+ | 原文片段 | `ragRecall`(默认开启)对本机全部持久化会话做纯词法原文检索(不调模型);`rawRecall`(默认关闭)仅从当前命中记忆的来源会话提取原文片段。 |
64
65
  | persona | 维护「这个人是谁」的画像(`persona/human.md`),注入在记忆摘要之前,默认预算 12000 字节;设置 → 记忆 → 画像 可查看/编辑,并可锁定不让后台改写。 |
65
- | 开放承诺 | 把会话里答应过、但还没到期/没做的事记成台账,到期未闭环会提醒。 |
66
- | 反思与技能草稿 | 每周从记忆里提炼跨项目观察(必须引用来源记忆);可把重复流程提成技能草稿,需你手动晋升。 |
66
+ | 开放承诺与提醒门控 | 把会话里答应过、未完成的事记成台账,到期未闭环直接提醒;无截止日期待办由 `noticeGate` 模型判定是否打扰,默认静默,带 6 小时同候选集冷却、2048 token 输出上限,并在流异常时透出真实 `finish` 原因。 |
67
+ | 反思与技能草稿 | 每周从记忆里提炼跨项目观察(必须引用来源记忆,流异常与 4096 token 上限已适配);可把重复流程提成技能草稿,需手动晋升。 |
68
+ | 跨客户端 MCP 服务 | 内置零依赖 stdio MCP 服务 `dsh-cross-memory-mcp`,暴露 5 个工具供外部 Agent 共用同一记忆库与画像。 |
67
69
  | GUI | 设置 → 记忆:浏览/搜索/新增/删除、**画像查看/编辑与锁定**、配置项、待裁决;插件页该包下也有同一张配置卡。 |
68
70
 
69
71
  ### 画像
@@ -99,25 +101,32 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
99
101
  # logFile: /custom/path/log # 默认 $DSH_HOME/logs/dsh-cross-memory.log;显式写空串关闭文件日志
100
102
  ```
101
103
 
102
- **可调项**(65 项,都是 `.volatile()` 字段):修改后立即生效,不需要重启,也不会重挂插件实例。可以在设置 → 记忆 → 配置里改,也可以直接改当前 profile 的 patch。常用项如下:
104
+ **可调项**(其余配置项均为 `.volatile()` 字段):修改后立即生效,不需要重启,也不会重挂插件实例。可以在设置 → 记忆 → 配置里改,也可以直接改当前 profile 的 patch。常用项如下:
103
105
 
104
106
  | 键 | 默认 | 说明 |
105
107
  | --- | --- | --- |
106
108
  | `maxSummaryBytes` | `8192` | 每会话注入摘要的总字节预算;`0` 关闭注入,只留工具 |
107
109
  | `maxSummaryEntries` | `20` | 每个作用域最多列出几条 |
108
- | `globalSummaryEntries` | `6` | 全局段最多列几条(两作用域共用总预算,全局段先渲染) |
110
+ | `globalSummaryEntries` | `6` | 全局段最多列几条(两作用域共用总字节预算,`project` 先渲染,全局段另有独立限额) |
109
111
  | `globalSummaryBytes` | `1200` | 全局段单独占的字节预算;`0` 不注入全局段 |
110
112
  | `summaryFreshSlots` | `3` | 每作用域预留几个名额给从未出现过的记忆,避免老条目长期占位 |
113
+ | `personaMaxBytes` | `12000` | 用户画像 `<persona>` 注入预算(字节);`0` 关闭 |
111
114
  | `recallMode` | `on-demand` | `once` 只注一次摘要 / `on-demand` 额外按需补注 / `off` 只用工具 |
112
115
  | `recallMinScore` | `6` | 按需补注的相关度下限;与 `recallMinTerms` 一起构成精度门槛 |
113
116
  | `recallMinTerms` | `1` | 补注所需的实词数。中文改写常只共享一个实词,故默认 1,靠分数门槛控噪声 |
114
117
  | `recallMaxPerConversation` | `8` | 一个会话最多按需补注多少条记忆;`0` 关闭 |
115
- | `recallMaxBytes` | `2400` | 每个按需补注块的字节预算;`0` 关闭|
118
+ | `recallMaxBytes` | `2400` | 每个按需补注块的字节预算;`0` 关闭 |
116
119
  | `injectDelta` | `true` | 摘要注入后新写入的记忆以增量块补发,每会话最多两次 |
117
120
  | `deltaMaxBytes` | `1600` | 每个增量块的字节预算;一条完整条目约 200–350 字节,`0` 关闭增量块 |
118
121
  | `rotationEntries` | `16` | 每会话额外列出多少个未出现过的标题;`0` 关闭标题轮转 |
119
122
  | `rotationEveryTurns` | `8` | 同一个长会话里每隔多少个用户轮重新发一次标题轮转块;`0` 只发一次 |
120
- | `rawRecall` | `false` | 补注块是否附带来源会话的原文片段(默认关闭) |
123
+ | `ragRecall` | `true` | 从本机全部持久化会话日志按词法检索原文片段(纯本地,不调模型) |
124
+ | `ragRecallBytes` | `12000` | 全历史原文片段的字节预算 |
125
+ | `ragRecallExcerpts` | `6` | 每次按需补注最多附带几段全历史原文 |
126
+ | `ragRecallSessions` | `0` | 最多打开多少个最新会话日志;`0` 表示扫描全部 |
127
+ | `ragRecallChars` | `2000` | 单段全历史原文的最大字符数 |
128
+ | `rawRecall` | `false` | 补注块是否附带当前命中记忆来源会话的原文片段(默认关闭) |
129
+ | `denseEnabled` | `false` | 是否启用本机向量排序通道(Ollama `http://127.0.0.1:11434` / `qwen3-embedding:0.6b` 与 BM25 做 RRF 融合,不可达时静默退回词法) |
121
130
  | `maxEntriesPerScope` | `0`(不限制) | 每作用域保留上限;`0` 表示不设上限,条目一直保留,由召回排序决定用哪些。设了上限后超出部分归档最久没被读到或注入的条目(手写、`pinned`、`permanent` 除外) |
122
131
  | `maxUnusedDays` | `0`(关闭) | 多久没用就归档(手写、`pinned`、`permanent` 除外);`0` 关闭。关闭时未读条目只是排序靠后,不会消失 |
123
132
  | `snapshotMaxAgeDays` | `0`(关闭) | `durability: snapshot` 条目的过期天数;`0` 关闭 |
@@ -128,14 +137,17 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
128
137
  | `extractIntervalMinutes` | `30` | 周期性抽取间隔;`0` 关闭周期检查 |
129
138
  | `minIdleHours` | `6` | 会话至少空闲多久才可被抽取 |
130
139
  | `maxAgeDays` | `10` | 超过这么多天没活动的会话不再抽取 |
140
+ | `recordScope` | `both` | 抽取范围:`both`(工作与生活事实均抽取)/ `work`(仅工作相关) |
131
141
  | `consolidate` | `true` | 是否启用合并重整 |
132
142
  | `consolidateCooldownHours` | `6` | 两次合并之间的最小间隔 |
133
143
  | `autoDecide` | `true` | 允许 AI 裁决本会排队等你的合并决定 |
144
+ | `noticeGate` | `true` | 对无截止日期待办启用提醒门控;开启后对同一批候选带 6 小时冷却 |
145
+ | `peakHours` | 空 | 避开模型高峰计费时段(例如 `Mon-Fri 09:00-12:00, Mon-Fri 14:00-18:00`),期间后台抽取与合并顺延 |
134
146
  | `syncRemote` | 空 | 记忆库同步用的 Git remote;空 = 只在本机提交 |
135
147
  | `syncClock` | `12:05,18:05` | 定时同步的本地时刻;空则回退到 `syncIntervalMinutes` |
136
148
  | `syncIntervalMinutes` | `10` | 后台同步间隔;`0` 关闭定时器 |
137
149
  | `syncDebounceSeconds` | `2` | 一批连续写入合并成一次本地提交的等待时间 |
138
- | `extractProvider` / `extractModel` | 空 | 抽取调用的模型路由;空则沿用会话路由 |
150
+ | `extractProvider` / `extractModel` | 空 | 抽取、门控与反思的路由覆盖;留空(含空串)自动回落到当前会话路由 |
139
151
  | `logLevel` | `info` | 插件日志详细程度:`off`/`error`/`warn`/`info`/`debug` |
140
152
 
141
153
  完整字段与逐项说明以设置页「配置」标签为准(也可 `dsh --profile <profile> --dump-config`)。
@@ -152,6 +164,32 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
152
164
 
153
165
  `kind` 取值:`fact` / `preference` / `knowledge` / `failure` / `procedure`。
154
166
 
167
+ ## MCP 服务(跨客户端共用记忆库)
168
+
169
+ 本包附带零额外运行时依赖的 stdio MCP 服务,供 Antigravity、Claude Code、Cursor、Codex、VS Code 等外部客户端直接读写同一份 `$DSH_HOME/memories` 记忆库与 `persona/human.md`:
170
+
171
+ - **入口**:bin 命令 `dsh-cross-memory-mcp`,或直接运行 `node /path/to/dsh-cross-memory/lib/mcp.js`(包导出 `./mcp`)。
172
+ - **暴露工具(5 个)**:`memory_persona`、`memory_search`、`memory_read`、`memory_write`、`memory_projects`。
173
+ - **环境变量**:
174
+ - `DSH_HOME`:DSH 根目录,默认 `~/.dsh`。
175
+ - `DSH_MEMORIES_DIR`:显式指定记忆库目录,默认 `$DSH_HOME/memories`。
176
+ - `DSH_MEMORY_DENSE`:是否启用本地向量重排,默认开启;设为 `0`、`false` 或 `off` 时关闭。
177
+ - `DSH_MEMORY_DENSE_URL`:向量服务地址,默认 `http://127.0.0.1:11434`。
178
+ - `DSH_MEMORY_DENSE_MODEL`:向量模型名称,默认 `qwen3-embedding:0.6b`。
179
+
180
+ 通用客户端配置示例(JSON-RPC 2.0 stdio):
181
+
182
+ ```json
183
+ {
184
+ "mcpServers": {
185
+ "dsh-memories": {
186
+ "command": "node",
187
+ "args": ["/path/to/dsh-cross-memory/lib/mcp.js"]
188
+ }
189
+ }
190
+ }
191
+ ```
192
+
155
193
  ## `/memories` 命令
156
194
 
157
195
  ```
@@ -184,6 +222,7 @@ dsh plugin --profile <profile> add /path/to/packages/dsh-cross-memory
184
222
  ```text
185
223
  $DSH_HOME/memories/
186
224
  ├── index.json # 可重建的索引缓存
225
+ ├── cache/ # 本机向量嵌入缓存(开启 denseEnabled 或 MCP 向量重排时生成)
187
226
  ├── entries/<id>.md # 每条全局记忆一个文件
188
227
  ├── archive/<id>.md # 归档的全局记忆(可恢复)
189
228
  ├── projects/<slug>/
@@ -207,9 +246,9 @@ $DSH_HOME/memories/
207
246
  ## 隐私边界
208
247
 
209
248
  - **默认不联网**。记忆只写在 `$DSH_HOME` 下,不往你的工作区仓库写文件;Git 同步默认关闭。
210
- - **后台模型调用**会经过你配置的模型路由(默认沿用会话自己的路由)。抽取输入是会话尾部,只取用户与助手正文,丢弃工具结果和插件注入的内容,避免记忆自噬;落盘前做密钥擦除(`sk-…`、`ghp_…`、`AKIA…`、JWT、私钥块、`api_key=…`、`Bearer …` 等)。
249
+ - **后台模型调用**会经过你配置的模型路由(默认沿用会话自己的路由)。抽取输入是会话尾部,只取用户与助手正文,丢弃工具结果和插件注入的内容,避免记忆自噬;落盘前做中英文密钥与口令擦除(`sk-…`、`ghp_…`、`AKIA…`、JWT、私钥块、`api_key=…`、`Bearer …`、「密码/口令/授权码是…」等)。
211
250
  - **注入的内容是背景数据,不是指令**:注入块会明确告诉模型,记忆记录的是写入时的事实,不一定现在仍成立。
212
- - **原始片段是 opt-in**:`rawRecall` 默认关闭;打开后补注块会附带来源会话的原文(只读本机会话日志)。
251
+ - **全历史词法检索与可选通道**:`ragRecall`(默认开启)仅在本地读取持久化会话日志做词法检索,不触发模型调用;`rawRecall`(默认关闭)仅从命中记忆的来源会话提取片段;`denseEnabled`(默认关闭)仅请求本机 Ollama(`http://127.0.0.1:11434`),不可达时静默退回词法。
213
252
  - **通知可选**:默认通过操作系统通知提醒(每日摘要、到期承诺),`noticeQuietHours` 可设置静默时段,`noticesEnabled: false` 完全关闭。通知投递目前只在 macOS 生效(走 `osascript`);其他平台投递失败,通知仍留在队列里,可用 `/memories notices` 查看。
214
253
  - **彻底关掉后台行为**:`autoExtract: false`、`consolidate: false`、`reflectionEnabled: false`;再设 `maxSummaryBytes: 0` 或 `recallMode: off` 就只剩 `memory` 工具与 `/memories` 命令。
215
254
  - 归档与合并只动 `$DSH_HOME` 下的文件;归档条目可 `restore`,合并失败的改动会回滚。
@@ -235,12 +274,12 @@ $DSH_HOME/memories/
235
274
 
236
275
  | 依赖 | 区间 |
237
276
  | --- | --- |
238
- | DSH | `^0.2.1-rc.2 \|\| ^0.2.2-alpha.2` |
277
+ | DSH | `^0.2.1-rc.2 \|\| ^0.2.2-alpha.2 \|\| ^0.2.3-alpha.1` |
239
278
  | Node.js | `>=24`(与 DSH 宿主自带运行时一致) |
240
279
  | Cordis | `^4.0.5 \|\| ^4.0.6-alpha.1` |
241
280
  | Schemastery | `^3.18.5 \|\| ^3.18.6-alpha.1` |
242
281
 
243
- `@deepseek-ai/*` 均为 `peerDependencies`,由宿主提供,插件不另装内核包。本包在 DSH 内核 0.2.2-rc.1 上开发和测试(`devDependencies` 锁定 Cordis 4.1.0、Schemastery 3.19.0)。不同内核版本的子代理约定差异(预设路线 / 无预设直调 / 老内核黑名单路线)已在插件内适配。
282
+ `@deepseek-ai/*` 均为 `peerDependencies`,由宿主提供,插件不另装内核包。本包在 DSH 内核 0.2.2-rc.1 上开发和测试(`devDependencies` 锁定 Cordis 4.1.0、Schemastery 3.19.0)。不同内核版本的子代理约定差异(新版扁平 `SubagentActivationSpec` 预设路线并自动 `dispose` / 无预设直调 / 老内核黑名单路线)已在插件内适配。
244
283
 
245
284
  ## 开发
246
285
 
package/docs/DETAIL.md CHANGED
@@ -14,11 +14,11 @@ dsh-cross-memory extracts whatever is worth keeping from a session (preferences,
14
14
  Each conversation receives the following blocks in order, each with its own budget:
15
15
 
16
16
  1. `<persona>`: a snapshot of the user profile, bounded by `personaMaxBytes` (default 12000 bytes, `0` disables it) and truncated at a line boundary. A legacy single-file `persona.md` is still read; saving writes `persona/human.md`.
17
- 2. Memory summary: within `maxSummaryBytes` (default 4096), split into a `global` and a `project` section. Both scopes share one byte budget and `global` renders first, so it also has `globalSummaryEntries` and `globalSummaryBytes` caps of its own.
17
+ 2. Memory summary: within `maxSummaryBytes` (default 8192), `project` and `global` entries are ranked together (`rankForSummary`) and `project` renders first; both scopes share one byte budget, and `global` also has `globalSummaryEntries` and `globalSummaryBytes` caps of its own.
18
18
  3. Delta block: memories written after the summary was injected are announced in small blocks (`injectDelta`, at most twice per conversation, `deltaMaxBytes` default 1600 each; one complete entry costs 200-350 bytes, so the former 800 admitted one or two).
19
19
  4. Title rotation: titles the summary had no room for, `rotationEntries` (default 16) per conversation, re-emitted every `rotationEveryTurns` (default 8) user turns in a long session.
20
- 5. On-demand recall: injected only when the current user turn lands enough distinct terms in an entry's title, `keys`, `tags` or `appliesTo` (or matches a whole phrase) (`recallMinTerms` default 2, `recallMinScore` default 9, at most `recallMaxPerConversation` per conversation). A term appearing in more than `evidenceMaxDf` (default 0.15) of one scope does not count as evidence. When the strict gate refuses, one alias fallback still runs: it scores `keys` and `appliesTo` only, needs a single substantive term, and applies a floor scaled by `ALIAS_FLOOR_SHARE` (0.5, so half of `recallMinScore`), injecting at most two entries with a line saying the match was by alias. It exists because a turn phrased with a memory's *other* name shares exactly one term and the two-term gate refuses it. The floor has to be scaled rather than shared: one CJK alias term scores 6 in those two fields at most, so the normal 9 would have made the pass fire for English turns and never for Chinese ones. An alias filed in only one field (3.5) is still refused, and body words never take part.
21
- 6. Raw excerpts: with `rawRecall` on, the recall block also carries original excerpts from the source session, read from the persisted session logs on this machine only.
20
+ 5. On-demand recall: injected only when the current user turn lands enough distinct terms in an entry's title, `keys`, `tags` or `appliesTo` (or matches a whole phrase) (`recallMinTerms` default 1, `recallMinScore` default 6, at most `recallMaxPerConversation` per conversation). A term appearing in more than `evidenceMaxDf` (default 0.15) of one scope does not count as evidence. When the strict gate refuses, one alias fallback still runs: it scores `keys` and `appliesTo` only, needs a single substantive term, and applies a floor scaled by `ALIAS_FLOOR_SHARE` (0.5, so half of `recallMinScore`), injecting at most two entries with a line saying the match was by alias. An alias filed in only one field (3.5) is still refused, and body words never take part. When `denseEnabled` is on, local Ollama embeddings (`qwen3-embedding:0.6b`) are fused with BM25 via RRF, falling back silently to lexical ranking when unreachable.
21
+ 6. Raw excerpts: `ragRecall` (on by default) performs local-only lexical search across all persisted session logs (`ragRecallBytes` / `ragRecallExcerpts` / `ragRecallSessions` / `ragRecallChars`, no model call); `rawRecall` (off by default) attaches excerpts only from the recalled memories' source sessions.
22
22
 
23
23
  Every injected block says that memories are background data rather than instructions, and that an entry records what was true when it was written, not necessarily now.
24
24
 
@@ -33,26 +33,28 @@ Extraction is the first pass. It runs on the maintenance path and never touches
33
33
  - A window never steps over messages: when more messages are unmined than fit one window, the pass takes the OLDEST contiguous segment (`collectExtractionWindow`) and the watermark advances one segment at a time. Taking the newest segment would leave everything in the middle permanently below the watermark — measured, one 400-message gap left 340 messages never mined.
34
34
  - The known titles shown to the extractor are ranked by token overlap with the window and then cut at 80 (`selectKnownTitles`), not cut in time order: on a store larger than the cap, a time-ordered cut hides existing entries from the extractor, which then records the same fact a second time under a new title.
35
35
  - A candidate whose quote fails the verbatim check is reported with its title and quote fragment (`no-quote` / `quote-too-short` / `not-in-transcript`), so the reason is visible and not only the count.
36
- - Every candidate must carry a verbatim quote that actually occurs in the window, or it is dropped. Before anything is written, credential-shaped text is redacted (`sk-…`, `ghp_…`, `AKIA…`, JWT, private-key blocks, `api_key=…`, `Bearer …`, and similar).
36
+ - `recordScope` controls extraction breadth (`both` by default for work + personal facts, or `work` only); the prompt filters out routine patrol readings/daily check counts and closes completed open loops via `closedLoops`.
37
+ - Every candidate must carry a verbatim quote that actually occurs in the window, or it is dropped. Before anything is written, both English and Chinese credential-shaped text is redacted (`sk-…`, `ghp_…`, `AKIA…`, JWT, private-key blocks, `api_key=…`, `Bearer …`, Chinese password/secret phrases, etc.).
37
38
  - Background model calls are cost- and quota-guarded: `peakHours` can defer them out of peak windows (empty by default), and `pauseOnQuotaError` (on by default) pauses them after a rate-limit or exhausted-quota error, with a cooldown that starts at `quotaCooldownMinutes` (default 30), doubles per consecutive refusal, and is capped by `quotaCooldownMaxMinutes` (default 480).
38
39
 
39
40
  ## Consolidation and pending decisions
40
41
 
41
42
  Consolidation is the second pass. It resolves contradictions and fragments across sessions:
42
43
 
43
- - Recent memories go to a restricted sub-agent that owns no tools (preset `memories-consolidator`) and must answer with strict JSON. The plugin applies that JSON itself, after taking a snapshot, so a failed plan can be rolled back. A deployment without a preset registry falls back to one plain model call that also owns no tools.
44
+ - Recent memories go to a restricted sub-agent that owns no tools (preset `memories-consolidator`), started via the flattened `SubagentActivationSpec` and disposed in a `finally` block; it must answer with strict JSON. The plugin applies that JSON itself, after taking a snapshot, so a failed plan can be rolled back. A deployment without a preset registry falls back to one plain model call that also owns no tools.
44
45
  - Only reversible changes are applied unattended: merging duplicates, sharpening wording, retiring entries nothing ever read. Rewrites and retirements that could lose information wait for you: an entry a person wrote, a pinned or permanent entry, a retire of a memory that was actually read, and a rewrite that drops cited file paths or shrinks the body below half its previous length are never applied silently.
45
46
  - An existing entry never changes scope; only new memories are placed as `global` or `project` by this pass.
46
47
  - A pending proposal expires after `consolidateProposalMaxAgeHours` (default 72). `autoDecide` (on by default) lets an AI adjudicate first, but a verdict below `autoDecideMinConfidence` (default 0.7) still waits for you.
47
48
  - There are three confirmation entries over the same `pending/consolidation.json`: an in-answer `resolve_memory_proposal` action card (Apply / Reject / Not now), the per-row 待裁决 panel in Settings, and `/memories plan|apply|reject`. The model offers the card from the `memory-proposal` skill as an `action-card` block at the end of its answer; `details` carries only the current proposal's `label`, `count` and `stagedAt`. Every action reconciles first, so a proposal already decided by the command, the panel or a newer pass settles as `settled-elsewhere`/`superseded` instead of being applied twice. The notice pump no longer sends pending-decision backlog (this deployment has no usable `osascript` channel); confirmation goes through the three entries above.
48
49
  - When two memories contradict each other, the sub-agent reports the pair as a conflict instead of picking one silently.
49
- - Consolidation maintains the persona profile unless `persona/human.lock` exists, and turns repeatable procedures into skill drafts (at most 2 per pass). A draft lands in `memories/skills/<name>/SKILL.md`; `/memories promote` copies it to `$DSH_HOME/skills/<name>/SKILL.md`, and re-promotion is refused when the promoted copy is newer than the draft.
50
+ - Consolidation maintains and deduplicates the persona profile unless `persona/human.lock` exists, receives existing skill draft names to prevent synonymous drafts, and turns repeatable procedures into skill drafts (at most 2 per pass). A draft lands in `memories/skills/<name>/SKILL.md`; `/memories promote` copies it to `$DSH_HOME/skills/<name>/SKILL.md`, and re-promotion is refused when the promoted copy is newer than the draft. Consolidation failure stacks (top 6 frames) are logged at `warn` level.
51
+ - `noticeGate` and weekly `reflectionEnabled` use `resolveLlmRoute` (falling back to the session route whenever `extractProvider`/`extractModel` are empty strings), inspect `assembler.finish.kind` to surface stream errors, and allocate `2048` / `4096` maxTokens respectively; `noticeGate` also applies a 6-hour same-candidate cooldown (`noticeGate:lastAt` / `noticeGate:lastFingerprint`).
50
52
 
51
53
  ## Retention and archival
52
54
 
53
- - A memory that has not been read or surfaced, and is not newly written, for `maxUnusedDays` (default 90) is archived. Archiving is not deletion: `/memories restore` brings it back.
54
- - An entry with `durability=snapshot` is also archived once it is `snapshotMaxAgeDays` (default 60) past the moment it was measured; reading a stale reading does not make it fresh.
55
- - `maxEntriesPerScope` (default 1000) caps each scope; past it, the least recently read or surfaced entries are archived. `pinned`, `permanent` and `source=user` entries are never retired automatically, so a scope can stay slightly above its cap.
55
+ - A memory that has not been read or surfaced, and is not newly written, for `maxUnusedDays` (default `0`, disabled) is archived when enabled. Archiving is not deletion: `/memories restore` brings it back.
56
+ - An entry with `durability=snapshot` is also archived once it is `snapshotMaxAgeDays` (default `0`, disabled) past the moment it was measured when enabled; reading a stale reading does not make it fresh.
57
+ - `maxEntriesPerScope` (default `0`, unlimited) caps each scope when set; past it, the least recently read or surfaced entries are archived. `pinned`, `permanent` and `source=user` entries are never retired automatically, so a scope can stay slightly above its cap.
56
58
  - Each scope's `archive/` keeps the newest 500 files; older archives are cleaned up.
57
59
  - Evidence notes under `sessions/` keep the newest 200; older ones are removed. When a note is gone, `evidence` says so explicitly instead of inventing a summary.
58
60
  - `forget` (the `memory` tool and `/memories forget`) is a physical delete, with no restore.
@@ -73,7 +75,8 @@ Consolidation is the second pass. It resolves contradictions and fragments acros
73
75
 
74
76
  ## Limits
75
77
 
76
- - Recall is lexical (title, `keys`, `tags`, `appliesTo`, body) with time decay and a one-hop expansion along shared `keys`/`tags` — not vector search; the on-demand gate counts only title, `keys`, `tags` and `appliesTo`. Chinese is handled as character bigrams: a shared run of two characters counts as one strong term. A search that finds nothing does not simply answer "none": the tool lists the `keys`/`tags` vocabulary that shares characters with the query so the model can retry in the store's own words (`suggestAliases`; a vocabulary hint, never a match).
78
+ - Recall is lexical by default (title, `keys`, `tags`, `appliesTo`, body) with time decay and a one-hop expansion along shared `keys`/`tags`; the on-demand gate counts only title, `keys`, `tags` and `appliesTo`. Chinese is handled as character bigrams: a shared run of two characters counts as one strong term. Optional `denseEnabled` fuses local Ollama embeddings (`qwen3-embedding:0.6b`) with BM25 via RRF. A search that finds nothing does not simply answer "none": the tool lists the `keys`/`tags` vocabulary that shares characters with the query so the model can retry in the store's own words (`suggestAliases`; a vocabulary hint, never a match).
79
+ - A standalone zero-dependency stdio MCP server (`dsh-cross-memory-mcp` / `./mcp`) exposes `memory_persona`, `memory_search`, `memory_read`, `memory_write`, and `memory_projects` so external clients can share the same `$DSH_HOME/memories` store.
77
80
  - An injected memory is what was concluded when it was written, not current truth; use `memory` action=evidence to open the source conversation when it matters.
78
81
  - A `snapshot` value expires from when it was measured; do not use one in place of a reading that changes on its own.
79
82
  - Extraction and consolidation are quota- and peak-hour aware; neither is guaranteed to have run at any particular moment.
package/docs/DETAIL.zh.md CHANGED
@@ -14,11 +14,11 @@ dsh-cross-memory 把会话里值得长期保留的内容(偏好、决定、踩
14
14
  每个会话按顺序拿到下面这些块,每块都有自己的预算:
15
15
 
16
16
  1. `<persona>`:用户画像快照,预算 `personaMaxBytes`(默认 12000 字节,`0` 关闭),超长部分按行截断。旧的单文件 `persona.md` 仍会被读取,保存后写到 `persona/human.md`。
17
- 2. 记忆摘要:在 `maxSummaryBytes`(默认 4096)内分 `global` 与 `project` 两段;两段共用一个字节预算,`global` 先渲染,另有 `globalSummaryEntries` 与 `globalSummaryBytes` 限制它的大小。
17
+ 2. 记忆摘要:在 `maxSummaryBytes`(默认 8192)内把 `project` 与 `global` 合并排序(`rankForSummary`)后,按 `project` 先行渲染;两段共用同一个字节预算,`global` 另有 `globalSummaryEntries` 与 `globalSummaryBytes` 限制其大小。
18
18
  3. 增量块:摘要注入之后新写入的记忆以小块补发(`injectDelta`,每会话最多两次、每次 `deltaMaxBytes` 默认 1600 字节;一条完整条目约 200–350 字节,旧的 800 只装得下一两条)。
19
19
  4. 标题轮转:只列摘要没提到的标题,每会话 `rotationEntries`(默认 16)条,同一个长会话里每 `rotationEveryTurns`(默认 8)个用户轮重新发一次。
20
- 5. 按需补注:当前用户轮与某条记忆的标题、`keys`、`tags`、`appliesTo` 命中足够多的实词(或整句短语命中)才会注入(`recallMinTerms` 默认 2、`recallMinScore` 默认 9、每会话最多 `recallMaxPerConversation` 条);在单个作用域里出现比例超过 `evidenceMaxDf`(默认 0.15)的词不计入证据。严格门没过时还有一道别名回退:只对 `keys` 与 `appliesTo` 计分、只要求一个实词、门槛按 `ALIAS_FLOOR_SHARE`(0.5)缩放(默认 9 的一半),最多补 2 条,注入块里会写明「按别名匹配」。它存在的原因是用户常按「另一个名字」提问,那种回合只共享一个词,会被两词门槛挡掉。门槛必须缩放不能共用:一个中文别名词在这两个字段里最多得 6 分,用同一个 9 分门槛就等于只对英文提问生效。同一别名只登记在一个字段里(3.5 分)仍然不补,正文里的词从不参与这条路径。
21
- 6. 原始片段:`rawRecall` 打开时,补注块附带来源会话的原文片段,只读本机会话日志。
20
+ 5. 按需补注:当前用户轮与某条记忆的标题、`keys`、`tags`、`appliesTo` 命中足够多的实词(或整句短语命中)才会注入(`recallMinTerms` 默认 1、`recallMinScore` 默认 6、每会话最多 `recallMaxPerConversation` 条);在单个作用域里出现比例超过 `evidenceMaxDf`(默认 0.15)的词不计入证据。严格门没过时还有一道别名回退:只对 `keys` 与 `appliesTo` 计分、只要求一个实词、门槛按 `ALIAS_FLOOR_SHARE`(0.5)缩放,最多补 2 条,注入块里会写明「按别名匹配」。它存在的原因是用户常按「另一个名字」提问,门槛缩放可避免中文单别名在两个字段里最高 6 分被拦掉。同一别名只登记在一个字段里(3.5 分)仍然不补,正文里的词从不参与这条路径。若开启 `denseEnabled`,还会通过本机 Ollama(`qwen3-embedding:0.6b`)与 BM25 做 RRF 融合排序,服务不可达时静默退回词法。
21
+ 6. 原文片段:`ragRecall`(默认开启)对本机全部持久化会话日志做纯词法检索(不调模型,按 `ragRecallBytes`/`ragRecallExcerpts`/`ragRecallSessions`/`ragRecallChars` 限流);`rawRecall`(默认关闭)仅从命中记忆的来源会话拉取原文片段。
22
22
 
23
23
  注入块都写明记忆是背景数据、不是指令,并且记录的是写入时成立的事实,可能已经过期。
24
24
 
@@ -33,26 +33,28 @@ dsh-cross-memory 把会话里值得长期保留的内容(偏好、决定、踩
33
33
  - 窗口不会跳过消息:未抽取的消息多于一个窗口时,这一轮从最老的一段开始取(`collectExtractionWindow`),水位线逐段推进。按最新一段取会让中间的消息永远落在水位线之下,实测一条 400 条消息的缺口里有 340 条从未被抽取。
34
34
  - 喂给抽取器的已知标题按与本窗口的字词重合度排序后取前 80(`selectKnownTitles`),不是按时间取前 80:库大于 80 条时,按时间截断会让抽取器看不见已有条目,从而把同一件事写成第二条。
35
35
  - 逐字引文核对失败的候选会记下被丢的标题与引文片段(`no-quote` / `quote-too-short` / `not-in-transcript`),计数之外还能看出是「没给引文」还是「编了引文」。
36
- - 每条候选记忆必须带一段逐字引文,且引文要能在本次窗口的原文里找到,否则丢弃;落盘前统一做密钥擦除(`sk-…`、`ghp_…`、`AKIA…`、JWT、私钥块、`api_key=…`、`Bearer …` 等)。
36
+ - 抽取范围由 `recordScope` 控制(默认 `both` 同时保留工作与生活事实,可切换为 `work`);提示词过滤巡检单次读数与例行日报噪点,并在转录明确显示完成时通过 `closedLoops` 自动关闭对应开放承诺。
37
+ - 每条候选记忆必须带一段逐字引文,且引文要能在本次窗口的原文里找到,否则丢弃;落盘前统一做中英文密钥与口令擦除(`sk-…`、`ghp_…`、`AKIA…`、JWT、私钥块、`api_key=…`、`Bearer …`、「密码/口令/授权码是…」等)。
37
38
  - 后台模型调用受成本与配额保护:`peakHours` 可把后台调用推到谷时(默认空),`pauseOnQuotaError`(默认开)在限流或配额不足后暂停,冷却从 `quotaCooldownMinutes`(默认 30)起逐次翻倍,上限 `quotaCooldownMaxMinutes`(默认 480)。
38
39
 
39
40
  ## 合并与待裁决
40
41
 
41
42
  合并是第二遍,处理跨会话的矛盾与碎片:
42
43
 
43
- - 一批记忆交给一个不含任何工具的子代理(预设 `memories-consolidator`),它只返回严格 JSON 方案;插件自己应用方案,并在应用前留快照,出错的改动可以回滚。部署没有预设注册表时退回一次无工具的普通模型调用。
44
+ - 一批记忆交给一个不含任何工具的子代理(预设 `memories-consolidator`),按新版扁平 `SubagentActivationSpec` 发起并在结束时调用 `activation.dispose()`,它只返回严格 JSON 方案;插件自己应用方案,并在应用前留快照,出错的改动可以回滚。部署没有预设注册表时退回一次无工具的普通模型调用。
44
45
  - 可以自动执行的是可逆改动:合并重复、收紧措辞、退役从没被读过的条目。可能丢信息的改写与退役进入**待裁决**:人手写、置顶或永久保留的条目,被读到过的退役,丢失正文里文件路径引用或正文不到原来一半的改写,都不会被静默处理。
45
46
  - 已在库里的条目不会换作用域,新记忆才由这一遍决定放在 `global` 还是 `project`。
46
47
  - 待裁决方案在 `consolidateProposalMaxAgeHours`(默认 72)小时后自动作废;`autoDecide`(默认开)允许 AI 先判断是否丢信息,置信度低于 `autoDecideMinConfidence`(默认 0.7)时仍然留给你。
47
48
  - 确认入口有三个,操作同一份 `pending/consolidation.json`:回答内的 `resolve_memory_proposal` 卡片(确认应用 / 拒绝 / 稍后)、设置页「待裁决」逐条处理、`/memories plan|apply|reject`。卡片由模型按 `memory-proposal` 技能在最终回答末尾用 `action-card` 块给出,`details` 只带当前提案的 `label`/`count`/`stagedAt`;点按钮前 Host 会先 reconcile,提案已被 `/memories`、设置页或新的一轮合并处理掉时卡片落 `settled-elsewhere`/`superseded`,不会重复应用。通知泵不再推送待确认积压(本机没有可用的 `osascript` 投递通道),待确认只走上面三个入口。
48
49
  - 两条记忆互相矛盾时,子代理把这一对列进冲突报告(保留哪条、丢弃哪条),而不是悄悄挑一个。
49
- - 合并会维护画像,`persona/human.lock` 存在时跳过;也会把重复流程提成技能草稿(每轮最多 2 个),草稿落在 `memories/skills/<name>/SKILL.md`,`/memories promote` 才复制到 `$DSH_HOME/skills/<name>/SKILL.md`;已晋升的文件比草稿新时,重复晋升会被拒绝。
50
+ - 合并会维护画像(自动去除同段重复或近义条目,`persona/human.lock` 存在时跳过);同时传入已有技能草稿名称避免重名,重复流程提成技能草稿(每轮最多 2 个)落在 `memories/skills/<name>/SKILL.md`,`/memories promote` 才复制到 `$DSH_HOME/skills/<name>/SKILL.md`;已晋升的文件比草稿新时,重复晋升会被拒绝。合并失败时堆栈前 6 帧按 `warn` 级落盘。
51
+ - 提醒门控(`noticeGate`)与每周反思(`reflectionEnabled`)的 `resolveLlmRoute` 在 `extractProvider` / `extractModel` 为空串时自动回落到当前会话路由,并检查 `assembler.finish.kind` 透出真实错误(输出上限分别为 `2048` 与 `4096` token);门控另带 6 小时同候选集冷却(`noticeGate:lastAt` / `noticeGate:lastFingerprint`)。
50
52
 
51
53
  ## 保留与归档
52
54
 
53
- - `maxUnusedDays`(默认 90)内没有被读到、没有被注入摘要、也不是新写的记忆会被归档;归档不是删除,`/memories restore` 可以取回。
54
- - `durability=snapshot` 的条目另按 `snapshotMaxAgeDays`(默认 60)从测量时间起算归档,被读一次不会让读数变新。
55
- - `maxEntriesPerScope`(默认 1000)是每个作用域的上限,超出时归档最久没有被读到或注入的条目;`pinned`、`permanent` 与 `source=user` 的条目不会被自动退役,所以作用域可能略超上限。
55
+ - `maxUnusedDays`(默认 `0` 关闭;设为正数后启用)内没有被读到、没有被注入摘要、也不是新写的记忆会被归档;归档不是删除,`/memories restore` 可以取回。
56
+ - `durability=snapshot` 的条目另按 `snapshotMaxAgeDays`(默认 `0` 关闭;设为正数后启用)从测量时间起算归档,被读一次不会让读数变新。
57
+ - `maxEntriesPerScope`(默认 `0` 不限制;设为正数后启用)是每个作用域的上限,超出时归档最久没有被读到或注入的条目;`pinned`、`permanent` 与 `source=user` 的条目不会被自动退役,所以作用域可能略超上限。
56
58
  - 每个作用域的 `archive/` 目录只保留最新的 500 个文件,更早的归档会被清理。
57
59
  - `sessions/` 下的证据笔记只保留最新的 200 份,更早的会被清掉;笔记不在时 `evidence` 会直接说明没有这份证据笔记,而不是编造内容。
58
60
  - `/memories forget` 与 `memory` 工具的 `forget` 是**物理删除**,不可恢复。
@@ -73,7 +75,8 @@ dsh-cross-memory 把会话里值得长期保留的内容(偏好、决定、踩
73
75
 
74
76
  ## 注意与限制
75
77
 
76
- - 检索与召回都是词法匹配,不是向量检索:标题、`keys`、`tags`、`appliesTo`、正文按权重计分,再叠时间衰减与沿共享 `keys`/`tags` 的一跳扩展;按需补注的门槛只认标题、`keys`、`tags`、`appliesTo` 四个字段。中文按字符二元组处理,共享两个汉字记为一次强命中。检索零命中时工具不直接回「没有」:它会列出库里与被查词共享字符的 `keys`/`tags` 词表,让模型用库自己的说法重试一次(`suggestAliases`,只是词表提示,不是匹配结果)。
78
+ - 检索与召回默认走词法匹配(标题、`keys`、`tags`、`appliesTo`、正文按权重计分,叠时间衰减与沿共享 `keys`/`tags` 的一跳扩展;按需补注的门槛只认标题、`keys`、`tags`、`appliesTo` 四个字段);中文按字符二元组处理,共享两个汉字记为一次强命中。可选开启 `denseEnabled` 叠加本机 Ollama 向量重排(RRF 融合)。检索零命中时工具不直接回「没有」,而是列出库里与被查词共享字符的 `keys`/`tags` 词表,让模型用库自己的说法重试一次(`suggestAliases`,只是词表提示,不是匹配结果)。
79
+ - 包内另附独立的零依赖 stdio MCP 服务(`dsh-cross-memory-mcp` / `./mcp`),暴露 `memory_persona`、`memory_search`、`memory_read`、`memory_write`、`memory_projects` 供外部客户端直接共用同一份 `$DSH_HOME/memories` 存储。
77
80
  - 注入的记忆是写入当时的结论,不是当前事实;需要判断时用 `memory` 的 `evidence` 打开来源会话。
78
81
  - `durability=snapshot` 的数字从测量时间起算过期,不要用它代替会自己变化的读数。
79
82
  - 合并与抽取都受配额与谷时限制,后台不保证在某个时刻一定跑过。
package/lib/backfill.js CHANGED
@@ -16,6 +16,7 @@
16
16
  import { createHash } from 'node:crypto';
17
17
  import { readFile, readdir, stat } from 'node:fs/promises';
18
18
  import { basename, dirname, join } from 'node:path';
19
+ import { promisify } from 'node:util';
19
20
  import * as zlib from 'node:zlib';
20
21
  /** zstd frame magic bytes; a session log is a concatenation of frames. */
21
22
  const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
@@ -64,6 +65,36 @@ export function decodeSessionLog(buffer) {
64
65
  }
65
66
  return parts.join('');
66
67
  }
68
+ /**
69
+ * Async variant of {@link decodeSessionLog}: decompresses frames on libuv's
70
+ * worker pool so large persisted logs never stall the Host event loop.
71
+ */
72
+ export async function decodeSessionLogAsync(buffer) {
73
+ const zstd = zlib;
74
+ if (typeof zstd.zstdDecompress !== 'function')
75
+ return decodeSessionLog(buffer);
76
+ const decompress = promisify(zstd.zstdDecompress);
77
+ const offsets = [];
78
+ let index = buffer.indexOf(ZSTD_MAGIC);
79
+ while (index >= 0) {
80
+ offsets.push(index);
81
+ index = buffer.indexOf(ZSTD_MAGIC, index + ZSTD_MAGIC.length);
82
+ }
83
+ const parts = [];
84
+ for (let frame = 0; frame < offsets.length; frame += 1) {
85
+ const start = offsets[frame];
86
+ if (start === undefined)
87
+ continue;
88
+ const end = offsets[frame + 1] ?? buffer.length;
89
+ try {
90
+ parts.push((await decompress(buffer.subarray(start, end))).toString('utf8'));
91
+ }
92
+ catch {
93
+ // Not a standalone frame boundary: skip it.
94
+ }
95
+ }
96
+ return parts.join('');
97
+ }
67
98
  /** Join the text blocks of one message, ignoring reasoning and tool calls. */
68
99
  function blockText(blocks) {
69
100
  if (!Array.isArray(blocks))
@@ -272,5 +303,5 @@ export async function findSessionLogs(sessionsDir) {
272
303
  */
273
304
  export async function readSessionLog(file, modifiedAt) {
274
305
  const buffer = await readFile(file);
275
- return parseSessionLog(decodeSessionLog(buffer), file, modifiedAt);
306
+ return parseSessionLog(await decodeSessionLogAsync(buffer), file, modifiedAt);
276
307
  }
package/lib/client.js CHANGED
@@ -216,7 +216,7 @@ window.__ModuleLoader__.load({
216
216
  {
217
217
  field: 'maxSummaryBytes', kind: 'number', min: 0, step: 256,
218
218
  label: { zh: '摘要字节上限', en: 'Summary byte budget' },
219
- hint: { zh: '一次会话注入的记忆摘要最大字节数,默认 4096;0 表示关闭注入。', en: 'Bytes of memory summary injected once per conversation, default 4096. 0 disables injection.' },
219
+ hint: { zh: '一次会话注入的记忆摘要最大字节数,默认 8192;0 表示关闭注入。', en: 'Bytes of memory summary injected once per conversation, default 8192. 0 disables injection.' },
220
220
  },
221
221
  {
222
222
  field: 'maxSummaryEntries', kind: 'number', min: 1, step: 1,
@@ -251,7 +251,7 @@ window.__ModuleLoader__.load({
251
251
  {
252
252
  field: 'recallMinScore', kind: 'number', min: 0, step: 1,
253
253
  label: { zh: '按需注入的相关度下限', en: 'Recall relevance floor' },
254
- hint: { zh: '补注需要达到的相关度分数,是一个"更严/更松"的旋钮。真正的精度由下面「补注所需命中词数」把关:中文提问共享两个词大约得 9–12 分,所以默认 9;只共用「日志」这类一个常见词大约 8 分,因此单靠相关度是拦不住的。', en: 'Relevance a memory must reach to be injected on demand. This is a strictness knob; precision comes from the strong-term requirement below. A Chinese paraphrase sharing two bigrams scores about 9-12, and one shared common word about 8, which is why the default sits at 9.' },
254
+ hint: { zh: '补注需要达到的相关度分数,是一个"更严/更松"的旋钮。真正的精度由下面「补注所需命中词数」把关:中文提问共享两个词大约得 9–12 分,默认 6;只共用「日志」这类一个常见词大约 8 分,因此单靠相关度是拦不住的。', en: 'Relevance a memory must reach to be injected on demand. This is a strictness knob; precision comes from the strong-term requirement below. A Chinese paraphrase sharing two bigrams scores about 9-12, and one shared common word about 8; default is 6.' },
255
255
  },
256
256
  {
257
257
  field: 'recallMaxPerConversation', kind: 'number', min: 0, step: 1,
@@ -281,7 +281,7 @@ window.__ModuleLoader__.load({
281
281
  {
282
282
  field: 'ragRecall', kind: 'boolean',
283
283
  label: { zh: '全量会话原文检索', en: 'Full-history raw retrieval' },
284
- hint: { zh: '把「补注带原始会话片段」的来源从「记忆来源会话」扩大到本机全部历史会话:按词法给每段原文打分,取最像的几条注入。零模型调用、只读本机日志。默认关闭,因为它会打开更多 session 日志。', en: 'Widens the raw channel from the memories\' source sessions to every persisted session: scores each passage lexically and injects the best few. Local-only, no model call. Off by default because it opens more session logs.' },
284
+ hint: { zh: '把「补注带原始会话片段」的来源从「记忆来源会话」扩大到本机全部历史会话:按词法给每段原文打分,取最像的几条注入。零模型调用、只读本机日志。默认开启(若需减少本地日志读取可关闭)。', en: 'Widens the raw channel from the memories\' source sessions to every persisted session: scores each passage lexically and injects the best few. Local-only, no model call. On by default; turn off to avoid scanning local session logs.' },
285
285
  },
286
286
  {
287
287
  field: 'ragRecallBytes', kind: 'number', min: 0, step: 100,
@@ -30,10 +30,10 @@ export const CONSOLIDATE_SYSTEM = [
30
30
  '- A problem that is already fixed is recorded as fixed ("已修 in <commit>"); never leave it reading as an open problem.',
31
31
  '- Write each body as 1-4 self-contained sentences. Titles are short and imperative.',
32
32
  '',
33
- 'When two or more memories together describe a repeatable procedure that would be worth running again, also return it as a skill: a short kebab-case name, a one-line description, and the ordered steps. Skills are drafts a human promotes; return at most 2.',
33
+ 'When two or more memories together describe a repeatable procedure that would be worth running again, also return it as a skill: a short kebab-case name, a one-line description, and the ordered steps. Skills are drafts a human promotes; return at most 2. If "Existing skill drafts" are listed in the input and one already covers the same workflow, either reuse its EXACT name to refine it or omit it — never invent a synonymous new skill name.',
34
34
  '',
35
35
  'When two memories contradict each other, do not quietly pick one: list the pair under "conflicts" with the id to keep, the id to drop, and one sentence saying what disagrees. A memory from the user ("voice: user") beats one the assistant concluded, and the newer statement beats the older — unless a rule is permanent, in which case name the pair and drop the OTHER one. "conflicts" is a report as much as an instruction: it is how the user finds out they changed their mind.',
36
- 'Also maintain "persona": a short profile of the USER, in markdown, built only from what they themselves said. The input marks those entries with "voice: user" and may include the current profile — refine it, do not rewrite it from nothing, and keep it under 40 lines. Contents: how they want work done, the corrections they have issued, how they write, what they care about, and what they never want. Write it in the third person ("他要求…"), never as instructions to yourself. If no entry carries voice: user, and no current profile exists, omit the field entirely.',
36
+ 'Also maintain "persona": a short profile of the USER, in markdown, built only from what they themselves said. The input marks those entries with "voice: user" and may include the current profile — refine it in place, do not rewrite it from nothing, deduplicate any repeated or near-identical bullets within each section (keep only the single sharpest version; never append a rephrased copy of an existing bullet), and keep it under 40 lines. Contents: how they want work done, the corrections they have issued, how they write, what they care about, and what they never want. Write it in the third person ("他要求…"), never as instructions to yourself. If no entry carries voice: user, and no current profile exists, omit the field entirely.',
37
37
  '',
38
38
  'Reply with JSON only, no prose and no code fence:',
39
39
  '{"memories":[{"id":string|null,"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"appliesTo":string,"derivedFrom":string[]}],"retire":[string],"skills":[{"name":string,"description":string,"steps":string[]}],"notes":string,"persona":string}',
@@ -104,7 +104,7 @@ export const CONSOLIDATE_JSON_SCHEMA = {
104
104
  },
105
105
  };
106
106
  /** Render the input document handed to the consolidation agent. */
107
- export function renderConsolidationInput(entries, projectLabel, currentPersona) {
107
+ export function renderConsolidationInput(entries, projectLabel, currentPersona, existingSkills) {
108
108
  const sections = new Map();
109
109
  for (const entry of entries) {
110
110
  const list = sections.get(entry.scope);
@@ -118,6 +118,13 @@ export function renderConsolidationInput(entries, projectLabel, currentPersona)
118
118
  blocks.push('## Current profile of the user (refine it; do not rewrite it from nothing)');
119
119
  blocks.push(currentPersona.trim(), '');
120
120
  }
121
+ if (existingSkills !== undefined && existingSkills.length > 0) {
122
+ blocks.push('## Existing skill drafts (reuse exact name to refine; never invent a synonymous new name)');
123
+ for (const skill of existingSkills) {
124
+ blocks.push(`- ${skill.name}${skill.description.length > 0 ? `: ${skill.description}` : ''}`);
125
+ }
126
+ blocks.push('');
127
+ }
121
128
  for (const scope of ['global', 'project']) {
122
129
  const list = sections.get(scope);
123
130
  if (list === undefined || list.length === 0)
@@ -433,7 +440,7 @@ export async function runConsolidation(seam, request) {
433
440
  if (request.entries.length === 0)
434
441
  return undefined;
435
442
  const known = new Set(request.entries.map((entry) => entry.id));
436
- const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona);
443
+ const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona, request.existingSkills);
437
444
  const timeout = AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
438
445
  const prompt = [{ type: 'text', text: `${CONSOLIDATE_SYSTEM}\n\n---\n\n${input}` }];
439
446
  const answer = await runChild(seam, prompt, request, timeout);
@@ -453,18 +460,17 @@ export async function runConsolidation(seam, request) {
453
460
  return plan;
454
461
  }
455
462
  /**
456
- * Build the spec the 0.2.1-rc.2 seam takes.
463
+ * Build the flattened `SubagentActivationSpec` the kernel seam takes.
457
464
  *
458
- * Extracted so a test can inspect it without a kernel: the one bug this shape
459
- * can carry — a missing `label` — is invisible from the seam's type unless the
460
- * type declares the field, and the failure it causes happens inside the
461
- * kernel's descriptor validator, three calls away from here. See
462
- * {@link ActivationSpec.label}.
465
+ * Extracted so a test can inspect it without a kernel: the kernel reads
466
+ * `provider`, `label`, `signal`, `delivery`, `prompt`, `parent`, `maxDepth`,
467
+ * `outputSchema`, `agentOptions`, and `agentPreset` at the top level.
463
468
  *
464
469
  * @param request - route, preset and lineage parent.
465
470
  * @param prompt - the child's single user message.
466
471
  * @param timeout - the child's deadline.
467
- * @returns the spec, with every optional field absent rather than `undefined`.
472
+ * @param outputSchema - JSON schema for structured output.
473
+ * @returns the flattened spec, with optional fields omitted rather than `undefined`.
468
474
  */
469
475
  export function buildActivationSpec(request, prompt, timeout, outputSchema = CONSOLIDATE_JSON_SCHEMA) {
470
476
  const agentOptions = request.provider !== undefined && request.model !== undefined
@@ -473,32 +479,18 @@ export function buildActivationSpec(request, prompt, timeout, outputSchema = CON
473
479
  return {
474
480
  provider: request.subagentProvider ?? 'spawn',
475
481
  // Never optional, never derived: a missing label fails the kernel's
476
- // descriptor validator BEFORE the child starts, and the symptom is a
477
- // silently dead consolidation pass rather than a start error.
482
+ // descriptor validator BEFORE the child starts.
478
483
  label: CONSOLIDATE_LABEL,
479
- // The result is consumed here, not by the parent conversation: a settlement
480
- // notice for this child is noise, and when the child misses
481
- // `structured_output` that notice reads as a failure even though the answer
482
- // arrived. See {@link ActivationSpec.delivery}.
484
+ // The result is consumed here, not by the parent conversation.
483
485
  delivery: 'caller',
484
- // Same class of mistake as the label, one field later: the kernel reads
485
- // `spec.signal` and never `spec.request.signal`, so it has to be here too.
486
486
  signal: timeout,
487
- request: {
488
- prompt,
489
- parent: request.parent,
490
- signal: timeout,
491
- ...agentOptions !== undefined ? { agentOptions } : {},
492
- outputSchema,
493
- // The child may not delegate further: it returns a plan, nothing else.
494
- //
495
- // `maxDepth` is the cap on the CHILD's depth, and DSH counts depth from
496
- // 1 (a top-level agent is 0, its child is 1). So 1 admits this child and
497
- // rejects any grandchild — 0 would reject the child itself, which is how
498
- // this line was wrong the first time.
499
- maxDepth: 1,
500
- ...request.agentPreset !== undefined ? { agentPreset: request.agentPreset } : {},
501
- },
487
+ prompt,
488
+ parent: request.parent,
489
+ ...agentOptions !== undefined ? { agentOptions } : {},
490
+ outputSchema,
491
+ // `maxDepth` caps the CHILD's depth (top-level agent is 0, child is 1).
492
+ maxDepth: 1,
493
+ ...request.agentPreset !== undefined ? { agentPreset: request.agentPreset } : {},
502
494
  };
503
495
  }
504
496
  /**
@@ -537,8 +529,13 @@ async function runChild(seam, prompt, request, timeout, outputSchema = CONSOLIDA
537
529
  : undefined;
538
530
  if (typeof seam.startActivation === 'function' && request.agentPreset !== undefined) {
539
531
  const run = await seam.startActivation(buildActivationSpec(request, prompt, timeout, outputSchema));
540
- const result = await run.result;
541
- return { text: textOf(result), ...stopReasonOf(result) };
532
+ try {
533
+ const result = await run.result;
534
+ return { text: textOf(result), ...stopReasonOf(result) };
535
+ }
536
+ finally {
537
+ await run.dispose?.().catch(() => undefined);
538
+ }
542
539
  }
543
540
  if (typeof seam.start === 'function') {
544
541
  const run = await seam.start('spawn', {
@@ -610,7 +607,7 @@ export async function runConsolidationDirect(llm, request) {
610
607
  if (route === undefined)
611
608
  return undefined;
612
609
  const known = new Set(request.entries.map((entry) => entry.id));
613
- const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona);
610
+ const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona, request.existingSkills);
614
611
  const messages = [createUserMessage({
615
612
  content: [{ type: 'text', text: input }],
616
613
  source: { kind: MEMORY_SOURCE_KIND },
@@ -629,17 +626,22 @@ export async function runConsolidationDirect(llm, request) {
629
626
  const assembler = new BlockAssembler();
630
627
  for await (const chunk of llm.stream(options))
631
628
  assembler.push(chunk);
629
+ const finish = assembler.finish;
630
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
631
+ request.onSkip?.(`the model call failed (${finish.kind}: ${finish.failure.message})`);
632
+ return undefined;
633
+ }
632
634
  const text = assembler.blocks()
633
635
  .filter((block) => block.type === 'text')
634
636
  .map((block) => block.text)
635
637
  .join('\n');
636
638
  if (text.trim().length === 0) {
637
- request.onSkip?.('the model returned an empty reply');
639
+ request.onSkip?.(`the model returned an empty reply (finish: ${finish.kind})`);
638
640
  return undefined;
639
641
  }
640
642
  const plan = parsePlan(text, known, request.maxUpserts);
641
643
  if (plan === undefined)
642
- request.onSkip?.(`the model's reply carried no plan (${text.length} chars)`);
644
+ request.onSkip?.(`the model's reply carried no plan (${text.length} chars, finish: ${finish.kind})`);
643
645
  return plan;
644
646
  }
645
647
  /**