mocode-ai 1.8.0 → 1.8.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/config/index.js +1 -1
- package/dist/headless.js +10 -1
- package/dist/i18n/index.js +8 -0
- package/dist/llm/index.js +6 -2
- package/dist/memory/graph.js +181 -11
- package/dist/memory/index.js +3 -3
- package/dist/memory/persona.js +94 -3
- package/dist/memory/reflect.js +229 -20
- package/dist/memory/relation-vocab.js +19 -0
- package/dist/memory/store.js +19 -0
- package/dist/repl/commands/memory.js +90 -5
- package/dist/repl/commands.js +3 -0
- package/dist/repl/running-input.js +45 -32
- package/dist/repl/runtime.js +20 -7
- package/dist/tools/builtins/edit-file.js +1 -1
- package/dist/tools/builtins/memory-forget.js +26 -5
- package/dist/tools/builtins/memory-graph.js +7 -0
- package/dist/ui/layout-internal/state.js +4 -2
- package/dist/ui/layout-internal/statusbar.js +7 -5
- package/package.json +1 -1
package/dist/memory/reflect.js
CHANGED
|
@@ -12,8 +12,9 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
12
12
|
import path from 'node:path';
|
|
13
13
|
import { chat } from '../llm/index.js';
|
|
14
14
|
import { config, isMemoryEnabled } from '../config/index.js';
|
|
15
|
-
import { saveEntry, updateEntry, forgetEntry, loadAll, gcMemories } from './store.js';
|
|
16
|
-
import { addTriple, ensurePrimaryPerson, PRIMARY_PERSON_ID } from './graph.js';
|
|
15
|
+
import { saveEntry, updateEntry, forgetEntry, supersedeEntry, loadAll, gcMemories } from './store.js';
|
|
16
|
+
import { addTriple, ensurePrimaryPerson, invalidateProfileEdges, voteEdge, loadScopeGraph, PRIMARY_PERSON_ID, } from './graph.js';
|
|
17
|
+
import { isInternalizedEdge } from './persona.js';
|
|
17
18
|
import { normalizeRelation, isKnownRelation, relationCheatSheet } from './relation-vocab.js';
|
|
18
19
|
// ── 日志(静默容错,裁尾保最近)─────────────────────────────────────────────
|
|
19
20
|
function logPath() {
|
|
@@ -90,20 +91,60 @@ function buildMemorySample() {
|
|
|
90
91
|
})
|
|
91
92
|
.join('\n---\n');
|
|
92
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* 待投票的画像边快照(反思 prompt 用):当前 global 图里 person-primary 的 active 边,
|
|
96
|
+
* 连同当前证据计数/后验,让模型只对"本轮对话行为确实印证或相悖"的边投票。
|
|
97
|
+
* 关键:这是**本轮反思开始前**拍的快照,本轮新建的 profile/corrections 边不在白名单——
|
|
98
|
+
* 防止模型给自己刚推断出的信念投票一次转正(自我强化)。
|
|
99
|
+
*/
|
|
100
|
+
function buildProfileEvidenceSnapshot() {
|
|
101
|
+
const g = loadScopeGraph('global');
|
|
102
|
+
const byId = new Map(g.entities.map((e) => [e.id, e]));
|
|
103
|
+
const edges = g.edges
|
|
104
|
+
.filter((e) => !e.invalidAt && e.src === PRIMARY_PERSON_ID && e.dst !== PRIMARY_PERSON_ID)
|
|
105
|
+
.slice(0, 20);
|
|
106
|
+
const votable = new Set();
|
|
107
|
+
const statements = new Map();
|
|
108
|
+
const text = edges
|
|
109
|
+
.map((e) => {
|
|
110
|
+
const dst = byId.get(e.dst);
|
|
111
|
+
const target = dst?.name ?? e.dst;
|
|
112
|
+
const statement = e.fact?.trim() || `${e.relation}:${target}`;
|
|
113
|
+
votable.add(e.id);
|
|
114
|
+
statements.set(e.id, statement);
|
|
115
|
+
const c = e.evidence?.confirmed ?? 0;
|
|
116
|
+
const x = e.evidence?.contradicted ?? 0;
|
|
117
|
+
const state = isInternalizedEdge(e) ? 'internalized' : 'candidate';
|
|
118
|
+
return `[${e.id}] (${state}, evidence confirm=${c} contradict=${x}) ${statement}`;
|
|
119
|
+
})
|
|
120
|
+
.join('\n');
|
|
121
|
+
return { text: edges.length === 0 ? '(无)' : text, votable, statements };
|
|
122
|
+
}
|
|
93
123
|
const TYPES = 'decision | fact | pitfall | reference | feedback';
|
|
124
|
+
/** 后台反思整体超时:卡住的请求不能拖过退出 drain,也不该长期占用在飞槽位。 */
|
|
125
|
+
const REFLECT_TIMEOUT_MS = 60_000;
|
|
126
|
+
/**
|
|
127
|
+
* 后台任务的重试预算:只要 3 次尝试(连接类首败零等待,其后退避 ~1s、~2s)。
|
|
128
|
+
* 不能用交互式 chat 默认的 10 次——指数退避累计 0+1+2+4+8+16+30≈61s,恰好打满
|
|
129
|
+
* 上面的 60s 超时:后端持续失败时超时会落在退避 sleep 里,最后只剩一条含义不明的
|
|
130
|
+
* 'AbortError: This operation was aborted'(实测 2026-10 多次出现在状态行)。
|
|
131
|
+
*/
|
|
132
|
+
const REFLECT_MAX_ATTEMPTS = 3;
|
|
94
133
|
const REFLECT_SYS = `You are mocode's memory reflector. Review the recent session and existing memories, producing **only** updates worth remembering long-term.
|
|
95
|
-
Output strictly JSON (no markdown code blocks, no explanatory text): {"saves":[{"type":"...","name":"...","summary":"...","body":"..."}],"updates":[{"id":"...","reason":"...","summary":"...","body":"..."}],"forgets":[{"id":"...","reason":"..."}],"triples":[{"src":"...","relation":"...","dst":"...","fact":"..."}],"profile":[{"relation":"...","dst":"...","fact":"..."}]}
|
|
134
|
+
Output strictly JSON (no markdown code blocks, no explanatory text): {"saves":[{"type":"...","name":"...","summary":"...","body":"...","supersedes":"old-id-or-empty"}],"updates":[{"id":"...","reason":"...","summary":"...","body":"..."}],"forgets":[{"id":"...","reason":"..."}],"triples":[{"src":"...","relation":"...","dst":"...","fact":"..."}],"profile":[{"relation":"...","dst":"...","fact":"..."}],"corrections":[{"relation":"...","dst":"...","fact":"...","old":"..."}],"evidence":[{"edgeId":"...","vote":"confirm|contradict","reason":"..."}]}
|
|
96
135
|
Empty arrays are valid (if nothing is worth saving, all arrays are empty).
|
|
97
136
|
Rules:
|
|
98
137
|
① Only store non-obvious, cross-session-useful facts/decisions/pitfalls; do not store current bugs, temp files, undecided TODOs, or volatile items;
|
|
99
138
|
② Better to store less than to store trivially correct info (e.g. "keep it concise");
|
|
100
|
-
③ ids in updates/forgets must come from the "existing memories" list below; do not fabricate ids not listed there;
|
|
139
|
+
③ ids in updates/forgets/supersedes must come from the "existing memories" list below; do not fabricate ids not listed there;
|
|
101
140
|
④ names in saves must be concise and not collide with existing ones; type ∈ {${TYPES}};
|
|
102
|
-
⑤ If an existing memory contradicts new facts or is outdated, update the old entry (modify summary/body) rather than creating a duplicate;
|
|
141
|
+
⑤ If an existing memory contradicts new facts or is outdated, update the old entry (modify summary/body) rather than creating a duplicate; if a NEW entry fully replaces an old one whose title/scope differs, put the old id in that save's "supersedes" field (the old entry is marked superseded, not deleted);
|
|
103
142
|
⑥ forgets are for memories clearly stale / superseded by a new entry (archive, not hard-delete);
|
|
104
143
|
⑦ triples are PROJECT knowledge-graph facts about THIS CODEBASE distilled from this session: concise entity names (lowercase snake_case or proper nouns) plus a one-line fact. Prioritize the high-reuse structural relations in this order — dependency/ownership (depends_on, uses, used_by, calls, part_of), location (implemented_in, reads, writes, configured_by, runs_on, listens_on), verification (tests, documented_in), rationale/risk (decided_by, conflicts_with); full list: ${relationCheatSheet('project')}. Favor facts that would help a future session navigate or avoid re-deriving (which module implements X, what depends on Y, what conflicts with Z). A relation outside this list is allowed only when none fits (it gets flagged for review). Only emit triples that are stable, non-obvious and reusable in this repo (2-6 at most).
|
|
105
|
-
⑧ profile is for facts about THE USER (the human), which must apply across ALL projects — identity, role, expertise, language/communication style, stable preferences, current goals, constraints. They are attached to the single canonical person entity. Each item: dst is a short atomic value/entity, fact is one neutral Chinese sentence stating it. Prefer these relations: ${relationCheatSheet('global')}. A relation outside this list is allowed only when none fits. NEVER put repo paths, commands, file names, ports, secrets or one-task details in profile — those belong in triples. Only emit profile when the user explicitly revealed something durable about themselves (0-3 items); when unsure, omit
|
|
106
|
-
|
|
144
|
+
⑧ profile is for facts about THE USER (the human), which must apply across ALL projects — identity, role, expertise, language/communication style, stable preferences, current goals, constraints. They are attached to the single canonical person entity. Each item: dst is a short atomic value/entity, fact is one neutral Chinese sentence stating it. Prefer these relations: ${relationCheatSheet('global')}. A relation outside this list is allowed only when none fits. NEVER put repo paths, commands, file names, ports, secrets or one-task details in profile — those belong in triples. Only emit profile when the user explicitly revealed something durable about themselves (0-3 items); when unsure, omit. Profile items from your own inference are stored as LOW confidence and will NOT be internalized until the user confirms them — do not inflate them.
|
|
145
|
+
⑨ corrections is the HIGHEST signal channel: use it ONLY when the user explicitly corrects a prior belief about themselves ("不对/别这样/我已经不在 X 了/我更喜欢…"). Each correction invalidates the previous value for that relation and installs the new one as user-confirmed. "relation" is the profile relation being corrected, "dst"/"fact" are the NEW value (same shape as profile), "old" is the old value being withdrawn (short hint, may be empty). Do not put repo/code corrections here — those use updates/forgets.
|
|
146
|
+
⑩ evidence is the ONLY channel that adjusts confidence of an EXISTING profile belief from observed behavior — it never creates facts. You are given "Profile beliefs under review" containing only votable edge ids with their current counts. Rules: vote only on ids from that list, at most one vote per id, and only when THIS session genuinely bears on the belief — "confirm" when the user acts/chooses/agrees consistently with it, "contradict" when they act against it or state something incompatible; mere non-mention is NEITHER (omit). NEVER vote on beliefs you are newly creating in profile/corrections this same turn. Be conservative: a few independent confirms (with zero contradicts) auto-internalize a candidate; repeated contradicts demote an internalized belief back to candidate, and every such move is surfaced to the user. When unsure, cast no vote.`;
|
|
147
|
+
const REFLECT_USER = (transcript, sample, profileEdges) => `## Recent session\n${transcript}\n\n## Existing memories\n${sample}\n\n## Profile beliefs under review (evidence votes may only target these ids)\n${profileEdges}\n\nProduce JSON:`;
|
|
107
148
|
export function parsePlan(content) {
|
|
108
149
|
if (!content)
|
|
109
150
|
return null;
|
|
@@ -138,7 +179,10 @@ export function parsePlan(content) {
|
|
|
138
179
|
}
|
|
139
180
|
/** 取一次反思 LLM 返回的可解析文本(content 优先;tool_calls 的 JSON 串参数兜底)。 */
|
|
140
181
|
async function fetchReflection(messages, signal) {
|
|
141
|
-
const r = await chat(messages, {}, signal, undefined, {
|
|
182
|
+
const r = await chat(messages, {}, signal, undefined, {
|
|
183
|
+
reasoningEffort: 'low',
|
|
184
|
+
maxAttempts: REFLECT_MAX_ATTEMPTS,
|
|
185
|
+
});
|
|
142
186
|
if (!r.toolCalls.length && r.content)
|
|
143
187
|
return { content: r.content, raw: null };
|
|
144
188
|
// 推理模型偶发只把 JSON 塞进 tool_calls 参数、或 content 为 null:从工具调用里捞 JSON 串。
|
|
@@ -158,13 +202,22 @@ async function fetchReflection(messages, signal) {
|
|
|
158
202
|
* 首轮解析失败时做**一次修复式重试**(明确要求"只输出 JSON、不要思考过程"),
|
|
159
203
|
* 重试仍失败才报 parse-failed——此时 rawParseFailure 带原始返回指纹,由 kickoff 落
|
|
160
204
|
* memory.log,不再像旧版那样无声丢掉一整轮且无从排查。store 调用全同步。
|
|
161
|
-
*
|
|
205
|
+
* REFLECT_TIMEOUT_MS 超时(AbortSignal.timeout)防 exit 时 drain 挂死;重试预算收紧到
|
|
206
|
+
* REFLECT_MAX_ATTEMPTS 次,避免交互式 10 次退避打满超时后只剩含义不明的 AbortError。
|
|
162
207
|
*/
|
|
163
208
|
export async function runReflection(transcript, signal) {
|
|
164
209
|
const ts = new Date().toISOString();
|
|
165
210
|
const sample = buildMemorySample();
|
|
211
|
+
// 本轮开始前的画像边快照:evidence 票只能投给这些 id(本轮新建边无法自我投票)。
|
|
212
|
+
const evidenceSnap = buildProfileEvidenceSnapshot();
|
|
213
|
+
const beforeInternalized = new Set(loadScopeGraph('global')
|
|
214
|
+
.edges.filter((e) => evidenceSnap.votable.has(e.id) && isInternalizedEdge(e))
|
|
215
|
+
.map((e) => e.id));
|
|
166
216
|
const sys = { role: 'system', content: REFLECT_SYS };
|
|
167
|
-
const user = {
|
|
217
|
+
const user = {
|
|
218
|
+
role: 'user',
|
|
219
|
+
content: REFLECT_USER(transcript, sample, evidenceSnap.text),
|
|
220
|
+
};
|
|
168
221
|
const result = {
|
|
169
222
|
ts,
|
|
170
223
|
saves: 0,
|
|
@@ -175,7 +228,7 @@ export async function runReflection(transcript, signal) {
|
|
|
175
228
|
gcCapped: 0,
|
|
176
229
|
gcGced: 0,
|
|
177
230
|
};
|
|
178
|
-
const timeoutSignal = signal ?? AbortSignal.timeout(
|
|
231
|
+
const timeoutSignal = signal ?? AbortSignal.timeout(REFLECT_TIMEOUT_MS);
|
|
179
232
|
let content = null;
|
|
180
233
|
try {
|
|
181
234
|
const first = await fetchReflection([sys, user], timeoutSignal);
|
|
@@ -198,7 +251,18 @@ export async function runReflection(transcript, signal) {
|
|
|
198
251
|
}
|
|
199
252
|
}
|
|
200
253
|
catch (e) {
|
|
201
|
-
|
|
254
|
+
// 超时到期时 fetch/退避 sleep 抛的是 AbortError/DOMException,文案 'This operation
|
|
255
|
+
// was aborted' 完全无法区分原因;统一归类成可读的超时提示(秒数按实际信号预算)。
|
|
256
|
+
if (timeoutSignal.aborted) {
|
|
257
|
+
// 内部自建信号的预算由本模块常量决定,可给出准确秒数;外部传入的信号(retention
|
|
258
|
+
// 巩固)预算在调用方,不臆测数字。
|
|
259
|
+
result.error = signal
|
|
260
|
+
? '反思超时(后端持续失败或无响应)'
|
|
261
|
+
: `反思超时(${REFLECT_TIMEOUT_MS / 1000}s,后端持续失败或无响应)`;
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
result.error = e instanceof Error ? e.name + ': ' + e.message : String(e);
|
|
265
|
+
}
|
|
202
266
|
return result;
|
|
203
267
|
}
|
|
204
268
|
const plan = parsePlan(content);
|
|
@@ -221,8 +285,15 @@ export async function runReflection(transcript, signal) {
|
|
|
221
285
|
body: String(s.body ?? s.summary),
|
|
222
286
|
type: normalizeType(s.type),
|
|
223
287
|
});
|
|
224
|
-
if (r.ok)
|
|
288
|
+
if (r.ok) {
|
|
225
289
|
saves++;
|
|
290
|
+
// 新条目显式取代旧条目(标题/范围不同,不适合原地 update):回填取代链,
|
|
291
|
+
// 旧条目转 superseded(从默认索引隐藏但不删除,可审计)。
|
|
292
|
+
const oldId = typeof s.supersedes === 'string' ? s.supersedes.trim() : '';
|
|
293
|
+
if (oldId && oldId !== r.id) {
|
|
294
|
+
supersedeEntry(oldId, r.id, 'superseded by new entry from reflection');
|
|
295
|
+
}
|
|
296
|
+
}
|
|
226
297
|
}
|
|
227
298
|
}
|
|
228
299
|
if (Array.isArray(plan.updates)) {
|
|
@@ -269,6 +340,8 @@ export async function runReflection(transcript, signal) {
|
|
|
269
340
|
}
|
|
270
341
|
}
|
|
271
342
|
// 全局用户画像:挂到规范 person-primary、写 global 图(与项目 triples 分流)。
|
|
343
|
+
// M2 信念分级:反思**推断**的画像以 prov=reflection / confidence=0.4 落库——
|
|
344
|
+
// 不进 About you(L2),只进候选(L1),等用户确认或多会话佐证后晋升。
|
|
272
345
|
let profiles = 0;
|
|
273
346
|
if (Array.isArray(plan.profile) && plan.profile.length > 0) {
|
|
274
347
|
let personId = PRIMARY_PERSON_ID;
|
|
@@ -290,11 +363,87 @@ export async function runReflection(transcript, signal) {
|
|
|
290
363
|
dst: String(p.dst),
|
|
291
364
|
fact: p.fact ? String(p.fact) : undefined,
|
|
292
365
|
scope: 'global',
|
|
366
|
+
prov: 'reflection',
|
|
367
|
+
confidence: 0.4,
|
|
293
368
|
});
|
|
294
369
|
if (r.ok && !r.duplicate)
|
|
295
370
|
profiles++;
|
|
296
371
|
}
|
|
297
372
|
}
|
|
373
|
+
// 用户纠正桶(最高信号):失效同关系旧画像值,以 user_confirmed(1.0,直接 L2)安装新值。
|
|
374
|
+
// 单值关系即便不显式失效旧边,addTriple 也会按 (src,relation) 时序取代;这里多做一步
|
|
375
|
+
// 是为了 old 指向的非单值旧值(prefers/constraint 等多值关系)也能被精准撤回。
|
|
376
|
+
let corrections = 0;
|
|
377
|
+
const profileChangedFacts = [];
|
|
378
|
+
if (Array.isArray(plan.corrections)) {
|
|
379
|
+
let personId = PRIMARY_PERSON_ID;
|
|
380
|
+
try {
|
|
381
|
+
personId = ensurePrimaryPerson().id;
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
personId = PRIMARY_PERSON_ID;
|
|
385
|
+
}
|
|
386
|
+
for (const c of plan.corrections.slice(0, 6)) {
|
|
387
|
+
if (!c?.relation || !c.dst)
|
|
388
|
+
continue;
|
|
389
|
+
const relation = normalizeRelation(String(c.relation));
|
|
390
|
+
if (!isKnownRelation(relation, 'global'))
|
|
391
|
+
relViolations++;
|
|
392
|
+
const oldHint = typeof c.old === 'string' ? c.old.trim() : '';
|
|
393
|
+
invalidateProfileEdges(relation, oldHint || undefined);
|
|
394
|
+
const r = addTriple({
|
|
395
|
+
src: personId,
|
|
396
|
+
relation,
|
|
397
|
+
dst: String(c.dst),
|
|
398
|
+
fact: c.fact ? String(c.fact) : undefined,
|
|
399
|
+
scope: 'global',
|
|
400
|
+
prov: 'user_confirmed',
|
|
401
|
+
confidence: 1,
|
|
402
|
+
});
|
|
403
|
+
if (r.ok && !r.duplicate) {
|
|
404
|
+
corrections++;
|
|
405
|
+
const factText = c.fact ? String(c.fact) : String(c.dst);
|
|
406
|
+
profileChangedFacts.push(factText);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
// 环境证据投票:只能投本轮开始前快照里的边;同 id 一轮一票;不存在/本轮新建的 id 一律
|
|
411
|
+
// 丢弃(防自我强化)。以投票前后的内化态变化识别自动转正/降级。
|
|
412
|
+
let promotions = 0;
|
|
413
|
+
let demotions = 0;
|
|
414
|
+
let evidenceVotes = 0;
|
|
415
|
+
const promotionFacts = [];
|
|
416
|
+
const demotionFacts = [];
|
|
417
|
+
if (Array.isArray(plan.evidence)) {
|
|
418
|
+
const seen = new Set();
|
|
419
|
+
for (const v of plan.evidence.slice(0, 20)) {
|
|
420
|
+
const id = typeof v?.edgeId === 'string' ? v.edgeId.trim() : '';
|
|
421
|
+
if (!id || seen.has(id))
|
|
422
|
+
continue;
|
|
423
|
+
if (!evidenceSnap.votable.has(id))
|
|
424
|
+
continue;
|
|
425
|
+
const vote = typeof v.vote === 'string' ? v.vote.trim().toLowerCase() : '';
|
|
426
|
+
if (vote !== 'confirm' && vote !== 'contradict')
|
|
427
|
+
continue;
|
|
428
|
+
seen.add(id);
|
|
429
|
+
const was = beforeInternalized.has(id);
|
|
430
|
+
const vr = voteEdge(id, vote);
|
|
431
|
+
if (!vr.ok)
|
|
432
|
+
continue;
|
|
433
|
+
evidenceVotes++;
|
|
434
|
+
const eNow = loadScopeGraph('global').edges.find((x) => x.id === id);
|
|
435
|
+
const now = eNow ? isInternalizedEdge(eNow) : false;
|
|
436
|
+
const fact = evidenceSnap.statements.get(id) ?? id;
|
|
437
|
+
if (!was && now) {
|
|
438
|
+
promotions++;
|
|
439
|
+
promotionFacts.push(fact);
|
|
440
|
+
}
|
|
441
|
+
else if (was && !now) {
|
|
442
|
+
demotions++;
|
|
443
|
+
demotionFacts.push(fact);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
298
447
|
const gc = gcMemories();
|
|
299
448
|
result.saves = saves;
|
|
300
449
|
result.updates = updates;
|
|
@@ -302,6 +451,15 @@ export async function runReflection(transcript, signal) {
|
|
|
302
451
|
result.triples = triples;
|
|
303
452
|
result.profiles = profiles;
|
|
304
453
|
result.relViolations = relViolations;
|
|
454
|
+
result.corrections = corrections;
|
|
455
|
+
result.profileChanged = corrections > 0;
|
|
456
|
+
result.profileChangedFacts = profileChangedFacts.slice(0, 3);
|
|
457
|
+
result.promotions = promotions;
|
|
458
|
+
result.promotionFacts = promotionFacts.slice(0, 3);
|
|
459
|
+
result.demotions = demotions;
|
|
460
|
+
result.demotionFacts = demotionFacts.slice(0, 3);
|
|
461
|
+
if (evidenceVotes)
|
|
462
|
+
result.evidenceVotes = evidenceVotes;
|
|
305
463
|
result.gcDecayed = gc.decayed;
|
|
306
464
|
result.gcCapped = gc.capped;
|
|
307
465
|
result.gcGced = gc.gced;
|
|
@@ -318,30 +476,81 @@ function normalizeType(t) {
|
|
|
318
476
|
// ── 后台编排:kickoff / drain / 缓存 ─────────────────────────────────────────
|
|
319
477
|
let inflight = null;
|
|
320
478
|
let lastReflectResult = null;
|
|
321
|
-
/**
|
|
479
|
+
/**
|
|
480
|
+
* 自动反思节流(默认开启后必须配成本闸,否则每 reflectEveryN 轮一个后台 LLM 请求):
|
|
481
|
+
* - 每进程至多 N 次自动反思(/reflect 手动不受限);
|
|
482
|
+
* - 转录里 user 实质内容低于阈值不触发(纯工具轮/空轮没有可记的东西)。
|
|
483
|
+
* env:MOCODE_REFLECT_MAX_PER_SESSION 覆盖次数。
|
|
484
|
+
*/
|
|
485
|
+
const MAX_AUTO_REFLECTS = Math.max(1, Number(process.env.MOCODE_REFLECT_MAX_PER_SESSION) || 3);
|
|
486
|
+
const MIN_USER_CHARS = 40;
|
|
487
|
+
let autoReflectCount = 0;
|
|
488
|
+
/** 转录里是否有足够的"用户原话"值得反思(tool_call/assistant 行不计)。 */
|
|
489
|
+
export function hasSubstantialUserContent(transcript) {
|
|
490
|
+
const userText = transcript
|
|
491
|
+
.split('\n')
|
|
492
|
+
.filter((line) => line.startsWith('user:'))
|
|
493
|
+
.map((line) => line.slice(5).trim())
|
|
494
|
+
.join(' ')
|
|
495
|
+
.trim();
|
|
496
|
+
return userText.length >= MIN_USER_CHARS;
|
|
497
|
+
}
|
|
498
|
+
/** 测试专用:重置自动反思计数。 */
|
|
499
|
+
export function __resetReflectThrottleForTests() {
|
|
500
|
+
autoReflectCount = 0;
|
|
501
|
+
}
|
|
502
|
+
/** 摘要串(供 repl flush):存N 改N 忘N 图N [画像N 纠N 违N];有错误附上。 */
|
|
322
503
|
export function formatReflectResult(r) {
|
|
323
504
|
const parts = [`存${r.saves}`, `改${r.updates}`, `忘${r.forgets}`, `图${r.triples}`];
|
|
324
505
|
if (r.profiles)
|
|
325
|
-
parts.push(
|
|
506
|
+
parts.push(`画像候选${r.profiles}`);
|
|
507
|
+
if (r.corrections)
|
|
508
|
+
parts.push(`纠正${r.corrections}`);
|
|
509
|
+
if (r.promotions)
|
|
510
|
+
parts.push(`印证转正${r.promotions}`);
|
|
511
|
+
if (r.demotions)
|
|
512
|
+
parts.push(`反证降级${r.demotions}`);
|
|
326
513
|
if (r.relViolations)
|
|
327
514
|
parts.push(`违${r.relViolations}`);
|
|
328
515
|
if (r.gcDecayed || r.gcCapped || r.gcGced) {
|
|
329
516
|
parts.push(`遗忘(衰减${r.gcDecayed}/封顶${r.gcCapped}/清除${r.gcGced})`);
|
|
330
517
|
}
|
|
331
|
-
|
|
518
|
+
let line = `记忆反思:${parts.join(' ')}${r.error ? ` [${r.error}]` : ''}`;
|
|
519
|
+
// 关于人的信念被改动必须让用户有机会否决(区别于仓库事实的静默写入)。
|
|
520
|
+
// 不加 ANSI:repl flush 时整串已包 ui.gray。
|
|
521
|
+
if (r.profileChanged && r.profileChangedFacts?.length) {
|
|
522
|
+
line += `\n ↳ 已按你的纠正更新长期画像:${r.profileChangedFacts.join(';')}(/memory profile 可查看或撤销)`;
|
|
523
|
+
}
|
|
524
|
+
// 信念分级的自动升降级同样必须透明:它们改了常驻画像却没经过显式批准,要给用户否决机会。
|
|
525
|
+
if (r.promotions && r.promotionFacts?.length) {
|
|
526
|
+
line += `\n ↳ 多次行为印证,已自动内化:${r.promotionFacts.join(';')}(/memory drop 可撤销)`;
|
|
527
|
+
}
|
|
528
|
+
if (r.demotions && r.demotionFacts?.length) {
|
|
529
|
+
line += `\n ↳ 与近期行为反复相悖,已退回候选:${r.demotionFacts.join(';')}(/memory confirm 可恢复)`;
|
|
530
|
+
}
|
|
531
|
+
return line;
|
|
332
532
|
}
|
|
333
533
|
/**
|
|
334
|
-
* fire-and-forget 触发反思。已有在飞任务 /
|
|
534
|
+
* fire-and-forget 触发反思。已有在飞任务 / 记忆子系统总开关关闭 → 跳过。
|
|
535
|
+
* 自动触发(manual=false)还受两道成本闸:config.autoReflect 开关、每进程次数上限、
|
|
536
|
+
* 转录需含足够用户原话;手动 /reflect(manual=true)绕过前两道(仍要求记忆开关开)。
|
|
335
537
|
* 记忆关闭时反思毫无意义(没有可存的地方),且会误打日志、误弹摘要,故一并短路。
|
|
336
538
|
* repl 轮末调:与下一轮 agent 并发跑,不阻塞。
|
|
337
539
|
*/
|
|
338
|
-
export function kickoffReflection(transcript) {
|
|
540
|
+
export function kickoffReflection(transcript, manual = false) {
|
|
339
541
|
if (inflight)
|
|
340
542
|
return;
|
|
341
|
-
if (!config.autoReflect)
|
|
342
|
-
return;
|
|
343
543
|
if (!isMemoryEnabled())
|
|
344
544
|
return;
|
|
545
|
+
if (!manual) {
|
|
546
|
+
if (!config.autoReflect)
|
|
547
|
+
return;
|
|
548
|
+
if (autoReflectCount >= MAX_AUTO_REFLECTS)
|
|
549
|
+
return;
|
|
550
|
+
if (!hasSubstantialUserContent(transcript))
|
|
551
|
+
return;
|
|
552
|
+
autoReflectCount++;
|
|
553
|
+
}
|
|
345
554
|
inflight = (async () => {
|
|
346
555
|
try {
|
|
347
556
|
const r = await runReflection(transcript);
|
|
@@ -65,6 +65,21 @@ export const RELATION_ALIASES = {
|
|
|
65
65
|
};
|
|
66
66
|
const PROJECT_SET = new Set(PROJECT_RELATIONS);
|
|
67
67
|
const PROFILE_SET = new Set(PROFILE_RELATIONS);
|
|
68
|
+
/**
|
|
69
|
+
* 画像轨的**单值关系**(Wikidata single-value 约束的最小落地):同一主语在该关系上
|
|
70
|
+
* 只允许一条 active 边——写入新值(哪怕 dst 不同,如换城市/换工作)时,同 src+relation
|
|
71
|
+
* 的旧边一律时序失效。多值关系(prefers / has_hobby / constraint…)不在此列。
|
|
72
|
+
*/
|
|
73
|
+
const PROFILE_SINGLE_VALUE = new Set([
|
|
74
|
+
'named',
|
|
75
|
+
'has_role',
|
|
76
|
+
'works_at',
|
|
77
|
+
'located_in',
|
|
78
|
+
'speaks',
|
|
79
|
+
'verbosity',
|
|
80
|
+
'communication_style',
|
|
81
|
+
'current_goal',
|
|
82
|
+
]);
|
|
68
83
|
/** 关系名归一:lowercase + 空白转下划线 + 别名映射。 */
|
|
69
84
|
export function normalizeRelation(raw) {
|
|
70
85
|
const base = String(raw ?? '')
|
|
@@ -78,6 +93,10 @@ export function isKnownRelation(relation, scope) {
|
|
|
78
93
|
const r = normalizeRelation(relation);
|
|
79
94
|
return scope === 'global' ? PROFILE_SET.has(r) : PROJECT_SET.has(r);
|
|
80
95
|
}
|
|
96
|
+
/** 画像关系是否单值(换值即作废旧边;先归一再判定)。 */
|
|
97
|
+
export function isSingleValueProfile(relation) {
|
|
98
|
+
return PROFILE_SINGLE_VALUE.has(normalizeRelation(relation));
|
|
99
|
+
}
|
|
81
100
|
/** 注入反思提示词的紧凑词表(按 scope)。 */
|
|
82
101
|
export function relationCheatSheet(scope) {
|
|
83
102
|
return scope === 'global' ? PROFILE_RELATIONS.join(', ') : PROJECT_RELATIONS.join(', ');
|
package/dist/memory/store.js
CHANGED
|
@@ -225,6 +225,25 @@ export function updateEntry(id, patch) {
|
|
|
225
225
|
writeAtomic(p, entries);
|
|
226
226
|
return { ok: true };
|
|
227
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* 把旧条目标记为被新条目取代(status=superseded + supersededBy 链,不删除可审计)。
|
|
230
|
+
* 与 forgetEntry 的区别:这是 belief-revision 语义——"旧信念被新事实取代",
|
|
231
|
+
* 而不是"过期清理"。pinned 条目同样允许被取代(取代链是显式修正,不是自动遗忘)。
|
|
232
|
+
*/
|
|
233
|
+
export function supersedeEntry(oldId, newId, reason) {
|
|
234
|
+
const all = loadAll();
|
|
235
|
+
const oldE = all.find((x) => x.id === oldId);
|
|
236
|
+
if (!oldE)
|
|
237
|
+
return { ok: false, notFound: true };
|
|
238
|
+
oldE.status = 'superseded';
|
|
239
|
+
oldE.supersededBy = newId;
|
|
240
|
+
oldE.updatedAt = nowIso();
|
|
241
|
+
if (reason)
|
|
242
|
+
oldE.lastUpdateReason = reason;
|
|
243
|
+
const p = pathForScope(oldE.scope);
|
|
244
|
+
writeAtomic(p, all.filter((x) => x.scope === oldE.scope));
|
|
245
|
+
return { ok: true };
|
|
246
|
+
}
|
|
228
247
|
/** 归档(默认,可复活)/ 硬删;pinned 拒删。 */
|
|
229
248
|
export function forgetEntry(id, mode = 'archive') {
|
|
230
249
|
const all = loadAll();
|
|
@@ -1,14 +1,54 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 记忆命令组:/memory · /reflect
|
|
2
|
+
* 记忆命令组:/memory · /reflect · /memory profile|confirm|drop
|
|
3
3
|
*
|
|
4
|
-
* 只读概览 +
|
|
5
|
-
*
|
|
4
|
+
* 只读概览 + 后台反思触发 + 长期画像检视/纠错。/memory_switch /memory_status 是
|
|
5
|
+
* **配置写入**命令,与 /subagent /fe /mcp 同属 tool-group,放 tool-group.ts,不在这里。
|
|
6
|
+
* 注意:顶层 /profile 被刻意禁用(见 tests/tool-profiles.test.ts),画像命令并入 /memory 组。
|
|
6
7
|
*/
|
|
7
8
|
import * as layout from '../../ui/layout.js';
|
|
8
9
|
import { ui } from '../../ui/theme.js';
|
|
9
10
|
import { isMemoryEnabled } from '../../config/index.js';
|
|
10
|
-
import {
|
|
11
|
+
import { getAgentMode } from '../../agent/mode.js';
|
|
12
|
+
import { kickoffReflection, snapshotTranscript, loadAll, listInternalizedProfile, listProfileCandidates, promoteEdge, invalidateEdge, } from '../../memory/index.js';
|
|
11
13
|
import { unhandled, next } from './types.js';
|
|
14
|
+
/** /profile 改动画像后,让 About you 段(history[0])立刻反映,不用等重启。 */
|
|
15
|
+
function refreshSystemPrompt(ctx) {
|
|
16
|
+
ctx.history[0] = { role: 'system', content: ctx.buildSystemMessage(getAgentMode() === 'plan') };
|
|
17
|
+
ctx.refreshStatusBase(ctx.history);
|
|
18
|
+
}
|
|
19
|
+
/** 渲染 /profile:已内化(L2)与待确认候选(L1)两段。 */
|
|
20
|
+
function renderProfile() {
|
|
21
|
+
const internalized = listInternalizedProfile();
|
|
22
|
+
const candidates = listProfileCandidates();
|
|
23
|
+
const ev = (e) => {
|
|
24
|
+
const c = e?.confirmed ?? 0;
|
|
25
|
+
const x = e?.contradicted ?? 0;
|
|
26
|
+
return c || x ? ` [印证${c}/相悖${x}]` : '';
|
|
27
|
+
};
|
|
28
|
+
const lines = [];
|
|
29
|
+
lines.push(`${ui.accent}长期画像(已内化,每轮常驻 About you)${ui.reset}`);
|
|
30
|
+
if (internalized.length === 0) {
|
|
31
|
+
lines.push(`${ui.dim} (暂无;用户亲述/确认,或多次行为印证零反驳的稳定事实才会进这里)${ui.reset}`);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
for (const c of internalized) {
|
|
35
|
+
lines.push(` ${ui.accent}${c.edge.id}${ui.reset} ${c.text}${ui.dim}${ev(c.edge.evidence)}${ui.reset}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
lines.push('');
|
|
39
|
+
lines.push(`${ui.accent}待确认候选(反思推断,未内化、不常驻)${ui.reset}`);
|
|
40
|
+
if (candidates.length === 0) {
|
|
41
|
+
lines.push(`${ui.dim} (暂无)${ui.reset}`);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
for (const c of candidates) {
|
|
45
|
+
lines.push(` ${ui.dim}${c.edge.id}${ui.reset} ${c.text} ${ui.dim}[conf ${c.edge.confidence ?? '?'}${ev(c.edge.evidence)}]${ui.reset}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
lines.push('');
|
|
49
|
+
lines.push(`${ui.dim}/memory confirm <edge-id> 确认候选并内化 · /memory drop <edge-id> 撤销某条${ui.reset}`);
|
|
50
|
+
return lines.join('\n') + '\n';
|
|
51
|
+
}
|
|
12
52
|
export const memoryCommands = [
|
|
13
53
|
(ctx) => {
|
|
14
54
|
if (ctx.line !== '/memory')
|
|
@@ -44,8 +84,53 @@ export const memoryCommands = [
|
|
|
44
84
|
return next();
|
|
45
85
|
}
|
|
46
86
|
// 手动触发后台反思 pass(不等;完成后下次 INPUT 态显摘要)。
|
|
47
|
-
|
|
87
|
+
// manual=true:绕过自动节流(次数/转录闸门),但记忆总开关关闭时仍短路。
|
|
88
|
+
kickoffReflection(snapshotTranscript(ctx.history, 20), true);
|
|
48
89
|
layout.contentWrite(`${ui.dim}(反思已触发,后台进行;完成后下次输入态显示摘要。日志见 .mocode/memory.log)${ui.reset}\n`);
|
|
49
90
|
return next();
|
|
50
91
|
},
|
|
92
|
+
(ctx) => {
|
|
93
|
+
if (ctx.line !== '/memory profile')
|
|
94
|
+
return unhandled();
|
|
95
|
+
if (!isMemoryEnabled()) {
|
|
96
|
+
layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory profile 无效。用 /memory_switch 打开)${ui.reset}\n`);
|
|
97
|
+
return next();
|
|
98
|
+
}
|
|
99
|
+
layout.contentWrite(renderProfile());
|
|
100
|
+
return next();
|
|
101
|
+
},
|
|
102
|
+
(ctx) => {
|
|
103
|
+
if (!ctx.line.startsWith('/memory confirm'))
|
|
104
|
+
return unhandled();
|
|
105
|
+
const edgeId = ctx.line.slice('/memory confirm'.length).trim();
|
|
106
|
+
if (!edgeId) {
|
|
107
|
+
layout.contentWrite(`${ui.dim}用法:/memory confirm <edge-id>(先 /memory profile 看候选)${ui.reset}\n`);
|
|
108
|
+
return next();
|
|
109
|
+
}
|
|
110
|
+
const r = promoteEdge(edgeId);
|
|
111
|
+
if (!r.ok) {
|
|
112
|
+
layout.contentWrite(`${ui.dim}(确认失败:${r.reason})${ui.reset}\n`);
|
|
113
|
+
return next();
|
|
114
|
+
}
|
|
115
|
+
refreshSystemPrompt(ctx);
|
|
116
|
+
layout.contentWrite(`${ui.dim}(已确认并内化 [${edgeId}],下一轮起常驻 About you)${ui.reset}\n`);
|
|
117
|
+
return next();
|
|
118
|
+
},
|
|
119
|
+
(ctx) => {
|
|
120
|
+
if (!ctx.line.startsWith('/memory drop'))
|
|
121
|
+
return unhandled();
|
|
122
|
+
const edgeId = ctx.line.slice('/memory drop'.length).trim();
|
|
123
|
+
if (!edgeId) {
|
|
124
|
+
layout.contentWrite(`${ui.dim}用法:/memory drop <edge-id>(先 /memory profile 看列表)${ui.reset}\n`);
|
|
125
|
+
return next();
|
|
126
|
+
}
|
|
127
|
+
const r = invalidateEdge(edgeId, 'profile-dropped');
|
|
128
|
+
if (!r.ok) {
|
|
129
|
+
layout.contentWrite(`${ui.dim}(撤销失败:${r.reason})${ui.reset}\n`);
|
|
130
|
+
return next();
|
|
131
|
+
}
|
|
132
|
+
refreshSystemPrompt(ctx);
|
|
133
|
+
layout.contentWrite(`${ui.dim}(已撤销画像 [${edgeId}],时序失效、可审计;下一轮 About you 不再含它)${ui.reset}\n`);
|
|
134
|
+
return next();
|
|
135
|
+
},
|
|
51
136
|
];
|
package/dist/repl/commands.js
CHANGED
|
@@ -44,6 +44,9 @@ export function buildSlashCommands() {
|
|
|
44
44
|
{ name: 'off', value: '/memory_switch off', desc: d('commands.memoryOff') },
|
|
45
45
|
{ name: 'status', value: '/memory_status', desc: d('commands.memoryStatus') },
|
|
46
46
|
{ name: 'reflect', value: '/reflect', desc: d('commands.memoryReflect') },
|
|
47
|
+
{ name: 'profile', value: '/memory profile', desc: d('commands.memoryProfile') },
|
|
48
|
+
{ name: 'confirm', value: '/memory confirm ', submit: false, desc: d('commands.memoryProfileConfirm') },
|
|
49
|
+
{ name: 'drop', value: '/memory drop ', submit: false, desc: d('commands.memoryProfileDrop') },
|
|
47
50
|
],
|
|
48
51
|
},
|
|
49
52
|
{ name: '/init', desc: d('commands.memoryInit') },
|