mocode-ai 1.9.9 → 1.10.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/dist/agent/index.js +13 -3
- package/dist/agent/mentioned-files.js +71 -0
- package/dist/agent/model-turn.js +83 -16
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +151 -23
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +46 -0
- package/dist/agent/stages/history-manager.js +1 -0
- package/dist/agent/tool-helpers.js +2 -2
- package/dist/agent/tool-turn.js +49 -4
- package/dist/agent/work-discipline.js +9 -9
- package/dist/changeset/unified-diff.js +59 -0
- package/dist/config/index.js +13 -10
- package/dist/context/relevance.js +2 -1
- package/dist/context/usage-snapshot.js +50 -0
- package/dist/headless.js +3 -1
- package/dist/host/commit-message.js +41 -0
- package/dist/host/protocol.js +205 -10
- package/dist/host/stdio.js +1096 -63
- package/dist/i18n/index.js +26 -10
- package/dist/llm/index.js +28 -3
- package/dist/llm/message-shape.js +45 -0
- package/dist/llm/providers/anthropic.js +2 -0
- package/dist/llm/reasoning.js +17 -0
- package/dist/memory/adoption.js +159 -27
- package/dist/memory/anchor-relocate.js +227 -0
- package/dist/memory/consolidate-skips.js +196 -0
- package/dist/memory/health.js +88 -6
- package/dist/memory/index.js +2 -1
- package/dist/memory/reflect.js +36 -4
- package/dist/memory/store.js +30 -0
- package/dist/models/reasoning-cap.js +19 -2
- package/dist/orchestrator/lane-executor.js +7 -1
- package/dist/orchestrator/repl.js +30 -49
- package/dist/prompt/system-prompt.js +30 -0
- package/dist/repl/commands/appearance.js +1 -2
- package/dist/repl/commands/compact.js +4 -0
- package/dist/repl/commands/diff.js +5 -46
- package/dist/repl/commands/memory.js +77 -4
- package/dist/repl/commands/model-actions.js +4 -3
- package/dist/repl/commands/model.js +2 -3
- package/dist/repl/message-format.js +7 -6
- package/dist/repl/running-input.js +27 -65
- package/dist/repl/runtime.js +129 -89
- package/dist/repl/status-bar.js +4 -38
- package/dist/rollback/store.js +36 -23
- package/dist/runtime/browser-diagnostics.js +77 -0
- package/dist/runtime/browser-manager.js +150 -22
- package/dist/runtime/runtime.js +1 -1
- package/dist/session/compact.js +44 -4
- package/dist/session/retention.js +4 -0
- package/dist/session/short-path-metrics.js +185 -0
- package/dist/session/store.js +78 -3
- package/dist/session/terminal-transcript.js +101 -0
- package/dist/tools/builtins/ask-human.js +2 -2
- package/dist/tools/builtins/browser.js +4 -1
- package/dist/tools/builtins/edit-file.js +28 -5
- package/dist/tools/builtins/grep.js +85 -35
- package/dist/tools/builtins/memory-save.js +1 -1
- package/dist/tools/builtins/memory-update.js +1 -1
- package/dist/tools/builtins/plan-update.js +4 -2
- package/dist/tools/builtins/read-file.js +95 -44
- package/dist/tools/builtins/run-command.js +57 -9
- package/dist/tools/builtins/task.js +4 -0
- package/dist/tools/constants.js +8 -0
- package/dist/tools/ripgrep-client.js +31 -11
- package/dist/tools/tool-runtime.js +29 -8
- package/dist/ui/layout-internal/content-write.js +7 -3
- package/dist/ui/layout-internal/core.js +1 -1
- package/dist/ui/layout-internal/state.js +0 -6
- package/dist/ui/layout-internal/statusbar.js +0 -30
- package/dist/ui/output-sink.js +24 -0
- package/dist/ui/spinner.js +3 -1
- package/package.json +4 -2
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* R2.7 锚点重定位:文件搬家之后,把 `missing` 的锚点指到新地址。**只提议,确认后写**。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么需要它
|
|
5
|
+
*
|
|
6
|
+
* R2 的锚点一旦写入就固定了字面路径,而文件是会搬的。实测真实库:32 个锚点里 4 个
|
|
7
|
+
* `missing`,其中 3 个是 `tests/agent-core.test.ts` → `tests/agent/agent-core.test.ts`,
|
|
8
|
+
* 1 个是 `src/orchestrator/tail.ts` → `src/memory/tail.ts`。这些条目本身**没错**,
|
|
9
|
+
* 错的只是地址;但 health 会把它们算进失效里,模型读到 `STALE-CODE` 也会怀疑内容。
|
|
10
|
+
* 结果是「重锚一下就好」的事被读成「这条记忆过期了,该删」。
|
|
11
|
+
*
|
|
12
|
+
* ## 为什么是「提议」而不是自动改写
|
|
13
|
+
*
|
|
14
|
+
* 同名文件是普遍现象(`tail.ts`、`index.ts`、`config.ts`)。按 basename 自动重写会把
|
|
15
|
+
* 一条讲 A 的记忆锚到 B 上,而锚错的代价比缺锚大得多:缺锚只是不校验,锚错是**假装校验过**。
|
|
16
|
+
* 所以这里只给候选,写库必须用户 `/memory anchor relocate <n>` 显式确认——与 R2.6 回填同一形态。
|
|
17
|
+
*
|
|
18
|
+
* ## 判据(两道,缺一不可)
|
|
19
|
+
*
|
|
20
|
+
* 1. **basename 完全相同**——这是「同一个文件」的必要条件,不是充分条件;
|
|
21
|
+
* 2. **旧路径的父目录名出现在新路径的目录段里**——`tests/agent-core.test.ts` 的父目录
|
|
22
|
+
* `tests` 仍在新路径里 → 强证据;`src/orchestrator/tail.ts` 的父目录 `orchestrator`
|
|
23
|
+
* 不在 `src/memory/` 里 → 只有「同名」一条弱证据,不提议、单独列出让人看。
|
|
24
|
+
*
|
|
25
|
+
* 只在旧路径没有父目录(工作区根下的文件)时才退回「basename 唯一」判据。
|
|
26
|
+
*
|
|
27
|
+
* ## 不动 hash
|
|
28
|
+
*
|
|
29
|
+
* 重定位只换路径,**绝不**顺带接受新内容:`updateEntry` 的 `anchors` 是整体重建(hash 现算),
|
|
30
|
+
* 拿它做重定位会把同一批锚点里真正 `stale` 的那些一起洗成 fresh,等于静默确认
|
|
31
|
+
* 「这些记忆的内容就是现在这样」。所以写库走 `replaceAnchors`:原样保留其它锚点对象,
|
|
32
|
+
* 只替换被搬走的那一条。
|
|
33
|
+
*/
|
|
34
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
35
|
+
import path from 'node:path';
|
|
36
|
+
import { getSandboxRoot } from '../sandbox/root.js';
|
|
37
|
+
import { buildAnchor, evaluateAnchor, resolveAnchorPath } from './anchor.js';
|
|
38
|
+
import { loadAll, replaceAnchors } from './store.js';
|
|
39
|
+
/**
|
|
40
|
+
* 扫描时跳过的目录。
|
|
41
|
+
*
|
|
42
|
+
* `dist`/`dist-tests` 里是同一批源码的编译产物——不排除的话,一次 `npm run build` 之后
|
|
43
|
+
* 每个 `src/x.ts` 都能匹配到 `dist/src/x.ts`,全是假候选(而且路径更深、看起来更"新")。
|
|
44
|
+
*/
|
|
45
|
+
const SKIP_DIRS = new Set([
|
|
46
|
+
'node_modules',
|
|
47
|
+
'.git',
|
|
48
|
+
'dist',
|
|
49
|
+
'dist-tests',
|
|
50
|
+
'coverage',
|
|
51
|
+
'.mocode',
|
|
52
|
+
'.next',
|
|
53
|
+
'build',
|
|
54
|
+
'out',
|
|
55
|
+
'.venv',
|
|
56
|
+
'__pycache__',
|
|
57
|
+
]);
|
|
58
|
+
/** 目录遍历的文件数上限:候选是给人核对的清单,扫不完的深度没有价值。 */
|
|
59
|
+
export const RELOCATE_MAX_FILES = 40_000;
|
|
60
|
+
const RELOCATE_MAX_DEPTH = 12;
|
|
61
|
+
/** 一次最多列多少条提议。与 `/memory anchor` 回填同量级:一屏能核完。 */
|
|
62
|
+
export const RELOCATE_MAX_PROPOSALS = 20;
|
|
63
|
+
function workspaceRoot(root) {
|
|
64
|
+
return root ?? getSandboxRoot() ?? process.cwd();
|
|
65
|
+
}
|
|
66
|
+
function indexWorkspace(base) {
|
|
67
|
+
const byBase = new Map();
|
|
68
|
+
let files = 0;
|
|
69
|
+
let truncated = false;
|
|
70
|
+
const walk = (dir, rel, depth) => {
|
|
71
|
+
if (truncated || depth > RELOCATE_MAX_DEPTH)
|
|
72
|
+
return;
|
|
73
|
+
let dirents;
|
|
74
|
+
try {
|
|
75
|
+
dirents = readdirSync(dir, { withFileTypes: true });
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
for (const d of dirents) {
|
|
81
|
+
if (truncated)
|
|
82
|
+
return;
|
|
83
|
+
const relPath = rel ? `${rel}/${d.name}` : d.name;
|
|
84
|
+
if (d.isDirectory()) {
|
|
85
|
+
if (SKIP_DIRS.has(d.name))
|
|
86
|
+
continue;
|
|
87
|
+
walk(path.join(dir, d.name), relPath, depth + 1);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
// 只看真文件:符号链接的 isFile() 为 false,顺着它会跑出工作区。
|
|
91
|
+
if (!d.isFile())
|
|
92
|
+
continue;
|
|
93
|
+
if (files >= RELOCATE_MAX_FILES) {
|
|
94
|
+
truncated = true;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
files += 1;
|
|
98
|
+
const seen = byBase.get(d.name);
|
|
99
|
+
if (seen)
|
|
100
|
+
seen.push(relPath);
|
|
101
|
+
else
|
|
102
|
+
byBase.set(d.name, [relPath]);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
walk(base, '', 0);
|
|
106
|
+
return { byBase, files, truncated };
|
|
107
|
+
}
|
|
108
|
+
/** 锚点路径的目录段(不含文件名)。 */
|
|
109
|
+
function dirSegments(p) {
|
|
110
|
+
const parts = p.split('/');
|
|
111
|
+
parts.pop();
|
|
112
|
+
return parts.filter(Boolean);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* 扫描所有 `missing` 的文件锚点,给出重定位提议。**只读**。
|
|
116
|
+
*
|
|
117
|
+
* 符号级 missing(文件还在、符号没了)刻意不处理:那不是搬家,改名后的符号与新语义
|
|
118
|
+
* 无法从路径推断,只能人工改记忆。
|
|
119
|
+
*/
|
|
120
|
+
export function collectRelocationProposals(root) {
|
|
121
|
+
const base = workspaceRoot(root);
|
|
122
|
+
const index = indexWorkspace(base);
|
|
123
|
+
const scan = {
|
|
124
|
+
proposals: [],
|
|
125
|
+
ambiguous: [],
|
|
126
|
+
unresolved: [],
|
|
127
|
+
weak: [],
|
|
128
|
+
files: index.files,
|
|
129
|
+
truncated: index.truncated,
|
|
130
|
+
};
|
|
131
|
+
for (const e of loadAll()) {
|
|
132
|
+
if (e.status !== 'active' || !e.anchors || e.anchors.length === 0)
|
|
133
|
+
continue;
|
|
134
|
+
for (const anchor of e.anchors) {
|
|
135
|
+
if ((anchor.kind ?? 'file') !== 'file')
|
|
136
|
+
continue;
|
|
137
|
+
const ev = evaluateAnchor(anchor, base);
|
|
138
|
+
if (ev.status !== 'missing')
|
|
139
|
+
continue;
|
|
140
|
+
// 文件还在 → missing 来自符号片段,与路径无关。
|
|
141
|
+
if (existsSync(resolveAnchorPath(anchor.path, base)))
|
|
142
|
+
continue;
|
|
143
|
+
const from = anchor.path;
|
|
144
|
+
const baseName = path.posix.basename(from);
|
|
145
|
+
const candidates = (index.byBase.get(baseName) ?? []).filter((p) => p !== from);
|
|
146
|
+
if (candidates.length === 0) {
|
|
147
|
+
scan.unresolved.push({ id: e.id, from });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const parent = dirSegments(from).pop();
|
|
151
|
+
const parentMatched = parent ? candidates.filter((p) => dirSegments(p).includes(parent)) : [];
|
|
152
|
+
const pool = parent ? parentMatched : candidates;
|
|
153
|
+
if (pool.length === 1) {
|
|
154
|
+
if (scan.proposals.length >= RELOCATE_MAX_PROPOSALS)
|
|
155
|
+
continue;
|
|
156
|
+
scan.proposals.push({
|
|
157
|
+
index: scan.proposals.length + 1,
|
|
158
|
+
id: e.id,
|
|
159
|
+
name: e.name,
|
|
160
|
+
from,
|
|
161
|
+
to: pool[0],
|
|
162
|
+
...(anchor.symbol ? { symbol: anchor.symbol } : {}),
|
|
163
|
+
parentMatched: pool === parentMatched && parentMatched.length === 1,
|
|
164
|
+
});
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (pool.length === 0) {
|
|
168
|
+
// 旧父目录名完全消失,只剩同名 —— 弱证据。
|
|
169
|
+
scan.weak.push({ id: e.id, from, candidate: candidates[0] });
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
scan.ambiguous.push({ id: e.id, from, candidates: pool.slice(0, 4) });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return scan;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* 写入选中的提议。`picks` 是 **1 基序号**(与屏幕上列出的一致)。
|
|
179
|
+
*
|
|
180
|
+
* 其它锚点对象原样保留(含各自的 hash),只有被搬走的那一条重新构建——
|
|
181
|
+
* 这是与 `updateEntry({anchors})` 的关键区别,见文件头。
|
|
182
|
+
*/
|
|
183
|
+
export function applyRelocations(proposals, picks, root) {
|
|
184
|
+
const base = workspaceRoot(root);
|
|
185
|
+
const out = { saved: [], failed: [] };
|
|
186
|
+
const wanted = proposals.filter((p) => picks === 'all' || picks.includes(p.index));
|
|
187
|
+
for (const p of wanted) {
|
|
188
|
+
const entry = loadAll().find((e) => e.id === p.id);
|
|
189
|
+
if (!entry) {
|
|
190
|
+
out.failed.push({ id: p.id, from: p.from, reason: '条目已消失' });
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const current = entry.anchors ?? [];
|
|
194
|
+
const target = current.find((a) => (a.kind ?? 'file') === 'file' && a.path === p.from);
|
|
195
|
+
if (!target) {
|
|
196
|
+
out.failed.push({ id: p.id, from: p.from, reason: '锚点已不存在(可能已重定位过)' });
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (current.some((a) => (a.kind ?? 'file') === 'file' && a.path === p.to)) {
|
|
200
|
+
out.failed.push({ id: p.id, from: p.from, reason: `已锚定 ${p.to},重定位会造成重复` });
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
// 两次扫描之间文件可能又被删了;此时不写入,避免留下一条新的 missing。
|
|
204
|
+
if (!existsSync(resolveAnchorPath(p.to, base))) {
|
|
205
|
+
out.failed.push({ id: p.id, from: p.from, reason: `${p.to} 已不存在` });
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const rebuilt = buildAnchor({ kind: 'file', path: p.to, ...(p.symbol ? { symbol: p.symbol } : {}) }, base);
|
|
209
|
+
if (!rebuilt.ok) {
|
|
210
|
+
// 符号在新文件里找不到是常见情形(搬家常伴随rename),必须说出来而不是静默丢锚点。
|
|
211
|
+
out.failed.push({ id: p.id, from: p.from, reason: `重锚 ${p.to} 失败:${rebuilt.reason}` });
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const next = current.map((a) => (a === target ? rebuilt.anchor : a));
|
|
215
|
+
const r = replaceAnchors(p.id, next, 'anchor relocate');
|
|
216
|
+
if (!r.ok) {
|
|
217
|
+
out.failed.push({ id: p.id, from: p.from, reason: 'blocked' in r ? `写入被拦:${r.blocked}` : '条目已消失' });
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
out.saved.push({ id: p.id, from: p.from, to: p.to });
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
/** 供命令层渲染的一行摘要。 */
|
|
225
|
+
export function describeRelocation(p) {
|
|
226
|
+
return `${p.from} → ${p.symbol ? `${p.to}#${p.symbol}` : p.to}`;
|
|
227
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* R11.5 巩固跳过记忆:同一批情节被模型判过「只是凑巧」之后,不要每轮再花钱问一遍。
|
|
3
|
+
*
|
|
4
|
+
* 存在理由(实测数据驱动的,不是预防性设计):真实库里 20 次巩固全部是
|
|
5
|
+
* `巩固 0/1 组 跳过 1`,而跳过的理由从来没被记录(见 `reflect.ts` 的 `plan.skip` 分支),
|
|
6
|
+
* 只能事后手工重放 11 条情节才发现分组信号全是 `看看 / 我看 / 功能 / 还是` 这类口语糊料。
|
|
7
|
+
* 于是一边是每次真花 LLM 调用,一边是零收益且零证据。
|
|
8
|
+
*
|
|
9
|
+
* 这一层只解决成本,不解决判据:成员集合完全相同的组,输入提示词也完全相同,
|
|
10
|
+
* 模型第二次给的答案不会比第一次更好。只要成员变了(有新情节并进来),签名就变,
|
|
11
|
+
* 立刻重新问一次 —— 那是新证据,值得问。
|
|
12
|
+
*
|
|
13
|
+
* 叶子依赖:只依赖 node 内置 + write-gate。不 import episodic/reflect(= 环),
|
|
14
|
+
* 签名由调用方用 `consolidationSignature()` 从成员 id 算出来传进来。
|
|
15
|
+
*/
|
|
16
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { memoryWriteBlockReason } from './write-gate.js';
|
|
19
|
+
/**
|
|
20
|
+
* 状态文件条目上限。签名随成员组合增长,不封顶就会无限膨胀;
|
|
21
|
+
* 50 条足够覆盖「最近几十个候选组」,更老的签名对应的情节多半早已衰减归档。
|
|
22
|
+
*/
|
|
23
|
+
const MAX_ENTRIES = 50;
|
|
24
|
+
/** 条目过期天数:超过这么久没再出现的签名,其成员情节基本都已进入归档区。 */
|
|
25
|
+
const EXPIRE_DAYS = 60;
|
|
26
|
+
/** 理由截断长度:它是日志/健康快照的注脚,不是正文。 */
|
|
27
|
+
const MAX_REASON_CHARS = 160;
|
|
28
|
+
const EMPTY_FILE = {
|
|
29
|
+
schemaVersion: 1,
|
|
30
|
+
updatedAt: '',
|
|
31
|
+
totals: { asked: 0, skipped: 0, mutedHits: 0 },
|
|
32
|
+
skips: {},
|
|
33
|
+
};
|
|
34
|
+
function skipsPath() {
|
|
35
|
+
return path.join(process.cwd(), '.mocode', 'memory-consolidate-skips.json');
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* 组的签名 = 成员 id 排序拼接。
|
|
39
|
+
*
|
|
40
|
+
* 刻意用**精确成员集合**而不是「共享文件/词元」这类主题摘要:后者会随着情节池的噪声变化漂移,
|
|
41
|
+
* 让「同一个组」时而被认出来时而被当成新组,停问就变成随机行为。成员集合是确定性的,
|
|
42
|
+
* 而它恰好等价于「模型看到的提示词完全相同」这个真正决定答案的条件。
|
|
43
|
+
*/
|
|
44
|
+
export function consolidationSignature(ids) {
|
|
45
|
+
return [...ids].sort().join('|');
|
|
46
|
+
}
|
|
47
|
+
/** 读状态文件(静默容错:缺失/损坏/坏字段 → 零值,永不抛)。 */
|
|
48
|
+
export function loadConsolidationSkips() {
|
|
49
|
+
try {
|
|
50
|
+
const p = skipsPath();
|
|
51
|
+
if (!existsSync(p))
|
|
52
|
+
return structuredCloneEmpty();
|
|
53
|
+
const raw = JSON.parse(readFileSync(p, 'utf8'));
|
|
54
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0);
|
|
55
|
+
const skips = {};
|
|
56
|
+
for (const [sig, entry] of Object.entries(raw.skips ?? {})) {
|
|
57
|
+
if (!entry || typeof entry !== 'object')
|
|
58
|
+
continue;
|
|
59
|
+
const e = entry;
|
|
60
|
+
if (typeof e.lastAt !== 'string')
|
|
61
|
+
continue;
|
|
62
|
+
skips[sig] = {
|
|
63
|
+
strikes: num(e.strikes),
|
|
64
|
+
lastAt: e.lastAt,
|
|
65
|
+
reason: typeof e.reason === 'string' ? e.reason : undefined,
|
|
66
|
+
members: num(e.members),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
schemaVersion: 1,
|
|
71
|
+
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : '',
|
|
72
|
+
totals: {
|
|
73
|
+
asked: num(raw.totals?.asked),
|
|
74
|
+
skipped: num(raw.totals?.skipped),
|
|
75
|
+
mutedHits: num(raw.totals?.mutedHits),
|
|
76
|
+
},
|
|
77
|
+
skips,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return structuredCloneEmpty();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function structuredCloneEmpty() {
|
|
85
|
+
return { ...EMPTY_FILE, totals: { ...EMPTY_FILE.totals }, skips: {} };
|
|
86
|
+
}
|
|
87
|
+
/** 原子写 + 过期/超量裁剪 + 总闸。失败静默:状态文件绝不影响巩固主流程。 */
|
|
88
|
+
function save(file) {
|
|
89
|
+
if (memoryWriteBlockReason() !== null)
|
|
90
|
+
return;
|
|
91
|
+
const now = Date.now();
|
|
92
|
+
const cutoff = now - EXPIRE_DAYS * 86400000;
|
|
93
|
+
const kept = Object.entries(file.skips)
|
|
94
|
+
.filter(([, e]) => {
|
|
95
|
+
const t = Date.parse(e.lastAt);
|
|
96
|
+
return !Number.isFinite(t) || t >= cutoff;
|
|
97
|
+
})
|
|
98
|
+
.sort((a, b) => b[1].lastAt.localeCompare(a[1].lastAt))
|
|
99
|
+
.slice(0, MAX_ENTRIES);
|
|
100
|
+
file.skips = Object.fromEntries(kept);
|
|
101
|
+
file.updatedAt = new Date(now).toISOString();
|
|
102
|
+
try {
|
|
103
|
+
const p = skipsPath();
|
|
104
|
+
mkdirSync(path.dirname(p), { recursive: true });
|
|
105
|
+
const tmp = p + '.tmp';
|
|
106
|
+
writeFileSync(tmp, JSON.stringify(file, null, 2) + '\n', 'utf8');
|
|
107
|
+
renameSync(tmp, p);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// 静默:观测/节流状态写不进去,最多是下一轮多问一次
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** 记一次真实的巩固请求(模型即将被问到)。 */
|
|
114
|
+
export function recordConsolidationAsk() {
|
|
115
|
+
const file = loadConsolidationSkips();
|
|
116
|
+
file.totals.asked += 1;
|
|
117
|
+
save(file);
|
|
118
|
+
}
|
|
119
|
+
/** 记一次「因签名已停问而未发请求」。 */
|
|
120
|
+
export function recordConsolidationMuteHit() {
|
|
121
|
+
const file = loadConsolidationSkips();
|
|
122
|
+
file.totals.mutedHits += 1;
|
|
123
|
+
save(file);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* 记一次模型判「凑巧」。
|
|
127
|
+
*
|
|
128
|
+
* 同样的签名再被判一次 → strikes 累加;达到阈值后由 `isConsolidationGroupMuted` 拦下请求。
|
|
129
|
+
* 理由只在**本次**写入,便于 health 展示「最近为什么没用」。
|
|
130
|
+
*/
|
|
131
|
+
export function recordConsolidationSkip(signature, info) {
|
|
132
|
+
const file = loadConsolidationSkips();
|
|
133
|
+
const prev = file.skips[signature];
|
|
134
|
+
const entry = {
|
|
135
|
+
strikes: (prev?.strikes ?? 0) + 1,
|
|
136
|
+
lastAt: new Date().toISOString(),
|
|
137
|
+
reason: info.reason ? info.reason.replace(/\s+/g, ' ').slice(0, MAX_REASON_CHARS) : prev?.reason,
|
|
138
|
+
members: info.members,
|
|
139
|
+
};
|
|
140
|
+
file.skips[signature] = entry;
|
|
141
|
+
file.totals.skipped += 1;
|
|
142
|
+
save(file);
|
|
143
|
+
return entry;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* 清除某组的跳过记忆(巩固成功时调用)。
|
|
147
|
+
*
|
|
148
|
+
* 必须清:成员已经 derivedInto 指向新语义条目,不会再来;若日后因故重新进池,
|
|
149
|
+
* 旧的 strikes 会让它一上来就被停问,等于把一条曾经成功的通道永久焊死。
|
|
150
|
+
*/
|
|
151
|
+
export function clearConsolidationSkip(signature) {
|
|
152
|
+
const file = loadConsolidationSkips();
|
|
153
|
+
if (!(signature in file.skips))
|
|
154
|
+
return;
|
|
155
|
+
delete file.skips[signature];
|
|
156
|
+
save(file);
|
|
157
|
+
}
|
|
158
|
+
/** 该组是否已达到「不必再问」的连续跳过次数。 */
|
|
159
|
+
export function isConsolidationGroupMuted(signature, threshold) {
|
|
160
|
+
const entry = loadConsolidationSkips().skips[signature];
|
|
161
|
+
return !!entry && entry.strikes >= threshold;
|
|
162
|
+
}
|
|
163
|
+
/** 供 health 展示的汇总(零副作用,只读)。 */
|
|
164
|
+
export function consolidationSkipStats() {
|
|
165
|
+
const file = loadConsolidationSkips();
|
|
166
|
+
const entries = Object.values(file.skips);
|
|
167
|
+
let lastAt = null;
|
|
168
|
+
let lastReason = null;
|
|
169
|
+
for (const e of entries) {
|
|
170
|
+
if (!lastAt || e.lastAt > lastAt) {
|
|
171
|
+
lastAt = e.lastAt;
|
|
172
|
+
lastReason = e.reason ?? null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
asked: file.totals.asked,
|
|
177
|
+
skipped: file.totals.skipped,
|
|
178
|
+
mutedHits: file.totals.mutedHits,
|
|
179
|
+
muted: entries.length,
|
|
180
|
+
lastReason,
|
|
181
|
+
lastAt,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** 仅供测试:清空状态文件,避免用例间串味。 */
|
|
185
|
+
export function __resetConsolidationSkipsForTests() {
|
|
186
|
+
const file = structuredCloneEmpty();
|
|
187
|
+
file.updatedAt = '';
|
|
188
|
+
try {
|
|
189
|
+
const p = skipsPath();
|
|
190
|
+
mkdirSync(path.dirname(p), { recursive: true });
|
|
191
|
+
writeFileSync(p, JSON.stringify(file, null, 2) + '\n', 'utf8');
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
// 静默
|
|
195
|
+
}
|
|
196
|
+
}
|
package/dist/memory/health.js
CHANGED
|
@@ -19,10 +19,12 @@ import { loadAll, loadAnchorStaleMap, loadStalenessMap, wantsTrigger, } from './
|
|
|
19
19
|
import { readRecallStats } from './recall-stats.js';
|
|
20
20
|
import { proactiveCounters } from './proactive.js';
|
|
21
21
|
import { adoptionStats } from './adoption.js';
|
|
22
|
+
import { loadPendingCandidates } from './pending.js';
|
|
23
|
+
import { consolidationSkipStats } from './consolidate-skips.js';
|
|
22
24
|
import { listInternalizedProfile, listProfileCandidates } from './persona.js';
|
|
23
25
|
import { MAX_ACTIVE } from '../tools/constants.js';
|
|
24
26
|
/** 快照结构版本。字段增删时自增,让读旧文件的人能立刻发现口径变了。 */
|
|
25
|
-
export const MEMORY_HEALTH_SCHEMA_VERSION =
|
|
27
|
+
export const MEMORY_HEALTH_SCHEMA_VERSION = 5;
|
|
26
28
|
function rate(num, den) {
|
|
27
29
|
if (den <= 0)
|
|
28
30
|
return 0;
|
|
@@ -58,6 +60,19 @@ export function buildMemoryHealth() {
|
|
|
58
60
|
const recall = readRecallStats();
|
|
59
61
|
const pc = proactiveCounters();
|
|
60
62
|
const adoption = adoptionStats();
|
|
63
|
+
// R13:候选队列只在记忆开启时才存在;读失败/不存在 → 0 条(与 load 的静默容错一致)。
|
|
64
|
+
const pendingCandidates = loadPendingCandidates();
|
|
65
|
+
const oldestPendingAt = pendingCandidates.reduce((oldest, c) => {
|
|
66
|
+
const at = typeof c.at === 'string' ? c.at : '';
|
|
67
|
+
if (!at)
|
|
68
|
+
return oldest;
|
|
69
|
+
return oldest === null || at < oldest ? at : oldest;
|
|
70
|
+
}, null);
|
|
71
|
+
const oldestMs = oldestPendingAt ? Date.parse(oldestPendingAt) : NaN;
|
|
72
|
+
const pendingAgeHours = Number.isFinite(oldestMs)
|
|
73
|
+
? Math.max(0, Math.round(((Date.now() - oldestMs) / 3600000) * 10) / 10)
|
|
74
|
+
: 0;
|
|
75
|
+
const consolidationSkips = consolidationSkipStats();
|
|
61
76
|
let internalized = 0;
|
|
62
77
|
let candidates = 0;
|
|
63
78
|
try {
|
|
@@ -86,8 +101,12 @@ export function buildMemoryHealth() {
|
|
|
86
101
|
},
|
|
87
102
|
anchors: {
|
|
88
103
|
anchored: anchorEntries.length,
|
|
89
|
-
|
|
90
|
-
|
|
104
|
+
// 两个数不互斥:一条条目可以同时有内容变的锚点与已消失的锚点。
|
|
105
|
+
// 刻意不合成一个数——「去核对代码」与「去重新锚定」是两种完全不同的动作。
|
|
106
|
+
stale: anchorEntries.filter((e) => anchorStale.get(e.id)?.changed.length).length,
|
|
107
|
+
staleRate: rate(anchorEntries.filter((e) => anchorStale.get(e.id)?.changed.length).length, anchorEntries.length),
|
|
108
|
+
missing: anchorEntries.filter((e) => anchorStale.get(e.id)?.missing.length).length,
|
|
109
|
+
missingRate: rate(anchorEntries.filter((e) => anchorStale.get(e.id)?.missing.length).length, anchorEntries.length),
|
|
91
110
|
byKind: anchorByKind,
|
|
92
111
|
},
|
|
93
112
|
derived: {
|
|
@@ -114,6 +133,19 @@ export function buildMemoryHealth() {
|
|
|
114
133
|
},
|
|
115
134
|
profile: { internalized, candidates },
|
|
116
135
|
adoption,
|
|
136
|
+
compaction: {
|
|
137
|
+
pending: pendingCandidates.length,
|
|
138
|
+
oldestAt: oldestPendingAt,
|
|
139
|
+
ageHours: pendingAgeHours,
|
|
140
|
+
},
|
|
141
|
+
consolidation: {
|
|
142
|
+
asked: consolidationSkips.asked,
|
|
143
|
+
skipped: consolidationSkips.skipped,
|
|
144
|
+
skipRate: rate(consolidationSkips.skipped, consolidationSkips.asked),
|
|
145
|
+
muted: consolidationSkips.muted,
|
|
146
|
+
mutedHits: consolidationSkips.mutedHits,
|
|
147
|
+
lastReason: consolidationSkips.lastReason,
|
|
148
|
+
},
|
|
117
149
|
warnings: [],
|
|
118
150
|
};
|
|
119
151
|
health.warnings = collectWarnings(health);
|
|
@@ -149,7 +181,31 @@ function collectWarnings(h) {
|
|
|
149
181
|
out.push(`派生条目 ${Math.round(h.derived.staleRate * 100)}% 已因源失效待复核:需要一轮反思去重写结论`);
|
|
150
182
|
}
|
|
151
183
|
if (h.adoption.pending >= 12) {
|
|
152
|
-
out.push(
|
|
184
|
+
out.push(`本会话已有 ${h.adoption.pending} 条送达记忆尚未评估:运行 /reflect 或等待下一次压缩以复用既有模型调用裁决`);
|
|
185
|
+
}
|
|
186
|
+
// R2:missing 必须单独告警。它是「文件搬家」而不是「记忆过期」,混进 staleRate 会误导
|
|
187
|
+
// (实测真实库 4 条 missing 里 3 条是 tests/agent-core.test.ts → tests/agent/agent-core.test.ts)。
|
|
188
|
+
if (h.anchors.missing >= 3) {
|
|
189
|
+
out.push(`${h.anchors.missing} 条记忆的锚点文件已不存在(多为文件搬家):用 /memory anchor relocate 重定位,不要当成记忆过期删掉`);
|
|
190
|
+
}
|
|
191
|
+
if (h.anchors.anchored >= 6 && h.anchors.staleRate >= 0.4) {
|
|
192
|
+
out.push(`已锚定条目里 ${Math.round(h.anchors.staleRate * 100)}% 内容已变:这些记忆需核对代码后 update,否则会被当现状读`);
|
|
193
|
+
}
|
|
194
|
+
// R14:派生通道零产出时必须说清「不是坏了,是没人往里写」——否则每次看健康报告
|
|
195
|
+
// 都要重新推导一遍,而它唯一的自动生产者就是 R11 巩固。
|
|
196
|
+
if (h.derived.total === 0 && h.consolidation.asked > 0) {
|
|
197
|
+
out.push(`派生条目为 0:唯一自动生产者是情节巩固(已问 ${h.consolidation.asked} 次、成 ${h.episodes.consolidated} 条),R14 的读时判定链路本身完整`);
|
|
198
|
+
}
|
|
199
|
+
// R13:队列积压与「没通电」是两件相反的事,告警要把方向说清。
|
|
200
|
+
// 只按条数告警会漏掉最坏形态:两三条候选晾了一整天,条数不够但原料已失效。
|
|
201
|
+
// R11.5:巩固空转。与上面那条「零巩固」告警不重复:那条说的是结果,这条说的是代价。
|
|
202
|
+
// 阈值放在 6 次:一次巩固最多两组请求,两轮自动触发就到 4 次,6 次已足以确认是系统性无效。
|
|
203
|
+
if (h.consolidation.asked >= 6 && h.consolidation.skipped === h.consolidation.asked) {
|
|
204
|
+
out.push(`巩固已问 ${h.consolidation.asked} 次全被判「只是凑巧」(${h.consolidation.muted} 组停问):` +
|
|
205
|
+
`最近理由:${h.consolidation.lastReason ?? '未记录'}`);
|
|
206
|
+
}
|
|
207
|
+
if (h.compaction.pending >= 10 || (h.compaction.pending > 0 && h.compaction.ageHours >= 24)) {
|
|
208
|
+
out.push(`压缩候选已积压 ${h.compaction.pending} 条(最旧 ${h.compaction.ageHours}h):运行 /reflect 让既有反思调用裁决,否则队列上限会把旧的挤掉`);
|
|
153
209
|
}
|
|
154
210
|
return out.slice(0, 6);
|
|
155
211
|
}
|
|
@@ -213,7 +269,8 @@ export function formatMemoryHealth(h = buildMemoryHealth()) {
|
|
|
213
269
|
if (types)
|
|
214
270
|
lines.push(`按类:${types}`);
|
|
215
271
|
lines.push(`trigger 覆盖:${h.trigger.withTrigger}/${h.trigger.required}(${pct(h.trigger.coverage)})`);
|
|
216
|
-
lines.push(`锚点:${h.anchors.anchored} 条已锚 ·
|
|
272
|
+
lines.push(`锚点:${h.anchors.anchored} 条已锚 · 内容变 ${h.anchors.stale}(${pct(h.anchors.staleRate)})` +
|
|
273
|
+
` · 文件缺失 ${h.anchors.missing ?? 0}(${pct(h.anchors.missingRate ?? 0)})` +
|
|
217
274
|
` | 派生:${h.derived.total} 条 · 待复核 ${h.derived.stale}(${pct(h.derived.staleRate)})`);
|
|
218
275
|
lines.push(`情节:active ${h.episodes.active} · 已巩固 ${h.episodes.consolidated}(${pct(h.episodes.consolidationRate)})`);
|
|
219
276
|
lines.push(`检索:memory_search ${h.retrieval.searches} 次 · 图谱命中 ${h.retrieval.graphHits}(${pct(h.retrieval.graphHitRate)})` +
|
|
@@ -221,7 +278,32 @@ export function formatMemoryHealth(h = buildMemoryHealth()) {
|
|
|
221
278
|
lines.push(`前摄:可匹配调用 ${h.proactive.toolCalls} · 注入 ${h.proactive.injections}(${pct(h.proactive.injectRate)})` +
|
|
222
279
|
` · trigger ${h.proactive.triggerHits} / 锚点 ${h.proactive.anchorHits}(其中失效 ${h.proactive.staleAnchorHits},${pct(h.proactive.staleAnchorRate)})`);
|
|
223
280
|
lines.push(`画像:内化 ${h.profile.internalized} · 候选 ${h.profile.candidates}`);
|
|
224
|
-
|
|
281
|
+
// R13:0 条也照常输出 —— 「队列空」本身就是要观测的状态,藏起来就又回到
|
|
282
|
+
// 「看不见 = 不知道通没通电」。有积压时补上最旧时长。
|
|
283
|
+
// 兼容旧快照:这份 JSON 是覆盖写的单点文件,磁盘上可能还是 schemaVersion 2 的旧结构,
|
|
284
|
+
// 缺 compaction 时按 0 条渲染而不是抛 TypeError(渲染函数不该因为快照旧了而崩)。
|
|
285
|
+
const compaction = h.compaction ?? { pending: 0, oldestAt: null, ageHours: 0 };
|
|
286
|
+
lines.push(`压缩候选:待裁决 ${compaction.pending}` +
|
|
287
|
+
(compaction.pending > 0 ? ` · 最旧 ${compaction.ageHours}h(${compaction.oldestAt})` : ''));
|
|
288
|
+
// R11.5:asked 为 0 时说明「还没问过」,不显示 0% 空转率——
|
|
289
|
+
// 没数据与有数据但结果为零是两件不同的事,渲染上必须能区分。
|
|
290
|
+
// 同样兼容旧快照(缺 consolidation 时按零值渲染)。
|
|
291
|
+
const consolidation = h.consolidation ?? {
|
|
292
|
+
asked: 0,
|
|
293
|
+
skipped: 0,
|
|
294
|
+
skipRate: 0,
|
|
295
|
+
muted: 0,
|
|
296
|
+
mutedHits: 0,
|
|
297
|
+
lastReason: null,
|
|
298
|
+
};
|
|
299
|
+
lines.push(`巩固:问过 ${consolidation.asked} 次 · 跳过 ${consolidation.skipped}(${pct(consolidation.skipRate)})` +
|
|
300
|
+
` · 停问 ${consolidation.muted} 组(省 ${consolidation.mutedHits} 次)` +
|
|
301
|
+
(consolidation.lastReason ? ` | 最近理由:${consolidation.lastReason}` : ''));
|
|
302
|
+
lines.push(`采纳:送达 ${h.adoption.delivered} · 已评估 ${h.adoption.evaluated}(采纳 ${h.adoption.adopted} / 无关 ${h.adoption.notApplicable} / 不明 ${h.adoption.unclear})` +
|
|
303
|
+
` · 本会话待评估 ${h.adoption.pending}` +
|
|
304
|
+
// stranded 单列并注明「不会再降」:它与 pending 长得像,要求的动作却完全相反。
|
|
305
|
+
(h.adoption.stranded ? ` · 已结束会话滞留 ${h.adoption.stranded}(只能等 90 天归档)` : '') +
|
|
306
|
+
` · 已抑制 ${h.adoption.suppressed}`);
|
|
225
307
|
for (const w of h.warnings)
|
|
226
308
|
lines.push(`⚠ ${w}`);
|
|
227
309
|
return lines;
|
package/dist/memory/index.js
CHANGED
|
@@ -12,7 +12,7 @@ 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 { recordMemoryDelivery, recordMemorySuppression, adoptionEvaluationInstruction, extractAdoptionEvaluations, applyAdoptionEvaluations, adoptionStats, adoptionEvents, pruneAdoptionLedger, __resetAdoptionForTests, } from './adoption.js';
|
|
15
|
+
export { recordMemoryDelivery, recordMemorySuppression, flushAdoptionSuppressions, adoptionEvaluationInstruction, extractAdoptionEvaluations, applyAdoptionEvaluations, adoptionStats, adoptionEvents, pruneAdoptionLedger, __resetAdoptionForTests, } from './adoption.js';
|
|
16
16
|
export { captureMemoryBaseline, buildMemoryTailSection, memoryTailChangedIds, __resetMemoryBaselineForTests, } from './tail.js';
|
|
17
17
|
export { buildTurnRecallSection, isTurnRecallEnabled, flushTurnRecallStats, turnRecallCounters, __resetTurnRecallForTests, } from './turn-recall.js';
|
|
18
18
|
export { isCompactHandoffEnabled, appendPendingCandidates, loadPendingCandidates, trimPendingCandidates, pendingCandidateCount, extractMemoryCandidates, formatPendingForReflect, memoryCandidatesInstruction, MEMORY_CANDIDATES_HEADING, } from './pending.js';
|
|
@@ -20,3 +20,4 @@ export { kickoffReflection, reflectOnExit, drainMemoryBackground, getLastReflect
|
|
|
20
20
|
export { isEpisodicEnabled, isConsolidationEnabled, collectChangedFiles, extractCompactionSummary, parsePendingSteps, buildEpisode, recordSessionEpisode, listEpisodes, buildEpisodeSection, episodeFactsOf, findConsolidationGroups, applyConsolidation, CONSOLIDATED_NAME_SUFFIX, } from './episodic.js';
|
|
21
21
|
export { collectSeedCandidates, applySeedCandidates, extractConventionBullets, seedNameOf, SEED_MAX_CANDIDATES, } from './seed.js';
|
|
22
22
|
export { collectAnchorCandidates, applyAnchorCandidates, extractAnchorPaths, looksLikePath, ANCHOR_BACKFILL_MAX_ENTRIES, ANCHOR_BACKFILL_MAX_PATHS, } from './anchor-backfill.js';
|
|
23
|
+
export { collectRelocationProposals, applyRelocations, describeRelocation, RELOCATE_MAX_FILES, RELOCATE_MAX_PROPOSALS, } from './anchor-relocate.js';
|
package/dist/memory/reflect.js
CHANGED
|
@@ -19,6 +19,8 @@ import { detectHijack, findSourceLine, isUntrustedRole } from './guard.js';
|
|
|
19
19
|
import { appendAudit } from './audit.js';
|
|
20
20
|
import { normalizeRelation, isKnownRelation, relationCheatSheet } from './relation-vocab.js';
|
|
21
21
|
import { formatPendingForReflect, loadPendingCandidates, trimPendingCandidates } from './pending.js';
|
|
22
|
+
import { clearConsolidationSkip, consolidationSignature, isConsolidationGroupMuted, recordConsolidationAsk, recordConsolidationMuteHit, recordConsolidationSkip, } from './consolidate-skips.js';
|
|
23
|
+
import { CONSOLIDATE_SKIP_STRIKES } from '../tools/constants.js';
|
|
22
24
|
import { adoptionEvaluationInstruction, applyAdoptionEvaluations } from './adoption.js';
|
|
23
25
|
import { applyConsolidation, findConsolidationGroups, isConsolidationEnabled, } from './episodic.js';
|
|
24
26
|
// ── 日志(静默容错,裁尾保最近)─────────────────────────────────────────────
|
|
@@ -645,6 +647,11 @@ export function formatReflectResult(r) {
|
|
|
645
647
|
parts.push(`反证降级${r.demotions}`);
|
|
646
648
|
if (r.relViolations)
|
|
647
649
|
parts.push(`违${r.relViolations}`);
|
|
650
|
+
// R13:压缩候选的消费量必须出现在反思摘要里。不报这一项时,「候选队列空」与
|
|
651
|
+
// 「压缩这条通道压根没产出」在日志里长得一模一样——实测就是这样把一条正常运转的
|
|
652
|
+
// 通道误判成没通电的。只在真消费过时才输出,避免常态多一个恒为 0 的噪声字段。
|
|
653
|
+
if (r.pendingConsumed)
|
|
654
|
+
parts.push(`压缩候选${r.pendingConsumed}`);
|
|
648
655
|
if (r.adoptionsEvaluated)
|
|
649
656
|
parts.push(`采纳评估${r.adoptionsEvaluated}`);
|
|
650
657
|
if (r.gcDecayed || r.gcCapped || r.gcGced) {
|
|
@@ -864,7 +871,16 @@ export async function runConsolidation(groups, signal) {
|
|
|
864
871
|
return result;
|
|
865
872
|
const timeoutSignal = signal ?? AbortSignal.timeout(REFLECT_TIMEOUT_MS);
|
|
866
873
|
for (const group of list) {
|
|
874
|
+
// R11.5:成员集合相同的组,喂给模型的提示词逐字相同,答案不会因为再问一次而变好。
|
|
875
|
+
// 连续被判「凑巧」达到阈值后直接跳过,省下一次真实 LLM 调用。
|
|
876
|
+
const signature = consolidationSignature(group.members.map((m) => m.entry.id));
|
|
877
|
+
if (isConsolidationGroupMuted(signature, CONSOLIDATE_SKIP_STRIKES)) {
|
|
878
|
+
result.muted = (result.muted ?? 0) + 1;
|
|
879
|
+
recordConsolidationMuteHit();
|
|
880
|
+
continue;
|
|
881
|
+
}
|
|
867
882
|
try {
|
|
883
|
+
recordConsolidationAsk();
|
|
868
884
|
const first = await fetchReflection([{ role: 'system', content: CONSOLIDATE_SYS }, consolidatePrompt(group)], timeoutSignal);
|
|
869
885
|
let plan = parseConsolidationPlan(first.content);
|
|
870
886
|
if (plan === null) {
|
|
@@ -887,11 +903,20 @@ export async function runConsolidation(groups, signal) {
|
|
|
887
903
|
}
|
|
888
904
|
if (plan.skip) {
|
|
889
905
|
result.skipped++;
|
|
906
|
+
// R11.5:理由必须留证。此前这里只 increment,于是 20 次 0 产出没有任何解释。
|
|
907
|
+
if (plan.reason) {
|
|
908
|
+
result.skipReasons ??= [];
|
|
909
|
+
result.skipReasons.push(plan.reason.replace(/\s+/g, ' ').slice(0, 160));
|
|
910
|
+
}
|
|
911
|
+
recordConsolidationSkip(signature, { reason: plan.reason, members: group.members.length });
|
|
890
912
|
continue;
|
|
891
913
|
}
|
|
892
914
|
const applied = applyConsolidation(group, plan.draft);
|
|
893
|
-
if (applied.ok)
|
|
915
|
+
if (applied.ok) {
|
|
894
916
|
result.consolidated++;
|
|
917
|
+
// 成功即清记忆:成员已挂 derivedInto 不会再进池,若因故回来也不该一上来就被停问。
|
|
918
|
+
clearConsolidationSkip(signature);
|
|
919
|
+
}
|
|
895
920
|
else
|
|
896
921
|
result.error ??= applied.reason;
|
|
897
922
|
}
|
|
@@ -963,11 +988,18 @@ export function __resetConsolidateThrottleForTests() {
|
|
|
963
988
|
autoConsolidateCount = 0;
|
|
964
989
|
lastConsolidationResult = null;
|
|
965
990
|
}
|
|
966
|
-
/** 摘要串(供 repl flush):巩固 N 组(跳过 M 条)。 */
|
|
991
|
+
/** 摘要串(供 repl flush 与 memory.log):巩固 N 组(跳过 M 条 · 停问 K 组)。 */
|
|
967
992
|
export function formatConsolidationResult(r) {
|
|
968
993
|
const parts = [`巩固 ${r.consolidated}/${r.groups} 组`];
|
|
969
|
-
if (r.skipped > 0)
|
|
970
|
-
|
|
994
|
+
if (r.skipped > 0) {
|
|
995
|
+
// 理由随摘要一起落 memory.log:跳过本身不是问题,无从得知为什么跳过才是问题
|
|
996
|
+
// (实测 20 次 `跳过 1` 连续 9 天没有一句理由,只能事后手工重放情节才看出来)。
|
|
997
|
+
const reasons = r.skipReasons?.length ? `:${r.skipReasons.join(' / ')}` : '';
|
|
998
|
+
parts.push(`跳过 ${r.skipped}${reasons}`);
|
|
999
|
+
}
|
|
1000
|
+
// 停问是省下的请求,不是跳过;混为一谈会让空转率永远上不去。
|
|
1001
|
+
if (r.muted)
|
|
1002
|
+
parts.push(`停问 ${r.muted}(已连续判凑巧)`);
|
|
971
1003
|
if (r.error)
|
|
972
1004
|
parts.push(`错误 ${r.error}`);
|
|
973
1005
|
return parts.join(' ');
|