mocode-ai 1.8.9 → 1.8.10

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.
Files changed (53) hide show
  1. package/dist/agent/index.js +17 -17
  2. package/dist/agent/model-turn.js +8 -4
  3. package/dist/agent/run-coordinator.js +6 -0
  4. package/dist/agent/spawn.js +8 -4
  5. package/dist/agent/stages/tool-dispatcher.js +31 -11
  6. package/dist/changeset/hash.js +17 -0
  7. package/dist/changeset/index.js +6 -10
  8. package/dist/context/text-search.js +28 -10
  9. package/dist/flows/cli.js +1 -1
  10. package/dist/flows/flow.js +1 -1
  11. package/dist/flows/trace.js +1 -1
  12. package/dist/headless.js +23 -0
  13. package/dist/index.js +1 -1
  14. package/dist/memory/anchor.js +319 -0
  15. package/dist/memory/audit.js +65 -0
  16. package/dist/memory/episodic.js +546 -0
  17. package/dist/memory/graph.js +233 -9
  18. package/dist/memory/health.js +208 -0
  19. package/dist/memory/index.js +12 -3
  20. package/dist/memory/pending.js +269 -0
  21. package/dist/memory/portable.js +150 -0
  22. package/dist/memory/proactive.js +588 -0
  23. package/dist/memory/recall-stats.js +1 -1
  24. package/dist/memory/reflect.js +260 -6
  25. package/dist/memory/relation-vocab.js +26 -4
  26. package/dist/memory/store.js +587 -41
  27. package/dist/memory/tail.js +88 -0
  28. package/dist/memory/write-gate.js +44 -0
  29. package/dist/permissions/computer-review.js +1 -1
  30. package/dist/permissions/flow-review.js +1 -1
  31. package/dist/repl/commands/flow.js +1 -1
  32. package/dist/repl/commands/memory.js +257 -6
  33. package/dist/repl/commands/session.js +13 -0
  34. package/dist/repl/commands/tool-group.js +6 -0
  35. package/dist/repl/episode-finalize.js +55 -0
  36. package/dist/repl/runtime.js +41 -3
  37. package/dist/runtime/uia-selector.js +1 -1
  38. package/dist/runtime/uia-service.js +3 -3
  39. package/dist/runtime/wait-until.js +1 -1
  40. package/dist/runtime/window-list.js +1 -1
  41. package/dist/sandbox/policy.js +49 -0
  42. package/dist/session/compact.js +47 -12
  43. package/dist/session/gui-actions.js +1 -1
  44. package/dist/tools/builtins/computer.js +5 -5
  45. package/dist/tools/builtins/memory-graph.js +12 -1
  46. package/dist/tools/builtins/memory-list.js +13 -3
  47. package/dist/tools/builtins/memory-save.js +82 -2
  48. package/dist/tools/builtins/memory-search.js +57 -2
  49. package/dist/tools/builtins/memory-update.js +52 -1
  50. package/dist/tools/builtins/read-file.js +51 -2
  51. package/dist/tools/builtins/run-flow.js +1 -1
  52. package/dist/tools/constants.js +60 -0
  53. package/package.json +6 -1
@@ -12,10 +12,12 @@ 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, supersedeEntry, loadAll, gcMemories } from './store.js';
15
+ import { saveEntry, updateEntry, forgetEntry, supersedeEntry, loadAll, loadStalenessMap, gcMemories, wantsTrigger, } from './store.js';
16
16
  import { addTriple, ensurePrimaryPerson, invalidateProfileEdges, voteEdge, loadScopeGraph, PRIMARY_PERSON_ID, } from './graph.js';
17
17
  import { isInternalizedEdge } from './persona.js';
18
18
  import { normalizeRelation, isKnownRelation, relationCheatSheet } from './relation-vocab.js';
19
+ import { formatPendingForReflect, loadPendingCandidates, trimPendingCandidates } from './pending.js';
20
+ import { applyConsolidation, findConsolidationGroups, isConsolidationEnabled, } from './episodic.js';
19
21
  // ── 日志(静默容错,裁尾保最近)─────────────────────────────────────────────
20
22
  function logPath() {
21
23
  return path.join(process.cwd(), '.mocode', 'memory.log');
@@ -76,6 +78,9 @@ function buildMemorySample() {
76
78
  const all = loadAll().filter((e) => e.status === 'active');
77
79
  if (all.length === 0)
78
80
  return '(无)';
81
+ // R14:派生条目要带上失效标记。反思看到"这条的根据已经变了"才会去复核或改写,
82
+ // 否则它会拿一条 stale 的抽象结论去跟新事实较劲(甚至因"不矛盾"而继续保留它)。
83
+ const stale = loadStalenessMap();
79
84
  const byCreated = [...all].sort((a, b) => (a.createdAt || '').localeCompare(b.createdAt || ''));
80
85
  const byRecall = [...all].sort((a, b) => a.recallCount - b.recallCount);
81
86
  const picked = new Map();
@@ -87,7 +92,19 @@ function buildMemorySample() {
87
92
  return list
88
93
  .map((e) => {
89
94
  const body = e.body.length > 600 ? e.body.slice(0, 586) + '…[截断]' : e.body;
90
- return `[${e.id}] ${e.name} (${e.type}, recalled ${e.recallCount})\nsummary: ${e.summary}\nbody: ${body}`;
95
+ // R3:把 trigger 现状一并给模型看。缺 trigger 的条件式条目在反思样本里显式标出,
96
+ // 模型才知道有机会借 updates 补上(否则 propmpt 里那条"可事后补 trigger"永远无从触发)。
97
+ const when = e.trigger ? `trigger: ${e.trigger}` : '';
98
+ const gap = !e.trigger && wantsTrigger(e.type) ? 'trigger: (缺,可借 updates 补)' : '';
99
+ const st = stale.get(e.id);
100
+ const staleNote = st?.stale
101
+ ? `derivedFrom: ${(e.derivedFrom ?? []).join(', ')} — 其中已失效: ${[
102
+ ...st.inactive,
103
+ ...st.missing.map((m) => `${m}(已删)`),
104
+ ].join(', ')} [此条可能已过期,请复核后 update 或 forget]`
105
+ : '';
106
+ const tail = [when, gap, e.action ? `action: ${e.action}` : '', staleNote].filter(Boolean).join('\n');
107
+ return `[${e.id}] ${e.name} (${e.type}, recalled ${e.recallCount})\nsummary: ${e.summary}\n${tail ? tail + '\n' : ''}body: ${body}`;
91
108
  })
92
109
  .join('\n---\n');
93
110
  }
@@ -131,7 +148,7 @@ const REFLECT_TIMEOUT_MS = 60_000;
131
148
  */
132
149
  const REFLECT_MAX_ATTEMPTS = 3;
133
150
  const REFLECT_SYS = `You are mocode's memory reflector. Review the recent session and existing memories, producing **only** updates worth remembering long-term.
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":"..."}]}
151
+ Output strictly JSON (no markdown code blocks, no explanatory text): {"saves":[{"type":"...","name":"...","summary":"...","body":"...","trigger":"...","action":"...","supersedes":"old-id-or-empty","derivedFrom":["existing-id"]}],"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":"..."}]}
135
152
  Empty arrays are valid (if nothing is worth saving, all arrays are empty).
136
153
  Rules:
137
154
  ① Only store non-obvious, cross-session-useful facts/decisions/pitfalls; do not store current bugs, temp files, undecided TODOs, or volatile items;
@@ -143,8 +160,11 @@ Rules:
143
160
  ⑦ 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).
144
161
  ⑧ 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
162
  ⑨ 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:`;
163
+ ⑩ 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.
164
+ ⑪ trigger/action — memory entries are CONDITION→ACTION, not just description. For pitfall / decision / feedback saves, write "trigger" = the SITUATION in which this will matter again, phrased as a condition a future session can recognise from its current task (e.g. "constructing a tool schema for kimi-k3 via dashscope compatible-mode", not "when editing code"), and "action" = what to DO once it holds. A vague trigger is WORSE than none — it pollutes proactive matching. Leaving trigger empty is correct when you genuinely cannot predict the situation: it will be filled in later, once the situation actually recurs. fact/reference usually need no trigger. You MAY also fill a missing trigger on an EXISTING entry via updates (just pass "trigger") when this session showed the real situation and the entry currently has none — that is the expected way to complete R1.5 after the fact; do not rewrite an entry's trigger merely to make it prettier.
165
+ ⑫ derivedFrom — when a save GENERALIZES several existing memories into one abstraction (the same lesson learned in 3 different places), put their ids in that save's "derivedFrom". Do NOT use it for a save that merely cites or supersedes a single entry (that is what "supersedes" is for). Only ids from the "existing memories" list are accepted; self-references and unknowns are dropped. Rationale: the derived entry then carries a live link back to its sources, so the system can tell a future session "the evidence behind this has changed" without deleting an abstraction that may still be true. Most saves should leave it empty.
166
+ ⑬ anchors — when a save describes HOW a specific piece of code works (a function's contract, a file's structure, a const's meaning, a call-order invariant), attach "anchors": [{"path":"src/foo/bar.ts","symbol":"functionOrConstName"}]. Paths are workspace-relative with forward slashes. Add a symbol whenever the fact is about one function/class/const — that keeps unrelated edits in the same file from marking it stale. Leave anchors empty for anything that is not about specific code (user preferences, process decisions, external services, tool-usage pitfalls). You do NOT write hashes: the content hash is captured at write time, and a later edit to that code makes the memory surface as STALE-CODE instead of silently serving an outdated fact. Paths/symbols that cannot be resolved are dropped. Anchors are the ONE channel that makes memory notice the code moved underneath it — use them whenever the memory would be wrong or misleading after a refactor.`;
167
+ const REFLECT_USER = (transcript, sample, profileEdges, pending = '') => `## 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${pending}\n\nProduce JSON:`;
148
168
  export function parsePlan(content) {
149
169
  if (!content)
150
170
  return null;
@@ -208,15 +228,22 @@ async function fetchReflection(messages, signal) {
208
228
  export async function runReflection(transcript, signal) {
209
229
  const ts = new Date().toISOString();
210
230
  const sample = buildMemorySample();
231
+ // R14:本轮开始前已存在的条目 id 集合。derivedFrom 只接受其中真实存在的 id——
232
+ // 模型偶尔会编 id,而编出来的 id 在 computeStaleness 里恒判 missing,
233
+ // 等于让这条新记忆天生就带 stale 标记。
234
+ const knownIds = new Set(loadAll().map((e) => e.id));
211
235
  // 本轮开始前的画像边快照:evidence 票只能投给这些 id(本轮新建边无法自我投票)。
212
236
  const evidenceSnap = buildProfileEvidenceSnapshot();
213
237
  const beforeInternalized = new Set(loadScopeGraph('global')
214
238
  .edges.filter((e) => evidenceSnap.votable.has(e.id) && isInternalizedEdge(e))
215
239
  .map((e) => e.id));
216
240
  const sys = { role: 'system', content: REFLECT_SYS };
241
+ // R13.3:压缩交接过来的候选。**读一次、只在成功裁决后清空**——反思失败(超时/解析失败)
242
+ // 时保留队列,下一轮还能再试;否则一次网络抖动就把压缩捞出的推理链永久丢掉。
243
+ const pending = loadPendingCandidates();
217
244
  const user = {
218
245
  role: 'user',
219
- content: REFLECT_USER(transcript, sample, evidenceSnap.text),
246
+ content: REFLECT_USER(transcript, sample, evidenceSnap.text, formatPendingForReflect(pending)),
220
247
  };
221
248
  const result = {
222
249
  ts,
@@ -284,6 +311,25 @@ export async function runReflection(transcript, signal) {
284
311
  summary: String(s.summary),
285
312
  body: String(s.body ?? s.summary),
286
313
  type: normalizeType(s.type),
314
+ trigger: s.trigger ? String(s.trigger) : undefined,
315
+ action: s.action ? String(s.action) : undefined,
316
+ // R14:归纳来源。只接受 existing memories 里真实存在的 id——模型偶尔会编 id,
317
+ // 而编出来的 id 在 computeStaleness 里恒判 missing,等于让这条记忆天生 stale。
318
+ // 这里不静默吞掉,而是过滤掉未知项(saveEntry 内部再滤自引用与重复)。
319
+ derivedFrom: Array.isArray(s.derivedFrom)
320
+ ? s.derivedFrom.map((x) => String(x ?? '').trim()).filter((x) => x && knownIds.has(x))
321
+ : undefined,
322
+ // R2:代码锚点。与 derivedFrom 同理只做**形状过滤**——path/symbol 指向不存在的
323
+ // 文件或符号时由 buildAnchors 丢弃(saveEntry 内),这里不预先校验:多一次
324
+ // 文件系统遍历,而且"文件暂时不存在"不该让整条记忆保存失败。
325
+ anchors: Array.isArray(s.anchors)
326
+ ? s.anchors
327
+ .map((a) => ({
328
+ path: String(a?.path ?? '').trim(),
329
+ symbol: a?.symbol ? String(a.symbol).trim() : undefined,
330
+ }))
331
+ .filter((a) => a.path)
332
+ : undefined,
287
333
  });
288
334
  if (r.ok) {
289
335
  saves++;
@@ -304,6 +350,9 @@ export async function runReflection(transcript, signal) {
304
350
  summary: u.summary ? String(u.summary) : undefined,
305
351
  body: u.body ? String(u.body) : undefined,
306
352
  reason: u.reason ? String(u.reason) : undefined,
353
+ // R1.5.5 存量兼容:老条目按 updates 逐批补 trigger,不阻断读取。
354
+ trigger: typeof u.trigger === 'string' ? u.trigger : undefined,
355
+ action: typeof u.action === 'string' ? u.action : undefined,
307
356
  });
308
357
  if (r.ok)
309
358
  updates++;
@@ -322,6 +371,7 @@ export async function runReflection(transcript, signal) {
322
371
  // 关系名先归一(别名/拼写);词表外关系仍允许写(软封闭世界),但计 relViolations 供观测。
323
372
  let triples = 0;
324
373
  let relViolations = 0;
374
+ let scopeEscalated = 0;
325
375
  if (Array.isArray(plan.triples)) {
326
376
  for (const t of plan.triples.slice(0, 10)) {
327
377
  if (!t?.src || !t?.relation || !t?.dst)
@@ -329,11 +379,17 @@ export async function runReflection(transcript, signal) {
329
379
  const relation = normalizeRelation(String(t.relation));
330
380
  if (!isKnownRelation(relation, 'project'))
331
381
  relViolations++;
382
+ // 溯源:项目三元组同样由反思**推断**而来,与 global 画像一致地落 prov/confidence。
383
+ // 此前漏传导致项目图全部边 prov 为空,两轴模型(declared/inferred)在项目格无法生效。
384
+ // sourceEntry 保持 null:三元组源自会话转录,不对应任何内存条目的 id,伪造会污染溯源链。
332
385
  const r = addTriple({
333
386
  src: String(t.src),
334
387
  relation,
335
388
  dst: String(t.dst),
336
389
  fact: t.fact ? String(t.fact) : undefined,
390
+ scope: 'project',
391
+ prov: 'reflection',
392
+ confidence: 0.4,
337
393
  });
338
394
  if (r.ok && !r.duplicate)
339
395
  triples++;
@@ -366,6 +422,9 @@ export async function runReflection(transcript, signal) {
366
422
  prov: 'reflection',
367
423
  confidence: 0.4,
368
424
  });
425
+ // 目标形如本仓库源码路径 → addTriple 已确定性改判到 project(画像轨收不下它)。
426
+ if (r.ok && r.scopeEscalated)
427
+ scopeEscalated++;
369
428
  if (r.ok && !r.duplicate)
370
429
  profiles++;
371
430
  }
@@ -444,6 +503,13 @@ export async function runReflection(transcript, signal) {
444
503
  }
445
504
  }
446
505
  }
506
+ // R13.3:本轮成功裁决了这批候选 → 从队列里删掉**这一批**。传候选本身而不是条数:
507
+ // 队列有 40 条上限,满队时反思期间新增的候选把最旧的挤出去、长度不变,
508
+ // 按条数切会把整队清空并连带删掉这一轮没看过的新候选。失败路径早已 return,队列原样保留。
509
+ if (pending.length > 0) {
510
+ trimPendingCandidates(pending);
511
+ result.pendingConsumed = pending.length;
512
+ }
447
513
  const gc = gcMemories();
448
514
  result.saves = saves;
449
515
  result.updates = updates;
@@ -451,6 +517,8 @@ export async function runReflection(transcript, signal) {
451
517
  result.triples = triples;
452
518
  result.profiles = profiles;
453
519
  result.relViolations = relViolations;
520
+ if (scopeEscalated)
521
+ result.scopeEscalated = scopeEscalated;
454
522
  result.corrections = corrections;
455
523
  result.profileChanged = corrections > 0;
456
524
  result.profileChangedFacts = profileChangedFacts.slice(0, 3);
@@ -586,3 +654,189 @@ export function getLastReflectResult() {
586
654
  export function clearLastReflectResult() {
587
655
  lastReflectResult = null;
588
656
  }
657
+ const CONSOLIDATE_SYS = `You are mocode's sleep-time consolidator. You are given SEVERAL past working sessions from the same workspace that appear to share a theme. Your job: decide whether they really share a reusable lesson, and if so, state it ONCE as a durable memory.
658
+
659
+ Output strictly JSON (no markdown fences, no explanation):
660
+ {"skip":false,"type":"...","name":"...","summary":"...","body":"...","trigger":"...","action":"..."}
661
+ or, when these sessions share no real lesson:
662
+ {"skip":true,"reason":"..."}
663
+
664
+ Rules:
665
+ ① **Generalize only what actually recurs.** These episodes came from different sessions; the value is the pattern a future session can reuse. Do NOT just restate what each session did.
666
+ ② **If they merely touched the same files for unrelated reasons, output {"skip":true}.** A false generalization is worse than no memory: it turns coincidence into a rule. The "shared signals" section lists why they were grouped — use it as a hint, not as proof.
667
+ ③ Keep every concrete detail that would make the conclusion wrong when omitted (the actual constraint, the actual cause, the actual command/path). Drop the story: which session, in what order, how many times.
668
+ ④ type ∈ {${TYPES}}. Choose by nature: a repeatable approach → decision; something that bites → pitfall; a stable structural fact → fact; a preference/expectation of the user → feedback; external knowledge → reference.
669
+ ⑤ name: short, lowercase-kebab or a concise phrase, distinct from existing memories.
670
+ ⑥ summary: one line (< 120 chars) — the reusable claim itself.
671
+ ⑦ body: 3-6 lines. State the pattern, then the evidence in one line (e.g. "seen in 3 sessions across 2 weeks"), then the boundary (when it does NOT hold).
672
+ ⑧ trigger/action: for pitfall/decision/feedback, trigger = the SITUATION a future session can recognise from its current task; action = what to do then. Vague triggers ("when editing code") are worse than empty — omit them instead.
673
+ ⑨ Never mention memory ids, session ids, or that this came from consolidation. The entry must read as knowledge, not as a bookkeeping artifact.`;
674
+ function consolidatePrompt(group) {
675
+ const signals = [`sessions: ${group.sessions}`, `episodes: ${group.members.length}`];
676
+ if (group.sharedFiles.length > 0)
677
+ signals.push(`shared files: ${group.sharedFiles.join(', ')}`);
678
+ if (group.sharedTokens.length > 0)
679
+ signals.push(`shared terms: ${group.sharedTokens.join(', ')}`);
680
+ return {
681
+ role: 'user',
682
+ content: `## Sessions that appear to share a theme\n${group.input}\n\n## Shared signals\n${signals.join('\n')}\n\nProduce JSON:`,
683
+ };
684
+ }
685
+ /** 解析巩固产物。`skip` 与残缺 JSON 都返回 null 之外的可判别结果。 */
686
+ export function parseConsolidationPlan(content) {
687
+ if (!content)
688
+ return null;
689
+ let s = content.trim();
690
+ const fences = [...s.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
691
+ if (fences.length)
692
+ s = fences[fences.length - 1][1].trim();
693
+ const first = s.indexOf('{');
694
+ const last = s.lastIndexOf('}');
695
+ if (first >= 0 && last > first)
696
+ s = s.slice(first, last + 1);
697
+ let p;
698
+ try {
699
+ p = JSON.parse(s.replace(/,\s*([}\]])/g, '$1'));
700
+ }
701
+ catch {
702
+ return null;
703
+ }
704
+ if (!p || typeof p !== 'object')
705
+ return null;
706
+ if (p.skip === true)
707
+ return { skip: true, reason: typeof p.reason === 'string' ? p.reason : undefined };
708
+ const str = (v) => (typeof v === 'string' ? v.trim() : '');
709
+ const draft = {
710
+ type: normalizeType(p.type),
711
+ name: str(p.name),
712
+ summary: str(p.summary),
713
+ body: str(p.body),
714
+ trigger: str(p.trigger) || undefined,
715
+ action: str(p.action) || undefined,
716
+ };
717
+ // name/summary/body 缺一不可:残缺的产物写进库就是一条没有标题或没有内容的记忆,
718
+ // 而它还挂着 derivedFrom/derivedInto 双向链,比不巩固更糟。
719
+ if (!draft.name || !draft.summary || !draft.body)
720
+ return null;
721
+ return { skip: false, draft };
722
+ }
723
+ /**
724
+ * 跑一轮巩固。`groups` 省略时现算候选(调用方通常省略)。
725
+ * 任一组失败不影响其它组:一组解析失败只损失那一组的归纳机会,不该连坐。
726
+ */
727
+ export async function runConsolidation(groups, signal) {
728
+ const ts = new Date().toISOString();
729
+ const list = groups ?? findConsolidationGroups();
730
+ const result = { ts, groups: list.length, consolidated: 0, skipped: 0 };
731
+ if (list.length === 0)
732
+ return result;
733
+ const timeoutSignal = signal ?? AbortSignal.timeout(REFLECT_TIMEOUT_MS);
734
+ for (const group of list) {
735
+ try {
736
+ const first = await fetchReflection([{ role: 'system', content: CONSOLIDATE_SYS }, consolidatePrompt(group)], timeoutSignal);
737
+ let plan = parseConsolidationPlan(first.content);
738
+ if (plan === null) {
739
+ // 与反思同一套「修复式重试」:推理模型偶发把 JSON 混进说明文字。
740
+ const repair = await fetchReflection([
741
+ { role: 'system', content: CONSOLIDATE_SYS },
742
+ consolidatePrompt(group),
743
+ { role: 'assistant', content: first.content ?? '' },
744
+ {
745
+ role: 'user',
746
+ content: '上一条无法解析。只输出一个 JSON 对象,不要围栏不要解释。无共同规律就输出 {"skip":true}。',
747
+ },
748
+ ], timeoutSignal);
749
+ plan = parseConsolidationPlan(repair.content);
750
+ if (plan === null) {
751
+ result.error ??= 'parse-failed';
752
+ result.rawParseFailure ??= repair.raw ?? first.raw ?? undefined;
753
+ continue;
754
+ }
755
+ }
756
+ if (plan.skip) {
757
+ result.skipped++;
758
+ continue;
759
+ }
760
+ const applied = applyConsolidation(group, plan.draft);
761
+ if (applied.ok)
762
+ result.consolidated++;
763
+ else
764
+ result.error ??= applied.reason;
765
+ }
766
+ catch (e) {
767
+ if (timeoutSignal.aborted) {
768
+ result.error = '巩固超时(后端持续失败或无响应)';
769
+ break; // 超时说明后端已不可用,继续下一组只会再等一次
770
+ }
771
+ result.error ??= e instanceof Error ? e.message : String(e);
772
+ }
773
+ }
774
+ return result;
775
+ }
776
+ /**
777
+ * fire-and-forget 触发巩固。与 kickoffReflection 共用 `inflight`:
778
+ * 后台 LLM 任务串行执行,不会同时压两条请求给后端(drain 也只需等一个槽位)。
779
+ *
780
+ * **无候选时零成本返回**:分组是纯本地计算,先算再看要不要发请求——
781
+ * 这是这条通道与反思的关键成本差异(反思每 N 轮必发一次,巩固只在真有材料时才发)。
782
+ */
783
+ export function kickoffConsolidation(manual = false) {
784
+ if (inflight)
785
+ return;
786
+ if (!isMemoryEnabled())
787
+ return;
788
+ if (!isConsolidationEnabled())
789
+ return;
790
+ const groups = findConsolidationGroups();
791
+ if (groups.length === 0)
792
+ return;
793
+ if (!manual) {
794
+ if (autoConsolidateCount >= MAX_AUTO_CONSOLIDATIONS)
795
+ return;
796
+ autoConsolidateCount++;
797
+ }
798
+ inflight = (async () => {
799
+ try {
800
+ const r = await runConsolidation(groups);
801
+ lastConsolidationResult = r;
802
+ appendLog(`[${r.ts}] ${formatConsolidationResult(r)}`);
803
+ if (r.rawParseFailure) {
804
+ appendLog(` ↳ 巩固 parse-failed 原始返回: ${r.rawParseFailure.replace(/\s+/g, ' ').slice(0, 500)}`);
805
+ }
806
+ }
807
+ catch (e) {
808
+ appendLog(`[${new Date().toISOString()}] 巩固异常: ${e instanceof Error ? e.message : String(e)}`);
809
+ }
810
+ finally {
811
+ inflight = null;
812
+ }
813
+ })();
814
+ }
815
+ /**
816
+ * 自动巩固的每进程次数上限。比反思的 3 次更紧:巩固一次最多两组请求,
817
+ * 而它的收益只在"情节攒够了"时才兑现,高频跑只会把同一批数据反复归纳。
818
+ * env:MOCODE_CONSOLIDATE_MAX_PER_SESSION 覆盖。
819
+ */
820
+ const MAX_AUTO_CONSOLIDATIONS = Math.max(1, Number(process.env.MOCODE_CONSOLIDATE_MAX_PER_SESSION) || 2);
821
+ let autoConsolidateCount = 0;
822
+ let lastConsolidationResult = null;
823
+ export function getLastConsolidationResult() {
824
+ return lastConsolidationResult;
825
+ }
826
+ export function clearLastConsolidationResult() {
827
+ lastConsolidationResult = null;
828
+ }
829
+ /** 测试用:清零自动巩固计数(模块级状态,共享进程里必须清)。 */
830
+ export function __resetConsolidateThrottleForTests() {
831
+ autoConsolidateCount = 0;
832
+ lastConsolidationResult = null;
833
+ }
834
+ /** 摘要串(供 repl flush):巩固 N 组(跳过 M 条)。 */
835
+ export function formatConsolidationResult(r) {
836
+ const parts = [`巩固 ${r.consolidated}/${r.groups} 组`];
837
+ if (r.skipped > 0)
838
+ parts.push(`跳过 ${r.skipped}`);
839
+ if (r.error)
840
+ parts.push(`错误 ${r.error}`);
841
+ return parts.join(' ');
842
+ }
@@ -1,6 +1,6 @@
1
1
  // relation-vocab.ts —— 受控关系词表(轻量,不含实体类型/domain-range)。
2
2
  //
3
- // 这是 memory-2.2 本体方案里"软封闭世界"的最小落地:只约束**关系名**,不引入实体类型
3
+ // 这是 design-notes/memory/memory.md §3 D1("不做完整本体")的最小落地:只约束**关系名**,不引入实体类型
4
4
  // 体系或推理。反思抽取 triples/profile 时优先用词表内关系;词表外关系**仍允许写入**
5
5
  // (软策略,不阻断长尾),但会被计数为 relViolation 供观测。等真实数据证明需要,再升级
6
6
  // 为完整 ontology.ts(实体 type + domain/range + 逆/传递)。
@@ -43,7 +43,21 @@ export const PROFILE_RELATIONS = [
43
43
  'skill_level',
44
44
  'related_to',
45
45
  ];
46
- /** 常见同义/拼写漂移 → 规范关系(反思落库前归范)。 */
46
+ /**
47
+ * 同义/拼写漂移 → 规范关系(所有写入路径落库前归范,见 graph.addTriple)。
48
+ *
49
+ * 收录标准很窄,只收**一对一**的确定性变体:
50
+ * ① 拼写错误(`cals`→`calls`、`suports_override`→`supports_override`);
51
+ * ② 同一关系的不同词形,且**方向与语态不变**(`depends`→`depends_on`、`prefer`→`prefers`)。
52
+ *
53
+ * **刻意不收**语义近义词与方向反转的关系。实测踩过的坑:
54
+ * - `implements` 指向的是**概念**(`vertex_provider --implements--> gemini_contents_protocol`),
55
+ * 而 `implemented_in` 指向的是**文件**;合并会把 `X implements Y` 误读成 `X 实现在 Y 里`;
56
+ * - `tested_in`(`X 被 Y 测试`)与 `tests`(`X 测试 Y`)主语宾语对调;
57
+ * - `configures`(`MOCODE_ARCHIVE_AFTER_DAYS --configures--> policy`)与
58
+ * `configured_by`(`X --configured_by--> Y`)方向相反。
59
+ * 这三类留在词表外更安全——它们会进 `relViolations` 观测,而不是被静默改写。
60
+ */
47
61
  export const RELATION_ALIASES = {
48
62
  employed_by: 'works_at',
49
63
  employer: 'works_at',
@@ -57,11 +71,19 @@ export const RELATION_ALIASES = {
57
71
  port: 'listens_on',
58
72
  depends: 'depends_on',
59
73
  dependency: 'depends_on',
60
- implements: 'implemented_in',
61
- impl: 'implemented_in',
62
74
  decides: 'decided_by',
63
75
  conflict: 'conflicts_with',
64
76
  configure: 'configured_by',
77
+ // —— 确定性拼写错误(实测出现在真实图里的脏关系名)——
78
+ cals: 'calls',
79
+ suports_override: 'supports_override',
80
+ // —— 同关系不同词形(方向/语态不变)——
81
+ prefer: 'prefers',
82
+ use: 'uses',
83
+ call: 'calls',
84
+ read: 'reads',
85
+ write: 'writes',
86
+ test: 'tests',
65
87
  };
66
88
  const PROJECT_SET = new Set(PROJECT_RELATIONS);
67
89
  const PROFILE_SET = new Set(PROFILE_RELATIONS);