mocode-ai 1.8.9 → 1.9.0
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.
- package/dist/agent/index.js +17 -17
- package/dist/agent/model-turn.js +8 -4
- package/dist/agent/run-coordinator.js +6 -0
- package/dist/agent/spawn.js +8 -4
- package/dist/agent/stages/tool-dispatcher.js +31 -11
- package/dist/attachments/clipboard.js +22 -0
- package/dist/attachments/image.js +63 -0
- package/dist/changeset/hash.js +17 -0
- package/dist/changeset/index.js +6 -10
- package/dist/context/text-search.js +28 -10
- package/dist/flows/cli.js +1 -1
- package/dist/flows/flow.js +1 -1
- package/dist/flows/trace.js +1 -1
- package/dist/headless.js +23 -0
- package/dist/i18n/index.js +16 -2
- package/dist/index.js +1 -1
- package/dist/memory/anchor.js +319 -0
- package/dist/memory/audit.js +65 -0
- package/dist/memory/episodic.js +546 -0
- package/dist/memory/graph.js +233 -9
- package/dist/memory/health.js +208 -0
- package/dist/memory/index.js +12 -3
- package/dist/memory/pending.js +269 -0
- package/dist/memory/portable.js +150 -0
- package/dist/memory/proactive.js +588 -0
- package/dist/memory/recall-stats.js +1 -1
- package/dist/memory/reflect.js +260 -6
- package/dist/memory/relation-vocab.js +26 -4
- package/dist/memory/store.js +587 -41
- package/dist/memory/tail.js +88 -0
- package/dist/memory/write-gate.js +44 -0
- package/dist/permissions/computer-review.js +1 -1
- package/dist/permissions/flow-review.js +1 -1
- package/dist/repl/commands/flow.js +1 -1
- package/dist/repl/commands/image.js +30 -17
- package/dist/repl/commands/memory.js +257 -6
- package/dist/repl/commands/session.js +13 -0
- package/dist/repl/commands/tool-group.js +6 -0
- package/dist/repl/commands.js +1 -0
- package/dist/repl/episode-finalize.js +55 -0
- package/dist/repl/message-format.js +18 -0
- package/dist/repl/runtime.js +110 -5
- package/dist/runtime/uia-selector.js +1 -1
- package/dist/runtime/uia-service.js +3 -3
- package/dist/runtime/wait-until.js +1 -1
- package/dist/runtime/window-list.js +1 -1
- package/dist/sandbox/policy.js +49 -0
- package/dist/session/compact.js +47 -12
- package/dist/session/gui-actions.js +1 -1
- package/dist/tools/builtins/computer.js +5 -5
- package/dist/tools/builtins/memory-graph.js +12 -1
- package/dist/tools/builtins/memory-list.js +13 -3
- package/dist/tools/builtins/memory-save.js +82 -2
- package/dist/tools/builtins/memory-search.js +57 -2
- package/dist/tools/builtins/memory-update.js +52 -1
- package/dist/tools/builtins/read-file.js +51 -2
- package/dist/tools/builtins/run-flow.js +1 -1
- package/dist/tools/constants.js +60 -0
- package/dist/ui/clipboard.js +97 -0
- package/dist/ui/layout-internal/core.js +1 -1
- package/dist/ui/layout-internal/input-paint.js +7 -5
- package/dist/ui/layout-internal/state.js +8 -0
- package/dist/ui/layout-internal/statusbar.js +22 -1
- package/dist/ui/prompt-internal/editor.js +39 -0
- package/package.json +6 -1
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
// proactive.ts —— 前摄通道(R3):让记忆在**踩坑之前**自己出现。
|
|
2
|
+
//
|
|
3
|
+
// 问题不是"检索不准",是"根本不会去检索"。编程 agent 最贵的错误是重复踩已知的坑,
|
|
4
|
+
// 而踩坑那一刻模型恰恰想不到要先 memory_search。pull 通道(主动检索)的实测调用次数
|
|
5
|
+
// 至今为 0,所以这里做 push:每次工具调用前用它**规范化后的参数**去匹配既有记忆的
|
|
6
|
+
// `trigger` 字段(R1.5 定义),命中就把 `trigger → action` 前置到工具结果里。
|
|
7
|
+
//
|
|
8
|
+
// 设计取舍(全部为"宁少勿多"服务):
|
|
9
|
+
// - 只用子串/词元交集,不用用户可控正则 —— trigger 是模型写的自由文本,
|
|
10
|
+
// 把它编译成 RegExp 既有 ReDoS 风险,也会因为一个笔误正则让整条通道静默失效;
|
|
11
|
+
// - 每次工具调用最多注入 1 条,每进程最多 3 条,同一条命中后不再重复弹;
|
|
12
|
+
// - 只弹 `pitfall`/`decision`/`feedback`(天然是条件-动作式)或 pinned 条目,
|
|
13
|
+
// 普通 `fact`/`reference` 有 trigger 也不弹 —— 刷屏会让模型学会忽略提醒。
|
|
14
|
+
//
|
|
15
|
+
// 叶子依赖:只依赖 store.ts 与 context/text-search.ts 的纯函数,不读 config
|
|
16
|
+
// (memory 总开关由调用方判定后经 `enabled` 传入,同 store.ts 的既有约定)。
|
|
17
|
+
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { tokenize } from '../context/text-search.js';
|
|
21
|
+
import { loadAll, wantsTrigger } from './store.js';
|
|
22
|
+
import { evaluateAnchors, toAnchorPath } from './anchor.js';
|
|
23
|
+
/** 每次工具调用最多注入的条数。 */
|
|
24
|
+
const MAX_HINTS_PER_CALL = 1;
|
|
25
|
+
/**
|
|
26
|
+
* 每**用户轮**最多注入次数。
|
|
27
|
+
*
|
|
28
|
+
* 刻意不按进程计:REPL 进程常驻整天,按进程限 3 次等于几轮之后前摄通道永久静默。
|
|
29
|
+
* 而单轮内反复弹才是"狼来了"的真实来源——一轮 3 次已经足够醒目,再多久会失效。
|
|
30
|
+
* 由调用方在轮末调 `resetProactiveTurn()` 归零。
|
|
31
|
+
*/
|
|
32
|
+
const MAX_PER_TURN = 3;
|
|
33
|
+
/** 注入段硬预算(字符),防止一条长 trigger 挤占工具结果。 */
|
|
34
|
+
const HINT_MAX_CHARS = 480;
|
|
35
|
+
/** 至少命中的不同词元数。1 个太松(任何含"代码"的 trigger 都会弹)。 */
|
|
36
|
+
const MIN_MATCHED_TOKENS = 2;
|
|
37
|
+
/**
|
|
38
|
+
* 高频泛化词:单独命中它们不构成"这条记忆相关"的证据。
|
|
39
|
+
* 它们仍计入命中数,但不能作为**唯一**的强信号词。
|
|
40
|
+
*/
|
|
41
|
+
const GENERIC_TOKENS = new Set([
|
|
42
|
+
'the',
|
|
43
|
+
'a',
|
|
44
|
+
'an',
|
|
45
|
+
'to',
|
|
46
|
+
'is',
|
|
47
|
+
'of',
|
|
48
|
+
'in',
|
|
49
|
+
'on',
|
|
50
|
+
'for',
|
|
51
|
+
'and',
|
|
52
|
+
'or',
|
|
53
|
+
'if',
|
|
54
|
+
'when',
|
|
55
|
+
'this',
|
|
56
|
+
'that',
|
|
57
|
+
'with',
|
|
58
|
+
'use',
|
|
59
|
+
'uses',
|
|
60
|
+
'used',
|
|
61
|
+
'file',
|
|
62
|
+
'files',
|
|
63
|
+
'code',
|
|
64
|
+
'tool',
|
|
65
|
+
'tools',
|
|
66
|
+
'call',
|
|
67
|
+
'calls',
|
|
68
|
+
'run',
|
|
69
|
+
'runs',
|
|
70
|
+
'set',
|
|
71
|
+
'get',
|
|
72
|
+
'new',
|
|
73
|
+
'old',
|
|
74
|
+
'not',
|
|
75
|
+
'should',
|
|
76
|
+
'must',
|
|
77
|
+
'before',
|
|
78
|
+
'after',
|
|
79
|
+
'then',
|
|
80
|
+
// CJK 单字/泛化词(分词器会产出 unigram 与 bigram)
|
|
81
|
+
'时',
|
|
82
|
+
'的',
|
|
83
|
+
'了',
|
|
84
|
+
'和',
|
|
85
|
+
'与',
|
|
86
|
+
'在',
|
|
87
|
+
'是',
|
|
88
|
+
'工具',
|
|
89
|
+
'文件',
|
|
90
|
+
'代码',
|
|
91
|
+
'使用',
|
|
92
|
+
'时候',
|
|
93
|
+
'相关',
|
|
94
|
+
]);
|
|
95
|
+
/** 这些工具自身就是记忆通道,不需要前摄提醒(否则自我循环)。 */
|
|
96
|
+
const SKIPPED_TOOL_PREFIXES = ['memory_'];
|
|
97
|
+
const SKIPPED_TOOLS = new Set(['ask_human', 'plan_update', 'note_append', 'use_skill']);
|
|
98
|
+
/**
|
|
99
|
+
* R3.6:参数里"操作目标文件"的键名白名单。
|
|
100
|
+
*
|
|
101
|
+
* 刻意**不**做启发式全扫:编辑类工具的参数里还有 `old_string`/`content`,那些是
|
|
102
|
+
* **文本内容**,里面出现的路径不是本次操作对象——扫进去会大量误命中,而误报的代价
|
|
103
|
+
* 是整条通道被无视。白名单可枚举、可测试,新工具加参数时补一个键即可。
|
|
104
|
+
*/
|
|
105
|
+
const PATH_ARG_KEYS = new Set([
|
|
106
|
+
'path',
|
|
107
|
+
'file',
|
|
108
|
+
'files',
|
|
109
|
+
'filename',
|
|
110
|
+
'target',
|
|
111
|
+
'targets',
|
|
112
|
+
'source',
|
|
113
|
+
'sources',
|
|
114
|
+
'from',
|
|
115
|
+
'to',
|
|
116
|
+
'dest',
|
|
117
|
+
'destination',
|
|
118
|
+
'input',
|
|
119
|
+
'output',
|
|
120
|
+
'pattern', // glob 的 pattern 常含路径前缀,只用于粗匹配,不解析通配
|
|
121
|
+
]);
|
|
122
|
+
/** 单次调用最多看几个路径实参。防止 `files: [50 个]` 把匹配成本放大。 */
|
|
123
|
+
const MAX_ANCHOR_PATHS = 8;
|
|
124
|
+
/**
|
|
125
|
+
* 前摄通道开关(R3.5)。默认开启,可用 MOCODE_MEMORY_PROACTIVE=0/false/off/no 关闭。
|
|
126
|
+
* 注意:这是**独立开关**,不代替 memory 总开关 —— 调用方仍需先判定 memory 是否启用,
|
|
127
|
+
* 两者是与关系(总开关 veto 优先)。
|
|
128
|
+
*/
|
|
129
|
+
export function isProactiveEnabled() {
|
|
130
|
+
const raw = process.env.MOCODE_MEMORY_PROACTIVE;
|
|
131
|
+
if (raw === undefined)
|
|
132
|
+
return true;
|
|
133
|
+
return !['0', 'false', 'off', 'no'].includes(raw.trim().toLowerCase());
|
|
134
|
+
}
|
|
135
|
+
let cache = null;
|
|
136
|
+
function memoryFiles() {
|
|
137
|
+
return [path.join(os.homedir(), '.mocode', 'memory.jsonl'), path.join(process.cwd(), '.mocode', 'memory.jsonl')];
|
|
138
|
+
}
|
|
139
|
+
/** 廉价指纹:一次 stat 两个文件。读不到就当空(不抛)。 */
|
|
140
|
+
function filesStamp() {
|
|
141
|
+
return memoryFiles()
|
|
142
|
+
.map((p) => {
|
|
143
|
+
try {
|
|
144
|
+
const s = statSync(p);
|
|
145
|
+
return `${s.mtimeMs}:${s.size}`;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return '0:0';
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
.join('|');
|
|
152
|
+
}
|
|
153
|
+
/** 条目是否具备"可前摄"资格(R3.1 + R3.4)。 */
|
|
154
|
+
function eligible(e) {
|
|
155
|
+
if (e.status !== 'active')
|
|
156
|
+
return false;
|
|
157
|
+
if (!e.trigger || !e.trigger.trim())
|
|
158
|
+
return false;
|
|
159
|
+
// 高价值判定:三类天然条件-动作式的记忆,或用户显式置顶的。
|
|
160
|
+
return e.pinned || wantsTrigger(e.type);
|
|
161
|
+
}
|
|
162
|
+
function buildIndex() {
|
|
163
|
+
const stamp = filesStamp();
|
|
164
|
+
if (cache && cache.stamp === stamp)
|
|
165
|
+
return cache;
|
|
166
|
+
const docs = [];
|
|
167
|
+
const postings = new Map();
|
|
168
|
+
const anchorDocs = new Map();
|
|
169
|
+
for (const entry of loadAll()) {
|
|
170
|
+
// R3.6:锚点索引独立于 trigger 索引收集(理由见 ProactiveIndex.anchorDocs)。
|
|
171
|
+
// 只收 active:归档/被取代的条目说的是历史,不该在你要改代码时冒出来。
|
|
172
|
+
if (entry.status === 'active' && entry.anchors && entry.anchors.length > 0) {
|
|
173
|
+
for (const a of entry.anchors) {
|
|
174
|
+
const list = anchorDocs.get(a.path);
|
|
175
|
+
if (list)
|
|
176
|
+
list.push(entry);
|
|
177
|
+
else
|
|
178
|
+
anchorDocs.set(a.path, [entry]);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!eligible(entry))
|
|
182
|
+
continue;
|
|
183
|
+
// trigger 是主键;name/summary 作为弱补充,提高"用户用词与模型措辞不一致"时的召回。
|
|
184
|
+
const text = [entry.trigger ?? '', entry.name, entry.summary].join(' ');
|
|
185
|
+
// 单字(含 CJK unigram / 单个字母)不参与匹配:一个中文词会被分词器同时产出
|
|
186
|
+
// "记"、"忆"、"记忆" 三个 token,拿单字计分会把一个词算成三次命中,阈值形同虚设。
|
|
187
|
+
const tokens = new Set(tokenize(text).filter((t) => t.length >= 2));
|
|
188
|
+
if (tokens.size === 0)
|
|
189
|
+
continue;
|
|
190
|
+
const docIndex = docs.length;
|
|
191
|
+
docs.push({ entry, tokens });
|
|
192
|
+
for (const t of tokens) {
|
|
193
|
+
const list = postings.get(t);
|
|
194
|
+
if (list)
|
|
195
|
+
list.push(docIndex);
|
|
196
|
+
else
|
|
197
|
+
postings.set(t, [docIndex]);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
cache = { stamp, postings, docs, anchorDocs };
|
|
201
|
+
return cache;
|
|
202
|
+
}
|
|
203
|
+
/** 测试专用:清掉索引缓存与注入计数。 */
|
|
204
|
+
export function __resetProactiveForTests() {
|
|
205
|
+
cache = null;
|
|
206
|
+
fired.clear();
|
|
207
|
+
turnCount = 0;
|
|
208
|
+
}
|
|
209
|
+
// ── 参数规范化(R3.2)────────────────────────────────────────────────────────
|
|
210
|
+
/**
|
|
211
|
+
* 把工具参数压成一段可匹配的文本。
|
|
212
|
+
*
|
|
213
|
+
* 规范化要点(全部确定性的字符串处理,不碰语义):
|
|
214
|
+
* - 去引号:JSON 里的转义引号会把 `"path"` 变成 `path`,否则永远匹配不上;
|
|
215
|
+
* - 路径转工作区相对:`C:\a\b\src\x.ts` 与 `/home/u/p/src/x.ts` 都应匹配 trigger 里的 `src/x.ts`;
|
|
216
|
+
* - 合并空白、统一小写。
|
|
217
|
+
*/
|
|
218
|
+
export function normalizeArgsText(value, depth = 0) {
|
|
219
|
+
if (depth > 4 || value === null || value === undefined)
|
|
220
|
+
return '';
|
|
221
|
+
if (typeof value === 'string')
|
|
222
|
+
return value;
|
|
223
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
224
|
+
return String(value);
|
|
225
|
+
if (Array.isArray(value))
|
|
226
|
+
return value.map((v) => normalizeArgsText(v, depth + 1)).join(' ');
|
|
227
|
+
if (typeof value === 'object') {
|
|
228
|
+
return Object.values(value)
|
|
229
|
+
.map((v) => normalizeArgsText(v, depth + 1))
|
|
230
|
+
.join(' ');
|
|
231
|
+
}
|
|
232
|
+
return '';
|
|
233
|
+
}
|
|
234
|
+
/** 文本级规范化:去引号、反斜杠转正斜杠、路径转相对、合并空白、小写。 */
|
|
235
|
+
export function canonicalizeContext(raw) {
|
|
236
|
+
let s = String(raw ?? '');
|
|
237
|
+
// 引号去掉(保留内容):" ' ` 以及中文引号
|
|
238
|
+
s = s.replace(/["'`“”‘’]/g, '');
|
|
239
|
+
s = s.replace(/\\/g, '/');
|
|
240
|
+
// 绝对路径转相对:把工作区前缀剥掉,让 trigger 里写的 `src/x.ts` 能命中。
|
|
241
|
+
const cwd = process.cwd().replace(/\\/g, '/').replace(/\/+$/, '');
|
|
242
|
+
if (cwd) {
|
|
243
|
+
const lower = s.toLowerCase();
|
|
244
|
+
const lcwd = cwd.toLowerCase();
|
|
245
|
+
if (lcwd.length > 1 && lower.includes(lcwd)) {
|
|
246
|
+
// 大小写不敏感地剥前缀:用索引切片,避免正则里塞用户路径
|
|
247
|
+
let out = '';
|
|
248
|
+
let i = 0;
|
|
249
|
+
while (i < s.length) {
|
|
250
|
+
if (lower.startsWith(lcwd, i)) {
|
|
251
|
+
i += lcwd.length;
|
|
252
|
+
out += ' ';
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
out += s[i];
|
|
256
|
+
i++;
|
|
257
|
+
}
|
|
258
|
+
s = out;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// home 目录前缀同样剥掉
|
|
262
|
+
const home = os.homedir().replace(/\\/g, '/').replace(/\/+$/, '');
|
|
263
|
+
if (home && home !== '/' && s.toLowerCase().includes(home.toLowerCase())) {
|
|
264
|
+
const lower = s.toLowerCase();
|
|
265
|
+
const lhome = home.toLowerCase();
|
|
266
|
+
let out = '';
|
|
267
|
+
let i = 0;
|
|
268
|
+
while (i < s.length) {
|
|
269
|
+
if (lower.startsWith(lhome, i)) {
|
|
270
|
+
i += lhome.length;
|
|
271
|
+
out += ' ~ ';
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
out += s[i];
|
|
275
|
+
i++;
|
|
276
|
+
}
|
|
277
|
+
s = out;
|
|
278
|
+
}
|
|
279
|
+
// 路径分隔符两侧的空白不该影响匹配
|
|
280
|
+
s = s.replace(/\s*\/\s*/g, '/');
|
|
281
|
+
s = s.replace(/\s+/g, ' ').trim();
|
|
282
|
+
return s.toLowerCase();
|
|
283
|
+
}
|
|
284
|
+
// ── 匹配 ──────────────────────────────────────────────────────────────────
|
|
285
|
+
/** 已注入过的条目 id → 注入次数(冷却 R3.4:同一条在同一进程内只弹一次)。 */
|
|
286
|
+
const fired = new Map();
|
|
287
|
+
let turnCount = 0;
|
|
288
|
+
const EMPTY_COUNTERS = {
|
|
289
|
+
toolCalls: 0,
|
|
290
|
+
injections: 0,
|
|
291
|
+
triggerHits: 0,
|
|
292
|
+
anchorHits: 0,
|
|
293
|
+
staleAnchorHits: 0,
|
|
294
|
+
distinctEntries: 0,
|
|
295
|
+
updatedAt: null,
|
|
296
|
+
};
|
|
297
|
+
function statsPath() {
|
|
298
|
+
return path.join(process.cwd(), '.mocode', 'memory-proactive-stats.json');
|
|
299
|
+
}
|
|
300
|
+
let counters = null;
|
|
301
|
+
function readCountersFile() {
|
|
302
|
+
try {
|
|
303
|
+
const raw = readFileSync(statsPath(), 'utf8');
|
|
304
|
+
const o = JSON.parse(raw);
|
|
305
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
|
|
306
|
+
return {
|
|
307
|
+
toolCalls: num(o.toolCalls),
|
|
308
|
+
injections: num(o.injections),
|
|
309
|
+
triggerHits: num(o.triggerHits),
|
|
310
|
+
anchorHits: num(o.anchorHits),
|
|
311
|
+
staleAnchorHits: num(o.staleAnchorHits),
|
|
312
|
+
distinctEntries: num(o.distinctEntries),
|
|
313
|
+
updatedAt: typeof o.updatedAt === 'string' ? o.updatedAt : null,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
return { ...EMPTY_COUNTERS }; // 缺失/损坏一律当零,埋点绝不抛
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/** 当前累计值(只读快照;首次调用会懒加载既有文件)。 */
|
|
321
|
+
export function proactiveCounters() {
|
|
322
|
+
counters ??= readCountersFile();
|
|
323
|
+
return { ...counters, distinctEntries: fired.size > 0 ? fired.size : counters.distinctEntries };
|
|
324
|
+
}
|
|
325
|
+
function bump(field) {
|
|
326
|
+
counters ??= readCountersFile();
|
|
327
|
+
counters[field] += 1;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* 把累计值写入 `.mocode/memory-proactive-stats.json`。幂等、失败静默。
|
|
331
|
+
*
|
|
332
|
+
* `distinctEntries` 只在有注入时更新:进程内 `fired` 为空时不能把文件里的历史值清零,
|
|
333
|
+
* 否则每次重启都把覆盖广度重置成 0。
|
|
334
|
+
*/
|
|
335
|
+
export function flushProactiveStats() {
|
|
336
|
+
if (!counters)
|
|
337
|
+
return; // 从没匹配过 → 无新数据,零 IO
|
|
338
|
+
const snapshot = { ...counters };
|
|
339
|
+
if (fired.size > 0)
|
|
340
|
+
snapshot.distinctEntries = fired.size;
|
|
341
|
+
snapshot.updatedAt = new Date().toISOString();
|
|
342
|
+
try {
|
|
343
|
+
const p = statsPath();
|
|
344
|
+
mkdirSync(path.dirname(p), { recursive: true });
|
|
345
|
+
const tmp = p + '.tmp';
|
|
346
|
+
writeFileSync(tmp, JSON.stringify(snapshot, null, 2), 'utf8');
|
|
347
|
+
renameSync(tmp, p);
|
|
348
|
+
counters = snapshot;
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
// 静默:埋点不可写不影响功能
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
/** 测试专用:清计数与落盘缓存(模块级状态,共享进程必须清)。 */
|
|
355
|
+
export function __resetProactiveCountersForTests() {
|
|
356
|
+
counters = null;
|
|
357
|
+
}
|
|
358
|
+
/** 新的一轮用户输入开始:重置每轮限额。同一条记忆仍受 `fired` 的进程级冷却约束。 */
|
|
359
|
+
export function resetProactiveTurn() {
|
|
360
|
+
turnCount = 0;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* 匹配候选(不做限额,供测试与观测)。返回按分降序、去重。
|
|
364
|
+
*
|
|
365
|
+
* @param contextText 当前用户轮的文本。**不是可选糖**:trigger 写的是自然语言
|
|
366
|
+
* ("构造工具 schema 发给 dashscope 时"),而工具参数只有 `{"path":"src/llm/tool-schema.ts"}`,
|
|
367
|
+
* 两者可重合的词常常只有 1 个,单靠参数永远达不到阈值——通道会静默失效。
|
|
368
|
+
* trigger 里的场景词几乎都出现在用户的提问里,所以必须把轮文本并进来才有信号。
|
|
369
|
+
*/
|
|
370
|
+
export function matchProactive(toolName, args, contextText) {
|
|
371
|
+
const ctx = `${toolName} ${normalizeArgsText(args)} ${contextText ?? ''}`;
|
|
372
|
+
const canonical = canonicalizeContext(ctx);
|
|
373
|
+
if (canonical.length < 4)
|
|
374
|
+
return [];
|
|
375
|
+
const tokens = new Set(tokenize(canonical));
|
|
376
|
+
if (tokens.size === 0)
|
|
377
|
+
return [];
|
|
378
|
+
const index = buildIndex();
|
|
379
|
+
if (index.docs.length === 0)
|
|
380
|
+
return [];
|
|
381
|
+
const score = new Map();
|
|
382
|
+
const strong = new Map();
|
|
383
|
+
for (const t of tokens) {
|
|
384
|
+
// 与索引侧同口径:单字不算证据(一个中文词会被分词器拆成单字+bigram,按单字计分等于数三次)。
|
|
385
|
+
if (t.length < 2)
|
|
386
|
+
continue;
|
|
387
|
+
const hits = index.postings.get(t);
|
|
388
|
+
if (!hits)
|
|
389
|
+
continue;
|
|
390
|
+
const isGeneric = GENERIC_TOKENS.has(t);
|
|
391
|
+
for (const d of hits) {
|
|
392
|
+
score.set(d, (score.get(d) ?? 0) + 1);
|
|
393
|
+
if (!isGeneric)
|
|
394
|
+
strong.set(d, true);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
const out = [];
|
|
398
|
+
for (const [d, s] of score) {
|
|
399
|
+
if (s < MIN_MATCHED_TOKENS)
|
|
400
|
+
continue;
|
|
401
|
+
// 必须有至少一个非泛化词命中,否则"含'代码'两个字"就会触发一切。
|
|
402
|
+
if (!strong.get(d))
|
|
403
|
+
continue;
|
|
404
|
+
const doc = index.docs[d];
|
|
405
|
+
if (!doc)
|
|
406
|
+
continue;
|
|
407
|
+
out.push({ entry: doc.entry, score: s });
|
|
408
|
+
}
|
|
409
|
+
out.sort((a, b) => b.score - a.score || Number(b.entry.pinned) - Number(a.entry.pinned));
|
|
410
|
+
return out;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* 生成要前置到工具结果的提醒段。无命中 / 超额 / 冷却中 → 空串(零注入)。
|
|
414
|
+
*
|
|
415
|
+
* @param enabled 由调用方判定:memory 总开关 && isProactiveEnabled()。
|
|
416
|
+
* @param contextText 当前用户轮文本,参与匹配(理由见 matchProactive)。
|
|
417
|
+
*/
|
|
418
|
+
export function proactiveHint(toolName, args, enabled, contextText) {
|
|
419
|
+
if (!enabled)
|
|
420
|
+
return '';
|
|
421
|
+
if (turnCount >= MAX_PER_TURN)
|
|
422
|
+
return '';
|
|
423
|
+
if (SKIPPED_TOOLS.has(toolName))
|
|
424
|
+
return '';
|
|
425
|
+
if (SKIPPED_TOOL_PREFIXES.some((p) => toolName.startsWith(p)))
|
|
426
|
+
return '';
|
|
427
|
+
// R4.1:只有真正走到匹配的工具调用才计入分母。被开关/冷却/跳过工具挡掉的不算——
|
|
428
|
+
// 否则「命中率」会被大量与记忆无关的几何式调用(如连续 read_file)稀释成无意义的数字。
|
|
429
|
+
bump('toolCalls');
|
|
430
|
+
const matches = matchProactive(toolName, args, contextText);
|
|
431
|
+
const picked = [];
|
|
432
|
+
for (const m of matches) {
|
|
433
|
+
if (picked.length >= MAX_HINTS_PER_CALL)
|
|
434
|
+
break;
|
|
435
|
+
// 冷却:同一条在同一进程内只弹一次。反复弹同一条是"狼来了"的主要来源。
|
|
436
|
+
if (fired.has(m.entry.id))
|
|
437
|
+
continue;
|
|
438
|
+
picked.push(m);
|
|
439
|
+
}
|
|
440
|
+
if (picked.length > 0) {
|
|
441
|
+
const lines = picked.map((m) => {
|
|
442
|
+
const e = m.entry;
|
|
443
|
+
const head = `- [${e.id}] ${e.name}`;
|
|
444
|
+
const when = e.trigger ? `\n when: ${e.trigger}` : '';
|
|
445
|
+
const action = e.action ? `\n do: ${e.action}` : '';
|
|
446
|
+
const body = !e.action && e.body ? `\n ${e.body.slice(0, 160)}` : '';
|
|
447
|
+
return head + when + action + body;
|
|
448
|
+
});
|
|
449
|
+
let out = `[proactive memory] 以下记忆的触发条件与你刚刚这次调用相符(按需采用,不是强制):\n${lines.join('\n')}`;
|
|
450
|
+
if (out.length > HINT_MAX_CHARS)
|
|
451
|
+
out = out.slice(0, HINT_MAX_CHARS) + ' …';
|
|
452
|
+
for (const m of picked) {
|
|
453
|
+
fired.set(m.entry.id, (fired.get(m.entry.id) ?? 0) + 1);
|
|
454
|
+
turnCount++;
|
|
455
|
+
}
|
|
456
|
+
bump('triggerHits');
|
|
457
|
+
bump('injections');
|
|
458
|
+
return out;
|
|
459
|
+
}
|
|
460
|
+
// R3.6:trigger 没命中时的弱通道 —— 这次调用碰到的文件,有没有记忆锚定过它。
|
|
461
|
+
// `read_file` 排除在外:R2.4 已经在它自己的结果尾部直接回注了同样的信息,
|
|
462
|
+
// 两边都弹就是同一句话出现两次,只会教模型忽略这一段。
|
|
463
|
+
if (toolName === 'read_file')
|
|
464
|
+
return '';
|
|
465
|
+
const anchorHit = anchorHint(args);
|
|
466
|
+
if (!anchorHit)
|
|
467
|
+
return '';
|
|
468
|
+
turnCount++;
|
|
469
|
+
bump('anchorHits');
|
|
470
|
+
bump('injections');
|
|
471
|
+
if (anchorHit.stale)
|
|
472
|
+
bump('staleAnchorHits');
|
|
473
|
+
return anchorHit.text;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* R3.6 锚点弱通道:把「这次要动的文件」映射回锚定它的记忆。
|
|
477
|
+
*
|
|
478
|
+
* 为什么值得单独一条通道:锚定 `anchors` 的多是 `reference` 型结构知识
|
|
479
|
+
* (“resultEvent 是 history 回灌的唯一汇聚点”),它们通常**没有 trigger**
|
|
480
|
+
* ——`wantsTrigger` 只认 pitfall/decision/feedback。所以只靠 trigger 索引,
|
|
481
|
+
* 这类记忆在你要改那个文件时永远不会出现。
|
|
482
|
+
*
|
|
483
|
+
* 匹配是**路径相等**,不是模糊重合:同一个文件就是同一个文件,不需要阈值,
|
|
484
|
+
* 也不会被 GENERIC_TOKENS 那套泛化词规则连累。
|
|
485
|
+
*/
|
|
486
|
+
function anchorHint(args) {
|
|
487
|
+
const paths = extractAnchorPaths(args);
|
|
488
|
+
if (paths.length === 0)
|
|
489
|
+
return null;
|
|
490
|
+
const index = buildIndex();
|
|
491
|
+
if (index.anchorDocs.size === 0)
|
|
492
|
+
return null;
|
|
493
|
+
const picked = [];
|
|
494
|
+
const seen = new Set();
|
|
495
|
+
for (const raw of paths) {
|
|
496
|
+
let p;
|
|
497
|
+
try {
|
|
498
|
+
p = toAnchorPath(raw);
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
for (const entry of index.anchorDocs.get(p) ?? []) {
|
|
504
|
+
if (seen.has(entry.id) || fired.has(entry.id))
|
|
505
|
+
continue;
|
|
506
|
+
seen.add(entry.id);
|
|
507
|
+
// R4.1:stale 判定在挑选时就做掉,不再在渲染阶段重复 stat——一条命中要算一次
|
|
508
|
+
// 「这次弹出的是不是已经过期的记忆」,而这个比例是锚点通道最关键的噪音指标。
|
|
509
|
+
const state = evaluateAnchors(entry.anchors);
|
|
510
|
+
picked.push({ entry, path: p, stale: state.stale });
|
|
511
|
+
if (picked.length >= MAX_HINTS_PER_CALL)
|
|
512
|
+
break;
|
|
513
|
+
}
|
|
514
|
+
if (picked.length >= MAX_HINTS_PER_CALL)
|
|
515
|
+
break;
|
|
516
|
+
}
|
|
517
|
+
if (picked.length === 0)
|
|
518
|
+
return null;
|
|
519
|
+
const lines = picked.map(({ entry, path: p, stale }) => {
|
|
520
|
+
// 锚点已失效要说出来:那条记忆描述的是**改写前**的代码,直接照做可能出错。
|
|
521
|
+
// 但也不能因此不弹 —— 用户正要在同一个文件上动手,恰恰是最该知道
|
|
522
|
+
// “这里有过一条记忆,但它已经过期了”的时刻。
|
|
523
|
+
const state = evaluateAnchors(entry.anchors);
|
|
524
|
+
const staleTag = stale ? ` [STALE-CODE: ${describeStale(state)}]` : '';
|
|
525
|
+
const when = entry.trigger ? `\n when: ${entry.trigger}` : '';
|
|
526
|
+
const action = entry.action ? `\n do: ${entry.action}` : '';
|
|
527
|
+
const body = !entry.action && entry.body ? `\n ${entry.body.slice(0, 160)}` : '';
|
|
528
|
+
return `- [${entry.id}] ${entry.name} (锚定 ${p})${staleTag}${when}${action}${body}`;
|
|
529
|
+
});
|
|
530
|
+
let out = `[proactive memory] 有记忆锚定了你即将操作的文件(按需采用,不是强制):\n${lines.join('\n')}`;
|
|
531
|
+
if (out.length > HINT_MAX_CHARS)
|
|
532
|
+
out = out.slice(0, HINT_MAX_CHARS) + ' …';
|
|
533
|
+
for (const { entry } of picked)
|
|
534
|
+
fired.set(entry.id, (fired.get(entry.id) ?? 0) + 1);
|
|
535
|
+
return { text: out, stale: picked.some((p) => p.stale) };
|
|
536
|
+
}
|
|
537
|
+
function describeStale(state) {
|
|
538
|
+
const parts = [];
|
|
539
|
+
if (state.changed.length > 0)
|
|
540
|
+
parts.push(`代码已变更 ${state.changed.join(', ')}`);
|
|
541
|
+
if (state.missing.length > 0)
|
|
542
|
+
parts.push(`代码已消失 ${state.missing.join(', ')}`);
|
|
543
|
+
return parts.join('; ');
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* 从工具参数里抽「文件路径」类实参。
|
|
547
|
+
*
|
|
548
|
+
* 只认**已知的键名**,不做启发式扫描整个参数对象:
|
|
549
|
+
* - 启发式会把 `content`/`old_string` 里出现的路径当成本次操作目标,而那些是
|
|
550
|
+
* **文本内容**不是操作对象,会制造大量误命中;
|
|
551
|
+
* - 键名白名单是可枚举、可测试的,新工具加参数时只需在这里补一个键。
|
|
552
|
+
*
|
|
553
|
+
* 值可以是字符串或字符串数组(`files: [...]`),最多取 MAX_ANCHOR_PATHS 条。
|
|
554
|
+
*/
|
|
555
|
+
export function extractAnchorPaths(args) {
|
|
556
|
+
if (!args || typeof args !== 'object')
|
|
557
|
+
return [];
|
|
558
|
+
const out = [];
|
|
559
|
+
const push = (v) => {
|
|
560
|
+
if (typeof v !== 'string')
|
|
561
|
+
return;
|
|
562
|
+
const s = v.trim();
|
|
563
|
+
if (!s || s.length > 512)
|
|
564
|
+
return;
|
|
565
|
+
if (out.length < MAX_ANCHOR_PATHS)
|
|
566
|
+
out.push(s);
|
|
567
|
+
};
|
|
568
|
+
for (const [key, value] of Object.entries(args)) {
|
|
569
|
+
if (!PATH_ARG_KEYS.has(key))
|
|
570
|
+
continue;
|
|
571
|
+
if (Array.isArray(value)) {
|
|
572
|
+
for (const v of value)
|
|
573
|
+
push(v);
|
|
574
|
+
}
|
|
575
|
+
else {
|
|
576
|
+
push(value);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return out;
|
|
580
|
+
}
|
|
581
|
+
/** 本轮已注入次数(观测用)。 */
|
|
582
|
+
export function proactiveTurnCount() {
|
|
583
|
+
return turnCount;
|
|
584
|
+
}
|
|
585
|
+
/** 已注入过的条目 id(观测/测试用)。 */
|
|
586
|
+
export function proactiveFiredIds() {
|
|
587
|
+
return [...fired.keys()];
|
|
588
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// recall-stats.ts —— 项目图谱 pull 召回的轻量埋点。
|
|
2
2
|
//
|
|
3
|
-
// 目的(memory
|
|
3
|
+
// 目的(design-notes/memory/memory.md §2.1):项目图谱曾"只写不读"。pull 通道(常驻 hint + memory_search
|
|
4
4
|
// 强化)上线后,用零依赖计数器回答"模型到底有没有在用图谱":搜了几次、图谱段有几次命中。
|
|
5
5
|
// 数据只存项目 <cwd>/.mocode/memory-recall-stats.json,供 memory_graph stats 展示,据此
|
|
6
6
|
// 决定要不要再加"turn 起步阈值注入"的安全网。全部静默容错、tmp+rename 原子写。
|