dsh-plugin-tool-management 0.22.5 → 0.22.7

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 (70) hide show
  1. package/CHANGELOG.md +1652 -1415
  2. package/README.md +192 -177
  3. package/README_EN.md +192 -177
  4. package/docs/ARCHITECTURE.md +137 -134
  5. package/docs/COMPATIBILITY.md +112 -107
  6. package/docs/TROUBLESHOOTING.md +287 -285
  7. package/lib/client.js +15176 -12341
  8. package/lib/compat/capability-specs.js +66 -16
  9. package/lib/compat/host-contracts.js +11 -2
  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 +107 -22
  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 +41 -20
  18. package/lib/context-inject-select.js +33 -4
  19. package/lib/context-inject-surface.js +30 -10
  20. package/lib/context-inject.js +106 -14
  21. package/lib/evolution/cold.js +389 -0
  22. package/lib/evolution/config.js +498 -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 +883 -0
  27. package/lib/evolution/limits.js +21 -0
  28. package/lib/evolution/maintenance.js +544 -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 +178 -0
  34. package/lib/evolution/scope-card.js +144 -0
  35. package/lib/evolution/state.js +540 -0
  36. package/lib/evolution/write.js +1855 -0
  37. package/lib/index.js +1437 -57
  38. package/lib/legacy-tool-names.js +19 -4
  39. package/lib/mcp/tool-visibility.js +127 -10
  40. package/lib/memories/catalog.js +226 -0
  41. package/lib/memories/constants.js +137 -8
  42. package/lib/memories/discovery.js +59 -25
  43. package/lib/memories/projection.js +116 -31
  44. package/lib/memories/render-auto.js +199 -0
  45. package/lib/memories/search.js +3 -5
  46. package/lib/memories/service.js +168 -17
  47. package/lib/memories/snapshot.js +176 -24
  48. package/lib/op-registry.js +59 -0
  49. package/lib/ops/compat.js +6 -2
  50. package/lib/ops/evolution.js +896 -0
  51. package/lib/ops/memory.js +95 -72
  52. package/lib/ops/trash.js +14 -2
  53. package/lib/prompts/service.js +4 -1
  54. package/lib/scenes/candidates.js +5 -1
  55. package/lib/scope/workspace-key.js +39 -0
  56. package/lib/settings-sidecars.js +2 -2
  57. package/lib/skills/official.js +180 -36
  58. package/lib/subagents/run-provider.js +35 -22
  59. package/lib/text-width.js +65 -0
  60. package/lib/tool-table-switch.js +119 -19
  61. package/lib/tools/control.js +45 -12
  62. package/lib/tools/deps.js +2 -2
  63. package/lib/tools/mcp.js +6 -4
  64. package/lib/tools/memory.js +1098 -267
  65. package/lib/tools/note-ref.js +20 -0
  66. package/lib/tools/remove.js +1 -1
  67. package/lib/tools/scene.js +3 -3
  68. package/lib/tools/table.js +103 -24
  69. package/package.json +155 -156
  70. package/docs/UPDATE.md +0 -50
@@ -0,0 +1,498 @@
1
+ // 自主记忆的三级开关:全局 / 工作区 / 会话。
2
+ //
3
+ // 为什么三级而不是一个总开关:用户的两个真实诉求 ——「只给这个对话开」「只给这个项目开」——
4
+ // 一个布尔值都表达不了。要么全局开(每个新会话都学,敏感项目里是负担),要么全局关
5
+ // (想试的会话也开不了)。三级覆盖是能同时满足这两句话的最小结构。
6
+ //
7
+ // 为什么下层能覆盖上层的「关」:如果规定「全局关了下面一律不能开」,那"全局关、只给这个
8
+ // 对话开"就无法表达。所以解析规则是**就近优先**,不是"与"。
9
+ //
10
+ // 与 `scope-overrides.json` 的区别(两个东西长得很像,不能混):
11
+ // - 那一份管「这个会话的逐条开关存在哪一格」(作用域粒度),是 UI 偏好;
12
+ // - 这一份管「这个环境允不允许主动学」,是策略。
13
+ // 层(记忆存在哪)永远用真实 sid 与真实 cwd,不读作用域粒度 —— 见 docs 01-model §4。
14
+ import { createHash } from 'node:crypto';
15
+ import { mkdir } from 'node:fs/promises';
16
+ import { hubPath } from '../hub.js';
17
+ import { WORKSPACE_HASH_LEN } from '../memories/constants.js';
18
+ import { charWidth } from '../text-width.js';
19
+ import { NOTE_RATE_DEFAULTS, NOTE_RATE_MINUTES_MAX, NOTE_RATE_MINUTES_MIN, NOTE_RATE_NOTES_MAX, NOTE_RATE_NOTES_MIN, } from './limits.js';
20
+ /** 策略文件的目录(hub 内相对路径)。 */
21
+ export const EVOLUTION_DIR = 'evolution';
22
+ export const EVOLUTION_SETTINGS_FILE = 'evolution/settings.json';
23
+ export const EVOLUTION_WORKSPACES_FILE = 'evolution/workspaces.json';
24
+ export const EVOLUTION_SESSIONS_FILE = 'evolution/sessions.json';
25
+ /** 工作区身份:`workspaceScopeKeyOf` 的键取 sha256 前 16 位。 */
26
+ export function workspaceHashOf(scopeKey) {
27
+ return createHash('sha256').update(String(scopeKey)).digest('hex').slice(0, WORKSPACE_HASH_LEN);
28
+ }
29
+ /** 自定义风格的引用前缀;后面接 `CustomNoteStyle.id`。 */
30
+ export const CUSTOM_NOTE_STYLE_PREFIX = 'custom:';
31
+ /** 用户最多保存几档自定义风格。 */
32
+ export const MAX_CUSTOM_NOTE_STYLES = 3;
33
+ /** 名称的显示宽度上限(半角单位):16 个字母,或 8 个汉字(每个算 2)。 */
34
+ export const MAX_CUSTOM_NOTE_STYLE_NAME_WIDTH = 16;
35
+ /** 宽字符(汉字 / 全角 / emoji)个数上限:8 个。 */
36
+ export const MAX_CUSTOM_NOTE_STYLE_WIDE = 8;
37
+ /** 自定义指引上限:与旧 `noteStyleText` 同一长度,足够写清口吻。 */
38
+ export const MAX_CUSTOM_NOTE_STYLE_GUIDE = 200;
39
+ /**
40
+ * 每种内置风格给模型的一句话指引(注入进自动段与复习器提示)。
41
+ *
42
+ * 长度也归这里管:复习器的基础提示不再硬写「一句」,否则详细档与它直接打架。
43
+ */
44
+ export const NOTE_STYLE_GUIDE = {
45
+ default: 'Write one or two clear sentences: the conclusion first, then the key reason only when it changes how the note is applied. No emoji, no tone words, no filler.',
46
+ detailed: 'Write a complete note in two or three short sentences: state the conclusion first, then the reason and any conditions or exceptions. No emoji, no tone words, no filler.',
47
+ minimal: 'Write in as few words as possible.',
48
+ };
49
+ /** 旧值 → 新值:`efficient` 改名为 `default`,`friendly` 并入 `detailed`。 */
50
+ function styleIdOf(raw) {
51
+ const s = typeof raw === 'string' ? raw.trim() : '';
52
+ if (s === 'efficient')
53
+ return 'default';
54
+ if (s === 'friendly')
55
+ return 'detailed';
56
+ if (s === 'default' || s === 'detailed' || s === 'minimal')
57
+ return s;
58
+ if (s.startsWith(CUSTOM_NOTE_STYLE_PREFIX) && s.length > CUSTOM_NOTE_STYLE_PREFIX.length)
59
+ return s;
60
+ return undefined;
61
+ }
62
+ /** 名称显示宽度:汉字 / 全角 / emoji 算 2,其余算 1。客户端 `evoNameMetrics` 同一口径。 */
63
+ /**
64
+ * 名称截断:宽度最多 16 个半角单位,且宽字符最多 8 个。
65
+ * 于是中文最多 8 个字,英文最多 16 个字母,混排同时受两者约束。
66
+ */
67
+ function truncateStyleName(s) {
68
+ let out = '';
69
+ let width = 0;
70
+ let wide = 0;
71
+ for (const ch of s) {
72
+ const w = charWidth(ch);
73
+ const nextWide = wide + (w === 2 ? 1 : 0);
74
+ if (width + w > MAX_CUSTOM_NOTE_STYLE_NAME_WIDTH || nextWide > MAX_CUSTOM_NOTE_STYLE_WIDE)
75
+ break;
76
+ out += ch;
77
+ width += w;
78
+ wide = nextWide;
79
+ }
80
+ return out;
81
+ }
82
+ /**
83
+ * 自定义风格列表归一化:最多 3 个,名称按显示宽度截断,指引截到 200 字符。
84
+ *
85
+ * id 只保留安全字符;缺失 / 重复时补一个 `cN`。id 是 `noteStyle` 的引用键,
86
+ * 不能为空,也不能重复 —— 否则选中一个会命中另一个。
87
+ */
88
+ function normalizeCustomStyles(raw) {
89
+ if (!Array.isArray(raw))
90
+ return [];
91
+ const out = [];
92
+ const seen = new Set();
93
+ for (const item of raw) {
94
+ if (!item || typeof item !== 'object')
95
+ continue;
96
+ const name = truncateStyleName(String(item.name ?? '').trim().replaceAll(/\s+/g, ' '));
97
+ const guide = String(item.guide ?? '').trim().replaceAll(/\s+/g, ' ').slice(0, MAX_CUSTOM_NOTE_STYLE_GUIDE);
98
+ if (name === '' || guide === '')
99
+ continue;
100
+ let id = String(item.id ?? '').trim().replace(/[^A-Za-z0-9_-]/g, '').slice(0, 32);
101
+ if (id === '' || seen.has(id)) {
102
+ let n = out.length + 1;
103
+ while (seen.has('c' + n))
104
+ n++;
105
+ id = 'c' + n;
106
+ }
107
+ seen.add(id);
108
+ out.push({ id, name, guide });
109
+ if (out.length >= MAX_CUSTOM_NOTE_STYLES)
110
+ break;
111
+ }
112
+ return out;
113
+ }
114
+ /** 选中的风格是否还指向一个存在的自定义档。 */
115
+ function styleAvailable(style, customStyles) {
116
+ if (style === 'default' || style === 'detailed' || style === 'minimal')
117
+ return true;
118
+ const id = style.slice(CUSTOM_NOTE_STYLE_PREFIX.length);
119
+ return customStyles.some((s) => s.id === id);
120
+ }
121
+ /**
122
+ * 把任意输入洗成合法风格与自定义风格列表。
123
+ *
124
+ * 兼容两种旧设置:`efficient` / `friendly` 改名;`noteStyle=custom` + `noteStyleText`
125
+ * 的单条自定义文本迁移成一条名为「我的风格」的自定义档。迁移只发生在读设置时,
126
+ * `writeSettings` 落盘的是新形状,所以旧字段不会一直存在。
127
+ */
128
+ export function normalizeNoteStyle(raw) {
129
+ // 兼容裸字符串(老接口 / 测试直接传 `'detailed'`)。
130
+ const r = raw !== null && typeof raw === 'object' ? raw : { style: raw };
131
+ const legacyText = typeof r.custom === 'string'
132
+ ? r.custom.trim().replaceAll(/\s+/g, ' ').slice(0, MAX_CUSTOM_NOTE_STYLE_GUIDE)
133
+ : '';
134
+ let customStyles = normalizeCustomStyles(r.customStyles);
135
+ if (r.style === 'custom' && legacyText !== '' && customStyles.length === 0) {
136
+ customStyles = [{ id: 'legacy', name: '我的风格', guide: legacyText }];
137
+ }
138
+ let style = r.style === 'custom' && legacyText !== ''
139
+ ? `custom:legacy`
140
+ : (styleIdOf(r.style) ?? 'default');
141
+ // 选中的自定义档被删掉 / 引用了不存在的 id:退回默认档,绝不注入一句空指引。
142
+ if (!styleAvailable(style, customStyles))
143
+ style = 'default';
144
+ return { style, customStyles };
145
+ }
146
+ /** 生效的风格指引(一句话,注入用)。找不到自定义档时退回默认档。 */
147
+ export function noteStyleGuideOf(style, customStyles = []) {
148
+ if (style.startsWith(CUSTOM_NOTE_STYLE_PREFIX)) {
149
+ const id = style.slice(CUSTOM_NOTE_STYLE_PREFIX.length);
150
+ return customStyles.find((s) => s.id === id)?.guide ?? NOTE_STYLE_GUIDE.default;
151
+ }
152
+ return NOTE_STYLE_GUIDE[style] ?? NOTE_STYLE_GUIDE.default;
153
+ }
154
+ /**
155
+ * 注入到自主记忆段的风格行;默认档返回空串。
156
+ *
157
+ * 默认档不注入:`memory_note` 的工具描述已经约束了均衡写法,再发一行只是常驻 token。
158
+ * 非默认档(详细 / 极简 / 自定义)才需要把实际风格告诉模型。
159
+ */
160
+ export function noteStyleLineOf(style, customStyles = []) {
161
+ if (style === 'default')
162
+ return '';
163
+ const guide = noteStyleGuideOf(style, customStyles);
164
+ return guide === '' ? '' : `When saving a new learned note, write it in this style: ${guide}`;
165
+ }
166
+ /**
167
+ * 出厂值。两个开关都 `false` 是硬要求:这个功能改变的是「agent 可以不经用户要求就写记忆」,
168
+ * 授权边界的变更必须由用户显式打开。
169
+ */
170
+ export const DEFAULT_EVOLUTION_SETTINGS = {
171
+ learnGlobal: false,
172
+ learnWorkspace: false,
173
+ autoConfirm: false,
174
+ maxReviewsPerSession: 3,
175
+ learnWindowMinutes: NOTE_RATE_DEFAULTS.minutes,
176
+ maxLearnsPerWindow: NOTE_RATE_DEFAULTS.notes,
177
+ model: '',
178
+ noteStyle: 'default',
179
+ customNoteStyles: [],
180
+ };
181
+ const boolOf = (v, fallback) => (typeof v === 'boolean' ? v : fallback);
182
+ /**
183
+ * 旧配置 → 两个新开关。
184
+ *
185
+ * 旧版有 `enabled` + `learnScope` + `writeTarget` 三个字段,但界面只暴露过 `enabled`;
186
+ * `writeTarget` 是「最多写到哪」的上限,升级时把它翻译成「只开哪一层」最接近原意:
187
+ * 上限是工作区的人不该突然获得写全局的资格。`learnScope='off'` 是旧版的「不学」开关,
188
+ * 即使 `enabled=true` 也必须迁成两项全关,否则升级后会在用户没点头的情况下开始学习。
189
+ * 旧值在 `enabled=false` 时同样两项全关。
190
+ */
191
+ function legacyLearnFlags(raw) {
192
+ if (typeof raw?.enabled !== 'boolean')
193
+ return undefined;
194
+ if (raw.enabled === false || raw.learnScope === 'off')
195
+ return { global: false, workspace: false };
196
+ // `writeTarget` 是旧版的显式上限;`learnScope` 是更早的同类概念(`workspace` / `session` 都表示
197
+ // "只在这个项目里学")。两个字段都认,否则只写了 `learnScope='workspace'` 的旧配置会掉进
198
+ // 下面的兜底、升级后**从工作区扩大到全局** —— 那是用户从没同意过的权限变化。
199
+ if (raw.writeTarget === 'workspace' || raw.writeTarget === 'session')
200
+ return { global: false, workspace: true };
201
+ if (raw.learnScope === 'workspace' || raw.learnScope === 'session')
202
+ return { global: false, workspace: true };
203
+ return { global: true, workspace: true };
204
+ }
205
+ const intOf = (v, fallback, min, max) => {
206
+ if (typeof v !== 'number' || !Number.isFinite(v))
207
+ return fallback;
208
+ return Math.min(max, Math.max(min, Math.round(v)));
209
+ };
210
+ /** 宽松读:坏值一律回退到出厂值,不抛错(界面要能打开)。 */
211
+ export function normalizeEvolutionSettings(raw) {
212
+ const r = raw && typeof raw === 'object' ? raw : {};
213
+ const d = DEFAULT_EVOLUTION_SETTINGS;
214
+ const legacy = legacyLearnFlags(r);
215
+ const style = normalizeNoteStyle({
216
+ style: r.noteStyle,
217
+ customStyles: r.customNoteStyles,
218
+ custom: r.noteStyleText,
219
+ });
220
+ return {
221
+ learnGlobal: typeof r.learnGlobal === 'boolean' ? r.learnGlobal : (legacy?.global ?? d.learnGlobal),
222
+ learnWorkspace: typeof r.learnWorkspace === 'boolean' ? r.learnWorkspace : (legacy?.workspace ?? d.learnWorkspace),
223
+ autoConfirm: typeof r.autoConfirm === 'boolean' ? r.autoConfirm : d.autoConfirm,
224
+ maxReviewsPerSession: intOf(r.maxReviewsPerSession, d.maxReviewsPerSession, 0, 20),
225
+ learnWindowMinutes: intOf(r.learnWindowMinutes, d.learnWindowMinutes, NOTE_RATE_MINUTES_MIN, NOTE_RATE_MINUTES_MAX),
226
+ maxLearnsPerWindow: intOf(r.maxLearnsPerWindow, d.maxLearnsPerWindow, NOTE_RATE_NOTES_MIN, NOTE_RATE_NOTES_MAX),
227
+ model: typeof r.model === 'string' ? r.model : d.model,
228
+ noteStyle: style.style,
229
+ customNoteStyles: style.customStyles,
230
+ };
231
+ }
232
+ /** 覆盖层归一化:只保留**明确写了**的字段,没写的保持 undefined(= 继承)。 */
233
+ export function normalizeOverrides(raw) {
234
+ const r = raw && typeof raw === 'object' ? raw : {};
235
+ const out = {};
236
+ const legacy = legacyLearnFlags(r);
237
+ if (typeof r.learnGlobal === 'boolean')
238
+ out.learnGlobal = r.learnGlobal;
239
+ else if (legacy !== undefined)
240
+ out.learnGlobal = legacy.global;
241
+ if (typeof r.learnWorkspace === 'boolean')
242
+ out.learnWorkspace = r.learnWorkspace;
243
+ else if (legacy !== undefined)
244
+ out.learnWorkspace = legacy.workspace;
245
+ if (typeof r.autoConfirm === 'boolean')
246
+ out.autoConfirm = r.autoConfirm;
247
+ if (typeof r.maxReviewsPerSession === 'number' && Number.isFinite(r.maxReviewsPerSession))
248
+ out.maxReviewsPerSession = intOf(r.maxReviewsPerSession, DEFAULT_EVOLUTION_SETTINGS.maxReviewsPerSession, 0, 20);
249
+ if (typeof r.learnWindowMinutes === 'number' && Number.isFinite(r.learnWindowMinutes))
250
+ out.learnWindowMinutes = intOf(r.learnWindowMinutes, NOTE_RATE_DEFAULTS.minutes, NOTE_RATE_MINUTES_MIN, NOTE_RATE_MINUTES_MAX);
251
+ if (typeof r.maxLearnsPerWindow === 'number' && Number.isFinite(r.maxLearnsPerWindow))
252
+ out.maxLearnsPerWindow = intOf(r.maxLearnsPerWindow, NOTE_RATE_DEFAULTS.notes, NOTE_RATE_NOTES_MIN, NOTE_RATE_NOTES_MAX);
253
+ if (typeof r.model === 'string')
254
+ out.model = r.model;
255
+ // 覆盖层只选风格,不定义自定义档;`custom:<id>` 是否存在由 resolveEffectiveConfig 校验。
256
+ if (r.noteStyle !== undefined) {
257
+ const style = styleIdOf(r.noteStyle);
258
+ if (style !== undefined)
259
+ out.noteStyle = style;
260
+ }
261
+ return out;
262
+ }
263
+ /** 这一层是否真的覆盖了至少一个字段(用于界面显示"来源")。 */
264
+ export function hasOverrides(o) {
265
+ if (!o)
266
+ return false;
267
+ return Object.keys(o).some((k) => o[k] !== undefined);
268
+ }
269
+ /**
270
+ * 逐字段解析:会话 → 工作区 → 全局,取第一个有定义的。
271
+ *
272
+ * 注入与学习共用同一道开关:`enabled` 为假就既不学也不注入。曾经有过一颗独立的
273
+ * 「学但不注入」开关,它让「学但不生效」与「关掉这一层」两套授权边界并存,用户无法
274
+ * 从界面判断哪一颗才决定上下文内容 —— 已删除,不再保留字段。
275
+ *
276
+ * ⚠️ 旧配置里可能还存着 `inject`。这里**刻意忽略它**:它已不是受支持的字段,
277
+ * 认它等于让那些用户的自主记忆永久不注入,而界面上已没有地方能改回来。
278
+ */
279
+ export function resolveEffectiveConfig(global, workspace, session) {
280
+ const layers = [session, workspace].filter((x) => x !== undefined);
281
+ const pick = (k) => {
282
+ for (const layer of layers) {
283
+ const v = layer[k];
284
+ if (v !== undefined)
285
+ return v;
286
+ }
287
+ return undefined;
288
+ };
289
+ const learnGlobal = pick('learnGlobal') ?? global.learnGlobal;
290
+ const learnWorkspace = pick('learnWorkspace') ?? global.learnWorkspace;
291
+ const enabled = learnGlobal || learnWorkspace;
292
+ // 自定义档的定义永远来自全局;覆盖层只能选,不能改。选中的 id 被删掉时退回默认档。
293
+ const customStyles = global.customNoteStyles ?? [];
294
+ const pickedStyle = pick('noteStyle');
295
+ const noteStyle = pickedStyle !== undefined && styleAvailable(pickedStyle, customStyles)
296
+ ? pickedStyle
297
+ : (styleAvailable(global.noteStyle, customStyles) ? global.noteStyle : 'default');
298
+ return {
299
+ learnGlobal,
300
+ learnWorkspace,
301
+ autoConfirm: pick('autoConfirm') ?? global.autoConfirm,
302
+ enabled,
303
+ maxReviewsPerSession: pick('maxReviewsPerSession') ?? global.maxReviewsPerSession,
304
+ learnWindowMinutes: pick('learnWindowMinutes') ?? global.learnWindowMinutes,
305
+ maxLearnsPerWindow: pick('maxLearnsPerWindow') ?? global.maxLearnsPerWindow,
306
+ model: pick('model') ?? global.model,
307
+ noteStyle,
308
+ customNoteStyles: customStyles,
309
+ source: hasOverrides(session) ? 'session' : hasOverrides(workspace) ? 'workspace' : 'global',
310
+ };
311
+ }
312
+ export function normalizeWorkspacesFile(raw) {
313
+ const r = raw && typeof raw === 'object' ? raw : {};
314
+ const src = r.workspaces && typeof r.workspaces === 'object' ? r.workspaces : {};
315
+ const workspaces = {};
316
+ for (const [hash, value] of Object.entries(src)) {
317
+ if (!/^[0-9a-f]{8,64}$/.test(hash) || !value || typeof value !== 'object')
318
+ continue;
319
+ if (typeof value.key !== 'string' || value.key === '')
320
+ continue;
321
+ workspaces[hash] = {
322
+ key: value.key,
323
+ cwd: typeof value.cwd === 'string' ? value.cwd : '',
324
+ label: typeof value.label === 'string' ? value.label : '',
325
+ createdAt: typeof value.createdAt === 'string' ? value.createdAt : '',
326
+ lastSeenAt: typeof value.lastSeenAt === 'string' ? value.lastSeenAt : '',
327
+ ...(typeof value.missingAt === 'string' || value.missingAt === null ? { missingAt: value.missingAt } : {}),
328
+ ...(value.evolution !== undefined ? { evolution: normalizeOverrides(value.evolution) } : {}),
329
+ };
330
+ }
331
+ return { version: 1, workspaces };
332
+ }
333
+ export function normalizeSessionsFile(raw) {
334
+ const r = raw && typeof raw === 'object' ? raw : {};
335
+ const src = r.sessions && typeof r.sessions === 'object' ? r.sessions : {};
336
+ const sessions = {};
337
+ for (const [sid, value] of Object.entries(src)) {
338
+ if (sid === '' || !value || typeof value !== 'object')
339
+ continue;
340
+ sessions[sid] = {
341
+ lastSeenAt: typeof value.lastSeenAt === 'string' ? value.lastSeenAt : '',
342
+ ...(value.evolution !== undefined ? { evolution: normalizeOverrides(value.evolution) } : {}),
343
+ };
344
+ }
345
+ return { version: 1, sessions };
346
+ }
347
+ const TTL_MS = 3000;
348
+ /**
349
+ * 建一份三级开关的门面。与 `createSettingsSidecars` 同构:读宽松(坏文件回默认,界面能开),
350
+ * 写严格(坏文件拒绝保存,避免用默认值覆盖用户刚改的配置)。
351
+ */
352
+ export function createEvolutionConfig(deps) {
353
+ let settingsCache = null;
354
+ let workspacesCache = null;
355
+ let sessionsCache = null;
356
+ /**
357
+ * 写之前把 `evolution/` 建出来。`writeJsonFile` 只做原子写,不建父目录(它假定调用方
358
+ * 已经在 hub 根下)。少了这一步,第一次打开开关时会以 ENOENT 失败。
359
+ */
360
+ async function ensureEvolutionDir() {
361
+ await deps.ensurePaths();
362
+ await mkdir(hubPath(EVOLUTION_DIR), { recursive: true });
363
+ }
364
+ async function readForWrite(abs, label) {
365
+ const read = await deps.readJsonFileStrict(abs);
366
+ if (read.status === 'corrupt' || read.status === 'unreadable') {
367
+ return {
368
+ ok: false,
369
+ error: `${label}文件${read.status === 'corrupt' ? '损坏' : '不可读'},已拒绝保存:${read.error}`,
370
+ };
371
+ }
372
+ return { ok: true, raw: read.status === 'ok' ? read.value : null };
373
+ }
374
+ async function readSettings(force = false) {
375
+ if (settingsCache && !force && Date.now() - settingsCache.at < TTL_MS)
376
+ return settingsCache.value;
377
+ await deps.ensurePaths();
378
+ const raw = await deps.readJsonFile(hubPath(EVOLUTION_SETTINGS_FILE));
379
+ settingsCache = { at: Date.now(), value: normalizeEvolutionSettings(raw) };
380
+ return settingsCache.value;
381
+ }
382
+ function settingsSync() {
383
+ if (settingsCache)
384
+ return settingsCache.value;
385
+ void readSettings().catch(() => { });
386
+ return DEFAULT_EVOLUTION_SETTINGS;
387
+ }
388
+ async function readWorkspaces(force = false) {
389
+ if (workspacesCache && !force && Date.now() - workspacesCache.at < TTL_MS)
390
+ return workspacesCache.value;
391
+ await deps.ensurePaths();
392
+ const raw = await deps.readJsonFile(hubPath(EVOLUTION_WORKSPACES_FILE));
393
+ workspacesCache = { at: Date.now(), value: normalizeWorkspacesFile(raw) };
394
+ return workspacesCache.value;
395
+ }
396
+ async function readSessions(force = false) {
397
+ if (sessionsCache && !force && Date.now() - sessionsCache.at < TTL_MS)
398
+ return sessionsCache.value;
399
+ await deps.ensurePaths();
400
+ const raw = await deps.readJsonFile(hubPath(EVOLUTION_SESSIONS_FILE));
401
+ sessionsCache = { at: Date.now(), value: normalizeSessionsFile(raw) };
402
+ return sessionsCache.value;
403
+ }
404
+ async function effective(scopeKey, sid) {
405
+ const [global, workspaces, sessions] = await Promise.all([readSettings(), readWorkspaces(), readSessions()]);
406
+ const hash = scopeKey ? workspaceHashOf(scopeKey) : undefined;
407
+ const workspace = hash ? workspaces.workspaces[hash]?.evolution : undefined;
408
+ const session = sid ? sessions.sessions[sid]?.evolution : undefined;
409
+ const resolved = resolveEffectiveConfig(global, workspace, session);
410
+ return {
411
+ ...resolved,
412
+ ...(scopeKey !== undefined ? { workspaceKey: scopeKey } : {}),
413
+ ...(hash !== undefined ? { workspaceHash: hash } : {}),
414
+ ...(sid !== undefined ? { sessionId: sid } : {}),
415
+ };
416
+ }
417
+ async function writeSettings(patch) {
418
+ await ensureEvolutionDir();
419
+ return deps.withWriteLock(async () => {
420
+ const read = await readForWrite(hubPath(EVOLUTION_SETTINGS_FILE), '自主记忆设置');
421
+ if (!read.ok)
422
+ return read;
423
+ // **基线取锁内新读到的磁盘值**,不是调用方手里那份可能已经过期的完整对象。
424
+ // 早先签名收的是 `EvolutionSettings`(完整),调用方用 3 秒缓存的 `readSettings()`
425
+ // 拼出整份再传进来 —— 两个窗口同时改不同字段时,后写的会用旧值覆盖前一个的改动。
426
+ const normalized = normalizeEvolutionSettings({ ...normalizeEvolutionSettings(read.raw), ...patch });
427
+ await deps.writeJsonFile(hubPath(EVOLUTION_SETTINGS_FILE), normalized);
428
+ settingsCache = { at: Date.now(), value: normalized };
429
+ return { ok: true, settings: normalized };
430
+ });
431
+ }
432
+ async function writeWorkspace(scopeKey, cwd, label, overrides) {
433
+ const hash = workspaceHashOf(scopeKey);
434
+ await ensureEvolutionDir();
435
+ return deps.withWriteLock(async () => {
436
+ const read = await readForWrite(hubPath(EVOLUTION_WORKSPACES_FILE), '工作区记录');
437
+ if (!read.ok)
438
+ return read;
439
+ const current = normalizeWorkspacesFile(read.raw);
440
+ const now = new Date().toISOString();
441
+ const prev = current.workspaces[hash];
442
+ current.workspaces[hash] = {
443
+ key: scopeKey,
444
+ cwd,
445
+ label,
446
+ createdAt: prev?.createdAt || now,
447
+ lastSeenAt: now,
448
+ ...(prev?.missingAt !== undefined ? { missingAt: prev.missingAt } : {}),
449
+ ...(overrides === undefined ? {} : { evolution: overrides }),
450
+ };
451
+ await deps.writeJsonFile(hubPath(EVOLUTION_WORKSPACES_FILE), current);
452
+ workspacesCache = { at: Date.now(), value: current };
453
+ return { ok: true, hash };
454
+ });
455
+ }
456
+ /**
457
+ * 标记 / 清除工作区失效。
458
+ *
459
+ * 为什么不复用 `writeWorkspace`:那个方法每次都会刷新 `lastSeenAt`,而失效扫描的
460
+ * 语义正相反 —— 目录都不在了,"刚刚见过"是假话。而且它需要 scopeKey 与 cwd,
461
+ * 扫描手上只有 hash。
462
+ */
463
+ async function markWorkspaceMissing(hash, missingAt) {
464
+ await ensureEvolutionDir();
465
+ return deps.withWriteLock(async () => {
466
+ const read = await readForWrite(hubPath(EVOLUTION_WORKSPACES_FILE), '工作区记录');
467
+ if (!read.ok)
468
+ return read;
469
+ const current = normalizeWorkspacesFile(read.raw);
470
+ const prev = current.workspaces[hash];
471
+ if (!prev)
472
+ return { ok: true, changed: false };
473
+ if ((prev.missingAt ?? null) === missingAt)
474
+ return { ok: true, changed: false };
475
+ current.workspaces[hash] = { ...prev, missingAt };
476
+ await deps.writeJsonFile(hubPath(EVOLUTION_WORKSPACES_FILE), current);
477
+ workspacesCache = { at: Date.now(), value: current };
478
+ return { ok: true, changed: true };
479
+ });
480
+ }
481
+ async function writeSession(sid, overrides) {
482
+ await ensureEvolutionDir();
483
+ return deps.withWriteLock(async () => {
484
+ const read = await readForWrite(hubPath(EVOLUTION_SESSIONS_FILE), '会话记录');
485
+ if (!read.ok)
486
+ return read;
487
+ const current = normalizeSessionsFile(read.raw);
488
+ current.sessions[sid] = {
489
+ lastSeenAt: new Date().toISOString(),
490
+ ...(overrides === undefined ? {} : { evolution: overrides }),
491
+ };
492
+ await deps.writeJsonFile(hubPath(EVOLUTION_SESSIONS_FILE), current);
493
+ sessionsCache = { at: Date.now(), value: current };
494
+ return { ok: true };
495
+ });
496
+ }
497
+ return { readSettings, settingsSync, readWorkspaces, readSessions, effective, writeSettings, writeWorkspace, markWorkspaceMissing, writeSession };
498
+ }
@@ -0,0 +1,48 @@
1
+ // episode 的形状与两种构造方式(冷路径的落盘格式)。
2
+ //
3
+ // 现在唯一的**生产**来源是官方 `compaction/summary`(`checkpointEpisodeOf`)。旧版按轮次
4
+ // 攒 digest 的那一套(轮内捕获 / 值不值得复习的启发式)已经没有调用点,删掉了 —— 那份
5
+ // 摘要信息密度低,而且压缩 checkpoint 本来就是同一段对话更高密度的提炼。
6
+ //
7
+ // `episodeOf` / `TurnDigest` 留着:盘上可能还有升级前排队、没复习完的旧 episode,
8
+ // 读回来的形状必须仍然可构造、复习提示里也仍按旧版式渲染。
9
+ /** 单个轮次最多记多少条事件。 */
10
+ export const MAX_EVENTS_PER_TURN = 40;
11
+ /** 旧版按轮次复习产出的 episode;现在只为兼容盘上已排队的旧项保留。 */
12
+ export function episodeOf(digest, meta) {
13
+ return {
14
+ id: `${meta.session}:${digest.turn}`,
15
+ session: meta.session,
16
+ turn: digest.turn,
17
+ at: meta.at,
18
+ ...(meta.cwd !== undefined ? { cwd: meta.cwd } : {}),
19
+ ...(meta.workspaceHash !== undefined ? { workspaceHash: meta.workspaceHash } : {}),
20
+ reason: meta.reason,
21
+ userTexts: digest.userTexts.slice(-8),
22
+ tools: digest.tools.slice(-12),
23
+ events: digest.events.slice(-MAX_EVENTS_PER_TURN),
24
+ };
25
+ }
26
+ /**
27
+ * 官方 `compaction/summary` 产出的 episode。
28
+ *
29
+ * `seq` 是官方 session log 的序号,压缩事件在同一会话里单调,用它当 turn 既稳定又不会
30
+ * 与旧版按轮号建的 episode 撞名(旧 id 是 `<session>:<turn>`,这里是 `<session>:compact:<seq>`)。
31
+ * checkpoint 是模型转述,不是用户原话 —— userTexts / tools 一律留空,证据门不该拿到
32
+ * 一份看似「用户说过」的文本。
33
+ */
34
+ export function checkpointEpisodeOf(input) {
35
+ return {
36
+ id: `${input.session}:compact:${input.seq}`,
37
+ session: input.session,
38
+ turn: Math.max(0, Math.floor(input.seq)),
39
+ at: input.at,
40
+ ...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
41
+ ...(input.workspaceHash !== undefined ? { workspaceHash: input.workspaceHash } : {}),
42
+ reason: 'compaction',
43
+ userTexts: [],
44
+ tools: [],
45
+ events: [],
46
+ checkpoint: input.checkpoint,
47
+ };
48
+ }