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,198 @@
1
+ // 自动段的渲染:每个域只渲染**一层**(全局 / 本工作区)。
2
+ //
3
+ // 三条硬约束,每一条都对应一个会毁掉体验的具体故障:
4
+ //
5
+ // ① **预算按层独立**。两个自动记忆域各占一条消息,各自只装自己那一层的条目;上限是该层
6
+ // max + 固定开销。用户记忆是另一条消息,不在这里竞争 —— 手写记忆再多也不会把自动段挤成 0,
7
+ // 反过来自动记忆再多也挤不掉用户写的东西。拆域之前两层共用一脚预算,任何一条新增都会让
8
+ // 整段(含用户记忆)重发;现在只有变化的那一层会重发。
9
+ //
10
+ // ② **不按场景分组**。全局层就是全局;「本工作区」块里的工作区 / 旧会话 / 旧场景条目都按
11
+ // 本地处理,不写成 `## Scene Memories: X` —— 那会让模型以为用户建了一个叫 `_ws/3f2a` 的场景。
12
+ //
13
+ // ③ **文本稳定**。注入去重按正文字节比对,任何"按当前时间算"的东西(相对时间、随机顺序、
14
+ // 每次重排)都会让整段每轮重发。所以:条目按固定规则排序,时间只体现为分数(影响谁进来),
15
+ // 不体现为文本。
16
+ import { AUTO_MEMORY_NOTE, AUTO_MEMORY_NOTE_PARTIAL, LAYER_GLOBAL, LAYER_SCENE, LAYER_SESSION, LAYER_WORKSPACE, TRUNCATION_MARKER, } from './constants.js';
17
+ import { isInjectableStatus } from './catalog.js';
18
+ import { itemBlock } from './projection.js';
19
+ import { scoreOf, tierOf } from '../evolution/state.js';
20
+ const zeroByLayer = () => ({ global: 0, workspace: 0, scene: 0, session: 0 });
21
+ /**
22
+ * 本层还能用多少字节:总盘减去更高优先级内容已占的部分。
23
+ *
24
+ * 不给自动段单独设上限 —— 总盘已经管住了"一共能吃多少",再叠一层层配额只会让
25
+ * "明明还有空间却不注入"变成一种无法解释的行为。
26
+ */
27
+ export function remainingBytesOf(totalBytes, reservedBytes) {
28
+ const total = Number.isFinite(totalBytes) ? totalBytes : 0;
29
+ const used = Number.isFinite(reservedBytes) ? reservedBytes : 0;
30
+ return Math.max(0, total - used);
31
+ }
32
+ /**
33
+ * 一条笔记的注入块:与手写记忆同构(`itemBlock`),正文**完整**进上下文。
34
+ *
35
+ * 不带类型标签,也**不带 id**:模型不需要知道内部分类;而 id(`_ws/<hash16>/<slug>`)
36
+ * 是磁盘目录,对模型和用户都没有意义 —— 真要按引用定位,`memory_get` 已经支持
37
+ * id / slot / 名称 / 注入行首句四种写法。
38
+ *
39
+ * 边界不再另附:正文落盘时就把 `边界:…` 拼在了末尾(`renderBody`),再附一次会让同一句话
40
+ * 在上下文里出现两遍。
41
+ *
42
+ * **playbook 只放标题**:它带着十几个步骤,整段塞进每轮上下文会吃掉大半预算,而且模型在
43
+ * 没决定执行之前根本用不上。这里只告诉它"有这么一份已验证流程",真要执行时再 `memory_get`。
44
+ */
45
+ export function lineOf(entry) {
46
+ const fallback = entry.id.slice(entry.id.lastIndexOf('/') + 1);
47
+ const name = (entry.title ?? '').trim() || entry.key || '';
48
+ const body = entry.body || entry.oneLine;
49
+ if (entry.status === 'playbook') {
50
+ const title = name || fallback;
51
+ return `- **${title}** — playbook; read the full note for steps\n`;
52
+ }
53
+ // 没有名称的旧条目(`auto_title` 与 `auto_key` 都缺):只输出正文,不留一对空加粗。
54
+ if (name === '')
55
+ return `- ${body.trim()}\n`;
56
+ return itemBlock(name, body).text;
57
+ }
58
+ const countersOf = (state, id) => state.entries[id]?.counters ?? { injected: 0, read: 0 };
59
+ /** 这条目录项是否属于这一层。workspace 域兼容旧数据:会话层按 sid、场景层按启用场景。 */
60
+ function inLayer(entry, layer, scope) {
61
+ if (layer === 'global')
62
+ return entry.layer === LAYER_GLOBAL;
63
+ if (entry.layer === LAYER_WORKSPACE)
64
+ return scope.workspaceHash !== undefined && entry.workspace === scope.workspaceHash;
65
+ // 会话层 / 场景层已不再写入,但盘上可能还有旧条目:按当前环境放进「本工作区」块,
66
+ // 不让它们静默消失(维护扫描仍按原规则 GC 会话层)。
67
+ if (entry.layer === LAYER_SESSION)
68
+ return scope.sessionId !== undefined && entry.session === scope.sessionId;
69
+ if (entry.layer === LAYER_SCENE)
70
+ return scope.enabledScenes !== undefined && scope.enabledScenes.has(entry.scene);
71
+ return false;
72
+ }
73
+ /**
74
+ * 渲染某一层的自动段正文。纯函数:同样的输入永远给同样的字节(去重的前提)。
75
+ *
76
+ * 标题不在这里:全局那块并进 `## Always-on memories`,工作区那块由注入框架给
77
+ * `# Workspace notes`。
78
+ */
79
+ export function renderAutoLayer(layer, input) {
80
+ const empty = { text: '', body: '', truncated: false, count: 0, tokens: 0, budget: 0, dropped: 0, byLayer: zeroByLayer(), pickedIds: [], picked: [] };
81
+ // 风格行只进 `text`(注入正文),不进 `body`(条目集合):合并块用 body 拼用户记忆,
82
+ // 风格行由调用方单独拼在收尾句之后。它也算进条目预算,否则会在满配时把正文顶出上限。
83
+ const styleLine = String(input.noteStyleLine ?? '').trim();
84
+ const styleCost = Buffer.byteLength(styleLine, 'utf8');
85
+ const tailOf = (note) => note + (styleLine === '' ? '' : '\n' + styleLine);
86
+ const budget = remainingBytesOf(input.totalBytes, input.reservedBytes);
87
+ // 收尾句也要占地方:装满了却发不出去,等于这一层白渲染。
88
+ const noteCost = Buffer.byteLength(AUTO_MEMORY_NOTE, 'utf8');
89
+ if (budget <= noteCost + styleCost) {
90
+ const dropped = input.entries.length;
91
+ if (dropped === 0)
92
+ return { ...empty, budget: 0 };
93
+ // 预算耗尽时也要留一句"笔记没显示":合并块只在 `truncated` 为真时去掉「完整集合」,
94
+ // 没有这一句,模型会以为自动笔记本来就不存在。这里不报条数 —— 这个分支还没按层过滤,
95
+ // `input.entries.length` 会把别的层 / 已停用的条目也算进去。
96
+ const body = `${TRUNCATION_MARKER} Learned notes are not shown here because the hand-written memories are large; list them with memory_get (kind=note).`;
97
+ // 「Learned notes」在这里指**这一类**(agent 学的笔记),不是板块名 —— 板块名随层不同,
98
+ // 这句要在两层的渲染里都读得通。
99
+ const text = body + '\n\n' + tailOf(AUTO_MEMORY_NOTE_PARTIAL) + '\n';
100
+ return { ...empty, text, body, truncated: true, tokens: Math.ceil(Buffer.byteLength(text, 'utf8') / 3), budget: 0, dropped };
101
+ }
102
+ const usable = budget - noteCost - styleCost;
103
+ const scope = input.scope;
104
+ // 候选:状态可注入 + 层匹配 + 没有待裁决理由。
105
+ const candidates = [];
106
+ for (const entry of input.entries) {
107
+ if (!entry.enabled)
108
+ continue;
109
+ if (!isInjectableStatus(entry.status))
110
+ continue;
111
+ if (!inLayer(entry, layer, scope))
112
+ continue;
113
+ const st = input.state.entries[entry.id];
114
+ // 待裁决的不注入:与用户记忆冲突、或表述有歧义的条目,等用户确认后才算数。
115
+ //
116
+ // **只看 `pendingReason`,不看 `reviewDue`**:后者是「这条有点旧了,看一眼」的提醒,
117
+ // 不是停用。两者曾共用一个字段,于是维护扫描一挂 TTL 提醒,一条仍在生效的记忆就从
118
+ // 上下文里消失了 —— 界面还显示生效、预算还把它算进去,而模型一条都看不到。
119
+ if (st && typeof st.pendingReason === 'string' && st.pendingReason !== '')
120
+ continue;
121
+ candidates.push({
122
+ entry,
123
+ score: scoreOf({
124
+ // 档位从证据算,不从 catalog 读:catalog 是派生数据,多存一份就多一处会漂。
125
+ tier: st ? tierOf(st.evidence) : 'inferred',
126
+ updatedAt: new Date(entry.mtime || 0).toISOString(),
127
+ }, countersOf(input.state, entry.id)),
128
+ });
129
+ }
130
+ // 一条候选都没有:只发风格行。风格行是「以后怎么写」的写作规范,与「现在有没有条目可注入」
131
+ // 无关 —— 只学不用(`inject: false`)正好落进这里:条目一条都不进,而学习还在继续,
132
+ // 吞掉风格行会让用户选的「详细 / 极简 / 自定义」对这批笔记完全失效,而 `memory_note` 的
133
+ // 工具描述还让模型去 `follow the style line in the learned-notes section`。
134
+ if (candidates.length === 0) {
135
+ if (styleLine === '')
136
+ return { ...empty, budget, dropped: 0 };
137
+ const text = styleLine + '\n';
138
+ return { ...empty, text, budget, dropped: 0, tokens: Math.ceil(Buffer.byteLength(text, 'utf8') / 3) };
139
+ }
140
+ // 排序必须是**确定**的:分数降序 → id 升序(同分时给一个稳定次序,否则每次 pre-step 顺序都变,
141
+ // 去重指纹跟着变,整段重发)。
142
+ candidates.sort((a, b) => b.score - a.score || a.entry.id.localeCompare(b.entry.id));
143
+ // 预算按**实际渲染块**的字节记,不按 `estTokens`:块里还有 `- `、加粗的名称与围栏,
144
+ // 估算口径会少算,条目一多就顶穿总盘。
145
+ const costOf = (entry) => Buffer.byteLength(lineOf(entry), 'utf8');
146
+ // **固定开销要先扣掉**:段尾那句收尾语、两个换行、以及"还有 N 条没列出"的截断标记。
147
+ //
148
+ // 早先只累计条目块,标记与换行完全没进 `spent` —— 于是 `auto.text` 实测会超出本层预算
149
+ // 几十到上百字节,两层叠起来就顶穿 256 KiB 的总盘。"按实际渲染块字节记"是这一层的
150
+ // 不变量,标记也是渲染块的一部分。
151
+ const tailBytes = Buffer.byteLength('\n' + tailOf(AUTO_MEMORY_NOTE_PARTIAL) + '\n', 'utf8');
152
+ const markerBytes = Buffer.byteLength('\n' + `${TRUNCATION_MARKER} ${candidates.length} more learned note(s) not shown; list them with memory_get (kind=note).` + '\n', 'utf8');
153
+ const fixed = tailBytes + markerBytes;
154
+ const picked = [];
155
+ let spent = 0;
156
+ for (const cand of candidates) {
157
+ // 只按字节停:装不下就跳过这一条、继续试更短的,直到预算用尽。
158
+ // 不设条数上限 —— 条数多到读不动的问题由字节预算自己解决(正文越长装得越少)。
159
+ const cost = costOf(cand.entry);
160
+ // 预留 `fixed`:真出现截断时标记要放得下,不截断时那几个字节就是安全余量。
161
+ if (fixed + spent + cost > usable)
162
+ continue;
163
+ picked.push(cand.entry);
164
+ spent += cost;
165
+ }
166
+ if (picked.length === 0) {
167
+ const body = `${TRUNCATION_MARKER} ${candidates.length} more learned note(s) not shown; list them with memory_get (kind=note).`;
168
+ const text = body + '\n\n' + tailOf(AUTO_MEMORY_NOTE_PARTIAL) + '\n';
169
+ return { ...empty, text, body, truncated: true, tokens: Math.ceil(Buffer.byteLength(text, 'utf8') / 3), budget, dropped: candidates.length };
170
+ }
171
+ // 单层内按正文排序:先总则后特例在这里没有意义(层已经分开了),稳定才是第一位的。
172
+ picked.sort((a, b) => a.oneLine.localeCompare(b.oneLine) || a.id.localeCompare(b.id));
173
+ const dropped = candidates.length - picked.length;
174
+ // 每条块的结尾已经带换行(`itemBlock` 如此),拼起来不再补 `\n`。
175
+ const entryBlocks = picked.map(lineOf);
176
+ const lines = [...entryBlocks];
177
+ if (dropped > 0)
178
+ lines.push('', `${TRUNCATION_MARKER} ${dropped} more learned note(s) not shown; list them with memory_get (kind=note).\n`);
179
+ // 收尾句(与用户记忆的版式一致):条目 → 截断提示 → 空行 → 收尾句。
180
+ // 截断时去掉「完整集合」声明,否则段尾那句与上面的省略提示自相矛盾。
181
+ const note = dropped > 0 ? AUTO_MEMORY_NOTE_PARTIAL : AUTO_MEMORY_NOTE;
182
+ const body = lines.join('');
183
+ const text = body + '\n' + tailOf(note) + '\n';
184
+ const byLayer = zeroByLayer();
185
+ byLayer[layer] = picked.length;
186
+ return {
187
+ text,
188
+ body,
189
+ truncated: dropped > 0,
190
+ count: picked.length,
191
+ tokens: Math.ceil(Buffer.byteLength(text, 'utf8') / 3),
192
+ budget,
193
+ dropped,
194
+ byLayer,
195
+ pickedIds: picked.map((e) => e.id),
196
+ picked: picked.map((e, i) => ({ id: e.id, line: entryBlocks[i] })),
197
+ };
198
+ }
@@ -13,8 +13,6 @@ function termScore(term, doc) {
13
13
  return 40;
14
14
  if (id.includes(term))
15
15
  return 30;
16
- if (doc.description.toLowerCase().includes(term))
17
- return 20;
18
16
  if (doc.tags.some((tag) => String(tag).toLowerCase().includes(term)))
19
17
  return 15;
20
18
  if (doc.body.toLowerCase().includes(term))
@@ -68,15 +66,15 @@ export function searchMemories(docs, query, limit) {
68
66
  }
69
67
  if (!matchedAll)
70
68
  continue;
71
- // 片段优先取正文(信息量最大),正文没命中时退回描述。
69
+ // 片段优先取正文(信息量最大);只在名称/标签上命中时退回名称,别把命中词藏起来。
72
70
  const bodyHit = terms.some((t) => doc.body.toLowerCase().includes(t));
73
- const snippet = bodyHit ? snippetOf(doc.body, terms) : snippetOf(doc.description, terms);
71
+ const snippet = bodyHit ? snippetOf(doc.body, terms) : snippetOf(doc.name, terms);
74
72
  hits.push({
75
73
  id: doc.id,
76
74
  scene: doc.group,
77
75
  name: doc.name,
78
- description: doc.description,
79
76
  enabled: doc.enabled,
77
+ ...(doc.origin !== undefined ? { origin: doc.origin } : {}),
80
78
  score,
81
79
  snippet,
82
80
  });
@@ -28,7 +28,8 @@ export { planMemoryExport } from './export-plan.js';
28
28
  // - 不再写 ~/.dsh/AGENTS.md(原始终层投影下线)
29
29
  //
30
30
  // 状态分层(两份文件各司其职,互不写回):
31
- // - 规则文件:正文真源。frontmatter 可声明 name/description/whenToUse/globs/metadata。
31
+ // - 规则文件:正文真源。frontmatter 可声明 name/whenToUse/globs/metadata(旧数据里的
32
+ // `description` 不再读:它只是正文的有损副本,而正文本身就会注入)。
32
33
  // - memories-index.json:启停/排序/标签/启用场景集合等**索引为准**字段(不写回记忆文件)。
33
34
  //
34
35
  // 发现必须自实现(不复用 readonly-discovery):可写来源只扫一层会压扁子目录场景,
@@ -49,17 +50,20 @@ import { parseSkillDoc, resolveDshHome, rewriteFrontmatterFields, yamlFieldLines
49
50
  import { newTrashId } from '../hub.js';
50
51
  // 预算 / 保留场景名 / 段渲染常量(抽到 ./constants.ts:投影函数与本服务共用,
51
52
  // 留在这里会让 projection.ts 反向 import 本文件,形成运行时循环依赖)。
52
- import { bundleDocName, DEFAULT_MAX_BYTES, GLOBAL_SCENE, LEGACY_BUNDLE_DOC, SCENE_CATALOG_MAX_BYTES, SHARED_GROUP, SNAPSHOT_TTL_MS, isValidGroupPath, isValidGroupSegment, MEMORIES_TRASH_DIR, fail, } from './constants.js';
53
+ import { bundleDocName, byteLen, DEFAULT_MAX_BYTES, GLOBAL_SCENE, LEGACY_BUNDLE_DOC, SCENE_CATALOG_MAX_BYTES, SCENE_MEMORY_NOTE, SCENE_MEMORY_NOTE_PARTIAL, SHARED_GROUP, SNAPSHOT_TTL_MS, isValidGroupPath, isValidGroupSegment, MEMORIES_TRASH_DIR, fail, } from './constants.js';
53
54
  // 对外契约保持在原路径:本文件此前直接 export 这两个,index.ts 等已按此 import。
54
55
  export { GLOBAL_SCENE, GLOBAL_SCENE_LABEL } from './constants.js';
55
56
  export { isValidGroupSegment, isValidGroupPath, MEMORIES_INDEX_FILE, MEMORIES_TRASH_DIR } from './constants.js';
56
57
  // parseModeState 搬到了 index-io.ts,但 test/contracts.test.mjs 按原路径引它 —— 契约不能断。
57
58
  export { parseModeState } from './index-io.js';
58
59
  // 投影 / 渲染纯函数(抽到 ./projection.ts):索引 → 界面与注入看到的那份文本。
59
- import { enabledSceneOf, normalizeActive, resolveActiveScenes, sceneLabel, sceneOf, sceneOrderOf, } from './projection.js';
60
+ import { enabledSceneOf, normalizeActive, resolveActiveScenes, sceneLabel, sceneOf, sceneOrderOf, signatureOfIndex, } from './projection.js';
60
61
  // 索引 IO 组与发现/快照组(抽出)。
61
62
  import { writeFileAtomically, isIndexQuarantined, readIndex, readIndexSync, writeIndex, repairFromQuarantine, isAbsentError } from './index-io.js';
62
- import { deriveFromDoc, projectRule, relocateLegacyLayout, buildSnapshot, probeSceneFilesSync, renderSceneCatalog, renderSceneMemory } from './snapshot.js';
63
+ import { deriveFromDoc, projectRule, relocateLegacyLayout, buildSnapshot, probeSceneFilesSync, renderSceneCatalog, renderSceneMemory, renderWorkspaceMemory } from './snapshot.js';
64
+ import { buildCatalog, catalogPathOf } from './catalog.js';
65
+ import { autoNotesRootOf, migrateLegacyAutoNotes } from '../evolution/notes.js';
66
+ import { watchDirectories } from '../skills/dir-watch.js';
63
67
  // ── 目录常量与失败约定 ─────────────────────────────────────────────────────
64
68
  // 其余跨文件共用的常量与无依赖小工具(message / isValidGroupSegment / isValidGroupPath /
65
69
  // MEMORIES_INDEX_FILE)已下沉到 ./constants.ts,避免 index-io / snapshot 反向引本文件。
@@ -88,6 +92,8 @@ export function createMemoriesService(ctx, deps) {
88
92
  // 旧的 $DSH_HOME/scene-memory 与更旧的 $DSH_HOME/rules 由 relocateLegacyLayout() 搬入。
89
93
  const stateDir = deps.stateDir && deps.stateDir.trim() !== '' ? resolve(deps.stateDir) : join(resolveDshHome(), HUB_DIR);
90
94
  const memoriesRoot = deps.memoriesRoot && deps.memoriesRoot.trim() !== '' ? resolve(deps.memoriesRoot) : join(stateDir, MEMORIES_DIR);
95
+ // 自主记忆的独立根:正文与它自己的启停索引都住这里,不进用户记忆的场景体系。
96
+ const autoNotesRoot = autoNotesRootOf(stateDir);
91
97
  const scenesRoot = deps.scenesDir && deps.scenesDir.trim() !== '' ? resolve(deps.scenesDir) : join(stateDir, SCENES_DIR);
92
98
  const maxBytes = Number.isFinite(deps.maxBytes) && deps.maxBytes > 0 ? deps.maxBytes : DEFAULT_MAX_BYTES;
93
99
  // 旧布局迁移:每个进程只跑一次。放在目录解析之后、任何首次读盘之前。
@@ -104,6 +110,7 @@ export function createMemoriesService(ctx, deps) {
104
110
  }
105
111
  try {
106
112
  await mkdir(join(memoriesRoot, GLOBAL_SCENE), { recursive: true });
113
+ await mkdir(autoNotesRoot, { recursive: true });
107
114
  await mkdir(scenesRoot, { recursive: true });
108
115
  }
109
116
  catch {
@@ -161,6 +168,7 @@ export function createMemoriesService(ctx, deps) {
161
168
  const SCENE_CACHE_MAX = 16;
162
169
  const sceneCache = new Map();
163
170
  const sceneCatalogCache = new Map();
171
+ const wsCache = new Map();
164
172
  /** 取一条缓存并把它移到队尾(Map 保序 ⇒ 头部就是最久没用的那条)。 */
165
173
  const cacheGet = (cache, key) => {
166
174
  const hit = cache.get(key);
@@ -213,18 +221,98 @@ export function createMemoriesService(ctx, deps) {
213
221
  // 边界(写清楚免得后来者以为漏改):技能 / MCP / 子智能体三个域**结构上不会**出现这种假
214
222
  // 「已清空」—— 它们是 SWR 缓存,计算失败时保留上一次的值,因此只可能"没能更新",
215
223
  // 不可能从"有内容"变成"空串";`''` 只在真的渲染不出东西时出现。
216
- const emptySceneMemory = () => ({ text: '', bytes: 0, truncated: false, maxBytes, scenes: [], items: [], dropped: [] });
224
+ const emptySceneMemory = () => ({ text: '', body: '', tail: '', bytes: 0, truncated: false, maxBytes, scenes: [], items: [], dropped: [], blocks: [] });
217
225
  /** 索引读不到 / 解析不了 → 注入侧必须报「取数失败」,而不是把"全部未启用"当成"用户清空了记忆"。 */
218
226
  const assertIndexReadable = () => {
219
227
  if (isIndexQuarantined(stateDir))
220
228
  throw new Error('记忆索引当前读不到,无法确定哪些记忆处于启用状态');
221
229
  };
230
+ // ── 探测结果缓存(目录监听 + TTL 兜底)────────────────────────────────────
231
+ //
232
+ // 为什么需要:`probeSceneFilesSync` 是一次**完整目录树**的 readdirSync + 每文件 statSync,
233
+ // 而注入通道每个 step 都要同步取一次文本(scene 与 memory 两域各一次,入参相同)。
234
+ // 实测 2000 个记忆文件 ≈ 23 ms/次,每步 46 ms 全在事件循环上。
235
+ //
236
+ // 为什么不能只靠监听:worker 崩溃 / 某个目录挂不上都**不会**回报(`attached()` 只说
237
+ // "有没有挂上过"),把"监听还在"当成前提,静默失效就会变成永久返回旧内容 —— 那正是
238
+ // 本模块一直在避免的形态。所以监听只用来**提前**失效,TTL 才是兜底:
239
+ // · 监听挂着 → 命中缓存,watcher 一报变化立刻清;最坏 TTL 过期。
240
+ // · 监听没挂上 → 不进缓存,保持原来的每次探测。
241
+ //
242
+ // 键 = memoriesRoot + 索引指纹 + 会话覆盖指纹(`probeSceneFilesSync` 的入参三要素),
243
+ // 值 = probe 结果。会话覆盖不同 → 不同条目,与两份段缓存同一口径。
244
+ const PROBE_CACHE_TTL_MS = 5000;
245
+ const probeCache = new Map();
246
+ /**
247
+ * 监听没挂上时多久重试一次。
248
+ *
249
+ * 为什么不能"试一次就认命":`watchDirectories` 在目录**当时不存在**时直接返回未挂上,
250
+ * 而全新用户的记忆根目录是在第一次写记忆时才建出来的 —— 一次性的装配会让这个进程
251
+ * 从此永远拿不到缓存(每步仍全树 stat)。也不能每步都重试:没挂上时每步新建一个
252
+ * worker。30s 是两者的折中:最坏多付 30s 的无缓存,之后自动回到稳态。
253
+ *
254
+ * 同时兼作"worker 已崩"的复活间隔 —— 崩溃同样只表现为 `attached()` 为 false。
255
+ */
256
+ const WATCH_RETRY_MS = 30000;
257
+ let memoriesWatch = null;
258
+ let memoriesWatchAt = 0;
259
+ /** 清空探测缓存(watcher 报变化 / 写操作后 / 索引不可信时)。 */
260
+ const clearProbeCache = () => { probeCache.clear(); };
261
+ /**
262
+ * 取数时确保监听在。**推迟到首次使用**:apply 期 `roots()` / 目录物化会读宿主目录,
263
+ * 而这里只需要一个已存在的目录。
264
+ *
265
+ * `attached()` 是异步回来的:刚建出来的那一两拍必然读到 false。所以"没挂上"的重试
266
+ * 只在距上次装配超过 `WATCH_RETRY_MS` 时发生 —— 否则每步都会拆了重建一个 worker。
267
+ */
268
+ const ensureMemoriesWatch = () => {
269
+ const now = Date.now();
270
+ if (memoriesWatch !== null) {
271
+ if (memoriesWatch.attached())
272
+ return;
273
+ if (now - memoriesWatchAt < WATCH_RETRY_MS)
274
+ return;
275
+ try {
276
+ memoriesWatch.dispose();
277
+ }
278
+ catch { /* 旧的拆不掉也不挡新建 */ }
279
+ memoriesWatch = null;
280
+ }
281
+ memoriesWatchAt = now;
282
+ try {
283
+ memoriesWatch = watchDirectories([memoriesRoot], clearProbeCache);
284
+ }
285
+ catch {
286
+ memoriesWatch = null; // 建不出 worker = 没有监听,缓存靠 TTL(见上面的取舍)
287
+ }
288
+ };
289
+ /** 探测:监听挂着时走缓存,否则直连(`clearProbeCache` 之后必然直连一次)。 */
290
+ function probeWithCache(index, override) {
291
+ ensureMemoriesWatch();
292
+ const watched = memoriesWatch !== null && memoriesWatch.attached();
293
+ if (!watched)
294
+ return probeSceneFilesSync(memoriesRoot, index, false, override);
295
+ const key = memoriesRoot + '\u0000' + signatureOfIndex(index) + '\u0000' + scopeKeyOf(override);
296
+ const hit = probeCache.get(key);
297
+ if (hit !== undefined && Date.now() - hit.at < PROBE_CACHE_TTL_MS)
298
+ return hit.value;
299
+ const value = probeSceneFilesSync(memoriesRoot, index, false, override);
300
+ probeCache.set(key, { at: Date.now(), value });
301
+ // 上限:键里带会话覆盖,会话多时会有很多条;100 条 LRU 足够(同一时刻活跃的会话远少于此)。
302
+ while (probeCache.size > 100) {
303
+ const oldest = probeCache.keys().next();
304
+ if (oldest.done === true)
305
+ break;
306
+ probeCache.delete(oldest.value);
307
+ }
308
+ return value;
309
+ }
222
310
  /** 记忆段:注入侧口径(索引不可信或目录读不动 → 抛)。 */
223
311
  function requireSceneMemory(scope) {
224
312
  const index = readIndexSync(stateDir);
225
313
  assertIndexReadable(); // 抛在这里 ⇒ 下面必然处于「索引可信」状态,无需再传 forceDisabled
226
314
  const override = { scene: scope?.scene, memory: scope?.memory };
227
- const probe = probeSceneFilesSync(memoriesRoot, index, false, override);
315
+ const probe = probeWithCache(index, override);
228
316
  const key = scopeKeyOf(scope);
229
317
  const hit = cacheGet(sceneCache, key);
230
318
  if (hit !== undefined && hit.signature === probe.signature)
@@ -248,12 +336,96 @@ export function createMemoriesService(ctx, deps) {
248
336
  return cacheGet(sceneCache, scopeKeyOf(scope))?.value ?? emptySceneMemory();
249
337
  }
250
338
  }
339
+ /**
340
+ * 工作区记忆段:`_ws/<hash16>` 下的用户手写条目,只在本项目成立。
341
+ *
342
+ * 与场景段分开成一条消息:一条"这个仓库用 pnpm"混进"任何对话都成立"的块里,模型会把它
343
+ * 当成通用规则。段内容只由本工作区那一组决定,与"当前启用哪个场景"无关。
344
+ *
345
+ * @param workspaceGroup 目标组;空串 = 本会话没有工作区身份,整段为空(不注入)。
346
+ * @param scope 会话覆盖(只影响缓存分桶与逐条开关)。
347
+ */
348
+ function workspaceMemory(workspaceGroup, scope, budgetBytes) {
349
+ if (workspaceGroup === '')
350
+ return emptySceneMemory();
351
+ // 预算可以与场景记忆段不同:两块共用一个总盘时,工作区那段只能拿剩下的部分。
352
+ const limit = Number.isFinite(budgetBytes) && budgetBytes > 0 ? budgetBytes : maxBytes;
353
+ const index = readIndexSync(stateDir);
354
+ assertIndexReadable();
355
+ const override = { scene: scope?.scene, memory: scope?.memory };
356
+ const probe = probeWithCache(index, override);
357
+ const key = 'ws\u0000' + workspaceGroup + '\u0000' + limit + '\u0000' + scopeKeyOf(scope);
358
+ const hit = cacheGet(wsCache, key);
359
+ if (hit !== undefined && hit.signature === probe.signature)
360
+ return hit.value;
361
+ const value = renderWorkspaceMemory(probe, workspaceGroup, limit);
362
+ cacheSet(wsCache, key, { signature: probe.signature, value });
363
+ return value;
364
+ }
365
+ /**
366
+ * 「场景 + 场景记忆」合并段:场景说明行紧跟着它的记忆条目,同一个域发出去。
367
+ *
368
+ * 为什么合并:场景说明回答「现在在哪个场景、这个场景是干什么的」,场景记忆是「这个场景下
369
+ * 记了哪些条目」—— 两者是同一个问题的框架与内容。拆成两个域时模型读到的顺序是
370
+ * 「场景说明 …(隔一段全局记忆)… 场景记忆」,中间夹着任何别的东西都会让 `## Scene Memories: X`
371
+ * 与它的说明分成两处,模型得自己回头对齐。
372
+ *
373
+ * 全局记忆与自主·全局仍留在 `memoryGlobal` 域:它们在**任何**对话里都成立,不属于某个
374
+ * 场景,混进来会让「全局」与「本场景」的边界消失。
375
+ *
376
+ * 预算:场景说明行固定先扣,剩下的给条目 —— 说明是框架,永远该在场。
377
+ */
378
+ function sceneWithMemoryProjection(scope) {
379
+ const catalog = sceneCatalog(scope);
380
+ const memory = memoryProjection(scope);
381
+ // 只取**非全局桶**的条目:全局记忆留在 `memoryGlobal` 域(它在任何对话里都成立,
382
+ // 不属于某个场景)。留着会让这一域的顺序变成「场景说明 → 全局记忆 → 场景记忆」,
383
+ // 场景说明与它的条目又被隔开 —— 那正是这次要修的东西。
384
+ const sceneBlocks = memory.blocks.filter(function (b) { return b.scene !== GLOBAL_SCENE; });
385
+ // 没有启用任何场景(catalog 为空)→ 这一域没有任何东西可发。
386
+ // 不退回整段记忆:全局记忆归 `memoryGlobal`,两边都发会让它出现两遍。
387
+ if (catalog.text === '' || sceneBlocks.length === 0) {
388
+ if (catalog.text === '')
389
+ return { text: '', body: '', tail: '', bytes: 0, truncated: catalog.truncated, maxBytes: catalog.maxBytes, scenes: [], items: [], dropped: [], blocks: [] };
390
+ }
391
+ // 场景说明行在前,该场景的条目紧跟其后:先读「在哪个场景」,再读这个场景记了什么。
392
+ const catalogText = catalog.text.replace(/\s+$/, '');
393
+ // 逐块重建正文:`blocks[].block` 只有条目本身,分组标题在 `group` 里(`Scene Memories: <名>`)。
394
+ // 同一个场景的标题只在**首条**出现 —— 与 `renderSceneMemory` 的 `header` 语义一致。
395
+ const chunks = [];
396
+ let lastGroup = null;
397
+ for (const b of sceneBlocks) {
398
+ if (b.group !== lastGroup) {
399
+ lastGroup = b.group;
400
+ chunks.push('## ' + b.group);
401
+ }
402
+ chunks.push(b.block);
403
+ }
404
+ const body = chunks.join('\n\n').replace(/\n{3,}/g, '\n\n');
405
+ const parts = [catalogText];
406
+ if (body !== '')
407
+ parts.push(body);
408
+ const note = catalog.truncated || memory.truncated ? SCENE_MEMORY_NOTE_PARTIAL : SCENE_MEMORY_NOTE;
409
+ const text = parts.join('\n\n') + '\n\n' + note;
410
+ return {
411
+ text,
412
+ body: parts.join('\n\n'),
413
+ tail: '',
414
+ bytes: byteLen(text),
415
+ truncated: catalog.truncated || memory.truncated,
416
+ maxBytes: catalog.maxBytes,
417
+ scenes: catalog.scenes,
418
+ items: memory.items.filter(function (it) { return it.scene !== GLOBAL_SCENE; }),
419
+ dropped: memory.dropped.filter(function (it) { return it.scene !== GLOBAL_SCENE; }),
420
+ blocks: sceneBlocks,
421
+ };
422
+ }
251
423
  /** 场景段:只有注入侧一个消费者,直接按注入口径(读失败抛)。 */
252
424
  function sceneCatalog(scope) {
253
425
  const index = readIndexSync(stateDir);
254
426
  assertIndexReadable();
255
427
  const override = { scene: scope?.scene, memory: scope?.memory };
256
- const probe = probeSceneFilesSync(memoriesRoot, index, false, override);
428
+ const probe = probeWithCache(index, override);
257
429
  const key = scopeKeyOf(scope);
258
430
  const hit = cacheGet(sceneCatalogCache, key);
259
431
  if (hit !== undefined && hit.signature === probe.signature)
@@ -552,16 +724,11 @@ export function createMemoriesService(ctx, deps) {
552
724
  return lines.join('\n') + String(body ?? '');
553
725
  }
554
726
  /**
555
- * update 时重写文件:只替换 name / description 的取值行,其余字段、嵌套、注释与顺序逐字保留。
556
- * `description === undefined` 表示保留原值,`null` 表示删除该字段。
727
+ * update 时重写文件:只替换 name 的取值行,其余字段、嵌套、注释与顺序逐字保留。
728
+ * 盘上残留的旧 `description:` 行**不主动删**:记忆文件是用户资产,读侧已忽略它。
557
729
  */
558
- function serializeUpdatedFile(text, newName, description, body) {
559
- const updates = { name: newName };
560
- if (description === null)
561
- updates.description = null;
562
- else if (description !== undefined)
563
- updates.description = description;
564
- return rewriteFrontmatterFields(text, updates, body);
730
+ function serializeUpdatedFile(text, newName, body) {
731
+ return rewriteFrontmatterFields(text, { name: newName }, body);
565
732
  }
566
733
  /**
567
734
  * 写操作成功后:失效快照 + 丢弃场景记忆段缓存 + 通知 provider。
@@ -575,6 +742,30 @@ export function createMemoriesService(ctx, deps) {
575
742
  // 都可能不同(比如某条记忆被本会话覆盖关掉),逐条算哪几条受影响只会漏。
576
743
  sceneCache.clear();
577
744
  sceneCatalogCache.clear();
745
+ // 探测缓存同样清:写操作刚改了磁盘,下一拍必须重扫(监听会晚 200ms 才报,别等它)。
746
+ clearProbeCache();
747
+ // 顺带重建自动记忆的派生索引:删除 / 编辑一条自动记忆走的是本服务的 op,
748
+ // 它不知道 catalog 的存在,而注入只读 catalog —— 不在这里重建,用户就会看到
749
+ // "删了还在注入"。全量重建 300 条约 40ms,写操作本来就不频繁,值得。
750
+ await rebuildCatalog().catch(() => { });
751
+ };
752
+ /**
753
+ * 全量重建 `evolution/catalog.json`(派生数据:丢了可重建)。
754
+ *
755
+ * 两个入口共用:启动时(补齐历史条目 / 版本不符 / 文件缺失)与每次记忆写之后。
756
+ * 失败一律吞掉 —— 派生索引坏了的后果是"这轮注入少几条",而抛出去会让写操作假失败。
757
+ */
758
+ const rebuildCatalog = async () => {
759
+ // 一次性迁移放在重建之前:老版本把自动条目写在 memories/ 下,不搬过来它们就永远
760
+ // 不进这份 catalog。marker 让这一步整体幂等,写后每次重建也不会重复搬。
761
+ await migrateLegacyAutoNotes({ memoriesRoot, stateDir, autoRoot: autoNotesRoot }).catch(() => undefined);
762
+ // 读**自主库自己那份**索引,不是用户记忆的 memories-index.json:启停 / 置顶是两码事,
763
+ // 共用一份就会出现「用户停用了一个场景,自动条目跟着消失」。
764
+ await mkdir(autoNotesRoot, { recursive: true });
765
+ const index = await readIndex(autoNotesRoot);
766
+ const built = await buildCatalog(autoNotesRoot, index);
767
+ await mkdir(join(stateDir, 'evolution'), { recursive: true });
768
+ await writeFileAtomically(catalogPathOf(stateDir), JSON.stringify(built, null, 2) + '\n', { mode: 0o600 });
578
769
  };
579
770
  /**
580
771
  * 场景档案引擎专用:读-改-写 mode/archives/active 切片(写队列内,保持与其余索引写串行)。
@@ -748,7 +939,10 @@ export function createMemoriesService(ctx, deps) {
748
939
  // - `promptText`:全局提示词正文 = 场景期间用场景提示词、平时用 AGENTS.md 正文。
749
940
  // **不判"与文件重复"** —— 预设挂了官方 agent-instructions 时那份正文已经由文件送达
750
941
  // (注入侧会跳过整个域),没挂时(极简)才需要注入兜底;判定在注入器的 `selectInjections` 里。
751
- const memoryText = (scope) => requireSceneMemory(scope).text;
942
+ const memoryProjection = (scope) => requireSceneMemory(scope);
943
+ const workspaceMemoryText = (group, scope, budgetBytes) => workspaceMemory(group, scope, budgetBytes).text;
944
+ const workspaceMemoryProjection = (group, scope, budgetBytes) => workspaceMemory(group, scope, budgetBytes);
945
+ const memoryText = (scope) => memoryProjection(scope).text;
752
946
  // 场景段。与记忆段是**两次探测**:`probeSceneFilesSync` 没有内部缓存(signature 本身就是
753
947
  // 扫描的结果,缓存不了),代价是有界的一次目录树 stat(**不读正文**),换来两段各自渲染、
754
948
  // 各自去重 —— 只改场景描述时不会连带重发整段记忆正文。
@@ -958,6 +1152,7 @@ export function createMemoriesService(ctx, deps) {
958
1152
  ...(deps.skillsTrashDir ? { skillsTrashDir: deps.skillsTrashDir } : {}),
959
1153
  snapshot, invalidateSnapshot, sceneMemory, scenePrompt,
960
1154
  scopeOverrideOf: (sessionId) => deps.scopeOverrideOf?.(sessionId),
1155
+ ...(deps.workspacesOf === undefined ? {} : { workspacesOf: deps.workspacesOf }),
961
1156
  parseId, locateRule, refuseOutsideRoot, buildProjected, sceneRows,
962
1157
  copyIntoMemoriesTrash, listAttachments, serializeRuleFile, serializeUpdatedFile,
963
1158
  ensureLayout, presetExistsSync,
@@ -1033,11 +1228,23 @@ export function createMemoriesService(ctx, deps) {
1033
1228
  ops,
1034
1229
  writeOps,
1035
1230
  memoryText,
1231
+ memoryProjection,
1232
+ sceneWithMemoryProjection,
1233
+ workspaceMemoryText,
1234
+ workspaceMemoryProjection,
1036
1235
  sceneCatalogText,
1037
1236
  promptText,
1038
1237
  promptFiles,
1039
1238
  promptBaselineText: readGlobalAgentsMdSync,
1040
1239
  refresh,
1240
+ dispose: () => {
1241
+ try {
1242
+ memoriesWatch?.dispose();
1243
+ }
1244
+ catch { /* 卸载路径上不留抛错 */ }
1245
+ memoriesWatch = null;
1246
+ probeCache.clear();
1247
+ },
1041
1248
  patchIndex,
1042
1249
  saveArchive,
1043
1250
  readArchiveSlice,
@@ -1052,6 +1259,34 @@ export function createMemoriesService(ctx, deps) {
1052
1259
  }
1053
1260
  return out;
1054
1261
  },
1262
+ // 自动记忆管线的第二个调用方(见接口注释):四样都是本域内部已有的能力,这里只是
1263
+ // 明确地交出去,不新增实现。
1264
+ autoAccess: {
1265
+ snapshot,
1266
+ // 笔记库有自己的根与自己的索引;门禁读它,不能拿用户记忆快照顶替。
1267
+ // 不写索引清理:预演在写锁外跑,写清理会与真正的写入并发。
1268
+ autoSnapshot: () => buildSnapshot(autoNotesRoot, autoNotesRoot, { writeCleanup: false }),
1269
+ serializeRuleFile,
1270
+ // 同步版:注入的 `text(agent)` 没有 await 的位置。读不到索引就当"没有启用场景",
1271
+ // 失败方向是"少注入场景层"而不是"把工作区层也关掉"。
1272
+ activeSceneSync: (scope) => {
1273
+ try {
1274
+ return enabledSceneOf(readIndexSync(stateDir), scope?.scene);
1275
+ }
1276
+ catch {
1277
+ return null;
1278
+ }
1279
+ },
1280
+ memoriesRoot,
1281
+ /** 自主记忆自己的根目录(装配 learner 时传它,别再传 memoriesRoot)。 */
1282
+ autoNotesRoot,
1283
+ stateDir,
1284
+ // 自动段与手写段共用同一个盘:两块都进同一次对话的上下文,各算一份就没人说得清
1285
+ // "一共能吃多少"。
1286
+ maxBytes,
1287
+ invalidateSnapshot,
1288
+ rebuildCatalog,
1289
+ },
1055
1290
  };
1056
1291
  return service;
1057
1292
  }