mocode-ai 1.10.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,7 +17,6 @@ import { t } from '../i18n/index.js';
17
17
  import { isToolErrorOutput } from '../tools/result.js';
18
18
  import { appendCurrentSessionTraceEvent, capToolResultForHistory } from '../session/index.js';
19
19
  import { buildTurnRecallSection, isTurnRecallEnabled } from '../memory/turn-recall.js';
20
- import { memoryTailChangedIds } from '../memory/tail.js';
21
20
  import { createHandoffStripper, handoffDisplaySuppressed } from '../ui/handoff-block.js';
22
21
  /** 当前 turn 的 batch id(runAgent 内闭包变量;一条 turn 一轮 tool batch 结束即清空)。 */
23
22
  let currentBatchId = null;
@@ -539,7 +538,7 @@ runtimeOrContext = defaultRuntime, drainUserMessages, transcript) {
539
538
  // ① runAgent 是 TUI 组合根,只有真实用户轮会走到;runAgentCore 被全部 agent 单测
540
539
  // 直接调用,在那儿读记忆库会让测试读到本机真实记忆、失去隔离性;
541
540
  // ② spawn 走 runtime.run 不经过这里,子 agent 天然零注入。
542
- // 排除 memoryTailChangedIds():那批条目由 R17 尾注播报,同一轮不应讲两遍。
541
+ // R17 尾注的正文和排除集来自同一份快照。
543
542
  const userText = Array.isArray(userInput)
544
543
  ? userInput
545
544
  .filter((part) => part.type === 'text')
@@ -547,7 +546,9 @@ runtimeOrContext = defaultRuntime, drainUserMessages, transcript) {
547
546
  .join(' ')
548
547
  : userInput;
549
548
  const memoryRecall = isMemoryEnabled() && isTurnRecallEnabled()
550
- ? buildTurnRecallSection(userText, { excludeIds: memoryTailChangedIds() })
549
+ ? buildTurnRecallSection(userText, {
550
+ excludeIds: typeof memoryTail === 'string' ? undefined : memoryTail?.shownIds,
551
+ })
551
552
  : '';
552
553
  try {
553
554
  result = await runtime.run({
@@ -561,7 +562,7 @@ runtimeOrContext = defaultRuntime, drainUserMessages, transcript) {
561
562
  hooks: combinedHooks,
562
563
  toolPolicy,
563
564
  initialToolRoute,
564
- memoryTail,
565
+ memoryTail: typeof memoryTail === 'string' ? memoryTail : memoryTail?.text,
565
566
  memoryRecall,
566
567
  onTraceEvent: appendCurrentSessionTraceEvent,
567
568
  });
@@ -3,6 +3,7 @@ import { imageTurnAgingEnabled, visionBatch, visionKeep } from '../config/index.
3
3
  import { estimateRequestBytes, learnRequestByteLimit, requestByteLimit } from '../context/request-limit.js';
4
4
  import { createImageDescriber, relieveRequestBytes } from './request-governor.js';
5
5
  import { countOversizedImages } from '../context/vision-window.js';
6
+ import { compactOverlappingReads } from '../context/overlapping-reads.js';
6
7
  import { getActiveSessionStore } from '../session/store.js';
7
8
  import { getCurrentSessionId } from '../session/state.js';
8
9
  import { appendGlobalUsage } from '../session/global-usage.js';
@@ -187,26 +188,16 @@ export async function runModelTurn(input) {
187
188
  const remainingSteps = maxSteps - step;
188
189
  const ephemeralReminder = [
189
190
  runPolicy.reminder,
190
- // 正文纪律:与 step 0 的 Opening analysis 互斥——两段永远不同框,不再需要白名单交叉引用。
191
- // 原先这半句只挂在 step 0 的 Opening analysis 里,而本段是临时拼进本次请求、不写回 history
192
- // 的(见下方 return),于是从每个用户轮的第 2 步起就彻底消失——长任务后半程等于裸奔
193
- // (实测:同一结论换个措辞每步复述一遍,屏幕上像卡死循环)。
194
- // step 0 由 Opening analysis 独自承担:那里既没有工具结果可复述,也没有"已说过的观点",
195
- // 而"能直接答就直接答"的授权已写在 Answer-first 里,本段三条约束在 step 0 均无对象。
196
- // 子 agent 静默执行、不写屏,沿用 suppressOpeningAnalysis 一并免注入。
191
+ // 主 agent 在后续请求中就近约束工具期间的正文。首轮与引导开场由各自的动态段负责。
192
+ // 子 agent 由委派提示约束静默,本段随 suppressOpeningAnalysis 跳过。
197
193
  !opts.suppressOpeningAnalysis && step > 0 && !input.opening
198
194
  ? '## Silent work\n' +
199
- // 禁令范围收在「调用之间」,而不是「不要宣布你要做什么」:后者与 step 0 的
200
- // Opening analysis(要求说明打算怎么入手)字面冲突,只能靠下面的白名单化解,
201
- // 模型得读完清单才解开。开场分析发生在首次工具调用之前,天然不在本禁令范围内。
202
- 'Prefer doing over narrating. Do not narrate between tool calls: no sentence announcing ' +
203
- 'the next call, and no sentence restating what a result means — one such sentence per ' +
204
- 'call is noise, and repeated variants of ' +
205
- 'the same conclusion read to the user as a stuck loop. If something genuinely must be said ' +
206
- 'mid-task (a blocking decision, or a finding that changes what happens next), say it in one ' +
207
- 'short sentence and keep going. Never repeat a point already made in this turn. Text is for: ' +
208
- "direct answers to the user's questions, blocking questions, " +
209
- 'findings that change the next action, and the final report.'
195
+ 'When continuing independently with tools, emit only tool calls. ' +
196
+ 'Handle findings, recoverable errors, and verification silently. ' +
197
+ 'If you need user input to proceed, ask one concise question. ' +
198
+ 'Use `ask_human` when available, or ask in a text-only reply and wait. ' +
199
+ 'Answer direct questions and save material findings for the final report. ' +
200
+ 'Never repeat a point already made in this turn.'
210
201
  : '',
211
202
  // 仅 step 0:就近重申 Answer-first,并保留「开场一句」这条祈使要求。
212
203
  // 859b974 曾把它改写成条件句(only when ... needs a user decision or complex),
@@ -218,7 +209,9 @@ export async function runModelTurn(input) {
218
209
  'Before your first tool call in every user-facing turn, you MUST output exactly one short visible sentence ' +
219
210
  'telling the user what you will check or change first and what it will help you establish. ' +
220
211
  'Use plain language and put the sentence first in the SAME assistant response as the tool calls. ' +
221
- 'If no tools are needed, answer directly. After this opening, work silently.'
212
+ 'If no tools are needed, answer directly. ' +
213
+ 'If the task already warrants a new plan and `plan_update` is available, make it your first tool call. ' +
214
+ 'After this opening, work silently.'
222
215
  : '',
223
216
  input.opening === 'steering'
224
217
  ? '## Steering opening\n' +
@@ -276,7 +269,8 @@ export async function runModelTurn(input) {
276
269
  // 放在这里统一更新:首次请求与 overflow 重建都会经过,UI 不会拿旧一段继续外推。
277
270
  runtimeContextState.ephemeralText = ephemeralReminder || undefined;
278
271
  onContextUpdate?.();
279
- return ephemeralReminder ? [...history, { role: 'system', content: ephemeralReminder }] : history;
272
+ const request = compactOverlappingReads(history);
273
+ return ephemeralReminder ? [...request, { role: 'system', content: ephemeralReminder }] : request;
280
274
  };
281
275
  let requestHistory = buildRequestHistory();
282
276
  // 每次真正发请求前刷新:overflow 去图/压缩会替换 requestHistory,锚点不能钉在首次尝试上。
@@ -5,6 +5,7 @@
5
5
  // 与 index.ts 的关系:index.ts 的 runAgent = runAgentCore + TUI hooks 薄封装(行为不变)。
6
6
  // spawn.ts 的 spawnAgent = runAgentCore + 静默 hooks(子 agent)。
7
7
  import { estimateTokens } from '../llm/index.js';
8
+ import { withReadFileBatch } from '../tools/builtins/read-file.js';
8
9
  import { validateToolArguments } from '../tools/validation.js';
9
10
  import { getPlanDisabledTools, getRuntimeDisabledTools, getSkillRuntimeDisabledTools } from '../tools/constants.js';
10
11
  import { isMemoryEnabled } from '../config/index.js';
@@ -519,16 +520,18 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
519
520
  const eligibleReadonly = otherIndexes.filter((index) => isParallelTool(calls[index].name, ctx.toolRuntime) && !isToolDeniedForStep(calls[index].name));
520
521
  if (eligibleReadonly.length > 0) {
521
522
  hooks.onToolStart?.(calls[eligibleReadonly[0]].name);
522
- for (const index of eligibleReadonly) {
523
- startedReadonly[index] = runToolWithProactive(calls[index].name, calls[index].arguments, signal, {
524
- callId: calls[index].id,
525
- onOutput: (chunk) => hooks.onToolOutput?.(calls[index], chunk),
526
- allowedToolNames: currentAllowedToolNames(),
527
- delegation: delegationForOrchestrator(),
528
- readDedup,
529
- ...(result.finishReason ? { finishReason: result.finishReason } : {}),
530
- });
531
- }
523
+ withReadFileBatch(() => {
524
+ for (const index of eligibleReadonly) {
525
+ startedReadonly[index] = runToolWithProactive(calls[index].name, calls[index].arguments, signal, {
526
+ callId: calls[index].id,
527
+ onOutput: (chunk) => hooks.onToolOutput?.(calls[index], chunk),
528
+ allowedToolNames: currentAllowedToolNames(),
529
+ delegation: delegationForOrchestrator(),
530
+ readDedup,
531
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
532
+ });
533
+ }
534
+ });
532
535
  }
533
536
  const lastReadonlyIndex = eligibleReadonly.length > 0 ? eligibleReadonly[eligibleReadonly.length - 1] : -1;
534
537
  for (let index = 0; index < calls.length; index++) {
@@ -692,14 +695,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
692
695
  for (const tc of batch)
693
696
  hooks.onToolHeader?.(tc);
694
697
  hooks.onToolStart?.(batch[0].name);
695
- const started = batch.map((tc) => runToolWithProactive(tc.name, tc.arguments, signal, {
698
+ const started = withReadFileBatch(() => batch.map((tc) => runToolWithProactive(tc.name, tc.arguments, signal, {
696
699
  callId: tc.id,
697
700
  onOutput: (chunk) => hooks.onToolOutput?.(tc, chunk),
698
701
  allowedToolNames: currentAllowedToolNames(),
699
702
  delegation: delegationForOrchestrator(),
700
703
  readDedup,
701
704
  ...(result.finishReason ? { finishReason: result.finishReason } : {}),
702
- }));
705
+ })));
703
706
  // 完成即发:usage/onToolOutcome/trace 在各 outcome 落地瞬间发出(1s 的
704
707
  // grep 不再被 60s 的 web_fetch 卡住可见性);history 回灌严格按原序。
705
708
  await Promise.all(started.map(async (pending, k) => {
@@ -24,12 +24,14 @@ import { summarizeToolCall, summarizeToolResult, truncateDisplay } from '../ui/r
24
24
  import { t } from '../i18n/index.js';
25
25
  import { createContextState } from '../session/compact.js';
26
26
  import { defaultAgentRuntimeContext, getActiveAgentRuntimeContext, } from './runtime-context.js';
27
+ const SUBAGENT_SILENT_WORK = 'Work silently until your final reply.';
27
28
  /** 子 agent 系统提示后缀(仅 legacy 直接调用路径用;共享前缀路径的系统提示直接复用父 agent)。 */
28
29
  const SUBAGENT_SUFFIX = `
29
30
 
30
31
  ## ⛯ SUB-AGENT MODE (you are a sub-agent)
31
32
  You are a sub-agent spawned by the main agent to handle a delegated sub-task, with the same tools and full capabilities as the main agent.
32
33
  - Focus on the assigned sub-task and see it through to completion.
34
+ - ${SUBAGENT_SILENT_WORK}
33
35
  - When done, your final text reply is returned to the main agent as the result — concise and actionable: what you did, key findings, files changed, blockers.`;
34
36
  const SUBAGENT_ROLE = `## Sub-agent execution
35
37
  You are executing one delegated sub-task with the same engineering standards and full capabilities as the main agent.
@@ -112,6 +114,8 @@ export async function spawnAgent(opts) {
112
114
  `Sub-task:\n${opts.prompt}`,
113
115
  [
114
116
  "You have the same tools and the same full capabilities as the main agent. Your file writes land directly in the workspace and belong to the main agent's current rollback transaction.",
117
+ // 只在新追加的委派消息里约束静默,保留父会话的缓存前缀。
118
+ SUBAGENT_SILENT_WORK,
115
119
  'Your final text reply is returned to the main agent as the result — concise and actionable: what you did, key findings, files changed, blockers.',
116
120
  ].join('\n'),
117
121
  opts.systemPromptSuffix ?? '',
@@ -6,6 +6,7 @@ import { checkPermission as defaultCheckPermission } from '../../permissions/ind
6
6
  import { jailResolve as defaultJailResolve } from '../../sandbox/index.js';
7
7
  import { summarizeToolArguments } from '../../session/index.js';
8
8
  import { getPlanDisabledTools } from '../../tools/constants.js';
9
+ import { withReadFileBatch } from '../../tools/builtins/read-file.js';
9
10
  import { defaultToolRuntime } from '../../tools/registry.js';
10
11
  import { validateToolArguments } from '../../tools/validation.js';
11
12
  import { deniedOutcome, isParallelTool, isParallelOrchestrationCall, isResourceLockedCall, parseArgs, readDiffContext, unregisteredToolOutcome, } from '../tool-helpers.js';
@@ -119,8 +120,10 @@ class LegacyCompatibleToolDispatcher {
119
120
  const eligibleReadonly = otherIndexes.filter((index) => isParallelTool(calls[index].name, toolRuntime) && !request.isDenied(calls[index].name));
120
121
  if (eligibleReadonly.length > 0) {
121
122
  request.onEvent({ type: 'start', tool: calls[eligibleReadonly[0]].name });
122
- for (const index of eligibleReadonly)
123
- startedReadonly[index] = execute(calls[index]);
123
+ withReadFileBatch(() => {
124
+ for (const index of eligibleReadonly)
125
+ startedReadonly[index] = execute(calls[index]);
126
+ });
124
127
  }
125
128
  const lastReadonlyIndex = eligibleReadonly.length > 0 ? eligibleReadonly[eligibleReadonly.length - 1] : -1;
126
129
  for (let index = 0; index < calls.length; index++) {
@@ -262,7 +265,7 @@ class LegacyCompatibleToolDispatcher {
262
265
  for (const call of batch)
263
266
  request.onEvent({ type: 'header', call });
264
267
  request.onEvent({ type: 'start', tool: batch[0].name });
265
- const started = batch.map((call) => execute(call));
268
+ const started = withReadFileBatch(() => batch.map((call) => execute(call)));
266
269
  // 完成即发:usage/host_outcome/trace_end 在各 outcome 落地瞬间发出(1s 的 grep 不再
267
270
  // 被 60s 的 run_command 卡住可见性);result(history 回灌)严格保持原序。
268
271
  await Promise.all(started.map(async (pending, offset) => {
@@ -1,6 +1,9 @@
1
1
  // Lightweight, advisory working guidance. The agent decides how much discovery and
2
2
  // validation each task needs; the framework does not enforce a completion gate.
3
- export const PLAN_USAGE_GUIDANCE = 'Use a plan for distinct deliverables, work that needs a durable handoff, or when the user requests one. Locating, editing and checking one focused change are one task.';
3
+ export const PLAN_USAGE_GUIDANCE = 'For tool-using work, call `plan_update` before broad investigation or implementation when the user requests a plan, ' +
4
+ 'the task has distinct deliverables or at least three substantive phases, crosses components with separate checks, risks context loss, or needs a durable handoff. ' +
5
+ 'If a focused check reveals that the task meets these criteria, create or update the plan before continuing. Reuse a plan that already fits the task. ' +
6
+ 'Locating, editing and checking one focused change count as one phase.';
4
7
  /**
5
8
  * 从 config.model 字符串里嗅探 model family。匹配规则尽量宽松,够用即可。
6
9
  * 未来 AHE 闭环后可以换成 config.modelFamily 字段。
@@ -175,7 +175,8 @@ export async function commitChangeSet(changeSet, signal) {
175
175
  }
176
176
  const captures = effective.map((change) => ({
177
177
  change,
178
- capture: beginPathMutation(change.absolutePath),
178
+ // dry-run 已读取原文。首次替换前仍会逐路径复核 hash,复核失败时整批不落回滚快照。
179
+ capture: beginPathMutation(change.absolutePath, change.before ?? undefined),
179
180
  }));
180
181
  const createdDirectories = new Set();
181
182
  const tempByPath = new Map();
@@ -484,9 +484,8 @@ ${buildValidationCommandsSection()}
484
484
  ${buildWorkDisciplineSection(inferModelFamily(config.model))}
485
485
 
486
486
  ## Tool policy
487
- - Opening and silent execution: the main agent starts every tool-using user turn with exactly one short visible sentence explaining what it will check or change first and why, in the SAME assistant response as the first tool calls. A new batch of live user updates gets one similar opening before the next tools. Sub-agents stay silent. After the opening, strictly no step-by-step narration (no "let me…", "让我先…", "now checking…" between calls).
488
- - Known vs unknown target: when the request already names the file (a filename or path appears in the user's message), that file is KNOWN — make read_file on it your FIRST tool call. Do NOT grep/glob beforehand to "locate" or "confirm" a file the request already identified; that burns a full model round-trip for zero new information. Search only when the target file or symbol is genuinely unknown: grep with a narrow pattern and context to inspect nearby code immediately. For a known file and symbol, read_file(path, anchor, limit) locates and reads the implementation in one call.
489
- - Edit against fresh exact text. For an unknown file and a specific symbol or literal, use grep(edit_context=true). If it returns an [edit_context ...] excerpt that covers the change, copy the exact text and pass its hash as expected_hash to edit_file without rereading. Otherwise use read_file on the exact path and narrow range. Ordinary search hits, summaries and diffs are not edit evidence.
487
+ - Read the named file first. For a local edit with a known line, use read_file with offset and about 40 lines of context. With exact target text, anchor to it or a nearby line and set a small limit. If only the declaration is known, use it as the anchor and read enough of the implementation to find the edit. Read a wider range when the task spans multiple blocks. Use narrow grep to discover unknown paths.
488
+ - Edit against fresh exact text. For an unknown file and a specific symbol or literal, use grep(edit_context=true, max_edit_candidates=3). If an [edit_context ...] excerpt covers the change, choose the path that matches the user’s intent, copy the exact text and pass that file’s hash as expected_hash to edit_file without rereading. Otherwise use read_file on the exact path and narrow range. Ordinary search hits, summaries and diffs are not edit evidence.
490
489
  - Pick the right file tool: for an EXISTING file, DEFAULT to edit_file — one old_string for a single change, replacements[] for many separate changes in one atomic call, or a line range for a big block. Do NOT overwrite an existing file with write_file just to tweak parts of it (re-sending the whole file wastes tokens and its long JSON is truncation-prone). Use write_file only to create a new file, to append (append=true needs no read_file and no hash), or to rewrite essentially the WHOLE file (a full rewrite needs the latest read_file hash). expected_hash is OPTIONAL in edit_file old_string/replacements mode, REQUIRED in line-range mode. Never write a throwaway script (tmp_patch*.cjs, fix_*.py, ...) to modify source files: scripts run outside ChangeSet tracking, so rollback and diff cannot see them.
491
490
  - Treat evidence from before compaction, session resume, an edit conflict, or an external change as stale. Reread the affected range before reusing its text or hash. In old_string mode with a fresh read_file, expected_hash is optional.
492
491
  - Emit multiple independent tool calls in ONE assistant message so they run concurrently — e.g. several read_file regions, a grep plus a glob, or several web_fetch calls. One lookup per message wastes a full model round-trip each time. Place parallel-safe calls consecutively; keep any call that depends on their results (e.g. an edit) for the next message.
@@ -0,0 +1,66 @@
1
+ const READ_HEADER = /^\[artifact source=read_file path=.+ hash=sha256:[a-f0-9]{64}\]$/;
2
+ const NUMBERED_LINE = /^ *([1-9]\d*)\t/;
3
+ const MIN_RESULT_CHARS = 4_000;
4
+ const MIN_SAVED_CHARS = 800;
5
+ /** 从实际会发出的同轮工具结果中复用原文。持久化历史和工具界面仍持有完整结果。 */
6
+ export function compactOverlappingReads(history) {
7
+ const earlierVersions = new Map();
8
+ let result = history;
9
+ for (let i = 0; i < history.length; i++) {
10
+ const message = history[i];
11
+ if (message.role === 'user')
12
+ earlierVersions.clear();
13
+ if (message.role !== 'tool' || typeof message.content !== 'string')
14
+ continue;
15
+ const content = message.content;
16
+ const headerEnd = content.indexOf('\n');
17
+ if (headerEnd < 0 || !READ_HEADER.test(content.slice(0, headerEnd)))
18
+ continue;
19
+ if (content.includes('…[已截断'))
20
+ continue;
21
+ const header = content.slice(0, headerEnd);
22
+ const previous = earlierVersions.get(header);
23
+ if (previous === undefined) {
24
+ earlierVersions.set(header, content);
25
+ continue;
26
+ }
27
+ const prior = typeof previous === 'string'
28
+ ? new Set(previous.split('\n').filter((line) => NUMBERED_LINE.test(line)))
29
+ : previous;
30
+ earlierVersions.set(header, prior);
31
+ const output = [header];
32
+ let start = 0;
33
+ let end = 0;
34
+ const flush = () => {
35
+ if (!start)
36
+ return;
37
+ output.push(`[Lines ${start}–${end} already shown above for this file version.]`);
38
+ start = 0;
39
+ };
40
+ for (const line of content.slice(headerEnd + 1).split('\n')) {
41
+ const match = NUMBERED_LINE.exec(line);
42
+ const number = Number(match?.[1]);
43
+ if (match && content.length >= MIN_RESULT_CHARS && prior.has(line)) {
44
+ if (start && number !== end + 1)
45
+ flush();
46
+ if (!start)
47
+ start = number;
48
+ end = number;
49
+ }
50
+ else {
51
+ flush();
52
+ output.push(line);
53
+ }
54
+ if (match)
55
+ prior.add(line);
56
+ }
57
+ flush();
58
+ const compacted = output.join('\n');
59
+ if (content.length - compacted.length < MIN_SAVED_CHARS)
60
+ continue;
61
+ if (result === history)
62
+ result = history.slice();
63
+ result[i] = { ...message, content: compacted };
64
+ }
65
+ return result;
66
+ }
@@ -48,7 +48,15 @@ function observationKey(call) {
48
48
  tool: 'grep',
49
49
  pattern: args.pattern,
50
50
  glob: typeof args.glob === 'string' ? args.glob : '**/*',
51
- maxPerFile: Math.min(Math.max(rawMax, 1), 50),
51
+ ...(args.mode === 'files'
52
+ ? { mode: 'files' }
53
+ : {
54
+ mode: 'matches',
55
+ maxPerFile: Math.min(Math.max(rawMax, 1), 50),
56
+ context: Math.min(Math.max(normalizedInteger(args.context, 0), 0), 10),
57
+ editContext: args.edit_context === true,
58
+ maxEditCandidates: normalizedInteger(args.max_edit_candidates, 1),
59
+ }),
52
60
  });
53
61
  }
54
62
  return null;
@@ -1,4 +1,5 @@
1
1
  import { chatTools, correctTokenEstimate, estimateMessagesTokens, estimateToolSchemaTokens, estimateTokens, } from '../llm/index.js';
2
+ import { compactOverlappingReads } from './overlapping-reads.js';
2
3
  /**
3
4
  * 与终端底栏、上下文压力线同口径:system + 对话 + 实际工具 schema + ephemeral。
4
5
  * 不能用本轮累计 input+output:后者是消耗量,不是此刻驻留的上下文。
@@ -11,13 +12,15 @@ export function measureContextUsage(history, contextWindowTokens, contextState)
11
12
  const activeTools = contextState.activeTools ?? chatTools;
12
13
  const ephemeralText = contextState.ephemeralText ?? '';
13
14
  const ephemeralRaw = ephemeralText ? estimateTokens(ephemeralText) : 0;
14
- const fullRaw = estimateMessagesTokens([...history]) + estimateToolSchemaTokens(activeTools) + ephemeralRaw;
15
+ const historyRaw = estimateMessagesTokens(compactOverlappingReads([...history]));
16
+ const schemaRaw = estimateToolSchemaTokens(activeTools);
17
+ const fullRaw = historyRaw + schemaRaw + ephemeralRaw;
15
18
  const anchor = contextState.promptAnchor;
16
- const anchorHistory = anchor ? history.slice(0, anchor.historyLen) : history;
19
+ const anchorPrefixRaw = anchor
20
+ ? estimateMessagesTokens(compactOverlappingReads(history.slice(0, anchor.historyLen)))
21
+ : 0;
17
22
  const anchorHistoryRaw = anchor
18
- ? estimateMessagesTokens([...anchorHistory]) +
19
- estimateToolSchemaTokens(activeTools) +
20
- (anchor.ephemeralText ? estimateTokens(anchor.ephemeralText) : 0)
23
+ ? anchorPrefixRaw + schemaRaw + (anchor.ephemeralText ? estimateTokens(anchor.ephemeralText) : 0)
21
24
  : 0;
22
25
  if (anchor &&
23
26
  history.length >= anchor.historyLen &&
@@ -26,7 +29,7 @@ export function measureContextUsage(history, contextWindowTokens, contextState)
26
29
  // 同长度替换/原地微压缩也不能沿用旧锚点;历史增长时只比较锚点前缀。
27
30
  Math.abs(anchorHistoryRaw - anchor.baseRaw) <= 4 &&
28
31
  fullRaw >= anchor.baseRaw - 4) {
29
- const grownRaw = estimateMessagesTokens([...history]) - estimateMessagesTokens([...anchorHistory]);
32
+ const grownRaw = historyRaw - anchorPrefixRaw;
30
33
  tokens = anchor.measuredPromptTokens + Math.max(0, grownRaw);
31
34
  // 只有完全同一请求快照才全是实测;后续新增内容仍属于估算。
32
35
  source = history.length === anchor.historyLen && fullRaw <= anchor.baseRaw + 4 ? 'measured' : 'estimated';
@@ -10,7 +10,7 @@ import { appendCurrentSessionTraceEvent, createContextState, SessionStore, } fro
10
10
  import { registerWorkspace, readWorkspaceRegistry } from '../workspace/registry.js';
11
11
  import { clearSkillActivation } from '../skills/activation.js';
12
12
  import { buildSystemMessage } from '../prompt/system-prompt.js';
13
- import { buildMemoryTailSection, buildTurnRecallSection, captureMemoryBaseline, gcMemories, initPersona, isTurnRecallEnabled, memoryTailChangedIds, } from '../memory/index.js';
13
+ import { buildMemoryTailSnapshot, buildTurnRecallSection, captureMemoryBaseline, gcMemories, initPersona, isTurnRecallEnabled, } from '../memory/index.js';
14
14
  import { ToolPolicyController } from '../tools/policy.js';
15
15
  import { routeToolGroups } from '../tools/router.js';
16
16
  // 装配官方默认工具包:registry 不再顶层 import builtins(破模块循环),host 入口须显式装配。
@@ -178,15 +178,6 @@ function setMode(command) {
178
178
  }
179
179
  emit('mode_changed', { mode: command.mode, previous }, command.id);
180
180
  }
181
- /**
182
- * R18 每轮静默召回段。开关求与的写法与 REPL 一致(src/agent/index.ts 的 runAgent):
183
- * 记忆总开关 × 召回子开关。排除 memoryTailChangedIds() —— 那批已由 R17 尾注播报。
184
- */
185
- function turnRecallFor(prompt) {
186
- if (!isMemoryEnabled() || !isTurnRecallEnabled())
187
- return '';
188
- return buildTurnRecallSection(prompt, { excludeIds: memoryTailChangedIds() });
189
- }
190
181
  function createSession() {
191
182
  const activeRuntime = runtime();
192
183
  sessionId = activeRuntime.session.create();
@@ -448,6 +439,11 @@ async function run(command) {
448
439
  planMode,
449
440
  };
450
441
  emit('tool_route', initialToolRoute, command.id);
442
+ const memoryEnabled = isMemoryEnabled();
443
+ const memoryTail = buildMemoryTailSnapshot(memoryEnabled);
444
+ const memoryRecall = memoryEnabled && isTurnRecallEnabled()
445
+ ? buildTurnRecallSection(command.prompt, { excludeIds: memoryTail.shownIds })
446
+ : '';
451
447
  const result = await runtime().run({
452
448
  turn: 'new',
453
449
  turnLabel: command.prompt.split('\n')[0]?.slice(0, 40) ?? command.prompt.slice(0, 40),
@@ -464,11 +460,8 @@ async function run(command) {
464
460
  traceContext: { sessionId },
465
461
  onTraceEvent: appendCurrentSessionTraceEvent,
466
462
  permissionPrompt: (request) => waitForApproval(command.id, request),
467
- // R17 尾注 + R18 静默召回:与 REPL 同口径(src/agent/index.ts 的 runAgent)。
468
- // 两者都走 ephemeral 段,不重建 history[0],前缀缓存不受影响;
469
- // 排除 memoryTailChangedIds() 是刻意的——那批条目已由尾注播报,同一轮不重复讲。
470
- memoryTail: buildMemoryTailSection(isMemoryEnabled()),
471
- memoryRecall: turnRecallFor(command.prompt),
463
+ memoryTail: memoryTail.text,
464
+ memoryRecall,
472
465
  });
473
466
  lastToolGroups = toolPolicy.groupNames;
474
467
  persistSession();
@@ -13,7 +13,7 @@ export { buildProjectGraphHint, GRAPH_HINT_MAX_CHARS } from './recall.js';
13
13
  export { isProactiveEnabled, proactiveHint, resetProactiveTurn, proactiveTurnCount, proactiveFiredIds, proactiveCounters, flushProactiveStats, __resetProactiveForTests, __resetProactiveCountersForTests, } from './proactive.js';
14
14
  export { buildMemoryHealth, writeMemoryHealth, readMemoryHealth, formatMemoryHealth, MEMORY_HEALTH_SCHEMA_VERSION, } from './health.js';
15
15
  export { recordMemoryDelivery, recordMemorySuppression, flushAdoptionSuppressions, adoptionEvaluationInstruction, extractAdoptionEvaluations, applyAdoptionEvaluations, adoptionStats, adoptionEvents, pruneAdoptionLedger, __resetAdoptionForTests, } from './adoption.js';
16
- export { captureMemoryBaseline, buildMemoryTailSection, memoryTailChangedIds, __resetMemoryBaselineForTests, } from './tail.js';
16
+ export { captureMemoryBaseline, buildMemoryTailSection, buildMemoryTailSnapshot, __resetMemoryBaselineForTests, } from './tail.js';
17
17
  export { buildTurnRecallSection, isTurnRecallEnabled, flushTurnRecallStats, turnRecallCounters, __resetTurnRecallForTests, } from './turn-recall.js';
18
18
  export { isCompactHandoffEnabled, appendPendingCandidates, loadPendingCandidates, trimPendingCandidates, pendingCandidateCount, extractMemoryCandidates, formatPendingForReflect, memoryCandidatesInstruction, MEMORY_CANDIDATES_HEADING, } from './pending.js';
19
19
  export { kickoffReflection, reflectOnExit, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, runReflection, kickoffConsolidation, runConsolidation, parseConsolidationPlan, getLastConsolidationResult, clearLastConsolidationResult, formatConsolidationResult, } from './reflect.js';
@@ -44,11 +44,9 @@ export function captureMemoryBaseline() {
44
44
  * 只看 updatedAt 变化,不看 body 内容——reason 改一个字的编辑也算更新,
45
45
  * 这是刻意的:能更新说明模型认为它值得改,那下一轮就该知道改了什么。
46
46
  */
47
- export function buildMemoryTailSection(enabled = true) {
48
- if (!enabled)
49
- return '';
50
- if (!baseline)
51
- return ''; // 没拍过基线 = 调用方没接线,静默不猜
47
+ export function buildMemoryTailSnapshot(enabled = true) {
48
+ if (!enabled || !baseline)
49
+ return { text: '', shownIds: new Set() };
52
50
  const changed = [];
53
51
  for (const e of loadAll()) {
54
52
  if (e.status !== 'active')
@@ -62,7 +60,7 @@ export function buildMemoryTailSection(enabled = true) {
62
60
  changed.push(e);
63
61
  }
64
62
  if (changed.length === 0)
65
- return '';
63
+ return { text: '', shownIds: new Set() };
66
64
  changed.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
67
65
  const shown = changed.slice(0, MAX_TAIL_ENTRIES);
68
66
  for (const entry of shown)
@@ -76,7 +74,7 @@ export function buildMemoryTailSection(enabled = true) {
76
74
  return `${head}\n ${clipped}`;
77
75
  });
78
76
  const omitted = changed.length - shown.length;
79
- return [
77
+ const text = [
80
78
  '## Memory updated during this session',
81
79
  'These entries were created or updated after this session started — by background reflection, an earlier turn, or a save you made. They are NOT in the Memory Index at the top (that is a startup snapshot). Treat them as current context; if one contradicts what the code now says, the code wins.',
82
80
  ...lines,
@@ -84,26 +82,11 @@ export function buildMemoryTailSection(enabled = true) {
84
82
  ]
85
83
  .filter((s) => s.length > 0)
86
84
  .join('\n');
85
+ return { text, shownIds: new Set(shown.map((entry) => entry.id)) };
87
86
  }
88
- /**
89
- * 本会话内新增或变更过的条目 id。
90
- *
91
- * 给 R18 每轮静默召回用:这批条目已经由这里(尾注)负责播报,召回再讲一遍等于
92
- * 同一轮把同一条记忆说两次——模型会以为那是两件事,而且白烧 token。
93
- * 基线未拍过时返回空集(调用方未接线,此时不该替它推断谁是新条目)。
94
- */
95
- export function memoryTailChangedIds() {
96
- if (!baseline)
97
- return new Set();
98
- const out = new Set();
99
- for (const e of loadAll()) {
100
- if (e.type === 'episode')
101
- continue;
102
- const before = baseline.get(e.id);
103
- if (before === undefined || before !== e.updatedAt)
104
- out.add(e.id);
105
- }
106
- return out;
87
+ /** 仅需要正文的调用方可继续使用字符串接口。 */
88
+ export function buildMemoryTailSection(enabled = true) {
89
+ return buildMemoryTailSnapshot(enabled).text;
107
90
  }
108
91
  /** 仅供测试:清掉基线,避免共享进程里上一个测试的基线串味。 */
109
92
  export function __resetMemoryBaselineForTests() {
@@ -29,7 +29,7 @@ import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index
29
29
  import { createTerminalTranscript, createTerminalTurn, rollbackTerminalTranscript, terminalCompactionMarker, } from '../session/terminal-transcript.js';
30
30
  import { skillsChangedSinceLastObserve } from '../skills/index.js';
31
31
  import { clearSkillActivation } from '../skills/activation.js';
32
- import { initPersona, gcMemories, kickoffReflection, kickoffConsolidation, reflectOnExit, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, flushTurnRecallStats, flushAdoptionSuppressions, pruneAdoptionLedger, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSection, loadAll, } from '../memory/index.js';
32
+ import { initPersona, gcMemories, kickoffReflection, kickoffConsolidation, reflectOnExit, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, flushTurnRecallStats, flushAdoptionSuppressions, pruneAdoptionLedger, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSnapshot, loadAll, } from '../memory/index.js';
33
33
  import { finalizeCurrentEpisode } from './episode-finalize.js';
34
34
  import { collectQueryHistory } from '../session/query-history.js';
35
35
  import { ToolPolicyController } from '../tools/policy.js';
@@ -716,7 +716,7 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
716
716
  }, toolPolicy, initialToolRoute,
717
717
  // R17:每用户轮现算一次「本会话内新增/更新的记忆」。走 ephemeral 尾注,不重建
718
718
  // history[0](否则整段对话的前缀缓存每轮失效)。基线无变化时返回空串 → 零注入。
719
- buildMemoryTailSection(isMemoryEnabled()), runtime, () => drainSteeringMessages().map((text) => {
719
+ buildMemoryTailSnapshot(isMemoryEnabled()), runtime, () => drainSteeringMessages().map((text) => {
720
720
  echoInput(text.split('\n'));
721
721
  queryHistory.push(text);
722
722
  terminalTurn?.addUser(text);
@@ -19,8 +19,8 @@ export function beginTurn(firstLine) {
19
19
  export function getCurrentTurnId() {
20
20
  return getActiveRollbackStore().getCurrentTurnId();
21
21
  }
22
- export function beginPathMutation(path) {
23
- return getActiveRollbackStore().beginPathMutation(path);
22
+ export function beginPathMutation(path, preparedFile) {
23
+ return getActiveRollbackStore().beginPathMutation(path, preparedFile);
24
24
  }
25
25
  export function endPathMutation(capture, op) {
26
26
  getActiveRollbackStore().endPathMutation(capture, op);