mocode-ai 1.8.8 → 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 (61) 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/config/index.js +6 -1
  9. package/dist/context/text-search.js +28 -10
  10. package/dist/flows/cli.js +1 -1
  11. package/dist/flows/flow.js +1 -1
  12. package/dist/flows/trace.js +1 -1
  13. package/dist/headless.js +23 -0
  14. package/dist/index.js +1 -1
  15. package/dist/memory/anchor.js +319 -0
  16. package/dist/memory/audit.js +65 -0
  17. package/dist/memory/episodic.js +546 -0
  18. package/dist/memory/graph.js +233 -9
  19. package/dist/memory/health.js +208 -0
  20. package/dist/memory/index.js +12 -3
  21. package/dist/memory/pending.js +269 -0
  22. package/dist/memory/portable.js +150 -0
  23. package/dist/memory/proactive.js +588 -0
  24. package/dist/memory/recall-stats.js +1 -1
  25. package/dist/memory/reflect.js +260 -6
  26. package/dist/memory/relation-vocab.js +26 -4
  27. package/dist/memory/store.js +587 -41
  28. package/dist/memory/tail.js +88 -0
  29. package/dist/memory/write-gate.js +44 -0
  30. package/dist/permissions/computer-review.js +1 -1
  31. package/dist/permissions/flow-review.js +1 -1
  32. package/dist/repl/commands/flow.js +1 -1
  33. package/dist/repl/commands/memory.js +257 -6
  34. package/dist/repl/commands/session.js +13 -0
  35. package/dist/repl/commands/tool-group.js +6 -0
  36. package/dist/repl/episode-finalize.js +55 -0
  37. package/dist/repl/running-input.js +1 -1
  38. package/dist/repl/runtime.js +41 -3
  39. package/dist/runtime/uia-selector.js +1 -1
  40. package/dist/runtime/uia-service.js +3 -3
  41. package/dist/runtime/wait-until.js +1 -1
  42. package/dist/runtime/window-list.js +1 -1
  43. package/dist/sandbox/policy.js +49 -0
  44. package/dist/session/compact.js +47 -12
  45. package/dist/session/gui-actions.js +1 -1
  46. package/dist/tools/builtins/computer.js +5 -5
  47. package/dist/tools/builtins/memory-graph.js +12 -1
  48. package/dist/tools/builtins/memory-list.js +13 -3
  49. package/dist/tools/builtins/memory-save.js +82 -2
  50. package/dist/tools/builtins/memory-search.js +57 -2
  51. package/dist/tools/builtins/memory-update.js +52 -1
  52. package/dist/tools/builtins/read-file.js +51 -2
  53. package/dist/tools/builtins/run-flow.js +1 -1
  54. package/dist/tools/constants.js +60 -0
  55. package/dist/ui/intervention.js +38 -2
  56. package/dist/ui/layout-internal/core.js +8 -2
  57. package/dist/ui/layout-internal/input-paint.js +15 -7
  58. package/dist/ui/layout-internal/screen.js +9 -0
  59. package/dist/ui/layout-internal/scroll.js +49 -11
  60. package/dist/ui/layout-internal/state.js +8 -0
  61. package/package.json +6 -1
@@ -24,7 +24,8 @@ import { renderChip } from '../attachments/image.js';
24
24
  import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index.js';
25
25
  import { effectiveSystemPrompt, skillsChangedSinceLastObserve } from '../skills/index.js';
26
26
  import { clearSkillActivation } from '../skills/activation.js';
27
- import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, initPersona, gcMemories, kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, } from '../memory/index.js';
27
+ import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, buildEpisodeSection, initPersona, gcMemories, kickoffReflection, kickoffConsolidation, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSection, } from '../memory/index.js';
28
+ import { finalizeCurrentEpisode } from './episode-finalize.js';
28
29
  import { collectQueryHistory } from '../session/query-history.js';
29
30
  import { ToolPolicyController } from '../tools/policy.js';
30
31
  import { routeToolGroups } from '../tools/router.js';
@@ -214,6 +215,9 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
214
215
  // best-effort
215
216
  }
216
217
  }
218
+ // R17:会话内记忆尾注的基线在**会话边界**拍一次(启动 / /clear / /resume)。
219
+ // 放在 gcMemories 之后:GC 归档的条目刚落定,基线应以「会话真正开始时」的库为准。
220
+ captureMemoryBaseline();
217
221
  // 开关现读:运行时 /memory_switch 重建 history[0] 时,About you 与 Memory Index 同步显隐。
218
222
  const buildSystemMessage = (planMode) => {
219
223
  const memoryOn = isMemoryEnabled();
@@ -221,6 +225,8 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
221
225
  buildAboutYouSection(memoryOn) +
222
226
  (planMode ? getPlanModeSuffix() : '') +
223
227
  buildMemoryIndexSection(memoryOn) +
228
+ // R6.3:情节走独立小节(不进 Memory Index / 不进 About you,理由见 episodic.ts)。
229
+ buildEpisodeSection(memoryOn) +
224
230
  buildProjectGraphHint(memoryOn));
225
231
  };
226
232
  // 有预加载(--resume)则用它,并把 history[0] 刷成当前 system prompt(config 可能已变);
@@ -572,10 +578,15 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
572
578
  messageAttachments.set(msgIndex, imgs);
573
579
  // 运行中每步 chat() 返回后刷新状态行 context 用量条(用 fresh lastUsage / 估算),
574
580
  // 否则整轮冻结在轮首 refreshStatusBase 的值,「执行 grep」时 2k/1000k 不动。
581
+ // 前摄通道的每轮限额在此重置(R3.4):按进程计会让常驻 REPL 几轮后永久静默。
582
+ resetProactiveTurn();
575
583
  const result = await runAgent(history, userInput, signal, () => {
576
584
  refreshStatusBase(history);
577
585
  layout.drawStatusBar();
578
- }, toolPolicy, initialToolRoute, runtime);
586
+ }, toolPolicy, initialToolRoute,
587
+ // R17:每用户轮现算一次「本会话内新增/更新的记忆」。走 ephemeral 尾注,不重建
588
+ // history[0](否则整段对话的前缀缓存每轮失效)。基线无变化时返回空串 → 零注入。
589
+ buildMemoryTailSection(isMemoryEnabled()), runtime);
579
590
  // 撞限 salvage 摘要要在 TUI 落地:runAgent 只把 finalText 带回不渲染,主线撞限的
580
591
  // 收尾摘要若不打印,这笔收尾请求的 token 就白花(用户只看到「达到最大步数」一行)。
581
592
  if (result.terminationReason === 'max_steps' && result.finalText) {
@@ -598,10 +609,23 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
598
609
  }
599
610
  // 后台反思:每 reflectEveryN 轮 fire-and-forget 一次(与下一轮 agent 并发,不阻塞)。
600
611
  // 已有在飞任务 / autoReflect 关 → kickoff 内部自守卫。快照同步取(避免下一轮 mutate history 竞态)。
612
+ // 召回计数脏集在此统一落盘:搜索本身不再写盘(纯读语义),一轮一次即可。
613
+ flushRecallStats();
614
+ // R4.1:前摄计数同样是内存累计(每次工具调用都写盘会变成写放大热点),
615
+ // 与召回计数一起在轮末落一次。健康快照仍只由 /memory health 与退出路径写,
616
+ // 因为它要读全库 + 算 stale,不该每轮付这个成本。
617
+ flushProactiveStats();
601
618
  turnCount++;
602
619
  if (turnCount % config.reflectEveryN === 0) {
603
620
  kickoffReflection(snapshotTranscript(history, 20));
604
621
  }
622
+ else {
623
+ // R11:非反思轮才轮到情节巩固。两者共用同一个在飞槽位(后台 LLM 任务串行,
624
+ // 不并压两条请求给后端),所以放在 else 里而不是紧跟其后 —— 否则反思刚占住
625
+ // 槽位,巩固这一轮必然被静默跳过,实际 cadence 会漂移成"只有反思没命中时才跑"。
626
+ // 无候选时它是纯本地计算,零成本返回。
627
+ kickoffConsolidation();
628
+ }
605
629
  }
606
630
  catch (e) {
607
631
  ok = false;
@@ -672,6 +696,9 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
672
696
  async function resumeFromPick(pick) {
673
697
  if (!pick)
674
698
  return; // Esc / Ctrl+D 取消
699
+ // R6.1:切换前把**当前**会话落成情节记忆——下面 history.length=0 之后内容就没了。
700
+ // 幂等,重复切换只会刷新同一条。
701
+ finalizeCurrentEpisode(currentSessionId, history, queryHistory);
675
702
  const loaded = runtime.session.resume(pick.id);
676
703
  if (!loaded || !loaded.history.length) {
677
704
  layout.contentWrite(`${ui.yellow}${t('repl.loadFailed')}${ui.reset}\n`);
@@ -685,6 +712,9 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
685
712
  history.length = 0;
686
713
  history.push(...loaded.history);
687
714
  queryHistory = loaded.queryHistory ? [...loaded.queryHistory] : queryHistoryFromMessages(loaded.history);
715
+ // R17:换会话是会话边界,尾注基线重拍——否则被切换掉的那段会话里写的条目,
716
+ // 会在续接会话的第一轮被当成「新学到的」重复播报。
717
+ captureMemoryBaseline();
688
718
  lastToolGroups = [...(loaded.lastToolGroups ?? [])];
689
719
  setAgentMode('auto'); // 续接重置为 auto(mode 不落盘;listener 重写 history[0] 回 auto,与 loaded 幂等)
690
720
  contextState.lastUsage = undefined;
@@ -938,7 +968,15 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
938
968
  }
939
969
  }
940
970
  }
941
- // 退出前等在飞反思收尾(Ctrl+C 走 SIGINT 直退不等;fire-and-forget 不承诺中断时完成)。
971
+ // R6.1:退出前落情节(纯本地、零 LLM,毫秒级;放在 drain 之前让两者并行收尾)。
972
+ finalizeCurrentEpisode(currentSessionId, history, queryHistory);
973
+ // R4.1:退出时写一份健康快照。放这里而不是每轮:它要读全库 + 算 stale,
974
+ // 每次退出一个文件,正好构成一条随时间推移的趋势线。
975
+ flushProactiveStats();
976
+ writeMemoryHealth(isMemoryEnabled());
977
+ // 退出前等在飞反思收尾。注意:Ctrl+C 在 TUI(raw 模式)下是按键不是 SIGINT,空输入框时
978
+ // 由主循环 catch { break } 接住,因此**会**走到这里等反思跑完;只有非 raw 模式下的
979
+ // 进程级 SIGINT → process.exit(130) 才跳过(fire-and-forget 不承诺中断时完成)。
942
980
  await drainMemoryBackground();
943
981
  await runtime.close();
944
982
  await closeAllMcp();
@@ -1,5 +1,5 @@
1
1
  /**
2
- * UIA 元素树的纯函数层(design-notes/computer-use-rpa.md §2.2–2.4)。
2
+ * UIA 元素树的纯函数层(design-notes/computer-use/computer-use-rpa.md §2.2–2.4)。
3
3
  *
4
4
  * 只处理 JSON 化的元素树:解析/规整 PowerShell 侧输出、选择器生成与匹配、inspect 文本渲染、
5
5
  * ref → 名称登记表(供权限层展示与敏感判定)。不碰进程、屏幕或 COM,跨平台可单测。
@@ -1,5 +1,5 @@
1
1
  /**
2
- * UI Automation 常驻服务(Windows):computer 工具的「元素之眼」(design-notes/computer-use-rpa.md §2.1)。
2
+ * UI Automation 常驻服务(Windows):computer 工具的「元素之眼」(design-notes/computer-use/computer-use-rpa.md §2.1)。
3
3
  *
4
4
  * 为什么独立成进程而不是塞进 input-injector:
5
5
  * 1. 元素树遍历可能要几百 ms 到数秒,注入器是串行管道,混在一起会让 click 排在慢 tree 后面;
@@ -54,7 +54,7 @@ const PS_UIA_SCRIPT = [
54
54
  ' [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();',
55
55
  ' [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr ctx);',
56
56
  ' [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();',
57
- // ── 窗口 API(list_windows / focus_window / 窗口截图,design-notes/computer-use-rpa.md §4)──
57
+ // ── 窗口 API(list_windows / focus_window / 窗口截图,design-notes/computer-use/computer-use-rpa.md §4)──
58
58
  // 结构体读写与回调全放 C# 里:PowerShell 对嵌套值类型赋值落在副本上(见 input-injector.ts 的教训)。
59
59
  ' public struct RECT { public int L; public int T; public int R; public int B; }',
60
60
  ' public delegate bool EnumProc(IntPtr h, IntPtr l);',
@@ -247,7 +247,7 @@ const PS_UIA_SCRIPT = [
247
247
  ' $resp.rect = To-Rect $el.Current.BoundingRectangle',
248
248
  ' $resp.ok = $true',
249
249
  ' }',
250
- // ── 窗口 op(design-notes/computer-use-rpa.md §4)──
250
+ // ── 窗口 op(design-notes/computer-use/computer-use-rpa.md §4)──
251
251
  // windows:枚举顶层可见窗口(z-order 前→后),过滤/编号/norm 换算在 TS 侧(window-list.ts)。
252
252
  ' "windows" {',
253
253
  ' $fg = [MoUia]::GetForegroundWindow()',
@@ -1,5 +1,5 @@
1
1
  /**
2
- * computer.wait_until 的纯逻辑层(design-notes/computer-use-rpa.md §3.1)。
2
+ * computer.wait_until 的纯逻辑层(design-notes/computer-use/computer-use-rpa.md §3.1)。
3
3
  *
4
4
  * 条件解析、轮询状态机、type 输入方式选择都在这里;抓屏与元素存在性检查通过 WaitDeps 注入,
5
5
  * 因此可以用合成 PngImage 序列 + 假时钟离线单测,不碰屏幕/进程。
@@ -1,5 +1,5 @@
1
1
  /**
2
- * computer.list_windows / focus_window 的纯逻辑层(design-notes/computer-use-rpa.md §4)。
2
+ * computer.list_windows / focus_window 的纯逻辑层(design-notes/computer-use/computer-use-rpa.md §4)。
3
3
  *
4
4
  * 窗口枚举的原始数据来自 uia-service 的 `windows` op;过滤、编号(w1..wN)、norm1000 换算、
5
5
  * 按 ref / title_regex 选窗口都在这里,可用 fixture 离线单测,不碰 Win32。
@@ -31,6 +31,48 @@ export const SANDBOX_EXEMPT_TOOLS = new Set([
31
31
  * resolve(absolutePath) 原样返回)。**新加带 path 参数的工具须列入此集**,否则不会被牢笼挡。
32
32
  */
33
33
  export const SANDBOX_PATH_TOOLS = new Set(['read_file', 'write_file', 'edit_file']);
34
+ /**
35
+ * 记忆子系统的**持久状态文件**(R16.5)。
36
+ *
37
+ * 为什么需要这份名单:`SANDBOX_PATH_TOOLS` 只把路径栏在 cwd 内,而 `<cwd>/.mocode/`
38
+ * 恰恰就在 cwd 里。于是 `write_file('.mocode/memory.jsonl', …)` 完全合法——模型(或一次
39
+ * 被注入的指令)可以直接覆盖整个记忆库、往图谱里塞一条伪造的 `person-primary --works_at-->`
40
+ * 边,或把 pending 队列清空。记忆是**跨会话长期生效**的状态,一旦被写脏,影响面远超一次错误编辑。
41
+ *
42
+ * 为什么拦在沙箱层而不是在 memory_* 工具里:模型手上能碰文件的工具是 write_file/edit_file,
43
+ * 它们与 memory_* 毫无关联。拦在 memory_* 内部等于没拦。
44
+ *
45
+ * 为什么**不**拦读取:`memory_search` 之外,诊断与自查常要读这几个文件。禁读只会把
46
+ * 可观测性一起关掉,而读不会污染状态。
47
+ */
48
+ const MEMORY_STATE_FILES = [
49
+ 'memory.jsonl', // 条目库(两 scope:global + project)
50
+ 'memory-graph.json', // 知识图谱
51
+ 'memory-pending.jsonl', // 压缩→反思候选队列
52
+ 'memory-audit.jsonl', // R8 审计日志
53
+ 'memory-health.json', // 健康快照
54
+ 'memory-recall-stats.json', // 召回统计(R0.2)
55
+ ];
56
+ /**
57
+ * 写入类工具试图改 `.mocode` 下的记忆状态文件时返回拒绝文案;否则 null。
58
+ *
59
+ * 判定按**路径分量**而不是字符串包含:必须同时满足 ①父目录段恰为 `.mocode`,
60
+ * ②文件名在名单内(允许 `.tmp` 后缀——原子写的半成品同样不能碰)。
61
+ * 这样 `src/.mocode-spec/memory.jsonl`(不在 .mocode 目录下)不会被误伤。
62
+ */
63
+ function rejectMemoryStateWrite(absPath) {
64
+ const parts = absPath.split(/[\\/]+/).filter(Boolean);
65
+ const base = (parts.at(-1) ?? '').toLowerCase();
66
+ const dir = (parts.at(-2) ?? '').toLowerCase();
67
+ if (dir !== '.mocode')
68
+ return null;
69
+ const name = base.endsWith('.tmp') ? base.slice(0, -4) : base;
70
+ if (!MEMORY_STATE_FILES.includes(name))
71
+ return null;
72
+ return (`错误:${name} 是记忆子系统的持久状态文件,不允许用写文件工具直接改动。` +
73
+ `请改用 memory_save / memory_update / memory_forget / memory_graph 工具,` +
74
+ `或 /memory 命令(批量遗忘、导出、暂停)。`);
75
+ }
34
76
  /**
35
77
  * 工具执行前的沙箱校验。返 string = 拒绝(直接喂 LLM,不执行);返 null = 放行(可能已重写 args.path)。
36
78
  * **不抛**——契约对齐「调度器永不抛错、永远返回字符串」(tools/registry.ts executeTool)。
@@ -49,6 +91,13 @@ export function enforceSandbox(name, args) {
49
91
  const why = e instanceof Error ? e.message : String(e);
50
92
  return `错误:路径越界,已被沙箱拒绝: ${p} (${why})`;
51
93
  }
94
+ // 校验在重写之后:判的是**真实目标**而不是模型写的相对串,
95
+ // 否则 `./.mocode/../.mocode/memory.jsonl` 这类变体可以绕过。
96
+ if (name !== 'read_file') {
97
+ const deny = rejectMemoryStateWrite(args.path);
98
+ if (deny)
99
+ return deny;
100
+ }
52
101
  }
53
102
  return null;
54
103
  }
@@ -1,5 +1,6 @@
1
1
  import { chat, chatTools, correctTokenEstimate, estimateMessagesTokens, estimatePromptTokens, estimateToolSchemaTokens, estimateTokens, } from '../llm/index.js';
2
- import { config } from '../config/index.js';
2
+ import { config, isMemoryEnabled } from '../config/index.js';
3
+ import { appendPendingCandidates, extractMemoryCandidates, isCompactHandoffEnabled, memoryCandidatesInstruction, } from '../memory/pending.js';
3
4
  import { COMPACT_USER_VERBATIM_MAX_TOKENS, COMPACT_USER_VERBATIM_WINDOW_RATIO, MAX_HISTORY_RESULT, MAX_MEMORY_RESULT, MAX_OLD_TOOL_STUB, MAX_SKILL_RESULT, SUMMARY_KEYFACTS_MAX_CHARS, SUMMARY_KEYFACTS_MIN_CHARS, SUMMARY_KEYFACTS_WINDOW_RATIO, SUMMARY_MSG_MAX_CHARS, SUMMARY_OUTPUT_MAX_CHARS, SUMMARY_TRANSCRIPT_WINDOW_RATIO, USER_DIRECTIVE_MAX_CHARS, USER_DIRECTIVE_MAX_CONSTRAINTS, } from '../tools/constants.js';
4
5
  import { ui } from '../ui/theme.js';
5
6
  import { Spinner } from '../ui/spinner.js';
@@ -479,6 +480,30 @@ function capSummaryOutput(summary) {
479
480
  const at = cut > SUMMARY_OUTPUT_MAX_CHARS * 0.5 ? cut : SUMMARY_OUTPUT_MAX_CHARS;
480
481
  return summary.slice(0, at) + '\n[摘要输出超长,已截断]';
481
482
  }
483
+ /**
484
+ * R13 摘要出口:先切走 `## Memory Candidates` 段,再对剩下的正文封顶。
485
+ *
486
+ * 顺序不能反:
487
+ * - 先封顶会把候选段(按指令写在正文之后)直接截掉,通道静默失效;
488
+ * - 不切走就存进 history,摘要里会混进一段"给反思看的草稿",白占上下文,而且下一代
489
+ * 压缩会把它当叙述再压一遍。
490
+ *
491
+ * `capture=false` 时仍然切走、但不入队——这样开关关闭后产出的摘要也不会残留该段。
492
+ * 子 agent 的压缩不入队:候选是项目级知识,子 agent 的中间推理不该污染主库
493
+ * (与 archive/snapshot 的 main-agent-only 同一条边界)。
494
+ */
495
+ function finalizeSummaryOutput(raw, capture) {
496
+ const { summary, candidates } = extractMemoryCandidates(raw);
497
+ if (capture && candidates.length > 0) {
498
+ try {
499
+ appendPendingCandidates(candidates);
500
+ }
501
+ catch {
502
+ /* best-effort:入队失败只丢这一批候选,绝不阻塞压缩 */
503
+ }
504
+ }
505
+ return capSummaryOutput(summary);
506
+ }
482
507
  /** 按封顶配额拼转录。scale ∈ (0,1] 等比缩小各角色配额(总预算不足时用)。 */
483
508
  function buildTranscript(stripped, scale) {
484
509
  const caps = SUMMARY_MSG_MAX_CHARS;
@@ -505,7 +530,7 @@ function buildTranscript(stripped, scale) {
505
530
  })
506
531
  .join('\n');
507
532
  }
508
- async function defaultSummarize(older, focus, signal, runtime = defaultCompactionRuntime) {
533
+ async function defaultSummarize(older, focus, signal, runtime = defaultCompactionRuntime, capture = false) {
509
534
  // 已中断就别白拼转录了(几千 token 的字符串拼接 + 一去不回的 LLM 请求)。
510
535
  if (signal?.aborted) {
511
536
  throw new DOMException('This operation was aborted', 'AbortError');
@@ -544,7 +569,10 @@ async function defaultSummarize(older, focus, signal, runtime = defaultCompactio
544
569
  'Rules: total ≤ 400 words. State conclusions and locations (path:line where useful), never paste content. ' +
545
570
  'The Key Facts section is carried forward verbatim into future summaries: write each fact as one self-contained line ' +
546
571
  '(no pronouns, no "as above", no cross-references), so it still reads correctly after later compactions. ' +
547
- 'Never invent facts, paths, or results that are not in the transcript; if unsure whether something happened, omit it.',
572
+ 'Never invent facts, paths, or results that are not in the transcript; if unsure whether something happened, omit it.' +
573
+ // R13:候选段是"附加要求",只在捕获开启时追加。它的内容不计入 400 词上限,
574
+ // 且必须写在正文结构之后——解析端按 `## Memory Candidates` 标题切走。
575
+ (capture ? memoryCandidatesInstruction() : ''),
548
576
  };
549
577
  const userMsg = {
550
578
  role: 'user',
@@ -562,7 +590,7 @@ async function defaultSummarize(older, focus, signal, runtime = defaultCompactio
562
590
  // 推理模型可能只返 reasoning_content(content 为 null),或幻觉出 tool_calls → 视为失败
563
591
  if (r.toolCalls.length > 0 || !r.content)
564
592
  return null;
565
- return capSummaryOutput(r.content);
593
+ return finalizeSummaryOutput(r.content, capture);
566
594
  }
567
595
  finally {
568
596
  spinner.stop();
@@ -586,7 +614,7 @@ function buildForkMessages(history, kept) {
586
614
  return out;
587
615
  }
588
616
  /** fork 尾部 user 消息:摘要任务指令(原 legacy sysMsg 的规则,措辞改为"上方对话")。 */
589
- function compactForkInstruction(focus) {
617
+ function compactForkInstruction(focus, capture = false) {
590
618
  const focusLine = focus ? `Focus: prioritize facts / decisions / file changes related to 「${focus}」.\n\n` : '';
591
619
  return (focusLine +
592
620
  '[COMPACT TASK] You are an aggressive session compressor writing a handoff note for an agent that is about to lose the context above. ' +
@@ -603,7 +631,8 @@ function compactForkInstruction(focus) {
603
631
  'GUI EXCEPTION to "step-by-step recaps": for computer/screen-control actions keep the SEQUENCE as an ordered list — one line per action: `N. <action> (<coordinates or target>) → <observed result>`. Never collapse it into prose and never drop attempts that produced no visible change.\n' +
604
632
  'Rules: total ≤ 400 words. State conclusions and locations (path:line where useful), never paste content. ' +
605
633
  'Write each Key Fact as one self-contained line (no pronouns, no "as above", no cross-references). ' +
606
- 'Do not emit tool calls and do not invent facts; if unsure whether something happened, omit it.');
634
+ 'Do not emit tool calls and do not invent facts; if unsure whether something happened, omit it.' +
635
+ (capture ? memoryCandidatesInstruction() : ''));
607
636
  }
608
637
  /** buffer 校验:fork 全量(含指令 + 摘要输出上限)必须装得进窗口,否则回落 legacy。 */
609
638
  function forkFits(prefix, instruction, activeTools, window) {
@@ -613,7 +642,7 @@ function forkFits(prefix, instruction, activeTools, window) {
613
642
  return forkInput + outputBudget <= window;
614
643
  }
615
644
  /** 执行 fork 请求:复用父前缀 + activeTools,记录 compact phase 用量。 */
616
- async function forkSummarize(prefix, instruction, signal, runtime, activeTools, state) {
645
+ async function forkSummarize(prefix, instruction, signal, runtime, activeTools, state, capture = false) {
617
646
  if (signal?.aborted)
618
647
  throw new DOMException('This operation is aborted', 'AbortError');
619
648
  const messages = [...prefix, { role: 'user', content: instruction }];
@@ -630,7 +659,7 @@ async function forkSummarize(prefix, instruction, signal, runtime, activeTools,
630
659
  // 同 legacy:幻觉 tool_calls 或空 content → 失败(调用方回落 microcompact)。
631
660
  if (r.toolCalls.length > 0 || !r.content)
632
661
  return null;
633
- return capSummaryOutput(r.content);
662
+ return finalizeSummaryOutput(r.content, capture);
634
663
  }
635
664
  finally {
636
665
  spinner.stop();
@@ -834,17 +863,23 @@ export async function compactHistory(history, opts) {
834
863
  ...older,
835
864
  ];
836
865
  }
866
+ // R13.4:交接开关。三条件必须是「与」——
867
+ // - memory 总开关关掉时不该再往库里送料(否则"关闭记忆"只关了一半);
868
+ // - `state === contextState` 是主 agent 判据:子 agent 的压缩不入队,理由同
869
+ // archive/snapshot(子 agent 的中间推理不属于项目级知识);
870
+ // - 独立开关让它能单独关(压缩是高频路径,出问题要能立刻止血而不连带关记忆)。
871
+ const captureCandidates = state === contextState && isMemoryEnabled() && isCompactHandoffEnabled();
837
872
  const summarizeFn = opts.summarize ??
838
873
  (async (older, focus, signal) => {
839
874
  const rt = opts.runtime ?? defaultCompactionRuntime;
840
875
  // P0:fork 关闭或 buffer 装不下 → 回落 legacy 独立 compressor 路径。
841
876
  if (!config.compactFork)
842
- return defaultSummarize(older, focus, signal, rt);
877
+ return defaultSummarize(older, focus, signal, rt, captureCandidates);
843
878
  const prefix = buildForkMessages(history, kept);
844
- const instruction = compactForkInstruction(focus);
879
+ const instruction = compactForkInstruction(focus, captureCandidates);
845
880
  if (!forkFits(prefix, instruction, activeTools, opts.window))
846
- return defaultSummarize(older, focus, signal, rt);
847
- return forkSummarize(prefix, instruction, signal, rt, activeTools, state);
881
+ return defaultSummarize(older, focus, signal, rt, captureCandidates);
882
+ return forkSummarize(prefix, instruction, signal, rt, activeTools, state, captureCandidates);
848
883
  });
849
884
  let summary = null;
850
885
  try {
@@ -91,7 +91,7 @@ export function parseComputerOutput(output) {
91
91
  const n = /, (\d+) nodes \(/.exec(text);
92
92
  return { intent: 'inspect', observation: n ? `${n[1]} nodes` : 'listed' };
93
93
  }
94
- // 窗口作用域(computer.ts, design-notes/computer-use-rpa.md §4)。
94
+ // 窗口作用域(computer.ts, design-notes/computer-use/computer-use-rpa.md §4)。
95
95
  // list_windows:`Windows (N, front to back). ...`,只回灌文本。
96
96
  if (text.startsWith(LIST_WINDOWS_OUTPUT_PREFIX)) {
97
97
  const n = /^Windows \((\d+)/.exec(text);
@@ -74,7 +74,7 @@ const ACTIONS = [
74
74
  'list_windows',
75
75
  'focus_window',
76
76
  ];
77
- /** inspect 默认/最大展示节点数(design-notes/computer-use-rpa.md §2.4)。 */
77
+ /** inspect 默认/最大展示节点数(design-notes/computer-use/computer-use-rpa.md §2.4)。 */
78
78
  const INSPECT_DEFAULT_NODES = 120;
79
79
  const INSPECT_MAX_NODES = 300;
80
80
  const ELEMENT_ACTIONS = new Set(['click_element', 'set_value']);
@@ -186,7 +186,7 @@ export function validateComputerArgs(args) {
186
186
  return 'set_value via must be pattern|keys';
187
187
  }
188
188
  }
189
- // 窗口作用域(design-notes/computer-use-rpa.md §4):window("wN",来自最近一次 list_windows)与 title_regex 二选一。
189
+ // 窗口作用域(design-notes/computer-use/computer-use-rpa.md §4):window("wN",来自最近一次 list_windows)与 title_regex 二选一。
190
190
  const hasWin = args.window !== undefined;
191
191
  const hasRe = args.title_regex !== undefined;
192
192
  if (hasWin && (typeof args.window !== 'string' || !/^w\d+$/.test(args.window))) {
@@ -488,7 +488,7 @@ async function executeAction(injector, action, args, screen, signal) {
488
488
  const { node } = el.item;
489
489
  const text = args.text;
490
490
  const label = `element ${el.item.ref} ${node.role} ${JSON.stringify(node.name)}`;
491
- // 密码框:模型不代填密码(design-notes/computer-use-rpa.md §2.6),用户需要时手动输入。
491
+ // 密码框:模型不代填密码(design-notes/computer-use/computer-use-rpa.md §2.6),用户需要时手动输入。
492
492
  if (node.isPassword)
493
493
  throw new Error(`${label} is a password field; refusing to fill it — ask the user to type it`);
494
494
  const hasValuePattern = node.patterns.includes('value');
@@ -929,7 +929,7 @@ const computerToolBase = {
929
929
  }
930
930
  return { status: 'success', code: 'OK', retryable: false, output: text };
931
931
  }
932
- // wait_until:轮询直到画面稳定/变化或元素出现/消失;不注入输入(design-notes/computer-use-rpa.md §3.1)。
932
+ // wait_until:轮询直到画面稳定/变化或元素出现/消失;不注入输入(design-notes/computer-use/computer-use-rpa.md §3.1)。
933
933
  // 轮询帧只在内存里比对、用完即删文件;仅结束时抓一张正式截图回灌并设为新的差分基准。
934
934
  if (action === 'wait_until') {
935
935
  const parsed = parseWaitCondition(args.condition, diffThreshold());
@@ -1121,7 +1121,7 @@ function buildTraceForCall(args) {
1121
1121
  return buildTraceEntry(args, ctx);
1122
1122
  }
1123
1123
  /**
1124
- * 对外导出的 computer 工具 = 基础工具 + 结构化录制(design-notes/computer-use-rpa.md §5.1)。
1124
+ * 对外导出的 computer 工具 = 基础工具 + 结构化录制(design-notes/computer-use/computer-use-rpa.md §5.1)。
1125
1125
  * 仅在动作成功后追加一行 gui-trace.jsonl;回放期间(withTraceSuspended)与 MOCODE_FLOW_TRACE=false 时不录。
1126
1126
  */
1127
1127
  export const computerTool = {
@@ -57,10 +57,21 @@ export const memoryGraphTool = {
57
57
  const action = String(args.action ?? '').trim();
58
58
  if (action === 'stats') {
59
59
  const s = graphStats();
60
+ const pct = (n, total) => (total === 0 ? '—' : `${Math.round((n / total) * 100)}%`);
61
+ const pv = s.vocab.project;
62
+ const gv = s.vocab.global;
63
+ const prov = Object.entries(s.provDistribution)
64
+ .sort((a, b) => b[1] - a[1])
65
+ .map(([k, n]) => `${k} ${n}`)
66
+ .join(', ');
60
67
  return [
61
- `实体 ${s.entities} 条边(active ${s.edgesActive} / 已失效 ${s.edgesInvalid})`,
68
+ `实体 ${s.entities} 条边(active ${s.edgesActive} / 已失效 ${s.edgesInvalid}),已分型实体 ${s.typedEntities}`,
62
69
  `project: ${s.byScope.project.entities} 实体, ${s.byScope.project.edges} 边`,
63
70
  `global: ${s.byScope.global.entities} 实体, ${s.byScope.global.edges} 边`,
71
+ `关系词表命中: project ${pv.inVocab}/${pv.total}(${pct(pv.inVocab, pv.total)}) | global ${gv.inVocab}/${gv.total}(${pct(gv.inVocab, gv.total)})`,
72
+ `溯源分布: ${prov || '(无)'}`,
73
+ `跨 scope 关系使用(观察用,非错误): project 用画像关系 ${s.crossScopeRelationUse.projectUsesProfileRel} 条 | global 用项目关系 ${s.crossScopeRelationUse.globalUsesProjectRel} 条`,
74
+ `global 图指向本仓库源码路径的边: ${s.globalRepoPathEdges}(守卫生效后应为 0)`,
64
75
  formatRecallStats(),
65
76
  ].join('\n');
66
77
  }
@@ -1,9 +1,11 @@
1
- import { listEntries } from '../../memory/store.js';
1
+ import { listEntries, wantsTrigger } from '../../memory/store.js';
2
2
  // ---------- memory_list ----------
3
3
  // 列索引(id/name/summary,无正文、不 bump recall)。用于浏览有哪些、拿 id 再 memory_search 取正文。
4
+ // R3:显式标出「该有 trigger 却还没有」的条目。前摄通道的唯一供料就是 trigger,
5
+ // 模型只有在列表里看得见缺口时才会去补;不暴露缺口 = 通道永远是空索引(实测覆盖率 0)。
4
6
  export const memoryListTool = {
5
7
  name: 'memory_list',
6
- description: 'List the memory index (id/name/summary, no body). Get an id, then use memory_search for the full body.',
8
+ description: 'List the memory index (id/name/summary, no body). Get an id, then use memory_search for the full body. Entries marked "NO-TRIGGER" are pitfall/decision/feedback memories still missing a trigger, so the proactive channel can never surface them — fill it via memory_update when you know the situation they apply to.',
7
9
  parameters: {
8
10
  type: 'object',
9
11
  properties: {
@@ -25,6 +27,14 @@ export const memoryListTool = {
25
27
  });
26
28
  if (items.length === 0)
27
29
  return '(无记忆条目)';
28
- return items.map((i) => `- ${i.id}: ${i.name} — ${i.summary} (${i.type}, ${i.status})`).join('\n');
30
+ const lines = items.map((i) => {
31
+ const gap = !i.hasTrigger && wantsTrigger(i.type) ? ' [NO-TRIGGER]' : '';
32
+ return `- ${i.id}: ${i.name} — ${i.summary} (${i.type}, ${i.status})${gap}`;
33
+ });
34
+ const gaps = items.filter((i) => !i.hasTrigger && wantsTrigger(i.type)).length;
35
+ if (gaps > 0) {
36
+ lines.push(`\n${gaps} 条条目缺 trigger,前摄通道永远命中不到它们。若你清楚某条适用的具体场景(不是"改代码时"这类泛化说法),用 memory_update 补上 trigger/action。`);
37
+ }
38
+ return lines.join('\n');
29
39
  },
30
40
  };
@@ -1,5 +1,47 @@
1
- import { saveEntry } from '../../memory/store.js';
1
+ import { saveEntry, memoryWriteBlockedMessage } from '../../memory/store.js';
2
2
  import { addTriple } from '../../memory/graph.js';
3
+ import { buildAnchors } from '../../memory/anchor.js';
4
+ /**
5
+ * 把工具参数里的 anchors 归一成 AnchorInput[]。
6
+ *
7
+ * 只取 path/symbol,**不接受调用方传 hash**:hash 若由模型抄写,错一个字符就变成
8
+ * 永久 stale,而且这种错误无法从输出里看出来。hash 一律由 store 在写入时现算。
9
+ */
10
+ function parseAnchorInputs(raw) {
11
+ if (!Array.isArray(raw))
12
+ return [];
13
+ const out = [];
14
+ for (const item of raw) {
15
+ if (!item || typeof item !== 'object')
16
+ continue;
17
+ const a = item;
18
+ const p = typeof a.path === 'string' ? a.path.trim() : '';
19
+ if (!p)
20
+ continue;
21
+ const s = typeof a.symbol === 'string' ? a.symbol.trim() : '';
22
+ out.push({ path: p, ...(s ? { symbol: s } : {}) });
23
+ }
24
+ return out;
25
+ }
26
+ /**
27
+ * 锚点结果的说明文字。**失败必须说出来**:静默丢弃会让模型以为已经锚定,
28
+ * 下次代码改了也不会得到提示——那正是 R2 要解决的场景静默失效。
29
+ * 这里重跑一次 buildAnchors 只是为了取失败名单(文件已缓存,成本是一次 stat)。
30
+ */
31
+ function anchorNoteOf(anchors) {
32
+ if (anchors.length === 0)
33
+ return '';
34
+ const built = buildAnchors(anchors);
35
+ const ok = built.map((a) => (a.symbol ? `${a.path}#${a.symbol}` : a.path));
36
+ const failed = anchors
37
+ .filter((a) => !ok.includes(a.symbol ? `${a.path}#${a.symbol}` : a.path))
38
+ .map((a) => (a.symbol ? `${a.path}#${a.symbol}` : a.path));
39
+ if (failed.length === 0)
40
+ return `;锚定代码 ${ok.length} 处`;
41
+ return ok.length > 0
42
+ ? `;锚定代码 ${ok.length} 处(未锚定: ${failed.join(', ')} — 文件或符号不存在)`
43
+ : `;锚点全部未生效(${failed.join(', ')} — 文件或符号不存在)`;
44
+ }
3
45
  // ---------- memory_save ----------
4
46
  // 存一条长期记忆(跨会话)。启动只把标题/摘要注入索引(几百 token);详情按需 memory_search 取。
5
47
  // 撞库(name→id 已存在)拒绝,引导用 memory_update。
@@ -23,6 +65,14 @@ export const memorySaveTool = {
23
65
  description: 'Category, default fact',
24
66
  },
25
67
  pinned: { type: 'boolean', description: 'Pin (exempt from auto-forgetting decay), default false' },
68
+ trigger: {
69
+ type: 'string',
70
+ description: 'R1.5 WHEN this memory applies — the situation that should make a future session recall it, e.g. "constructing a tool schema for kimi-k3 via dashscope". Write a condition, not "applies to code changes". Optional at first write (leave empty if you cannot predict it); required in spirit for pitfall/decision/feedback. It may be filled in later once the situation actually recurs.',
71
+ },
72
+ action: {
73
+ type: 'string',
74
+ description: 'R1.5 WHAT to do when the trigger holds — a concrete action ("strip uniqueItems recursively before sending"), not a restatement of the symptom.',
75
+ },
26
76
  scope: {
27
77
  type: 'string',
28
78
  enum: ['project', 'global'],
@@ -45,6 +95,24 @@ export const memorySaveTool = {
45
95
  required: ['relation', 'dst'],
46
96
  },
47
97
  },
98
+ anchors: {
99
+ type: 'array',
100
+ description: 'R2 code anchors: the code this memory talks about. Record them when the memory describes how a specific file/function works, so a later change to that code can mark the memory stale instead of silently serving an outdated fact. Pass paths/symbols only — the content hash is computed for you at write time. Anchors that cannot be resolved (file or symbol not found) are dropped.',
101
+ items: {
102
+ type: 'object',
103
+ properties: {
104
+ path: {
105
+ type: 'string',
106
+ description: 'Workspace-relative file path, e.g. "src/memory/store.ts" (forward slashes)',
107
+ },
108
+ symbol: {
109
+ type: 'string',
110
+ description: 'Optional function/class/const name. Prefer this over a whole-file anchor — it avoids false staleness when unrelated code in the same file changes.',
111
+ },
112
+ },
113
+ required: ['path'],
114
+ },
115
+ },
48
116
  },
49
117
  required: ['name', 'summary', 'body'],
50
118
  },
@@ -60,6 +128,9 @@ export const memorySaveTool = {
60
128
  return '错误:缺少 body。';
61
129
  const type = typeof args.type === 'string' ? args.type : undefined;
62
130
  const scope = args.scope === 'global' ? 'global' : 'project';
131
+ const trigger = typeof args.trigger === 'string' ? args.trigger.trim() : '';
132
+ const action = typeof args.action === 'string' ? args.action.trim() : '';
133
+ const anchors = parseAnchorInputs(args.anchors);
63
134
  const r = saveEntry({
64
135
  name,
65
136
  summary,
@@ -67,10 +138,19 @@ export const memorySaveTool = {
67
138
  type,
68
139
  pinned: args.pinned === true,
69
140
  scope,
141
+ trigger: trigger || undefined,
142
+ action: action || undefined,
143
+ anchors,
70
144
  });
71
145
  if (!r.ok) {
146
+ // R8.3/R8.5:写入被总闸拦下必须与「已存在」分开说,否则模型会以为换个 name
147
+ // 就能写进去,反复重试一条永远写不进去的路径。
148
+ if ('blocked' in r)
149
+ return memoryWriteBlockedMessage(r.blocked);
72
150
  return `已存在同名记忆 [${r.exists}]。改用 memory_update(id="${r.exists}", …) 更新,或换一个 name。`;
73
151
  }
152
+ // 锚点解析失败的要说出来:静默丢弃会让模型以为「已锚定」,下次代码改了也不会得到提示。
153
+ const anchorNote = anchorNoteOf(anchors);
74
154
  // 知识图谱挂边:容错——图失败不影响记忆保存结果
75
155
  const links = Array.isArray(args.links) ? args.links : [];
76
156
  let linked = 0;
@@ -90,6 +170,6 @@ export const memorySaveTool = {
90
170
  linked++;
91
171
  }
92
172
  const linkNote = links.length > 0 ? `;知识图谱挂边 ${linked}/${links.length}` : '';
93
- return `已保存记忆 [${r.id}] "${name}"(下次启动进索引)${linkNote}。`;
173
+ return `已保存记忆 [${r.id}] "${name}"(下次启动进索引)${linkNote}${anchorNote}。`;
94
174
  },
95
175
  };