mocode-ai 1.8.10 → 1.9.1

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 (38) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/dist/agent/index.js +18 -1
  4. package/dist/agent/model-turn.js +19 -5
  5. package/dist/agent/run-coordinator.js +32 -5
  6. package/dist/attachments/clipboard.js +22 -0
  7. package/dist/attachments/image.js +63 -0
  8. package/dist/config/index.js +1 -1
  9. package/dist/headless.js +7 -0
  10. package/dist/i18n/index.js +20 -2
  11. package/dist/memory/anchor-backfill.js +227 -0
  12. package/dist/memory/anchor.js +91 -9
  13. package/dist/memory/graph.js +54 -6
  14. package/dist/memory/guard.js +174 -0
  15. package/dist/memory/health.js +13 -0
  16. package/dist/memory/index.js +5 -2
  17. package/dist/memory/reflect.js +130 -7
  18. package/dist/memory/seed.js +227 -0
  19. package/dist/memory/store.js +16 -2
  20. package/dist/memory/tail.js +20 -0
  21. package/dist/memory/turn-recall.js +149 -0
  22. package/dist/repl/commands/image.js +30 -17
  23. package/dist/repl/commands/memory.js +217 -4
  24. package/dist/repl/commands.js +1 -0
  25. package/dist/repl/message-format.js +18 -0
  26. package/dist/repl/runtime.js +103 -9
  27. package/dist/tools/builtins/memory-graph.js +20 -6
  28. package/dist/tools/builtins/memory-list.js +3 -1
  29. package/dist/tools/builtins/memory-save.js +30 -3
  30. package/dist/tools/builtins/memory-search.js +5 -0
  31. package/dist/tools/builtins/memory-update.js +13 -3
  32. package/dist/ui/clipboard.js +97 -0
  33. package/dist/ui/layout-internal/core.js +1 -1
  34. package/dist/ui/layout-internal/input-paint.js +7 -5
  35. package/dist/ui/layout-internal/state.js +8 -0
  36. package/dist/ui/layout-internal/statusbar.js +22 -1
  37. package/dist/ui/prompt-internal/editor.js +50 -1
  38. package/package.json +1 -1
@@ -0,0 +1,149 @@
1
+ // turn-recall.ts —— 每轮静默召回(R18):按本轮用户问题把相关旧记忆送进 ephemeral 段。
2
+ //
3
+ // 为什么需要它:记忆有两条投递路径,此前都覆盖不到「这一轮问的这个话题」——
4
+ // ① 启动注入:buildMemoryIndexSection 只在 history[0] 出现一次,整场会话不刷新;
5
+ // ② R17 尾注:只播「本会话内新增/变更」的条目,回答的是"刚学了什么",不是"这轮该想起什么";
6
+ // ③ R3 前摄:只在**工具调用**那一刻按参数命中 trigger,而 40 条 active 里只有 13 条有 trigger。
7
+ // 于是用户问一个和旧记忆高度相关的问题时,模型只能靠自己去 memory_search —— 实测这条路
8
+ // 走不通(上线很久后 searches 仍是个位数)。这里补上第三条:问题进来就先静默取一次。
9
+ //
10
+ // 为什么走 ephemeral 尾部而不是重建 history[0]:重建 history[0] 会让整段对话的 KV 前缀
11
+ // 缓存每轮失效(每轮按全价重算 prompt)。附在末尾则前缀逐字节不变,与 sessionStateText /
12
+ // memoryTail 同一手法。
13
+ //
14
+ // 三条硬约束(全部为"宁少勿多"服务):
15
+ // - ≤3 条、单条 body ≤300 字符:真实库索引段已 6010 字符,每轮再灌正文会失控;
16
+ // - 走 R15.5 的「证据词元命中数 ≥2」下限:BM25 只要有一个 token 重合就返回,
17
+ // 没有下限时无关问题也会被"召回"一堆东西——那正是模型学会无视记忆的开始;
18
+ // - 不 bump recallCount:静默注入 ≠ 模型采用。而索引 policy 把 `recallCount>=1` 当作
19
+ // 「近期活跃」永久展示,静默注入过的条目会被永久钉在索引顶部,反而让「真的被主动
20
+ // 检索过」这个信号失去意义。计数另走 turnRecallCounters(只作观测)。
21
+ //
22
+ // 叶子依赖:只依赖 store(读)、text-search(纯函数)、anchor(读时判定)。
23
+ // 开关与排除集由调用方传入,本模块不读 config —— 与 store.ts / tail.ts 的既有约定一致。
24
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
25
+ import path from 'node:path';
26
+ import { TextSearchIndex } from '../context/text-search.js';
27
+ import { MEMORY_SEARCH_MIN_EVIDENCE } from '../tools/constants.js';
28
+ import { evaluateAnchors } from './anchor.js';
29
+ import { loadAll } from './store.js';
30
+ /**
31
+ * 每轮静默召回开关。默认开启,可用 MOCODE_MEMORY_TURN_RECALL=0/false/off/no 关闭。
32
+ *
33
+ * 与 R3 的 MOCODE_MEMORY_PROACTIVE 各自独立:两者都是 push 通道,但判据完全不同
34
+ * (一个看本轮问题,一个看工具参数),用户可能只想留其中一条。
35
+ */
36
+ export function isTurnRecallEnabled() {
37
+ const raw = process.env.MOCODE_MEMORY_TURN_RECALL;
38
+ if (raw === undefined)
39
+ return true;
40
+ return !['0', 'false', 'off', 'no'].includes(raw.trim().toLowerCase());
41
+ }
42
+ /** 每轮最多送几条。3 与 R17 尾注、R2.4 锚点回注同口径。 */
43
+ const MAX_TURN_RECALL = 3;
44
+ /** 单条 body 截断。只留「结论 + 一条理由」,砍掉长表格与代码块。 */
45
+ const MAX_RECALL_BODY_CHARS = 300;
46
+ /**
47
+ * 查询侧最短长度。低于此值不检索:短查询(「好」「改」)没有证据词元,
48
+ * 下限会退化成不过滤,把整库当结果返回。
49
+ */
50
+ const MIN_QUERY_CHARS = 4;
51
+ /**
52
+ * 生成「可能与本轮相关」的记忆段。无命中 / 开关关闭 / 查询过短 → 空串(零注入)。
53
+ *
54
+ * 与 `searchEntries` 的关键差异:纯读。不改 recallCount,不写任何文件。
55
+ */
56
+ export function buildTurnRecallSection(query, opts = {}) {
57
+ if (opts.enabled === false)
58
+ return '';
59
+ const q = (query ?? '').trim();
60
+ if (q.length < MIN_QUERY_CHARS)
61
+ return '';
62
+ const pool = loadAll().filter((e) => e.status === 'active' && e.type !== 'episode' && !(opts.excludeIds?.has(e.id) ?? false));
63
+ if (pool.length === 0)
64
+ return '';
65
+ // 计「检索过」而不是「命中过」:否则 turns === hits 恒成立,分母失去意义。
66
+ // 真正想知道的是"每轮召回到底有多少轮能拿东西",所以两者必须分开计。
67
+ countTurn();
68
+ // 字段权重必须与 store.ts:searchEntries 逐字一致(name 10 / id 8 / summary 5 / body 1)。
69
+ // 两处各写一份是刻意的:任何一方漂移都会让「静默召回」与「显式 memory_search」
70
+ // 排出不同顺序,而模型会以为其中一个是坏的。
71
+ const index = new TextSearchIndex(pool.map((e) => ({
72
+ id: e.id,
73
+ fields: [
74
+ { text: e.name, weight: 10 },
75
+ { text: e.id, weight: 8 },
76
+ { text: e.summary, weight: 5 },
77
+ { text: e.body, weight: 1 },
78
+ ],
79
+ })), { minEvidenceMatched: MEMORY_SEARCH_MIN_EVIDENCE });
80
+ const byId = new Map(pool.map((e) => [e.id, e]));
81
+ const limit = Math.max(1, Math.min(opts.limit ?? MAX_TURN_RECALL, MAX_TURN_RECALL));
82
+ const hits = index
83
+ .search(q, limit)
84
+ .map((hit) => byId.get(hit.id))
85
+ .filter((e) => e !== undefined);
86
+ if (hits.length === 0)
87
+ return '';
88
+ countHits(hits.length);
89
+ const lines = hits.map(formatEntry);
90
+ return [
91
+ '## Possibly relevant memory (recalled for this turn)',
92
+ 'Retrieved by keyword match against the current question, not by your own request — open the full body with memory_search(id) when you act on one. If an entry contradicts what the code now says, the code wins.',
93
+ ...lines,
94
+ ].join('\n');
95
+ }
96
+ /** 单条渲染。stale 打标沿用 R2/R14 的口径:两类失效对模型的要求不同。 */
97
+ function formatEntry(e) {
98
+ const tags = [];
99
+ if (e.pinned)
100
+ tags.push('pinned');
101
+ const anchorState = evaluateAnchors(e.anchors);
102
+ if (anchorState.stale)
103
+ tags.push('STALE-CODE');
104
+ const suffix = tags.length > 0 ? ` [${tags.join(', ')}]` : '';
105
+ const body = (e.body ?? '').replace(/\s+/g, ' ').trim();
106
+ const clipped = body.length > MAX_RECALL_BODY_CHARS ? `${body.slice(0, MAX_RECALL_BODY_CHARS)}…` : body;
107
+ const head = `- [${e.type}] ${e.id}: ${e.name} — ${e.summary}${suffix}`;
108
+ return clipped ? `${head}\n ${clipped}` : head;
109
+ }
110
+ const EMPTY_COUNTERS = { turns: 0, hits: 0, entries: 0, updatedAt: null };
111
+ let counters = null;
112
+ function countTurn() {
113
+ counters ??= { ...EMPTY_COUNTERS };
114
+ counters.turns += 1;
115
+ }
116
+ /** 与 countTurn 分开:同一轮不能既在"检索过"又在"命中过"里各加一次 turns。 */
117
+ function countHits(entryCount) {
118
+ counters ??= { ...EMPTY_COUNTERS };
119
+ counters.hits += 1;
120
+ counters.entries += entryCount;
121
+ }
122
+ /** 只读快照(供 /memory health 展示)。 */
123
+ export function turnRecallCounters() {
124
+ return { ...(counters ?? EMPTY_COUNTERS) };
125
+ }
126
+ function statsPath() {
127
+ return path.join(process.cwd(), '.mocode', 'memory-turn-recall-stats.json');
128
+ }
129
+ /** 落盘。与 flushProactiveStats 同一时机调用;失败静默。 */
130
+ export function flushTurnRecallStats() {
131
+ if (!counters)
132
+ return; // 从未检索过 → 无新数据,零 IO
133
+ const snapshot = { ...counters, updatedAt: new Date().toISOString() };
134
+ try {
135
+ const p = statsPath();
136
+ mkdirSync(path.dirname(p), { recursive: true });
137
+ const tmp = p + '.tmp';
138
+ writeFileSync(tmp, JSON.stringify(snapshot, null, 2), 'utf8');
139
+ renameSync(tmp, p);
140
+ counters = snapshot;
141
+ }
142
+ catch {
143
+ // 静默:埋点不可写不影响功能
144
+ }
145
+ }
146
+ /** 仅供测试:清掉内存计数,避免共享进程里上一个用例的数字串味。 */
147
+ export function __resetTurnRecallForTests() {
148
+ counters = null;
149
+ }
@@ -1,8 +1,8 @@
1
1
  /**
2
- * 图片附件命令组:/image · /image list · /image clear · /image &lt;path&gt;
2
+ * 图片附件命令组:/image · /image list · /image clear · /image clip · /image &lt;path&gt;
3
3
  *
4
4
  * 单 handler 内部按完整 line 分流,顺序与原 if 链一致:
5
- * 先 list/clear(完整匹配),再落到 &lt;path&gt; 分支。
5
+ * 先 list/clear/clip(完整匹配),再落到 &lt;path&gt; 分支。
6
6
  *
7
7
  * dispatch 阶段**不调 runTurn**:仅 mutate ctx.attachments 状态,
8
8
  * 提交时(runTurn 入口)才 flush 进 history。
@@ -10,13 +10,18 @@
10
10
  import * as layout from '../../ui/layout.js';
11
11
  import { ui } from '../../ui/theme.js';
12
12
  import { config } from '../../config/index.js';
13
+ import { t } from '../../i18n/index.js';
13
14
  import { loadImageAttachmentWithDownscale, renderChip, MAX_INLINE_BYTES_DEFAULT } from '../../attachments/image.js';
14
- import { modelSupportsVision } from '../../llm/capabilities.js';
15
+ import { readClipboardAsAttachment } from '../../attachments/clipboard.js';
15
16
  import { unhandled, next } from './types.js';
16
17
  export const imageCommands = [
17
18
  async (ctx) => {
18
19
  const { line } = ctx;
19
- const isImage = line === '/image' || line === '/image list' || line === '/image clear' || line.startsWith('/image ');
20
+ const isImage = line === '/image' ||
21
+ line === '/image list' ||
22
+ line === '/image clear' ||
23
+ line === '/image clip' ||
24
+ line.startsWith('/image ');
20
25
  if (!isImage)
21
26
  return unhandled();
22
27
  const pending = ctx.attachments.list();
@@ -43,12 +48,30 @@ export const imageCommands = [
43
48
  }
44
49
  return next();
45
50
  }
51
+ // /image clip:从系统剪贴板抓截图(Ctrl+Y 快捷键的命令形态,供终端吞键时兜底)。
52
+ // 成功只更新脚栏(push 钩子已同步 chip/降采样 badge/视觉预警),不写内容缓冲——
53
+ // 否则确认行会游离在 banner 与气泡之间,提交后又在气泡下重复一次。
54
+ if (line === '/image clip') {
55
+ const r = await readClipboardAsAttachment();
56
+ if (!r.ok) {
57
+ if ('empty' in r) {
58
+ layout.contentWrite(` ${ui.yellow}${t('prompt.imageEmpty')}${ui.reset}\n`);
59
+ }
60
+ else {
61
+ layout.contentWrite(`${ui.red}[image] ${r.reason}${ui.reset}\n`);
62
+ }
63
+ }
64
+ else if (!ctx.attachments.list().some((a) => a.id === r.att.id)) {
65
+ ctx.attachments.push(r.att);
66
+ }
67
+ return next();
68
+ }
46
69
  const arg = line
47
70
  .slice('/image'.length)
48
71
  .trim()
49
72
  .replace(/^["']|["']$/g, '');
50
73
  if (!arg) {
51
- layout.contentWrite(`${ui.dim}用法: /image <path>${ui.reset}\n`);
74
+ layout.contentWrite(`${ui.dim}用法: /image <path>(或 /image clip 抓剪贴板截图)${ui.reset}\n`);
52
75
  return next();
53
76
  }
54
77
  const maxBytes = config.maxImageBytes ?? MAX_INLINE_BYTES_DEFAULT;
@@ -57,20 +80,10 @@ export const imageCommands = [
57
80
  layout.contentWrite(`${ui.red}[image] ${r.reason}${ui.reset}\n`);
58
81
  return next();
59
82
  }
60
- if (!ctx.attachments.list().find((a) => a.id === r.att.id)) {
83
+ // 成功只更新脚栏(push 钩子同步 chip/降采样 badge/视觉预警),不写内容缓冲。
84
+ if (!ctx.attachments.list().some((a) => a.id === r.att.id)) {
61
85
  ctx.attachments.push(r.att);
62
86
  }
63
- // 用户粘/挂的高 DPI 截图超限时会被降采样:必须说出来,否则用户以为发的是原图,
64
- // 之后模型「看不清小字」时无从归因。
65
- if (r.downscaledFrom) {
66
- layout.contentWrite(` ${ui.yellow}⚠ 原图 ${r.downscaledFrom.width}×${r.downscaledFrom.height} 超过内联上限,已降采样后附加(磁盘原图不变)。${ui.reset}\n`);
67
- }
68
- layout.contentWrite(` ${ui.dim}${renderChip(r.att)} — will attach to next message${ui.reset}\n`);
69
- // 提前警告(不阻断附加):当前模型已知不支持视觉(如 MiniMax M2.x / gpt-3.5 等)时,
70
- // 附加时就提示,而不是等发送后才在 catch 块里翻译 API 报错——减少一轮无意义请求。
71
- if (!modelSupportsVision(config.model)) {
72
- layout.contentWrite(` ${ui.yellow}⚠ 当前模型 ${config.model} 已知不支持视觉输入,发送图片可能会失败。可用 /model 切换。${ui.reset}\n`);
73
- }
74
87
  return next();
75
88
  },
76
89
  ];
@@ -12,8 +12,12 @@ import { isMemoryEnabled } from '../../config/index.js';
12
12
  import { getAgentMode } from '../../agent/mode.js';
13
13
  import { kickoffReflection, snapshotTranscript, loadAll, loadAllGraph, loadStalenessMap, listInternalizedProfile, listProfileCandidates, promoteEdge, invalidateEdge, writeMemoryHealth, formatMemoryHealth, flushProactiveStats,
14
14
  // R8 用户主权面
15
- purgeEntries, buildPack, writePack, importPackFile, memoryWriteBlockedMessage, setMemoryWritesPaused, isMemoryWritesPaused, appendAudit, } from '../../memory/index.js';
16
- import { evaluateAnchors, evaluateAnchor } from '../../memory/anchor.js';
15
+ purgeEntries, buildPack, writePack, importPackFile, memoryWriteBlockedMessage, setMemoryWritesPaused, isMemoryWritesPaused, appendAudit, readAudit,
16
+ // R9.1 冷启动播种
17
+ collectSeedCandidates, applySeedCandidates,
18
+ // R2.6 存量锚点回填
19
+ collectAnchorCandidates, applyAnchorCandidates, } from '../../memory/index.js';
20
+ import { evaluateAnchors, evaluateAnchor, anchorLabel } from '../../memory/anchor.js';
17
21
  import { unhandled, next } from './types.js';
18
22
  /** /profile 改动画像后,让 About you 段(history[0])立刻反映,不用等重启。 */
19
23
  function refreshSystemPrompt(ctx) {
@@ -61,7 +65,14 @@ function renderProfile() {
61
65
  * 编一个出来比不显示更糟;要看得更细用 `/memory show <id>` 看图谱边的 prov/confidence。
62
66
  */
63
67
  export function sourceMark(e) {
64
- return e.source?.session ? '[reflection]' : '[tool]';
68
+ // R16.1:工具输出衍生的条目必须与“模型亲述”区分开——它可能是从网页里逐字抄来的一段话。
69
+ // 不把两类混成一个标记:用户判断“要不要信这条”时,二手转述本来就该多一层怀疑。
70
+ //
71
+ // R9.1:`source.file` 是第三种来源——来自用户自己维护的文档(AGENTS.md/草稿),
72
+ // 既不是模型判断、也不是反思推断。它单独一个标记,因为"我写的"与"它想的"
73
+ // 在可信度上正好相反:文档是用户的主权声明,反思是模型的猜测。
74
+ const base = e.source?.file ? '[seed]' : e.source?.session ? '[reflection]' : '[tool]';
75
+ return e.origin === 'tool_output' ? `${base} [UNVERIFIED-ORIGIN]` : base;
65
76
  }
66
77
  /** `/memory show <id>`:一条记忆的全部出处。导出仅供测试断言渲染结果。 */
67
78
  export function renderEntryDetail(e) {
@@ -78,6 +89,13 @@ export function renderEntryDetail(e) {
78
89
  kv('来源', e.source?.session
79
90
  ? `后台产生(反思/情节),会话 ${e.source.session.slice(0, 8)}${e.source.turn !== undefined ? ` 第 ${e.source.turn} 轮` : ''}`
80
91
  : '会话内工具写入(memory_save)');
92
+ // R16.1:来源可信度单独一行,不与上面的“谁写的”混在一起——
93
+ // “反思写的”与“反思从网页上抄的”是两件完全不同的事。
94
+ if (e.origin === 'tool_output') {
95
+ kv('来源可信度', '工具输出衍生(内容逐字来自网页/文件/命令输出,未经用户确认)');
96
+ }
97
+ if (e.firstSeen)
98
+ kv('首次出现', e.firstSeen);
81
99
  if (e.lastUpdateReason)
82
100
  kv('最近变更', e.lastUpdateReason);
83
101
  if (e.trigger)
@@ -106,7 +124,7 @@ export function renderEntryDetail(e) {
106
124
  lines.push(`${ui.dim} 代码锚点(${e.anchors.length}):${st.stale ? `已变动 ${st.changed.length}/缺失 ${st.missing.length}` : '全部 fresh'}${ui.reset}`);
107
125
  for (const a of e.anchors) {
108
126
  const r = evaluateAnchor(a);
109
- const label = a.symbol ? `${a.path}#${a.symbol}` : a.path;
127
+ const label = anchorLabel(a);
110
128
  const flag = r.status === 'fresh' ? '' : ` ${ui.dim}[${r.status}${r.detail ? `: ${r.detail}` : ''}]${ui.reset}`;
111
129
  lines.push(` ${ui.dim}${label}${ui.reset}${flag}`);
112
130
  }
@@ -116,6 +134,43 @@ export function renderEntryDetail(e) {
116
134
  lines.push(`${ui.dim}${e.body}${ui.reset}`);
117
135
  return lines.join('\n') + '\n';
118
136
  }
137
+ /**
138
+ * R16.4 来源链:该 id 相关的审计轨迹(写入/被拒/被遗忘/被导出)。
139
+ *
140
+ * 为什么按 id **过滤审计文件**而不是给条目加一个"历史版本"字段:审计是 append-only
141
+ * 的事件流,条目是当前状态。把历史塞进条目会让每次写入都重写正文,而审计行天然
142
+ * 可跨进程、可被 `--match` 批量操作一起记录——两者的生命周期根本不同。
143
+ *
144
+ * 被拒记录(`action: 'refuse'`)不挂 id(内容压根没进库),所以额外按名字前缀匹配
145
+ * `detail`:用户查一条"是不是曾经想写但被拦过"时,那是最有用的线索。
146
+ */
147
+ export function renderAuditTrail(id, records, nameHint) {
148
+ const lines = [];
149
+ const related = records.filter((r) => {
150
+ if (r.ids?.some((x) => x === id))
151
+ return true;
152
+ if (r.action !== 'refuse')
153
+ return false;
154
+ // 被拒记录没有 id(内容压根没进库),只能按 detail 里的名字/被查串匹配。
155
+ if (r.detail.includes(id))
156
+ return true;
157
+ return !!nameHint && r.detail.includes(nameHint.slice(0, 60));
158
+ });
159
+ lines.push(`${ui.accent}来源链${ui.reset} ${ui.dim}(${related.length} 条审计记录)${ui.reset}`);
160
+ if (related.length === 0) {
161
+ lines.push(`${ui.dim} (无:该条目没有写入/拒绝/遗忘轨迹。审计从 R8 起才有记录,更早的条目自然为空)${ui.reset}`);
162
+ return lines.join('\n');
163
+ }
164
+ for (const r of related.slice(-12)) {
165
+ const mark = r.action === 'refuse' ? `${ui.yellow}拒绝` : r.action === 'write' ? `${ui.accent}写入` : r.action;
166
+ lines.push(` ${ui.dim}${r.at}${ui.reset} ${mark}${ui.reset} ${ui.dim}${r.detail}${ui.reset}`);
167
+ if (r.reason)
168
+ lines.push(` ${ui.dim}原因: ${r.reason}${ui.reset}`);
169
+ if (r.snippet)
170
+ lines.push(` ${ui.dim}证据: ${r.snippet}${ui.reset}`);
171
+ }
172
+ return lines.join('\n');
173
+ }
119
174
  /** 解析 `/memory forget` 的参数。返回 null 表示使用错误(调用方打用法)。 */
120
175
  function parseForgetArgs(rest) {
121
176
  const toks = rest.split(/\s+/).filter(Boolean);
@@ -153,6 +208,22 @@ function parseForgetArgs(rest) {
153
208
  return out;
154
209
  }
155
210
  const FORGET_USAGE = '用法:/memory forget --all | --match <关键词> | --since <YYYY-MM-DD> [--scope global|project] [--dry-run]';
211
+ /**
212
+ * 解析 `/memory seed 1,3,5` 的序号列表。
213
+ *
214
+ * 容忍中文逗号、空格分隔与重复(`1, 1, 3` → `[1,3]`)——用户从列表里抄序号时
215
+ * 这些写法都会出现,为格式差异报错纯属给用户添堵。非法输入返回空数组,调用方打用法。
216
+ */
217
+ export function parseSeedPicks(raw) {
218
+ const out = new Set();
219
+ for (const tok of raw.split(/[,,\s]+/).filter(Boolean)) {
220
+ const n = Number(tok);
221
+ if (!Number.isInteger(n) || n < 1)
222
+ return [];
223
+ out.add(n);
224
+ }
225
+ return [...out].sort((a, b) => a - b);
226
+ }
156
227
  export const memoryCommands = [
157
228
  (ctx) => {
158
229
  if (ctx.line !== '/memory')
@@ -287,6 +358,26 @@ export const memoryCommands = [
287
358
  layout.contentWrite(renderEntryDetail(hit) + '\n');
288
359
  return next();
289
360
  },
361
+ // ── R16.4 来源链 ────────────────────────────────────────────────────────
362
+ (ctx) => {
363
+ if (!ctx.line.startsWith('/memory audit'))
364
+ return unhandled();
365
+ const id = ctx.line.slice('/memory audit'.length).trim();
366
+ if (!id) {
367
+ layout.contentWrite(`${ui.dim}用法:/memory audit <id>(条目详情 + 写入/拒绝轨迹)${ui.reset}\n`);
368
+ return next();
369
+ }
370
+ // 允许前缀,同 /memory show:概览里的 id 很长,用户常只记得前几个字符。
371
+ const all = loadAll();
372
+ const hit = all.find((e) => e.id === id) ?? all.find((e) => e.id.startsWith(id));
373
+ if (hit)
374
+ layout.contentWrite(renderEntryDetail(hit) + '\n');
375
+ else
376
+ layout.contentWrite(`${ui.dim}(找不到记忆 [${id}];下面只显示审计轨迹)${ui.reset}\n`);
377
+ layout.contentWrite(renderAuditTrail(hit?.id ?? id, readAudit(300)) + '\n');
378
+ layout.contentWrite(`${ui.dim}(审计文件 .mocode/memory-audit.jsonl · 只记动作与 id,不存正文)${ui.reset}\n`);
379
+ return next();
380
+ },
290
381
  // ── R8.3 暂停写入 ──────────────────────────────────────────────────────
291
382
  (ctx) => {
292
383
  if (ctx.line !== '/memory pause' && !ctx.line.startsWith('/memory pause '))
@@ -345,6 +436,128 @@ export const memoryCommands = [
345
436
  `图谱 +${r.addedEntities} 实体/+${r.addedEdges} 边)${ui.reset}\n`);
346
437
  return next();
347
438
  },
439
+ // ── R9.1 冷启动播种 ────────────────────────────────────────────────────
440
+ (ctx) => {
441
+ if (ctx.line !== '/memory seed' && !ctx.line.startsWith('/memory seed '))
442
+ return unhandled();
443
+ if (!isMemoryEnabled()) {
444
+ layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory seed 无效。用 /memory_switch 打开)${ui.reset}\n`);
445
+ return next();
446
+ }
447
+ const arg = ctx.line.slice('/memory seed'.length).trim();
448
+ // 每次都重新扫:AGENTS.md 可能在上一轮被 /init 改写过,缓存反而制造"列表过期"的怪象。
449
+ const scan = collectSeedCandidates(ctx.banner().cwd);
450
+ // 无参数 = 只看不写。先让用户核对自己写了什么,再决定记哪些。
451
+ if (!arg) {
452
+ if (scan.files.length === 0) {
453
+ layout.contentWrite(`${ui.dim}(工作区里没有 AGENTS.md / CLAUDE.md / .mocode/agents-draft.md,无可播种内容)${ui.reset}\n`);
454
+ return next();
455
+ }
456
+ if (scan.candidates.length === 0) {
457
+ layout.contentWrite(`${ui.dim}(读了 ${scan.files.join('、')},但没找到「约定」段的 bullet;` +
458
+ `只抽 ## 约定 / ## Conventions 下的条目,或首个二级标题之前的 bullet)${ui.reset}\n`);
459
+ return next();
460
+ }
461
+ layout.contentWrite(`${ui.accent}可从已有文档播种 ${scan.candidates.length} 条约定${ui.reset}` +
462
+ `${ui.dim}(来源:${scan.files.join('、')})${ui.reset}\n`);
463
+ for (const [i, c] of scan.candidates.entries()) {
464
+ layout.contentWrite(` ${ui.accent}${i + 1}${ui.reset} ${ui.dim}${c.name}${ui.reset}\n`);
465
+ layout.contentWrite(` ${ui.dim}${c.summary}${ui.reset}\n`);
466
+ }
467
+ if (scan.truncated > 0) {
468
+ layout.contentWrite(` ${ui.dim}… 另有 ${scan.truncated} 条超出上限未列出${ui.reset}\n`);
469
+ }
470
+ layout.contentWrite(`${ui.dim}/memory seed <序号>[,<序号>…] 写入选中的 · /memory seed all 全部写入(${ui.reset}` +
471
+ `${ui.dim}只提议不自动写:这些是项目的约定,不是你的偏好)${ui.reset}\n`);
472
+ return next();
473
+ }
474
+ // 写入:解析 `all` 或逗号分隔的序号。
475
+ const picks = arg === 'all' ? 'all' : parseSeedPicks(arg);
476
+ if (picks !== 'all' && picks.length === 0) {
477
+ layout.contentWrite(`${ui.dim}用法:/memory seed · /memory seed all · /memory seed 1,3,5${ui.reset}\n`);
478
+ return next();
479
+ }
480
+ if (scan.candidates.length === 0) {
481
+ layout.contentWrite(`${ui.dim}(没有可播种的约定;先跑 /memory seed 看列表)${ui.reset}\n`);
482
+ return next();
483
+ }
484
+ if (picks !== 'all') {
485
+ const outOfRange = picks.filter((n) => n > scan.candidates.length);
486
+ if (outOfRange.length > 0) {
487
+ layout.contentWrite(`${ui.dim}(序号 ${outOfRange.join(',')} 超出范围:只有 ${scan.candidates.length} 条;先跑 /memory seed 看列表)${ui.reset}\n`);
488
+ return next();
489
+ }
490
+ }
491
+ const r = applySeedCandidates(scan.candidates, picks);
492
+ if (r.saved.length > 0)
493
+ refreshSystemPrompt(ctx); // 新条目要进索引,下一轮就该看得见
494
+ layout.contentWrite(`${ui.dim}(播种完成:新增 ${r.saved.length} · 已存在 ${r.existed.length} · 拒绝 ${r.refused.length})${ui.reset}\n`);
495
+ for (const s of r.saved)
496
+ layout.contentWrite(` ${ui.dim}+ [${s.id}] ${s.name}${ui.reset}\n`);
497
+ // 已存在不逐条列:那是「本来就记过了」,安静跳过比刷一屏更有用。
498
+ for (const f of r.refused) {
499
+ layout.contentWrite(` ${ui.yellow}! ${f.name}${ui.reset}${ui.dim}(命中守卫 ${f.rule},未写入)${ui.reset}\n`);
500
+ }
501
+ return next();
502
+ },
503
+ // ── R2.6 存量锚点回填(只提议不自动写)──────────────────────────────────
504
+ (ctx) => {
505
+ if (ctx.line !== '/memory anchor' && !ctx.line.startsWith('/memory anchor '))
506
+ return unhandled();
507
+ if (!isMemoryEnabled()) {
508
+ layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory anchor 无效。用 /memory_switch 打开)${ui.reset}\n`);
509
+ return next();
510
+ }
511
+ const arg = ctx.line.slice('/memory anchor'.length).trim();
512
+ const cwd = ctx.banner().cwd;
513
+ // 每次重扫:两次命令之间可能刚改过文件,列表必须反映此刻的磁盘。
514
+ const scan = collectAnchorCandidates(cwd);
515
+ if (!arg) {
516
+ if (scan.candidates.length === 0) {
517
+ layout.contentWrite(`${ui.dim}(没有可回填的条目:${scan.alreadyAnchored} 条已有锚点,` +
518
+ `${scan.noPath} 条 body 里没有可解析的工作区路径)${ui.reset}\n`);
519
+ return next();
520
+ }
521
+ layout.contentWrite(`${ui.accent}可为 ${scan.candidates.length} 条记忆回填代码锚点${ui.reset}` +
522
+ `${ui.dim}(已有锚点 ${scan.alreadyAnchored} 条已跳过;路径取自条目正文,且此刻文件存在)${ui.reset}\n`);
523
+ for (const c of scan.candidates) {
524
+ layout.contentWrite(` ${ui.accent}${c.index}${ui.reset} ${ui.dim}${c.id}${ui.reset}\n`);
525
+ layout.contentWrite(` ${ui.dim}${c.paths.join(' ')}${ui.reset}\n`);
526
+ }
527
+ if (scan.truncated > 0) {
528
+ layout.contentWrite(` ${ui.dim}… 另有 ${scan.truncated} 条超出上限未列出${ui.reset}\n`);
529
+ }
530
+ layout.contentWrite(`${ui.dim}/memory anchor <序号>[,<序号>…] 写入选中的 · /memory anchor all 全部写入(${ui.reset}` +
531
+ `${ui.dim}锚点写入后,代码一改就会在这些条目上显示 STALE-CODE)${ui.reset}\n`);
532
+ return next();
533
+ }
534
+ const picks = arg === 'all' ? 'all' : parseSeedPicks(arg);
535
+ if (picks !== 'all' && picks.length === 0) {
536
+ layout.contentWrite(`${ui.dim}用法:/memory anchor · /memory anchor all · /memory anchor 1,3,5${ui.reset}\n`);
537
+ return next();
538
+ }
539
+ if (scan.candidates.length === 0) {
540
+ layout.contentWrite(`${ui.dim}(没有可回填的条目;先跑 /memory anchor 看列表)${ui.reset}\n`);
541
+ return next();
542
+ }
543
+ if (picks !== 'all') {
544
+ const outOfRange = picks.filter((n) => !scan.candidates.some((c) => c.index === n));
545
+ if (outOfRange.length > 0) {
546
+ layout.contentWrite(`${ui.dim}(序号 ${outOfRange.join(',')} 超出范围:只有 ${scan.candidates.length} 条;先跑 /memory anchor 看列表)${ui.reset}\n`);
547
+ return next();
548
+ }
549
+ }
550
+ const r = applyAnchorCandidates(scan.candidates, picks, cwd);
551
+ layout.contentWrite(`${ui.dim}(回填完成:写入 ${r.saved.length} · 条目已消失 ${r.missing.length} · 路径已失效 ${r.lost.length})${ui.reset}\n`);
552
+ for (const s of r.saved) {
553
+ layout.contentWrite(` ${ui.dim}+ ${s.id} ${s.paths.join(' ')}${ui.reset}\n`);
554
+ }
555
+ // 路径在两次扫描之间消失:必须说出来,否则用户以为"选中的都写好了"。
556
+ for (const l of r.lost) {
557
+ layout.contentWrite(` ${ui.yellow}! ${l.id}${ui.reset}${ui.dim}(正文提到的路径已不存在:${l.paths.join(', ')};未写入)${ui.reset}\n`);
558
+ }
559
+ return next();
560
+ },
348
561
  // ── R8.2 批量遗忘 ──────────────────────────────────────────────────────
349
562
  (ctx) => {
350
563
  if (!ctx.line.startsWith('/memory forget'))
@@ -154,6 +154,7 @@ export function buildSlashCommands() {
154
154
  desc: d('commands.image'),
155
155
  children: [
156
156
  { name: 'attach <path>', value: '/image ', submit: false, desc: d('commands.imageAttach') },
157
+ { name: 'clip', value: '/image clip', desc: d('commands.imageClip') },
157
158
  { name: 'list', value: '/image list', desc: d('commands.imageList') },
158
159
  { name: 'clear', value: '/image clear', desc: d('commands.imageClear') },
159
160
  ],
@@ -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
  }