mocode-ai 1.9.0 → 1.9.2
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/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/dist/agent/index.js +18 -1
- package/dist/agent/model-turn.js +35 -5
- package/dist/agent/run-coordinator.js +32 -5
- package/dist/config/index.js +1 -1
- package/dist/headless.js +7 -0
- package/dist/i18n/index.js +48 -0
- package/dist/memory/anchor-backfill.js +227 -0
- package/dist/memory/anchor.js +91 -9
- package/dist/memory/graph.js +54 -6
- package/dist/memory/guard.js +174 -0
- package/dist/memory/health.js +13 -0
- package/dist/memory/index.js +5 -2
- package/dist/memory/reflect.js +130 -7
- package/dist/memory/seed.js +227 -0
- package/dist/memory/store.js +16 -2
- package/dist/memory/tail.js +20 -0
- package/dist/memory/turn-recall.js +149 -0
- package/dist/repl/commands/memory.js +217 -4
- package/dist/repl/commands/session.js +33 -0
- package/dist/repl/commands/stats.js +105 -3
- package/dist/repl/commands.js +6 -1
- package/dist/repl/runtime.js +34 -7
- package/dist/runtime/runtime.js +13 -0
- package/dist/session/compact.js +16 -0
- package/dist/session/global-usage.js +173 -0
- package/dist/session/store.js +82 -1
- package/dist/tools/builtins/memory-graph.js +20 -6
- package/dist/tools/builtins/memory-list.js +3 -1
- package/dist/tools/builtins/memory-save.js +30 -3
- package/dist/tools/builtins/memory-search.js +5 -0
- package/dist/tools/builtins/memory-update.js +13 -3
- package/dist/ui/prompt-internal/editor.js +11 -1
- package/package.json +1 -1
package/dist/memory/anchor.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
//
|
|
14
14
|
// 叶子依赖:node:fs / node:path / sandbox/root(共享叶子)/ changeset/hash(叶子)。
|
|
15
15
|
// 不依赖 store.ts(反向依赖会成环:store 要用本模块在写入时算 hash)。
|
|
16
|
-
import { readFileSync, statSync } from 'node:fs';
|
|
16
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
17
17
|
import path from 'node:path';
|
|
18
18
|
import { contentHash } from '../changeset/hash.js';
|
|
19
19
|
import { getSandboxRoot } from '../sandbox/root.js';
|
|
@@ -23,6 +23,16 @@ export const MAX_ANCHORS = 8;
|
|
|
23
23
|
const MAX_ANCHOR_FILE_BYTES = 4 * 1024 * 1024;
|
|
24
24
|
/** 符号片段最长行数,防止一个类把整个文件都算进来。 */
|
|
25
25
|
const MAX_SYMBOL_FRAGMENT_LINES = 400;
|
|
26
|
+
/**
|
|
27
|
+
* R7.1 目录锚点最多看多少个子项。
|
|
28
|
+
*
|
|
29
|
+
* 为什么要封顶:`evaluateAnchor` 在 `listEntries` / `searchEntries` / `proactive` 这些
|
|
30
|
+
* **每次召回都会走的同步函数**里被调用,递归整棵树会让一次启动变成全盘 stat。
|
|
31
|
+
* 只数直接子项的名字,足以发现「新增/删除/改名」,也就是「我记的这个目录已经不是
|
|
32
|
+
* 那个目录了」这一档最要紧的变化。`node_modules` 这类目录超过上限时只取前 N 个,
|
|
33
|
+
* 指纹退化为「前缀不变即 fresh」——比为了精确而把启动拖慢好几秒划算。
|
|
34
|
+
*/
|
|
35
|
+
const MAX_DIR_ENTRIES = 512;
|
|
26
36
|
export const NOT_ANCHOR_STALE = { stale: false, changed: [], missing: [] };
|
|
27
37
|
// ── 路径归一 ──────────────────────────────────────────────────────────────
|
|
28
38
|
/** 工作区根:沙箱根优先(子 agent 有隔离 overlay),否则 cwd。 */
|
|
@@ -185,10 +195,53 @@ export function __resetAnchorCacheForTests() {
|
|
|
185
195
|
function hashPair(text, path) {
|
|
186
196
|
return { contentHash: contentHash(text), normHash: contentHash(normalizeForHash(text, path)) };
|
|
187
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* R7.1 目录指纹:只取**直接子项名单**(排序后)。
|
|
200
|
+
*
|
|
201
|
+
* 刻意**不含目录 mtime**——设计文档原写「子项名 + mtime」,实现时去掉:mtime 在
|
|
202
|
+
* 「往目录里写个临时文件再删掉」时也会变,而结构完全没变,那是一次假 stale;
|
|
203
|
+
* 反之文件内容改动本就不是目录锚点该管的事(那该锚文件)。宁可漏报不可误报,
|
|
204
|
+
* 与 `normHash` 的判据一致。
|
|
205
|
+
*
|
|
206
|
+
* 不递归的理由写在 `MAX_DIR_ENTRIES` 上面。名字列表负责「新增/删除/改名」,
|
|
207
|
+
* 子目录内部的变化看不见——这是为同步热路径付得起的价钱。
|
|
208
|
+
*/
|
|
209
|
+
function hashDir(abs) {
|
|
210
|
+
let names;
|
|
211
|
+
try {
|
|
212
|
+
const s = statSync(abs);
|
|
213
|
+
if (!s.isDirectory())
|
|
214
|
+
return { ok: false, reason: '不是目录' };
|
|
215
|
+
names = readdirSync(abs).sort();
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return { ok: false, reason: '目录不存在或不可读' };
|
|
219
|
+
}
|
|
220
|
+
const shown = names.slice(0, MAX_DIR_ENTRIES);
|
|
221
|
+
const over = names.length - shown.length;
|
|
222
|
+
const payload = `dir:${shown.join('\n')}${over > 0 ? `\n+${over}` : ''}`;
|
|
223
|
+
return { ok: true, hash: contentHash(payload) };
|
|
224
|
+
}
|
|
188
225
|
export function buildAnchor(input, root) {
|
|
189
226
|
const rawPath = String(input.path ?? '').trim();
|
|
190
227
|
if (!rawPath)
|
|
191
228
|
return { ok: false, reason: 'path 为空' };
|
|
229
|
+
const kind = input.kind ?? 'file';
|
|
230
|
+
// URL:只记录,不校验。判定必须同步(见 MemoryAnchor.kind),而 HTTP 请求不能出现在
|
|
231
|
+
// listEntries / searchEntries / proactive 里。存下来仍有价值——它让「这条记忆说的是
|
|
232
|
+
// 哪个页面」可追溯,也让将来的异步校验有据可依;但**绝不**假装它被验证过。
|
|
233
|
+
if (kind === 'url') {
|
|
234
|
+
if (!/^https?:\/\//i.test(rawPath))
|
|
235
|
+
return { ok: false, reason: 'URL 必须以 http(s):// 开头' };
|
|
236
|
+
return { ok: true, anchor: { kind: 'url', path: rawPath } };
|
|
237
|
+
}
|
|
238
|
+
if (kind === 'dir') {
|
|
239
|
+
const abs = resolveAnchorPath(rawPath, root);
|
|
240
|
+
const d = hashDir(abs);
|
|
241
|
+
if (!d.ok)
|
|
242
|
+
return { ok: false, reason: d.reason };
|
|
243
|
+
return { ok: true, anchor: { kind: 'dir', path: toAnchorPath(rawPath, root), contentHash: d.hash } };
|
|
244
|
+
}
|
|
192
245
|
const symbol = input.symbol?.trim() || undefined;
|
|
193
246
|
const abs = resolveAnchorPath(rawPath, root);
|
|
194
247
|
const file = readCached(abs);
|
|
@@ -209,7 +262,7 @@ export function buildAnchor(input, root) {
|
|
|
209
262
|
},
|
|
210
263
|
};
|
|
211
264
|
}
|
|
212
|
-
/** 批量构建:丢弃失败项、按 path+symbol 去重、封顶 MAX_ANCHORS。 */
|
|
265
|
+
/** 批量构建:丢弃失败项、按 kind+path+symbol 去重、封顶 MAX_ANCHORS。 */
|
|
213
266
|
export function buildAnchors(inputs, root) {
|
|
214
267
|
if (!inputs || inputs.length === 0)
|
|
215
268
|
return [];
|
|
@@ -219,7 +272,7 @@ export function buildAnchors(inputs, root) {
|
|
|
219
272
|
const r = buildAnchor(input, root);
|
|
220
273
|
if (!r.ok)
|
|
221
274
|
continue;
|
|
222
|
-
const key = `${r.anchor.path}\u0000${r.anchor.symbol ?? ''}`;
|
|
275
|
+
const key = `${r.anchor.kind ?? 'file'}\u0000${r.anchor.path}\u0000${r.anchor.symbol ?? ''}`;
|
|
223
276
|
if (seen.has(key))
|
|
224
277
|
continue;
|
|
225
278
|
seen.add(key);
|
|
@@ -229,8 +282,26 @@ export function buildAnchors(inputs, root) {
|
|
|
229
282
|
}
|
|
230
283
|
return out;
|
|
231
284
|
}
|
|
232
|
-
/**
|
|
285
|
+
/** 判定单个锚点的现状。按 `kind` 分派;缺省 `file`(R2 旧条目零迁移)。 */
|
|
233
286
|
export function evaluateAnchor(anchor, root) {
|
|
287
|
+
const kind = anchor.kind ?? 'file';
|
|
288
|
+
if (kind === 'url') {
|
|
289
|
+
// 刻意恒 unknown,不是「懒得做」:unknown 不算 stale(见 EntryAnchorState),
|
|
290
|
+
// 所以 URL 锚点既不会冤枉条目,也不会假装校验过。
|
|
291
|
+
return { anchor, status: 'unknown', detail: 'URL 锚点不做同步校验(需网络)' };
|
|
292
|
+
}
|
|
293
|
+
if (kind === 'dir') {
|
|
294
|
+
const d = hashDir(resolveAnchorPath(anchor.path, root));
|
|
295
|
+
if (!d.ok)
|
|
296
|
+
return { anchor, status: 'missing', detail: d.reason };
|
|
297
|
+
if (anchor.contentHash && d.hash === anchor.contentHash)
|
|
298
|
+
return { anchor, status: 'fresh' };
|
|
299
|
+
if (!anchor.contentHash)
|
|
300
|
+
return { anchor, status: 'unknown', detail: '目录锚点缺指纹' };
|
|
301
|
+
return { anchor, status: 'stale', detail: '目录结构已变更' };
|
|
302
|
+
}
|
|
303
|
+
if (!anchor.contentHash)
|
|
304
|
+
return { anchor, status: 'unknown', detail: '锚点缺内容哈希' };
|
|
234
305
|
const abs = resolveAnchorPath(anchor.path, root);
|
|
235
306
|
const file = readCached(abs);
|
|
236
307
|
if (file.oversized)
|
|
@@ -247,6 +318,12 @@ export function evaluateAnchor(anchor, root) {
|
|
|
247
318
|
return { anchor, status: 'fresh', detail: '仅排版/注释变化' };
|
|
248
319
|
return { anchor, status: 'stale', detail: '内容已变更' };
|
|
249
320
|
}
|
|
321
|
+
/** 锚点标签(工具输出与 `/memory show` 共用)。URL 直接给原文,不加 `#symbol`。 */
|
|
322
|
+
export function anchorLabel(anchor) {
|
|
323
|
+
if ((anchor.kind ?? 'file') !== 'file')
|
|
324
|
+
return anchor.path;
|
|
325
|
+
return anchor.symbol ? `${anchor.path}#${anchor.symbol}` : anchor.path;
|
|
326
|
+
}
|
|
250
327
|
/** 判定一条记忆的全部锚点。 */
|
|
251
328
|
export function evaluateAnchors(anchors, root) {
|
|
252
329
|
if (!anchors || anchors.length === 0)
|
|
@@ -255,7 +332,7 @@ export function evaluateAnchors(anchors, root) {
|
|
|
255
332
|
const missing = [];
|
|
256
333
|
for (const anchor of anchors) {
|
|
257
334
|
const r = evaluateAnchor(anchor, root);
|
|
258
|
-
const label = anchor
|
|
335
|
+
const label = anchorLabel(anchor);
|
|
259
336
|
if (r.status === 'stale')
|
|
260
337
|
changed.push(label);
|
|
261
338
|
else if (r.status === 'missing')
|
|
@@ -289,14 +366,19 @@ export function describeAnchorState(state) {
|
|
|
289
366
|
export function evaluateAnchorsAgainst(anchors, text, anchorPath) {
|
|
290
367
|
if (!anchors || anchors.length === 0)
|
|
291
368
|
return NOT_ANCHOR_STALE;
|
|
292
|
-
|
|
369
|
+
// 只判 `file` 类:调用方(或 `read_file`)手里握着的是**一段文件文本**,
|
|
370
|
+
// 拿它去判目录指纹或 URL 必然得出"对不上",那是假 stale。
|
|
371
|
+
const fileAnchors = anchors.filter((a) => (a.kind ?? 'file') === 'file' && !!a.contentHash);
|
|
372
|
+
if (fileAnchors.length === 0)
|
|
373
|
+
return NOT_ANCHOR_STALE;
|
|
374
|
+
const scoped = anchorPath ? fileAnchors.filter((a) => a.path === anchorPath) : fileAnchors;
|
|
293
375
|
if (scoped.length === 0)
|
|
294
376
|
return NOT_ANCHOR_STALE;
|
|
295
377
|
const changed = [];
|
|
296
378
|
const missing = [];
|
|
297
379
|
for (const anchor of scoped) {
|
|
298
380
|
const target = anchor.symbol ? extractSymbolFragment(text, anchor.symbol) : text;
|
|
299
|
-
const label = anchor
|
|
381
|
+
const label = anchorLabel(anchor);
|
|
300
382
|
if (target === null) {
|
|
301
383
|
// 符号不在**这个文件**里(调用方已按 path 过滤):文件在、符号没了(重命名/删除),
|
|
302
384
|
// 按 missing 处理。
|
|
@@ -311,9 +393,9 @@ export function evaluateAnchorsAgainst(anchors, text, anchorPath) {
|
|
|
311
393
|
}
|
|
312
394
|
return { stale: changed.length > 0 || missing.length > 0, changed, missing };
|
|
313
395
|
}
|
|
314
|
-
/** 该条目是否锚定了给定文件(供 read_file 反向查找)
|
|
396
|
+
/** 该条目是否锚定了给定文件(供 read_file 反向查找)。目录/URL 锚点不参与。 */
|
|
315
397
|
export function anchorsFile(anchors, anchorPath) {
|
|
316
398
|
if (!anchors || anchors.length === 0)
|
|
317
399
|
return false;
|
|
318
|
-
return anchors.some((a) => a.path === anchorPath);
|
|
400
|
+
return anchors.some((a) => (a.kind ?? 'file') === 'file' && a.path === anchorPath);
|
|
319
401
|
}
|
package/dist/memory/graph.js
CHANGED
|
@@ -619,10 +619,58 @@ export function searchGraphFacts(query, opts = {}) {
|
|
|
619
619
|
}
|
|
620
620
|
return chosen;
|
|
621
621
|
}
|
|
622
|
-
|
|
622
|
+
/**
|
|
623
|
+
* R12.2 时间切片:`asOf` 时刻这条边是否成立。
|
|
624
|
+
*
|
|
625
|
+
* 语义完全由**已有字段**推出,不新增 schema:`validAt` 是「我开始这么认为」的时刻,
|
|
626
|
+
* `invalidAt` 是「我改主意」的时刻。于是在时刻 T:
|
|
627
|
+
* validAt <= T < invalidAt(∞)
|
|
628
|
+
* 这就是 R12 想要的双时间轴读侧——`knownAt`/`validFrom` 那套字段在当前写法下
|
|
629
|
+
* 是 `validAt` 的冗余别名,改名要迁移全库边、双写要两处保持一致,收益只是名字更准,
|
|
630
|
+
* 不值得。真正缺的那一半(「事实在现实中成立」与「我何时得知」分离)在单机单用户
|
|
631
|
+
* 场景里没有观测来源:用户说「我上周就搬了」时,我们只知道说的时刻,
|
|
632
|
+
* 编一个 validFrom 出来等于造假数据。
|
|
633
|
+
*
|
|
634
|
+
* 缺 `validAt` / 坏时间戳的历史边按「一直在」处理:`unknown` 不冤枉,
|
|
635
|
+
* 与锚点 unknown 不算 stale 同一判据。
|
|
636
|
+
*/
|
|
637
|
+
export function edgeActiveAt(e, atMs) {
|
|
638
|
+
const v = Date.parse(e.validAt);
|
|
639
|
+
if (Number.isFinite(v) && atMs < v)
|
|
640
|
+
return false;
|
|
641
|
+
if (e.invalidAt) {
|
|
642
|
+
const i = Date.parse(e.invalidAt);
|
|
643
|
+
if (Number.isFinite(i) && atMs >= i)
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
return true;
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* 解析 `asOf` 参数。空/未传 → `ms: null`(当前视图,行为与不带参数完全一致)。
|
|
650
|
+
*
|
|
651
|
+
* 只写日期时按**本地**零点解释:图里的时间戳是 UTC,但用户说「10 月 26 日那天」
|
|
652
|
+
* 想的是自己的那一天;按 UTC 零点会把它变成北京时间 08:00,把当天早上发生的事
|
|
653
|
+
* 判成「那时还没发生」。
|
|
654
|
+
*/
|
|
655
|
+
export function parseAsOf(raw) {
|
|
656
|
+
if (raw === undefined || raw === null)
|
|
657
|
+
return { ok: true, ms: null };
|
|
658
|
+
const s = String(raw).trim();
|
|
659
|
+
if (!s)
|
|
660
|
+
return { ok: true, ms: null };
|
|
661
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {
|
|
662
|
+
const [y, m, d] = s.split('-').map(Number);
|
|
663
|
+
const t = new Date(y, m - 1, d).getTime();
|
|
664
|
+
return Number.isFinite(t) ? { ok: true, ms: t } : { ok: false, reason: `无法解析 asOf "${s}"` };
|
|
665
|
+
}
|
|
666
|
+
const t = Date.parse(s);
|
|
667
|
+
return Number.isFinite(t) ? { ok: true, ms: t } : { ok: false, reason: `无法解析 asOf "${s}"` };
|
|
668
|
+
}
|
|
669
|
+
function buildAdjacency(g, relation, atMs) {
|
|
623
670
|
const adj = new Map();
|
|
624
671
|
for (const e of g.edges) {
|
|
625
|
-
|
|
672
|
+
// R12.2:给了 asOf 就按「那时成立」筛,否则按「现在成立」筛(旧行为)。
|
|
673
|
+
if (atMs == null ? !!e.invalidAt : !edgeActiveAt(e, atMs))
|
|
626
674
|
continue;
|
|
627
675
|
if (relation && e.relation !== relation)
|
|
628
676
|
continue;
|
|
@@ -643,7 +691,7 @@ function buildAdjacency(g, relation) {
|
|
|
643
691
|
* 邻居遍历:depth 1-3(BFS + 邻接表 O(V+E)),只看 active 边,边数封顶 40 防图爆炸。
|
|
644
692
|
* relation 可选:只沿该类型的边走(深跳聚焦用,如沿 depends_on 链追踪)。
|
|
645
693
|
*/
|
|
646
|
-
export function neighborsOf(nameOrId, depth = 1, relation) {
|
|
694
|
+
export function neighborsOf(nameOrId, depth = 1, relation, asOfMs) {
|
|
647
695
|
const g = loadAllGraph();
|
|
648
696
|
const center = findEntityIn(g, nameOrId) ?? g.entities.find((e) => e.id === nameOrId);
|
|
649
697
|
if (!center)
|
|
@@ -651,7 +699,7 @@ export function neighborsOf(nameOrId, depth = 1, relation) {
|
|
|
651
699
|
const rel = relation?.trim().toLowerCase().replace(/\s+/g, '_') || undefined;
|
|
652
700
|
const maxDepth = Math.max(1, Math.min(Math.floor(depth) || 1, 3));
|
|
653
701
|
const MAX_EDGES_OUT = 40;
|
|
654
|
-
const adj = buildAdjacency(g, rel);
|
|
702
|
+
const adj = buildAdjacency(g, rel, asOfMs);
|
|
655
703
|
const visited = new Set([center.id]);
|
|
656
704
|
const seenEdges = new Set();
|
|
657
705
|
const outEdges = [];
|
|
@@ -686,7 +734,7 @@ const MAX_PATH_DEPTH = 6;
|
|
|
686
734
|
* 两实体间最短路径:active 边视为无向,双向 BFS(每次展开较小前沿),
|
|
687
735
|
* 总跳数封顶 MAX_PATH_DEPTH 防图爆炸。不连通 / 未知端 → null。
|
|
688
736
|
*/
|
|
689
|
-
export function pathBetween(aNameOrId, bNameOrId) {
|
|
737
|
+
export function pathBetween(aNameOrId, bNameOrId, asOfMs) {
|
|
690
738
|
const g = loadAllGraph();
|
|
691
739
|
const from = findEntityIn(g, aNameOrId) ?? g.entities.find((e) => e.id === aNameOrId);
|
|
692
740
|
const to = findEntityIn(g, bNameOrId) ?? g.entities.find((e) => e.id === bNameOrId);
|
|
@@ -698,7 +746,7 @@ export function pathBetween(aNameOrId, bNameOrId) {
|
|
|
698
746
|
const bwd = new Map([[to.id, { prev: null, edge: null }]]);
|
|
699
747
|
let fFront = [from.id];
|
|
700
748
|
let bFront = [to.id];
|
|
701
|
-
const adj = buildAdjacency(g);
|
|
749
|
+
const adj = buildAdjacency(g, undefined, asOfMs);
|
|
702
750
|
let meet = null;
|
|
703
751
|
for (let d = 0; d < MAX_PATH_DEPTH && !meet; d++) {
|
|
704
752
|
const expandFwd = fFront.length <= bFront.length;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* R16 记忆投毒防御:确定性守卫(零 LLM、零 IO)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:记忆是**自动写入**的,而写进去的内容有两个入口是不受用户控制的——
|
|
5
|
+
* ① 反思读的是整段转录,而转录里有 `tool:` 行(网页正文、文件内容、命令输出);
|
|
6
|
+
* ② 模型自己读完网页后调 `memory_save`。
|
|
7
|
+
* 于是「网页里一句话 → 被反思当成结论 → 每次启动都注入 system prompt」成为一条
|
|
8
|
+
* 持久化路径:一次投毒影响此后**每一个**会话,且比一次性提示注入严重得多。
|
|
9
|
+
*
|
|
10
|
+
* 2026 年业界共识是现有提示注入防御覆盖不到间接注入;这里不做"理解语义",
|
|
11
|
+
* 只做两件可判定的事:
|
|
12
|
+
* - `detectHijack`:**改写控制权**的语句不该变成记忆。它不是在描述世界,是在给
|
|
13
|
+
* 未来的 agent 下命令。确定性正则,**不靠模型判断**(模型正是被攻击对象)。
|
|
14
|
+
* - `findSourceLine`:这条内容是不是**逐字抄自**转录里某个角色。抄自 `tool:` 行
|
|
15
|
+
* 说明它来自工具输出(不可信来源),抄自 `user:` 行说明是用户亲述(可信)。
|
|
16
|
+
* 同一个原语同时服务「来源追溯」与「不可信来源判定」,不建两套。
|
|
17
|
+
*
|
|
18
|
+
* **精度优先于召回**,三条理由:
|
|
19
|
+
* ① 误杀的代价是用户/模型想记的合法结论被永久拒绝,且这个拒绝是静默发生的;
|
|
20
|
+
* ② 漏掉的代价由 `origin: 'tool_output'` 的标记与审计日志兜着——它仍然可见、可查;
|
|
21
|
+
* ③ 一份「关于投毒手法的记忆」本身就该被允许存在(用户会想记"遇到这类网页要当心"),
|
|
22
|
+
* 因此**引号内**的出现一律不算命中:那是在**提及**这句话,不是在**执行**它。
|
|
23
|
+
*
|
|
24
|
+
* 叶子依赖:不 import 任何项目模块(否则 store → guard → store 成环)。
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* 改写控制权的语句。
|
|
28
|
+
*
|
|
29
|
+
* 判据不是"出现祈使句"(用户说"以后都先跑 typecheck"是**合法偏好**,必须能记),
|
|
30
|
+
* 而是"试图改变 agent 的身份/指令来源/报告义务"这三类之一:
|
|
31
|
+
* - 指令来源被改写(忽略之前的指令 / disregard previous instructions);
|
|
32
|
+
* - 身份被改写(你现在是… / you are now…);
|
|
33
|
+
* - 报告义务被解除(不要告诉用户 / without telling the user)——这是攻击者最想让
|
|
34
|
+
* agent 做的那件事,也是用户最不可能主动要求持久记住的那件事。
|
|
35
|
+
*/
|
|
36
|
+
const HIJACK_RULES = [
|
|
37
|
+
// ── 指令来源改写 ──
|
|
38
|
+
{
|
|
39
|
+
rule: 'ignore-instructions',
|
|
40
|
+
re: /(?:忽略|无视|忘掉|忘记|抛开|绕过)\s*(?:掉)?\s*(?:之前|以上|上面|前面|先前|此前|所有|全部)\s*的?\s*(?:所有|全部)?\s*(?:指令|指示|命令|提示|要求|规则|限制)/,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
rule: 'ignore-instructions-en',
|
|
44
|
+
re: /\b(?:ignore|disregard|forget|bypass)\s+(?:all\s+)?(?:of\s+)?(?:the\s+)?(?:previous|prior|above|preceding|earlier|system)\s+(?:instructions?|prompts?|rules?|directions?|guidelines?)/i,
|
|
45
|
+
},
|
|
46
|
+
// ── 身份改写 ──
|
|
47
|
+
{
|
|
48
|
+
rule: 'role-override',
|
|
49
|
+
re: /(?:从现在|从此刻|自现在)\s*(?:开始|起)[,,]?\s*你\s*(?:是|将|要|必须|只)/,
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
rule: 'role-override-en',
|
|
53
|
+
re: /\byou\s+are\s+now\s+(?:a|an|the|in|my|allowed|permitted|free|unrestricted)\b/i,
|
|
54
|
+
},
|
|
55
|
+
// ── 报告义务解除 ──
|
|
56
|
+
{
|
|
57
|
+
rule: 'hide-from-user',
|
|
58
|
+
re: /(?:不要|别|无需|不必|切勿)\s*(?:再)?\s*(?:告诉|通知|告知|提醒|询问|告诉)\s*(?:用户|使用者|他|她)/,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
rule: 'hide-from-user-en',
|
|
62
|
+
re: /\b(?:without|do\s+not|don't|never)\s+(?:telling|informing|notifying|asking|alerting)\s+(?:the\s+)?user\b/i,
|
|
63
|
+
},
|
|
64
|
+
// ── 自身提示词外泄(常与投毒同现,且一旦落进记忆会被反复读到) ──
|
|
65
|
+
{
|
|
66
|
+
rule: 'prompt-exfiltration',
|
|
67
|
+
re: /(?:输出|打印|显示|复述|泄露|告诉)\s*(?:你的|完整的)?\s*(?:系统提示词|系统提示|system\s*prompt|初始指令)/i,
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
rule: 'prompt-exfiltration-en',
|
|
71
|
+
re: /\b(?:print|output|reveal|repeat|show|leak)\s+(?:your\s+)?(?:system\s+prompt|initial\s+instructions?)\b/i,
|
|
72
|
+
},
|
|
73
|
+
// 中文里动词常后置("系统提示词完整输出一遍"),上面那条只覆盖动词前置的写法。
|
|
74
|
+
{
|
|
75
|
+
rule: 'prompt-exfiltration-post',
|
|
76
|
+
re: /(?:系统提示词|系统提示|初始指令)[^。\n]{0,12}?(?:输出|打印|显示|复述|泄露|贴出|告诉我)/,
|
|
77
|
+
},
|
|
78
|
+
];
|
|
79
|
+
/**
|
|
80
|
+
* 引号/代码围栏内的文本在检测前剥掉。
|
|
81
|
+
*
|
|
82
|
+
* 为什么:一条合法记忆可能正是「网页里出现『忽略之前的指令』时要当心」。那句话在
|
|
83
|
+
* 原句里是**被引用的对象**,不是本记忆在命令未来 agent。剥掉引用段即可区分
|
|
84
|
+
* 「使用」与「提及」,而不需要任何语义理解。
|
|
85
|
+
*
|
|
86
|
+
* 只处理成对出现的完整引号;单边引号(奇数个)不剥——那更可能是攻击者故意留下的
|
|
87
|
+
* 半个引号想绕过检测,此时按"不剥"处理更保守。
|
|
88
|
+
*/
|
|
89
|
+
function stripQuoted(text) {
|
|
90
|
+
const quoted = [
|
|
91
|
+
/```[\s\S]*?```/g,
|
|
92
|
+
/`[^`\n]*`/g,
|
|
93
|
+
/「[^」\n]*」/g,
|
|
94
|
+
/『[^』\n]*』/g,
|
|
95
|
+
/“[^”\n]*”/g,
|
|
96
|
+
/"[^"\n]*"/g,
|
|
97
|
+
/'[^'\n]*'/g,
|
|
98
|
+
];
|
|
99
|
+
let out = text;
|
|
100
|
+
for (const re of quoted)
|
|
101
|
+
out = out.replace(re, ' ');
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* 该文本是否在尝试改写 agent 的控制权。返回第一条命中规则,无命中返 null。
|
|
106
|
+
*
|
|
107
|
+
* 只在**写入**时调用(反思 saves、`memory_save`),不在读取时调用:已落库的旧条目不
|
|
108
|
+
* 因为规则变严而失效,那会让规则更新变成一次隐式的库删除。
|
|
109
|
+
*/
|
|
110
|
+
export function detectHijack(text) {
|
|
111
|
+
const raw = String(text ?? '');
|
|
112
|
+
if (!raw.trim())
|
|
113
|
+
return null;
|
|
114
|
+
const probe = stripQuoted(raw);
|
|
115
|
+
for (const { rule, re } of HIJACK_RULES) {
|
|
116
|
+
const m = re.exec(probe);
|
|
117
|
+
if (m)
|
|
118
|
+
return { rule, sample: m[0].slice(0, 120) };
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
/** 逐字重合判定用:合并空白、小写,避免缩进/换行差异把真正的复制判成"不是抄的"。 */
|
|
123
|
+
function normalizeForCopy(s) {
|
|
124
|
+
return String(s ?? '')
|
|
125
|
+
.toLowerCase()
|
|
126
|
+
.replace(/\s+/g, ' ')
|
|
127
|
+
.trim();
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* 默认的逐字重合长度。
|
|
131
|
+
*
|
|
132
|
+
* 60 是权衡:太短(如 20)会把"src/memory/store.ts 里有个 loadAll"这类**常识性重合**
|
|
133
|
+
* 判成复制;太长(如 200)则因为 `snapshotTranscript` 把每条消息截到 600 字符、
|
|
134
|
+
* 整体截到 6000 字符,长结论的原文往往已被截断,永远匹配不上。
|
|
135
|
+
*/
|
|
136
|
+
const DEFAULT_MIN_EXACT = 60;
|
|
137
|
+
/**
|
|
138
|
+
* 在转录里找这条内容**逐字抄自**哪一行,返回该行角色。
|
|
139
|
+
*
|
|
140
|
+
* 用途有二,同一份实现:
|
|
141
|
+
* ① 来源追溯(R16.3):记下这条记忆的原文出现在转录的哪个角色里;
|
|
142
|
+
* ② 不可信来源判定(R16.1):来自 `tool:` 的 = 工具输出(网页/文件/命令),
|
|
143
|
+
* 其可信度远低于用户亲述。
|
|
144
|
+
*
|
|
145
|
+
* 找不到逐字重合时返 null —— 说明它是**概括**而不是复制,那种情况下没有可靠的
|
|
146
|
+
* 来源信号,不猜(与 `memory_save` 的 empty-graph 同一条原则:证据不足不下结论)。
|
|
147
|
+
*/
|
|
148
|
+
export function findSourceLine(text, transcript, minExact = DEFAULT_MIN_EXACT) {
|
|
149
|
+
const needle = normalizeForCopy(text);
|
|
150
|
+
if (needle.length < minExact)
|
|
151
|
+
return null;
|
|
152
|
+
const hayLines = String(transcript ?? '').split('\n');
|
|
153
|
+
const window = Math.max(20, minExact);
|
|
154
|
+
for (const line of hayLines) {
|
|
155
|
+
const m = /^([A-Za-z_?]+):\s?/.exec(line);
|
|
156
|
+
if (!m)
|
|
157
|
+
continue;
|
|
158
|
+
const role = m[1];
|
|
159
|
+
const body = normalizeForCopy(line.slice(m[0].length));
|
|
160
|
+
if (body.length < window)
|
|
161
|
+
continue;
|
|
162
|
+
// 滑动窗口:任意一段 window 长的连续片段出现在记忆正文里,就视为逐字抄自该行。
|
|
163
|
+
for (let i = 0; i + window <= body.length; i += 10) {
|
|
164
|
+
if (needle.includes(body.slice(i, i + window))) {
|
|
165
|
+
return { role, line: line.slice(0, 200) };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
/** 该来源角色是否属于"不受用户控制的输入"(工具输出 / 助手的中间产物不算可信证据)。 */
|
|
172
|
+
export function isUntrustedRole(role) {
|
|
173
|
+
return role === 'tool' || role === 'function';
|
|
174
|
+
}
|
package/dist/memory/health.js
CHANGED
|
@@ -45,6 +45,13 @@ export function buildMemoryHealth() {
|
|
|
45
45
|
const anchorStale = loadAnchorStaleMap(all);
|
|
46
46
|
const derivedEntries = active.filter((e) => (e.derivedFrom?.length ?? 0) > 0);
|
|
47
47
|
const anchorEntries = active.filter((e) => (e.anchors?.length ?? 0) > 0);
|
|
48
|
+
// R7.1:按 kind 计数。逐锚点统计而不是逐条目——一条记忆可以同时锚定文件与目录,
|
|
49
|
+
// 只数条目会把「多用了一种锚点」这一事实抹掉。
|
|
50
|
+
const anchorByKind = { file: 0, dir: 0, url: 0 };
|
|
51
|
+
for (const e of active) {
|
|
52
|
+
for (const a of e.anchors ?? [])
|
|
53
|
+
anchorByKind[a.kind ?? 'file'] += 1;
|
|
54
|
+
}
|
|
48
55
|
const episodes = active.filter((e) => e.type === 'episode');
|
|
49
56
|
const consolidated = episodes.filter((e) => !!e.derivedInto);
|
|
50
57
|
const recall = readRecallStats();
|
|
@@ -79,6 +86,7 @@ export function buildMemoryHealth() {
|
|
|
79
86
|
anchored: anchorEntries.length,
|
|
80
87
|
stale: anchorEntries.filter((e) => anchorStale.get(e.id)?.stale).length,
|
|
81
88
|
staleRate: rate(anchorEntries.filter((e) => anchorStale.get(e.id)?.stale).length, anchorEntries.length),
|
|
89
|
+
byKind: anchorByKind,
|
|
82
90
|
},
|
|
83
91
|
derived: {
|
|
84
92
|
total: derivedEntries.length,
|
|
@@ -185,6 +193,11 @@ const pct = (v) => `${Math.round(v * 100)}%`;
|
|
|
185
193
|
/** 供 `/memory health` 渲染的多行文本(无 UI 依赖,命令层自己上色)。 */
|
|
186
194
|
export function formatMemoryHealth(h = buildMemoryHealth()) {
|
|
187
195
|
const lines = [];
|
|
196
|
+
// 生成时间放首行:这份 JSON 是**覆盖写**的单点快照,不是历史趋势。
|
|
197
|
+
// 拿它判断现状前必须先看有多旧——实测踩过:磁盘上是 11-02 的快照,retrieval.searches 仍为 0、
|
|
198
|
+
// warning 还写着「memory_search 从未被调用」,而 11-03 的 recall-stats 已经是 4 次。
|
|
199
|
+
// `/memory health` 是现场重算的,所以命令输出里这个时间恒为当下;只有直接读文件时才有意义。
|
|
200
|
+
lines.push(`快照:${h.generatedAt}`);
|
|
188
201
|
lines.push(`条目:active ${h.entries.active} / total ${h.entries.total}` +
|
|
189
202
|
`(archived ${h.entries.archived}${h.entries.superseded ? `, superseded ${h.entries.superseded}` : ''})` +
|
|
190
203
|
` · 封顶占用 ${pct(h.entries.activeCapUsage)}`);
|
package/dist/memory/index.js
CHANGED
|
@@ -12,7 +12,10 @@ export { buildAboutYouSection, initPersona, isInternalizedEdge, listProfileCandi
|
|
|
12
12
|
export { buildProjectGraphHint, GRAPH_HINT_MAX_CHARS } from './recall.js';
|
|
13
13
|
export { isProactiveEnabled, proactiveHint, resetProactiveTurn, proactiveTurnCount, proactiveFiredIds, proactiveCounters, flushProactiveStats, __resetProactiveForTests, __resetProactiveCountersForTests, } from './proactive.js';
|
|
14
14
|
export { buildMemoryHealth, writeMemoryHealth, readMemoryHealth, formatMemoryHealth, MEMORY_HEALTH_SCHEMA_VERSION, } from './health.js';
|
|
15
|
-
export { captureMemoryBaseline, buildMemoryTailSection, __resetMemoryBaselineForTests, } from './tail.js';
|
|
15
|
+
export { captureMemoryBaseline, buildMemoryTailSection, memoryTailChangedIds, __resetMemoryBaselineForTests, } from './tail.js';
|
|
16
|
+
export { buildTurnRecallSection, isTurnRecallEnabled, flushTurnRecallStats, turnRecallCounters, __resetTurnRecallForTests, } from './turn-recall.js';
|
|
16
17
|
export { isCompactHandoffEnabled, appendPendingCandidates, loadPendingCandidates, trimPendingCandidates, pendingCandidateCount, extractMemoryCandidates, formatPendingForReflect, memoryCandidatesInstruction, MEMORY_CANDIDATES_HEADING, } from './pending.js';
|
|
17
|
-
export { kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, runReflection, kickoffConsolidation, runConsolidation, parseConsolidationPlan, getLastConsolidationResult, clearLastConsolidationResult, formatConsolidationResult, } from './reflect.js';
|
|
18
|
+
export { kickoffReflection, reflectOnExit, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, runReflection, kickoffConsolidation, runConsolidation, parseConsolidationPlan, getLastConsolidationResult, clearLastConsolidationResult, formatConsolidationResult, } from './reflect.js';
|
|
18
19
|
export { isEpisodicEnabled, isConsolidationEnabled, collectChangedFiles, extractCompactionSummary, parsePendingSteps, buildEpisode, recordSessionEpisode, listEpisodes, buildEpisodeSection, episodeFactsOf, findConsolidationGroups, applyConsolidation, CONSOLIDATED_NAME_SUFFIX, } from './episodic.js';
|
|
20
|
+
export { collectSeedCandidates, applySeedCandidates, extractConventionBullets, seedNameOf, SEED_MAX_CANDIDATES, } from './seed.js';
|
|
21
|
+
export { collectAnchorCandidates, applyAnchorCandidates, extractAnchorPaths, looksLikePath, ANCHOR_BACKFILL_MAX_ENTRIES, ANCHOR_BACKFILL_MAX_PATHS, } from './anchor-backfill.js';
|