mocode-ai 1.9.0 → 1.9.2

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.
@@ -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
+ }
@@ -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'))
@@ -44,6 +44,39 @@ export const sessionCommands = [
44
44
  layout.writeWelcomeBlock(ctx.welcomeLines()); // 回到空会话状态,欢迎引导重新出现
45
45
  return next();
46
46
  },
47
+ // /fork:把当前会话整个目录复制成一个新 id 会话(继承全部上下文),**不切换**窗口——
48
+ // 原会话继续在本窗口对话;分叉会话可用新终端 `mocode --resume <id>` 或本窗口 /resume 进入。
49
+ async (ctx) => {
50
+ if (ctx.line !== '/fork' && !ctx.line.startsWith('/fork '))
51
+ return unhandled();
52
+ const args = ctx.line.replace(/^\/fork\s*/, '').trim();
53
+ if (args) {
54
+ layout.contentWrite(`${ui.yellow}${t('repl.forkUsage')}${ui.reset}\n`);
55
+ return next();
56
+ }
57
+ const sourceId = ctx.state.currentSessionId;
58
+ if (!sourceId || ctx.history.length <= 1) {
59
+ layout.contentWrite(`${ui.dim}${t('repl.forkEmpty')}${ui.reset}\n`);
60
+ return next();
61
+ }
62
+ // 先落盘内存里的最新对话,分叉副本才能包含尚未自动保存的尾部;persistSnapshots 一并刷新。
63
+ ctx.runtime.session.save(ctx.history, sourceId, ctx.state.queryHistory, ctx.state.lastToolGroups);
64
+ let newId;
65
+ try {
66
+ newId = ctx.runtime.session.fork(sourceId);
67
+ }
68
+ catch (e) {
69
+ layout.contentWrite(`${ui.red}${t('repl.forkFailed', { message: e instanceof Error ? e.message : String(e) })}${ui.reset}\n`);
70
+ return next();
71
+ }
72
+ if (!newId) {
73
+ layout.contentWrite(`${ui.yellow}${t('repl.forkMissing')}${ui.reset}\n`);
74
+ return next();
75
+ }
76
+ layout.contentWrite(`${ui.accent}${t('repl.forkDone', { id: newId })}${ui.reset}\n`);
77
+ layout.contentWrite(`${ui.dim}${t('repl.forkHint', { id: newId })}${ui.reset}\n`);
78
+ return next();
79
+ },
47
80
  // /sessions:浏览全部已保存会话(慢路径,readdir+全量 JSON.parse,目录 N 大时会有可感知卡顿)。
48
81
  // 默认走 /resume(仅最近 10 条,瞬开);要翻历史续接更早的会话才用这条。
49
82
  // picker 走全显(cap=items.length,无 a 展开提示),靠 picker 自身开窗(以选中为中心分屏)。
@@ -1,14 +1,116 @@
1
1
  /**
2
- * 用量命令组:/stats(#token-efficiency P1)
2
+ * 用量命令组:/stats(当前会话诊断)· /usage(跨工作空间按天汇总)
3
3
  *
4
- * dialog-only:读取当前会话 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
5
- * 后端从未上报 cached 时命中率显示 n/a,不报错。
4
+ * /stats 读会话级 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
5
+ * /usage 读全局账本 ~/.mocode/usage-daily.jsonl(每次模型调用追加,含工作区/模型/
6
+ * 本地日期),输出最近 N 天的按天表、总计、工作区与模型排行。
6
7
  */
7
8
  import * as layout from '../../ui/layout.js';
9
+ import { ui } from '../../ui/theme.js';
10
+ import { fmtCompactTokens } from '../../ui/render.js';
11
+ import { t } from '../../i18n/index.js';
8
12
  import { getActiveSessionStore } from '../../session/store.js';
9
13
  import { formatUsageSummary, summarizeUsage } from '../../session/usage-stats.js';
14
+ import { readGlobalUsage, summarizeGlobalUsage, } from '../../session/global-usage.js';
10
15
  import { unhandled, next } from './types.js';
16
+ /** 计数千分位(请求数/会话数等)。 */
17
+ function n(v) {
18
+ return v.toLocaleString('en-US');
19
+ }
20
+ /** token 统一缩写:<1k 整数,1k-1M 用 k,≥1M 用 M(复用全项目同口径)。 */
21
+ function tok(v) {
22
+ return fmtCompactTokens(v);
23
+ }
24
+ /** 固定宽右对齐(数字串无 ANSI)。 */
25
+ function col(v, width) {
26
+ const s = String(v);
27
+ return s.length >= width ? s : ' '.repeat(width - s.length) + s;
28
+ }
29
+ function pct(part, whole) {
30
+ return whole > 0 ? `${((part / whole) * 100).toFixed(1)}%` : 'n/a';
31
+ }
32
+ /** 工作区/模型排行:名称左截断(保留尾部,工作区尾部目录更有辨识度),数值右对齐。 */
33
+ function groupTable(title, rows, nameWidth) {
34
+ const lines = [`${ui.accent}${title}${ui.reset}`];
35
+ if (rows.length === 0) {
36
+ lines.push(` ${ui.dim}${t('repl.usageNone')}${ui.reset}`);
37
+ return lines;
38
+ }
39
+ for (const r of rows.slice(0, 8)) {
40
+ let name = r.key;
41
+ if (name.length > nameWidth)
42
+ name = `…${name.slice(name.length - nameWidth + 1)}`;
43
+ lines.push(` ${ui.cyan}${name.padEnd(nameWidth)}${ui.reset} ${col(tok(r.input), 7)} in ${col(tok(r.output), 7)} out ${col(n(r.calls), 5)} calls ${ui.dim}${t('repl.usageSessions', { n: r.sessions })}${ui.reset}`);
44
+ }
45
+ if (rows.length > 8)
46
+ lines.push(` ${ui.dim}${t('repl.usageMore', { n: rows.length - 8 })}${ui.reset}`);
47
+ return lines;
48
+ }
49
+ function totalRow(b) {
50
+ return `${t('repl.usageTotalRow')} ${col(tok(b.input), 7)} in · ${col(tok(b.output), 7)} out · ${col(tok(b.cached), 7)} cached · ${col(tok(b.reasoning), 7)} reasoning`;
51
+ }
52
+ function formatGlobal(s) {
53
+ const lines = [];
54
+ const b = s.total;
55
+ const grandTotal = b.input + b.output;
56
+ lines.push(`${ui.accent}${t('repl.usageTitle', { from: s.fromDay, to: s.toDay, days: s.days })}${ui.reset}`);
57
+ lines.push(` ${t('repl.usageTotal', {
58
+ total: tok(grandTotal),
59
+ input: tok(b.input),
60
+ output: tok(b.output),
61
+ calls: n(b.calls),
62
+ sessions: n(s.sessionCount),
63
+ workspaces: n(s.workspaceCount),
64
+ })}`);
65
+ lines.push(` ${t('repl.usageMetrics', {
66
+ hit: pct(b.cached, b.input),
67
+ reasoning: pct(b.reasoning, b.output),
68
+ cacheWrite: tok(b.cacheCreation),
69
+ daily: tok(Math.round(grandTotal / s.days)),
70
+ })}`);
71
+ if (s.compact.calls > 0) {
72
+ lines.push(` ${ui.dim}${t('repl.usageCompact', { input: tok(s.compact.input), output: tok(s.compact.output), calls: n(s.compact.calls) })}${ui.reset}`);
73
+ }
74
+ lines.push('');
75
+ // 按天表(列宽固定,终端对齐;token 一律缩写)
76
+ lines.push(` ${ui.dim}${t('repl.usageColDate').padEnd(10)} ${col('in', 7)} ${col('out', 7)} ${col('cached', 7)} ${col('reason', 7)} ${col('calls', 6)} hit${ui.reset}`);
77
+ for (const d of s.byDay) {
78
+ if (d.calls === 0) {
79
+ lines.push(` ${ui.dim}${d.day} ${t('repl.usageEmptyDay')}${ui.reset}`);
80
+ continue;
81
+ }
82
+ lines.push(` ${ui.cyan}${d.day}${ui.reset} ${col(tok(d.input), 7)} ${col(tok(d.output), 7)} ${col(tok(d.cached), 7)} ${col(tok(d.reasoning), 7)} ${col(n(d.calls), 6)} ${pct(d.cached, d.input)}`);
83
+ }
84
+ lines.push(` ${ui.bold}${totalRow(b)}${ui.reset}`);
85
+ lines.push('');
86
+ lines.push(...groupTable(t('repl.usageByWorkspace'), s.byWorkspace, 40));
87
+ lines.push('');
88
+ lines.push(...groupTable(t('repl.usageByModel'), s.byModel, 32));
89
+ return lines.join('\n');
90
+ }
11
91
  export const statsCommands = [
92
+ // /usage [days]:跨工作空间按天汇总。默认 7 天,可传天数(如 /usage 30);非法参数给用法提示。
93
+ (ctx) => {
94
+ if (ctx.line !== '/usage' && !ctx.line.startsWith('/usage '))
95
+ return unhandled();
96
+ const arg = ctx.line.replace(/^\/usage\s*/, '').trim();
97
+ let days = 7;
98
+ if (arg) {
99
+ const parsed = Number(arg);
100
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 366) {
101
+ layout.contentWrite(`${ui.yellow}${t('repl.usageBadArg')}${ui.reset}\n`);
102
+ return next();
103
+ }
104
+ days = parsed;
105
+ }
106
+ const records = readGlobalUsage();
107
+ if (records.length === 0) {
108
+ layout.contentWrite(`${ui.dim}${t('repl.usageNoData')}${ui.reset}\n`);
109
+ return next();
110
+ }
111
+ layout.contentWrite(` ${formatGlobal(summarizeGlobalUsage(records, days))}\n`);
112
+ return next();
113
+ },
12
114
  (ctx) => {
13
115
  if (ctx.line !== '/stats')
14
116
  return unhandled();
@@ -24,9 +24,11 @@ export function buildSlashCommands() {
24
24
  { name: '/skills', desc: d('commands.skills') },
25
25
  { name: '/skill', desc: '执行某个 skill(/skill <name> [args-json])' },
26
26
  { name: '/compact', desc: d('commands.compact') },
27
+ { name: '/usage', desc: d('commands.usage') },
27
28
  { name: '/stats', desc: '查看本会话 token 用量与缓存命中率' },
28
29
  { name: '/effort', desc: '设置思考强度(/effort [low|medium|high|auto])' },
29
30
  { name: '/resume', desc: d('commands.sessionResume') },
31
+ { name: '/fork', desc: d('commands.sessionFork') },
30
32
  { name: '/sessions', desc: d('commands.sessionBrowse') },
31
33
  { name: '/rollback', desc: d('commands.sessionRollback') },
32
34
  { name: '/diff', desc: '查看 agent 文件改动 diff(/diff [N]|all,快照 vs 工作区)' },
@@ -205,7 +207,10 @@ export const LLM_ERROR_HINT_KEYS = {
205
207
  /** /help 的分组:按使用场景归组,组内保持菜单树顺序。未列入的顶层命令兜底进「其他」。 */
206
208
  export const HELP_GROUPS = [
207
209
  { key: 'help.groupFrequent', names: ['/help', '/clear', '/cd', '/context', '/compact', '/resume', '/model'] },
208
- { key: 'help.groupSession', names: ['/sessions', '/rollback', '/memory', '/skills', '/skill', '/init'] },
210
+ {
211
+ key: 'help.groupSession',
212
+ names: ['/fork', '/sessions', '/rollback', '/usage', '/memory', '/skills', '/skill', '/init'],
213
+ },
209
214
  {
210
215
  key: 'help.groupConfig',
211
216
  names: [