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
@@ -1,12 +1,13 @@
1
- // 记忆(rules)域的 model 工具:memory_manager_list / _read / _search / _switch / _save。
1
+ // 记忆(rules)域的 model 工具:memory_get / memory_switch / memory_remember。
2
2
  //
3
- // 为什么族名是 `memory_manager_` 而不是 `scene_memory_manager_`:后者是为了跟注入段名
4
- // (`scene-memory-manager-catalog`)对齐才改的,但那个名字描述的是**域**,
5
- // 而这个族操作的全是记忆。加场景能力时这个错配就现形了 —— 场景是另一个对象(容器,
6
- // 进入时切换 mcp / 技能 / 人设),硬塞进 `save` 会让 `description` 变成双义参数(给
7
- // `memory` 时是记忆描述、给 `scene` 时是场景描述),门禁也得按参数分叉(记忆写入有开关
8
- // 可放行,场景写入是改运行时环境、不该有那条路)。所以拆成两族:这里管记忆内容,
9
- // `scene_manager_*`(tools/scene.ts)管场景本身。
3
+ // 自主笔记(agent 学的一句话)是另一族 `memory_note`:两族按对象分开,读取统一走
4
+ // `memory_get`,id 形状也不同(用户记忆 `<scene>/<name>`,笔记 `note:<layer>/<slug>`)。
5
+ //
6
+ // 为什么工具名是 `memory_*` 而不是 `scene_memory_manager_*`:后者描述的是**域**,
7
+ // 而这些工具操作的全是记忆。加场景能力时这个错配就现形了 —— 场景是另一个对象(容器,
8
+ // 进入时切换 mcp / 技能 / 人设),硬塞进同一个写工具会让 `description` 变成双义参数、
9
+ // 门禁按参数分叉(记忆写入有开关可放行,场景写入是改运行时环境、不该有那条路)。
10
+ // 所以拆成两族:这里管记忆内容,`scene_manager_*`(tools/scene.ts)管场景本身。
10
11
  //
11
12
  // 场景清单也不挂在这条 list 的尾巴上(「记忆就管记忆,场景就管场景」)——
12
13
  // 它在 `scene_manager_list`,理由记在 tools/scene.ts 头部,别当"少写了一段"再加回来。
@@ -16,176 +17,492 @@
16
17
  // 模型必须自己先查一次再决定调哪条,而它手里的清单可能已经过期。合并后由工具侧兜住。
17
18
  //
18
19
  // 活动场景的记忆正文会自动注入上下文(无需调用工具读取);这里的工具用于查询/编辑规则
19
- // 本身。memory_manager_save 受 tools/pre-execute 审批门禁。
20
+ // 本身。memory_remember 受 tools/pre-execute 审批门禁。
20
21
  // 路径锚点:$DSH_HOME/tool-management/memories/<场景>/…(场景 `global` = 界面「全局」)。
21
- import { GLOBAL_SCENE, SHARED_GROUP } from '../memories/constants.js';
22
- import { candidateNote, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, listLimit, moreNotShown, scopeOnlyNote, scopeSessionDesc, sessionScopeOf, text } from './deps.js';
22
+ import { GLOBAL_SCENE, MAX_GROUP_SEGMENT_LENGTH, SHARED_GROUP } from '../memories/constants.js';
23
+ import { MAX_AUTO_TEXT_WIDTH, MAX_AUTO_TITLE_WIDTH } from '../evolution/write.js';
24
+ import { textContains } from '../evolution/gates.js';
25
+ import { textWidthOf, truncateToWidth } from '../text-width.js';
26
+ import { LIST_LIMIT_MAX, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, listLimit, moreNotShown, scopeOnlyNote, scopeSessionDesc, sessionScopeOf, text, toolOrNeutral } from './deps.js';
27
+ import { PROACTIVE_MEMORY_TOOL } from './table.js';
28
+ import { isNoteRef, noteRefOf, stripNoteRef } from './note-ref.js';
23
29
  /** 注册记忆域的 model 工具(列表 / 读取 / 检索 / 切换 / 保存)。 */
24
30
  export function buildMemoryTools(deps) {
25
31
  const { defineTool, register } = deps;
32
+ /**
33
+ * 运行时点名自主笔记工具:它不在工具表里时退回中性说法。
34
+ *
35
+ * 静态描述不能点名(契约测试拦),错误消息与回执同理 —— 指一条模型没有的工具
36
+ * 等于把它往墙上推。`toolOrNeutral` 只在可见时说出真实名字。
37
+ */
38
+ const noteTool = (agent, named, neutral) => toolOrNeutral(deps, agent, PROACTIVE_MEMORY_TOOL, named, neutral);
39
+ const evo = deps.evolutionOps;
40
+ /**
41
+ * 取一个自主记忆 op,缺失就抛。
42
+ *
43
+ * `evolutionOps` 的类型是 `Record<string, fn>`,所以严格模式下每个索引取值都是
44
+ * 「可能 undefined」;实际上这张表由 `buildEvolutionOps` 一次构造成完整对象,
45
+ * 要么全有、要么整个 `evolutionOps` 是 undefined(已被调用点的 `if (!evo)` 拦住)。
46
+ * 收口成一个取值函数:类型检查过得了,真缺 op 时也报得出是哪一个。
47
+ */
48
+ const opOf = (table, name) => {
49
+ const fn = table[name];
50
+ if (typeof fn !== 'function')
51
+ throw new Error('missing op: ' + name + ' (the plugin is only partly assembled)');
52
+ return fn;
53
+ };
54
+ // 开关决定能力面:关掉的层连 `layer` 参数都不该出现。省略依赖时按两层都开处理,
55
+ // 让旧装配 / 单元测试保持原行为。
56
+ const noteLayersOf = (agent) => {
57
+ const got = deps.autoNoteLayers ? deps.autoNoteLayers(agent) : undefined;
58
+ return got ?? { global: true, workspace: true };
59
+ };
60
+ const noteReadLayersOf = (agent) => {
61
+ const got = deps.autoNoteReadLayers
62
+ ? deps.autoNoteReadLayers(agent)
63
+ : deps.autoNoteLayers ? deps.autoNoteLayers(agent) : undefined;
64
+ return got ?? { global: true, workspace: true };
65
+ };
66
+ // 只有两层都开时层才是模型要选的东西;只剩一层时强制那一层,schema 里不留 `layer`。
67
+ const noteLayerParameter = {
68
+ type: 'string',
69
+ enum: ['global', 'workspace'],
70
+ description: 'global = every project; workspace = this project. Omit when unsure: the user chooses the layer on the card, or its default applies.',
71
+ };
72
+ const applyNoteLayerSchema = (tool, layers) => {
73
+ const properties = tool && tool.parameters && tool.parameters.properties;
74
+ if (!properties)
75
+ return;
76
+ if (layers.global && layers.workspace)
77
+ properties.layer = noteLayerParameter;
78
+ else
79
+ delete properties.layer;
80
+ };
81
+ /**
82
+ * 这条规则是不是自主笔记而不是用户记忆。
83
+ *
84
+ * `memory_get` 把两族并成一份输出,用户记忆那一半必须把笔记摘掉 —— 否则同一句话
85
+ * 会在「user memories」与「agent notes」各出现一次。`origin` 是权威字段;旧数据
86
+ * 没有它时按目录判(`_ws` / `_session` 只由笔记后端写入,见 memories/catalog.ts)。
87
+ */
88
+ const isAutoRule = (x) => {
89
+ if (x && x.origin === 'auto')
90
+ return true;
91
+ if (x && x.origin === 'user')
92
+ return false;
93
+ // 搜索结果把场景叫 `scene`,清单叫 `group`;两边都要认。
94
+ const group = String((x && (x.group !== undefined ? x.group : x.scene)) || '');
95
+ return group === '_ws' || group.startsWith('_ws/') ||
96
+ group === '_session' || group.startsWith('_session/');
97
+ };
98
+ /**
99
+ * 把模型给的引用解析成一条笔记:id(可带 `note:`)→ slot → title → 原文,唯一命中才算。
100
+ *
101
+ * 三条口径(都由真实测试暴露出来):
102
+ * - **原文 = 注入行里那一行**(`oneLine`,去标点的首句),不是整段正文。模型的引用
103
+ * 来自它看到的注入行,让它去猜"整段正文"只会白试一轮。末尾标点也一并忽略。
104
+ * - **先按活跃状态过滤**:同 slot 冲突替换后会留下一条 `superseded`,它与新的那条
105
+ * 同 key。不过滤就会报 ambiguous —— 而 agent 用 slot 当稳定句柄的前提就没了。
106
+ * 只有多条**活跃**同引用时才报歧义,防删错的初衷不变。
107
+ * - 活跃状态一个都没有时退回全量匹配,让错误消息能给出候选。
108
+ */
109
+ const resolveNote = async (ref) => {
110
+ const raw = stripNoteRef(ref);
111
+ if (raw === '' || !evo)
112
+ return { id: null, hits: [] };
113
+ const list = await opOf(evo, 'evolution-list')({ all: true });
114
+ const rows = list && Array.isArray(list.entries) ? list.entries : [];
115
+ const trimEnd = (s) => String(s ?? '').replace(/[。..!!??\s]+$/, '');
116
+ const matches = (e) => String(e.id || '') === raw ||
117
+ String(e.key || '') === raw ||
118
+ String(e.title || '') === raw ||
119
+ String(e.oneLine || '') === raw ||
120
+ trimEnd(e.oneLine) === trimEnd(raw);
121
+ const live = rows.filter((e) => {
122
+ const st = String(e.status || '');
123
+ return st === 'candidate' || st === 'active' || st === 'core' || st === 'playbook';
124
+ });
125
+ const activeHits = live.filter(matches);
126
+ if (activeHits.length === 1)
127
+ return { id: String(activeHits[0].id), hits: activeHits };
128
+ if (activeHits.length > 1)
129
+ return { id: null, hits: activeHits };
130
+ const hits = rows.filter(matches);
131
+ return hits.length === 1 ? { id: String(hits[0].id), hits } : { id: null, hits };
132
+ };
133
+ const describeNoteHits = (hits) => hits.map((e) => noteRefOf(String(e.id)) + (e.title ? ' (' + String(e.title) + ')' : '')).join(', ');
134
+ /** forget 的引用参数:新名 `note`,旧名 `memory` 兼容一次(改名前的调用习惯)。 */
135
+ const noteArgOf = (a) => String((a && (a.note !== undefined ? a.note : a.memory)) || '').trim();
136
+ /**
137
+ * 用户记忆里有没有一条已经在说这件事。有就返回它的 id,没有返回 `null`。
138
+ *
139
+ * 为什么要在**写笔记之前**查:两族记忆的保留策略完全不同 —— 用户记忆永久、恒注入、
140
+ * 不进回收站;笔记会被 TTL 提醒、被合并、被归档。模型看不见这个差别,于是同一条规则
141
+ * 常常在页面上出现两遍,而其中一遍会自己过期。
142
+ *
143
+ * 判据故意保守(**只拦明确重复**):
144
+ * - 归一化后正文完全相同;或
145
+ * - 一方是另一方的子串,且短的那边不短于 `COVER_MIN_WIDTH`。
146
+ *
147
+ * 不做语义相似度:笔记的价值恰恰在"换个说法补上用户没写的那半句",模糊匹配会把
148
+ * 真正该记的补充拦掉。宁可偶尔留一条冗余,也不要让模型学不到东西。
149
+ *
150
+ * 读不到记忆清单时返回 `null`(照常写):一次读失败不该变成"什么都不记"。
151
+ */
152
+ const userMemoryCovering = async (text) => {
153
+ /** 短边至少要有的实义字符数:比冲突门宽松,宁可偶尔留一条冗余也不拦掉真正的补充。 */
154
+ const COVER_MIN_CHARS = 8;
155
+ const want = String(text ?? '').trim();
156
+ if (want === '')
157
+ return null;
158
+ let all;
159
+ try {
160
+ all = await opOf(deps.rulesOps, 'rules-list')({});
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ if (!all || all.ok === false || !Array.isArray(all.rules))
166
+ return null;
167
+ for (const x of all.rules) {
168
+ if (isAutoRule(x))
169
+ continue;
170
+ const have = String((x && (x.body !== undefined ? x.body : x.text)) ?? '');
171
+ if (have.trim() === '')
172
+ continue;
173
+ // 包含判据只有一份实现(`textContains`):这里自己写一套 `includes` 会在标点、
174
+ // 空白与大小写口径上与冲突门分家,同一条内容可能"记忆页说是重复、写入侧说不是"。
175
+ if (textContains(have, want, COVER_MIN_CHARS))
176
+ return String(x.id);
177
+ }
178
+ return null;
179
+ };
180
+ /** 一条笔记的正文 + 证据链;`note:` 前缀由调用方决定是否剥掉。 */
181
+ const noteReadText = async (ref) => {
182
+ if (!evo)
183
+ throw new Error('agent notes are not available in this build');
184
+ const raw = stripNoteRef(ref);
185
+ if (raw === '')
186
+ throw new Error('missing argument: id — the note id (note:...), its slot, its title, or the first line of the note as injected (trailing punctuation ignored).');
187
+ let a = await opOf(evo, 'evolution-read')({ id: raw, touch: true });
188
+ if (!a || a.ok === false) {
189
+ const resolved = await resolveNote(raw);
190
+ if (resolved.id !== null)
191
+ a = await opOf(evo, 'evolution-read')({ id: resolved.id, touch: true });
192
+ else if (resolved.hits.length > 1) {
193
+ throw new Error('ambiguous: "' + ref + '" matches ' + describeNoteHits(resolved.hits) + '; pass one of these ids.');
194
+ }
195
+ }
196
+ if (!a || a.ok === false)
197
+ throw new Error(String((a && a.error) || 'no such agent note: ' + ref));
198
+ const st = a.state || {};
199
+ const bits = [
200
+ 'status ' + String(a.status || 'active'),
201
+ // 档位取代原来的 confidence 小数:三档能直接读懂,小数只由来源表换算。
202
+ 'tier ' + String(a.tier || 'inferred'),
203
+ a.layer,
204
+ // 类型是「这条以后怎么用」的判据:做法要照着执行,偏好只是风格,事实是可核对的陈述。
205
+ // 它同时决定保质期,所以读全文时也该看见。
206
+ ...(a.kind ? ['kind ' + String(a.kind)] : []),
207
+ ];
208
+ const lines = ['# ' + noteRefOf(String(a.id || raw)) + ' (agent note)', bits.join(' · ')];
209
+ if (a.title)
210
+ lines.push('title: ' + String(a.title));
211
+ if (a.key)
212
+ lines.push('slot: ' + String(a.key));
213
+ if (a.basis)
214
+ lines.push('basis: ' + String(a.basis));
215
+ if (a.boundary)
216
+ lines.push('boundary: ' + String(a.boundary));
217
+ if (a.alias)
218
+ lines.push('also said as: ' + String(a.alias));
219
+ if (a.degraded)
220
+ lines.push('degraded: ' + String(a.degraded));
221
+ lines.push('', String(a.body || ''));
222
+ const ev = Array.isArray(st.evidence) ? st.evidence : [];
223
+ if (ev.length) {
224
+ lines.push('', 'evidence (latest ' + ev.length + '):');
225
+ for (const e of ev)
226
+ lines.push('- [' + String(e.source || '') + '] ' + String(e.quote || '').slice(0, 200));
227
+ }
228
+ const tr = Array.isArray(st.transitions) ? st.transitions : [];
229
+ if (tr.length) {
230
+ lines.push('', 'timeline:');
231
+ for (const x of tr)
232
+ lines.push('- ' + String(x.at || '') + ' ' + String(x.from || '') + ' → ' + String(x.to || '') + ' (' + String(x.actor || '') + ': ' + String(x.reason || '') + ')');
233
+ }
234
+ return lines.join('\n');
235
+ };
236
+ const noteCatalogText = async (all, limit, layers) => {
237
+ if (!evo)
238
+ return '';
239
+ const r = await opOf(evo, 'evolution-list')({ all });
240
+ if (!r || r.ok === false)
241
+ throw new Error(String((r && r.error) || 'failed to read agent notes'));
242
+ const rows = (Array.isArray(r.entries) ? r.entries : [])
243
+ .filter((e) => e.layer === 'workspace' ? layers.workspace : layers.global);
244
+ const shown = rows.slice(0, limit);
245
+ const order = ['workspace', 'global'].filter((l) => l === 'workspace' ? layers.workspace : layers.global);
246
+ const lines = [];
247
+ for (const layer of order) {
248
+ const group = shown.filter((e) => e.layer === layer);
249
+ if (!group.length)
250
+ continue;
251
+ lines.push('[' + layer + ']');
252
+ for (const e of group) {
253
+ // slot 与 id 末段相同时不重复写:模型要的是「怎么引用这条」,id 已经给了;
254
+ // 两者不同才需要说明(合并时显式 slot 会覆盖 id 末段)。
255
+ lines.push('- ' + noteRefOf(String(e.id)) + ' · ' + String(e.status || 'active') +
256
+ (e.key && String(e.key) !== String(e.id).slice(String(e.id).lastIndexOf('/') + 1) ? ' · slot ' + String(e.key) : '') +
257
+ (e.title ? ' · ' + String(e.title) : '') +
258
+ // 类型决定保质期,也是「这条是做法还是偏好」的唯一机器可读标记:
259
+ // 模型要靠它决定该不该照着做、值不值得 `memory_get` 读全文。
260
+ // `evolution-list` 一直在返回 `kind`,这里此前没读。
261
+ (e.kind ? ' · ' + String(e.kind) : '') +
262
+ ' · ' + String(e.tier || 'inferred') +
263
+ ' · ' + (e.injects ? 'injects' : 'not injected') +
264
+ (e.pendingReason ? ' · pending: ' + String(e.pendingReason) : '') +
265
+ (e.reviewDue ? ' · review due: ' + String(e.reviewDue) : '') +
266
+ (e.oneLine ? ' — ' + String(e.oneLine) : ''));
267
+ }
268
+ }
269
+ // 总数只在两层都开时可信:只剩一层时 `r.total` 含已关层的条目,报出来就是泄漏。
270
+ const both = layers.global && layers.workspace;
271
+ const head = 'agent notes: ' + rows.length + ' listed' +
272
+ (both && r.total !== undefined ? ' / ' + r.total + ' in catalog' : '') +
273
+ (rows.length > shown.length ? ' (showing ' + shown.length + ', raise limit for more)' : '');
274
+ return head + '\n' + (lines.join('\n') || '(none)');
275
+ };
276
+ const noteSearchText = async (query, limit, layers) => {
277
+ if (!evo)
278
+ return '';
279
+ // 与用户记忆搜索同口径:搜索覆盖归档 / 未注入的条目,`all` 只影响清单。
280
+ // 带正文:`oneLine` 只是压平后按 160 宽度截断的摘要,只搜它等于搜不到正文后半截。
281
+ const r = await opOf(evo, 'evolution-list')({ all: true, withBody: true });
282
+ if (!r || r.ok === false)
283
+ throw new Error(String((r && r.error) || 'failed to read agent notes'));
284
+ const words = query.toLowerCase().split(/\s+/).filter((w) => w !== '');
285
+ const rows = (Array.isArray(r.entries) ? r.entries : [])
286
+ .filter((e) => e.layer === 'workspace' ? layers.workspace : layers.global)
287
+ .filter((e) => {
288
+ // `kind` 也要能搜:结果行里印着它(「列出所有做法类笔记」是很自然的请求),
289
+ // 只显示不索引等于「看得见、搜不到」。类型是四个固定词,不会污染正文匹配。
290
+ const hay = [e.id, e.key, e.title, e.oneLine, e.body, e.boundary, e.alias, e.kind]
291
+ .map((x) => String(x || '').toLowerCase()).join(' ');
292
+ return words.every((w) => hay.includes(w));
293
+ });
294
+ const shown = rows.slice(0, limit);
295
+ const lines = shown.map((e) => '- ' + noteRefOf(String(e.id)) + ' · ' + String(e.status || 'active') +
296
+ (e.kind ? ' · ' + String(e.kind) : '') +
297
+ (e.title ? ' · ' + String(e.title) : '') +
298
+ (e.oneLine ? ' — ' + String(e.oneLine) : ''));
299
+ return 'agent notes matching "' + query + '": ' + rows.length +
300
+ (rows.length > shown.length ? ' (showing ' + shown.length + ')' : '') +
301
+ '\n' + (lines.join('\n') || '(none)');
302
+ };
303
+ const userCatalogText = async (all, limit, scene, exec) => {
304
+ const opArgs = {};
305
+ if (scene !== undefined)
306
+ opArgs.group = scene;
307
+ const scoped = sessionScopeOf(deps, exec && exec.agent);
308
+ if (scoped !== null)
309
+ opArgs.sessionId = scoped.sessionId;
310
+ const r = await opOf(deps.rulesOps, 'rules-list')(opArgs);
311
+ if (!r || r.ok === false)
312
+ throw new Error((r && r.error) || 'failed to read memories');
313
+ // 「会注入」的判定与记忆段同源(renderSceneMemory):global 与 _shared 恒常注入,
314
+ // 其余场景要在 index.active 里,再叠加单条 enabled 与同名 bundle 的 shadowed。
315
+ const alwaysInjects = (group) => group === GLOBAL_SCENE || group === SHARED_GROUP;
316
+ const sceneOn = (group) => alwaysInjects(group) ||
317
+ (group !== '' && (r.activeMode === 'all' || String(r.activeScene || '') === group));
318
+ const stateOf = (x) => {
319
+ if (x.shadowed === true)
320
+ return { injects: false, label: 'shadowed' };
321
+ if (x.enabled === false)
322
+ return { injects: false, label: 'disabled' };
323
+ if (!sceneOn(String(x.group || '')))
324
+ return { injects: false, label: 'scene off' };
325
+ return { injects: true, label: 'injects' };
326
+ };
327
+ const rows = (r.rules || []).filter((x) => !isAutoRule(x)).map((x) => ({ x, ...stateOf(x) }));
328
+ const shown = all ? rows : rows.filter((row) => row.injects);
329
+ const visible = shown.slice(0, limit);
330
+ const lines = visible.map(({ x, label }) => ('- ' + x.id + ' [' + (x.group || 'no scene') + '] ' + label +
331
+ (x.form === 'bundle'
332
+ ? ' · bundle' + (x.attach && x.attach.count ? ' (' + x.attach.count + ' attachment(s))' : '')
333
+ : '')));
334
+ const scope = r.activeMode === 'all'
335
+ ? 'every scene (historical default, not narrowed)'
336
+ : (r.activeScene ? '"' + String(r.activeScene) + '"' : 'no scene is on');
337
+ const viewNoun = deps.scopeMode?.() === 'workspace' ? 'this workspace' : 'this conversation';
338
+ const sessionNote = scoped === null || scoped.scope === undefined
339
+ ? ''
340
+ : '\nthis is ' + viewNoun + "'s view" +
341
+ (scoped.scope.scene !== undefined ? ' — scene pinned to "' + scoped.scope.scene + '"; the machine-wide scene may differ' : '') +
342
+ (scoped.scope.memory !== undefined ? '; ' + Object.keys(scoped.scope.memory).length + ' switch(es) applied here' : '');
343
+ const sharedHere = rows.some(({ x }) => String(x.group || '') === SHARED_GROUP);
344
+ const header = 'user memories: ' + (all
345
+ ? rows.length + ' total'
346
+ : shown.length + ' injecting / ' + rows.length + ' total' +
347
+ (shown.length === rows.length ? '' : ' (pass all=true for all)')) +
348
+ '\ninjects from: ' + scope + ' + global' + (sharedHere ? ' + _shared' : '') + ' (always on)' + sessionNote + '\n';
349
+ const notice = await deps.reachNoticeForAgent(deps.presetRoster(), exec && exec.agent && exec.agent.ctx, deps.injectNoticeOptions());
350
+ return header + (lines.join('\n') || '(none)') + moreNotShown(shown.length, visible.length) + notice;
351
+ };
352
+ const userSearchText = async (query, limit, scene, exec) => {
353
+ // 搜索不跟随 `all`:找一条已停用 / 归档的条目正是搜索的用途(新建前先确认有没有)。
354
+ // 带场景过滤时向 op 要满上限,否则 op 先按 limit 截断、再过滤,目标场景的命中会被挤掉。
355
+ const opArgs = { query, limit: scene !== undefined ? LIST_LIMIT_MAX : limit };
356
+ const scoped = sessionScopeOf(deps, exec && exec.agent);
357
+ if (scoped !== null)
358
+ opArgs.sessionId = scoped.sessionId;
359
+ const r = await opOf(deps.rulesOps, 'rules-search')(opArgs);
360
+ if (!r || r.ok === false)
361
+ throw new Error((r && r.error) || 'failed to search memories');
362
+ let hits = Array.isArray(r.hits) ? r.hits : [];
363
+ hits = hits.filter((h) => !isAutoRule(h));
364
+ if (scene !== undefined)
365
+ hits = hits.filter((h) => String(h.scene || '') === scene);
366
+ if (!hits.length)
367
+ return 'user memories: no match for "' + query + '"';
368
+ const lines = hits.slice(0, limit).map((h) => '- ' + h.id + ' [' + (h.scene || 'no scene') + ']' +
369
+ (h.enabled === false ? ' (off here)' : '') +
370
+ (h.snippet ? ' — ' + h.snippet : ''));
371
+ return 'user memories matching "' + query + '": ' + hits.length +
372
+ (hits.length > limit ? ' (showing ' + limit + ')' : '') + '\n' + lines.join('\n');
373
+ };
374
+ const userReadText = async (id, exec) => {
375
+ const r = await opOf(deps.rulesOps, 'rules-read')({ id });
376
+ if (!r || r.ok === false)
377
+ return null;
378
+ const rule = r.rule || {};
379
+ // 自动条目由笔记渲染器负责;这里返回 null,让 readEntry 走 noteReadText。
380
+ if (isAutoRule(rule))
381
+ return null;
382
+ const attach = Array.isArray(rule.attachments) ? rule.attachments : [];
383
+ const form = rule.form === 'bundle' ? 'bundle' : 'flat';
384
+ const attLine = attach.length
385
+ ? '\nattachments (' + attach.length + '): ' + attach.map((a) => String((a && a.name) || a)).join(', ')
386
+ : '';
387
+ const scoped = sessionScopeOf(deps, exec && exec.agent);
388
+ const over = scoped?.scope?.memory?.[String(rule.id)];
389
+ const offHere = over === false
390
+ ? '\n(switched off here only — the body above is not injected here; the global setting is unchanged) '
391
+ : '';
392
+ return '# ' + rule.id + ' (memory, ' + form + ')' + attLine + '\n\n' + (rule.body || '') + offHere;
393
+ };
394
+ const readEntry = async (id, exec) => {
395
+ if (isNoteRef(id))
396
+ return noteReadText(id);
397
+ const mem = await userReadText(id, exec);
398
+ if (mem !== null)
399
+ return mem;
400
+ if (evo) {
401
+ try {
402
+ return await noteReadText(id);
403
+ }
404
+ catch (e) {
405
+ throw new Error('no user memory with id "' + id + '"; ' + (e instanceof Error ? e.message : String(e)));
406
+ }
407
+ }
408
+ throw new Error('no user memory with id "' + id + '". Call memory_get with no id to list what exists.');
409
+ };
410
+ /**
411
+ * 从标题或正文首行派生文件名:保留 Unicode,去掉路径分隔符与控制字符,空白压成 `-`。
412
+ *
413
+ * 用户说的是「记录一下:以后提交前跑测试」,不会给文件 slug。文件名必须是一个合法路径段
414
+ * (`isValidGroupSegment` 允许 Unicode),所以这里只做最低限度的清洗;真正的合法性
415
+ * 仍由 `rules-create` 兜底。
416
+ */
417
+ const slugOf = (raw) => {
418
+ const line = String(raw || '').split('\n').map((l) => l.trim()).find((l) => l !== '') || '';
419
+ const cleaned = line
420
+ .replace(/^#+\s*/, '')
421
+ .replace(/[\\/:*?"<>|\u0000-\u001f]/g, ' ')
422
+ .replace(/\s+/g, '-')
423
+ .replace(/-+/g, '-')
424
+ .replace(/^[-.]+|[-.]+$/g, '')
425
+ .slice(0, MAX_GROUP_SEGMENT_LENGTH);
426
+ return cleaned !== '' ? cleaned : 'memory';
427
+ };
428
+ /** 正文首行(去掉 markdown 标题标记),用于派生描述。 */
429
+ const firstLineOf = (raw) => {
430
+ const line = String(raw || '').split('\n').map((l) => l.trim()).find((l) => l !== '') || '';
431
+ return line.replace(/^#+\s*/, '').slice(0, 500);
432
+ };
433
+ /** 当前可用场景名:`scenes` 行与规则里的 group 取并集(有记忆但没显式记录的场景也要认)。 */
434
+ const sceneNamesOf = (r) => {
435
+ const names = new Set();
436
+ const rows = Array.isArray(r && r.scenes) ? r.scenes : [];
437
+ for (const s of rows) {
438
+ const name = String((s && (s.key || s.name)) || '');
439
+ if (name !== '')
440
+ names.add(name);
441
+ }
442
+ for (const x of (Array.isArray(r && r.rules) ? r.rules : [])) {
443
+ const group = String((x && x.group) || '');
444
+ if (group !== '')
445
+ names.add(group);
446
+ }
447
+ return [...names];
448
+ };
26
449
  register(defineTool({
27
- name: 'memory_manager_list',
28
- // 末尾**不点名** `scene_manager_list`:场景一族在出厂默认里就是关着的,指向一条模型没有的
29
- // 工具只会让它去猜名字(用户 把默认名单扩到十五条时去掉的这句)。
30
- description: 'List memories (id, scene, enabled, form flat|bundle, description) plus the scene the injection follows. What is injected each turn is in the "Current memories" reminder; use this for ids and for entries that are off. Pass `scene` to filter; all=true lists everything.',
31
- parameters: {
32
- // 参数名与其余五个域同词:同一个概念在工具面只该有一个名字
33
- // 而 `scene` 是它在 `scene_manager_*`、`<scene>/<name>` 与注入段标题里的叫法。
34
- // op 的内部契约字段仍是 `group`(`rules-list` 与界面侧调用方都读它),所以 execute 里
35
- // 显式映射一次 —— 改 op 的字段名要动界面,那不是这一条能顺手做的事。
36
- scene: { type: 'string', description: 'Optional scene filter; `global` and `_shared` are the always-on scenes.' },
37
- all: { type: 'boolean', description: 'Include memories that are off, in an inactive scene, or shadowed (default false).' },
38
- limit: { type: 'number', description: 'Max entries (default 50, max 100).' },
39
- },
40
- output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
41
- async execute(args, exec) {
42
- const showAll = Boolean(args && args.all === true);
43
- // `scene` → `group`:只把 op 认的那个字段传过去,别把 `scene` 也塞给它(它不认)。
44
- const opArgs = {};
45
- if (args && args.scene !== undefined)
46
- opArgs.group = args.scene;
47
- // 会话层(`memory_manager_list` 只列本会话场景):带上 sessionId,
48
- // op 就按本会话钉住的场景与逐条开关投影 —— 「会注入」这一栏与模型真实看到的一致。
49
- // 取不到会话 = 不给,op 退回全局口径(不报错)。
50
- const scoped = sessionScopeOf(deps, exec && exec.agent);
51
- if (scoped !== null)
52
- opArgs.sessionId = scoped.sessionId;
53
- const r = await deps.rulesOps['rules-list'](opArgs);
54
- if (!r || r.ok === false)
55
- throw new Error((r && r.error) || 'failed to read memories');
56
- // 「会注入」的判定与记忆段同源(renderSceneMemory):global 场景恒常注入,其余场景要
57
- // 在 index.active 里,再叠加单条 enabled 与同名 bundle 的 shadowed。默认只列这些,
58
- // 全列一次会把没启用的条目也算进上下文(与技能列表同口径)。
59
- //
60
- // **两个**保留桶恒常注入,不是一个:`global`(界面「全局」)之外还有 `_shared`
61
- // (公共基线)。注入侧 `resolveActiveScenes` 无条件把两者都放进 active
62
- // (见 memories/projection.ts),这里只认 `global` 就会把 `_shared` 标成
63
- // "scene off" 并默认藏起来 —— 而它每轮都在上下文里。模型照这份名单回答
64
- // 「没有这条记忆」,实际它正躺在自己眼前。`activeScene` 永远报不到 `_shared`
65
- // (`enabledSceneOf` 只回非保留场景),所以只能在这一层显式认。
66
- const alwaysInjects = (group) => group === GLOBAL_SCENE || group === SHARED_GROUP;
67
- const sceneOn = (group) => alwaysInjects(group) ||
68
- (group !== '' && (r.activeMode === 'all' || String(r.activeScene || '') === group));
69
- const stateOf = (x) => {
70
- if (x.shadowed === true)
71
- return { injects: false, label: 'shadowed' };
72
- if (x.enabled === false)
73
- return { injects: false, label: 'disabled' };
74
- if (!sceneOn(String(x.group || '')))
75
- return { injects: false, label: 'scene off' };
76
- return { injects: true, label: 'injects' };
77
- };
78
- const rows = (r.rules || []).map((x) => ({ x, ...stateOf(x) }));
79
- const shown = showAll ? rows : rows.filter((row) => row.injects);
80
- // 返回体也要有上限:返回值进上下文,而工具表只管 schema —— 这一笔它管不着。
81
- const limit = listLimit(args && args.limit);
82
- const visible = shown.slice(0, limit);
83
- const lines = visible.map(({ x, label }) => ('- ' + x.id + ' [' + (x.group || 'no scene') + '] ' + label +
84
- // 形态与附件:此前不报,模型分不清哪条是 bundle、更不知道它带了几个附件
85
- // (`rules-list` 早就把 `form` 与 bundle 的附件摘要给了出来,只是这里没渲染)。
86
- (x.form === 'bundle'
87
- ? ' · bundle' + (x.attach && x.attach.count ? ' (' + x.attach.count + ' attachment(s))' : '')
88
- : '') +
89
- (x.description ? ' — ' + x.description : '')));
90
- // 注入按哪个场景走 —— 上面那句「场景未启用」只有配上它才可解读:少了这一行,
91
- // 模型看到一片"未启用"会以为是条目自己的问题。(场景本身的清单在 `scene_manager_list`,
92
- const scope = r.activeMode === 'all'
93
- ? 'every scene (historical default, not narrowed)'
94
- : (r.activeScene ? '"' + String(r.activeScene) + '"' : 'no scene is on');
95
- // 会话层:本会话钉了场景 / 改了个别开关时,上面那行报的是**本会话**的投影
96
- // 与全局可能不同。不说清的话,模型会拿这份名单去回答"全局现在是什么" —— 那是错的答案。
97
- // 粒度决定这句话的主语:工作区粒度下那一格是同工作区共享的,"本对话"是假话。
98
- const viewNoun = deps.scopeMode?.() === 'workspace' ? 'this workspace' : 'this conversation';
99
- const sessionNote = scoped === null || scoped.scope === undefined
100
- ? ''
101
- : '\nthis is ' + viewNoun + "'s view" +
102
- (scoped.scope.scene !== undefined ? ' — scene pinned to "' + scoped.scope.scene + '"; the machine-wide scene may differ' : '') +
103
- (scoped.scope.memory !== undefined ? '; ' + Object.keys(scoped.scope.memory).length + ' switch(es) applied here' : '');
104
- // `_shared` 只在真有这类条目时点名:没有就不付这几个字,而有了不说的话,
105
- // 上面那句「只列会注入的」会让人以为名单里全是 global + 当前场景。
106
- const sharedHere = rows.some(({ x }) => String(x.group || '') === SHARED_GROUP);
107
- const header = 'memories: ' + (showAll
108
- ? rows.length + ' total'
109
- : shown.length + ' injecting / ' + rows.length + ' total' +
110
- (shown.length === rows.length ? '' : ' (pass all=true for all)')) +
111
- '\ninjects from: ' + scope + ' + global' + (sharedHere ? ' + _shared' : '') + ' (always on)' + sessionNote + '\n';
112
- // 注入边界:压制型预设(persona complete / 关闭运行时上下文)下本插件默认不注入,
113
- // 此时列出的记忆**不在**模型上下文里。必须说出来,否则模型会假设自己已经看到正文。
114
- const notice = await deps.reachNoticeForAgent(deps.presetRoster(), exec && exec.agent && exec.agent.ctx, deps.injectNoticeOptions());
115
- return header + (lines.join('\n') || '(none)') + moreNotShown(shown.length, visible.length) + notice;
116
- },
117
- }));
118
- register(defineTool({
119
- name: 'memory_manager_read',
120
- // "dropped by the byte budget" 改成"left out of it":byte budget
121
- // 是本插件内部术语,模型没有这个概念 —— 它只知道"这条在不在我上下文里"。说内部机制
122
- // 等于让它去猜一个它观测不到的量。
123
- description: 'Read one memory\'s full body, its form (flat|bundle) and its attachment names. Only for ones not already in your context (disabled, in an inactive scene, or left out). Attachment contents are not returned — use your file tools.',
124
- parameters: {
125
- memory: { type: 'string', required: true, description: 'Memory id like <scene>/<name>.' },
126
- },
127
- output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
128
- async execute(args, exec) {
129
- // op 的字段名是 `id`,不改 op:这里显式转换(键名对模型是 `<场景>/<名字>`,对 op 是 `id`)。
130
- const r = await deps.rulesOps['rules-read']({ id: String((args && args.memory) || '') });
131
- if (!r || r.ok === false)
132
- throw new Error((r && r.error) || 'failed to read memories');
133
- const rule = r.rule || {};
134
- // 形态与附件名:op 一直把 `attachments` 给了出来,这里此前**整个丢掉**,
135
- // 于是模型连"这条记忆是 bundle、带了 3 个附件"都看不到。只给名字不给内容 ——
136
- // 附件可能是图片或大 md,全文塞回来会吃光这一轮的上下文(与注入段附件行同口径)。
137
- const attach = Array.isArray(rule.attachments) ? rule.attachments : [];
138
- const form = rule.form === 'bundle' ? 'bundle' : 'flat';
139
- const attLine = attach.length
140
- ? '\nattachments (' + attach.length + '): ' + attach.map((a) => String((a && a.name) || a)).join(', ')
141
- : '';
142
- // 会话层:这条记忆在本会话是关着的(或不在本会话钉住的场景里)时,读得到
143
- // 正文 ≠ 它会进上下文。不说清的话,模型会以为自己已经掌握了它、下一轮却看不到。
144
- const scoped = sessionScopeOf(deps, exec && exec.agent);
145
- const over = scoped?.scope?.memory?.[String(rule.id)];
146
- const offHere = over === false
147
- ? '\n(switched off here only — the body above is not injected here; the global setting is unchanged) '
148
- : '';
149
- return '# ' + rule.id + ' (' + form + ')' + attLine + '\n\n' + (rule.body || '') + offHere;
150
- },
151
- }));
152
- register(defineTool({
153
- name: 'memory_manager_search',
154
- // 为什么单独一条而不是给 list 加 `query`:list 是"清单"(每条都要占一行输出),
155
- // 搜索是"找一条"(片段 + 排序)。混在一起时,搜不到就等于清单为空 —— 模型分不清
156
- // "没有这条记忆"和"这个词没匹配上"。默认在工具表里**关着**(见 tools/table.ts):
157
- // 它是按需检索,不是每轮都该付 schema 成本的能力。
158
- description: 'Search memories by words in id, scene, description, tags or body. Returns ids plus a short snippet; read the memory itself for the full body. All words must match (case-insensitive).',
450
+ name: 'memory_get',
451
+ description: 'Look up user-written memories and agent notes. No id → catalog (what exists and what injects); `id` → full body; `query` → filtered catalog with snippets. Agent note ids start with `note:`. Use this for ids and for entries not already in your context. Does not modify any memory; reading an agent note does count as a use, which keeps a note that is actually needed from aging out.',
159
452
  parameters: {
160
- query: { type: 'string', required: true, description: 'Words to look for; every word must match somewhere in the memory.' },
161
- limit: { type: 'number', description: 'Max hits (default 20, max 100).' },
453
+ id: { type: 'string', description: 'Read one entry: a user memory id (<scene>/<name>) or an agent note id (note:...).' },
454
+ query: { type: 'string', description: 'Filter the catalog by words in id, scene, tags, body or type; every word must match (case-insensitive). For agent notes the type is one of preference / fact / correction / procedure, so `query: "procedure"` lists the repeatable ones.' },
455
+ kind: { type: 'string', enum: ['memory', 'note'], description: 'Limit the catalog to user-written memories or agent notes.' },
456
+ scene: { type: 'string', description: 'Only user memories in this scene; `global` is the always-on scene.' },
457
+ all: { type: 'boolean', description: 'Catalog only: include entries that are off, in an inactive scene, or archived (default false). Search always covers everything.' },
458
+ limit: { type: 'number', description: 'Max entries per kind (default 50, max 100).' },
162
459
  },
163
460
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
164
461
  async execute(args, exec) {
462
+ // 参数写错要报错,不能静默降级:`limit` 被夹取、空 `query` / 空 `id` 被当成没传,
463
+ // 调用方会以为查询按自己的意图跑了。
464
+ if (args && args.limit !== undefined) {
465
+ const n = Number(args.limit);
466
+ if (!Number.isFinite(n) || n < 1 || n > LIST_LIMIT_MAX) {
467
+ throw new Error('limit must be a number between 1 and ' + LIST_LIMIT_MAX);
468
+ }
469
+ }
470
+ if (args && args.query !== undefined && String(args.query).trim() === '') {
471
+ throw new Error('query is empty: pass words to search for, or omit it to list the catalog');
472
+ }
473
+ if (args && args.id !== undefined && String(args.id).trim() === '') {
474
+ throw new Error('id is empty: pass a memory id, or omit it to list the catalog');
475
+ }
476
+ const id = String((args && args.id) || '').trim();
477
+ if (id !== '')
478
+ return readEntry(id, exec);
165
479
  const query = String((args && args.query) || '').trim();
166
- if (query === '')
167
- throw new Error('missing argument: query');
168
- const opArgs = { query };
169
- if (args && args.limit !== undefined)
170
- opArgs.limit = args.limit;
171
- // 与 list 同一条会话投影:`enabled` 报的是**这里**的生效值,不是全局。
172
- const scoped = sessionScopeOf(deps, exec && exec.agent);
173
- if (scoped !== null)
174
- opArgs.sessionId = scoped.sessionId;
175
- const r = await deps.rulesOps['rules-search'](opArgs);
176
- if (!r || r.ok === false)
177
- throw new Error((r && r.error) || 'failed to search memories');
178
- const hits = Array.isArray(r.hits) ? r.hits : [];
179
- if (!hits.length)
180
- return 'no memories match "' + query + '"';
181
- const lines = hits.map((h) => '- ' + h.id + ' [' + (h.scene || 'no scene') + ']' +
182
- (h.enabled === false ? ' (off here)' : '') +
183
- (h.snippet ? ' — ' + h.snippet : ''));
184
- return 'memories matching "' + query + '": ' + hits.length + '\n' + lines.join('\n');
480
+ const kind = args && args.kind === 'note' ? 'note' : args && args.kind === 'memory' ? 'memory' : '';
481
+ const all = args && args.all === true;
482
+ const limit = listLimit(args && args.limit);
483
+ const scene = args && typeof args.scene === 'string' && args.scene !== '' ? args.scene : undefined;
484
+ // 自主记忆关着时,笔记不在这份清单里出现:功能没开,模型不该看到「有笔记可读」
485
+ // 这种半开状态(直接给 note: id 仍然读得到 —— 那是显式请求)。
486
+ const readable = deps.autoNotesReadable ?? deps.autoLearnEnabled;
487
+ const readLayers = noteReadLayersOf(exec && exec.agent);
488
+ const notesOn = Boolean(evo && readable && readable(exec && exec.agent) && (readLayers.global || readLayers.workspace));
489
+ if (kind === 'note' && !notesOn) {
490
+ throw new Error('autonomous memory is off here, so agent notes are not available. The user can turn it on in Memory → Autonomous memory.');
491
+ }
492
+ const sections = [];
493
+ if (kind !== 'note') {
494
+ sections.push(query !== ''
495
+ ? await userSearchText(query, limit, scene, exec)
496
+ : await userCatalogText(all, limit, scene, exec));
497
+ }
498
+ if (kind !== 'memory' && notesOn) {
499
+ sections.push(query !== '' ? await noteSearchText(query, limit, readLayers) : await noteCatalogText(all, limit, readLayers));
500
+ }
501
+ return sections.filter((s) => s !== '').join('\n\n') || '(none)';
185
502
  },
186
503
  }));
187
504
  register(defineTool({
188
- name: 'memory_manager_switch',
505
+ name: 'memory_switch',
189
506
  // 为什么叫 `_switch` 而不是 `_set_enabled`:六个域里"拨一个开关"
190
507
  // 是同一件事,名字该同形 —— `mcp_manager_switch` 早就是这个名字,`_set_enabled` 只剩
191
508
  // 记忆 / 技能 / 人设三族在叫。**参数保留 `enabled` 布尔**:这里没有 `restart` 那第三个
@@ -201,16 +518,25 @@ export function buildMemoryTools(deps) {
201
518
  // 描述同时按"省 token"重写了一遍 —— 这几段文字每次请求都要发出去,废话是常驻成本。
202
519
  // 后半句"freeing the byte budget"删掉:byte budget 是本插件
203
520
  // 内部术语,模型据此做不了任何判断 —— "不再被注入"已经是它需要的全部因果。
204
- description: 'Enable or disable one memory. Disabled memories stop being injected. Reversible. Only when the user asks or approves.',
521
+ description: 'Enable or disable one user-written memory. Disabled memories stop being injected. Reversible. Agent notes are not switched here — forget them with the agent-note tool. Only when the user asks or approves.',
205
522
  parameters: {
206
- memory: { type: 'string', required: true, description: 'Memory id like <scene>/<name>.' },
523
+ id: { type: 'string', description: 'Memory id like <scene>/<name>.' },
524
+ // 改名前的参数名。保留在 schema 里,旧调用习惯(以及确认门的兼容分支)才真的走得通。
525
+ memory: { type: 'string', description: 'Deprecated alias for id; use id.' },
207
526
  enabled: { type: 'boolean', required: true, description: 'true = enable, false = disable.' },
208
527
  // 默认只改**这个对话**。写全局要显式说明。
209
528
  scope: { type: 'string', enum: ['session', 'global'], description: scopeSessionDesc('global = every conversation.') },
210
529
  },
211
530
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
212
531
  async execute(args, exec) {
213
- const memory = String((args && args.memory) || '');
532
+ // `memory` 是改名前的参数名,兼容一次;新调用方用 `id`。
533
+ const memory = String((args && (args.id !== undefined ? args.id : args.memory)) || '').trim();
534
+ if (memory === '')
535
+ throw new Error('missing argument: id — the memory id like <scene>/<name>.');
536
+ // 笔记不是用户记忆:这条工具拨的是索引里的开关,笔记的删除/停用走另一族。
537
+ if (isNoteRef(memory)) {
538
+ throw new Error('that is an agent note, not a user memory: use ' + noteTool(exec && exec.agent, 'memory_note action=forget', 'the agent-note tool') + '. User memory ids look like <scene>/<name>.');
539
+ }
214
540
  // `enabled` 必须是布尔:`rules-toggle` 缺了它直接拒(ops/memory.ts),但那是给用户看的
215
541
  // 中文 op 错;这里先挡一句说清"这条工具要什么"。
216
542
  if (typeof (args && args.enabled) !== 'boolean')
@@ -230,6 +556,11 @@ export function buildMemoryTools(deps) {
230
556
  if (sessionOnly) {
231
557
  if (!deps.sessionScopeSet)
232
558
  throw new Error('per-conversation switches are unavailable in this host: pass scope="global" to change it for every conversation');
559
+ // 会话覆盖只对真实存在的记忆有意义:拼错的 id 会静默写一条永远不会生效的覆盖。
560
+ const read = await opOf(deps.rulesOps, 'rules-read')({ id: memory });
561
+ if (!read || read.ok === false) {
562
+ throw new Error('no such memory: ' + memory + ' (per-conversation switches only apply to existing memories)');
563
+ }
233
564
  const sc = await deps.sessionScopeSet(exec && exec.agent, 'memory', memory, args.enabled === true);
234
565
  if (!sc || sc.ok === false)
235
566
  throw new Error((sc && sc.error) || 'failed to switch this memory here');
@@ -237,7 +568,7 @@ export function buildMemoryTools(deps) {
237
568
  (sc.cleared === true ? ' (that matches what this scope would see anyway, so the override was removed)' : '') +
238
569
  '. ' + globalUnchangedNote(deps) + ' Pass scope="global" to change it for every conversation.';
239
570
  }
240
- const r = await deps.rulesOps['rules-toggle']({ id: memory, enabled: args.enabled });
571
+ const r = await opOf(deps.rulesOps, 'rules-toggle')({ id: memory, enabled: args.enabled });
241
572
  if (!r || r.ok === false)
242
573
  throw new Error((r && r.error) || 'failed to switch this memory');
243
574
  const rule = r.rule || {};
@@ -245,10 +576,11 @@ export function buildMemoryTools(deps) {
245
576
  // 这一句不说,模型会以为已经生效 —— 与 skill_manager_switch 说清影子副本同一条理由。
246
577
  let sceneNote = '';
247
578
  try {
248
- const all = await deps.rulesOps['rules-list']({});
579
+ const all = await opOf(deps.rulesOps, 'rules-list')({});
249
580
  if (all && all.ok !== false) {
250
581
  const group = String(rule.group || '');
251
- const on = group === 'global' || (group !== '' && (all.activeMode === 'all' || String(all.activeScene || '') === group));
582
+ const on = group === GLOBAL_SCENE || group === SHARED_GROUP ||
583
+ (group !== '' && (all.activeMode === 'all' || String(all.activeScene || '') === group));
252
584
  if (!on)
253
585
  sceneNote = ' — BUT its scene "' + group + '" is not the one injecting, so it still will not be injected; turn that scene on (or move it to global) first';
254
586
  }
@@ -260,136 +592,635 @@ export function buildMemoryTools(deps) {
260
592
  },
261
593
  }));
262
594
  register(defineTool({
263
- name: 'memory_manager_save',
264
- // 「能推导的别记」「先查重」这两句必须有:记忆是唯一直接吃注入预算的域
265
- // (场景段 128 KiB),而模型很乐意把「这个项目用 pnpm」记一条 —— 那看一眼 `package.json`
266
- // 就知道,记下来却永久占着每一轮请求。合并 write/update 后这两句更要留:upsert 降低了
267
- // "再记一条"的摩擦,而摩擦正是这里唯一拦得住它的东西。
268
- description: 'Create a memory, or update the one with this id — the receipt says which. Memories cost context on every later request: record only what cannot be re-derived from code, config or git, and update an existing one rather than adding a near-duplicate. Blocked while the active scene is locked. Asks the user to confirm before it runs. Only on the user\'s instruction.',
595
+ name: 'memory_remember',
596
+ // 写入口只按**范围**分叉,不再按内容长短分叉:用户说「记录 a」时,唯一要判断的是
597
+ // 「记到哪儿」,而那是用户的问题,不是模型能猜的。旧版按"一句话 → 笔记 / 多段 → 记忆"
598
+ // 重定向,模型于是要在两条工具、三种后端之间选,参数串用是必然的。
599
+ description: 'Remember something the user explicitly asked you to keep. scope=global → every project; scope=workspace → only the project in this conversation; scope=scene → only when that working mode is on. Omit scope and ask the user where it belongs; do not guess. Pass `id` to update an existing memory or note instead of creating one. To delete a user memory the user asked you to remove, pass `action: "forget"` and `id` (moved to the recycle bin). For your own inferences use the agent-note tool, not this. User-memory writes are blocked while the active scene is locked.',
269
600
  parameters: {
270
- memory: { type: 'string', required: true, description: 'Memory id like <scene>/<name> — copy it from the list. `global` is the always-on scene.' },
271
- description: { type: 'string', description: 'One-sentence description (<=500 chars). Required when creating. Empty string = drop it and re-derive from the body; omit = keep.' },
272
- body: { type: 'string', description: 'Markdown body (<=256 KiB). Required when creating. Omit to keep the current body.' },
273
- // 不再承诺「旧文件进回收站」:bundle 记忆改名走的是
274
- // 「只重写正文、目录不动」那条路,一个字都不进回收站 —— 对 bundle 说进回收站是假话。
275
- // 与上一轮 P1-1 同口径:**只说可逆,不说实现细节**。
276
- nextName: { type: 'string', description: 'New memory name (= file name); omit to keep it.' },
601
+ action: { type: 'string', enum: ['forget'], description: 'forget: delete an existing user memory by `id` (moved to the recycle bin, restorable on the Memory page). Omit to create or update.' },
602
+ content: { type: 'string', description: 'What to remember: the memory body (Markdown, <=2400 display width: about 1200 Chinese chars / 2400 letters). Required when creating; do not pass with action=forget.' },
603
+ title: { type: 'string', description: 'Short name: the file name of the memory. Omit to derive from the first line.' },
604
+ id: { type: 'string', description: 'Update an existing entry instead of creating: a user memory id (<scene>/<name>) or an agent note id (note:...).' },
605
+ scope: { type: 'string', enum: ['scene', 'global', 'workspace'], description: 'Where it belongs: global (every project), workspace (only the project in this conversation), scene (only when that working mode is on). Ask the user when unsure.' },
606
+ scene: { type: 'string', description: 'scope=scene: the scene name; defaults to the active scene. `global` is the always-on scene.' },
607
+ nextName: { type: 'string', description: 'User memories: rename the existing memory to this file name.' },
277
608
  },
278
609
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
279
610
  async execute(args, exec) {
611
+ const agent = exec && exec.agent;
612
+ // 旧两条工具的字段名做一次兼容:`memory`/`body` 来自 save,`text`/`layer`/`slot`
613
+ // 来自 note。模型按旧习惯传进来时不该整次失败 —— 这正是合并写入入口要消掉的摩擦。
614
+ // 只做 fallback,不写进 schema:新调用方看到的仍是 content / id / scope。
615
+ const rawId = String((args && (args.id !== undefined ? args.id : args.memory)) || '').trim();
616
+ const content = String((args && (args.content !== undefined ? args.content : (args.body !== undefined ? args.body : (args.text !== undefined ? args.text : '')))) || '');
617
+ const title = String((args && args.title) || '').trim();
618
+ const nextName = String((args && args.nextName) || '').trim();
619
+ const scopeArg = String((args && (args.scope !== undefined ? args.scope : args.layer)) || '').trim();
620
+ const sceneArg = String((args && args.scene) || '').trim();
621
+ const slotArg = String((args && (args.slot !== undefined ? args.slot : args.key)) || '').trim();
622
+ const actionArg = String((args && args.action) || '').trim();
623
+ // 删除是用户明确要求时才走的另一条路:只按 id 定位,绝不把同时带来的 content
624
+ // 当成一次更新写回去 —— 真实会话里 `action=forget` + `content` 就把一条待删
625
+ // 记忆的正文改成了「删」,回执却说更新成功。
626
+ if (actionArg !== '' && actionArg !== 'forget') {
627
+ throw new Error('unknown action: ' + actionArg + ' — memory_remember creates or updates; use action=forget with id to delete a user memory.');
628
+ }
629
+ if (actionArg === 'forget') {
630
+ if (rawId === '')
631
+ throw new Error('missing argument: id — the user memory to delete (<scene>/<name>). Agent notes use memory_note action=forget.');
632
+ if (isNoteRef(rawId))
633
+ throw new Error('that is an agent note: delete it with memory_note action=forget.');
634
+ // 与 update 路径同一条兜底:裸 id 也可能是笔记 id(`note:` 前缀可省)。
635
+ // 两条路不一致时,模型按 update 的习惯传裸 id 来删,会得到"这不是用户记忆"的
636
+ // 错误,而它其实只是忘了加前缀。
637
+ if (!rawId.includes('/') && evo) {
638
+ let note = null;
639
+ try {
640
+ note = await opOf(evo, 'evolution-read')({ id: rawId });
641
+ }
642
+ catch {
643
+ note = null;
644
+ }
645
+ if (note && note.ok !== false) {
646
+ throw new Error('"' + rawId + '" is an agent note, not a user memory: delete it with memory_note action=forget (note=' + rawId + ').');
647
+ }
648
+ }
649
+ if (!rawId.includes('/'))
650
+ throw new Error('id must be <scene>/<name> (a user memory): ' + rawId);
651
+ if (content.trim() !== '' || nextName !== '' || title !== '' || slotArg !== '' || scopeArg !== '' || sceneArg !== '') {
652
+ throw new Error('action=forget deletes by id only: do not pass content, title, nextName, scope or scene.');
653
+ }
654
+ const blocked = await deps.lockedSceneGuard();
655
+ if (blocked)
656
+ throw new Error(blocked);
657
+ const all = await opOf(deps.rulesOps, 'rules-list')({});
658
+ if (!all || all.ok === false)
659
+ throw new Error((all && all.error) || 'failed to read memories');
660
+ const hit = (all.rules || []).find((x) => String(x.id) === rawId);
661
+ if (!hit)
662
+ throw new Error('no memory with id "' + rawId + '".' + existingNote((all.rules || []).map((x) => String(x.id)), 'memory ids'));
663
+ if (isAutoRule(hit))
664
+ throw new Error('that is an agent note: delete it with memory_note action=forget.');
665
+ const r = await opOf(deps.rulesOps, 'rules-remove')({ id: rawId });
666
+ if (!r || r.ok === false)
667
+ throw new Error(String((r && r.error) || 'failed to delete the memory'));
668
+ return 'OK: deleted ' + rawId + ' (moved to the recycle bin; restore it on the Memory page).';
669
+ }
670
+ /** 就地更新一条已有笔记:id / 层 / 状态不变,正文与标题替换。 */
671
+ const updateNote = async (a, ref) => {
672
+ if (nextName !== '')
673
+ throw new Error('nextName is for user memories; a note uses title.');
674
+ const layer = String(a.layer || '');
675
+ if (layer !== 'global' && layer !== 'workspace') {
676
+ throw new Error('that note is not a global or workspace note, so memory_remember cannot update it: ' + ref);
677
+ }
678
+ const id = String(a.id || stripNoteRef(ref));
679
+ const text = content !== '' ? content.trim() : String(a.body || '').trim();
680
+ if (text === '')
681
+ throw new Error('missing argument: content — the updated note text.');
682
+ if (textWidthOf(text) > MAX_AUTO_TEXT_WIDTH || /\n\s*\n/.test(text)) {
683
+ throw new Error('an agent note is one sentence (<= about 1200 Chinese chars / 2400 letters). This content is longer — use a user memory (scope=scene / global) instead.');
684
+ }
685
+ // 笔记的正文编辑是 `evolution-update`(就地改文件、id/层/状态不变);
686
+ // `evolution-learn` 是"学一条新的"——同 key 只会合并/追加,没 key 会新建 id,
687
+ // 拿它做更新会把原文留在旧条目里,回执却说"updated"。
688
+ const updateOp = evo['evolution-update'];
689
+ if (typeof updateOp !== 'function') {
690
+ throw new Error('this host cannot edit an agent note in place. Forget it with memory_note action=forget and learn a new one, or use memory_note action=learn with the same slot.');
691
+ }
692
+ // 并发编辑保护:先读一次拿当前正文指纹,写回时带上。缺了它,模型与用户同时改
693
+ // 同一条笔记时后保存的会静默覆盖先保存的,且没有任何 `stale` 提示 —— 界面编辑
694
+ // 弹窗一直传 `baseHash`,只有模型这条路漏了。
695
+ const readOp = evo['evolution-read'];
696
+ let baseHash = '';
697
+ if (typeof readOp === 'function') {
698
+ try {
699
+ const cur = await readOp({ id });
700
+ if (cur && cur.ok !== false && typeof cur.hash === 'string')
701
+ baseHash = cur.hash;
702
+ }
703
+ catch { /* 读不到指纹就按无指纹写(与旧行为一致),不因此拒掉整次更新 */ }
704
+ }
705
+ const payload = { id, text };
706
+ if (baseHash !== '')
707
+ payload.baseHash = baseHash;
708
+ if (title !== '')
709
+ payload.title = truncateToWidth(title, MAX_AUTO_TITLE_WIDTH);
710
+ const r = await updateOp(payload);
711
+ if (!r || r.ok === false)
712
+ throw new Error(String((r && r.error) || 'failed to update the note'));
713
+ const status = String(r.status || a.status || 'active');
714
+ const state = status === 'active' ? 'active' : status + ' — confirm it in Memory → Autonomous memory before it injects';
715
+ return 'OK: updated ' + noteRefOf(String(r.id || id)) + ' (' + String(r.layer || layer) + ' note, ' + state + ')';
716
+ };
717
+ // 带 id 时 scope 不参与路由,但仍要先挡掉不可能的范围:用户说「只在这个对话里」
718
+ // 时不能因为传了 id 就悄悄改掉磁盘上那份全局记忆。
719
+ if (scopeArg === 'conversation') {
720
+ throw new Error('scope=conversation is not supported: per-conversation memories are not injected. Use scope=scene (this working mode) or scope=global (every project).');
721
+ }
722
+ if (rawId !== '' && scopeArg === 'workspace' && !isNoteRef(rawId)) {
723
+ throw new Error('scope=workspace is for agent notes; to update a user memory pass id alone (or use id=note:... for a note).');
724
+ }
725
+ if (rawId !== '') {
726
+ if (isNoteRef(rawId)) {
727
+ if (!evo)
728
+ throw new Error('agent notes are not available in this build');
729
+ if (!(deps.autoLearnEnabled && deps.autoLearnEnabled(agent))) {
730
+ throw new Error('autonomous memory is off here, so agent notes cannot be updated. The user can turn it on in Memory → Autonomous memory.');
731
+ }
732
+ const raw = stripNoteRef(rawId);
733
+ let a = await opOf(evo, 'evolution-read')({ id: raw, touch: true });
734
+ if (!a || a.ok === false) {
735
+ const resolved = await resolveNote(raw);
736
+ if (resolved.id !== null) {
737
+ const found = await opOf(evo, 'evolution-read')({ id: resolved.id, touch: true });
738
+ if (found && found.ok !== false)
739
+ a = found;
740
+ }
741
+ else if (resolved.hits.length > 1) {
742
+ throw new Error('ambiguous: "' + rawId + '" matches ' + describeNoteHits(resolved.hits) + '; pass one of these ids.');
743
+ }
744
+ }
745
+ if (!a || a.ok === false)
746
+ throw new Error(String((a && a.error) || 'no such agent note: ' + rawId));
747
+ return updateNote(a, rawId);
748
+ }
749
+ if (!rawId.includes('/')) {
750
+ throw new Error('id must be <scene>/<name> (a user memory) or note:... (an agent note): ' + rawId);
751
+ }
752
+ const blocked = await deps.lockedSceneGuard();
753
+ if (blocked)
754
+ throw new Error(blocked);
755
+ const all = await opOf(deps.rulesOps, 'rules-list')({});
756
+ if (!all || all.ok === false)
757
+ throw new Error((all && all.error) || 'failed to read memories');
758
+ const hit = (all.rules || []).find((x) => String(x.id) === rawId);
759
+ if (!hit) {
760
+ // 与 memory_get 同一条回退:裸 id 也可能是笔记 id(`note:` 前缀可省)。
761
+ if (evo) {
762
+ let note = null;
763
+ try {
764
+ note = await opOf(evo, 'evolution-read')({ id: rawId, touch: true });
765
+ }
766
+ catch {
767
+ note = null;
768
+ }
769
+ if (note && note.ok !== false) {
770
+ if (!(deps.autoLearnEnabled && deps.autoLearnEnabled(agent))) {
771
+ throw new Error('autonomous memory is off here, so agent notes cannot be updated. The user can turn it on in Memory → Autonomous memory.');
772
+ }
773
+ return updateNote(note, rawId);
774
+ }
775
+ }
776
+ const ids = (all.rules || []).map((x) => String(x.id));
777
+ throw new Error('no memory with id "' + rawId + '"' + existingNote(ids, 'memory ids') + '. Pass scope=scene/global/workspace to create a new one.');
778
+ }
779
+ if (isAutoRule(hit)) {
780
+ throw new Error('that is an agent note, not a user memory: update it with id=note:' + rawId + ' or the agent-note tool.');
781
+ }
782
+ const touched = [];
783
+ const payload = { id: rawId };
784
+ const contentGiven = Boolean(args && (args.content !== undefined || args.body !== undefined || args.text !== undefined));
785
+ if (contentGiven) {
786
+ if (content.trim() === '')
787
+ throw new Error('content cannot be empty when updating a memory');
788
+ payload.body = content;
789
+ touched.push('content');
790
+ }
791
+ if (nextName !== '') {
792
+ payload.name = nextName;
793
+ touched.push('nextName');
794
+ }
795
+ if (!touched.length)
796
+ throw new Error('nothing to change: give content or nextName');
797
+ const r = await opOf(deps.rulesOps, 'rules-update')(payload);
798
+ if (!r || r.ok === false)
799
+ throw new Error((r && r.error) || 'failed to update the memory');
800
+ const rule = r.rule || {};
801
+ return 'OK: updated ' + String(rule.id || rawId) + ' (changed ' + touched.join(', ') + ')' +
802
+ (rule.id && String(rule.id) !== rawId ? ' → now ' + rule.id : '');
803
+ }
804
+ if (content.trim() === '') {
805
+ throw new Error('missing argument: content — what to remember. (The old body / text arguments are now content.)');
806
+ }
807
+ if (nextName !== '')
808
+ throw new Error('nextName renames an existing memory; to name a new one use title.');
809
+ const scope = scopeArg !== '' ? scopeArg : (sceneArg !== '' ? 'scene' : '');
810
+ if (scope === '') {
811
+ throw new Error('where should this be remembered? Pass scope=scene (only when this working mode is active), scope=global (every project), or scope=workspace (this project). Ask the user which one; do not guess.');
812
+ }
813
+ if (scope !== 'scene' && scope !== 'global' && scope !== 'workspace') {
814
+ throw new Error('unknown scope: ' + scope + ' (expected scene / global / workspace)');
815
+ }
816
+ if (scope === 'workspace') {
817
+ // 工作区记忆是**用户的资产**:写进用户记忆库的 `_ws/<hash16>` 组,与自主笔记完全分开
818
+ // (那棵树的同一层是 agent 自己的缓存,会衰减、会被合并、会进回收站)。
819
+ // 因此它不需要自主记忆开关 —— 用户说「记住这个项目的约定」不该被一个"agent 能不能
820
+ // 自学"的开关挡住。
821
+ const identity = deps.sessionIdentity ? deps.sessionIdentity(agent) : null;
822
+ const cwd = identity?.cwd;
823
+ if (!cwd) {
824
+ throw new Error('this conversation has no working directory, so there is no workspace to attach the memory to. Use scope=global, or scope=scene for the current working mode.');
825
+ }
826
+ const group = deps.workspaceGroupOf ? deps.workspaceGroupOf(agent) : '';
827
+ if (group === '') {
828
+ throw new Error('could not resolve a workspace for this conversation. Use scope=global, or scope=scene for the current working mode.');
829
+ }
830
+ const body = content;
831
+ const name = slugOf(title !== '' ? title : firstLineOf(body));
832
+ const r = await opOf(deps.rulesOps, 'rules-create')({
833
+ group,
834
+ name,
835
+ body,
836
+ enabled: true,
837
+ });
838
+ if (!r || r.ok === false)
839
+ throw new Error((r && r.error) || 'failed to save the workspace memory');
840
+ const id = String((r.rule && r.rule.id) || group + '/' + name);
841
+ return 'OK: remembered as a workspace memory ' + id + ' (only this project; injected whenever you work in it).';
842
+ }
843
+ if (scope === 'global' && sceneArg !== '' && sceneArg !== GLOBAL_SCENE) {
844
+ throw new Error('scope=global does not take a scene (got "' + sceneArg + '"). Use scope=scene with that scene, or omit scene.');
845
+ }
280
846
  const blocked = await deps.lockedSceneGuard();
281
847
  if (blocked)
282
848
  throw new Error(blocked);
283
- const memory = String((args && args.memory) || '').trim();
284
- // 拆成 `<场景>/<名字>`:要求两段都非空。**不做"没有斜杠就落 global"的兜底** —— 那会把
285
- // 一次拼错的 id 变成一条"每轮都注入"的全局记忆,而清单上看起来完全正常。
286
- // 清单里打印的就是 `<场景>/<名字>`,照抄比拼装准。
287
- const slash = memory.indexOf('/');
288
- if (slash <= 0 || slash === memory.length - 1) {
289
- // 这一条错得最有规律:用户口语里说的是「编程约定」,模型手里没有 id,就把那个名字
290
- // 直接传进来了。给两条现成的 id 比再解释一遍格式有用;读失败就只报格式
291
- // (`candidateNote` 自己吞掉失败,不改变错误结论)。
292
- const note = await candidateNote(async () => {
293
- const r = await deps.rulesOps['rules-list']({});
294
- return r && r.ok !== false ? (r.rules || []).map((x) => String(x.id)) : [];
295
- }, 'memory ids');
296
- throw new Error('memory must be <scene>/<name> (copy that from the listing; the always-on scene is written global/<name>): ' + (memory || '(empty)') + note);
297
- }
298
- const group = memory.slice(0, slash);
299
- const name = memory.slice(slash + 1);
300
- // 先取全量:既用来定位(命中 = 改、未命中 = 建),也是查重的数据源。判定必须在工具
301
- // 这一侧 —— `rules-create` 对同名是**拒绝**的(`error.rules.exists`),op 不会 upsert。
302
- const all = await deps.rulesOps['rules-list']({});
849
+ const all = await opOf(deps.rulesOps, 'rules-list')({});
303
850
  if (!all || all.ok === false)
304
851
  throw new Error((all && all.error) || 'failed to read memories');
305
- const hit = (all.rules || []).find((x) => String(x.id) === memory);
852
+ // `_shared` 不进候选:它恒常注入、在界面上也没有开关,agent 往里写等于**自己造一个
853
+ // 常开场景**,绕开了用户对"哪条记忆该生效"的控制。恒常注入的只有 `global` 一个。
854
+ const knownGroups = new Set(sceneNamesOf(all).filter((s) => s !== SHARED_GROUP));
855
+ knownGroups.add(GLOBAL_SCENE);
856
+ let group = scope === 'global' ? GLOBAL_SCENE : sceneArg;
857
+ if (scope === 'scene' && group === '') {
858
+ group = String((deps.activeSceneOf ? deps.activeSceneOf(agent) : '') || '');
859
+ }
860
+ if (group === '') {
861
+ const scenes = [...knownGroups].filter((s) => s !== '').sort();
862
+ throw new Error('scope=scene needs a scene, and this conversation has no active scene. Existing scenes: ' + scenes.join(', ') + '. Ask the user which one; do not guess.');
863
+ }
864
+ if (group === SHARED_GROUP) {
865
+ // 显式传了也拒:这条路径上没有"用户明确要求"的证据,而写进去的记忆不受任何开关
866
+ // 控制。要全局生效就用 scope=global;要场景生效就让用户先建 / 开一个场景。
867
+ throw new Error('_shared is not a writable scene: memories there are injected in every conversation and have no on/off switch, so an agent must not create one. Use scope=global for something that should apply everywhere, or scope=scene with a scene the user has turned on.');
868
+ }
869
+ if (group === '_ws' || group.startsWith('_ws/') || group === '_session' || group.startsWith('_session/')) {
870
+ throw new Error('"' + group + '" is internal storage for agent notes, not a user scene. For a workspace note use scope=workspace; for a user memory use an existing scene (global, …).');
871
+ }
872
+ if (!knownGroups.has(group)) {
873
+ const scenes = [...knownGroups].filter((s) => s !== '').sort();
874
+ throw new Error('scene "' + group + '" does not exist — memories can only be created inside an existing scene. Existing scenes: ' + scenes.join(', ') + '. The user creates scenes in the plugin panel (Scenes page); then remember again.');
875
+ }
876
+ const body = content;
877
+ const name = slugOf(title !== '' ? title : firstLineOf(body));
878
+ const id = group + '/' + name;
879
+ const hit = (all.rules || []).find((x) => String(x.id) === id);
306
880
  if (hit) {
307
- // 改的分支一律 read-modify-write(省略 = 保持),因为 `rules-update` 是整份重写。
308
- // 三个可改字段一个都没给就拒:op 会按"保留现有"落一次盘并刷新 updatedAt,
309
- // 模型以为改了点什么,其实只是把文件重写了一遍。
310
- const touched = ['body', 'description', 'nextName'].filter((k) => args[k] !== undefined);
311
- if (!touched.length)
312
- throw new Error('nothing to change: give at least one of body / description / nextName');
313
- const payload = { id: memory };
314
- // 只带模型真给过的键:`description` 传空串在 op 里是"删除并重新派生",与"未给"是两种
315
- // 意图,都必须原样透传 —— 所以用 `!== undefined` 而不是真值判断。
316
- if (args.body !== undefined)
317
- payload.body = args.body;
318
- if (args.description !== undefined)
319
- payload.description = args.description;
320
- if (args.nextName !== undefined)
321
- payload.name = args.nextName;
322
- const r = await deps.rulesOps['rules-update'](payload);
881
+ if (isAutoRule(hit)) {
882
+ throw new Error('the derived id "' + id + '" belongs to an agent note, not a user memory. Pick a different title, or use scope=workspace for a note.');
883
+ }
884
+ // 同名 upsert:用户说「记住」两次,第二句通常是在改同一条;替换正文而不是再建一条。
885
+ const payload = { id, body };
886
+ const r = await opOf(deps.rulesOps, 'rules-update')(payload);
323
887
  if (!r || r.ok === false)
324
888
  throw new Error((r && r.error) || 'failed to update the memory');
325
- const rule = r.rule || {};
326
- return 'OK: updated ' + String(rule.id || memory) + ' (changed ' + touched.join(', ') + ')' +
327
- (rule.id && String(rule.id) !== memory ? ' → now ' + rule.id : '');
328
- }
329
- // 建的分支:正文与描述都必填。`rules-create` 自己会拒空正文与非法名(ops/memory.ts),
330
- // 但那是给用户看的中文 op 错;模型需要的是"这条工具要什么",所以在工具侧先挡、点名缺哪个。
331
- const body = args && args.body !== undefined ? String(args.body) : '';
332
- const description = args && args.description !== undefined ? String(args.description) : '';
333
- const missing = [
334
- body.trim() === '' ? 'body' : '',
335
- description.trim() === '' ? 'description' : '',
336
- ].filter((x) => x !== '');
337
- if (missing.length) {
338
- // id 不存在 + 内容也不全:最可能是名字记差了一个字。先给**同一场景**里现成的 id
339
- // (整个库列出来只会把这条错误变成噪音),一条都没有才退回全库。
340
- const ids = (all.rules || []).map((x) => String(x.id));
341
- const here = ids.filter((id) => id.indexOf(group + '/') === 0);
342
- throw new Error('creating a memory needs ' + missing.join(' and ') + ' (' + memory + ' does not exist yet)'
343
- + existingNote(here.length ? here : ids, 'memory ids'));
344
- }
345
- // 查重只**说出来**,不拒绝 —— 猜错一次就把该记的东西记不下去,比多记一条代价大得多;
346
- // 而且"像不像同一条"本来就是人判断的事。只在建的分支提示:改的分支没有"再记一条"的风险。
889
+ return 'OK: updated ' + String((r.rule && r.rule.id) || id) + ' (same name already existed; content replaced)' +
890
+ globalActionNote(deps, agent, 'memory', 'memory');
891
+ }
347
892
  const norm = (value) => String(value ?? '').toLowerCase().replace(/\s+/g, ' ').trim();
348
893
  const wantName = norm(name);
349
- const wantDesc = norm(description);
350
894
  const similar = (all.rules || [])
895
+ .filter((x) => !isAutoRule(x))
351
896
  .filter((x) => {
352
897
  const have = norm(x.name);
353
- const desc = norm(x.description);
354
898
  if (have === wantName)
355
899
  return true;
356
- if (wantDesc !== '' && desc !== '' && desc === wantDesc)
357
- return true;
358
900
  // 名字互相包含:只在两边都不短于 4 个字符时算,否则 "git" 会把所有条目都匹配上。
359
901
  return have.length >= 4 && wantName.length >= 4 && (have.includes(wantName) || wantName.includes(have));
360
902
  })
361
903
  .map((x) => String(x.id))
362
904
  .slice(0, 3);
363
- const r = await deps.rulesOps['rules-create']({ group, name, description, body });
905
+ const r = await opOf(deps.rulesOps, 'rules-create')({ group, name, body, enabled: true });
364
906
  if (!r || r.ok === false)
365
907
  throw new Error((r && r.error) || 'failed to create the memory');
366
908
  // 刚建好的这条自己会在列表里,从名单里去掉。
367
- const dup = similar.filter((id) => id !== String(r.rule.id));
909
+ const dup = similar.filter((sid) => sid !== String(r.rule.id));
368
910
  const warn = dup.length
369
- ? `\nnote: ${dup.length} existing memories have a similar name or description (${dup.join(', ')}) — if it is the same thing, update that one instead of keeping two.`
911
+ ? `\nnote: ${dup.length} existing memories have a similar name (${dup.join(', ')}) — if it is the same thing, update that one instead of keeping two.`
370
912
  : '';
371
- // 回执必须同时说清**两个**条件:新建的记忆在 op 层是
372
- // `enabled: false`(ops/memory.ts 的 rulesCreate),而原先这句只提场景 —— 读起来像
373
- // "场景一开它就自动生效",模型据此以为已经生效,实际还差一次开关。与 skill_manager_save
374
- // 的 enableHint 同一形状:点名的工具在出厂默认名单里是关着的,关着就改说"用户开启后"。
375
- // 「会不会注入」按**本会话**的投影判:会话钉了别的场景时,这条记忆落进的
376
- // 那个场景在这个对话里根本没开着 —— 照全局口径回一句"打开就能用"是错的答案。
377
- const scoped = sessionScopeOf(deps, exec && exec.agent);
913
+ // 回执必须同时说清**两个**条件:记忆本身已开启(本工具创建时传了 `enabled: true`),
914
+ // 但它落进的场景在这个对话里未必开着 —— 场景没开,单条开关拨上去也不会注入。
915
+ // 「会不会注入」按**本会话**的投影判:会话钉了别的场景时,照全局口径回一句
916
+ // "打开就能用"是错的答案。
917
+ const scoped = sessionScopeOf(deps, agent);
378
918
  const effScene = scoped?.scope?.scene;
379
919
  const activeNow = effScene === undefined ? all.activeScene : effScene;
380
920
  const activeMode = effScene === undefined ? all.activeMode : 'custom';
381
- const sceneActive = group === 'global' ||
921
+ const sceneActive = group === GLOBAL_SCENE || group === SHARED_GROUP ||
382
922
  (group !== '' && (activeMode === 'all' || String(activeNow || '') === group));
383
- const sceneTail = sceneActive ? '' : ', and turn scene "' + group + '" on';
384
- // 判据按 **agent**:工具表是每个作用域一份,本作用域把它关掉(或人设 toolsDeny 砍掉)
385
- // 之后,点名它就是让模型白跑一趟 —— 与 mcp/skill 的 listHint 同一条。
386
- const enableHint = deps.toolVisibleFor('memory_manager_switch', exec && exec.agent)
387
- ? ' (created disabled — turn it on first with memory_manager_switch' + sceneTail + ')'
388
- : ' (created disabled — the user has to turn it on first' + sceneTail + ')';
389
- // 会话层:这条记忆写的是**磁盘上的那一份**(所有对话共用),本会话的开关只决定
390
- // "这里看不看得到"。模型据此回一句"记下了"时,用户很容易读成"只在这个对话里"。
923
+ const enableHint = sceneActive
924
+ ? ' (created enabled)'
925
+ : ' (created enabled, but scene "' + group + '" is not on in this conversation, so it will not be injected here until that scene is turned on)';
391
926
  return 'OK: created ' + r.rule.id + enableHint + warn +
392
- globalActionNote(deps, exec && exec.agent, 'memory', 'memory');
927
+ globalActionNote(deps, agent, 'memory', 'memory');
393
928
  },
394
929
  }));
930
+ // ── 自主笔记(只在开关打开时出现在工具表里)────────────────────────────────
931
+ //
932
+ // 为什么不复用 `memory_remember`:那条的契约是「Only on the user's instruction」并且
933
+ // 受确认门禁。自主笔记需要零摩擦:给 `save` 加一个 `auto` 参数会让同一个工具同时代表
934
+ // 两种授权,门禁只能按参数分叉;模型传错一次就是"该问的没问"。授权边界写在工具名上。
935
+ //
936
+ // 与用户记忆分开的另一点是**对象**:笔记是一句话、按层(global / workspace)走;
937
+ // 用户记忆是多段、按场景走。读取统一走 `memory_get`,这里只保留写入与删除。
938
+ // 弹卡策略:自动确认关 → 每次都问;开 → 不弹卡,由 agent 决定。生效判断在 gates 的 `autoActive`。
939
+ if (!deps.evolutionOps || !deps.autoLearnEnabled)
940
+ return { refreshNoteSchema() { } };
941
+ const noteOps = deps.evolutionOps;
942
+ const noteToolDef = defineTool({
943
+ name: PROACTIVE_MEMORY_TOOL,
944
+ description: 'Agent notes (autonomous memory) — one-line notes YOU decided are worth keeping across conversations: a preference, a fact, a correction of your behaviour, or a repeatable procedure. Use this for your own judgement; when the user explicitly asks you to remember something, use memory_remember instead (that is their asset, this is your cache).\n\nWrite it in one call and move on. If a call is refused, the reply names every problem at once — fix them in one retry, or drop the note and get back to the task. Do not reword the same idea repeatedly: a note that keeps failing is one the user did not need.\n\nRecord what will still hold in a different conversation, and nothing else:\n- A one-off ("this time", "for now", "next step") is not a note.\n- Something re-derivable from the code or config (dependency versions, file lists, config values) is not a note — read the file instead.\n- Say the thing itself, in words. Fragments, markup, and pure punctuation are refused.\n\nlearn: `title` (2-8 words) + `text` (<=1200 Chinese chars / 2400 letters; 1-2 clear sentences, or follow the style line in the learned-notes section); `kind` — preference / fact / correction / procedure (it sets the review interval: fact and procedure are re-checked after 30 days, preference and correction never expire, so a procedure filed as a correction stays forever); pass `slot` (a stable name) when you may update or forget it later; pass `quote` (their exact words) when you are recording something the user actually said — it is checked verbatim against this conversation, and if it does not match the note is still saved but with weaker evidence, so quote exactly when you can.\n\nEvery note shows the user a card unless they turned auto-confirm on. Check for an existing note on the same thing first (the memory read tool with kind=note lists them) — two notes saying the same thing in different words are both injected into every later conversation, and the duplicate check compares wording, not meaning. forget: `note` = id (note:...), slot, title, or the first line as it was injected. Inspect notes with the memory read tool.',
945
+ parameters: {
946
+ action: { type: 'string', enum: ['learn', 'forget'], required: true, description: 'learn or forget.' },
947
+ // ── learn ──
948
+ title: { type: 'string', description: 'learn: a short name for the row (2-8 words, <=50 Chinese chars / 100 letters), in the user\'s language.' },
949
+ text: { type: 'string', description: 'learn: the note itself (<=1200 Chinese chars / 2400 letters), in the user\'s language; by default 1-2 clear sentences, conclusion first, key reason only when it matters. Follow the style shown in the learned-notes section when present. `note` is accepted as an alias.' },
950
+ quote: { type: 'string', description: 'learn: the user\'s exact words, copied verbatim, when you are recording something they said. Checked against this conversation; a quote that does not match does not fail the call — the note is kept with weaker evidence. Omit it for your own inferences.' },
951
+ slot: { type: 'string', description: 'learn: optional stable slot name; learning again with the same slot merges when it says the same thing, and replaces the old note when it conflicts.' },
952
+ boundary: { type: 'string', description: 'learn: optional; when it may not hold.' },
953
+ ttlDays: { type: 'number', description: 'learn: optional; re-check after N days.' },
954
+ // `kind` 决定保质期(事实 / 做法 30 天后提醒复核,偏好 / 纠正不过期)。不给时由
955
+ // `inferKind` 按措辞猜,而它只能看字面 —— 「必须 / 不要」这类约束词会把做法误判成
956
+ // 纠正,于是一条会过期的做法被永久固化。模型知道这句话是什么,就让它自己说。
957
+ kind: {
958
+ type: 'string',
959
+ enum: ['preference', 'fact', 'correction', 'procedure'],
960
+ description: 'learn: how this note changes your future behaviour — preference (how to answer / which tool / which style), fact (a stable fact about the user or project), procedure (a repeatable sequence of steps), correction (the user fixing something you already did). Omit only when unsure.',
961
+ },
962
+ // ── forget ──
963
+ note: { type: 'string', description: 'forget: the note — id (note:...), slot, title, or the first line of the note as it was injected (trailing punctuation ignored; the full body is not required). learn: alias for text (the note body).' },
964
+ },
965
+ output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
966
+ async execute(args, exec) {
967
+ const agent = exec && exec.agent;
968
+ if (!deps.autoLearnEnabled(agent)) {
969
+ // 开关在调用途中被关掉(另一个窗口 / 本会话切了)也要说清,而不是静默什么都不做。
970
+ throw new Error('autonomous memory is off here, so nothing was done. The user can turn it on in Memory → Autonomous memory.');
971
+ }
972
+ const action = String((args && args.action) || 'learn');
973
+ if (action === 'forget') {
974
+ const ref = noteArgOf(args);
975
+ if (ref === '')
976
+ throw new Error('missing argument: note — the note id (note:...), its slot, its title, or the first line of the note as injected (trailing punctuation ignored).');
977
+ const raw = stripNoteRef(ref);
978
+ const forget = async (id) => opOf(noteOps, 'evolution-forget')({ id, actor: 'model' });
979
+ let r = await forget(raw);
980
+ if (!r || r.ok === false) {
981
+ // 注入行只显示 key / 摘要,模型不一定记得 id:按 id / slot / title / 原文反查一次,唯一命中才删。
982
+ const resolved = await resolveNote(raw);
983
+ if (resolved.id !== null)
984
+ r = await forget(resolved.id);
985
+ else if (resolved.hits.length > 1) {
986
+ throw new Error('ambiguous: "' + ref + '" matches ' + describeNoteHits(resolved.hits) + '; pass one of these ids.');
987
+ }
988
+ }
989
+ if (!r || r.ok === false) {
990
+ // 带 `note:` 前缀的一定是笔记:它只是不存在了,别再说"这像是用户记忆"。
991
+ if (isNoteRef(ref)) {
992
+ throw new Error('no such agent note: ' + ref + ' (it may have been forgotten or archived). List the current notes with memory_get kind=note.');
993
+ }
994
+ // 用户记忆 id 也是 `<scene>/<name>` 形状;零命中时明确说这不是笔记,别让模型再猜。
995
+ if (raw.includes('/')) {
996
+ throw new Error('no such agent note: ' + ref + '. That looks like a user memory id (<scene>/<name>) — user memories are disabled or deleted on the Memory page, not here. Agent note ids start with note:.');
997
+ }
998
+ // 走到这里说明 id / slot / title / 注入行都没命中。`evolution-forget` 的内部错
999
+ // (`not a memory id`)对模型没有任何可执行信息 —— 它要的是"下一步做什么"。
1000
+ throw new Error('no such agent note: "' + ref + '". Pass its id (note:<layer>/<slug>), its slot, its title, or the first line exactly as it was injected; list the current notes with memory_get kind=note to find one.');
1001
+ }
1002
+ return 'OK: forgot ' + noteRefOf(String(r.id || raw)) + '. It will not be learned again for 30 days.';
1003
+ }
1004
+ if (action !== 'learn')
1005
+ throw new Error('unknown action: ' + action + ' (expected learn / forget)');
1006
+ const layers = noteLayersOf(agent);
1007
+ const onlyLayer = layers.global && !layers.workspace ? 'global'
1008
+ : layers.workspace && !layers.global ? 'workspace' : undefined;
1009
+ const askedLayer = args && typeof args.layer === 'string' ? args.layer : '';
1010
+ if (askedLayer !== '') {
1011
+ if (askedLayer !== 'global' && askedLayer !== 'workspace') {
1012
+ throw new Error('unknown layer: ' + askedLayer + ' (expected global / workspace)');
1013
+ }
1014
+ // 关掉的层在模型眼里不该存在。显式点名它时拒绝而不是悄悄落到另一层 ——
1015
+ // 静默改层会让模型以为自己记到了它说的那一层。
1016
+ if (!(askedLayer === 'global' ? layers.global : layers.workspace)) {
1017
+ throw new Error('the ' + askedLayer + ' autonomous-memory layer is off here, so nothing was done. The user can turn it on in Memory → Autonomous memory' +
1018
+ (onlyLayer !== undefined ? ', or omit layer to use the enabled ' + onlyLayer + ' layer.' : '.'));
1019
+ }
1020
+ }
1021
+ // save 的参数串进来时(`body` / `memory`),直接指回用户记忆,
1022
+ // 别让一次完整记忆被当成一句话笔记丢掉。
1023
+ if (args && (args.body !== undefined || args.memory !== undefined)) {
1024
+ throw new Error('those are user-memory parameters, not note parameters: for a full memory call memory_remember with content and scope=scene/global. For a note pass title and text (the same slot merges the same meaning and replaces a conflicting note).');
1025
+ }
1026
+ // ── learn(默认)──
1027
+ //
1028
+ // 先查用户记忆里是不是已经有同一条:用户自己写过的(或让模型写过的)记忆**永久生效、
1029
+ // 不衰减、不进回收站**,而笔记是会被 TTL 提醒、被合并、被归档的缓存。模型不知道这件事,
1030
+ // 于是常见症状是——用户说「记住这个仓库用 pnpm」,模型先用 memory_remember 存了一条,
1031
+ // 之后每次看到又顺手记一条笔记,页面上同一条规则出现两遍,其中一遍还会自己过期。
1032
+ //
1033
+ // 命中就**不写**,并把已有的那条 id 告诉模型:它可以去更新那条,而不是另立一条。
1034
+ const identity = deps.sessionIdentity ? deps.sessionIdentity(agent) : null;
1035
+ // `note` 是模型按工具名最常写的那个字段(真实会话里就有人把正文塞进 `note`,
1036
+ // 然后在 `text` 的必填校验上白跑一次)。learn 时把它当正文别名;forget 仍只读 `note`。
1037
+ const bodyArg = args && String(args.text || '').trim() !== '' ? args.text : args && args.note;
1038
+ const text = String(bodyArg || '').trim();
1039
+ if (text === '')
1040
+ throw new Error('missing argument: text (or note) — the note itself, one sentence.');
1041
+ // 已经在用户记忆里说过的事不再记一条笔记:见 `userMemoryCovering` 的说明。
1042
+ const covered = await userMemoryCovering(text);
1043
+ if (covered !== null) {
1044
+ return 'Already covered by the user memory ' + covered + ', so nothing was recorded. That memory is permanent and always injected — update it with memory_remember (id=' + covered + ', content=...) if the wording needs to change. Do not keep a second copy as a note.';
1045
+ }
1046
+ // 非法 TTL 不能静默落默认值:调用方会以为"30 天后重查"生效了。
1047
+ if (args && args.ttlDays !== undefined) {
1048
+ const ttl = Number(args.ttlDays);
1049
+ if (!Number.isFinite(ttl) || ttl <= 0)
1050
+ throw new Error('ttlDays must be a positive number of days');
1051
+ }
1052
+ const payload = { text };
1053
+ // 没有 `source`:证据档位由门禁按 `quote` 的逐字核对结果判定,模型无从声明。
1054
+ for (const key of ['title', 'quote', 'boundary', 'layer', 'ttlDays', 'kind']) {
1055
+ if (args && args[key] !== undefined && args[key] !== '')
1056
+ payload[key] = args[key];
1057
+ }
1058
+ // 只剩一层时替模型定层:schema 里没有 `layer`,路由与卡片都需要一个确定值。
1059
+ if (onlyLayer !== undefined && (args.layer === undefined || args.layer === ''))
1060
+ payload.layer = onlyLayer;
1061
+ // `slot` 是模型面的名字;op 的字段仍是 `key`(同 slot 合并)。`key` 作为旧名兼容一次。
1062
+ const slot = String((args && (args.slot !== undefined ? args.slot : args.key)) || '');
1063
+ if (slot !== '')
1064
+ payload.key = slot;
1065
+ if (identity?.sessionId)
1066
+ payload.sessionId = identity.sessionId;
1067
+ if (identity?.cwd)
1068
+ payload.cwd = identity.cwd;
1069
+ const scene = deps.activeSceneOf ? deps.activeSceneOf(agent) : undefined;
1070
+ if (scene !== undefined)
1071
+ payload.scene = scene;
1072
+ // 门禁拒绝是**正常的业务结果**,不是异常 —— 但工具层只能通过 throw 回话。
1073
+ // 这里统一成一句给模型看的话:首条理由 + 同一轮命中的其余理由。
1074
+ // 一次给全,模型不必「改一道撞一道」(门禁原本串行短路,那是最贵的往返)。
1075
+ const gateError = (r) => new Error(gateErrorText(r, 'failed to record it'));
1076
+ // 没有 preview / 卡片依赖(旧装配、测试):保持原来的待确认路径。
1077
+ const previewOp = noteOps['evolution-preview'];
1078
+ const ask = deps.askMemoryScope;
1079
+ if (!previewOp || !ask) {
1080
+ const r = await opOf(noteOps, 'evolution-learn')(payload);
1081
+ if (!r || r.ok === false)
1082
+ throw gateError(r);
1083
+ return learnReceipt(r, 'none', payload);
1084
+ }
1085
+ // 先只读预演:拿到「弹卡后会发生什么」(层、是否合并 / 取代、会不会直接生效)。
1086
+ const preview = await previewOp(payload);
1087
+ if (!preview || preview.ok === false)
1088
+ throw gateError(preview);
1089
+ // 自动确认:不弹卡,模型给的层就是最终层;后台复习也走这条授权。
1090
+ if (preview.autoConfirm === true) {
1091
+ const r = await opOf(noteOps, 'evolution-learn')({ ...payload, autoActive: true });
1092
+ if (!r || r.ok === false)
1093
+ throw gateError(r);
1094
+ return learnReceipt(r, 'auto', payload);
1095
+ }
1096
+ const layerProvided = payload.layer === 'global' || payload.layer === 'workspace';
1097
+ const layer = preview.layer === 'global' ? 'global' : 'workspace';
1098
+ // 合并进一条已生效的记忆:层已经定了,结果也仍是 active,不必再问一次。
1099
+ if (typeof preview.mergeInto === 'string' && preview.mergeInto !== '' && preview.status === 'active') {
1100
+ const r = await opOf(noteOps, 'evolution-learn')(payload);
1101
+ if (!r || r.ok === false)
1102
+ throw new Error(String((r && r.error) || 'failed to record it'));
1103
+ return learnReceipt(r, 'none', payload);
1104
+ }
1105
+ // 其余一律弹卡:新条目、候选合并、冲突都由用户选层;选了就批准并立即生效。
1106
+ const allowed = Array.isArray(preview.allowedLayers)
1107
+ ? preview.allowedLayers.filter((l) => l === 'global' || l === 'workspace')
1108
+ : [];
1109
+ const request = {
1110
+ text: String(preview.text || payload.text || ''),
1111
+ ...(typeof preview.boundary === 'string' && preview.boundary !== '' ? { boundary: preview.boundary } : {}),
1112
+ // 门禁最终判定的类型(模型给了就用它,否则 `inferKind` 兜底)。卡片据此写明保质期 ——
1113
+ // 用户在决定「要不要这条」时,看不到类型就不知道自己批准的东西会不会过一阵被催复核。
1114
+ ...(typeof preview.kind === 'string' ? { kind: preview.kind } : {}),
1115
+ // 只有模型明确给了层才标「推荐」;省略层就是不确定,让用户自己选。
1116
+ ...(layerProvided ? { recommended: layer } : {}),
1117
+ allowed: allowed.length > 0 ? allowed : [layer],
1118
+ ...(typeof preview.mergeInto === 'string' && preview.mergeInto !== '' ? { mergeInto: preview.mergeInto } : {}),
1119
+ ...(Array.isArray(preview.supersedes) && preview.supersedes.length > 0
1120
+ ? { supersedes: preview.supersedes.filter((x) => typeof x === 'string') }
1121
+ : {}),
1122
+ ...(exec && exec.signal !== undefined ? { signal: exec.signal } : {}),
1123
+ };
1124
+ const choice = await ask(agent, request);
1125
+ // 没有可用卡片(headless / 非 live root / 卡片异常):退回待确认,不丢笔记。
1126
+ if (choice === null) {
1127
+ const r = await opOf(noteOps, 'evolution-learn')(payload);
1128
+ if (!r || r.ok === false)
1129
+ throw new Error(String((r && r.error) || 'failed to record it'));
1130
+ return learnReceipt(r, 'unavailable', payload);
1131
+ }
1132
+ // 用户在卡片里自己写了说法:不写盘,交回模型按他们的话重写,再调一次 learn 弹卡。
1133
+ // 不在同一次工具调用里循环,是因为用户写的可能是一句修改要求(「改成只在写代码时用」),
1134
+ // 而不是可以直接落盘的完整正文。
1135
+ if (choice.choice === 'revise') {
1136
+ return 'Not saved yet. The user wants this note worded differently:\n' +
1137
+ String(choice.custom ?? '') + '\n\n' +
1138
+ 'Rewrite the note to match their wording, then call memory_note action=learn again with the revised text. The card will ask them to confirm the new version.';
1139
+ }
1140
+ if (choice.choice === 'skip') {
1141
+ return 'Not saved: the user chose not to add it. Do not save it again unless they ask.';
1142
+ }
1143
+ const r = await opOf(noteOps, 'evolution-learn')({
1144
+ ...payload,
1145
+ layer: choice.choice,
1146
+ approved: true,
1147
+ });
1148
+ if (!r || r.ok === false)
1149
+ throw new Error(String((r && r.error) || 'failed to record it'));
1150
+ return learnReceipt(r, 'approved', payload);
1151
+ },
1152
+ });
1153
+ applyNoteLayerSchema(noteToolDef, noteLayersOf());
1154
+ register(noteToolDef);
1155
+ return { refreshNoteSchema() { applyNoteLayerSchema(noteToolDef, noteLayersOf()); } };
1156
+ }
1157
+ /**
1158
+ * 门禁拒绝 → 一句给模型看的话。
1159
+ *
1160
+ * 门禁可能在同一轮命中多个拒绝点(`also`)。逐条列出而不是只报第一条:门禁原本串行
1161
+ * 短路,模型撞一道改一道,每撞一次一轮往返 —— 热路径上那是最贵的一段,而它完全不知道
1162
+ * 后面还挡着什么。一次给全,它就能一轮决定「改哪里」或「这条不值得记,继续正事」。
1163
+ *
1164
+ * 措辞分工明确:`not recorded` 开头的是**别记了**,`refused` 开头的是**改一下再来**。
1165
+ * 模型据此能分辨该放弃还是该修正,不必靠猜。
1166
+ */
1167
+ function gateErrorText(r, fallback) {
1168
+ const head = String((r && r.error) || fallback);
1169
+ const also = r && Array.isArray(r.also) ? r.also : [];
1170
+ if (also.length === 0)
1171
+ return head;
1172
+ const rest = also.map(function (x) { return '- ' + String((x && x.error) || ''); }).filter(function (s) { return s !== '- '; });
1173
+ if (rest.length === 0)
1174
+ return head;
1175
+ return head + '\n\nAlso rejected for:' + '\n' + rest.join('\n');
1176
+ }
1177
+ /** learn 回执。状态(active / pending)以 learn 的返回为准,`card` 只补充「卡片 / 自动路径那一侧发生了什么」。 */
1178
+ function learnReceipt(r, card, payload) {
1179
+ const parts = ['OK: recorded ' + noteRefOf(String(r.id))];
1180
+ // 回执要给出之后能原样引用的东西:id 与 slot 都在,模型就不必猜 title/quote 哪个是键。
1181
+ if (payload && typeof payload.key === 'string' && payload.key !== '')
1182
+ parts.push('slot: ' + payload.key);
1183
+ // 回执要报落盘值:标题超宽时写入侧会截到 MAX_AUTO_TITLE_WIDTH,回显原串会让模型以为它存下了完整标题。
1184
+ if (payload && typeof payload.title === 'string' && payload.title !== '')
1185
+ parts.push('title: ' + truncateToWidth(payload.title.trim(), MAX_AUTO_TITLE_WIDTH));
1186
+ if (r.merged === true) {
1187
+ parts.push(String(r.status === 'active' ? 'merged into an existing active note' : 'merged into an existing pending note'));
1188
+ }
1189
+ else if (r.status === 'active') {
1190
+ parts.push('saved as active');
1191
+ }
1192
+ else {
1193
+ parts.push('saved as pending review — not injected until the user confirms it on the Memory page');
1194
+ }
1195
+ if (r.merged !== true && typeof r.tier === 'string')
1196
+ parts.push('tier ' + r.tier);
1197
+ // 类型要回显:它是保质期的来源(事实 / 做法 30 天后提醒复核,偏好 / 纠正不过期)。
1198
+ // 模型没传 `kind` 时这里是 `inferKind` 按措辞猜的结果 —— 不回显,它无从知道猜成了什么。
1199
+ if (typeof r.kind === 'string' && r.kind !== '')
1200
+ parts.push('kind ' + r.kind);
1201
+ if (Array.isArray(r.supersedes) && r.supersedes.length)
1202
+ parts.push('replaced ' + r.supersedes.join(', '));
1203
+ if (r.note)
1204
+ parts.push(String(r.note));
1205
+ if (r.pendingReason)
1206
+ parts.push('needs review: ' + String(r.pendingReason));
1207
+ if (card === 'approved' && r.status !== 'active' && r.pendingReason) {
1208
+ parts.push('the card approved it, but it stayed pending for the reason above');
1209
+ }
1210
+ if (card === 'unavailable')
1211
+ parts.push('no interactive card was available, so it stayed pending');
1212
+ if (card === 'pending-conflict')
1213
+ parts.push('it conflicts with a memory the user wrote; they can resolve it on the Memory page');
1214
+ if (card === 'pending')
1215
+ parts.push('it stayed pending for the reason above');
1216
+ // 层要说出来:用户以为"只在这个项目里",实际它进了全局(别的项目也会出现)——
1217
+ // 这个误读比记错内容更难发现。
1218
+ const layerNote = {
1219
+ global: 'applies in every project',
1220
+ workspace: 'applies in this project (visible to other conversations here too)',
1221
+ };
1222
+ const layerLine = typeof r.layer === 'string' ? layerNote[r.layer] : undefined;
1223
+ if (layerLine !== undefined)
1224
+ parts.push(layerLine);
1225
+ return parts.join('; ');
395
1226
  }