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
@@ -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
  };
@@ -1,4 +1,5 @@
1
- import { searchEntries } from '../../memory/store.js';
1
+ import { searchEntries, loadStalenessMap, } from '../../memory/store.js';
2
+ import { describeAnchorState, evaluateAnchors } from '../../memory/anchor.js';
2
3
  import { searchGraphFacts } from '../../memory/graph.js';
3
4
  import { recordRecallSearch } from '../../memory/recall-stats.js';
4
5
  // ---------- memory_search ----------
@@ -6,6 +7,37 @@ import { recordRecallSearch } from '../../memory/recall-stats.js';
6
7
  // (CJK 分词加权、边级相关度 + 一跳邻接,跨 global/project 两 scope)。命中条目即 bump
7
8
  // recallCount(遗忘衰减依据)。结果走 capToolResultForHistory 的放宽上限(同 use_skill)。
8
9
  const GRAPH_FACTS_LIMIT = 10;
10
+ /**
11
+ * R14:状态标记。**默认 active 且非失效时不输出任何东西**——绝大多数查询走默认
12
+ * `status:'active'`,那条路径必须零噪音,否则每条记忆都多一行前缀,白占上下文。
13
+ *
14
+ * R2:代码锚点失效走同一个位置但**分开措辞**。两种失效要模型做的事不一样:
15
+ * `STALE-DERIVED` 是「这条结论的根据没了」,`STALE-CODE` 是「结论可能仍对,但它描述的
16
+ * 那段代码/行号/细节要重新核对」——合并成一句会丢掉这个区别。
17
+ */
18
+ function statusMark(e, st, anchor) {
19
+ const parts = [];
20
+ if (e.status === 'superseded')
21
+ parts.push(`SUPERSEDED${e.supersededBy ? ` → ${e.supersededBy}` : ''}`);
22
+ else if (e.status === 'archived')
23
+ parts.push('ARCHIVED');
24
+ if (st?.stale) {
25
+ // 失效原因是给模型判断"还能不能用"的关键:源被取代(结论可能仍成立)
26
+ // 与源被删(根据没了)是两回事。
27
+ const why = [
28
+ st.inactive.length > 0 ? `源已失效: ${st.inactive.join(', ')}` : '',
29
+ st.missing.length > 0 ? `源已被删除: ${st.missing.join(', ')}` : '',
30
+ ]
31
+ .filter(Boolean)
32
+ .join('; ');
33
+ parts.push(`STALE-DERIVED${why ? ` (${why})` : ''}`);
34
+ }
35
+ if (anchor?.stale) {
36
+ const why = describeAnchorState(anchor);
37
+ parts.push(`STALE-CODE${why ? ` (${why})` : ''}`);
38
+ }
39
+ return parts.length > 0 ? ` [${parts.join(' | ')}]` : '';
40
+ }
9
41
  export const memorySearchTool = {
10
42
  name: 'memory_search',
11
43
  description: 'Search memory entries by keyword (substring match), returning full body. Also surfaces knowledge-graph facts (active edges across project + global), ranked by CJK-aware term overlap on entity names/aliases/relation/fact, plus one-hop neighbor edges for context.',
@@ -35,8 +67,31 @@ export const memorySearchTool = {
35
67
  status: typeof args.status === 'string' ? args.status : undefined,
36
68
  limit: typeof args.limit === 'number' ? args.limit : undefined,
37
69
  });
70
+ // R14:派生条目的失效判定要拿全库做源查找(源可能在另一 scope,也可能已被硬删),
71
+ // 不能在命中结果集内自洽判断。searchEntries 已 bump 过 recall,这里再 loadAll
72
+ // 拿到的是同一份(含脏集增量),不会引入不一致。
73
+ const staleInfo = r.length > 0 ? loadStalenessMap() : new Map();
74
+ // R2:锚点判定只针对**命中条目**,不走 loadAnchorStaleMap(那会扫全库并 stat 每个锚点)。
75
+ // 命中集通常 5 条,而且 readCached 有 mtime 缓存,成本可以忽略。
76
+ const anchorInfo = new Map();
77
+ for (const e of r) {
78
+ if (!e.anchors || e.anchors.length === 0)
79
+ continue;
80
+ anchorInfo.set(e.id, evaluateAnchors(e.anchors));
81
+ }
38
82
  const entryText = r
39
- .map((e) => `# [${e.id}] ${e.name} (${e.type}, recalled ${e.recallCount})\nsummary: ${e.summary}\n\n${e.body}`)
83
+ .map((e) => {
84
+ // R1.5:条件-动作字段放在最前面,它们是"要不要用上这条记忆"的判断依据;
85
+ // 只有存在时才输出,老条目无此字段不受影响。
86
+ const lead = [e.trigger ? `when: ${e.trigger}` : '', e.action ? `do: ${e.action}` : '']
87
+ .filter(Boolean)
88
+ .join('\n');
89
+ // R14:状态标记必须紧贴标题。模型是把整块结果当"现状"读的——一条已被取代的
90
+ // 条目混在 active 里,它不会自己去比对 updatedAt。实测 status='any' 时 archived
91
+ // 条目能占到前 4 名,不给标记就等于把过期事实当现状喂进去。
92
+ const mark = statusMark(e, staleInfo.get(e.id), anchorInfo.get(e.id));
93
+ return `# [${e.id}] ${e.name} (${e.type}, recalled ${e.recallCount})${mark}\nsummary: ${e.summary}\n${lead ? lead + '\n' : ''}\n${e.body}`;
94
+ })
40
95
  .join('\n\n---\n\n');
41
96
  // 知识图谱事实段:边级相关度检索(容错:图坏了不连累条目搜索)。
42
97
  let graphText = '';
@@ -1,4 +1,24 @@
1
1
  import { updateEntry } from '../../memory/store.js';
2
+ /**
3
+ * anchors 参数归一(同 memory_save):只取 path/symbol,hash 由 store 现算。
4
+ * 传空数组表示**清空**锚点,传 undefined 表示不动。
5
+ */
6
+ function parseAnchorInputs(raw) {
7
+ if (!Array.isArray(raw))
8
+ return [];
9
+ const out = [];
10
+ for (const item of raw) {
11
+ if (!item || typeof item !== 'object')
12
+ continue;
13
+ const a = item;
14
+ const p = typeof a.path === 'string' ? a.path.trim() : '';
15
+ if (!p)
16
+ continue;
17
+ const s = typeof a.symbol === 'string' ? a.symbol.trim() : '';
18
+ out.push({ path: p, ...(s ? { symbol: s } : {}) });
19
+ }
20
+ return out;
21
+ }
2
22
  // ---------- memory_update ----------
3
23
  // 原地改一条记忆(id 不变)。反思的弱意义:干活时发现事实变了/过时即纠正。
4
24
  export const memoryUpdateTool = {
@@ -14,6 +34,29 @@ export const memoryUpdateTool = {
14
34
  name: { type: 'string', description: 'New title (id does not change with name)' },
15
35
  pinned: { type: 'boolean', description: 'Toggle pin status (true pins and exempts decay / false unpins)' },
16
36
  reason: { type: 'string', description: 'Update reason (recorded in lastUpdateReason for traceability)' },
37
+ trigger: {
38
+ type: 'string',
39
+ description: 'R1.5 WHEN this memory applies. Use this to fill in a missing trigger after the situation actually recurred — that is the expected flow, do not invent a vague one up front. Pass "" to clear.',
40
+ },
41
+ action: {
42
+ type: 'string',
43
+ description: 'R1.5 WHAT to do when the trigger holds. Pass "" to clear.',
44
+ },
45
+ anchors: {
46
+ type: 'array',
47
+ description: 'R2 code anchors — REPLACES the whole set (pass [] to clear). Only paths/symbols; the content hash is recomputed at write time. Use this when the memory is about a specific file/function and you want a later edit to surface it as stale instead of silently serving an outdated fact.',
48
+ items: {
49
+ type: 'object',
50
+ properties: {
51
+ path: { type: 'string', description: 'Workspace-relative file path, e.g. "src/memory/store.ts"' },
52
+ symbol: {
53
+ type: 'string',
54
+ description: 'Optional function/class/const name; prefers a fragment over the whole file',
55
+ },
56
+ },
57
+ required: ['path'],
58
+ },
59
+ },
17
60
  },
18
61
  required: ['id'],
19
62
  },
@@ -32,8 +75,16 @@ export const memoryUpdateTool = {
32
75
  patch.reason = args.reason;
33
76
  if (typeof args.pinned === 'boolean')
34
77
  patch.pinned = args.pinned;
78
+ // trigger/action 无真值判断:空串是「清空」这个明确意图(见 updateEntry)。
79
+ if (typeof args.trigger === 'string')
80
+ patch.trigger = args.trigger;
81
+ if (typeof args.action === 'string')
82
+ patch.action = args.action;
83
+ // anchors 同理:空数组是「清空锚点」,不传才是「不动」。
84
+ if (args.anchors !== undefined)
85
+ patch.anchors = parseAnchorInputs(args.anchors);
35
86
  if (Object.keys(patch).length === 0)
36
- return '错误:至少传一个要改的字段(summary/body/name/pinned/reason)。';
87
+ return '错误:至少传一个要改的字段(summary/body/name/pinned/reason/trigger/action/anchors)。';
37
88
  const r = updateEntry(id, patch);
38
89
  if (r.ok)
39
90
  return `已更新记忆 [${id}]。`;
@@ -1,9 +1,11 @@
1
1
  import { readFile, stat } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
3
  import { contentHash } from '../../changeset/index.js';
4
+ import { entriesAnchoredTo } from '../../memory/store.js';
5
+ import { evaluateAnchorsAgainst, toAnchorPath } from '../../memory/anchor.js';
4
6
  import { IMAGE_READ_MARKER, MAX_FILE_LINES, MAX_HISTORY_RESULT } from '../constants.js';
5
7
  import { MAX_INLINE_BYTES_DEFAULT, isProbablyBinary, loadImageAttachmentWithDownscale, sniffImageMime, } from '../../attachments/image.js';
6
- import { config } from '../../config/index.js';
8
+ import { config, isMemoryEnabled } from '../../config/index.js';
7
9
  /** 默认单次 read_file 拉取的行数。刻意压低,逼 LLM 分块读大文件,
8
10
  * 配合 description 中的 PAGINATION IS MANDATORY 引导。
9
11
  * 300 行 ≈ 一个屏幕的源码量,够定位一段逻辑而不至于吃光上下文。 */
@@ -139,14 +141,21 @@ export const readFileTool = {
139
141
  };
140
142
  }
141
143
  }
142
- const output = end < lines.length
144
+ const baseOutput = end < lines.length
143
145
  ? `${artifactHeader}\n${body}\n\n... (${lines.length - end} 行未显示,共 ${lines.length} 行)`
144
146
  : `${artifactHeader}\n${body}`;
147
+ // R2.4:回注锚定本文件的记忆(最多 3 条,只回 fresh)。
148
+ // 为什么放在 read_file 而不是 system prompt:prompt 每轮注入会撞 cache,而且
149
+ // 「正在看这个文件」这一刻才是这条记忆最有用的时机;读到不相关的文件时零成本。
150
+ // 判定用**刚读到的这份 data**,不会再碰磁盘。
151
+ const output = baseOutput + memoryHintFor(path, data);
145
152
  // dedup 只登记「确实会进 context 的区间」。pushToolResult 会把超长输出经
146
153
  // capToolResultForHistory 中截到 MAX_HISTORY_RESULT(丢中段)——若此处仍登记
147
154
  // 完整 [reqStart, reqEnd],后续对「被截掉的中段」的重读会被 findUnchanged 命中,
148
155
  // 模型拿到 unchanged 短指针却找不到内容,只能反复缩小区间撞墙、最终用 shell 绕过
149
156
  // (实测事故:会话 20261012-033757)。故输出超 cap 时只登记头/尾两段实际保留的行。
157
+ // 用 output(含回注段)判长度:最终进 history 的就是它,回注把长度顶过 cap 时
158
+ // 必须按截断口径登记,否则会记成"完整保留"而制造幽灵命中。
150
159
  if (dedup && config.readDedup && output.length > MAX_HISTORY_RESULT) {
151
160
  const fileHash = contentHash(data);
152
161
  const truncated = truncatedOutputRanges(lines, start, end, output.length, MAX_HISTORY_RESULT);
@@ -159,6 +168,46 @@ export const readFileTool = {
159
168
  return { status: 'success', code: 'OK', retryable: false, output };
160
169
  },
161
170
  };
171
+ /** 回注条数上限。再多就变成噪音,模型会学会跳过这一段。 */
172
+ const MEMORY_HINT_LIMIT = 3;
173
+ /**
174
+ * 参与 fresh 判定的候选条数上限。
175
+ *
176
+ * 必须**先过滤 fresh、再截 3 条**:锚定同一个文件的记忆里,靠前的可能已经过期。
177
+ * 若先按 3 条截断再过滤,前 3 条恰好都 stale 时整段回注会静默消失,而第 4 条
178
+ * 明明仍然有效。这个上限只为防止上百条锚点时白跑一遍 hash 判定。
179
+ */
180
+ const MEMORY_HINT_SCAN = 20;
181
+ /**
182
+ * R2.4:本文件被哪些**仍然对得上**的记忆锚定。
183
+ *
184
+ * 只回 fresh 的:内容已经变了说明这条记忆过期,此刻提示它等于把旧事实塞进上下文;
185
+ * 它会在 `memory_search` 结果里带 `STALE-CODE` 标记出现,那里的语境更合适。
186
+ *
187
+ * 失败静默:记忆是增强通道,读文件本身的成功不能被它拖坏。
188
+ */
189
+ function memoryHintFor(path, data) {
190
+ try {
191
+ if (!isMemoryEnabled())
192
+ return '';
193
+ const anchorPath = toAnchorPath(path);
194
+ const hits = entriesAnchoredTo(anchorPath, { limit: MEMORY_HINT_SCAN });
195
+ if (hits.length === 0)
196
+ return '';
197
+ // 只判**本文件**的锚点:一条记忆可能同时锚定多个文件,拿本文件的文本去判别的文件
198
+ // 必然判 missing,整条记忆会被误当过期(见 evaluateAnchorsAgainst 的 anchorPath 说明)。
199
+ const fresh = hits
200
+ .filter((e) => !evaluateAnchorsAgainst(e.anchors, data, anchorPath).stale)
201
+ .slice(0, MEMORY_HINT_LIMIT);
202
+ if (fresh.length === 0)
203
+ return '';
204
+ const lines = fresh.map((e) => `- [${e.id}] ${e.name} — ${e.summary}`);
205
+ return `\n\n## Memory anchored to this file\n${lines.join('\n')}`;
206
+ }
207
+ catch {
208
+ return '';
209
+ }
210
+ }
162
211
  /**
163
212
  * 输出将被中截(头 60% / 尾 40%)时,反推真正保留进 context 的行区间。
164
213
  * 输出长度按行聚合估算:行号前缀(≤7 字符 + tab)与换行在各行间均摊,误差 ≤1 行,
@@ -1,5 +1,5 @@
1
1
  /**
2
- * run_flow 工具:回放 `.mocode/flows/<name>.json` 里录制好的桌面流程(design-notes/computer-use-rpa.md §5.3)。
2
+ * run_flow 工具:回放 `.mocode/flows/<name>.json` 里录制好的桌面流程(design-notes/computer-use/computer-use-rpa.md §5.3)。
3
3
  *
4
4
  * 与逐步调用 computer 的区别:整条流程不经过模型,按录制的 selector 现场定位元素,失败按步骤的
5
5
  * onError 策略重试 / 跳过 / 中止 / 交还模型。权限在整条 flow 层面一次做完(permissions/flow-review.ts):
@@ -70,6 +70,17 @@ export const USER_DIRECTIVE_MAX_CONSTRAINTS = 3;
70
70
  // ── 记忆(Tier-2 JSONL 工具库)──────────────────────────────────────────────
71
71
  /** 单条记忆 body 上限(字符)。进 history 前 memory_search 结果另有 MAX_MEMORY_RESULT 兜底。 */
72
72
  export const MAX_MEMORY_ENTRY = 4000;
73
+ /**
74
+ * 记忆检索的相关性下限:命中至少这么多个「证据词元」才算相关(R15 实测值)。
75
+ *
76
+ * 证据词元 = 长度 ≥ 2 的 token(ASCII 词或 CJK bigram),单个汉字不算 ——
77
+ * 「红烧肉怎么炖」里的「肉」「好」几乎必然出现在某条记忆正文里,这正是误报来源。
78
+ *
79
+ * 取值 2 的依据:`npm run eval:memory-retrieval` 的 6 条负例在 1 时仍会有 1 条漏过
80
+ * (只重合一个词就返回),取 2 后负例误报 100% → 0%,正例 recall@1 保持 98%。
81
+ * 代价是 1 条词面重合极弱的探针从 recall@3 掉出(pro-2),已记录在 R15 实施结果里。
82
+ */
83
+ export const MEMORY_SEARCH_MIN_EVIDENCE = 2;
73
84
  /** 启动注入 systemPrompt 的索引条目上限(遗忘封顶后 active 条目 ≤ MAX_ACTIVE,索引再封一层)。 */
74
85
  export const MAX_INDEX_ENTRIES = 50;
75
86
  /** active 记忆封顶:超则按 recallCount 低 × lastRecalledAt 老 淘汰到 archived。 */
@@ -78,6 +89,55 @@ export const MAX_ACTIVE = 100;
78
89
  export const DECAY_DAYS = 30;
79
90
  /** GC:archived 超 GC_DAYS → 硬删。 */
80
91
  export const GC_DAYS = 90;
92
+ /**
93
+ * R6 情节记忆的衰减周期,**刻意远短于事实记忆**。
94
+ *
95
+ * 情节是"最近发生了什么"的索引,价值随时间陡降:三天前的会话摘要还能帮你接上工作,
96
+ * 一个月前的只会挤占 token 并干扰判断。事实记忆(怎么配置、哪里有坑)则相反,
97
+ * 越久越该留。若共用 30/90 天,每会话一条 episode 会在两个月内堆到几百条,
98
+ * 把长期知识挤出 `MAX_ACTIVE` 的封顶——这是"情节淹没语义"的标准失败模式。
99
+ *
100
+ * 注意与 `buildEpisodeSection` 的注入上限配合:衰减周期决定**存多久**,
101
+ * 注入上限决定**每次显示几条**,两者必须同时生效才不会互相抵消。
102
+ */
103
+ export const EPISODE_DECAY_DAYS = 7;
104
+ /** 情节归档后多久硬删。比事实的 90 天短得多,理由同上。 */
105
+ export const EPISODE_GC_DAYS = 30;
106
+ /**
107
+ * R11 已巩固情节的衰减周期:被归纳进语义条目后,原始情节的价值只剩"哪次会话"的
108
+ * 追溯入口,主体知识已经在语义条目里。3 天足够覆盖"刚做完那次"的复盘窗口,
109
+ * 再久就是与已巩固的结论重复占 token。这是 R11.1 里「降权」的具体落法。
110
+ */
111
+ export const EPISODE_CONSOLIDATED_DECAY_DAYS = 3;
112
+ // ── R11 情节巩固(episode → 语义)──────────────────────────────────────────
113
+ /**
114
+ * 触发巩固的最少同主题情节数。
115
+ *
116
+ * 2 条不巩固:两条情节的"共性"很可能只是一次性的上下文(同一个 bug 修了两轮),
117
+ * 过早抽象会把噪声固化成长期事实。3 条且跨 2 个会话才够看出重复模式。
118
+ */
119
+ export const CONSOLIDATE_MIN_EPISODES = 3;
120
+ /** 触发巩固的最少不同会话数(单会话内的多次情节是同一件事的续集,不是模式)。 */
121
+ export const CONSOLIDATE_MIN_SESSIONS = 2;
122
+ /** 单次巩固最多处理的组数:后台任务要可控,且一组一次 LLM 调用。 */
123
+ export const CONSOLIDATE_MAX_GROUPS = 2;
124
+ /**
125
+ * 单组的成员上限。受 `store.ts` 的 `MAX_DERIVED_FROM`(8)约束——超过 8 条时
126
+ * `derivedFrom` 会被截断,剩下的源条目查不到来源反而失去可追溯性。
127
+ */
128
+ export const CONSOLIDATE_MAX_GROUP_SIZE = 8;
129
+ /** 分组时最多扫描的情节条数(按 createdAt 降序取最近的一批)。 */
130
+ export const CONSOLIDATE_SCAN_LIMIT = 40;
131
+ /** 两条情节的请求文本至少共享多少个非泛化 token 才算同主题。 */
132
+ export const CONSOLIDATE_MIN_TOKEN_OVERLAP = 2;
133
+ /** 喂给巩固模型的总输入字符预算(超了就整组丢弃,不做中截——残缺的组会被归纳错)。 */
134
+ export const CONSOLIDATE_INPUT_MAX_CHARS = 6000;
135
+ /** 启动时注入的最近 episode 条数(硬上限,见 R6.3)。 */
136
+ export const EPISODE_INJECT_LIMIT = 3;
137
+ /** 单条 episode 里保留的请求条数上限:一次会话几十轮很常见,全列等于存全文(R6.4 禁止)。 */
138
+ export const EPISODE_MAX_REQUESTS = 8;
139
+ /** 单条请求在 episode 里的字符上限(压平成一行后的截断长度)。 */
140
+ export const EPISODE_REQUEST_MAX_CHARS = 120;
81
141
  /** memory_search 结果(召回的记忆正文)的放宽上限:指令性内容,中截破坏语义,对齐 use_skill。 */
82
142
  export const MAX_MEMORY_RESULT = 64000;
83
143
  // ── 知识图谱层(memory-graph.json,单 scope 容量)──────────────────────────
@@ -1,5 +1,7 @@
1
1
  import { stdout, platform } from 'node:process';
2
2
  import { spawn } from 'node:child_process';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
3
5
  /**
4
6
  * 系统剪贴板读写(叶子模块,无 UI 依赖)。
5
7
  *
@@ -146,3 +148,98 @@ export async function readClipboard() {
146
148
  const xs = await captureOutput('xsel', ['--clipboard', '--output'], 'utf8');
147
149
  return xs ?? '';
148
150
  }
151
+ /** spawn 不吃 stdin 的命令,把 stdout 按二进制收集;空输出/失败返回 null(不抛)。 */
152
+ function captureBinary(cmd, args) {
153
+ return new Promise((resolve) => {
154
+ try {
155
+ const p = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
156
+ const chunks = [];
157
+ let settled = false;
158
+ const finish = (v) => {
159
+ if (settled)
160
+ return;
161
+ settled = true;
162
+ resolve(v);
163
+ };
164
+ p.stdout.on('data', (c) => chunks.push(c));
165
+ p.stdout.on('error', () => finish(null));
166
+ p.on('error', () => finish(null));
167
+ p.on('close', (code) => {
168
+ if (code !== 0)
169
+ return finish(null);
170
+ const buf = Buffer.concat(chunks);
171
+ finish(buf.length > 0 ? buf : null);
172
+ });
173
+ }
174
+ catch {
175
+ resolve(null);
176
+ }
177
+ });
178
+ }
179
+ /**
180
+ * 读取系统剪贴板里的图片(截图后 Win+Shift+S / Ctrl+C 图片文件的常见落点)。
181
+ *
182
+ * 各端统一导出 PNG 字节:
183
+ * - win32:STA 线程跑 WinForms `Clipboard::GetImage()` 存临时 PNG(剪贴板 API 要求 STA;
184
+ * Bitmap.Save 写文件而非 stdout,避免 PowerShell 管道把 PNG 当文本编码破坏字节);
185
+ * - darwin:osascript 让 Preview 风格的 `PNGf` TIFF 剪贴板项落到临时文件;
186
+ * - linux:Wayland `wl-paste -t image/png`;X11 `xclip -t image/png -o`。
187
+ *
188
+ * 剪贴板无图 / 工具缺失均返回 null(不抛),调用方按"剪贴板里没有图片"提示。
189
+ */
190
+ export async function readClipboardImage() {
191
+ if (platform === 'win32') {
192
+ const tmp = join(tmpdir(), `mocode-clip-${process.pid}-${Date.now()}.png`);
193
+ const out = await captureOutput('powershell', [
194
+ '-NoProfile',
195
+ '-NonInteractive',
196
+ '-STA',
197
+ '-Command',
198
+ `Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; ` +
199
+ `$img = $null; for ($i=0; $i -lt 5 -and $null -eq $img; $i++) { try { ` +
200
+ `$img = [System.Windows.Forms.Clipboard]::GetImage() } catch { Start-Sleep -Milliseconds 50 } }; ` +
201
+ `if ($null -ne $img) { $img.Save('${tmp.replace(/'/g, "''")}', [System.Drawing.Imaging.ImageFormat]::Png); $img.Dispose(); Write-Output OK }`,
202
+ ], 'utf8');
203
+ if (!out || !out.includes('OK'))
204
+ return null;
205
+ try {
206
+ const { readFile, rm } = await import('node:fs/promises');
207
+ const buf = await readFile(tmp);
208
+ await rm(tmp, { force: true });
209
+ return buf.length > 0 ? buf : null;
210
+ }
211
+ catch {
212
+ return null;
213
+ }
214
+ }
215
+ if (platform === 'darwin') {
216
+ // osascript 写文件用 HFS 冒号路径(Macintosh HD:Users:...),不能直接给 POSIX 斜线路径——
217
+ // `open for access POSIX file (...)` 在多数 macOS 版本上会解析失败。让 osascript 自己取
218
+ // 进程临时目录(POSIX file of (...)),再写 PNGf(raw data,ignore binary responses 必须关)。
219
+ const stamp = `mocode-clip-${process.pid}-${Date.now()}.png`;
220
+ const script = `set outPath to (POSIX file ((POSIX path of (path to temp items from user domain)) & "${stamp}"))` +
221
+ `\nset png_data to (the clipboard as «class PNGf»)` +
222
+ `\nset fp to open for access outPath with write permission` +
223
+ `\nwrite png_data to fp\nclose access fp` +
224
+ `\nreturn (POSIX path of outPath)`;
225
+ const out = await captureOutput('osascript', ['-e', script], 'utf8');
226
+ const tmp = out?.trim();
227
+ if (!tmp)
228
+ return null;
229
+ try {
230
+ const { readFile, rm } = await import('node:fs/promises');
231
+ const buf = await readFile(tmp);
232
+ await rm(tmp, { force: true });
233
+ return buf.length > 0 ? buf : null;
234
+ }
235
+ catch {
236
+ return null;
237
+ }
238
+ }
239
+ // linux:Wayland 优先,X11 兜底
240
+ const wl = await captureBinary('wl-paste', ['-t', 'image/png']);
241
+ if (wl)
242
+ return wl;
243
+ const xc = await captureBinary('xclip', ['-selection', 'clipboard', '-t', 'image/png', '-o']);
244
+ return xc;
245
+ }
@@ -30,7 +30,7 @@ import { paintInput, repaint } from './input-paint.js';
30
30
  import { WHEEL_LINES, screenRowToAbsLine, repaintViewport, scrollBy, scrollWheel, resetScroll, lockScrollToBottom, } from './scroll.js';
31
31
  import { contentWrite, contentInsertAfter, contentDeleteFrom, contentReplaceLine, reflowContentForResize, flushMdSegment, } from './content-write.js';
32
32
  export { isTuiActive, getGeo, getEffectiveContentBottom, setRegion, contentMode, isStreamingPaused } from './screen.js';
33
- export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, } from './statusbar.js';
33
+ export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, setPendingAttachChips, } from './statusbar.js';
34
34
  export { paintInput, paintRunningInput, repaint } from './input-paint.js';
35
35
  export { isScrolled, repaintViewport, repaintContentLine, scrollBy, scrollWheel, resetScroll, setMenuReserve, lockScrollToBottom, unlockScroll, isScrollLocked, } from './scroll.js';
36
36
  export { contentWrite, writeBanner, rewriteBanner, bannerHeight, contentWriteMd, contentWriteMdOnce, clearContent, rewindContent, writeWelcomeBlock, dismissWelcomeBlock, contentInsertAfter, contentDeleteFrom, totalRows, isLastContentRowBlank, normalizeMutationBoundary, normalizeInputBoundary, contentReplaceLine, notifyContentReset, } from './content-write.js';
@@ -7,7 +7,7 @@ import * as content from '../content.js';
7
7
  import { state } from './state.js';
8
8
  import { esc, cup, getGeo, getEffectiveContentBottom, setRegion, runningCaretPos } from './screen.js';
9
9
  import { SEL_OPEN, SEL_OFF, normalizeInputSelection, inputViewSig } from './selection.js';
10
- import { composeSpinnerLine, composeModelLine, composePlanLines, drawStatusBar } from './statusbar.js';
10
+ import { composeSpinnerLine, composeModelLine, composePlanLines, composePendingAttachLine, drawStatusBar, } from './statusbar.js';
11
11
  // ── 输入区(底栏输入框 + 向上菜单)──
12
12
  /**
13
13
  * 把逻辑行软折成可视行并开窗(超 maxInputRows 时滑窗保光标可见)。返回可见可视行文本(已折行)+
@@ -157,8 +157,9 @@ export function paintInput(view) {
157
157
  buf += cup(effBottom, 1) + esc.clearLine + line;
158
158
  }
159
159
  // 2c. 虚拟空行(内容区与状态栏之间的视觉间隔,属底栏非内容):
160
- // - 无活跃 plan:清空保留作分隔(原设计)
161
160
  // - 有活跃 plan:渲染 plan chip(整帧重画时也要更新,避免 listener 漏触发后残留)
161
+ // - 否则有待发图片附件:渲染附件 chip(不进内容缓冲,提交后由 echoInput 正式回显)
162
+ // - 都没有:清空保留作分隔
162
163
  // - plan 过长:占 2 行(planRows=2),spinner/上线/输入行随之整体下移 1 行
163
164
  // paintInput 与 drawStatusBar 共享同一 planRows 模块态,setRegion 已据此把脚栏撑高。
164
165
  {
@@ -171,10 +172,11 @@ export function paintInput(view) {
171
172
  buf += cup(g.contentBottom + 2, 1) + esc.clearLine;
172
173
  state.planRows = 1;
173
174
  }
174
- // plan 从非空变成空(已结算/无活跃段)时,清掉残留的 plan 行 1。
175
- // 上面 for 循环在 planBuf.length===0 时不写任何 cup,需要显式清一行回到「虚拟空行」。
175
+ // 无 plan 时:画待发附件脚栏(chip + 降采样 badge + 非视觉预警,不进内容缓冲);
176
+ // slash 菜单向上展开时最后一行也落在这一行,会互相覆盖——菜单打开期间隐藏(关菜单恢复)。
176
177
  if (planBuf.length === 0) {
177
- buf += cup(g.contentBottom + 1, 1) + esc.clearLine;
178
+ const attLine = view.menu && view.menu.lines.length > 0 ? '' : composePendingAttachLine(g.cols);
179
+ buf += cup(g.contentBottom + 1, 1) + esc.clearLine + attLine;
178
180
  }
179
181
  }
180
182
  // 3. 状态行:spinner 行 + model 行(两行式底栏)