mocode-ai 1.8.9 → 1.9.0

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 (65) 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/attachments/clipboard.js +22 -0
  7. package/dist/attachments/image.js +63 -0
  8. package/dist/changeset/hash.js +17 -0
  9. package/dist/changeset/index.js +6 -10
  10. package/dist/context/text-search.js +28 -10
  11. package/dist/flows/cli.js +1 -1
  12. package/dist/flows/flow.js +1 -1
  13. package/dist/flows/trace.js +1 -1
  14. package/dist/headless.js +23 -0
  15. package/dist/i18n/index.js +16 -2
  16. package/dist/index.js +1 -1
  17. package/dist/memory/anchor.js +319 -0
  18. package/dist/memory/audit.js +65 -0
  19. package/dist/memory/episodic.js +546 -0
  20. package/dist/memory/graph.js +233 -9
  21. package/dist/memory/health.js +208 -0
  22. package/dist/memory/index.js +12 -3
  23. package/dist/memory/pending.js +269 -0
  24. package/dist/memory/portable.js +150 -0
  25. package/dist/memory/proactive.js +588 -0
  26. package/dist/memory/recall-stats.js +1 -1
  27. package/dist/memory/reflect.js +260 -6
  28. package/dist/memory/relation-vocab.js +26 -4
  29. package/dist/memory/store.js +587 -41
  30. package/dist/memory/tail.js +88 -0
  31. package/dist/memory/write-gate.js +44 -0
  32. package/dist/permissions/computer-review.js +1 -1
  33. package/dist/permissions/flow-review.js +1 -1
  34. package/dist/repl/commands/flow.js +1 -1
  35. package/dist/repl/commands/image.js +30 -17
  36. package/dist/repl/commands/memory.js +257 -6
  37. package/dist/repl/commands/session.js +13 -0
  38. package/dist/repl/commands/tool-group.js +6 -0
  39. package/dist/repl/commands.js +1 -0
  40. package/dist/repl/episode-finalize.js +55 -0
  41. package/dist/repl/message-format.js +18 -0
  42. package/dist/repl/runtime.js +110 -5
  43. package/dist/runtime/uia-selector.js +1 -1
  44. package/dist/runtime/uia-service.js +3 -3
  45. package/dist/runtime/wait-until.js +1 -1
  46. package/dist/runtime/window-list.js +1 -1
  47. package/dist/sandbox/policy.js +49 -0
  48. package/dist/session/compact.js +47 -12
  49. package/dist/session/gui-actions.js +1 -1
  50. package/dist/tools/builtins/computer.js +5 -5
  51. package/dist/tools/builtins/memory-graph.js +12 -1
  52. package/dist/tools/builtins/memory-list.js +13 -3
  53. package/dist/tools/builtins/memory-save.js +82 -2
  54. package/dist/tools/builtins/memory-search.js +57 -2
  55. package/dist/tools/builtins/memory-update.js +52 -1
  56. package/dist/tools/builtins/read-file.js +51 -2
  57. package/dist/tools/builtins/run-flow.js +1 -1
  58. package/dist/tools/constants.js +60 -0
  59. package/dist/ui/clipboard.js +97 -0
  60. package/dist/ui/layout-internal/core.js +1 -1
  61. package/dist/ui/layout-internal/input-paint.js +7 -5
  62. package/dist/ui/layout-internal/state.js +8 -0
  63. package/dist/ui/layout-internal/statusbar.js +22 -1
  64. package/dist/ui/prompt-internal/editor.js +39 -0
  65. package/package.json +6 -1
@@ -0,0 +1,55 @@
1
+ // episode-finalize.ts —— 把「当前会话」落成一条情节记忆(R6.1)的 REPL 侧胶水。
2
+ //
3
+ // 为什么放在 repl/ 而不是 memory/episodic.ts:
4
+ // 内容来源横跨两个子系统——请求与改动文件来自 `history`(repl/agent 的资产),
5
+ // 未完成项来自 `notes.md`(session/notes)。真把它们塞进 memory/episodic.ts 会让
6
+ // memory 反向依赖 session,而 session/retention.ts 已经 import 了 memory/index
7
+ // (memory → session 与 session → memory 同时成立就是环)。
8
+ // 所以 episodic.ts 保持叶子(只认参数),本文件负责组装,依赖方向 repl → {memory, session}。
9
+ //
10
+ // 产出是**确定性、零 LLM**的(理由见 episodic.ts 头注释):退出路径不能等模型。
11
+ import { readFileSync } from 'node:fs';
12
+ import { isMemoryEnabled } from '../config/index.js';
13
+ import { getNotesFilePath } from '../session/notes.js';
14
+ import { collectChangedFiles, extractCompactionSummary, parsePendingSteps, recordSessionEpisode, } from '../memory/episodic.js';
15
+ /** 读 notes.md 正文;无文件/读失败返 null(不是错误——大多数会话没有 notes)。 */
16
+ function readNotes(sessionId) {
17
+ const p = getNotesFilePath(sessionId);
18
+ if (!p)
19
+ return null;
20
+ try {
21
+ return readFileSync(p, 'utf8');
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ /**
28
+ * 把当前会话落成情节记忆。幂等:同一会话被调用多次(退出 + /clear + /resume 切换)
29
+ * 只会刷新同一条,不会产生多条。
30
+ *
31
+ * 调用时机(全部在**会话状态还完整**时):
32
+ * ① REPL 主循环退出前;
33
+ * ② `/clear` 丢弃 history 之前;
34
+ * ③ `/resume`/`/sessions` 换掉 history 之前。
35
+ *
36
+ * 关于 Ctrl+C:TUI 下终端常驻 raw 模式(`editor.ts` 的 setRawMode(true)),此时 Ctrl+C 只是
37
+ * 一个按键、**不产生 SIGINT**——输入框为空时 `onCtrlC()` reject 后由主循环 `catch { break }`
38
+ * 接住,因此照样走 ①,情节正常落盘。真正跳过本函数的只有非 raw 模式(非 TTY / setRawMode
39
+ * 失败退化 readline)下的进程级 SIGINT → `process.exit(130)`,那条路径不承诺副作用完成,
40
+ * 与 drainMemoryBackground 的既有取舍一致。
41
+ */
42
+ export function finalizeCurrentEpisode(sessionId, history, queries) {
43
+ if (!sessionId)
44
+ return { ok: false, reason: 'no-session' };
45
+ if (!isMemoryEnabled())
46
+ return { ok: false, reason: 'disabled' };
47
+ const notes = readNotes(sessionId);
48
+ return recordSessionEpisode({
49
+ sessionId,
50
+ queries,
51
+ changedFiles: collectChangedFiles(history),
52
+ summaryText: extractCompactionSummary(history),
53
+ pendingSteps: parsePendingSteps(notes),
54
+ });
55
+ }
@@ -187,18 +187,36 @@ export function renderHistory(history) {
187
187
  if (atts && atts.length > 0) {
188
188
  for (const a of atts) {
189
189
  layout.contentWrite(` ${ui.dim}${renderChip(a)}${ui.reset}\n`);
190
+ if (a.downscaledFrom) {
191
+ const msg = a.path.startsWith('clipboard:')
192
+ ? t('prompt.imageDownscaled', {
193
+ width: a.downscaledFrom.width,
194
+ height: a.downscaledFrom.height,
195
+ })
196
+ : t('prompt.imageDownscaledFile', {
197
+ width: a.downscaledFrom.width,
198
+ height: a.downscaledFrom.height,
199
+ });
200
+ layout.contentWrite(` ${ui.yellow}${msg}${ui.reset}\n`);
201
+ }
190
202
  }
203
+ // 与实时 echoInput 同口径:附件区后补一个空行再进 agent 正文。
204
+ layout.contentWrite('\n');
191
205
  }
192
206
  else if (Array.isArray(m.content)) {
193
207
  // 旧 session 没侧 channel:从 data URL 头抽 mime,显一个通用 chip
194
208
  const c = m.content;
209
+ let fallbackChips = 0;
195
210
  for (const p of c) {
196
211
  if (p && typeof p === 'object' && p.type === 'image_url') {
197
212
  const url = p.image_url?.url ?? '';
198
213
  const mime = url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image';
199
214
  layout.contentWrite(` ${ui.dim}📷 ${mime}${ui.reset}\n`);
215
+ fallbackChips++;
200
216
  }
201
217
  }
218
+ if (fallbackChips > 0)
219
+ layout.contentWrite('\n');
202
220
  }
203
221
  continue;
204
222
  }
@@ -21,10 +21,13 @@ import '../tools/builtins/index.js';
21
21
  import { initializeAllMcp, getMcpTools, closeAllMcp } from '../mcp/index.js';
22
22
  import { refreshChatTools, classifyChatError } from '../llm/index.js';
23
23
  import { renderChip } from '../attachments/image.js';
24
+ import { readClipboardAsAttachment } from '../attachments/clipboard.js';
25
+ import { modelSupportsVision } from '../llm/capabilities.js';
24
26
  import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index.js';
25
27
  import { effectiveSystemPrompt, skillsChangedSinceLastObserve } from '../skills/index.js';
26
28
  import { clearSkillActivation } from '../skills/activation.js';
27
- import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, initPersona, gcMemories, kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, } from '../memory/index.js';
29
+ import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, buildEpisodeSection, initPersona, gcMemories, kickoffReflection, kickoffConsolidation, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSection, } from '../memory/index.js';
30
+ import { finalizeCurrentEpisode } from './episode-finalize.js';
28
31
  import { collectQueryHistory } from '../session/query-history.js';
29
32
  import { ToolPolicyController } from '../tools/policy.js';
30
33
  import { routeToolGroups } from '../tools/router.js';
@@ -71,6 +74,30 @@ let pendingTimer = null;
71
74
  * (供 renderHistory 复显文件名——base64 不可逆地塞进 history 后,只能从侧 channel 拿原文件名)。
72
75
  * messageAttachments 已移到 ./message-format.ts (共享 Map,renderHistory 与 runTurn 都用)。 */
73
76
  let pendingAttachments = [];
77
+ /**
78
+ * 把待发附件同步到脚栏「虚拟空行」(spinner 行上方,不进内容缓冲):
79
+ * chip 后挂降采样 badge(↓WxH,黄色);当前模型不支持视觉时行尾再拼短预警。
80
+ * 提交/撤回/清空/附加后都调一次;真正的归属与完整降采样说明在 echoInput 气泡下显示。
81
+ */
82
+ function syncPendingAttachChips() {
83
+ if (pendingAttachments.length === 0) {
84
+ layout.setPendingAttachChips([], '');
85
+ return;
86
+ }
87
+ const chips = pendingAttachments.map((a) => {
88
+ const badge = a.downscaledFrom
89
+ ? `${ui.yellow} ${t('prompt.imageDownscaledBadge', {
90
+ width: a.downscaledFrom.width,
91
+ height: a.downscaledFrom.height,
92
+ })}${ui.dim}`
93
+ : '';
94
+ return `${renderChip(a)}${badge}`;
95
+ });
96
+ const warning = modelSupportsVision(config.model)
97
+ ? ''
98
+ : `${ui.yellow}${t('prompt.imageVisionWarningShort', { model: config.model })}${ui.reset}`;
99
+ layout.setPendingAttachChips(chips, warning);
100
+ }
74
101
  // ── onRunningKey / onRunningMousePaste / startRunningListener / stopRunningListener 已移到 ./running-input.ts ──
75
102
  // formatUserMessage 已移到 ./message-format.ts
76
103
  /** 把多行提交输入回显进内容区(❯ 首行,续行按 prompt 宽度缩进)。仅 TUI 态回显(非 TTY 由 readline 自带回显)。 */
@@ -78,14 +105,46 @@ function echoInput(lines, trailingBlank = true) {
78
105
  if (!layout.isActive())
79
106
  return;
80
107
  layout.contentWrite(formatUserMessage(lines, trailingBlank));
81
- // 多模态附件:每张一行 chip 跟在 user bubble 后(原 /rollback /resume 复显一致)
108
+ // 多模态附件:每张一行 chip 跟在 user bubble 后(原 /rollback /resume 复显一致);
109
+ // 被降采样的图下一行给完整说明(脚栏只有 ↓WxH badge,正式归属处要说清原图尺寸)。
82
110
  for (const a of pendingAttachments) {
83
111
  layout.contentWrite(` ${ui.dim}${renderChip(a)}${ui.reset}\n`);
112
+ if (a.downscaledFrom) {
113
+ // 文件附件(/image <path>)磁盘原图还在;剪贴板附件原图不落盘——措辞分开,避免误导。
114
+ const msg = a.path.startsWith('clipboard:')
115
+ ? t('prompt.imageDownscaled', { width: a.downscaledFrom.width, height: a.downscaledFrom.height })
116
+ : t('prompt.imageDownscaledFile', { width: a.downscaledFrom.width, height: a.downscaledFrom.height });
117
+ layout.contentWrite(` ${ui.yellow}${msg}${ui.reset}\n`);
118
+ }
84
119
  }
120
+ // 有附件时 formatUserMessage 的尾空行落在 chip 之前(气泡→空行→chip),chip 与 agent
121
+ // 正文之间还需补一个空行,否则回复紧贴截图 chip(无附件时尾空行本就是分隔,不用补)。
122
+ if (pendingAttachments.length > 0)
123
+ layout.contentWrite('\n');
85
124
  // 用户气泡会填满终端整列宽;Windows Terminal 在末列进入 pending-wrap 后,紧随的 LF
86
125
  // 偶尔只更新内部滚屏状态,导致上一轮耗时行与新气泡暂时黏连。缓冲中的物理行始终正确,
87
126
  // 提交后立即按缓冲重绘,避免必须等滚动或 Agent 结束时的 repaint 才显示正确边界。
88
127
  layout.repaintViewport();
128
+ // chip 已在气泡下正式回显 → 清脚栏 pending 提示(不清 pendingAttachments:路由未完成,
129
+ // flush 在 runTurn 里;若 500ms 撤回窗口内被 recall,rewindContent 后会重新 sync 回来)。
130
+ if (pendingAttachments.length > 0)
131
+ layout.setPendingAttachChips([], '');
132
+ }
133
+ /**
134
+ * Ctrl+Y:从系统剪贴板抓截图 → 构造附件 → push 待发队列 → 同步脚栏。
135
+ *
136
+ * 成功(含重复图去重)返回 null——chip / ↓WxH 降采样 badge / 非视觉模型短预警都在脚栏
137
+ * 虚拟空行,不写内容缓冲;剪贴板无图返 {kind:'empty'}(黄提示),图太大/格式不支持返
138
+ * {kind:'error'}(红提示,透传 reason)。
139
+ */
140
+ async function pasteImageFromClipboard() {
141
+ const r = await readClipboardAsAttachment();
142
+ if (!r.ok)
143
+ return 'empty' in r ? { kind: 'empty' } : { kind: 'error', reason: r.reason };
144
+ if (!pendingAttachments.some((a) => a.id === r.att.id))
145
+ pendingAttachments.push(r.att);
146
+ syncPendingAttachChips();
147
+ return null;
89
148
  }
90
149
  /**
91
150
  * 等待 pending 撤回窗口(用户 Enter 后、agent 真发请求前的 500ms 兜底)。
@@ -214,6 +273,9 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
214
273
  // best-effort
215
274
  }
216
275
  }
276
+ // R17:会话内记忆尾注的基线在**会话边界**拍一次(启动 / /clear / /resume)。
277
+ // 放在 gcMemories 之后:GC 归档的条目刚落定,基线应以「会话真正开始时」的库为准。
278
+ captureMemoryBaseline();
217
279
  // 开关现读:运行时 /memory_switch 重建 history[0] 时,About you 与 Memory Index 同步显隐。
218
280
  const buildSystemMessage = (planMode) => {
219
281
  const memoryOn = isMemoryEnabled();
@@ -221,6 +283,8 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
221
283
  buildAboutYouSection(memoryOn) +
222
284
  (planMode ? getPlanModeSuffix() : '') +
223
285
  buildMemoryIndexSection(memoryOn) +
286
+ // R6.3:情节走独立小节(不进 Memory Index / 不进 About you,理由见 episodic.ts)。
287
+ buildEpisodeSection(memoryOn) +
224
288
  buildProjectGraphHint(memoryOn));
225
289
  };
226
290
  // 有预加载(--resume)则用它,并把 history[0] 刷成当前 system prompt(config 可能已变);
@@ -554,6 +618,7 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
554
618
  // 回填后用户再发随消息一起带走;side channel 也不会在未 push user msg 时错写 index。
555
619
  const imgs = pendingAttachments;
556
620
  pendingAttachments = [];
621
+ syncPendingAttachChips(); // 已随消息提交:清脚栏 pending chip(归属显示在 echoInput 的气泡下)
557
622
  const userInput = imgs.length === 0
558
623
  ? input
559
624
  : [
@@ -572,10 +637,15 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
572
637
  messageAttachments.set(msgIndex, imgs);
573
638
  // 运行中每步 chat() 返回后刷新状态行 context 用量条(用 fresh lastUsage / 估算),
574
639
  // 否则整轮冻结在轮首 refreshStatusBase 的值,「执行 grep」时 2k/1000k 不动。
640
+ // 前摄通道的每轮限额在此重置(R3.4):按进程计会让常驻 REPL 几轮后永久静默。
641
+ resetProactiveTurn();
575
642
  const result = await runAgent(history, userInput, signal, () => {
576
643
  refreshStatusBase(history);
577
644
  layout.drawStatusBar();
578
- }, toolPolicy, initialToolRoute, runtime);
645
+ }, toolPolicy, initialToolRoute,
646
+ // R17:每用户轮现算一次「本会话内新增/更新的记忆」。走 ephemeral 尾注,不重建
647
+ // history[0](否则整段对话的前缀缓存每轮失效)。基线无变化时返回空串 → 零注入。
648
+ buildMemoryTailSection(isMemoryEnabled()), runtime);
579
649
  // 撞限 salvage 摘要要在 TUI 落地:runAgent 只把 finalText 带回不渲染,主线撞限的
580
650
  // 收尾摘要若不打印,这笔收尾请求的 token 就白花(用户只看到「达到最大步数」一行)。
581
651
  if (result.terminationReason === 'max_steps' && result.finalText) {
@@ -598,10 +668,23 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
598
668
  }
599
669
  // 后台反思:每 reflectEveryN 轮 fire-and-forget 一次(与下一轮 agent 并发,不阻塞)。
600
670
  // 已有在飞任务 / autoReflect 关 → kickoff 内部自守卫。快照同步取(避免下一轮 mutate history 竞态)。
671
+ // 召回计数脏集在此统一落盘:搜索本身不再写盘(纯读语义),一轮一次即可。
672
+ flushRecallStats();
673
+ // R4.1:前摄计数同样是内存累计(每次工具调用都写盘会变成写放大热点),
674
+ // 与召回计数一起在轮末落一次。健康快照仍只由 /memory health 与退出路径写,
675
+ // 因为它要读全库 + 算 stale,不该每轮付这个成本。
676
+ flushProactiveStats();
601
677
  turnCount++;
602
678
  if (turnCount % config.reflectEveryN === 0) {
603
679
  kickoffReflection(snapshotTranscript(history, 20));
604
680
  }
681
+ else {
682
+ // R11:非反思轮才轮到情节巩固。两者共用同一个在飞槽位(后台 LLM 任务串行,
683
+ // 不并压两条请求给后端),所以放在 else 里而不是紧跟其后 —— 否则反思刚占住
684
+ // 槽位,巩固这一轮必然被静默跳过,实际 cadence 会漂移成"只有反思没命中时才跑"。
685
+ // 无候选时它是纯本地计算,零成本返回。
686
+ kickoffConsolidation();
687
+ }
605
688
  }
606
689
  catch (e) {
607
690
  ok = false;
@@ -672,6 +755,9 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
672
755
  async function resumeFromPick(pick) {
673
756
  if (!pick)
674
757
  return; // Esc / Ctrl+D 取消
758
+ // R6.1:切换前把**当前**会话落成情节记忆——下面 history.length=0 之后内容就没了。
759
+ // 幂等,重复切换只会刷新同一条。
760
+ finalizeCurrentEpisode(currentSessionId, history, queryHistory);
675
761
  const loaded = runtime.session.resume(pick.id);
676
762
  if (!loaded || !loaded.history.length) {
677
763
  layout.contentWrite(`${ui.yellow}${t('repl.loadFailed')}${ui.reset}\n`);
@@ -685,6 +771,9 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
685
771
  history.length = 0;
686
772
  history.push(...loaded.history);
687
773
  queryHistory = loaded.queryHistory ? [...loaded.queryHistory] : queryHistoryFromMessages(loaded.history);
774
+ // R17:换会话是会话边界,尾注基线重拍——否则被切换掉的那段会话里写的条目,
775
+ // 会在续接会话的第一轮被当成「新学到的」重复播报。
776
+ captureMemoryBaseline();
688
777
  lastToolGroups = [...(loaded.lastToolGroups ?? [])];
689
778
  setAgentMode('auto'); // 续接重置为 auto(mode 不落盘;listener 重写 history[0] 回 auto,与 loaded 幂等)
690
779
  contextState.lastUsage = undefined;
@@ -744,6 +833,7 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
744
833
  prompt: PROMPT,
745
834
  commands: buildSlashCommands(),
746
835
  onCycleMode: cycleMode,
836
+ onPasteImage: pasteImageFromClipboard,
747
837
  // Ctrl+R / Ctrl+P 历史搜索候选源:惰性工厂——当前会话内存 queryHistory + 最近落盘会话,
748
838
  // 聚合要读盘,只有面板真正打开(Ctrl+R/P)才求值,平常轮次零开销
749
839
  history: () => collectQueryHistory(queryHistory).map((e) => e.text),
@@ -841,9 +931,11 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
841
931
  list: () => pendingAttachments,
842
932
  clear: () => {
843
933
  pendingAttachments = [];
934
+ syncPendingAttachChips();
844
935
  },
845
936
  push: (att) => {
846
937
  pendingAttachments.push(att);
938
+ syncPendingAttachChips();
847
939
  },
848
940
  },
849
941
  buildSystemMessage,
@@ -888,7 +980,10 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
888
980
  layout.contentWrite(`${ui.dim}${t('repl.unknownCommandHint')}${ui.reset}\n`);
889
981
  continue; // 与其他命令一致:回 INPUT 态由循环顶部的 normalizeInputBoundary + enterInputMode 负责
890
982
  }
891
- const bubbleRows = input.length + 2 + pendingAttachments.length; // N 行 message + 2 行尾随空(含 \n\n 留下的 open current 行) + 每附件 1 行
983
+ // N 行 message + 2 行尾随空(含 \n\n 留下的 open current 行) + 每附件 1 行 chip
984
+ // + 每降采样附件 1 行完整说明 + 有附件时 chip 区与 agent 正文间的 1 行分隔空行。
985
+ const downscaledCount = pendingAttachments.filter((a) => a.downscaledFrom).length;
986
+ const bubbleRows = input.length + 2 + pendingAttachments.length + downscaledCount + (pendingAttachments.length > 0 ? 1 : 0);
892
987
  // 排队消息入队时即已确认 → 跳过 500ms 撤回窗口,直接发送。
893
988
  const shouldCommit = autoSend || (await awaitPendingRecall(input));
894
989
  if (!shouldCommit) {
@@ -897,6 +992,7 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
897
992
  // (runTurn 入口的 pendingAttachments.flush 仍按现有逻辑把附件塞进 userInput)。
898
993
  layout.rewindContent(bubbleRows);
899
994
  pendingPrefill = input;
995
+ syncPendingAttachChips(); // 撤回:echoInput 清掉的脚栏 chip 按保留的 pendingAttachments 恢复
900
996
  layout.enterInputMode(t('repl.idle'));
901
997
  continue;
902
998
  }
@@ -913,6 +1009,7 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
913
1009
  queryHistory.pop();
914
1010
  layout.rewindContent(bubbleRows);
915
1011
  pendingPrefill = input;
1012
+ syncPendingAttachChips(); // 撤回:脚栏 chip 按保留的 pendingAttachments 恢复
916
1013
  layout.enterInputMode(t('repl.idle'));
917
1014
  continue;
918
1015
  }
@@ -938,7 +1035,15 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
938
1035
  }
939
1036
  }
940
1037
  }
941
- // 退出前等在飞反思收尾(Ctrl+C 走 SIGINT 直退不等;fire-and-forget 不承诺中断时完成)。
1038
+ // R6.1:退出前落情节(纯本地、零 LLM,毫秒级;放在 drain 之前让两者并行收尾)。
1039
+ finalizeCurrentEpisode(currentSessionId, history, queryHistory);
1040
+ // R4.1:退出时写一份健康快照。放这里而不是每轮:它要读全库 + 算 stale,
1041
+ // 每次退出一个文件,正好构成一条随时间推移的趋势线。
1042
+ flushProactiveStats();
1043
+ writeMemoryHealth(isMemoryEnabled());
1044
+ // 退出前等在飞反思收尾。注意:Ctrl+C 在 TUI(raw 模式)下是按键不是 SIGINT,空输入框时
1045
+ // 由主循环 catch { break } 接住,因此**会**走到这里等反思跑完;只有非 raw 模式下的
1046
+ // 进程级 SIGINT → process.exit(130) 才跳过(fire-and-forget 不承诺中断时完成)。
942
1047
  await drainMemoryBackground();
943
1048
  await runtime.close();
944
1049
  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 = {