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.
package/README.md CHANGED
@@ -215,8 +215,8 @@ Common backend `base_url` values:
215
215
  | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `256000` |
216
216
  | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
217
217
  | `AUTO_COMPACT` | Final history-compaction safety fallback | `true` |
218
- | `AUTO_REFLECT` | Background reflection pass (on by default, max 3 auto runs/session; set `false` to disable) | `true` |
219
- | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
218
+ | `AUTO_REFLECT` | Background reflection pass (on by default, max 5 auto runs/session + one at exit if none ran; set `false` to disable) | `true` |
219
+ | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `2` |
220
220
  | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
221
221
  | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
222
222
  | `SKILLS_DIRS` | Override the default skill scan directories (platform path separator) | three default directories |
package/README.zh-CN.md CHANGED
@@ -214,8 +214,8 @@ LLM_MODEL=glm-4.6 # 换成你的模型名
214
214
  | `CONTEXT_WINDOW_TOKENS` | 模型上下文窗口,须对齐真实模型 | `256000` |
215
215
  | `LLM_STREAM_USAGE` | 流式请求带 `stream_options.include_usage` 拿真实用量 | `true` |
216
216
  | `AUTO_COMPACT` | 最终 history compact 安全保护 | `true` |
217
- | `AUTO_REFLECT` | 后台反思 pass(默认开启,每会话至多 3 次自动反思;显式 `false` 关闭) | `true` |
218
- | `REFLECT_EVERY_N` | 每 N 轮触发一次后台反思(与 agent 并发,不阻塞) | `5` |
217
+ | `AUTO_REFLECT` | 后台反思 pass(默认开启,每会话至多 5 次自动反思,退出时若一次未跑则补一次;显式 `false` 关闭) | `true` |
218
+ | `REFLECT_EVERY_N` | 每 N 轮触发一次后台反思(与 agent 并发,不阻塞) | `2` |
219
219
  | `ANYSEARCH_API_KEY` | 联网搜索 API key(不配走匿名免费额度) | 无 |
220
220
  | `ANYSEARCH_BASE_URL` | 搜索 API 端点 | `https://api.anysearch.com` |
221
221
  | `SKILLS_DIRS` | 覆盖默认 skill 扫描目录(平台分隔符) | 三目录自动扫描 |
@@ -8,7 +8,7 @@ import { summarizeToolCall, summarizeToolResult, truncateDisplay, fmtElapsed, fm
8
8
  import { renderFileChange, renderMultiFileChange } from '../ui/diff.js';
9
9
  import * as layout from '../ui/layout.js';
10
10
  import * as batch from '../ui/batch.js';
11
- import { config } from '../config/index.js';
11
+ import { config, isMemoryEnabled } from '../config/index.js';
12
12
  import { isMutationTool } from './core.js';
13
13
  import { createRuntime, defaultRuntime, Runtime } from '../runtime/index.js';
14
14
  import { createPetHooks } from '../pet/state.js';
@@ -16,6 +16,8 @@ import { defaultAgentRuntimeContext } from './runtime-context.js';
16
16
  import { t } from '../i18n/index.js';
17
17
  import { isToolErrorOutput } from '../tools/result.js';
18
18
  import { appendCurrentSessionTraceEvent } from '../session/index.js';
19
+ import { buildTurnRecallSection, isTurnRecallEnabled } from '../memory/turn-recall.js';
20
+ import { memoryTailChangedIds } from '../memory/tail.js';
19
21
  /** 当前 turn 的 batch id(runAgent 内闭包变量;一条 turn 一轮 tool batch 结束即清空)。 */
20
22
  let currentBatchId = null;
21
23
  /** 当前活跃的 sub-agent 组容器批 id(同一轮并行派发的多个 sub-agent 合并到这一个顶层摘要行下)。
@@ -497,6 +499,20 @@ runtimeOrContext = defaultRuntime) {
497
499
  const petHooks = createPetHooks();
498
500
  const combinedHooks = mergeHooks(hooks, petHooks);
499
501
  let result;
502
+ // R18:每轮静默召回。在这里(而非 runAgentCore)现算的理由:
503
+ // ① runAgent 是 TUI 组合根,只有真实用户轮会走到;runAgentCore 被全部 agent 单测
504
+ // 直接调用,在那儿读记忆库会让测试读到本机真实记忆、失去隔离性;
505
+ // ② spawn 走 runtime.run 不经过这里,子 agent 天然零注入。
506
+ // 排除 memoryTailChangedIds():那批条目由 R17 尾注播报,同一轮不应讲两遍。
507
+ const userText = Array.isArray(userInput)
508
+ ? userInput
509
+ .filter((part) => part.type === 'text')
510
+ .map((part) => part.text)
511
+ .join(' ')
512
+ : userInput;
513
+ const memoryRecall = isMemoryEnabled() && isTurnRecallEnabled()
514
+ ? buildTurnRecallSection(userText, { excludeIds: memoryTailChangedIds() })
515
+ : '';
500
516
  try {
501
517
  result = await runtime.run({
502
518
  turn: 'new',
@@ -509,6 +525,7 @@ runtimeOrContext = defaultRuntime) {
509
525
  toolPolicy,
510
526
  initialToolRoute,
511
527
  memoryTail,
528
+ memoryRecall,
512
529
  onTraceEvent: appendCurrentSessionTraceEvent,
513
530
  });
514
531
  }
@@ -5,7 +5,9 @@ import { createImageDescriber, relieveRequestBytes } from './request-governor.js
5
5
  import { countOversizedImagePlaceholders, countOversizedImages } from '../context/vision-window.js';
6
6
  import { getActiveSessionStore } from '../session/store.js';
7
7
  import { getCurrentSessionId } from '../session/state.js';
8
+ import { appendGlobalUsage } from '../session/global-usage.js';
8
9
  import { toUsageRecord } from '../session/usage-stats.js';
10
+ import { getWorkspaceRoot } from '../workspace/index.js';
9
11
  /**
10
12
  * 沿 cause 链(≤3 层)取第一个 errno,供 trace 取证。
11
13
  * undici 把底层 errno 挂在 cause 上(`TypeError: fetch failed` → cause `read ECONNRESET`),
@@ -36,7 +38,18 @@ export async function runModelTurn(input) {
36
38
  // 而不是全量 chatTools(含未路由的 MCP/写工具),避免凭空高估。
37
39
  runtimeContextState.activeTools = activeTools;
38
40
  let sessionStateText = opts.suppressSessionState ? '' : ctx.buildSessionStateReminder();
39
- runtimeContextState.ephemeralText = sessionStateText || undefined;
41
+ // R18/R17:两个记忆附加段一旦非空,末尾就多出一条 system 消息。下面所有涉及
42
+ // 「history 长度 -1」与 ephemeral token 估算的地方必须用**同一个**判据,否则用量条
43
+ // 与压缩压力线会持续低估(召回段 + 尾注的字数并不小)。
44
+ const memoryRecallText = input.memoryRecall ?? '';
45
+ const memoryTailText = opts.memoryTail ?? '';
46
+ const ephemeralJoined = () => [sessionStateText, memoryRecallText, memoryTailText].filter((s) => s.length > 0).join('\n\n');
47
+ /** 与 ephemeralJoined() 同源,保证「发了多少」与「算多大」永不漂移。 */
48
+ const ephemeralTokenEstimate = () => {
49
+ const joined = ephemeralJoined();
50
+ return joined ? estimateTokens(joined) : 0;
51
+ };
52
+ runtimeContextState.ephemeralText = ephemeralJoined() || undefined;
40
53
  onContextUpdate?.();
41
54
  let historyRebuilt = false;
42
55
  let overflowRetried = false;
@@ -105,7 +118,7 @@ export async function runModelTurn(input) {
105
118
  history: historyManager.snapshot(),
106
119
  step,
107
120
  tools: activeTools,
108
- ephemeralTokens: sessionStateText ? estimateTokens(sessionStateText) : 0,
121
+ ephemeralTokens: ephemeralTokenEstimate(),
109
122
  signal,
110
123
  });
111
124
  historyRebuilt = trimResult.kind === 'rebuild';
@@ -180,6 +193,9 @@ export async function runModelTurn(input) {
180
193
  '4. Before re-running a search/read you think you already did, check the summary and notes first; repeat only if the result is genuinely missing or the target changed.'
181
194
  : '',
182
195
  sessionStateText,
196
+ // R18:每轮静默召回。放在 R17 尾注之前:尾注说的是「刚变了什么」(时间上最新),
197
+ // 召回说的是「这轮可能用得上什么」(topic 相关),新的信息靠后更能被看见。
198
+ input.memoryRecall ?? '',
183
199
  // R17:会话内记忆尾注。放最后——它是最"新"的信息,且每轮可能不同,
184
200
  // 放在固定段之后能最大限度保住前缀缓存的可复用部分。
185
201
  opts.memoryTail ?? '',
@@ -410,7 +426,7 @@ export async function runModelTurn(input) {
410
426
  history: historyManager.snapshot(),
411
427
  step,
412
428
  tools: activeTools,
413
- ephemeralTokens: sessionStateText ? estimateTokens(sessionStateText) : 0,
429
+ ephemeralTokens: ephemeralTokenEstimate(),
414
430
  signal,
415
431
  });
416
432
  const overflowStats = overflowResult.kind === 'aborted' ? {} : overflowResult.stats;
@@ -457,6 +473,20 @@ export async function runModelTurn(input) {
457
473
  const sessionId = getCurrentSessionId();
458
474
  if (record && sessionId)
459
475
  getActiveSessionStore().appendUsage(sessionId, record);
476
+ // 全局跨工作空间账本(/usage 按天汇总);best-effort,见 global-usage.ts。
477
+ if (result.usage && sessionId) {
478
+ appendGlobalUsage({
479
+ workspace: getWorkspaceRoot(),
480
+ model: requestModel,
481
+ phase: 'main',
482
+ sessionId,
483
+ input: result.usage.promptTokens,
484
+ output: result.usage.completionTokens,
485
+ cached: result.usage.cachedTokens,
486
+ reasoning: result.usage.reasoningTokens,
487
+ cacheCreation: result.usage.cacheCreationTokens,
488
+ });
489
+ }
460
490
  if (result.usage) {
461
491
  cacheState.lastStepPromptTokens = result.usage.promptTokens;
462
492
  if (result.usage.cachedTokens > 0)
@@ -473,9 +503,9 @@ export async function runModelTurn(input) {
473
503
  runtimeContextState.promptAnchor = {
474
504
  measuredPromptTokens: result.usage.promptTokens,
475
505
  baseRaw: estimated,
476
- historyLen: sessionStateText ? requestHistoryLen - 1 : requestHistoryLen,
506
+ historyLen: ephemeralJoined() ? requestHistoryLen - 1 : requestHistoryLen,
477
507
  tools: activeTools,
478
- ephemeralText: sessionStateText,
508
+ ephemeralText: ephemeralJoined(),
479
509
  };
480
510
  }
481
511
  hooks.onChatDone?.();
@@ -6,6 +6,8 @@
6
6
  // spawn.ts 的 spawnAgent = runAgentCore + 静默 hooks(子 agent)。
7
7
  import { validateToolArguments } from '../tools/validation.js';
8
8
  import { getPlanDisabledTools, getRuntimeDisabledTools, getSkillRuntimeDisabledTools } from '../tools/constants.js';
9
+ import { isMemoryEnabled } from '../config/index.js';
10
+ import { isProactiveEnabled, proactiveHint } from '../memory/proactive.js';
9
11
  import { ADD_TOOL_GROUPS_TOOL_NAME } from '../config/profiles.js';
10
12
  import { defaultAgentRuntimeContext } from './runtime-context.js';
11
13
  import { runModelTurn } from './model-turn.js';
@@ -49,6 +51,30 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
49
51
  .filter((p) => p.type === 'text')
50
52
  .map((p) => p.text)
51
53
  .join(' ');
54
+ // R3.3:前摄注入的**唯一出口**。必须挂在这里,不能只挂在 StagedToolDispatcher 上:
55
+ // 生产入口 runAgent → runAgentCore 不传 `pipeline`,createAgentPipelineAssembly 默认
56
+ // 'legacy',而注入原先只写在 staged dispatcher 的 execute 里 → 线上前摄从未通电
57
+ // (证据:`.mocode/memory-proactive-stats.json` 从未生成,而同函数块里的
58
+ // `memory-recall-stats.json` 正常写入)。包一层执行出口而非逐处插桩,5 个调度分支
59
+ // (只读并发 / 串行 / 资源锁 / 编排 / 兜底)自然全覆盖。
60
+ const proactiveOn = isMemoryEnabled() && isProactiveEnabled();
61
+ const runToolWithProactive = async (name, argsRaw, sig, execOpts) => {
62
+ const outcome = await ctx.toolRuntime.executeToolOutcome(name, argsRaw, sig, execOpts);
63
+ if (!proactiveOn)
64
+ return outcome;
65
+ // 被拒绝 / 未执行的调用不该白烧一次匹配。
66
+ if (outcome.status !== 'success' && outcome.status !== 'error')
67
+ return outcome;
68
+ const proactive = proactiveHint(name, parseArgs(argsRaw), true, proactiveContext);
69
+ if (!proactive)
70
+ return outcome;
71
+ const base = outcome.output ?? '';
72
+ return { ...outcome, output: base ? `${base}\n\n${proactive}` : proactive };
73
+ };
74
+ // R18:每轮静默召回。段由**调用方**算(见 run-contracts 的 memoryRecall 注释):
75
+ // core 不读记忆库,否则每个 agent 单测都会去读真实的 ~/.mocode/memory.jsonl,
76
+ // 测试既失去隔离性、断言也会被本机记忆内容污染;spawn 不传即天然零注入。
77
+ const memoryRecall = opts.memoryRecall ?? '';
52
78
  const runtimeToolSchemas = ctx.toolRuntime.tools.map((tool) => ({
53
79
  type: 'function',
54
80
  function: {
@@ -184,6 +210,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
184
210
  step,
185
211
  maxSteps,
186
212
  readDedup,
213
+ memoryRecall,
187
214
  cacheState: modelCacheState,
188
215
  turnLifecycle,
189
216
  cancellationLifecycle,
@@ -402,7 +429,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
402
429
  if (eligibleReadonly.length > 0) {
403
430
  hooks.onToolStart?.(calls[eligibleReadonly[0]].name);
404
431
  for (const index of eligibleReadonly) {
405
- startedReadonly[index] = ctx.toolRuntime.executeToolOutcome(calls[index].name, calls[index].arguments, signal, {
432
+ startedReadonly[index] = runToolWithProactive(calls[index].name, calls[index].arguments, signal, {
406
433
  callId: calls[index].id,
407
434
  onOutput: (chunk) => hooks.onToolOutput?.(calls[index], chunk),
408
435
  allowedToolNames: currentAllowedToolNames(),
@@ -574,7 +601,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
574
601
  for (const tc of batch)
575
602
  hooks.onToolHeader?.(tc);
576
603
  hooks.onToolStart?.(batch[0].name);
577
- const started = batch.map((tc) => ctx.toolRuntime.executeToolOutcome(tc.name, tc.arguments, signal, {
604
+ const started = batch.map((tc) => runToolWithProactive(tc.name, tc.arguments, signal, {
578
605
  callId: tc.id,
579
606
  onOutput: (chunk) => hooks.onToolOutput?.(tc, chunk),
580
607
  allowedToolNames: currentAllowedToolNames(),
@@ -673,7 +700,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
673
700
  const hint = argumentErrorHint(entry.tc.name, runtimeContextState);
674
701
  const outcome = entry.denied
675
702
  ? entry.denied
676
- : await ctx.toolRuntime.executeToolOutcome(entry.tc.name, entry.tc.arguments, signal, {
703
+ : await runToolWithProactive(entry.tc.name, entry.tc.arguments, signal, {
677
704
  callId: entry.tc.id,
678
705
  onOutput: (chunk) => hooks.onToolOutput?.(entry.tc, chunk),
679
706
  allowedToolNames: currentAllowedToolNames(),
@@ -763,7 +790,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
763
790
  if (entry.denied)
764
791
  return Promise.resolve(entry.denied);
765
792
  const hint = argumentErrorHint(entry.tc.name, runtimeContextState);
766
- return ctx.toolRuntime.executeToolOutcome(entry.tc.name, entry.tc.arguments, signal, {
793
+ return runToolWithProactive(entry.tc.name, entry.tc.arguments, signal, {
767
794
  callId: entry.tc.id,
768
795
  onOutput: (chunk) => hooks.onToolOutput?.(entry.tc, chunk),
769
796
  allowedToolNames: currentAllowedToolNames(),
@@ -860,7 +887,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
860
887
  let diff = readDiffContext(tc, mutationParsed, ctx.jailResolve);
861
888
  hooks.onToolStart?.(tc.name);
862
889
  const serialHint = argumentErrorHint(tc.name, runtimeContextState);
863
- const outcome = await ctx.toolRuntime.executeToolOutcome(tc.name, tc.arguments, signal, {
890
+ const outcome = await runToolWithProactive(tc.name, tc.arguments, signal, {
864
891
  callId: tc.id,
865
892
  onOutput: (chunk) => hooks.onToolOutput?.(tc, chunk),
866
893
  allowedToolNames: currentAllowedToolNames(),
@@ -620,7 +620,7 @@ export const config = {
620
620
  toolClearing: process.env.MOCODE_TOOL_CLEARING !== 'false',
621
621
  autoReflect: process.env.AUTO_REFLECT !== 'false',
622
622
  memoryEnabled: process.env.MEMORY_ENABLED === 'true',
623
- reflectEveryN: Number(process.env.REFLECT_EVERY_N) || 5,
623
+ reflectEveryN: Number(process.env.REFLECT_EVERY_N) || 2,
624
624
  maxSteps: Number(process.env.MAX_STEPS) || 1000,
625
625
  subAgentEnabled: process.env.MOCODE_SUBAGENT_ENABLED === 'true',
626
626
  subAgentMaxSteps: Number(process.env.SUB_AGENT_MAX_STEPS) || Number(process.env.MAX_STEPS) || 1000,
package/dist/headless.js CHANGED
@@ -27,6 +27,7 @@ import { buildAboutYouSection, initPersona } from './memory/persona.js';
27
27
  import { buildProjectGraphHint } from './memory/recall.js';
28
28
  import { buildEpisodeSection, collectChangedFiles, extractCompactionSummary, recordSessionEpisode, } from './memory/episodic.js';
29
29
  import { flushProactiveStats } from './memory/proactive.js';
30
+ import { flushTurnRecallStats, buildTurnRecallSection, isTurnRecallEnabled } from './memory/turn-recall.js';
30
31
  import { writeMemoryHealth } from './memory/health.js';
31
32
  import { defaultRuntime, Runtime } from './runtime/index.js';
32
33
  import { runAgentCore } from './agent/core.js';
@@ -261,10 +262,14 @@ export async function runHeadless(opts) {
261
262
  const startedAt = Date.now();
262
263
  let exitCode = 0;
263
264
  let result;
265
+ // R18:一次性执行也做一轮静默召回。放在这里而非 runAgentCore:core 不读记忆库,
266
+ // 否则所有 agent 单测都会读到本机真实记忆。子 agent(spawn)不经过这里,天然零注入。
267
+ const memoryRecall = memoryOn && isTurnRecallEnabled() ? buildTurnRecallSection(prompt) : '';
264
268
  const invokeCore = () => runAgentCore({
265
269
  history,
266
270
  userInput: prompt,
267
271
  hooks,
272
+ ...(memoryRecall ? { memoryRecall } : {}),
268
273
  ...(jobSignal ? { signal: jobSignal } : {}),
269
274
  runtimeContext: runtime.context,
270
275
  ...(resumedFromCheckpoint ? { continueFromHistory: true } : {}),
@@ -301,6 +306,8 @@ export async function runHeadless(opts) {
301
306
  // R4.1:一次性执行同样留下度量 —— 否则 `mocode -p` 用的那一侧永远是空白。
302
307
  // 只在前摄计数有增量时才落盘,健康快照失败静默。
303
308
  flushProactiveStats();
309
+ // R18:一次性执行的静默召回计数同样落盘,否则 `mocode -p` 那一侧永远空白。
310
+ flushTurnRecallStats();
304
311
  writeMemoryHealth(memoryOn);
305
312
  await runtime.close();
306
313
  if (wt) {
@@ -10,10 +10,12 @@ const zhCN = {
10
10
  'commands.context': '显示上下文用量条',
11
11
  'commands.skills': '列出已发现的 skill',
12
12
  'commands.compact': '压缩历史(可带焦点 /compact …)',
13
+ 'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
13
14
  'commands.session': '会话恢复与回滚',
14
15
  'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
15
16
  'commands.sessionBrowse': '浏览全部已保存会话',
16
17
  'commands.sessionRollback': '菜单选轮次回滚(↑↓·Enter)',
18
+ 'commands.sessionFork': '从当前会话分叉出独立新会话(不切换窗口)',
17
19
  'commands.memory': '记忆库、开关与反思',
18
20
  'commands.memoryOverview': '条目计数与近期索引',
19
21
  'commands.memoryToggle': '切换记忆子系统开关',
@@ -179,6 +181,26 @@ const zhCN = {
179
181
  'repl.noSessions': '(没有已保存的会话)',
180
182
  'repl.noValue': '(无)',
181
183
  'repl.historyCleared': '(历史已清空,保留系统提示)',
184
+ 'repl.forkUsage': '用法:/fork(无参数;从当前会话分叉)',
185
+ 'repl.forkEmpty': '(当前还没有对话,无可分叉内容)',
186
+ 'repl.forkFailed': '(分叉失败:{message})',
187
+ 'repl.forkMissing': '(当前会话尚未落盘,无法分叉)',
188
+ 'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
189
+ 'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
190
+ 'repl.usageTitle': 'Token 用量(全局 · {from} ~ {to} · {days} 天)',
191
+ 'repl.usageTotal': '总计 {total} tokens = in {input} + out {output} · {calls} 次请求 · {sessions} 个会话 · {workspaces} 个工作空间',
192
+ 'repl.usageMetrics': '缓存命中 {hit} · 推理占输出 {reasoning} · 缓存写 {cacheWrite} · 日均 {daily}',
193
+ 'repl.usageCompact': '其中压缩(compact):in {input} / out {output} / {calls} 次',
194
+ 'repl.usageColDate': 'date',
195
+ 'repl.usageEmptyDay': '(无用量)',
196
+ 'repl.usageTotalRow': '合计',
197
+ 'repl.usageByWorkspace': '按工作空间',
198
+ 'repl.usageByModel': '按模型',
199
+ 'repl.usageNone': '(无)',
200
+ 'repl.usageMore': '… 其余 {n} 项已省略',
201
+ 'repl.usageSessions': '{n} 个会话',
202
+ 'repl.usageBadArg': '用法:/usage [天数 1-366](默认 7)',
203
+ 'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积)',
182
204
  'repl.planAlready': '(已在 plan 模式)',
183
205
  'repl.planChanged': '(已切到 plan 模式:只读探查 + 产出计划,审批后切 auto 执行。/auto 或 Shift+Tab 切回)',
184
206
  'repl.autoAlready': '(已在 auto 模式)',
@@ -411,6 +433,8 @@ const zhCN = {
411
433
  'memory.stateDisabled': '关闭',
412
434
  'memory.source': 'MEMORY_ENABLED={value} · {path}',
413
435
  'memory.statusHint': '路由 gate 决定 memory-read / memory-write 是否可选;Index 状态决定紧凑索引和后台反思是否启用。每个真实用户轮都会重新路由。',
436
+ // R9.4 空库提示:不能让用户对着空库静默空转,但也不能弹窗打断。
437
+ 'memory.emptyHint': '记忆库还是空的:输入 /memory seed 可以从 AGENTS.md 播种已有约定(只提议,选中才写入)',
414
438
  'memory.usage': '用法:/memory_switch [on|off|status](/memory_status 仅查看状态)',
415
439
  'memory.unchanged': 'Memory 已是{state},未变更。',
416
440
  'memory.changedOn': '已允许按需路由 memory-read / memory-write,并开启 Memory Index。',
@@ -476,10 +500,12 @@ const en = {
476
500
  'commands.context': 'Show context usage',
477
501
  'commands.skills': 'List discovered skills',
478
502
  'commands.compact': 'Compact history (optional focus: /compact …)',
503
+ 'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
479
504
  'commands.session': 'Resume sessions and roll back turns',
480
505
  'commands.sessionResume': 'Resume one of the 10 latest saved sessions',
481
506
  'commands.sessionBrowse': 'Browse all saved sessions',
482
507
  'commands.sessionRollback': 'Choose a turn to roll back (↑↓·Enter)',
508
+ 'commands.sessionFork': 'Fork the current session into an independent new one (window stays)',
483
509
  'commands.memory': 'Memory store, controls, and reflection',
484
510
  'commands.memoryOverview': 'Show counts and recent entries',
485
511
  'commands.memoryToggle': 'Toggle the memory subsystem',
@@ -640,6 +666,26 @@ const en = {
640
666
  'repl.noSessions': '(no saved sessions)',
641
667
  'repl.noValue': '(none)',
642
668
  'repl.historyCleared': '(history cleared; system prompt kept)',
669
+ 'repl.forkUsage': 'Usage: /fork (no arguments; forks the current session)',
670
+ 'repl.forkEmpty': '(no conversation yet; nothing to fork)',
671
+ 'repl.forkFailed': '(fork failed: {message})',
672
+ 'repl.forkMissing': '(current session is not persisted yet; cannot fork)',
673
+ 'repl.forkDone': 'Forked new session {id} (inherits full context; independent from the original)',
674
+ 'repl.forkHint': 'This window stays on the original session; run mocode --resume {id} in a new terminal, or use /resume here',
675
+ 'repl.usageTitle': 'Token usage (global · {from} ~ {to} · {days}d)',
676
+ 'repl.usageTotal': 'Total {total} tokens = in {input} + out {output} · {calls} requests · {sessions} sessions · {workspaces} workspaces',
677
+ 'repl.usageMetrics': 'Cache hit {hit} · reasoning share of output {reasoning} · cache write {cacheWrite} · daily avg {daily}',
678
+ 'repl.usageCompact': 'of which compact: in {input} / out {output} / {calls} calls',
679
+ 'repl.usageColDate': 'date',
680
+ 'repl.usageEmptyDay': '(no usage)',
681
+ 'repl.usageTotalRow': 'Total',
682
+ 'repl.usageByWorkspace': 'By workspace',
683
+ 'repl.usageByModel': 'By model',
684
+ 'repl.usageNone': '(none)',
685
+ 'repl.usageMore': '… {n} more hidden',
686
+ 'repl.usageSessions': '{n} sessions',
687
+ 'repl.usageBadArg': 'Usage: /usage [days 1-366] (default 7)',
688
+ 'repl.usageNoData': '(No global usage data yet; collection starts from model calls after this feature is enabled)',
643
689
  'repl.planAlready': '(already in plan mode)',
644
690
  'repl.planChanged': '(switched to plan mode: read-only research and planning; approval returns to auto. Use /auto or Shift+Tab to switch back)',
645
691
  'repl.autoAlready': '(already in auto mode)',
@@ -874,6 +920,8 @@ const en = {
874
920
  'memory.stateDisabled': 'disabled',
875
921
  'memory.source': 'MEMORY_ENABLED={value} · {path}',
876
922
  'memory.statusHint': 'The route gate controls whether memory-read / memory-write may be selected; the Index state controls prompt injection and background reflection. Every real user turn is routed again.',
923
+ // R9.4 empty-store hint: never let the user sit in front of an empty store, never interrupt either.
924
+ 'memory.emptyHint': 'Memory store is empty: /memory seed can propose entries from your AGENTS.md conventions (proposes only, writes only what you pick)',
877
925
  'memory.usage': 'Usage: /memory_switch [on|off|status] (/memory_status only reports state)',
878
926
  'memory.unchanged': 'Memory is already {state}; no change made.',
879
927
  'memory.changedOn': 'Memory-read / memory-write may now be routed on demand, and the Memory Index is enabled.',
@@ -0,0 +1,227 @@
1
+ /**
2
+ * R2.6 存量记忆的锚点回填:**只提议,不自动写**。
3
+ *
4
+ * ## 为什么现在做
5
+ *
6
+ * R2(代码锚点)在真实库上完全休眠:23 条 global + 72 条 project 里,有锚点的**一条也没有**。
7
+ * 不是实现错了,而是只有新写入才会产锚点,而老条目再也不会被重写一遍——于是 R2 的
8
+ * `STALE-CODE` 标记、R2.4 的 `read_file` 回注、R3.6 的锚点弱 trigger 三条通道全部空转。
9
+ *
10
+ * ## 为什么是「提议」而不是「自动回填」
11
+ *
12
+ * 设计文档的开放问题 12 曾倾向「不回填」,理由是「这条记忆讲的是哪个符号机器判断不了,
13
+ * 强行回填只会制造大量 stale 噪音」。这个判断对**符号**成立,对**路径**不成立:
14
+ * body 里写着的 `src/memory/store.ts` 是用户当时亲眼看到的路径,把它变成锚点不是猜测。
15
+ * 但路径正确 ≠ 这条记忆**只**关于这个文件(可能只是顺带提到),所以写库必须由用户
16
+ * `/memory anchor <n>` 显式确认——与 R9.1 播种同一形态。
17
+ *
18
+ * ## 确定性抽取的边界
19
+ *
20
+ * 只抽「看起来是文件路径、且该文件此刻**真的存在于工作区**」的字面量:
21
+ *
22
+ * - **要求存在**:不存在就锚不住任何东西,写进去只会是一条永远 missing 的噪音;
23
+ * - **只收白名单扩展名**:`2.01`(相机固件)和 `3.5.0`(App 版本)也是「点 + 数字」,
24
+ * 不设扩展名白名单会把它们当路径;
25
+ * - **跳过 URL 与 node_modules**:URL 有独立的 `kind:'url'`(且恒 unknown,对这条通道
26
+ * 没价值);node_modules 里的路径会随 `npm i` 整体消失。
27
+ *
28
+ * 单条最多 4 个:候选是给人看的清单,一屏 8 个路径没人会挨个核对;真正的锚点上限
29
+ * 仍是 `MAX_ANCHORS`(8),用户确认后按提议顺序取前 8 个。
30
+ */
31
+ import { existsSync, statSync } from 'node:fs';
32
+ import path from 'node:path';
33
+ import { getSandboxRoot } from '../sandbox/root.js';
34
+ import { toAnchorPath } from './anchor.js';
35
+ import { loadAll, updateEntry } from './store.js';
36
+ /** 一次最多列多少条候选(条目数)。与 `SEED_MAX_CANDIDATES` 同量级:一屏能核对完。 */
37
+ export const ANCHOR_BACKFILL_MAX_ENTRIES = 24;
38
+ /** 单条记忆最多提议几个路径。 */
39
+ export const ANCHOR_BACKFILL_MAX_PATHS = 4;
40
+ /**
41
+ * 认作「代码/文档文件」的扩展名白名单。
42
+ *
43
+ * 白名单而不是黑名单:路径的正则天然会撞上版本号(`2.01`、`4.00`)和域名(`typesafe.ai`),
44
+ * 只有枚举扩展名才能把它们挡在外面,而漏掉某个少见扩展名的代价只是"这条候选不出现"。
45
+ */
46
+ const FILE_EXT = new Set([
47
+ 'ts',
48
+ 'tsx',
49
+ 'js',
50
+ 'jsx',
51
+ 'mjs',
52
+ 'cjs',
53
+ 'py',
54
+ 'go',
55
+ 'rs',
56
+ 'java',
57
+ 'kt',
58
+ 'rb',
59
+ 'php',
60
+ 'c',
61
+ 'h',
62
+ 'cpp',
63
+ 'hpp',
64
+ 'cs',
65
+ 'swift',
66
+ 'sh',
67
+ 'bash',
68
+ 'zsh',
69
+ 'ps1',
70
+ 'bat',
71
+ 'json',
72
+ 'jsonl',
73
+ 'yaml',
74
+ 'yml',
75
+ 'toml',
76
+ 'ini',
77
+ 'xml',
78
+ 'md',
79
+ 'mdx',
80
+ 'txt',
81
+ 'html',
82
+ 'css',
83
+ 'scss',
84
+ 'less',
85
+ 'sql',
86
+ 'vue',
87
+ 'svelte',
88
+ ]);
89
+ /** 分隔符:空白 + 常见中英文标点。刻意不切 `/` `\\` `.` `:` `-`(它们都在路径内部)。 */
90
+ const TOKEN_SPLIT = /[\s()()「」『』【】[\]"'`<>,。、;;,|]+/;
91
+ /** 去掉 token 两端的包裹字符(反引号、引号已在 split 里切掉,这里兜住残留)。 */
92
+ function trimToken(tok) {
93
+ return tok
94
+ .replace(/^[.,;:!?]+/, '')
95
+ .replace(/[.,;:!?]+$/, '')
96
+ .replace(/^~(?=[/\\])/, '~');
97
+ }
98
+ /** 该 token 是否像一个文件路径(只看形状,不碰磁盘)。 */
99
+ export function looksLikePath(tok) {
100
+ if (!tok || tok.length > 200)
101
+ return false;
102
+ if (/^https?:\/\//i.test(tok) || tok.includes('://'))
103
+ return false;
104
+ // 域名:最后一段不像扩展名(类型是字母但整串含 @ 或形如 a.b.c 且每段都短)——交给扩展名白名单处理。
105
+ const m = /\.([A-Za-z][A-Za-z0-9]*)$/.exec(tok);
106
+ if (!m)
107
+ return false;
108
+ if (!FILE_EXT.has(m[1].toLowerCase()))
109
+ return false;
110
+ // 路径里必须有分隔符,或整串就是个纯文件名(如 AGENTS.md / SKILL.md)。
111
+ // 纯文件名交给存在性检查决定:能解析到工作区根下真实文件才算数。
112
+ if (/[\s]/.test(tok))
113
+ return false;
114
+ return true;
115
+ }
116
+ /**
117
+ * 从一个 token 解析出**工作区内**的真实文件,返回锚点路径;不在工作区/不存在 → null。
118
+ *
119
+ * 返回 `toAnchorPath` 归一后的形式(工作区内为相对路径):锚点要能跨机器、跨 clone 路径
120
+ * 仍然有效,存绝对路径会让同一条记忆换台电脑就永远 missing。
121
+ */
122
+ function resolveExistingFile(tok, root) {
123
+ if (!looksLikePath(tok))
124
+ return null;
125
+ if (tok.includes('node_modules'))
126
+ return null;
127
+ const abs = path.isAbsolute(tok) ? tok : path.resolve(root, tok);
128
+ // 必须落在工作区内:工作区外的绝对路径(用户自己的相机手册、别的项目)机器判断不了
129
+ // 归属,提议它等于让用户替我们猜。
130
+ const rel = path.relative(root, abs);
131
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
132
+ return null;
133
+ try {
134
+ if (!statSync(abs).isFile())
135
+ return null;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ return toAnchorPath(abs, root);
141
+ }
142
+ /** 从一条记忆的 name/summary/body 里抽候选路径(去重、保序)。 */
143
+ export function extractAnchorPaths(entry, root) {
144
+ const text = `${entry.name}\n${entry.summary}\n${entry.body}`;
145
+ const out = [];
146
+ const seen = new Set();
147
+ for (const raw of text.split(TOKEN_SPLIT)) {
148
+ const tok = trimToken(raw);
149
+ if (!tok || seen.has(tok))
150
+ continue;
151
+ seen.add(tok);
152
+ const p = resolveExistingFile(tok, root);
153
+ if (p && !out.includes(p))
154
+ out.push(p);
155
+ if (out.length >= ANCHOR_BACKFILL_MAX_PATHS)
156
+ break;
157
+ }
158
+ return out;
159
+ }
160
+ /**
161
+ * 扫描 active 条目,产出「可回填锚点」的候选。**只读**。
162
+ *
163
+ * 已有锚点的条目直接跳过,不做「补一条」:锚点集是整体替换语义(`UpdatePatch.anchors`),
164
+ * 混着补会让用户无法核对最后到底锚了什么。
165
+ */
166
+ export function collectAnchorCandidates(root) {
167
+ const base = root ?? getSandboxRoot() ?? process.cwd();
168
+ const all = loadAll().filter((e) => e.status === 'active' && e.type !== 'episode');
169
+ const candidates = [];
170
+ let alreadyAnchored = 0;
171
+ let noPath = 0;
172
+ for (const e of all) {
173
+ if (e.anchors && e.anchors.length > 0) {
174
+ alreadyAnchored += 1;
175
+ continue;
176
+ }
177
+ const paths = extractAnchorPaths(e, base);
178
+ if (paths.length === 0) {
179
+ noPath += 1;
180
+ continue;
181
+ }
182
+ candidates.push({
183
+ index: candidates.length + 1, // 1 基,只在最终列表里定格(截断前不编号)
184
+ id: e.id,
185
+ name: e.name,
186
+ summary: e.summary,
187
+ paths,
188
+ });
189
+ }
190
+ const truncated = Math.max(0, candidates.length - ANCHOR_BACKFILL_MAX_ENTRIES);
191
+ const kept = candidates.slice(0, ANCHOR_BACKFILL_MAX_ENTRIES);
192
+ // 截断后重编序号:用户看到的第一行就该是 1。
193
+ kept.forEach((c, i) => {
194
+ c.index = i + 1;
195
+ });
196
+ return { candidates: kept, alreadyAnchored, noPath, truncated };
197
+ }
198
+ /**
199
+ * 把选中的候选写成真锚点。
200
+ *
201
+ * `picks` 是 **1 基序号**(与屏幕上列出的一致)。走 `updateEntry` 而不是直接改 JSONL:
202
+ * hash 必须由 `buildAnchor` 现算,手写的 hash 只要错一个字符就是永久 stale。
203
+ *
204
+ * 逐条重新校验路径存在性——扫描与确认之间可能隔了很久(用户看完列表先去改别的),
205
+ * 期间文件可能被删。此时**不写入任何一条**:半套锚点会让这条记忆判定为 stale,
206
+ * 而它其实什么都没变。
207
+ */
208
+ export function applyAnchorCandidates(candidates, picks, root) {
209
+ const base = root ?? getSandboxRoot() ?? process.cwd();
210
+ const out = { saved: [], missing: [], lost: [] };
211
+ const wanted = candidates.filter((c) => picks === 'all' || picks.includes(c.index));
212
+ for (const c of wanted) {
213
+ const stillThere = c.paths.filter((p) => existsSync(path.resolve(base, p)));
214
+ if (stillThere.length === 0) {
215
+ out.lost.push({ index: c.index, id: c.id, paths: c.paths });
216
+ continue;
217
+ }
218
+ const anchors = stillThere.map((p) => ({ kind: 'file', path: p }));
219
+ const r = updateEntry(c.id, { anchors, reason: 'anchor backfill' });
220
+ if (!r.ok) {
221
+ out.missing.push({ index: c.index, id: c.id });
222
+ continue;
223
+ }
224
+ out.saved.push({ index: c.index, id: c.id, paths: stillThere });
225
+ }
226
+ return out;
227
+ }