dsh-plugin-tool-management 0.22.4 → 0.22.6

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 (73) hide show
  1. package/CHANGELOG.md +1624 -1395
  2. package/README.md +194 -177
  3. package/README_EN.md +194 -177
  4. package/docs/ARCHITECTURE.md +137 -0
  5. package/docs/COMPATIBILITY.md +112 -0
  6. package/docs/TROUBLESHOOTING.md +287 -0
  7. package/lib/client.js +14984 -12279
  8. package/lib/compat/capability-specs.js +66 -16
  9. package/lib/compat/host-contracts.js +14 -3
  10. package/lib/compat/host-roots.js +1 -1
  11. package/lib/compat/manual-review.js +1 -1
  12. package/lib/compat/preset-reach.js +1 -1
  13. package/lib/compat/probe.js +96 -11
  14. package/lib/confirm-gate.js +40 -6
  15. package/lib/context-inject-contract.js +31 -14
  16. package/lib/context-inject-delta.js +146 -0
  17. package/lib/context-inject-frame.js +38 -19
  18. package/lib/context-inject-select.js +33 -4
  19. package/lib/context-inject-surface.js +74 -22
  20. package/lib/context-inject.js +107 -15
  21. package/lib/evolution/cold.js +389 -0
  22. package/lib/evolution/config.js +507 -0
  23. package/lib/evolution/digest.js +48 -0
  24. package/lib/evolution/episodes.js +287 -0
  25. package/lib/evolution/evidence.js +167 -0
  26. package/lib/evolution/gates.js +874 -0
  27. package/lib/evolution/limits.js +21 -0
  28. package/lib/evolution/maintenance.js +516 -0
  29. package/lib/evolution/notes.js +328 -0
  30. package/lib/evolution/organize.js +118 -0
  31. package/lib/evolution/review.js +524 -0
  32. package/lib/evolution/route.js +91 -0
  33. package/lib/evolution/runtime.js +179 -0
  34. package/lib/evolution/scope-card.js +144 -0
  35. package/lib/evolution/state.js +514 -0
  36. package/lib/evolution/write.js +1773 -0
  37. package/lib/imports/unzip.js +144 -26
  38. package/lib/index.js +1371 -79
  39. package/lib/legacy-tool-names.js +19 -4
  40. package/lib/mcp/manager.js +1 -0
  41. package/lib/mcp/tool-visibility.js +204 -11
  42. package/lib/memories/catalog.js +215 -0
  43. package/lib/memories/constants.js +115 -7
  44. package/lib/memories/discovery.js +59 -25
  45. package/lib/memories/projection.js +116 -31
  46. package/lib/memories/render-auto.js +198 -0
  47. package/lib/memories/search.js +3 -5
  48. package/lib/memories/service.js +252 -17
  49. package/lib/memories/snapshot.js +174 -23
  50. package/lib/op-registry.js +59 -0
  51. package/lib/ops/compat.js +2 -0
  52. package/lib/ops/evolution.js +887 -0
  53. package/lib/ops/memory.js +95 -72
  54. package/lib/ops/trash.js +14 -2
  55. package/lib/prompts/service.js +30 -0
  56. package/lib/scope/workspace-key.js +39 -0
  57. package/lib/settings-sidecars.js +2 -2
  58. package/lib/skills/dir-watch.js +49 -22
  59. package/lib/skills/official.js +180 -36
  60. package/lib/skills/service.js +2 -2
  61. package/lib/subagents/run-provider.js +35 -22
  62. package/lib/text-width.js +59 -0
  63. package/lib/tool-table-switch.js +104 -16
  64. package/lib/tools/control.js +45 -12
  65. package/lib/tools/deps.js +2 -2
  66. package/lib/tools/mcp.js +6 -4
  67. package/lib/tools/memory.js +1045 -267
  68. package/lib/tools/note-ref.js +20 -0
  69. package/lib/tools/remove.js +1 -1
  70. package/lib/tools/scene.js +3 -3
  71. package/lib/tools/table.js +76 -20
  72. package/package.json +155 -152
  73. package/docs/UPDATE.md +0 -49
@@ -0,0 +1,524 @@
1
+ // 复习器(冷路径的第二段):宿主压缩上下文时,把那份 checkpoint 过一遍,挑出值得记的几条。
2
+ //
3
+ // 为什么值得多花一次模型调用:热路径(`memory_note`)靠模型在对话中"顺手"记,但它正忙着
4
+ // 解决用户的问题,注意力不在"这句话以后还用得上吗"。压缩时宿主已经把整段对话交给模型提炼
5
+ // 成结构化摘要 —— 那是信息密度最高、且已经付过钱的产物,同一个模型再读一遍它的判断质量
6
+ // 完全不同。这也是 Claude Code / Codex 那类 harness 的做法:记忆不是对话的副产品,
7
+ // 是**独立工序**。
8
+ //
9
+ // 三条纪律:
10
+ // 1. **严格 JSON**:只接受白名单字段;解析不出来按可恢复失败走退避重试(不占学习名额)。
11
+ // 逐条过九道门,复习器不是后门。
12
+ // 2. **成本上限**:每会话最多 `maxReviewsPerSession` 次**成功**复习。超了直接跳过并在
13
+ // outbox 记原因 —— 失败 / 超时 / 环境未就绪都不占名额,失控由 outbox 的退避兜住。
14
+ // 3. **失败不阻塞会话**:这里的所有异常都吞掉并写日志。用户不该因为记忆整理失败
15
+ // 看到报错,更不该等它。
16
+ import { readFile } from 'node:fs/promises';
17
+ import { mkdir } from 'node:fs/promises';
18
+ import { dirname } from 'node:path';
19
+ import { writeFileAtomically } from '../memories/index-io.js';
20
+ import { MAX_AUTO_TITLE_WIDTH } from './write.js';
21
+ import { truncateToWidth } from '../text-width.js';
22
+ import { normalizeNoteStyle, noteStyleGuideOf } from './config.js';
23
+ /** 一次复习最多落几条。多了就是在把摘要改写成记忆库,那不是复习。 */
24
+ export const MAX_ITEMS_PER_REVIEW = 3;
25
+ /**
26
+ * 单次请求的输出上限(token)。
27
+ *
28
+ * 必须装得下 `MAX_ITEMS_PER_REVIEW` 条**满配**正文:一条 2400 显示单位 ≈ 1200 汉字,
29
+ * 三条中文正文加上 JSON 包装就已经超过 3600 —— 那时输出被截断,`extractJson` 解析不出来,
30
+ * 整批按 `bad-json` 重试到死信。6000 留了足够的余量。
31
+ *
32
+ * 跟随 `MAX_AUTO_TEXT_WIDTH` 调整:改那个上限就要一起重算这里,否则长笔记会在复习这条路上
33
+ * 静默变成"永远重试失败"。
34
+ */
35
+ const MAX_OUTPUT_TOKENS = 6000;
36
+ /** 单次请求的超时。超了就按失败处理,下一轮再试。 */
37
+ const REVIEW_TIMEOUT_MS = 45_000;
38
+ const KINDS = new Set(['preference', 'fact', 'correction', 'procedure']);
39
+ const LAYERS = new Set(['global', 'workspace', 'scene', 'session']);
40
+ /**
41
+ * 从模型输出里抽出 JSON 对象。
42
+ *
43
+ * 三种常见形态都要认:整段就是 JSON、包在 ```json 里、前后带一句人话。
44
+ * 用"第一个 { 到最后一个 }"而不是正则匹配平衡括号:模型的 JSON 里可能有嵌套对象,
45
+ * 正则数不准;而多截一段的后果只是 JSON.parse 失败,与直接放弃等价。
46
+ */
47
+ export function extractJson(text) {
48
+ const s = String(text ?? '').trim();
49
+ if (s === '')
50
+ return null;
51
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(s);
52
+ const candidates = [fenced ? fenced[1] : s];
53
+ const first = s.indexOf('{');
54
+ const last = s.lastIndexOf('}');
55
+ if (first >= 0 && last > first)
56
+ candidates.push(s.slice(first, last + 1));
57
+ for (const c of candidates) {
58
+ try {
59
+ return JSON.parse(c.trim());
60
+ }
61
+ catch {
62
+ /* 试下一个 */
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+ /**
68
+ * 校验并裁剪模型给的条目。
69
+ *
70
+ * **越界字段直接丢,不整批拒**:一条写错了 kind 不该让另外两条也白跑。
71
+ * 缺 `text` 的条目要丢 —— 那是写入管线的必填项,补不出来。
72
+ */
73
+ export function parseReviewItems(raw) {
74
+ const box = raw && typeof raw === 'object' ? raw : {};
75
+ const list = Array.isArray(box.memories) ? box.memories : Array.isArray(box.items) ? box.items : [];
76
+ const out = [];
77
+ for (const row of list) {
78
+ if (out.length >= MAX_ITEMS_PER_REVIEW)
79
+ break;
80
+ if (!row || typeof row !== 'object')
81
+ continue;
82
+ const r = row;
83
+ // 正文**不在这里截**:超限交给写入管线拒(`too-long`),与热路径同一条规矩。
84
+ // 在这里截会存下一句被腰斩的话,而用户看不到任何提示 —— 那正是本版修掉的
85
+ // 「静默截断」。截断只留给展示字段(标题)。
86
+ const text = typeof r.text === 'string' ? r.text.trim() : '';
87
+ if (text === '')
88
+ continue;
89
+ const item = { text };
90
+ const title = typeof r.title === 'string' ? truncateToWidth(r.title.trim(), MAX_AUTO_TITLE_WIDTH) : '';
91
+ if (title !== '')
92
+ item.title = title;
93
+ if (typeof r.kind === 'string' && KINDS.has(r.kind))
94
+ item.kind = r.kind;
95
+ if (typeof r.quote === 'string' && r.quote.trim() !== '')
96
+ item.quote = r.quote.trim().slice(0, 2000);
97
+ if (typeof r.key === 'string' && r.key.trim() !== '')
98
+ item.key = r.key.trim().slice(0, 80);
99
+ if (typeof r.boundary === 'string' && r.boundary.trim() !== '')
100
+ item.boundary = r.boundary.trim().slice(0, 500);
101
+ if (typeof r.layer === 'string' && LAYERS.has(r.layer))
102
+ item.layer = r.layer;
103
+ if (typeof r.ttlDays === 'number' && Number.isFinite(r.ttlDays) && r.ttlDays > 0)
104
+ item.ttlDays = Math.min(3650, Math.floor(r.ttlDays));
105
+ out.push(item);
106
+ }
107
+ return out;
108
+ }
109
+ /**
110
+ * 拼复习用的 prompt。
111
+ *
112
+ * 压缩触发的复习只读官方 checkpoint;旧版按轮次排队的 episode 兼容旧渲染(盘上可能还有)。
113
+ * checkpoint 是模型转述,不是用户原话 —— 这里不给它「逐字」的标签,证据门也不会把它
114
+ * 当成引句来源。
115
+ */
116
+ export function buildReviewPrompt(episode, catalogLines) {
117
+ // 上限比旧版宽:清单里现在混着用户记忆与全局指令文件,截到 80 行会让后加的自主笔记
118
+ // 整段消失,而「别重复」恰恰最需要它们。
119
+ const known = catalogLines.slice(0, 160);
120
+ const lines = [];
121
+ if (typeof episode.checkpoint === 'string' && episode.checkpoint.trim() !== '') {
122
+ lines.push('## Host-compiled checkpoint (a summary written by another model, not the user\'s words)');
123
+ lines.push(episode.checkpoint);
124
+ }
125
+ else {
126
+ const users = episode.userTexts.slice(-6);
127
+ const tools = episode.events
128
+ .filter((e) => e.kind === 'tool')
129
+ .slice(-8)
130
+ .map((e) => '- ' + String(e.tool || 'tool') + (e.ok === false ? ' (failed)' : '') + (e.text ? ': ' + e.text.slice(0, 200) : ''));
131
+ lines.push('## 这一轮用户说的话(逐字,不要改写)');
132
+ lines.push(users.length ? users.map((t, i) => `[${i}] ${t.slice(0, 1500)}`).join('\n') : '(none)');
133
+ if (tools.length) {
134
+ lines.push('', '## 这一轮用到的工具');
135
+ lines.push(tools.join('\n'));
136
+ }
137
+ }
138
+ // 标题点名「已经在上下文里」而不只是「已经记住」:清单里除了自主记忆,还有用户手写的
139
+ // 记忆与全局指令文件的摘录 —— 它们本来就会注入每一次对话,再学一遍就是同一句话在上下文
140
+ // 里出现两次,还多一条要维护的副本。
141
+ lines.push('', '## 已经记住 / 已经在上下文里的东西(不要重复记)');
142
+ lines.push(known.length ? known.map((x) => '- ' + x).join('\n') : '(nothing yet)');
143
+ lines.push('', '## 输出');
144
+ lines.push('只输出 JSON,不要解释。没有值得记的就返回 {"memories":[]}。');
145
+ return lines.join('\n');
146
+ }
147
+ /**
148
+ * 压缩复习专用:checkpoint 里大半是「接着干活」的任务态,只有这一小类跨会话成立。
149
+ *
150
+ * 最后一句是**去重**的一半:清单里已经列了用户手写记忆与全局指令文件的摘录,它们每一次
151
+ * 对话都会注入。不点名这件事,模型会照着 checkpoint 里的说法再写一条几乎一样的笔记
152
+ * (真实数据:「gh cli已经登录」被重学成「GitHub CLI 已登录」)。
153
+ */
154
+ const CHECKPOINT_FILTER = [
155
+ 'The input is a host-compiled conversation checkpoint meant for resuming the current task, not for long-term memory.',
156
+ 'Keep ONLY what will still be true in a different conversation: user preferences, corrections of your behaviour, durable constraints, project facts that cannot be read from the code, and repeatable procedures.',
157
+ 'DISCARD everything task-local: Current Work, Next Step, Pending Jobs, Files and Code, Errors and Fixes, file paths, commands, error strings, dependency versions, and one-off instructions.',
158
+ 'The checkpoint is a paraphrase, not the user\'s words: never invent a `quote`. Leave it out entirely.',
159
+ 'The list at the end of the user message holds what is ALREADY in every conversation (the user\'s own memories and their global instructions, not just earlier notes). Do not restate any of it in other words — only add what that list does not already say. Saying the same thing with different wording is still a duplicate: the write path compares wording, not meaning, so it will not catch it for you.',
160
+ ].join(' ');
161
+ /** 旧版按轮次复习的提示:那份 episode 里是用户逐字原话,可以要求引句核对。 */
162
+ const TURN_SYSTEM_PROMPT = [
163
+ 'You extract durable memories from one finished conversation turn.',
164
+ 'Record only what will still matter in a different conversation: a stated preference, a correction of your behaviour, a project fact that cannot be read from the code, or a repeatable procedure.',
165
+ 'Do NOT record: one-off instructions ("this time", "for now"), anything derivable from package.json / config / git, or your own reasoning.',
166
+ 'For every item, `quote` must be an exact substring of what the user said in this turn. Do not paraphrase it.',
167
+ '`layer`: "global" only when it applies to every project or to the user personally; otherwise "workspace". Always pass it.',
168
+ 'Write every `text` in the user\'s language.',
169
+ 'Give every item a short `title` (2-8 words) in the user\'s language; it becomes the row name.',
170
+ 'At most 3 items. When in doubt, return fewer — a wrong memory is injected into every later conversation.',
171
+ 'The list at the end holds what is already in every conversation. Do not restate it in other words: the write path compares wording, not meaning, so a paraphrase will not be caught as a duplicate.',
172
+ // 与压缩那条**同一套判据**:两条路径都要求输出 `kind`,只给其中一条判据等于让另一条按字面猜。
173
+ // `kind` 决定保质期(见 `ttlDaysOf`):`fact` / `procedure` 30 天后提醒复核,
174
+ // `preference` / `correction` 不过期。猜错方向的代价不对称 —— 做法被判成偏好会永久驻留,
175
+ // 纠正被判成事实会在一个月后自己消失。
176
+ '`kind` decides how long the note lives, so pick by what the sentence IS:',
177
+ '- `preference` — how you should behave or answer (tone, format, language, what to avoid).',
178
+ '- `correction` — the user fixing a mistake you already made; it names no reusable method.',
179
+ '- `fact` — something true about this project or machine that cannot be read from the code.',
180
+ '- `procedure` — a repeatable way of doing something ("when X, do Y first").',
181
+ 'If it tells you how to act in a future situation, it is `procedure`, not `correction`.',
182
+ 'Output strict JSON: {"memories":[{"title":"Reply style","text":"the note","kind":"preference|fact|correction|procedure","quote":"exact user words","key":"kebab-case-slot","layer":"workspace","boundary":"when it might not hold"}]}',
183
+ ].join('\n');
184
+ /** 系统提示按 episode 来源分叉:压缩那份必须明确排除任务态章节。 */
185
+ export function reviewSystemPromptFor(episode, cfg) {
186
+ const style = normalizeNoteStyle({
187
+ style: cfg.noteStyle,
188
+ customStyles: cfg.customNoteStyles,
189
+ custom: cfg.noteStyleText,
190
+ });
191
+ const guide = noteStyleGuideOf(style.style, style.customStyles);
192
+ const base = typeof episode.checkpoint === 'string' && episode.checkpoint.trim() !== ''
193
+ ? CHECKPOINT_FILTER + '\n' + [
194
+ '`layer`: "global" only when it applies to every project or to the user personally; otherwise "workspace". Always pass it.',
195
+ 'Write every `text` in the user\'s language. Give every item a short `title` (2-8 words).',
196
+ 'At most 3 items. When in doubt, return fewer — a wrong memory is injected into every later conversation.',
197
+ // `kind` 决定保质期(见 `ttlDaysOf`):`fact` / `procedure` 30 天后提醒复核,
198
+ // `preference` / `correction` 不过期。不给判据时模型会按字面猜 —— 真实数据里
199
+ // 「必须重开子代理时先把结论写成简报」被标成 `correction`,于是一条会过期的做法
200
+ // 永久留在每次对话的上下文里。这里只说四者的分界,不重复上面已说的取舍。
201
+ '`kind` decides how long the note lives, so pick by what the sentence IS:',
202
+ '- `preference` — how you should behave or answer (tone, format, language, what to avoid).',
203
+ '- `correction` — the user fixing a mistake you already made; it names no reusable method.',
204
+ '- `fact` — something true about this project or machine that cannot be read from the code.',
205
+ '- `procedure` — a repeatable way of doing something ("when X, do Y first").',
206
+ 'If it tells you how to act in a future situation, it is `procedure`, not `correction`.',
207
+ 'Output strict JSON: {"memories":[{"title":"Reply style","text":"the note","kind":"preference|fact|correction|procedure","key":"kebab-case-slot","layer":"workspace","boundary":"when it might not hold"}]}',
208
+ ].join('\n')
209
+ : TURN_SYSTEM_PROMPT;
210
+ return guide === '' ? base : base + '\nWrite every `text` field in this style: ' + guide;
211
+ }
212
+ /**
213
+ * 预算记录保留多久。
214
+ *
215
+ * 这个文件是「每个会话还能复习几次」的账本,键是会话 id —— 而会话本身会不断新建。
216
+ * 不清的话它只增不减:真实环境里十几天就攒了十几个会话,长年使用会到几千条。
217
+ *
218
+ * 30 天足够覆盖任何还在活跃的会话;超期的记录即使留着也没有意义 —— 那个会话的
219
+ * 复习配额早已用不完,而清掉最多让它重新拥有一次配额(多花一次钱,不会少复习)。
220
+ */
221
+ const BUDGET_RETENTION_DAYS = 30;
222
+ /** 丢掉超期的会话记录;返回清理后的账本(没有变化时原样返回同一个对象)。 */
223
+ function pruneBudget(file, now = Date.now()) {
224
+ const keys = Object.keys(file.sessions);
225
+ const kept = {};
226
+ let dropped = 0;
227
+ for (const key of keys) {
228
+ const at = Date.parse(String(file.sessions[key]?.at ?? ''));
229
+ // 时间戳读不出来时**保留**:删掉一条活会话的记录会让它重新拥有整份配额。
230
+ if (Number.isFinite(at) && now - at > BUDGET_RETENTION_DAYS * 86400_000) {
231
+ dropped++;
232
+ continue;
233
+ }
234
+ kept[key] = file.sessions[key];
235
+ }
236
+ return dropped === 0 ? file : { sessions: kept };
237
+ }
238
+ /** 读一次预算文件;读不到 / 坏了都按空库(计数丢失只会多花一次钱,不会少复习)。 */
239
+ async function readBudget(path) {
240
+ try {
241
+ const raw = JSON.parse(await readFile(path, 'utf8'));
242
+ return raw && typeof raw === 'object' && raw.sessions && typeof raw.sessions === 'object'
243
+ ? { sessions: raw.sessions }
244
+ : { sessions: {} };
245
+ }
246
+ catch {
247
+ return { sessions: {} };
248
+ }
249
+ }
250
+ export function createReviewBudget(deps) {
251
+ let cache = null;
252
+ let loading = null;
253
+ async function load() {
254
+ if (cache)
255
+ return cache;
256
+ if (loading)
257
+ return loading;
258
+ loading = (async () => {
259
+ cache = await readBudget(deps.path);
260
+ return cache;
261
+ })();
262
+ return loading;
263
+ }
264
+ async function save(next) {
265
+ cache = next;
266
+ try {
267
+ await mkdir(dirname(deps.path), { recursive: true });
268
+ await writeFileAtomically(deps.path, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
269
+ }
270
+ catch {
271
+ /* 计数器写不进去不该挡住复习本身:下一次会重算,最多多花一次钱。 */
272
+ }
273
+ }
274
+ return {
275
+ async remaining(session, max) {
276
+ const file = await load();
277
+ const hit = file.sessions[session];
278
+ const used = hit ? Math.max(0, Number(hit.count) || 0) : 0;
279
+ // 0 是合法值(用户把每会话次数设成 0 = 不复习),不再夹到至少 1 次。
280
+ const cap = Math.max(0, Math.round(max ?? deps.max));
281
+ return Math.max(0, cap - used);
282
+ },
283
+ async spend(session) {
284
+ // **每次都以磁盘为准**,不要用 `load()` 的内存缓存做读-改-写。
285
+ //
286
+ // 预算是"这次还能不能花钱"的唯一闸门:缓存 + 整份写回会在两个会话并发复习时互相
287
+ // 覆盖计数,实际花费能超过 `maxReviewsPerSession`。这里重新读一次文件再写,把窗口
288
+ // 从"整个进程生命周期"压到"一次读+一次写"。
289
+ //
290
+ // 不引入跨进程文件锁:漏计一次最多多花一次钱,而锁本身在热路径上失败会让复习
291
+ // 整体停摆 —— 代价不对等。
292
+ const fresh = await readBudget(deps.path);
293
+ const hit = fresh.sessions[session];
294
+ const now = Date.now();
295
+ // 顺手清掉超期会话:这个文件只增不减,而键是不断新建的会话 id。
296
+ const pruned = pruneBudget(fresh, now);
297
+ const next = {
298
+ sessions: {
299
+ ...pruned.sessions,
300
+ [session]: { count: (hit ? Math.max(0, Number(hit.count) || 0) : 0) + 1, at: new Date(now).toISOString() },
301
+ },
302
+ };
303
+ await save(next);
304
+ },
305
+ };
306
+ }
307
+ /** 把一段流式输出收成一个字符串(只取 text-delta)。 */
308
+ async function collectText(stream) {
309
+ let out = '';
310
+ for await (const chunk of stream) {
311
+ if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string')
312
+ out += chunk.text;
313
+ }
314
+ return out;
315
+ }
316
+ export function createReviewer(deps) {
317
+ return {
318
+ async review(episode, cfg, liveRoute) {
319
+ const llm = deps.llm;
320
+ if (!llm || typeof llm.prepareCall !== 'function') {
321
+ return { ok: false, learned: 0, rejected: 0, reason: 'no-llm', error: '宿主没有提供 llm 服务' };
322
+ }
323
+ const left = await deps.budget.remaining(episode.session, cfg.maxReviewsPerSession);
324
+ if (left <= 0) {
325
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-skipped', reason: 'budget' });
326
+ return { ok: false, learned: 0, rejected: 0, reason: 'budget' };
327
+ }
328
+ // 配置里显式指定模型时优先(`provider/model` 或只有 model);否则用这一轮
329
+ // 对话正在用的那个 —— 默认换模型会让"学到的风格"和"对话的风格"不一致。
330
+ const route = routeOf(cfg.model, liveRoute ?? null);
331
+ if (!route) {
332
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-skipped', reason: 'no-model' });
333
+ return { ok: false, learned: 0, rejected: 0, reason: 'no-model', error: '拿不到这一轮的模型路由' };
334
+ }
335
+ // 「学习次数」只在复习成功跑完后记一次;失败 / 坏 JSON 走重试,不占名额。
336
+ // 失控由 outbox 的 attempts(三次进 dead)兜住,不靠把失败算成一次学习。
337
+ const isCheckpoint = typeof episode.checkpoint === 'string' && episode.checkpoint.trim() !== '';
338
+ let text = '';
339
+ /** 失败时记进日志的派发形状;成功路径不读它。 */
340
+ let dispatchShape;
341
+ const ac = new AbortController();
342
+ const timer = setTimeout(() => ac.abort(), REVIEW_TIMEOUT_MS);
343
+ try {
344
+ // 输出上限必须进 `prepareCall`:宿主会把适配器的默认 maxTokens 补进
345
+ // `prepared.config`(`dsh-llm-deepseek` 恒有 `defaultMaxTokens`),而 `prepared.stream`
346
+ // 会用 `callConfigEquals` 逐字段比对调用方传的配置与它,不一致直接抛
347
+ // `INVALID_PREPARED_CALL` —— 把上限放到 dispatch 那一侧,后台复习每次都失败。
348
+ const prepared = await llm.prepareCall({
349
+ provider: route.provider,
350
+ model: route.model,
351
+ temperature: 0,
352
+ maxTokens: MAX_OUTPUT_TOKENS,
353
+ });
354
+ const catalogLines = await deps.catalogLines();
355
+ const dispatchOptions = {
356
+ ...prepared.config,
357
+ messages: [{ role: 'user', content: [{ type: 'text', text: buildReviewPrompt(episode, catalogLines) }] }],
358
+ system: reviewSystemPromptFor(episode, cfg),
359
+ signal: ac.signal,
360
+ };
361
+ // 只在失败时用:宿主逐字段比对派发配置与 `prepared.config`,而它的错误信息
362
+ // 不带任何字段值。这份快照让日志能直接指出是哪个字段变了。
363
+ dispatchShape = {
364
+ sent: pickCallConfig(dispatchOptions),
365
+ prepared: pickCallConfig(prepared.config),
366
+ };
367
+ const stream = prepared.stream(dispatchOptions);
368
+ text = await collectText(stream);
369
+ }
370
+ catch (e) {
371
+ // 把派发时的配置快照记下来:宿主只在**字段不一致**时抛
372
+ // `INVALID_PREPARED_CALL`,而错误信息不带任何一个字段值 —— 没有这份快照,
373
+ // 日志里只剩一句「config changed」,谁也无法判断是 provider / model /
374
+ // reasoningEffort / temperature / maxTokens / stop 里的哪一个被改了。
375
+ //
376
+ // 只记这六个参与比对的字段(见官方 `callConfigEquals`):消息正文与 system
377
+ // 不进日志,那里有用户原文。
378
+ await deps.log({
379
+ at: new Date().toISOString(),
380
+ session: episode.session,
381
+ turn: episode.turn,
382
+ event: 'review-failed',
383
+ error: deps.message(e),
384
+ ...(dispatchShape !== undefined ? { dispatch: dispatchShape } : {}),
385
+ });
386
+ return { ok: false, learned: 0, rejected: 0, error: deps.message(e) };
387
+ }
388
+ finally {
389
+ clearTimeout(timer);
390
+ }
391
+ const parsed = extractJson(text);
392
+ if (parsed === null) {
393
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-bad-json', chars: text.length });
394
+ return { ok: false, learned: 0, rejected: 0, reason: 'bad-json' };
395
+ }
396
+ const items = parseReviewItems(parsed);
397
+ if (items.length === 0) {
398
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-empty' });
399
+ await deps.budget.spend(episode.session);
400
+ return { ok: true, learned: 0, rejected: 0 };
401
+ }
402
+ let learned = 0;
403
+ let rejected = 0;
404
+ const learnedItems = [];
405
+ for (const item of items) {
406
+ try {
407
+ const r = await deps.learner.learn({
408
+ text: item.text,
409
+ ...(item.title !== undefined ? { title: item.title } : {}),
410
+ ...(item.kind !== undefined ? { kind: item.kind } : {}),
411
+ ...(item.key !== undefined ? { key: item.key } : {}),
412
+ // checkpoint 是转述,不是用户原话:**不带引句**,门禁自然按推断处理。
413
+ // 带上了会走引句核对,核不上是硬拒 —— 而它本来就不可能逐字对上。
414
+ ...(!isCheckpoint && item.quote !== undefined ? { quote: item.quote } : {}),
415
+ ...(item.layer !== undefined ? { layer: item.layer } : {}),
416
+ ...(item.boundary !== undefined ? { boundary: item.boundary } : {}),
417
+ ...(item.ttlDays !== undefined ? { ttlDays: item.ttlDays } : {}),
418
+ // 后台没有人可弹卡,所以「要不要直接生效」跟随用户自己的授权:
419
+ // `autoConfirm` 开着 = 用户已同意由 agent 决定,直接落 active;
420
+ // 关着(默认)= 落候选,在记忆页逐条确认。
421
+ //
422
+ // 这里**不能恒为 true**:复习的输入是另一个模型写的转述,未经任何人过目就进入
423
+ // 之后每一次对话的上下文,与「没卡片时仍待确认」的承诺直接冲突。两种情况都
424
+ // 越不过用户手写记忆的冲突(门禁里 `user-conflict` 永远等用户裁决)。
425
+ ...(cfg.autoConfirm === true ? { autoActive: true } : {}),
426
+ }, cfg, {
427
+ sessionId: episode.session,
428
+ ...(episode.workspaceHash !== undefined ? { workspaceHash: episode.workspaceHash } : {}),
429
+ });
430
+ if (r.ok) {
431
+ learned++;
432
+ // 测试替身可能只返回 `{ok:true}`;没有 id 就不记摘要,不能因为展示字段缺失
433
+ // 让一次已经成功的复习在记账时抛异常。
434
+ if (typeof r.id === 'string' && r.id !== '') {
435
+ learnedItems.push({
436
+ id: r.id,
437
+ ...(item.title !== undefined ? { title: item.title } : {}),
438
+ text: item.text,
439
+ layer: String(r.layer ?? ''),
440
+ status: String(r.status ?? ''),
441
+ tier: String(r.tier ?? 'inferred'),
442
+ ...(typeof r.kind === 'string' ? { kind: r.kind } : {}),
443
+ });
444
+ }
445
+ }
446
+ else {
447
+ rejected++;
448
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-rejected', code: r.code, gate: r.gate });
449
+ }
450
+ }
451
+ catch (e) {
452
+ rejected++;
453
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-item-failed', error: deps.message(e) });
454
+ }
455
+ }
456
+ await deps.budget.spend(episode.session);
457
+ await deps.log({ at: new Date().toISOString(), session: episode.session, turn: episode.turn, event: 'review-done', learned, rejected });
458
+ return { ok: true, learned, rejected, ...(learnedItems.length > 0 ? { items: learnedItems } : {}) };
459
+ },
460
+ };
461
+ }
462
+ /**
463
+ * 参与宿主比对的六个字段(官方 `callConfigEquals` 逐字段比这一组)。
464
+ *
465
+ * 抽出来是为了让失败日志能直接指出差异:`undefined` 也保留成显式的 `null`,
466
+ * 否则 JSON 序列化会把键整个丢掉,"没这个字段"与"值是 undefined"就看不出区别。
467
+ */
468
+ function pickCallConfig(c) {
469
+ const out = {};
470
+ for (const key of ['provider', 'model', 'reasoningEffort', 'temperature', 'maxTokens', 'stop']) {
471
+ const v = c[key];
472
+ out[key] = v === undefined ? null : Array.isArray(v) ? [...v] : v;
473
+ }
474
+ return out;
475
+ }
476
+ /** `cfg.model` 支持 `provider/model` 与裸 model(provider 沿用会话的)。 */
477
+ function routeOf(configured, fallback) {
478
+ const raw = String(configured ?? '').trim();
479
+ if (raw !== '') {
480
+ const slash = raw.indexOf('/');
481
+ if (slash > 0 && slash < raw.length - 1)
482
+ return { provider: raw.slice(0, slash), model: raw.slice(slash + 1) };
483
+ if (fallback)
484
+ return { provider: fallback.provider, model: raw };
485
+ return null;
486
+ }
487
+ return fallback;
488
+ }
489
+ /**
490
+ * 供冷路径判断"这次复习要不要重试"。纯函数,好测。
491
+ *
492
+ * 三档退避 1 / 5 / 30 分钟;第 4 次才进 dead-letter —— 档位与 dead 的界要**错开一位**,
493
+ * 否则 30 分钟那一档永远用不到(`attempts === 3` 时就死了)。
494
+ */
495
+ export function nextRetryAt(attempts, now = Date.now()) {
496
+ const delays = [60_000, 5 * 60_000, 30 * 60_000];
497
+ const idx = Math.max(0, Math.min(delays.length - 1, attempts - 1));
498
+ return now + delays[idx];
499
+ }
500
+ /** 一次复习失败后还能再试几次(与 `nextRetryAt` 的档位数一致)。 */
501
+ export const MAX_REVIEW_ATTEMPTS = 3;
502
+ /**
503
+ * 失败后的补丁。
504
+ *
505
+ * `now` 与 `episodes.retryable` 用的是同一个时钟:两边各取一次 `Date.now()` 会在边界上
506
+ * 出现"刚写下的 nextAt 已经过期"或"要等到下次才过期"的抖动,重试判定就变得不可复现。
507
+ *
508
+ * `transient` 是**环境还没就绪**(拿不到模型路由 / 宿主没给 llm 服务):那不是这次复习的
509
+ * 错,重试次数不该被它烧掉 —— 启动重放时路由表必然是空的,按失败计数的话重启三次,
510
+ * 任何残留项都会在真正跑过一次之前就进 dead-letter。
511
+ */
512
+ export function outboxFailed(item, error, now = Date.now(), opts = {}) {
513
+ if (opts.transient === true) {
514
+ // 不增 attempts:保持 pending,等下一次触发(新压缩 / 重启 / 手动重放)。
515
+ // `immediate` 清掉退避(显式写 undefined —— `mark` 是合并写入,不给这个键会沿用旧值):
516
+ // 这一项的触发条件已经就绪(路由刚记上),再等一分钟只是白拖。
517
+ const wait = opts.immediate === true ? { nextAt: undefined } : { nextAt: nextRetryAt(1, now) };
518
+ return { status: 'pending', attempts: item.attempts ?? 0, reason: error, ...wait };
519
+ }
520
+ const attempts = (item.attempts ?? 0) + 1;
521
+ if (attempts > MAX_REVIEW_ATTEMPTS)
522
+ return { status: 'dead', attempts, reason: error };
523
+ return { status: 'failed', attempts, reason: error, nextAt: nextRetryAt(attempts, now) };
524
+ }
@@ -0,0 +1,91 @@
1
+ // 写入路由:一条自动记忆该落在哪一层。
2
+ //
3
+ // 三个轴是正交的:`layer` 是数据属性(谁能看见),`origin` 是谁写的,`allowed` 是策略
4
+ // (哪几层允许写)。本文件只算 `layer`;「开不开学习」由 `enabled` 在更外层判。
5
+ //
6
+ // 路由两步,顺序不能反:
7
+ // ① 按**内容与环境**判"想要哪层"(下面 ROUTE_RULES)
8
+ // ② 与两个开关的**允许层**求交
9
+ // 目标层被关掉时落到另一层并留痕(`degraded`),不静默改层;两层都不可用则 `blocked`,
10
+ // 由门禁给出明确错误 —— 拒绝比悄悄写到用户关掉的那一层好。
11
+ import { LAYER_GLOBAL, LAYER_WORKSPACE } from '../memories/constants.js';
12
+ /**
13
+ * 全局措辞。命中才允许升到全局层(还要叠加证据门:只有用户明说的才算)。
14
+ *
15
+ * 刻意收窄:只认"跨项目"与"永远/以后都"这两类**明确**表述。不认"一般"、"通常"、
16
+ * "最好"——那些是偏好强度,不是作用域。误判的代价是把项目约定升级成所有项目的约定,
17
+ * 而用户根本不知道它存在于全局层。
18
+ *
19
+ * 同样不认 `总是` / `always`:它们是**频率**,不是范围。"提交前总是先跑测试"在项目里说,
20
+ * 说的是这个项目的习惯;升到全局层之后,用户在别的仓库也会看到它。自动确认开着时更没有
21
+ * 卡片可以纠正 —— 这类词一个都不能留。
22
+ */
23
+ const GLOBAL_PATTERNS = [
24
+ /所有项目/, /任何项目/, /每个项目/, /各个项目/, /跨项目/,
25
+ /以后都/, /今后都/, /一律/, /永远都?/,
26
+ /不(?:管|论)哪(?:个|一)(?:项目|仓库)/,
27
+ /\ball projects?\b/i, /\bevery project\b/i, /\bacross projects?\b/i,
28
+ /\bfrom now on\b/i,
29
+ ];
30
+ /** 场景措辞:只有它才允许落场景层(场景是手动单选、默认不启用的,往里写等于让它消失)。 */
31
+ const SCENE_PATTERNS = [
32
+ /这个场景/, /该场景/, /当前场景/, /本场景/, /在这个场景/,
33
+ /写代码时/, /写文档时/, /做研究时/, /翻译时/,
34
+ /\bin this scene\b/i, /\bthis scene\b/i,
35
+ ];
36
+ export const hasGlobalPhrase = (text) => GLOBAL_PATTERNS.some((re) => re.test(text));
37
+ export const hasScenePhrase = (text) => SCENE_PATTERNS.some((re) => re.test(text));
38
+ /** 降级原因的人话(界面与工具回执共用一份,避免两处措辞不同)。 */
39
+ export const DEGRADE_NOTE = {
40
+ 'layer-off': '记到了另一层(想写的那一层在自主记忆设置里关着)',
41
+ 'no-workspace': '拿不到工作区路径,记到了全局',
42
+ };
43
+ export function routeLayer(input) {
44
+ // 只判两种层:**全局 / 本项目**。会话层与场景层已取消 —— 它们和用户记忆的场景单选
45
+ // 绑在一起(一个场景开着就不能开别的),而自主记忆不参与那套机制。
46
+ //
47
+ // 显式 `forcedLayer` **压过内容措辞**:用户在对话卡片里选了「本工作区」,正文里恰好有
48
+ // 「所有项目」时不能悄悄抬到全局 —— 那等于用户的选择没生效。没有显式层时才按内容判:
49
+ // 只有用户明说 / 纠正且带明确跨项目措辞才升全局;其余一律本项目。`forcedLayer` 里的
50
+ // session / scene 一律按本项目解释。
51
+ const wantsGlobal = input.forcedLayer !== undefined
52
+ ? input.forcedLayer === LAYER_GLOBAL
53
+ : (input.quoted && hasGlobalPhrase(input.text));
54
+ // `desired` 记**原始想要**,不随后续降级改写:界面解释"为什么被降级"靠它对照
55
+ // (想要全局、落了本项目),改写了这句解释就没法生成。
56
+ const desired = wantsGlobal ? LAYER_GLOBAL : LAYER_WORKSPACE;
57
+ let layer = desired;
58
+ let degraded;
59
+ if (layer === LAYER_GLOBAL && !input.allowed.global) {
60
+ layer = LAYER_WORKSPACE;
61
+ degraded = 'layer-off';
62
+ }
63
+ else if (layer === LAYER_WORKSPACE && !input.allowed.workspace) {
64
+ layer = LAYER_GLOBAL;
65
+ degraded = 'layer-off';
66
+ }
67
+ // 目标层已经确定;只有工作区层需要 cwd。只开工作区又没有 cwd 时不能退到全局 ——
68
+ // 那是用户明确关掉的一层,写进去等于开关失效。
69
+ if (layer === LAYER_WORKSPACE) {
70
+ if (!input.allowed.workspace)
71
+ return { layer, group: '', desired, blocked: true };
72
+ if (input.workspaceHash)
73
+ return { layer, group: `_ws/${input.workspaceHash}`, desired, ...(degraded !== undefined ? { degraded } : {}) };
74
+ if (input.allowed.global) {
75
+ // 拿不到工作区身份时不静默丢:落到全局并留降级痕迹,界面会说明"这条没绑到本项目"。
76
+ return { layer: LAYER_GLOBAL, group: 'global', desired, degraded: 'no-workspace' };
77
+ }
78
+ return { layer: LAYER_WORKSPACE, group: '', desired, degraded: 'no-workspace', blocked: true };
79
+ }
80
+ // 全局层:开关允许才走到这里;两者都关时也不该静默写全局。
81
+ if (!input.allowed.global)
82
+ return { layer: LAYER_GLOBAL, group: '', desired, blocked: true };
83
+ return { layer: LAYER_GLOBAL, group: 'global', desired, ...(degraded !== undefined ? { degraded } : {}) };
84
+ }
85
+ /** 从 group 反推层;旧 `_session/` / 场景目录一律按本项目读(迁移后只作兼容)。 */
86
+ export function layerOfRoute(group) {
87
+ const head = String(group ?? '').split('/')[0];
88
+ if (head === 'global')
89
+ return LAYER_GLOBAL;
90
+ return LAYER_WORKSPACE;
91
+ }