mocode-ai 1.9.9 → 1.10.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 (74) hide show
  1. package/dist/agent/index.js +13 -3
  2. package/dist/agent/mentioned-files.js +71 -0
  3. package/dist/agent/model-turn.js +83 -16
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +151 -23
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +46 -0
  8. package/dist/agent/stages/history-manager.js +1 -0
  9. package/dist/agent/tool-helpers.js +2 -2
  10. package/dist/agent/tool-turn.js +49 -4
  11. package/dist/agent/work-discipline.js +9 -9
  12. package/dist/changeset/unified-diff.js +59 -0
  13. package/dist/config/index.js +13 -10
  14. package/dist/context/relevance.js +2 -1
  15. package/dist/context/usage-snapshot.js +50 -0
  16. package/dist/headless.js +3 -1
  17. package/dist/host/commit-message.js +41 -0
  18. package/dist/host/protocol.js +205 -10
  19. package/dist/host/stdio.js +1096 -63
  20. package/dist/i18n/index.js +26 -10
  21. package/dist/llm/index.js +28 -3
  22. package/dist/llm/message-shape.js +45 -0
  23. package/dist/llm/providers/anthropic.js +2 -0
  24. package/dist/llm/reasoning.js +17 -0
  25. package/dist/memory/adoption.js +159 -27
  26. package/dist/memory/anchor-relocate.js +227 -0
  27. package/dist/memory/consolidate-skips.js +196 -0
  28. package/dist/memory/health.js +88 -6
  29. package/dist/memory/index.js +2 -1
  30. package/dist/memory/reflect.js +36 -4
  31. package/dist/memory/store.js +30 -0
  32. package/dist/models/reasoning-cap.js +19 -2
  33. package/dist/orchestrator/lane-executor.js +7 -1
  34. package/dist/orchestrator/repl.js +30 -49
  35. package/dist/prompt/system-prompt.js +30 -0
  36. package/dist/repl/commands/appearance.js +1 -2
  37. package/dist/repl/commands/compact.js +4 -0
  38. package/dist/repl/commands/diff.js +5 -46
  39. package/dist/repl/commands/memory.js +77 -4
  40. package/dist/repl/commands/model-actions.js +4 -3
  41. package/dist/repl/commands/model.js +2 -3
  42. package/dist/repl/message-format.js +7 -6
  43. package/dist/repl/running-input.js +27 -65
  44. package/dist/repl/runtime.js +129 -89
  45. package/dist/repl/status-bar.js +4 -38
  46. package/dist/rollback/store.js +36 -23
  47. package/dist/runtime/browser-diagnostics.js +77 -0
  48. package/dist/runtime/browser-manager.js +150 -22
  49. package/dist/runtime/runtime.js +1 -1
  50. package/dist/session/compact.js +44 -4
  51. package/dist/session/retention.js +4 -0
  52. package/dist/session/short-path-metrics.js +185 -0
  53. package/dist/session/store.js +78 -3
  54. package/dist/session/terminal-transcript.js +101 -0
  55. package/dist/tools/builtins/ask-human.js +2 -2
  56. package/dist/tools/builtins/browser.js +4 -1
  57. package/dist/tools/builtins/edit-file.js +28 -5
  58. package/dist/tools/builtins/grep.js +85 -35
  59. package/dist/tools/builtins/memory-save.js +1 -1
  60. package/dist/tools/builtins/memory-update.js +1 -1
  61. package/dist/tools/builtins/plan-update.js +4 -2
  62. package/dist/tools/builtins/read-file.js +95 -44
  63. package/dist/tools/builtins/run-command.js +57 -9
  64. package/dist/tools/builtins/task.js +4 -0
  65. package/dist/tools/constants.js +8 -0
  66. package/dist/tools/ripgrep-client.js +31 -11
  67. package/dist/tools/tool-runtime.js +29 -8
  68. package/dist/ui/layout-internal/content-write.js +7 -3
  69. package/dist/ui/layout-internal/core.js +1 -1
  70. package/dist/ui/layout-internal/state.js +0 -6
  71. package/dist/ui/layout-internal/statusbar.js +0 -30
  72. package/dist/ui/output-sink.js +24 -0
  73. package/dist/ui/spinner.js +3 -1
  74. package/package.json +4 -2
@@ -621,6 +621,36 @@ export function updateEntry(id, patch) {
621
621
  clearPendingScope(e.scope);
622
622
  return { ok: true };
623
623
  }
624
+ /**
625
+ * R2.7 只换锚点、不动内容:给重定位用。
626
+ *
627
+ * 为什么不复用 `updateEntry({anchors})`:那条路径会拿 `buildAnchors` 把**整批**锚点
628
+ * 重算一遍 hash。重定位只该改被搬走的那一条地址,若顺带重算,同一批里真正 stale 的锚点
629
+ * 会被静默洗成 fresh —— 等于未经核对就宣称「这条记忆讲的还是现在的代码」。
630
+ * 所以调用方自己组装好锚点对象(未变的原样保留、搬家的重新 build),这里只负责落盘。
631
+ */
632
+ export function replaceAnchors(id, anchors, reason) {
633
+ const blocked = memoryWriteBlockReason();
634
+ if (blocked)
635
+ return { ok: false, blocked };
636
+ const all = loadAll();
637
+ const e = all.find((x) => x.id === id);
638
+ if (!e)
639
+ return { ok: false, notFound: true };
640
+ if (anchors.length > 0)
641
+ e.anchors = [...anchors];
642
+ else
643
+ delete e.anchors;
644
+ if (reason)
645
+ e.lastUpdateReason = reason;
646
+ e.updatedAt = nowIso();
647
+ const p = pathForScope(e.scope);
648
+ const entries = all.filter((x) => x.scope === e.scope);
649
+ ensureDir(p);
650
+ writeAtomic(p, entries);
651
+ clearPendingScope(e.scope);
652
+ return { ok: true };
653
+ }
624
654
  /**
625
655
  * 把旧条目标记为被新条目取代(status=superseded + supersededBy 链,不删除可审计)。
626
656
  * 与 forgetEntry 的区别:这是 belief-revision 语义——"旧信念被新事实取代",
@@ -10,7 +10,7 @@ const PROVIDER_DIALECT = {
10
10
  alibaba: 'qwen',
11
11
  zhipuai: 'thinking-toggle',
12
12
  volcengine: 'thinking-toggle',
13
- deepseek: 'thinking-toggle',
13
+ deepseek: 'deepseek',
14
14
  moonshotai: 'thinking-toggle',
15
15
  };
16
16
  export function dialectForProvider(catalogProviderId) {
@@ -20,7 +20,7 @@ export function dialectForProvider(catalogProviderId) {
20
20
  function pickEffortValue(effort, values, off) {
21
21
  const v = values.map((s) => s.toLowerCase());
22
22
  const priorities = off
23
- ? { any: ['off', 'disabled', 'minimal', 'low'] }
23
+ ? { any: ['off', 'disabled', 'none', 'minimal', 'low'] }
24
24
  : effort === 'low'
25
25
  ? { any: ['low', 'minimal'] }
26
26
  : effort === 'medium'
@@ -72,6 +72,23 @@ export function paramsFromCatalog(input) {
72
72
  // 无 effort/toggle 元数据但已知是 OpenAI 方言:直接下发归一化档位(off→low)。
73
73
  return { reasoning_effort: isOff ? 'low' : input.effort };
74
74
  }
75
+ // ── DeepSeek:thinking 开关 + 官方 effort 档位 ──
76
+ if (dialect === 'deepseek') {
77
+ if (isOff)
78
+ return { thinking: { type: 'disabled' } };
79
+ const base = { thinking: { type: 'enabled' } };
80
+ if (effortOpt?.values?.length) {
81
+ // DeepSeek 官方只有 low/high/max 时没有 medium,统一映射到 high。
82
+ base.reasoning_effort =
83
+ input.effort === 'medium' && !effortOpt.values.some((value) => /^(medium|mid)$/i.test(value))
84
+ ? 'high'
85
+ : pickEffortValue(input.effort, effortOpt.values, false);
86
+ }
87
+ else {
88
+ base.reasoning_effort = input.effort === 'low' ? 'low' : 'high';
89
+ }
90
+ return base;
91
+ }
75
92
  // ── thinking-toggle 方言 ──
76
93
  if (dialect === 'thinking-toggle') {
77
94
  if (effortOpt?.values && effortOpt.values.length > 0 && !isOff) {
@@ -243,7 +243,13 @@ export class LaneReplExecutor {
243
243
  if (this.cancelled.has(process_.key) || process_.dead)
244
244
  this.settle(process_, null);
245
245
  }, this.pollMs);
246
- timer.unref?.();
246
+ // ⚠ 这里**不能** unref:`result` 只能由这个 interval 结算,而等待一轮是"有活在跑",
247
+ // 进程就该活着。unref 之后一旦事件循环没有别的 ref 句柄,Node 会直接排空 ——
248
+ // 这个 Promise 永不 resolve,`node --test` 报
249
+ // "Promise resolution is still pending but the event loop has already resolved"
250
+ // 并把它记成 cancelledByParent(CI 从 1.9.5 起就是被这条连锁拖垮的:本地 Windows
251
+ // 因为 Go 测试等残留 ref 句柄恰好托住了循环,所以一直没复现)。
252
+ // 对照:同文件的 waitReady 用 `await sleep()`(ref 句柄),语义一致。
247
253
  try {
248
254
  return await result;
249
255
  }
@@ -21,7 +21,7 @@ import { ui } from '../ui/theme.js';
21
21
  import * as layout from '../ui/layout.js';
22
22
  import { padEndDisplay, summarizeToolCall, truncateDisplay } from '../ui/render.js';
23
23
  import { promptWithSlashMenu } from '../ui/prompt.js';
24
- import { clearRunningInput, consumeQueuedTurn, getRunningInput, startRunningListener, stopRunningListener, waitForRunningComposer, } from '../repl/running-input.js';
24
+ import { clearRunningInput, getRunningInput, startRunningListener, stopRunningListener, waitForRunningComposer, } from '../repl/running-input.js';
25
25
  import { collectQueryHistory } from '../session/query-history.js';
26
26
  import { SupervisorRuntime } from './supervisor.js';
27
27
  import { terminalAutoOpenEnabled } from './terminal.js';
@@ -277,57 +277,38 @@ export async function runSupervisorChat(options) {
277
277
  // 运行态打开的 Ctrl+G 面板可能在本轮结束时仍开着:等它关闭再进 INPUT 态,
278
278
  // 否则两个 keypress 监听抢键(面板内容随后经 getRunningInput 预填)。
279
279
  await waitForRunningComposer();
280
- // 运行中按 Enter 排队的句子:agent 一结束就自动发送,跳过输入框(入队那一刻即已确认)。
281
- // 斜杠命令不静默执行(否则排队 /exit 会在用户没看着时触发),改为填回输入框等确认。
282
- const queued = consumeQueuedTurn();
283
280
  let input = null;
284
- let autoSend = false;
285
- if (queued && queued.text.trim().length > 0) {
286
- if (queued.text.trim().startsWith('/')) {
287
- pendingPrefill = queued.text.split('\n');
288
- }
289
- else {
290
- input = queued.text.split('\n');
291
- autoSend = true;
292
- // 排队时仍在输入框草稿里的字(typeahead)不能丢:回填为下一轮预填。
293
- if (getRunningInput().trim())
294
- pendingPrefill = [getRunningInput()];
295
- clearRunningInput();
296
- }
281
+ if (hasSubmitted)
282
+ layout.normalizeInputBoundary();
283
+ layout.enterInputMode('supervisor 待命');
284
+ try {
285
+ input = await promptWithSlashMenu({
286
+ prompt: PROMPT,
287
+ commands: supervisorCommands(),
288
+ history: () => collectQueryHistory(queryHistory).map((entry) => entry.text),
289
+ // 第二输入源(静默唤醒):只在**空输入框**里取,人正在打字时绝不抢。
290
+ // 排队的多条合并成一条——五个 Run 同时跑完,合成一次查收比五次清楚。
291
+ takeExternalTurn: () => {
292
+ if (wakeQueue.length === 0)
293
+ return null;
294
+ const batch = wakeQueue.splice(0, wakeQueue.length);
295
+ wakeText = batch.join('\n---\n');
296
+ return wakeText;
297
+ },
298
+ // 预填:命令预填优先,否则使用运行中的草稿。
299
+ ...(pendingPrefill
300
+ ? { initialLines: pendingPrefill }
301
+ : getRunningInput()
302
+ ? { initialLines: [getRunningInput()] }
303
+ : {}),
304
+ });
297
305
  }
298
- if (!autoSend) {
299
- if (hasSubmitted)
300
- layout.normalizeInputBoundary();
301
- layout.enterInputMode('supervisor 待命');
302
- try {
303
- input = await promptWithSlashMenu({
304
- prompt: PROMPT,
305
- commands: supervisorCommands(),
306
- history: () => collectQueryHistory(queryHistory).map((entry) => entry.text),
307
- // 第二输入源(静默唤醒):只在**空输入框**里取,人正在打字时绝不抢。
308
- // 排队的多条合并成一条——五个 Run 同时跑完,合成一次查收比五次清楚。
309
- takeExternalTurn: () => {
310
- if (wakeQueue.length === 0)
311
- return null;
312
- const batch = wakeQueue.splice(0, wakeQueue.length);
313
- wakeText = batch.join('\n---\n');
314
- return wakeText;
315
- },
316
- // 预填:待确认的排队斜杠命令优先,否则运行中打的字。
317
- ...(pendingPrefill
318
- ? { initialLines: pendingPrefill }
319
- : getRunningInput()
320
- ? { initialLines: [getRunningInput()] }
321
- : {}),
322
- });
323
- }
324
- catch {
325
- break; // Ctrl+C / Ctrl+D
326
- }
327
- pendingPrefill = null;
328
- // 预填已消费:不清会一直重填同一段(主 REPL 同款约定)。
329
- clearRunningInput();
306
+ catch {
307
+ break; // Ctrl+C / Ctrl+D
330
308
  }
309
+ pendingPrefill = null;
310
+ // 预填已消费:不清会一直重填同一段(主 REPL 同款约定)。
311
+ clearRunningInput();
331
312
  if (input === null)
332
313
  break;
333
314
  const line = input.join('\n').trim();
@@ -0,0 +1,30 @@
1
+ /**
2
+ * 一份系统提示的唯一组装点。
3
+ *
4
+ * 存在理由:这套段组合原先在两处各写一遍——REPL(src/repl/runtime.ts 的 buildSystemMessage)
5
+ * 与 stdio host(src/host/stdio.ts 的 systemMessage)。host 那份只拼了 buildBasePrompt +
6
+ * effectiveSystemPrompt,漏掉 About you / Memory Index / Episode / Project graph hint / plan 段,
7
+ * 结果是「记忆开关打开、记忆库装满,工作台里的模型却从没见过它」。
8
+ *
9
+ * 段顺序是契约,不是风格:
10
+ * 1. buildBasePrompt 的静态主体在前 → 支持 prompt caching 的后端能命中前缀;
11
+ * 2. 会话级/主题级段落按 REPL 的原顺序追加;
12
+ * 3. plan 段插在 About you 与 Memory Index 之间(与 REPL 一致,改动会让两端口径分叉)。
13
+ *
14
+ * 本模块刻意不 import 任何 UI 模块:host、REPL、以及将来的 GUI 都能安全调用。
15
+ */
16
+ import { buildBasePrompt, getPlanModeSuffix, isMemoryEnabled } from '../config/index.js';
17
+ import { effectiveSystemPrompt } from '../skills/index.js';
18
+ import { buildAboutYouSection, buildEpisodeSection, buildMemoryIndexSection, buildProjectGraphHint, } from '../memory/index.js';
19
+ /** base + About you + (plan) + Memory Index + Episode + Project graph hint + Skills 段。 */
20
+ export function buildSystemMessage(options = {}) {
21
+ const memoryOn = options.memoryEnabled ?? isMemoryEnabled();
22
+ const base = options.sessionId ? buildBasePrompt(options.sessionId) : buildBasePrompt();
23
+ return (effectiveSystemPrompt(base) +
24
+ buildAboutYouSection(memoryOn) +
25
+ (options.planMode ? getPlanModeSuffix() : '') +
26
+ buildMemoryIndexSection(memoryOn) +
27
+ // R6.3:情节走独立小节(不进 Memory Index / 不进 About you,理由见 memory/episodic.ts)。
28
+ buildEpisodeSection(memoryOn) +
29
+ buildProjectGraphHint(memoryOn));
30
+ }
@@ -15,7 +15,6 @@ import { config } from '../../config/index.js';
15
15
  import { updateConfigKey } from '../../config/file.js';
16
16
  import { promptThemePicker } from '../../ui/prompt.js';
17
17
  import { themeDescription } from '../commands.js';
18
- import { renderHistory } from '../message-format.js';
19
18
  import { unhandled, next } from './types.js';
20
19
  export const appearanceCommands = [
21
20
  async (ctx) => {
@@ -57,7 +56,7 @@ export const appearanceCommands = [
57
56
  ctx.refreshStatusBase(ctx.history);
58
57
  layout.clearContent();
59
58
  if (ctx.history.some((m) => m.role === 'user')) {
60
- renderHistory(ctx.history);
59
+ ctx.renderTranscript();
61
60
  }
62
61
  else {
63
62
  layout.writeBanner(bannerLines(ctx.banner()));
@@ -15,6 +15,7 @@ import { t } from '../../i18n/index.js';
15
15
  import { appendCurrentSessionRuntimeEvent, hashTraceValue } from '../../session/index.js';
16
16
  import { startRunningListener, stopRunningListener } from '../running-input.js';
17
17
  import { unhandled, next } from './types.js';
18
+ import { createTerminalTranscript } from '../../session/terminal-transcript.js';
18
19
  export const compactCommands = [
19
20
  async (ctx) => {
20
21
  const { line } = ctx;
@@ -35,6 +36,7 @@ export const compactCommands = [
35
36
  // 走调度器路径:与自动每步压缩完全一致——先跑零成本清理(cold tools 优先),最后才 LLM 摘要。
36
37
  // focus 透传到 compact_history action 的 LLM 摘要 prompt。
37
38
  // 返回 SchedulerRunLog 给 UI 显示决策;退化路径(开关关时)在 manualCompact 内部走 compactHistory。
39
+ const beforeReplay = createTerminalTranscript(ctx.history).base;
38
40
  const log = await (async () => {
39
41
  const signal = startRunningListener(t('running.compacting'));
40
42
  try {
@@ -53,6 +55,8 @@ export const compactCommands = [
53
55
  });
54
56
  if (!log)
55
57
  return next();
58
+ if (log.historyMutation !== 'none')
59
+ ctx.recordCompaction(beforeReplay);
56
60
  const d = log.compactDetail;
57
61
  appendCurrentSessionRuntimeEvent('compact', {
58
62
  source: 'manual',
@@ -17,10 +17,14 @@ import { readFileSync } from 'node:fs';
17
17
  import * as layout from '../../ui/layout.js';
18
18
  import { ui } from '../../ui/theme.js';
19
19
  import { getActiveRollbackStore } from '../../rollback/index.js';
20
+ // 实现已下沉到 src/changeset/unified-diff.ts(叶模块,无 ui/fs 依赖):
21
+ // host 的 `changes` 命令也要同一份 diff,而 host 进程不该为了 diff 拉进 layout。
22
+ import { unifiedFileDiff } from '../../changeset/unified-diff.js';
20
23
  import { unhandled, next } from './types.js';
24
+ // 保留旧的导出面(tests/ui/diff-commands.test.ts 直接从本模块取它)。
25
+ export { unifiedFileDiff };
21
26
  const MAX_DIFF_LINES = 400; // 单文件输出上限:防止把万行生成文件刷满内容区
22
27
  const MAX_FILES = 60; // 单次命令最多渲染文件数(超出提示收窄)
23
- const CONTEXT = 3; // hunk 上下文行数
24
28
  /** 快照 before 内容 → 文本(null → 无内容/不可用;base64 解码失败按 null)。 */
25
29
  function snapshotText(snapshot) {
26
30
  if (snapshot.before === null)
@@ -39,51 +43,6 @@ function snapshotText(snapshot) {
39
43
  function diffable(snapshot) {
40
44
  return snapshot.kind === 'file' && snapshot.contentUnavailable !== true;
41
45
  }
42
- /** 按行求公共前缀/后缀长度(与 lineDelta 同思路,但这里要保留行号做 hunk)。 */
43
- function hunkBoundaries(before, after) {
44
- let head = 0;
45
- while (head < before.length && head < after.length && before[head] === after[head])
46
- head++;
47
- let tail = 0;
48
- while (tail < before.length - head &&
49
- tail < after.length - head &&
50
- before[before.length - 1 - tail] === after[after.length - 1 - tail])
51
- tail++;
52
- return { head, tail };
53
- }
54
- /**
55
- * 行级 unified diff 单文件段(纯文本,颜色渲染层加)。
56
- * 策略:前后缀等行消除后,中间区整段输出为「先删后加」的单 hunk。对单文件一次
57
- * 编辑(agent 编辑的绝大多数形态:改一处/几处)等价于标准 diff;全文重写时输出
58
- * 体积与正确 diff 同量级,只是 hunk 划分更粗。无变化返回 ''(指纹差异但文本相同)。
59
- */
60
- export function unifiedFileDiff(pathRel, beforeText, afterText) {
61
- const before = beforeText === null ? [] : beforeText.split('\n');
62
- const after = afterText === null ? [] : afterText.split('\n');
63
- const { head, tail } = hunkBoundaries(before, after);
64
- const midBefore = before.slice(head, before.length - tail);
65
- const midAfter = after.slice(head, after.length - tail);
66
- if (midBefore.length === 0 && midAfter.length === 0)
67
- return '';
68
- const contextStart = Math.max(0, head - CONTEXT);
69
- const tailStartBefore = before.length - tail;
70
- const tailStartAfter = after.length - tail;
71
- const contextEndBefore = Math.min(before.length, tailStartBefore + CONTEXT);
72
- const contextEndAfter = Math.min(after.length, tailStartAfter + CONTEXT);
73
- const lines = [];
74
- lines.push(`--- a/${pathRel}`);
75
- lines.push(`+++ b/${pathRel}`);
76
- lines.push(`@@ -${contextStart + 1},${contextEndBefore - contextStart} +${contextStart + 1},${contextEndAfter - contextStart} @@`);
77
- for (let i = contextStart; i < head; i++)
78
- lines.push(` ${before[i]}`);
79
- for (const line of midBefore)
80
- lines.push(`-${line}`);
81
- for (const line of midAfter)
82
- lines.push(`+${line}`);
83
- for (let i = tailStartBefore; i < contextEndBefore; i++)
84
- lines.push(` ${before[i]}`);
85
- return lines.join('\n');
86
- }
87
46
  /** 渲染一条 diff 行:加绿/删红/hunk 头青/上下文 dim。 */
88
47
  function writeDiffLine(line) {
89
48
  if (line.startsWith('+'))
@@ -10,13 +10,15 @@ import * as layout from '../../ui/layout.js';
10
10
  import { ui } from '../../ui/theme.js';
11
11
  import { isMemoryEnabled } from '../../config/index.js';
12
12
  import { getAgentMode } from '../../agent/mode.js';
13
- import { kickoffReflection, snapshotTranscript, loadAll, loadAllGraph, loadStalenessMap, listInternalizedProfile, listProfileCandidates, promoteEdge, invalidateEdge, writeMemoryHealth, formatMemoryHealth, flushProactiveStats, adoptionEvents, adoptionStats, pruneAdoptionLedger,
13
+ import { kickoffReflection, snapshotTranscript, loadAll, loadAllGraph, loadStalenessMap, listInternalizedProfile, listProfileCandidates, promoteEdge, invalidateEdge, writeMemoryHealth, formatMemoryHealth, flushProactiveStats, pendingCandidateCount, adoptionEvents, adoptionStats, flushAdoptionSuppressions, pruneAdoptionLedger,
14
14
  // R8 用户主权面
15
15
  purgeEntries, buildPack, writePack, importPackFile, memoryWriteBlockedMessage, setMemoryWritesPaused, isMemoryWritesPaused, appendAudit, readAudit,
16
16
  // R9.1 冷启动播种
17
17
  collectSeedCandidates, applySeedCandidates,
18
18
  // R2.6 存量锚点回填
19
- collectAnchorCandidates, applyAnchorCandidates, } from '../../memory/index.js';
19
+ collectAnchorCandidates, applyAnchorCandidates,
20
+ // R2.7 锚点重定位
21
+ collectRelocationProposals, applyRelocations, } from '../../memory/index.js';
20
22
  import { evaluateAnchors, evaluateAnchor, anchorLabel } from '../../memory/anchor.js';
21
23
  import { unhandled, next } from './types.js';
22
24
  /** /profile 改动画像后,让 About you 段(history[0])立刻反映,不用等重启。 */
@@ -255,6 +257,12 @@ export const memoryCommands = [
255
257
  }
256
258
  if (active.length === 0)
257
259
  layout.contentWrite(`${ui.dim}(无 active 记忆;用 memory_save 存,或 /init 生成 AGENTS.md)${ui.reset}\n`);
260
+ // R13:压缩候选是"待裁决原料",积压时用户看到的是记忆库正常而通道在漏料。
261
+ // 只在真有积压时出一行——队列空是常态,常态不占屏幕。
262
+ const pendingCandidates = pendingCandidateCount();
263
+ if (pendingCandidates > 0) {
264
+ layout.contentWrite(`${ui.dim}(压缩候选 ${pendingCandidates} 条待裁决:运行 /reflect 让既有反思调用处理)${ui.reset}\n`);
265
+ }
258
266
  // R8.3:暂停状态必须在概览里可见——否则用户以为在记,其实一条都没落盘。
259
267
  if (isMemoryWritesPaused()) {
260
268
  layout.contentWrite(`${ui.dim}(写入已暂停:本会话不再新增/修改记忆;用 /memory pause off 恢复)${ui.reset}\n`);
@@ -269,10 +277,15 @@ export const memoryCommands = [
269
277
  layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory adoption 无效。用 /memory_switch 打开)${ui.reset}\n`);
270
278
  return next();
271
279
  }
280
+ // 抑制计数在内存聚合(每工具调用一次"记录"会把账本撑到几十 MB),看之前先落盘。
281
+ flushAdoptionSuppressions();
272
282
  pruneAdoptionLedger();
273
283
  const id = ctx.line.slice('/memory adoption'.length).trim();
274
284
  const stats = adoptionStats();
275
- layout.contentWrite(`${ui.dim}送达 ${stats.delivered} · 已评估 ${stats.evaluated}(采纳 ${stats.adopted} / 无关 ${stats.notApplicable} / 不明 ${stats.unclear}) · 待评估 ${stats.pending} · 已抑制 ${stats.suppressed}${ui.reset}\n`);
285
+ // 「本会话待评估」与「已结束会话滞留」必须分开写:前者能靠 /reflect 消化,
286
+ // 后者永远不会再降(只有 90 天归档会带走),混成一个数会让人反复去跑无效动作。
287
+ layout.contentWrite(`${ui.dim}送达 ${stats.delivered} · 已评估 ${stats.evaluated}(采纳 ${stats.adopted} / 无关 ${stats.notApplicable} / 不明 ${stats.unclear}) · 本会话待评估 ${stats.pending}` +
288
+ `${stats.stranded ? ` · 已结束会话滞留 ${stats.stranded}(不会再降)` : ''} · 已抑制 ${stats.suppressed}${ui.reset}\n`);
276
289
  const channels = Object.entries(stats.byChannel)
277
290
  .filter(([, count]) => count > 0)
278
291
  .map(([channel, count]) => `${channel} ${count}`)
@@ -304,6 +317,7 @@ export const memoryCommands = [
304
317
  return next();
305
318
  }
306
319
  flushProactiveStats();
320
+ flushAdoptionSuppressions();
307
321
  pruneAdoptionLedger();
308
322
  const health = writeMemoryHealth(true);
309
323
  if (!health) {
@@ -565,9 +579,68 @@ export const memoryCommands = [
565
579
  `${ui.dim}锚点写入后,代码一改就会在这些条目上显示 STALE-CODE)${ui.reset}\n`);
566
580
  return next();
567
581
  }
582
+ // ── R2.7 锚点重定位(文件搬家)─────────────────────────────────────────
583
+ // 独立分支放在序号解析之前:`relocate` 不是序号,落到下面会被当成非法输入打用法。
584
+ if (arg === 'relocate' || arg.startsWith('relocate ')) {
585
+ const sub = arg.slice('relocate'.length).trim();
586
+ const rel = collectRelocationProposals(cwd);
587
+ if (!sub) {
588
+ if (rel.proposals.length === 0) {
589
+ layout.contentWrite(`${ui.dim}(没有可重定位的锚点:${rel.weak.length} 条只有同名文件、${rel.ambiguous.length} 条同名多个、` +
590
+ `${rel.unresolved.length} 条连同名文件都没有)${ui.reset}\n`);
591
+ for (const w of rel.weak) {
592
+ layout.contentWrite(` ${ui.dim}${w.id}${ui.reset} ${ui.dim}${w.from} → ${w.candidate}(同名但父目录不符,需人工判断)${ui.reset}\n`);
593
+ }
594
+ return next();
595
+ }
596
+ layout.contentWrite(`${ui.accent}可为 ${rel.proposals.length} 个失效锚点重定位${ui.reset}` +
597
+ `${ui.dim}(同名文件唯一且旧父目录名仍在新路径里;扫过 ${rel.files} 个文件${rel.truncated ? ',已达上限' : ''})${ui.reset}\n`);
598
+ for (const p of rel.proposals) {
599
+ layout.contentWrite(` ${ui.accent}${p.index}${ui.reset} ${ui.dim}${p.id}${ui.reset}\n`);
600
+ layout.contentWrite(` ${ui.dim}${p.from} → ${p.to}${p.symbol ? `#${p.symbol}` : ''}${ui.reset}\n`);
601
+ }
602
+ if (rel.weak.length > 0) {
603
+ layout.contentWrite(` ${ui.dim}另有 ${rel.weak.length} 条只有同名文件、父目录不符,未提议${ui.reset}\n`);
604
+ }
605
+ if (rel.ambiguous.length > 0) {
606
+ layout.contentWrite(` ${ui.dim}另有 ${rel.ambiguous.length} 条同名文件多个,需人工判断${ui.reset}\n`);
607
+ }
608
+ if (rel.unresolved.length > 0) {
609
+ layout.contentWrite(` ${ui.dim}另有 ${rel.unresolved.length} 条工作区里找不到同名文件(多半是真删了,不是搬家)${ui.reset}\n`);
610
+ }
611
+ layout.contentWrite(`${ui.dim}/memory anchor relocate <序号>[,<序号>…] 写入 · all 全部写入${ui.reset}` +
612
+ `${ui.dim}(只换路径;其它锚点与内容一律不动)${ui.reset}\n`);
613
+ return next();
614
+ }
615
+ const relPicks = sub === 'all' ? 'all' : parseSeedPicks(sub);
616
+ if (relPicks !== 'all' && relPicks.length === 0) {
617
+ layout.contentWrite(`${ui.dim}用法:/memory anchor relocate · /memory anchor relocate all · /memory anchor relocate 1,2${ui.reset}\n`);
618
+ return next();
619
+ }
620
+ if (rel.proposals.length === 0) {
621
+ layout.contentWrite(`${ui.dim}(没有可重定位的锚点;先跑 /memory anchor relocate 看扫描结果)${ui.reset}\n`);
622
+ return next();
623
+ }
624
+ if (relPicks !== 'all') {
625
+ const bad = relPicks.filter((n) => !rel.proposals.some((p) => p.index === n));
626
+ if (bad.length > 0) {
627
+ layout.contentWrite(`${ui.dim}(序号 ${bad.join(',')} 超出范围:只有 ${rel.proposals.length} 条;先跑 /memory anchor relocate 看列表)${ui.reset}\n`);
628
+ return next();
629
+ }
630
+ }
631
+ const rr = applyRelocations(rel.proposals, relPicks, cwd);
632
+ layout.contentWrite(`${ui.dim}(重定位完成:写入 ${rr.saved.length} · 失败 ${rr.failed.length})${ui.reset}\n`);
633
+ for (const s of rr.saved)
634
+ layout.contentWrite(` ${ui.dim}+ ${s.id} ${s.from} → ${s.to}${ui.reset}\n`);
635
+ // 失败必须逐条说清:静默跳过会让人以为锚点已经修好了。
636
+ for (const f of rr.failed) {
637
+ layout.contentWrite(` ${ui.yellow}! ${f.id}${ui.reset}${ui.dim}(${f.from}:${f.reason};未写入)${ui.reset}\n`);
638
+ }
639
+ return next();
640
+ }
568
641
  const picks = arg === 'all' ? 'all' : parseSeedPicks(arg);
569
642
  if (picks !== 'all' && picks.length === 0) {
570
- layout.contentWrite(`${ui.dim}用法:/memory anchor · /memory anchor all · /memory anchor 1,3,5${ui.reset}\n`);
643
+ layout.contentWrite(`${ui.dim}用法:/memory anchor · /memory anchor all · /memory anchor 1,3,5 · /memory anchor relocate${ui.reset}\n`);
571
644
  return next();
572
645
  }
573
646
  if (scan.candidates.length === 0) {
@@ -12,7 +12,6 @@ import { writeConfigKeys } from '../../config/file.js';
12
12
  import { savePreset, setActivePresetName } from '../../config/presets.js';
13
13
  import { reconfigureClient } from '../../llm/index.js';
14
14
  import { promptIntervention } from '../../ui/intervention.js';
15
- import { renderHistory } from '../message-format.js';
16
15
  import { refreshCatalog } from '../../models/catalog.js';
17
16
  import { buildPreset, defaultPresetName, preferredKeyEnvName, resolveApiKey } from '../../models/map-preset.js';
18
17
  /** 应用预设到 config + 落 config 文件 + 重建 client + 重显。 */
@@ -26,7 +25,8 @@ export function applyPresetConfig(ctx, p) {
26
25
  // 预设带值用值;不带显式清除(否则旧 MAX_TOKENS 残留会盖过新预设)。
27
26
  maxTokens: p.maxTokens ?? null,
28
27
  anthropicPromptCache: p.anthropicPromptCache,
29
- ...(p.reasoningEffort ? { reasoningEffort: p.reasoningEffort } : {}),
28
+ // 预设缺省必须显式回 auto,不能残留上一个模型或全局设置的高档思考。
29
+ reasoningEffort: p.reasoningEffort ?? 'auto',
30
30
  });
31
31
  writeConfigKeys({
32
32
  LLM_PROVIDER: p.provider,
@@ -35,6 +35,7 @@ export function applyPresetConfig(ctx, p) {
35
35
  LLM_MODEL: p.model,
36
36
  CONTEXT_WINDOW_TOKENS: String(p.contextWindow),
37
37
  MAX_TOKENS: p.maxTokens ? String(p.maxTokens) : null,
38
+ REASONING_EFFORT: p.reasoningEffort ?? 'auto',
38
39
  ANTHROPIC_PROMPT_CACHE: p.anthropicPromptCache ? 'true' : 'false',
39
40
  });
40
41
  // 关键不变量:应用预设即激活——必须同步 .active 指针。否则重启时旧激活预设的优先级
@@ -49,7 +50,7 @@ export function applyPresetConfig(ctx, p) {
49
50
  ctx.refreshStatusBase(ctx.history);
50
51
  layout.clearContent();
51
52
  if (ctx.history.some((m) => m.role === 'user'))
52
- renderHistory(ctx.history);
53
+ ctx.renderTranscript();
53
54
  else
54
55
  layout.writeBanner(bannerLines(ctx.banner()));
55
56
  }
@@ -21,7 +21,6 @@ import { deletePreset, getPreset, isValidPresetName, listPresets, savePreset, se
21
21
  import { reconfigureClient } from '../../llm/index.js';
22
22
  import { recognizesReasoning } from '../../llm/reasoning.js';
23
23
  import { promptIntervention } from '../../ui/intervention.js';
24
- import { renderHistory } from '../message-format.js';
25
24
  import { MODEL_PRESETS, maskKey } from '../commands.js';
26
25
  import { unhandled, next } from './types.js';
27
26
  /** 决定自动存的预设名:协议、缓存配置和连接四元组都一致时不重复存。 */
@@ -101,7 +100,7 @@ export const modelCommands = [
101
100
  ctx.refreshStatusBase(history);
102
101
  layout.clearContent();
103
102
  if (history.some((m) => m.role === 'user')) {
104
- renderHistory(history);
103
+ ctx.renderTranscript();
105
104
  }
106
105
  else {
107
106
  layout.writeBanner(bannerLines(ctx.banner()));
@@ -454,7 +453,7 @@ export const modelCommands = [
454
453
  ctx.refreshStatusBase(history);
455
454
  layout.clearContent();
456
455
  if (history.some((m) => m.role === 'user')) {
457
- renderHistory(history);
456
+ ctx.renderTranscript();
458
457
  }
459
458
  else {
460
459
  layout.writeBanner(bannerLines(ctx.banner()));
@@ -138,7 +138,7 @@ export function queryHistoryFromMessages(messages) {
138
138
  * 用 batch.writeSummaryOnly 出单行摘要(与实时 runAgent 同一渲染器,UI 一致)。
139
139
  * 回放默认全折叠;用户可鼠标点击摘要行展开(由 BatchRenderer 接管,见 ui/batch.ts)。
140
140
  */
141
- export function renderHistory(history) {
141
+ export function renderHistory(history, useLiveAttachments = true) {
142
142
  const idToEntry = new Map();
143
143
  const idToArgs = new Map(); // tool_call id → 原始参数 JSON,供重建 mutation diff
144
144
  // 普通工具可跨 assistant 步聚合;mutation 各自占一个 group,并切断前后普通工具。
@@ -158,18 +158,18 @@ export function renderHistory(history) {
158
158
  for (let idx = 0; idx < history.length; idx++) {
159
159
  const m = history[idx];
160
160
  if (m.role === 'system') {
161
- // compact 摘要是被压缩掉的助手回复/工具过程的唯一留存:回放时显示出来(history[0] 的系统提示仍跳过)。
161
+ // 旧会话有摘要时显示摘要正文;展示记录中的无正文标记只提示模型做过压缩。
162
162
  const body = textOf(m.content);
163
163
  if (idx > 0 && body.startsWith(SUMMARY_MARKER)) {
164
164
  flushBatch();
165
165
  layout.normalizeMutationBoundary();
166
- layout.contentWrite(`${ui.dim}${t('repl.compactedNotice')}${ui.reset}\n\n`);
167
166
  const text = body.slice(SUMMARY_MARKER.length).trim();
167
+ layout.contentWrite(`${ui.dim}${t(text ? 'repl.compactedNotice' : 'repl.modelCompacted')}${ui.reset}\n\n`);
168
168
  if (text.length > SUMMARY_REPLAY_MAX_CHARS) {
169
169
  layout.contentWriteMdOnce(text.slice(0, SUMMARY_REPLAY_MAX_CHARS));
170
170
  layout.contentWrite(`${ui.dim}${t('repl.compactedTruncated', { total: text.length, shown: SUMMARY_REPLAY_MAX_CHARS })}${ui.reset}\n`);
171
171
  }
172
- else {
172
+ else if (text) {
173
173
  layout.contentWriteMdOnce(text);
174
174
  }
175
175
  layout.normalizeMutationBoundary();
@@ -183,7 +183,7 @@ export function renderHistory(history) {
183
183
  layout.normalizeInputBoundary();
184
184
  const lines = textOf(m.content).split('\n');
185
185
  layout.contentWrite(formatUserMessage(lines));
186
- const atts = messageAttachments.get(idx);
186
+ const atts = useLiveAttachments ? messageAttachments.get(idx) : undefined;
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`);
@@ -211,7 +211,8 @@ export function renderHistory(history) {
211
211
  if (p && typeof p === 'object' && p.type === 'image_url') {
212
212
  const url = p.image_url?.url ?? '';
213
213
  const mime = url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image';
214
- layout.contentWrite(` ${ui.dim}📷 ${mime}${ui.reset}\n`);
214
+ const name = p.name;
215
+ layout.contentWrite(` ${ui.dim}📷 ${typeof name === 'string' && name ? name : mime}${ui.reset}\n`);
215
216
  fallbackChips++;
216
217
  }
217
218
  }