mocode-ai 1.9.0 → 1.9.1
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 +19 -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 +4 -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/runtime.js +34 -7
- 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
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// turn-recall.ts —— 每轮静默召回(R18):按本轮用户问题把相关旧记忆送进 ephemeral 段。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:记忆有两条投递路径,此前都覆盖不到「这一轮问的这个话题」——
|
|
4
|
+
// ① 启动注入:buildMemoryIndexSection 只在 history[0] 出现一次,整场会话不刷新;
|
|
5
|
+
// ② R17 尾注:只播「本会话内新增/变更」的条目,回答的是"刚学了什么",不是"这轮该想起什么";
|
|
6
|
+
// ③ R3 前摄:只在**工具调用**那一刻按参数命中 trigger,而 40 条 active 里只有 13 条有 trigger。
|
|
7
|
+
// 于是用户问一个和旧记忆高度相关的问题时,模型只能靠自己去 memory_search —— 实测这条路
|
|
8
|
+
// 走不通(上线很久后 searches 仍是个位数)。这里补上第三条:问题进来就先静默取一次。
|
|
9
|
+
//
|
|
10
|
+
// 为什么走 ephemeral 尾部而不是重建 history[0]:重建 history[0] 会让整段对话的 KV 前缀
|
|
11
|
+
// 缓存每轮失效(每轮按全价重算 prompt)。附在末尾则前缀逐字节不变,与 sessionStateText /
|
|
12
|
+
// memoryTail 同一手法。
|
|
13
|
+
//
|
|
14
|
+
// 三条硬约束(全部为"宁少勿多"服务):
|
|
15
|
+
// - ≤3 条、单条 body ≤300 字符:真实库索引段已 6010 字符,每轮再灌正文会失控;
|
|
16
|
+
// - 走 R15.5 的「证据词元命中数 ≥2」下限:BM25 只要有一个 token 重合就返回,
|
|
17
|
+
// 没有下限时无关问题也会被"召回"一堆东西——那正是模型学会无视记忆的开始;
|
|
18
|
+
// - 不 bump recallCount:静默注入 ≠ 模型采用。而索引 policy 把 `recallCount>=1` 当作
|
|
19
|
+
// 「近期活跃」永久展示,静默注入过的条目会被永久钉在索引顶部,反而让「真的被主动
|
|
20
|
+
// 检索过」这个信号失去意义。计数另走 turnRecallCounters(只作观测)。
|
|
21
|
+
//
|
|
22
|
+
// 叶子依赖:只依赖 store(读)、text-search(纯函数)、anchor(读时判定)。
|
|
23
|
+
// 开关与排除集由调用方传入,本模块不读 config —— 与 store.ts / tail.ts 的既有约定一致。
|
|
24
|
+
import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { TextSearchIndex } from '../context/text-search.js';
|
|
27
|
+
import { MEMORY_SEARCH_MIN_EVIDENCE } from '../tools/constants.js';
|
|
28
|
+
import { evaluateAnchors } from './anchor.js';
|
|
29
|
+
import { loadAll } from './store.js';
|
|
30
|
+
/**
|
|
31
|
+
* 每轮静默召回开关。默认开启,可用 MOCODE_MEMORY_TURN_RECALL=0/false/off/no 关闭。
|
|
32
|
+
*
|
|
33
|
+
* 与 R3 的 MOCODE_MEMORY_PROACTIVE 各自独立:两者都是 push 通道,但判据完全不同
|
|
34
|
+
* (一个看本轮问题,一个看工具参数),用户可能只想留其中一条。
|
|
35
|
+
*/
|
|
36
|
+
export function isTurnRecallEnabled() {
|
|
37
|
+
const raw = process.env.MOCODE_MEMORY_TURN_RECALL;
|
|
38
|
+
if (raw === undefined)
|
|
39
|
+
return true;
|
|
40
|
+
return !['0', 'false', 'off', 'no'].includes(raw.trim().toLowerCase());
|
|
41
|
+
}
|
|
42
|
+
/** 每轮最多送几条。3 与 R17 尾注、R2.4 锚点回注同口径。 */
|
|
43
|
+
const MAX_TURN_RECALL = 3;
|
|
44
|
+
/** 单条 body 截断。只留「结论 + 一条理由」,砍掉长表格与代码块。 */
|
|
45
|
+
const MAX_RECALL_BODY_CHARS = 300;
|
|
46
|
+
/**
|
|
47
|
+
* 查询侧最短长度。低于此值不检索:短查询(「好」「改」)没有证据词元,
|
|
48
|
+
* 下限会退化成不过滤,把整库当结果返回。
|
|
49
|
+
*/
|
|
50
|
+
const MIN_QUERY_CHARS = 4;
|
|
51
|
+
/**
|
|
52
|
+
* 生成「可能与本轮相关」的记忆段。无命中 / 开关关闭 / 查询过短 → 空串(零注入)。
|
|
53
|
+
*
|
|
54
|
+
* 与 `searchEntries` 的关键差异:纯读。不改 recallCount,不写任何文件。
|
|
55
|
+
*/
|
|
56
|
+
export function buildTurnRecallSection(query, opts = {}) {
|
|
57
|
+
if (opts.enabled === false)
|
|
58
|
+
return '';
|
|
59
|
+
const q = (query ?? '').trim();
|
|
60
|
+
if (q.length < MIN_QUERY_CHARS)
|
|
61
|
+
return '';
|
|
62
|
+
const pool = loadAll().filter((e) => e.status === 'active' && e.type !== 'episode' && !(opts.excludeIds?.has(e.id) ?? false));
|
|
63
|
+
if (pool.length === 0)
|
|
64
|
+
return '';
|
|
65
|
+
// 计「检索过」而不是「命中过」:否则 turns === hits 恒成立,分母失去意义。
|
|
66
|
+
// 真正想知道的是"每轮召回到底有多少轮能拿东西",所以两者必须分开计。
|
|
67
|
+
countTurn();
|
|
68
|
+
// 字段权重必须与 store.ts:searchEntries 逐字一致(name 10 / id 8 / summary 5 / body 1)。
|
|
69
|
+
// 两处各写一份是刻意的:任何一方漂移都会让「静默召回」与「显式 memory_search」
|
|
70
|
+
// 排出不同顺序,而模型会以为其中一个是坏的。
|
|
71
|
+
const index = new TextSearchIndex(pool.map((e) => ({
|
|
72
|
+
id: e.id,
|
|
73
|
+
fields: [
|
|
74
|
+
{ text: e.name, weight: 10 },
|
|
75
|
+
{ text: e.id, weight: 8 },
|
|
76
|
+
{ text: e.summary, weight: 5 },
|
|
77
|
+
{ text: e.body, weight: 1 },
|
|
78
|
+
],
|
|
79
|
+
})), { minEvidenceMatched: MEMORY_SEARCH_MIN_EVIDENCE });
|
|
80
|
+
const byId = new Map(pool.map((e) => [e.id, e]));
|
|
81
|
+
const limit = Math.max(1, Math.min(opts.limit ?? MAX_TURN_RECALL, MAX_TURN_RECALL));
|
|
82
|
+
const hits = index
|
|
83
|
+
.search(q, limit)
|
|
84
|
+
.map((hit) => byId.get(hit.id))
|
|
85
|
+
.filter((e) => e !== undefined);
|
|
86
|
+
if (hits.length === 0)
|
|
87
|
+
return '';
|
|
88
|
+
countHits(hits.length);
|
|
89
|
+
const lines = hits.map(formatEntry);
|
|
90
|
+
return [
|
|
91
|
+
'## Possibly relevant memory (recalled for this turn)',
|
|
92
|
+
'Retrieved by keyword match against the current question, not by your own request — open the full body with memory_search(id) when you act on one. If an entry contradicts what the code now says, the code wins.',
|
|
93
|
+
...lines,
|
|
94
|
+
].join('\n');
|
|
95
|
+
}
|
|
96
|
+
/** 单条渲染。stale 打标沿用 R2/R14 的口径:两类失效对模型的要求不同。 */
|
|
97
|
+
function formatEntry(e) {
|
|
98
|
+
const tags = [];
|
|
99
|
+
if (e.pinned)
|
|
100
|
+
tags.push('pinned');
|
|
101
|
+
const anchorState = evaluateAnchors(e.anchors);
|
|
102
|
+
if (anchorState.stale)
|
|
103
|
+
tags.push('STALE-CODE');
|
|
104
|
+
const suffix = tags.length > 0 ? ` [${tags.join(', ')}]` : '';
|
|
105
|
+
const body = (e.body ?? '').replace(/\s+/g, ' ').trim();
|
|
106
|
+
const clipped = body.length > MAX_RECALL_BODY_CHARS ? `${body.slice(0, MAX_RECALL_BODY_CHARS)}…` : body;
|
|
107
|
+
const head = `- [${e.type}] ${e.id}: ${e.name} — ${e.summary}${suffix}`;
|
|
108
|
+
return clipped ? `${head}\n ${clipped}` : head;
|
|
109
|
+
}
|
|
110
|
+
const EMPTY_COUNTERS = { turns: 0, hits: 0, entries: 0, updatedAt: null };
|
|
111
|
+
let counters = null;
|
|
112
|
+
function countTurn() {
|
|
113
|
+
counters ??= { ...EMPTY_COUNTERS };
|
|
114
|
+
counters.turns += 1;
|
|
115
|
+
}
|
|
116
|
+
/** 与 countTurn 分开:同一轮不能既在"检索过"又在"命中过"里各加一次 turns。 */
|
|
117
|
+
function countHits(entryCount) {
|
|
118
|
+
counters ??= { ...EMPTY_COUNTERS };
|
|
119
|
+
counters.hits += 1;
|
|
120
|
+
counters.entries += entryCount;
|
|
121
|
+
}
|
|
122
|
+
/** 只读快照(供 /memory health 展示)。 */
|
|
123
|
+
export function turnRecallCounters() {
|
|
124
|
+
return { ...(counters ?? EMPTY_COUNTERS) };
|
|
125
|
+
}
|
|
126
|
+
function statsPath() {
|
|
127
|
+
return path.join(process.cwd(), '.mocode', 'memory-turn-recall-stats.json');
|
|
128
|
+
}
|
|
129
|
+
/** 落盘。与 flushProactiveStats 同一时机调用;失败静默。 */
|
|
130
|
+
export function flushTurnRecallStats() {
|
|
131
|
+
if (!counters)
|
|
132
|
+
return; // 从未检索过 → 无新数据,零 IO
|
|
133
|
+
const snapshot = { ...counters, updatedAt: new Date().toISOString() };
|
|
134
|
+
try {
|
|
135
|
+
const p = statsPath();
|
|
136
|
+
mkdirSync(path.dirname(p), { recursive: true });
|
|
137
|
+
const tmp = p + '.tmp';
|
|
138
|
+
writeFileSync(tmp, JSON.stringify(snapshot, null, 2), 'utf8');
|
|
139
|
+
renameSync(tmp, p);
|
|
140
|
+
counters = snapshot;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
// 静默:埋点不可写不影响功能
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** 仅供测试:清掉内存计数,避免共享进程里上一个用例的数字串味。 */
|
|
147
|
+
export function __resetTurnRecallForTests() {
|
|
148
|
+
counters = null;
|
|
149
|
+
}
|
|
@@ -12,8 +12,12 @@ import { isMemoryEnabled } from '../../config/index.js';
|
|
|
12
12
|
import { getAgentMode } from '../../agent/mode.js';
|
|
13
13
|
import { kickoffReflection, snapshotTranscript, loadAll, loadAllGraph, loadStalenessMap, listInternalizedProfile, listProfileCandidates, promoteEdge, invalidateEdge, writeMemoryHealth, formatMemoryHealth, flushProactiveStats,
|
|
14
14
|
// R8 用户主权面
|
|
15
|
-
purgeEntries, buildPack, writePack, importPackFile, memoryWriteBlockedMessage, setMemoryWritesPaused, isMemoryWritesPaused, appendAudit,
|
|
16
|
-
|
|
15
|
+
purgeEntries, buildPack, writePack, importPackFile, memoryWriteBlockedMessage, setMemoryWritesPaused, isMemoryWritesPaused, appendAudit, readAudit,
|
|
16
|
+
// R9.1 冷启动播种
|
|
17
|
+
collectSeedCandidates, applySeedCandidates,
|
|
18
|
+
// R2.6 存量锚点回填
|
|
19
|
+
collectAnchorCandidates, applyAnchorCandidates, } from '../../memory/index.js';
|
|
20
|
+
import { evaluateAnchors, evaluateAnchor, anchorLabel } from '../../memory/anchor.js';
|
|
17
21
|
import { unhandled, next } from './types.js';
|
|
18
22
|
/** /profile 改动画像后,让 About you 段(history[0])立刻反映,不用等重启。 */
|
|
19
23
|
function refreshSystemPrompt(ctx) {
|
|
@@ -61,7 +65,14 @@ function renderProfile() {
|
|
|
61
65
|
* 编一个出来比不显示更糟;要看得更细用 `/memory show <id>` 看图谱边的 prov/confidence。
|
|
62
66
|
*/
|
|
63
67
|
export function sourceMark(e) {
|
|
64
|
-
|
|
68
|
+
// R16.1:工具输出衍生的条目必须与“模型亲述”区分开——它可能是从网页里逐字抄来的一段话。
|
|
69
|
+
// 不把两类混成一个标记:用户判断“要不要信这条”时,二手转述本来就该多一层怀疑。
|
|
70
|
+
//
|
|
71
|
+
// R9.1:`source.file` 是第三种来源——来自用户自己维护的文档(AGENTS.md/草稿),
|
|
72
|
+
// 既不是模型判断、也不是反思推断。它单独一个标记,因为"我写的"与"它想的"
|
|
73
|
+
// 在可信度上正好相反:文档是用户的主权声明,反思是模型的猜测。
|
|
74
|
+
const base = e.source?.file ? '[seed]' : e.source?.session ? '[reflection]' : '[tool]';
|
|
75
|
+
return e.origin === 'tool_output' ? `${base} [UNVERIFIED-ORIGIN]` : base;
|
|
65
76
|
}
|
|
66
77
|
/** `/memory show <id>`:一条记忆的全部出处。导出仅供测试断言渲染结果。 */
|
|
67
78
|
export function renderEntryDetail(e) {
|
|
@@ -78,6 +89,13 @@ export function renderEntryDetail(e) {
|
|
|
78
89
|
kv('来源', e.source?.session
|
|
79
90
|
? `后台产生(反思/情节),会话 ${e.source.session.slice(0, 8)}${e.source.turn !== undefined ? ` 第 ${e.source.turn} 轮` : ''}`
|
|
80
91
|
: '会话内工具写入(memory_save)');
|
|
92
|
+
// R16.1:来源可信度单独一行,不与上面的“谁写的”混在一起——
|
|
93
|
+
// “反思写的”与“反思从网页上抄的”是两件完全不同的事。
|
|
94
|
+
if (e.origin === 'tool_output') {
|
|
95
|
+
kv('来源可信度', '工具输出衍生(内容逐字来自网页/文件/命令输出,未经用户确认)');
|
|
96
|
+
}
|
|
97
|
+
if (e.firstSeen)
|
|
98
|
+
kv('首次出现', e.firstSeen);
|
|
81
99
|
if (e.lastUpdateReason)
|
|
82
100
|
kv('最近变更', e.lastUpdateReason);
|
|
83
101
|
if (e.trigger)
|
|
@@ -106,7 +124,7 @@ export function renderEntryDetail(e) {
|
|
|
106
124
|
lines.push(`${ui.dim} 代码锚点(${e.anchors.length}):${st.stale ? `已变动 ${st.changed.length}/缺失 ${st.missing.length}` : '全部 fresh'}${ui.reset}`);
|
|
107
125
|
for (const a of e.anchors) {
|
|
108
126
|
const r = evaluateAnchor(a);
|
|
109
|
-
const label = a
|
|
127
|
+
const label = anchorLabel(a);
|
|
110
128
|
const flag = r.status === 'fresh' ? '' : ` ${ui.dim}[${r.status}${r.detail ? `: ${r.detail}` : ''}]${ui.reset}`;
|
|
111
129
|
lines.push(` ${ui.dim}${label}${ui.reset}${flag}`);
|
|
112
130
|
}
|
|
@@ -116,6 +134,43 @@ export function renderEntryDetail(e) {
|
|
|
116
134
|
lines.push(`${ui.dim}${e.body}${ui.reset}`);
|
|
117
135
|
return lines.join('\n') + '\n';
|
|
118
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* R16.4 来源链:该 id 相关的审计轨迹(写入/被拒/被遗忘/被导出)。
|
|
139
|
+
*
|
|
140
|
+
* 为什么按 id **过滤审计文件**而不是给条目加一个"历史版本"字段:审计是 append-only
|
|
141
|
+
* 的事件流,条目是当前状态。把历史塞进条目会让每次写入都重写正文,而审计行天然
|
|
142
|
+
* 可跨进程、可被 `--match` 批量操作一起记录——两者的生命周期根本不同。
|
|
143
|
+
*
|
|
144
|
+
* 被拒记录(`action: 'refuse'`)不挂 id(内容压根没进库),所以额外按名字前缀匹配
|
|
145
|
+
* `detail`:用户查一条"是不是曾经想写但被拦过"时,那是最有用的线索。
|
|
146
|
+
*/
|
|
147
|
+
export function renderAuditTrail(id, records, nameHint) {
|
|
148
|
+
const lines = [];
|
|
149
|
+
const related = records.filter((r) => {
|
|
150
|
+
if (r.ids?.some((x) => x === id))
|
|
151
|
+
return true;
|
|
152
|
+
if (r.action !== 'refuse')
|
|
153
|
+
return false;
|
|
154
|
+
// 被拒记录没有 id(内容压根没进库),只能按 detail 里的名字/被查串匹配。
|
|
155
|
+
if (r.detail.includes(id))
|
|
156
|
+
return true;
|
|
157
|
+
return !!nameHint && r.detail.includes(nameHint.slice(0, 60));
|
|
158
|
+
});
|
|
159
|
+
lines.push(`${ui.accent}来源链${ui.reset} ${ui.dim}(${related.length} 条审计记录)${ui.reset}`);
|
|
160
|
+
if (related.length === 0) {
|
|
161
|
+
lines.push(`${ui.dim} (无:该条目没有写入/拒绝/遗忘轨迹。审计从 R8 起才有记录,更早的条目自然为空)${ui.reset}`);
|
|
162
|
+
return lines.join('\n');
|
|
163
|
+
}
|
|
164
|
+
for (const r of related.slice(-12)) {
|
|
165
|
+
const mark = r.action === 'refuse' ? `${ui.yellow}拒绝` : r.action === 'write' ? `${ui.accent}写入` : r.action;
|
|
166
|
+
lines.push(` ${ui.dim}${r.at}${ui.reset} ${mark}${ui.reset} ${ui.dim}${r.detail}${ui.reset}`);
|
|
167
|
+
if (r.reason)
|
|
168
|
+
lines.push(` ${ui.dim}原因: ${r.reason}${ui.reset}`);
|
|
169
|
+
if (r.snippet)
|
|
170
|
+
lines.push(` ${ui.dim}证据: ${r.snippet}${ui.reset}`);
|
|
171
|
+
}
|
|
172
|
+
return lines.join('\n');
|
|
173
|
+
}
|
|
119
174
|
/** 解析 `/memory forget` 的参数。返回 null 表示使用错误(调用方打用法)。 */
|
|
120
175
|
function parseForgetArgs(rest) {
|
|
121
176
|
const toks = rest.split(/\s+/).filter(Boolean);
|
|
@@ -153,6 +208,22 @@ function parseForgetArgs(rest) {
|
|
|
153
208
|
return out;
|
|
154
209
|
}
|
|
155
210
|
const FORGET_USAGE = '用法:/memory forget --all | --match <关键词> | --since <YYYY-MM-DD> [--scope global|project] [--dry-run]';
|
|
211
|
+
/**
|
|
212
|
+
* 解析 `/memory seed 1,3,5` 的序号列表。
|
|
213
|
+
*
|
|
214
|
+
* 容忍中文逗号、空格分隔与重复(`1, 1, 3` → `[1,3]`)——用户从列表里抄序号时
|
|
215
|
+
* 这些写法都会出现,为格式差异报错纯属给用户添堵。非法输入返回空数组,调用方打用法。
|
|
216
|
+
*/
|
|
217
|
+
export function parseSeedPicks(raw) {
|
|
218
|
+
const out = new Set();
|
|
219
|
+
for (const tok of raw.split(/[,,\s]+/).filter(Boolean)) {
|
|
220
|
+
const n = Number(tok);
|
|
221
|
+
if (!Number.isInteger(n) || n < 1)
|
|
222
|
+
return [];
|
|
223
|
+
out.add(n);
|
|
224
|
+
}
|
|
225
|
+
return [...out].sort((a, b) => a - b);
|
|
226
|
+
}
|
|
156
227
|
export const memoryCommands = [
|
|
157
228
|
(ctx) => {
|
|
158
229
|
if (ctx.line !== '/memory')
|
|
@@ -287,6 +358,26 @@ export const memoryCommands = [
|
|
|
287
358
|
layout.contentWrite(renderEntryDetail(hit) + '\n');
|
|
288
359
|
return next();
|
|
289
360
|
},
|
|
361
|
+
// ── R16.4 来源链 ────────────────────────────────────────────────────────
|
|
362
|
+
(ctx) => {
|
|
363
|
+
if (!ctx.line.startsWith('/memory audit'))
|
|
364
|
+
return unhandled();
|
|
365
|
+
const id = ctx.line.slice('/memory audit'.length).trim();
|
|
366
|
+
if (!id) {
|
|
367
|
+
layout.contentWrite(`${ui.dim}用法:/memory audit <id>(条目详情 + 写入/拒绝轨迹)${ui.reset}\n`);
|
|
368
|
+
return next();
|
|
369
|
+
}
|
|
370
|
+
// 允许前缀,同 /memory show:概览里的 id 很长,用户常只记得前几个字符。
|
|
371
|
+
const all = loadAll();
|
|
372
|
+
const hit = all.find((e) => e.id === id) ?? all.find((e) => e.id.startsWith(id));
|
|
373
|
+
if (hit)
|
|
374
|
+
layout.contentWrite(renderEntryDetail(hit) + '\n');
|
|
375
|
+
else
|
|
376
|
+
layout.contentWrite(`${ui.dim}(找不到记忆 [${id}];下面只显示审计轨迹)${ui.reset}\n`);
|
|
377
|
+
layout.contentWrite(renderAuditTrail(hit?.id ?? id, readAudit(300)) + '\n');
|
|
378
|
+
layout.contentWrite(`${ui.dim}(审计文件 .mocode/memory-audit.jsonl · 只记动作与 id,不存正文)${ui.reset}\n`);
|
|
379
|
+
return next();
|
|
380
|
+
},
|
|
290
381
|
// ── R8.3 暂停写入 ──────────────────────────────────────────────────────
|
|
291
382
|
(ctx) => {
|
|
292
383
|
if (ctx.line !== '/memory pause' && !ctx.line.startsWith('/memory pause '))
|
|
@@ -345,6 +436,128 @@ export const memoryCommands = [
|
|
|
345
436
|
`图谱 +${r.addedEntities} 实体/+${r.addedEdges} 边)${ui.reset}\n`);
|
|
346
437
|
return next();
|
|
347
438
|
},
|
|
439
|
+
// ── R9.1 冷启动播种 ────────────────────────────────────────────────────
|
|
440
|
+
(ctx) => {
|
|
441
|
+
if (ctx.line !== '/memory seed' && !ctx.line.startsWith('/memory seed '))
|
|
442
|
+
return unhandled();
|
|
443
|
+
if (!isMemoryEnabled()) {
|
|
444
|
+
layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory seed 无效。用 /memory_switch 打开)${ui.reset}\n`);
|
|
445
|
+
return next();
|
|
446
|
+
}
|
|
447
|
+
const arg = ctx.line.slice('/memory seed'.length).trim();
|
|
448
|
+
// 每次都重新扫:AGENTS.md 可能在上一轮被 /init 改写过,缓存反而制造"列表过期"的怪象。
|
|
449
|
+
const scan = collectSeedCandidates(ctx.banner().cwd);
|
|
450
|
+
// 无参数 = 只看不写。先让用户核对自己写了什么,再决定记哪些。
|
|
451
|
+
if (!arg) {
|
|
452
|
+
if (scan.files.length === 0) {
|
|
453
|
+
layout.contentWrite(`${ui.dim}(工作区里没有 AGENTS.md / CLAUDE.md / .mocode/agents-draft.md,无可播种内容)${ui.reset}\n`);
|
|
454
|
+
return next();
|
|
455
|
+
}
|
|
456
|
+
if (scan.candidates.length === 0) {
|
|
457
|
+
layout.contentWrite(`${ui.dim}(读了 ${scan.files.join('、')},但没找到「约定」段的 bullet;` +
|
|
458
|
+
`只抽 ## 约定 / ## Conventions 下的条目,或首个二级标题之前的 bullet)${ui.reset}\n`);
|
|
459
|
+
return next();
|
|
460
|
+
}
|
|
461
|
+
layout.contentWrite(`${ui.accent}可从已有文档播种 ${scan.candidates.length} 条约定${ui.reset}` +
|
|
462
|
+
`${ui.dim}(来源:${scan.files.join('、')})${ui.reset}\n`);
|
|
463
|
+
for (const [i, c] of scan.candidates.entries()) {
|
|
464
|
+
layout.contentWrite(` ${ui.accent}${i + 1}${ui.reset} ${ui.dim}${c.name}${ui.reset}\n`);
|
|
465
|
+
layout.contentWrite(` ${ui.dim}${c.summary}${ui.reset}\n`);
|
|
466
|
+
}
|
|
467
|
+
if (scan.truncated > 0) {
|
|
468
|
+
layout.contentWrite(` ${ui.dim}… 另有 ${scan.truncated} 条超出上限未列出${ui.reset}\n`);
|
|
469
|
+
}
|
|
470
|
+
layout.contentWrite(`${ui.dim}/memory seed <序号>[,<序号>…] 写入选中的 · /memory seed all 全部写入(${ui.reset}` +
|
|
471
|
+
`${ui.dim}只提议不自动写:这些是项目的约定,不是你的偏好)${ui.reset}\n`);
|
|
472
|
+
return next();
|
|
473
|
+
}
|
|
474
|
+
// 写入:解析 `all` 或逗号分隔的序号。
|
|
475
|
+
const picks = arg === 'all' ? 'all' : parseSeedPicks(arg);
|
|
476
|
+
if (picks !== 'all' && picks.length === 0) {
|
|
477
|
+
layout.contentWrite(`${ui.dim}用法:/memory seed · /memory seed all · /memory seed 1,3,5${ui.reset}\n`);
|
|
478
|
+
return next();
|
|
479
|
+
}
|
|
480
|
+
if (scan.candidates.length === 0) {
|
|
481
|
+
layout.contentWrite(`${ui.dim}(没有可播种的约定;先跑 /memory seed 看列表)${ui.reset}\n`);
|
|
482
|
+
return next();
|
|
483
|
+
}
|
|
484
|
+
if (picks !== 'all') {
|
|
485
|
+
const outOfRange = picks.filter((n) => n > scan.candidates.length);
|
|
486
|
+
if (outOfRange.length > 0) {
|
|
487
|
+
layout.contentWrite(`${ui.dim}(序号 ${outOfRange.join(',')} 超出范围:只有 ${scan.candidates.length} 条;先跑 /memory seed 看列表)${ui.reset}\n`);
|
|
488
|
+
return next();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const r = applySeedCandidates(scan.candidates, picks);
|
|
492
|
+
if (r.saved.length > 0)
|
|
493
|
+
refreshSystemPrompt(ctx); // 新条目要进索引,下一轮就该看得见
|
|
494
|
+
layout.contentWrite(`${ui.dim}(播种完成:新增 ${r.saved.length} · 已存在 ${r.existed.length} · 拒绝 ${r.refused.length})${ui.reset}\n`);
|
|
495
|
+
for (const s of r.saved)
|
|
496
|
+
layout.contentWrite(` ${ui.dim}+ [${s.id}] ${s.name}${ui.reset}\n`);
|
|
497
|
+
// 已存在不逐条列:那是「本来就记过了」,安静跳过比刷一屏更有用。
|
|
498
|
+
for (const f of r.refused) {
|
|
499
|
+
layout.contentWrite(` ${ui.yellow}! ${f.name}${ui.reset}${ui.dim}(命中守卫 ${f.rule},未写入)${ui.reset}\n`);
|
|
500
|
+
}
|
|
501
|
+
return next();
|
|
502
|
+
},
|
|
503
|
+
// ── R2.6 存量锚点回填(只提议不自动写)──────────────────────────────────
|
|
504
|
+
(ctx) => {
|
|
505
|
+
if (ctx.line !== '/memory anchor' && !ctx.line.startsWith('/memory anchor '))
|
|
506
|
+
return unhandled();
|
|
507
|
+
if (!isMemoryEnabled()) {
|
|
508
|
+
layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory anchor 无效。用 /memory_switch 打开)${ui.reset}\n`);
|
|
509
|
+
return next();
|
|
510
|
+
}
|
|
511
|
+
const arg = ctx.line.slice('/memory anchor'.length).trim();
|
|
512
|
+
const cwd = ctx.banner().cwd;
|
|
513
|
+
// 每次重扫:两次命令之间可能刚改过文件,列表必须反映此刻的磁盘。
|
|
514
|
+
const scan = collectAnchorCandidates(cwd);
|
|
515
|
+
if (!arg) {
|
|
516
|
+
if (scan.candidates.length === 0) {
|
|
517
|
+
layout.contentWrite(`${ui.dim}(没有可回填的条目:${scan.alreadyAnchored} 条已有锚点,` +
|
|
518
|
+
`${scan.noPath} 条 body 里没有可解析的工作区路径)${ui.reset}\n`);
|
|
519
|
+
return next();
|
|
520
|
+
}
|
|
521
|
+
layout.contentWrite(`${ui.accent}可为 ${scan.candidates.length} 条记忆回填代码锚点${ui.reset}` +
|
|
522
|
+
`${ui.dim}(已有锚点 ${scan.alreadyAnchored} 条已跳过;路径取自条目正文,且此刻文件存在)${ui.reset}\n`);
|
|
523
|
+
for (const c of scan.candidates) {
|
|
524
|
+
layout.contentWrite(` ${ui.accent}${c.index}${ui.reset} ${ui.dim}${c.id}${ui.reset}\n`);
|
|
525
|
+
layout.contentWrite(` ${ui.dim}${c.paths.join(' ')}${ui.reset}\n`);
|
|
526
|
+
}
|
|
527
|
+
if (scan.truncated > 0) {
|
|
528
|
+
layout.contentWrite(` ${ui.dim}… 另有 ${scan.truncated} 条超出上限未列出${ui.reset}\n`);
|
|
529
|
+
}
|
|
530
|
+
layout.contentWrite(`${ui.dim}/memory anchor <序号>[,<序号>…] 写入选中的 · /memory anchor all 全部写入(${ui.reset}` +
|
|
531
|
+
`${ui.dim}锚点写入后,代码一改就会在这些条目上显示 STALE-CODE)${ui.reset}\n`);
|
|
532
|
+
return next();
|
|
533
|
+
}
|
|
534
|
+
const picks = arg === 'all' ? 'all' : parseSeedPicks(arg);
|
|
535
|
+
if (picks !== 'all' && picks.length === 0) {
|
|
536
|
+
layout.contentWrite(`${ui.dim}用法:/memory anchor · /memory anchor all · /memory anchor 1,3,5${ui.reset}\n`);
|
|
537
|
+
return next();
|
|
538
|
+
}
|
|
539
|
+
if (scan.candidates.length === 0) {
|
|
540
|
+
layout.contentWrite(`${ui.dim}(没有可回填的条目;先跑 /memory anchor 看列表)${ui.reset}\n`);
|
|
541
|
+
return next();
|
|
542
|
+
}
|
|
543
|
+
if (picks !== 'all') {
|
|
544
|
+
const outOfRange = picks.filter((n) => !scan.candidates.some((c) => c.index === n));
|
|
545
|
+
if (outOfRange.length > 0) {
|
|
546
|
+
layout.contentWrite(`${ui.dim}(序号 ${outOfRange.join(',')} 超出范围:只有 ${scan.candidates.length} 条;先跑 /memory anchor 看列表)${ui.reset}\n`);
|
|
547
|
+
return next();
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const r = applyAnchorCandidates(scan.candidates, picks, cwd);
|
|
551
|
+
layout.contentWrite(`${ui.dim}(回填完成:写入 ${r.saved.length} · 条目已消失 ${r.missing.length} · 路径已失效 ${r.lost.length})${ui.reset}\n`);
|
|
552
|
+
for (const s of r.saved) {
|
|
553
|
+
layout.contentWrite(` ${ui.dim}+ ${s.id} ${s.paths.join(' ')}${ui.reset}\n`);
|
|
554
|
+
}
|
|
555
|
+
// 路径在两次扫描之间消失:必须说出来,否则用户以为"选中的都写好了"。
|
|
556
|
+
for (const l of r.lost) {
|
|
557
|
+
layout.contentWrite(` ${ui.yellow}! ${l.id}${ui.reset}${ui.dim}(正文提到的路径已不存在:${l.paths.join(', ')};未写入)${ui.reset}\n`);
|
|
558
|
+
}
|
|
559
|
+
return next();
|
|
560
|
+
},
|
|
348
561
|
// ── R8.2 批量遗忘 ──────────────────────────────────────────────────────
|
|
349
562
|
(ctx) => {
|
|
350
563
|
if (!ctx.line.startsWith('/memory forget'))
|
package/dist/repl/runtime.js
CHANGED
|
@@ -26,7 +26,7 @@ import { modelSupportsVision } from '../llm/capabilities.js';
|
|
|
26
26
|
import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index.js';
|
|
27
27
|
import { effectiveSystemPrompt, skillsChangedSinceLastObserve } from '../skills/index.js';
|
|
28
28
|
import { clearSkillActivation } from '../skills/activation.js';
|
|
29
|
-
import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, buildEpisodeSection, initPersona, gcMemories, kickoffReflection, kickoffConsolidation,
|
|
29
|
+
import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, buildEpisodeSection, initPersona, gcMemories, kickoffReflection, kickoffConsolidation, reflectOnExit, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, flushTurnRecallStats, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSection, loadAll, } from '../memory/index.js';
|
|
30
30
|
import { finalizeCurrentEpisode } from './episode-finalize.js';
|
|
31
31
|
import { collectQueryHistory } from '../session/query-history.js';
|
|
32
32
|
import { ToolPolicyController } from '../tools/policy.js';
|
|
@@ -408,6 +408,19 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
|
|
|
408
408
|
if (!history.some((m) => m.role === 'user')) {
|
|
409
409
|
layout.writeWelcomeBlock(welcomeLines());
|
|
410
410
|
}
|
|
411
|
+
// R9.4 空库提示:记忆开着但一条 active 都没有 → 说清「怎么让它有」,而不是让用户
|
|
412
|
+
// 对着空库空转。只在启动时提示一次(不是每轮),且不给 UI 常驻噪音:
|
|
413
|
+
// 「零感知」路线要求的是**行为**里有记忆,不是界面上反复提醒记忆的存在。
|
|
414
|
+
if (isMemoryEnabled()) {
|
|
415
|
+
try {
|
|
416
|
+
const hasActive = loadAll().some((e) => e.status === 'active');
|
|
417
|
+
if (!hasActive)
|
|
418
|
+
layout.contentWrite(`${ui.dim} ${t('memory.emptyHint')}${ui.reset}\n`);
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
// 读库失败不阻塞启动(与 gcMemories 同口径)
|
|
422
|
+
}
|
|
423
|
+
}
|
|
411
424
|
// 启动时限频自动 GC(24h 闸门,归档+purge 全做):fire-and-forget,
|
|
412
425
|
// 不阻塞进入主循环;runRetention 内部归档本地秒完、reflection 后台跑。可用 MOCODE_AUTO_GC=false 关闭。
|
|
413
426
|
void runtime.session.autoGc().catch(() => undefined);
|
|
@@ -674,6 +687,8 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
|
|
|
674
687
|
// 与召回计数一起在轮末落一次。健康快照仍只由 /memory health 与退出路径写,
|
|
675
688
|
// 因为它要读全库 + 算 stale,不该每轮付这个成本。
|
|
676
689
|
flushProactiveStats();
|
|
690
|
+
// R18:每轮静默召回的计数同样在内存累计,轮末落一次。
|
|
691
|
+
flushTurnRecallStats();
|
|
677
692
|
turnCount++;
|
|
678
693
|
if (turnCount % config.reflectEveryN === 0) {
|
|
679
694
|
kickoffReflection(snapshotTranscript(history, 20));
|
|
@@ -834,6 +849,11 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
|
|
|
834
849
|
commands: buildSlashCommands(),
|
|
835
850
|
onCycleMode: cycleMode,
|
|
836
851
|
onPasteImage: pasteImageFromClipboard,
|
|
852
|
+
hasPendingAttachments: () => pendingAttachments.length > 0,
|
|
853
|
+
clearPendingAttachments: () => {
|
|
854
|
+
pendingAttachments = [];
|
|
855
|
+
syncPendingAttachChips();
|
|
856
|
+
},
|
|
837
857
|
// Ctrl+R / Ctrl+P 历史搜索候选源:惰性工厂——当前会话内存 queryHistory + 最近落盘会话,
|
|
838
858
|
// 聚合要读盘,只有面板真正打开(Ctrl+R/P)才求值,平常轮次零开销
|
|
839
859
|
history: () => collectQueryHistory(queryHistory).map((e) => e.text),
|
|
@@ -1035,16 +1055,23 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
|
|
|
1035
1055
|
}
|
|
1036
1056
|
}
|
|
1037
1057
|
}
|
|
1038
|
-
// R6.1:退出前落情节(纯本地、零 LLM
|
|
1058
|
+
// R6.1:退出前落情节(纯本地、零 LLM,毫秒级;放在反思之前——反思能从本轮情节里
|
|
1059
|
+
// 读到「这个会话干了什么」,顺序反了就少一段素材)。
|
|
1039
1060
|
finalizeCurrentEpisode(currentSessionId, history, queryHistory);
|
|
1040
1061
|
// R4.1:退出时写一份健康快照。放这里而不是每轮:它要读全库 + 算 stale,
|
|
1041
|
-
//
|
|
1062
|
+
// 每轮付这个成本不值当。
|
|
1063
|
+
// 注意:healthPath() 是**固定路径**(.mocode/memory-health.json),每次都是覆盖写,
|
|
1064
|
+
// 所以磁盘上只有「最后一次生成」的那份,不构成历史趋势线。想留存历史需自行按时间戳
|
|
1065
|
+
// 复制出去。快照只在退出与 /memory health 时生成,而 /memory health 是现场重算的,
|
|
1066
|
+
// 因此读这个文件判断现状前先看它的 generatedAt。
|
|
1067
|
+
// 退出兜底反思:短会话(1–2 轮)永远到不了 cadence,退出是唯一能确保发生的边界。
|
|
1068
|
+
// reflectOnExit 内部已含 drain(等在飞收尾),所以不必再单独调 drainMemoryBackground。
|
|
1069
|
+
// 放在写健康快照**之前**:这样快照能看到本轮新增的条目与计数,不会留下"刚反思完、
|
|
1070
|
+
// 快照却还是旧数字"的错位。
|
|
1071
|
+
await reflectOnExit(snapshotTranscript(history, 20));
|
|
1042
1072
|
flushProactiveStats();
|
|
1073
|
+
flushTurnRecallStats();
|
|
1043
1074
|
writeMemoryHealth(isMemoryEnabled());
|
|
1044
|
-
// 退出前等在飞反思收尾。注意:Ctrl+C 在 TUI(raw 模式)下是按键不是 SIGINT,空输入框时
|
|
1045
|
-
// 由主循环 catch { break } 接住,因此**会**走到这里等反思跑完;只有非 raw 模式下的
|
|
1046
|
-
// 进程级 SIGINT → process.exit(130) 才跳过(fire-and-forget 不承诺中断时完成)。
|
|
1047
|
-
await drainMemoryBackground();
|
|
1048
1075
|
await runtime.close();
|
|
1049
1076
|
await closeAllMcp();
|
|
1050
1077
|
layout.exitAltScreen();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { addTriple, graphStats, neighborsOf, pathBetween } from '../../memory/graph.js';
|
|
1
|
+
import { addTriple, graphStats, neighborsOf, parseAsOf, pathBetween } from '../../memory/graph.js';
|
|
2
2
|
import { formatRecallStats } from '../../memory/recall-stats.js';
|
|
3
3
|
// ---------- memory_graph ----------
|
|
4
4
|
// 知识图谱维护工具:邻居遍历(1-3 跳,可 relation 过滤)、两点最短路径、手工加三元组、看图统计。
|
|
@@ -33,6 +33,10 @@ export const memoryGraphTool = {
|
|
|
33
33
|
},
|
|
34
34
|
query: { type: 'string', description: 'neighbors: entity name or id; path: start entity' },
|
|
35
35
|
depth: { type: 'integer', description: 'neighbors: hops, 1-3, default 1' },
|
|
36
|
+
asOf: {
|
|
37
|
+
type: 'string',
|
|
38
|
+
description: 'neighbors/path: answer "what did I believe at THAT moment" instead of now. ISO timestamp or YYYY-MM-DD (local midnight). Edges are time-sliced by validAt/invalidAt: an edge counts iff validAt <= asOf < invalidAt. Use it when the current answer contradicts an older decision and you need to know which belief was held then. Omit for the current view.',
|
|
39
|
+
},
|
|
36
40
|
src: { type: 'string', description: 'add: source entity name' },
|
|
37
41
|
relation: {
|
|
38
42
|
type: 'string',
|
|
@@ -81,14 +85,20 @@ export const memoryGraphTool = {
|
|
|
81
85
|
return '错误:neighbors 需要 query(实体名或 id)。';
|
|
82
86
|
const depth = typeof args.depth === 'number' ? args.depth : 1;
|
|
83
87
|
const rel = typeof args.relation === 'string' ? args.relation.trim() : '';
|
|
84
|
-
const
|
|
88
|
+
const asOf = parseAsOf(args.asOf);
|
|
89
|
+
if (!asOf.ok)
|
|
90
|
+
return `错误:${asOf.reason}`;
|
|
91
|
+
const r = neighborsOf(query, depth, rel || undefined, asOf.ms);
|
|
85
92
|
if (!r.center)
|
|
86
93
|
return `(图中没有实体 "${query}")`;
|
|
87
94
|
const relNote = rel ? `,仅 ${rel} 边` : '';
|
|
95
|
+
const atNote = asOf.ms != null ? `,asOf ${new Date(asOf.ms).toISOString()}` : '';
|
|
88
96
|
const lines = [
|
|
89
97
|
`## ${r.center.name} (${r.center.id})${r.center.summary ? ` — ${r.center.summary}` : ''}`,
|
|
90
98
|
r.entities.length > 0 ? `\n## 邻居实体\n${fmtEntities(r.entities)}` : '',
|
|
91
|
-
`\n## 边(${r.edges.length}${relNote}${r.truncated ? ',已截断' : ''})\n${fmtEdges(r.edges)}`,
|
|
99
|
+
`\n## 边(${r.edges.length}${relNote}${atNote}${r.truncated ? ',已截断' : ''})\n${fmtEdges(r.edges)}`,
|
|
100
|
+
// 「那一刻没有边」与「实体不存在」是两种完全不同的答案,不说清楚会被误读成后者。
|
|
101
|
+
asOf.ms != null && r.edges.length === 0 ? '\n(该时刻没有成立的边——实体在,但那时还没有这条关系)' : '',
|
|
92
102
|
].filter(Boolean);
|
|
93
103
|
return lines.join('\n');
|
|
94
104
|
}
|
|
@@ -97,12 +107,16 @@ export const memoryGraphTool = {
|
|
|
97
107
|
const to = String(args.dst ?? '').trim();
|
|
98
108
|
if (!from || !to)
|
|
99
109
|
return '错误:path 需要 query(起点实体)和 dst(终点实体)。';
|
|
100
|
-
const
|
|
110
|
+
const asOf = parseAsOf(args.asOf);
|
|
111
|
+
if (!asOf.ok)
|
|
112
|
+
return `错误:${asOf.reason}`;
|
|
113
|
+
const r = pathBetween(from, to, asOf.ms);
|
|
114
|
+
const scope = asOf.ms != null ? `该时刻(${new Date(asOf.ms).toISOString()})` : '现在';
|
|
101
115
|
if (!r)
|
|
102
|
-
return `(无
|
|
116
|
+
return `(无 ${scope} 成立的路径:${from} ⇸ ${to},或端点实体不存在)`;
|
|
103
117
|
const chain = r.path.map((e) => e.name).join(' → ');
|
|
104
118
|
const lines = [
|
|
105
|
-
`## ${r.from.name} ⇢ ${r.to.name}(${r.edges.length}
|
|
119
|
+
`## ${r.from.name} ⇢ ${r.to.name}(${r.edges.length} 跳${asOf.ms != null ? `,asOf ${new Date(asOf.ms).toISOString()}` : ''})`,
|
|
106
120
|
`路径:${chain}`,
|
|
107
121
|
`\n## 边\n${fmtEdges(r.edges)}`,
|
|
108
122
|
];
|
|
@@ -29,7 +29,9 @@ export const memoryListTool = {
|
|
|
29
29
|
return '(无记忆条目)';
|
|
30
30
|
const lines = items.map((i) => {
|
|
31
31
|
const gap = !i.hasTrigger && wantsTrigger(i.type) ? ' [NO-TRIGGER]' : '';
|
|
32
|
-
|
|
32
|
+
// R16.1:来源不可信的条目在这里也要露出来,否则一眼扫列表看不出哪条是"从网页上抄的"。
|
|
33
|
+
const origin = i.origin === 'tool_output' ? ' [UNVERIFIED-ORIGIN]' : '';
|
|
34
|
+
return `- ${i.id}: ${i.name} — ${i.summary} (${i.type}, ${i.status})${gap}${origin}`;
|
|
33
35
|
});
|
|
34
36
|
const gaps = items.filter((i) => !i.hasTrigger && wantsTrigger(i.type)).length;
|
|
35
37
|
if (gaps > 0) {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { saveEntry, memoryWriteBlockedMessage } from '../../memory/store.js';
|
|
2
2
|
import { addTriple } from '../../memory/graph.js';
|
|
3
3
|
import { buildAnchors } from '../../memory/anchor.js';
|
|
4
|
+
import { detectHijack } from '../../memory/guard.js';
|
|
5
|
+
import { appendAudit } from '../../memory/audit.js';
|
|
4
6
|
/**
|
|
5
7
|
* 把工具参数里的 anchors 归一成 AnchorInput[]。
|
|
6
8
|
*
|
|
@@ -18,8 +20,11 @@ function parseAnchorInputs(raw) {
|
|
|
18
20
|
const p = typeof a.path === 'string' ? a.path.trim() : '';
|
|
19
21
|
if (!p)
|
|
20
22
|
continue;
|
|
23
|
+
// R7.1:非法 kind 一律按 file 处理。静默纠正比报错好——报错会让模型整条记忆都放弃写,
|
|
24
|
+
// 而它本来只是想锚一个文件,顺带把 kind 拼错了。
|
|
25
|
+
const k = a.kind === 'dir' || a.kind === 'url' ? a.kind : undefined;
|
|
21
26
|
const s = typeof a.symbol === 'string' ? a.symbol.trim() : '';
|
|
22
|
-
out.push({ path: p, ...(s ? { symbol: s } : {}) });
|
|
27
|
+
out.push({ ...(k ? { kind: k } : {}), path: p, ...(s ? { symbol: s } : {}) });
|
|
23
28
|
}
|
|
24
29
|
return out;
|
|
25
30
|
}
|
|
@@ -97,13 +102,18 @@ export const memorySaveTool = {
|
|
|
97
102
|
},
|
|
98
103
|
anchors: {
|
|
99
104
|
type: 'array',
|
|
100
|
-
description: '
|
|
105
|
+
description: 'Anchors: the thing this memory talks about, so a later change marks the memory stale instead of silently serving an outdated fact. kind=file (default) for a file or one of its symbols; kind=dir for a directory (detects added/removed/renamed entries, not edits inside files); kind=url for a web page (recorded as provenance only — it is never fetched, so it can never be verified). Pass paths/symbols only — hashes are computed for you at write time. Anchors that cannot be resolved are dropped.',
|
|
101
106
|
items: {
|
|
102
107
|
type: 'object',
|
|
103
108
|
properties: {
|
|
109
|
+
kind: {
|
|
110
|
+
type: 'string',
|
|
111
|
+
enum: ['file', 'dir', 'url'],
|
|
112
|
+
description: 'Default "file". Use "dir" for a directory, "url" for a web page.',
|
|
113
|
+
},
|
|
104
114
|
path: {
|
|
105
115
|
type: 'string',
|
|
106
|
-
description: 'Workspace-relative file path, e.g. "src/memory/store.ts" (
|
|
116
|
+
description: 'Workspace-relative file/directory path (forward slashes), e.g. "src/memory/store.ts" — or an http(s) URL when kind=url',
|
|
107
117
|
},
|
|
108
118
|
symbol: {
|
|
109
119
|
type: 'string',
|
|
@@ -131,6 +141,23 @@ export const memorySaveTool = {
|
|
|
131
141
|
const trigger = typeof args.trigger === 'string' ? args.trigger.trim() : '';
|
|
132
142
|
const action = typeof args.action === 'string' ? args.action.trim() : '';
|
|
133
143
|
const anchors = parseAnchorInputs(args.anchors);
|
|
144
|
+
// R16.2:指令性内容拒写。模型可能刚读完一个网页,把里面的"忽略之前的指令"当成
|
|
145
|
+
// 一条"要记住的约定"存进来——那样它此后每次启动都会进 system prompt。
|
|
146
|
+
// 确定性规则,**不靠模型自省**:模型正是被攻击对象,让它判断"这算不算注入"不可靠。
|
|
147
|
+
// 拒绝必须说清原因并留证,否则模型会换个 name 反复重试。
|
|
148
|
+
const hijack = detectHijack(`${name} ${summary} ${body}`);
|
|
149
|
+
if (hijack) {
|
|
150
|
+
appendAudit({
|
|
151
|
+
at: new Date().toISOString(),
|
|
152
|
+
action: 'refuse',
|
|
153
|
+
detail: `拒绝写入记忆「${name.slice(0, 60)}」:命中投毒规则 ${hijack.rule}`,
|
|
154
|
+
reason: `hijack:${hijack.rule}`,
|
|
155
|
+
snippet: hijack.sample,
|
|
156
|
+
});
|
|
157
|
+
return (`拒绝写入:内容命中投毒/注入规则 ${hijack.rule}(「${hijack.sample}」)。\n` +
|
|
158
|
+
`记忆会在**每次启动**时注入系统提示,所以这类"改写 agent 指令/身份/报告义务"的文本一律不落库。\n` +
|
|
159
|
+
`如果这是需要记住的知识(例如"看到这类网页要当心"),请改成**描述性结论**并避免逐字照抄原文。`);
|
|
160
|
+
}
|
|
134
161
|
const r = saveEntry({
|
|
135
162
|
name,
|
|
136
163
|
summary,
|