mocode-ai 1.10.0 → 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.
Files changed (59) hide show
  1. package/dist/agent/index.js +18 -7
  2. package/dist/agent/mentioned-files.js +71 -0
  3. package/dist/agent/model-turn.js +68 -30
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +155 -24
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +43 -0
  8. package/dist/agent/stages/history-manager.js +1 -0
  9. package/dist/agent/stages/tool-dispatcher.js +6 -3
  10. package/dist/agent/tool-helpers.js +2 -2
  11. package/dist/agent/tool-turn.js +49 -4
  12. package/dist/agent/work-discipline.js +12 -9
  13. package/dist/changeset/index.js +2 -1
  14. package/dist/config/index.js +12 -10
  15. package/dist/context/overlapping-reads.js +66 -0
  16. package/dist/context/relevance.js +11 -2
  17. package/dist/context/usage-snapshot.js +9 -6
  18. package/dist/host/stdio.js +96 -42
  19. package/dist/i18n/index.js +26 -10
  20. package/dist/llm/index.js +27 -3
  21. package/dist/llm/message-shape.js +18 -0
  22. package/dist/llm/reasoning.js +17 -0
  23. package/dist/memory/index.js +1 -1
  24. package/dist/memory/tail.js +9 -26
  25. package/dist/models/reasoning-cap.js +19 -2
  26. package/dist/orchestrator/lane-executor.js +7 -1
  27. package/dist/orchestrator/repl.js +30 -49
  28. package/dist/repl/commands/appearance.js +1 -2
  29. package/dist/repl/commands/compact.js +4 -0
  30. package/dist/repl/commands/model-actions.js +4 -3
  31. package/dist/repl/commands/model.js +2 -3
  32. package/dist/repl/message-format.js +7 -6
  33. package/dist/repl/running-input.js +27 -65
  34. package/dist/repl/runtime.js +119 -77
  35. package/dist/rollback/index.js +2 -2
  36. package/dist/rollback/store.js +73 -38
  37. package/dist/runtime/runtime.js +1 -1
  38. package/dist/session/compact.js +41 -4
  39. package/dist/session/retention.js +4 -0
  40. package/dist/session/short-path-metrics.js +185 -0
  41. package/dist/session/store.js +78 -3
  42. package/dist/session/terminal-transcript.js +101 -0
  43. package/dist/tools/builtins/ask-human.js +2 -2
  44. package/dist/tools/builtins/edit-file.js +79 -19
  45. package/dist/tools/builtins/grep.js +161 -42
  46. package/dist/tools/builtins/plan-update.js +4 -2
  47. package/dist/tools/builtins/read-file.js +148 -55
  48. package/dist/tools/builtins/run-command.js +57 -9
  49. package/dist/tools/ripgrep-client.js +72 -26
  50. package/dist/tools/tool-runtime.js +29 -8
  51. package/dist/ui/layout-internal/content-write.js +7 -3
  52. package/dist/ui/layout-internal/core.js +1 -1
  53. package/dist/ui/layout-internal/state.js +0 -6
  54. package/dist/ui/layout-internal/statusbar.js +0 -30
  55. package/dist/ui/output-sink.js +24 -0
  56. package/dist/ui/render.js +3 -0
  57. package/dist/ui/spinner.js +3 -1
  58. package/dist/verification/evidence.js +52 -0
  59. package/package.json +4 -2
@@ -0,0 +1,101 @@
1
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ export const TERMINAL_TRANSCRIPT_FILE = 'terminal-transcript.json';
4
+ /** 仅为回放保存图片的类型,图像字节仍由模型会话自身管理。 */
5
+ function displayContent(content, imageNames = []) {
6
+ if (!Array.isArray(content))
7
+ return content;
8
+ let imageIndex = 0;
9
+ return content.map((part) => {
10
+ if (part.type !== 'image_url')
11
+ return { ...part };
12
+ const name = imageNames[imageIndex++];
13
+ return {
14
+ ...part,
15
+ ...(name ? { name } : {}),
16
+ image_url: { url: /^data:image\/[a-z0-9.+-]+;/i.exec(part.image_url.url)?.[0] ?? 'data:image/png;' },
17
+ };
18
+ });
19
+ }
20
+ export function createTerminalTranscript(history) {
21
+ const base = history.map((message, index) => {
22
+ if (message.role === 'system' && index === 0)
23
+ return { role: 'system', content: '' };
24
+ if (message.role === 'user')
25
+ return { ...message, content: displayContent(message.content) };
26
+ if (message.role === 'assistant')
27
+ return {
28
+ role: 'assistant',
29
+ content: message.content,
30
+ ...(message.tool_calls ? { tool_calls: structuredClone(message.tool_calls) } : {}),
31
+ };
32
+ return { ...message };
33
+ });
34
+ if (base[0]?.role !== 'system')
35
+ base.unshift({ role: 'system', content: '' });
36
+ return { base, turns: [] };
37
+ }
38
+ export function terminalCompactionMarker() {
39
+ return { role: 'system', content: '# 会话摘要' };
40
+ }
41
+ export function rollbackTerminalTranscript(transcript, firstDiscardedTurnId, retainedHistory) {
42
+ const firstRecordedTurn = transcript.turns[0];
43
+ if (!firstRecordedTurn || firstDiscardedTurnId === undefined || firstDiscardedTurnId < firstRecordedTurn.turnId) {
44
+ return createTerminalTranscript(retainedHistory);
45
+ }
46
+ return { base: transcript.base, turns: transcript.turns.filter((turn) => turn.turnId < firstDiscardedTurnId) };
47
+ }
48
+ export function createTerminalTurn(content, imageNames) {
49
+ const messages = [{ role: 'user', content: displayContent(content, imageNames) }];
50
+ return {
51
+ messages,
52
+ addUser(text) {
53
+ messages.push({ role: 'user', content: text });
54
+ },
55
+ addText(text) {
56
+ if (!text)
57
+ return;
58
+ const last = messages.at(-1);
59
+ if (last?.role === 'assistant' && typeof last.content === 'string' && !last.tool_calls?.length) {
60
+ last.content += text;
61
+ }
62
+ else {
63
+ messages.push({ role: 'assistant', content: text });
64
+ }
65
+ },
66
+ addTool(call, output) {
67
+ messages.push({
68
+ role: 'assistant',
69
+ content: null,
70
+ tool_calls: [{ id: call.id, type: 'function', function: { name: call.name, arguments: call.arguments } }],
71
+ }, { role: 'tool', tool_call_id: call.id, content: output });
72
+ },
73
+ compacted() {
74
+ messages.push(terminalCompactionMarker());
75
+ },
76
+ };
77
+ }
78
+ export function parseTerminalTranscript(value) {
79
+ if (!value || typeof value !== 'object')
80
+ return;
81
+ const { base, turns } = value;
82
+ const isMessageList = (items) => Array.isArray(items) && items.every((item) => item && typeof item === 'object' && typeof item.role === 'string');
83
+ if (isMessageList(base) &&
84
+ Array.isArray(turns) &&
85
+ turns.every((turn) => Number.isSafeInteger(turn?.turnId) && isMessageList(turn.messages)))
86
+ return { base, turns };
87
+ }
88
+ export function readTerminalTranscriptFile(dir) {
89
+ try {
90
+ return parseTerminalTranscript(JSON.parse(readFileSync(path.join(dir, TERMINAL_TRANSCRIPT_FILE), 'utf8')));
91
+ }
92
+ catch {
93
+ // 旧会话或损坏记录仍可按模型历史回放。
94
+ }
95
+ }
96
+ export function writeTerminalTranscriptFile(dir, transcript) {
97
+ const file = path.join(dir, TERMINAL_TRANSCRIPT_FILE);
98
+ const temporary = file + '.tmp';
99
+ writeFileSync(temporary, JSON.stringify(transcript), 'utf8');
100
+ renameSync(temporary, file);
101
+ }
@@ -125,8 +125,8 @@ export const askHumanTool = {
125
125
  'Ask the user a question and wait for their response.',
126
126
  ' CHOICES: pass 2-4 concrete options via `options`, each as { label, description? }; every non-empty option requires a non-empty `label`.',
127
127
  ' FREE-TEXT: pass `options: []` when the answer cannot be reduced to choices (e.g. "paste the error message").',
128
- ' MUST call BEFORE any decision the user has not made (multiple reasonable approaches) or any key modification (public API, schema, dependencies, file moves/deletes, architecture, security, large or irreversible changes); never decide these yourself.',
129
- ' Skip only for trivial details that follow repository precedent and are easily reversible.',
128
+ ' Ask BEFORE unresolved choices that materially affect the outcome and before key modifications (public API, schema, dependencies, file moves/deletes, architecture, security, large or irreversible changes).',
129
+ ' Carry out routine, reversible implementation details of a clear request using local conventions.',
130
130
  ].join(' '),
131
131
  parameters: {
132
132
  type: 'object',
@@ -1,28 +1,75 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import { basename } from 'node:path';
3
+ import { unifiedFileDiff } from '../../changeset/unified-diff.js';
2
4
  import { jailResolve } from '../../sandbox/index.js';
3
5
  import { commitChangeSet, contentHash, createChangeSet, normalizeContentHash, summarizeChangeSet, } from '../../changeset/index.js';
4
6
  import { isProbablyBinary } from '../../attachments/image.js';
7
+ import { formatNumberedLines } from './read-file.js';
5
8
  /** 二进制嗅探只需文件头,与 read_file / write_file 同口径(16KB)。 */
6
9
  const SNIFF_BYTES = 16 * 1024;
7
- function conflict(path, details) {
10
+ // 复用已有 diff 渲染,只给模型回传完整的小补丁。大文件免去额外的全文拆行。
11
+ const MAX_PREVIEW_INPUT_CHARS = 256 * 1024;
12
+ const MAX_PREVIEW_CHARS = 2000;
13
+ const MAX_CONFLICT_CANDIDATES = 2;
14
+ const MAX_CONFLICT_EVIDENCE_CHARS = 2400;
15
+ function conflict(path, details, evidence) {
16
+ const recovery = evidence
17
+ ? `${evidence.next} If the target is still unclear, use read_file on the affected range.\n${evidence.excerpts}`
18
+ : 'Use read_file on the affected range of this exact path and copy the latest text and hash before editing again.';
8
19
  return {
9
20
  status: 'error',
10
21
  code: 'CHANGE_CONFLICT',
11
22
  retryable: false,
12
23
  changedFiles: [],
13
24
  staleFiles: [path],
14
- output: `CHANGE_CONFLICT: ${path} was not changed. ${details} Do not retry these arguments. Call read_file on this exact path and copy the exact target text (plus its latest hash if you pass expected_hash, which line-range mode requires) before editing again.`,
25
+ output: `CHANGE_CONFLICT: ${path} was not changed. ${details} Do not retry these arguments. ${recovery}`,
15
26
  };
16
27
  }
28
+ function findOccurrences(text, needle) {
29
+ const hits = [];
30
+ let from = 0;
31
+ while (hits.length <= MAX_CONFLICT_CANDIDATES) {
32
+ const hit = text.indexOf(needle, from);
33
+ if (hit < 0)
34
+ break;
35
+ hits.push(hit);
36
+ from = hit + needle.length;
37
+ }
38
+ return hits;
39
+ }
40
+ function ambiguousConflict(path, label, text, needle, hits, buffer, expectedHash) {
41
+ const capped = hits.length > MAX_CONFLICT_CANDIDATES;
42
+ const details = `${label} 出现 ${capped ? '至少 ' : ''}${hits.length} 次;请选定目标范围。`;
43
+ if (capped || buffer.length > MAX_PREVIEW_INPUT_CHARS || contentHash(buffer) !== expectedHash) {
44
+ return conflict(path, details);
45
+ }
46
+ if (!Buffer.from(buffer.toString('utf8')).equals(buffer))
47
+ return conflict(path, details);
48
+ const lines = text.split('\n');
49
+ const matchLineCount = needle.split('\n').length - Number(needle.endsWith('\n'));
50
+ const excerpts = hits.map((hit) => {
51
+ const matchLine = text.slice(0, hit).split('\n').length;
52
+ const start = Math.max(0, matchLine - 4);
53
+ const end = Math.min(lines.length, matchLine - 1 + matchLineCount + 3);
54
+ return `[edit_context path=${JSON.stringify(path)} hash=${expectedHash} lines=${start + 1}-${end} match=${matchLine}]\n${formatNumberedLines(lines, start, end)}`;
55
+ });
56
+ const evidence = excerpts.join('\n\n');
57
+ if (evidence.length > MAX_CONFLICT_EVIDENCE_CHARS)
58
+ return conflict(path, details);
59
+ const next = label === 'old_string'
60
+ ? "Use the candidate that matches the user's target. Copy its exact text or use the shown lines with its expected_hash."
61
+ : `Use the matching candidate to expand ${label} into unique exact text. Resubmit the complete replacements array with the shown expected_hash.`;
62
+ return conflict(path, details, { excerpts: evidence, next });
63
+ }
17
64
  export const editFileTool = {
18
65
  name: 'edit_file',
19
66
  description: `The DEFAULT tool for changing an EXISTING file: transactional, surgical edits — use this instead of re-writing the whole file with write_file. Pick ONE of three modes per call:
20
67
 
21
- **String replacement (default):** old_string must occur EXACTLY once; copy it verbatim from a fresh read_file output (see Tool policy — never reconstruct it from memory, summaries, or grep output). expected_hash is OPTIONAL in this mode: omit it and the tool checks the file itself (old_string must still match exactly once, and the commit is conflict-checked). If you do pass it, it must match the current file or the edit is rejected.
68
+ **String replacement (default):** old_string must occur EXACTLY once. Copy it verbatim from fresh read_file output or a complete [edit_context ...] excerpt from grep. Always pass the excerpt's hash as expected_hash when using grep evidence. With read_file, the hash is optional; the tool still checks uniqueness and conflicts at commit. Ordinary search results, summaries and diffs are not exact edit evidence.
22
69
 
23
70
  **Multiple replacements:** pass replacements: [{ old_string, new_string }, …] to apply MANY edits across the file in ONE atomic call. Each old_string must occur exactly once in the original file and the matches must not overlap; if ANY of them is missing, ambiguous, or overlapping, the whole call is rejected and nothing is written. Prefer this over write_file whenever you change several spots — it keeps each payload small and never touches unrelated content. Mutually exclusive with the single old_string and line-range modes.
24
71
 
25
- **Line-range:** line_start/line_end (1-based, inclusive) instead of old_string — for large blocks, repeated patterns, or hard-to-reproduce text. Line numbers drift when a file changes, so expected_hash (sha256 from the read_file artifact header) is REQUIRED here; if it is stale, re-read and retry with the new hash.`,
72
+ **Line-range:** line_start/line_end (1-based, inclusive) instead of old_string — for large blocks, repeated patterns, or hard-to-reproduce text. expected_hash from a fresh read_file or [edit_context ...] header is REQUIRED. If stale, reread only the affected range and retry with the new hash.`,
26
73
  risk: 'confirm',
27
74
  parameters: {
28
75
  type: 'object',
@@ -59,7 +106,7 @@ export const editFileTool = {
59
106
  },
60
107
  expected_hash: {
61
108
  type: 'string',
62
- description: 'sha256 hash from the latest read_file artifact header (sha256:<64 hex>). Optional for old_string / replacements modes; required for line-range mode.',
109
+ description: 'Latest sha256:<64 hex> from read_file or [edit_context ...]. Always pass it with grep edit evidence or line-range edits.',
63
110
  },
64
111
  },
65
112
  // 注意:expected_hash 与模式专属字段(new_string / replacements / line_*)都不放进 schema required。
@@ -143,12 +190,14 @@ export const editFileTool = {
143
190
  // String replacement mode
144
191
  const newNormalized = toLf(String(args.new_string));
145
192
  const oldNormalized = toLf(String(args.old_string));
146
- const count = normalized.split(oldNormalized).length - 1;
147
- if (count === 0) {
193
+ if (!oldNormalized)
194
+ return conflict(file, 'old_string 不能为空。');
195
+ const hits = findOccurrences(normalized, oldNormalized);
196
+ if (hits.length === 0) {
148
197
  return conflict(file, 'old_string 未找到;请重新 read_file 并复制最新内容。');
149
198
  }
150
- if (count > 1) {
151
- return conflict(file, `old_string 出现 ${count} 次;请增加上下文使其唯一。`);
199
+ if (hits.length > 1) {
200
+ return ambiguousConflict(file, 'old_string', normalized, oldNormalized, hits, buffer, expectedHash);
152
201
  }
153
202
  updated = normalized.replace(oldNormalized, () => newNormalized);
154
203
  }
@@ -158,19 +207,12 @@ export const editFileTool = {
158
207
  const located = [];
159
208
  for (let i = 0; i < multiEdits.length; i++) {
160
209
  const edit = multiEdits[i];
161
- const hits = [];
162
- let from = 0;
163
- let hit;
164
- // 空串已在上面拒绝;indexOf 步进至少 1 不会死循环。
165
- while ((hit = normalized.indexOf(edit.old, from)) !== -1) {
166
- hits.push(hit);
167
- from = hit + edit.old.length;
168
- }
210
+ const hits = findOccurrences(normalized, edit.old);
169
211
  if (hits.length === 0) {
170
212
  return conflict(file, `replacements[${i}].old_string 未找到;请重新 read_file 并复制最新内容。`);
171
213
  }
172
214
  if (hits.length > 1) {
173
- return conflict(file, `replacements[${i}].old_string 出现 ${hits.length} 次;请增加上下文使其唯一。`);
215
+ return ambiguousConflict(file, `replacements[${i}].old_string`, normalized, edit.old, hits, buffer, expectedHash);
174
216
  }
175
217
  located.push({ start: hits[0], end: hits[0] + edit.old.length, next: edit.next });
176
218
  }
@@ -232,15 +274,33 @@ export const editFileTool = {
232
274
  };
233
275
  }
234
276
  const summary = summarizeChangeSet(result.changeSet);
277
+ const committed = result.changeSet.prepared[0];
278
+ const literal = mode === 'single' ? String(args.old_string) : '';
279
+ const literalStart = literal ? data.indexOf(literal) : -1;
280
+ // CRLF 归一化、非 UTF-8 和重叠命中可能改变替换范围,只有实际事务满足才提供证明。
281
+ const exactTextReplacement = literalStart >= 0 &&
282
+ result.changedFiles.length === 1 &&
283
+ data.length + replacement.length <= MAX_PREVIEW_INPUT_CHARS &&
284
+ committed.before?.equals(buffer) &&
285
+ Buffer.from(data).equals(buffer) &&
286
+ data.indexOf(literal, literalStart + 1) < 0 &&
287
+ data.replace(literal, () => String(args.new_string)) === replacement;
288
+ let preview = '';
289
+ if (result.changedFiles.length > 0 && data.length + replacement.length <= MAX_PREVIEW_INPUT_CHARS) {
290
+ const diff = unifiedFileDiff(basename(file), data, replacement, 1);
291
+ if (diff && diff.length <= MAX_PREVIEW_CHARS)
292
+ preview = `\n${diff}`;
293
+ }
235
294
  return {
236
295
  status: 'success',
237
296
  code: 'OK',
238
297
  retryable: false,
239
298
  changedFiles: result.changedFiles,
240
299
  changeSet: summary,
300
+ ...(exactTextReplacement ? { exactTextReplacement: true } : {}),
241
301
  output: result.changedFiles.length === 0
242
302
  ? `文件 ${file} 内容未变化 (ChangeSet ${summary.id})。`
243
- : `已事务化编辑 ${file} (ChangeSet ${summary.id}, sha256=${summary.changes[0]?.afterHash})。`,
303
+ : `已事务化编辑 ${file} (ChangeSet ${summary.id}, sha256=${summary.changes[0]?.afterHash})。${preview}`,
244
304
  };
245
305
  },
246
306
  };
@@ -4,6 +4,7 @@ import { IGNORE, MAX_RESULTS } from '../constants.js';
4
4
  import { isProbablyBinary } from '../../attachments/image.js';
5
5
  import { getSandboxRoot, isInsideRoot, jailResolve } from '../../sandbox/index.js';
6
6
  import { runRipgrep } from '../ripgrep-client.js';
7
+ import { readSearchEditExcerpts } from './read-file.js';
7
8
  /**
8
9
  * grep 超时墙。
9
10
  *
@@ -18,6 +19,20 @@ const MAX_FILE_BYTES = 2 * 1024 * 1024;
18
19
  const MAX_BODY_LINE_CHARS = 400;
19
20
  /** context 参数上限:邻居行是 ×(1+2C) 放大,给到 10 已远超需要。 */
20
21
  const MAX_CONTEXT_LINES = 10;
22
+ const MAX_EDIT_CANDIDATES = 8;
23
+ const MAX_EDIT_EXCERPTS = 3;
24
+ const MAX_MULTI_EDIT_CONTEXT_CHARS = 4_000;
25
+ const MAX_PATH_OUTPUT_CHARS = 16_000;
26
+ function abortedResult(timedOut) {
27
+ if (!timedOut)
28
+ return '已中断';
29
+ return {
30
+ status: 'error',
31
+ code: 'TIMEOUT',
32
+ retryable: false,
33
+ output: `错误:grep 超过 ${GREP_TIMEOUT_MS / 1000}s 超时墙已被中止(收窄 glob 或确认无网络盘挂载后重试)`,
34
+ };
35
+ }
21
36
  function clipLine(line) {
22
37
  if (line.length <= MAX_BODY_LINE_CHARS)
23
38
  return line;
@@ -30,7 +45,7 @@ function clipLine(line) {
30
45
  * ` --` 不相邻分块之间的分隔
31
46
  * 原文不 trim:缩进是代码结构信息。
32
47
  */
33
- function renderFileBodies(file, maxPerFile) {
48
+ function renderFileBodies(file, maxPerFile, context) {
34
49
  const shown = file.matches.slice(0, maxPerFile);
35
50
  if (shown.length === 0)
36
51
  return [];
@@ -38,8 +53,12 @@ function renderFileBodies(file, maxPerFile) {
38
53
  const byLine = new Map();
39
54
  for (const e of shown)
40
55
  byLine.set(e.line, e);
41
- for (const e of file.contexts)
56
+ const lastContextLine = shown[shown.length - 1].line + context;
57
+ for (const e of file.contexts) {
58
+ if (e.line > lastContextLine)
59
+ break;
42
60
  byLine.set(e.line, e);
61
+ }
43
62
  const out = [];
44
63
  let previous = 0;
45
64
  for (const n of [...byLine.keys()].sort((a, b) => a - b)) {
@@ -53,28 +72,23 @@ function renderFileBodies(file, maxPerFile) {
53
72
  }
54
73
  /** 把聚合后的文件事件渲染成工具输出(配额/截断口径与旧实现一致)。 */
55
74
  function renderResults(files, maxPerFile, context, truncated) {
56
- const hits = [];
75
+ const out = [];
57
76
  let budgetTruncated = truncated;
77
+ let totalShown = 0;
58
78
  for (const file of files) {
59
79
  const bodyCost = Math.min(file.matches.length, maxPerFile) * (1 + 2 * context);
60
80
  const totalCost = file.matches.length + bodyCost;
61
- if (hits.length >= MAX_RESULTS || totalCost > MAX_RESULTS * 4) {
62
- if (hits.length < MAX_RESULTS)
63
- hits.push({ file, bodies: [] });
81
+ out.push(`${file.path}: ${file.matches.length} 处匹配,行号 [${file.matches.map((e) => e.line).join(', ')}]`);
82
+ totalShown += file.matches.length;
83
+ if (totalCost > MAX_RESULTS * 4) {
84
+ out.push(' (body 已折叠,见上方行号列表 → read_file 精读)');
64
85
  budgetTruncated = true;
65
- continue;
66
86
  }
67
- hits.push({ file, bodies: renderFileBodies(file, maxPerFile) });
68
- }
69
- const out = [];
70
- let totalShown = 0;
71
- for (const h of hits) {
72
- out.push(`${h.file.path}: ${h.file.matches.length} 处匹配,行号 [${h.file.matches.map((e) => e.line).join(', ')}]`);
73
- if (h.bodies.length > 0)
74
- out.push(...h.bodies);
75
- else
76
- out.push(' (body 已折叠,见上方行号列表 → read_file 精读)');
77
- totalShown += h.file.matches.length + h.bodies.length;
87
+ else {
88
+ const bodies = renderFileBodies(file, maxPerFile, context);
89
+ out.push(...bodies);
90
+ totalShown += bodies.length;
91
+ }
78
92
  if (totalShown >= MAX_RESULTS) {
79
93
  out.push(`...(结果达到 ${MAX_RESULTS} 条上限${context > 0 ? ',context 行同样计入;要更全就减小 context 或收窄 glob' : ''})`);
80
94
  break;
@@ -84,11 +98,67 @@ function renderResults(files, maxPerFile, context, truncated) {
84
98
  out.push('...(仍有更多匹配未展示,缩小 glob 或收窄正则)');
85
99
  return out.join('\n');
86
100
  }
101
+ function renderMatchedPaths(paths, truncated) {
102
+ const shown = [];
103
+ let chars = 0;
104
+ for (const path of paths) {
105
+ const line = /[\r\n]/.test(path) ? JSON.stringify(path) : path;
106
+ chars += line.length + 1;
107
+ if (chars > MAX_PATH_OUTPUT_CHARS) {
108
+ truncated = true;
109
+ break;
110
+ }
111
+ shown.push(line);
112
+ }
113
+ const output = shown.length > 0 ? [`[grep files=${shown.length}]`, ...shown] : ['无匹配文件'];
114
+ if (truncated)
115
+ output.push('...(文件列表不完整,缩小 glob 或收窄正则)');
116
+ return output.join('\n');
117
+ }
118
+ function renderEditCandidates(files, truncated) {
119
+ const out = [];
120
+ for (const file of files) {
121
+ if (out.length === MAX_EDIT_CANDIDATES)
122
+ break;
123
+ for (const match of file.matches.slice(0, MAX_EDIT_CANDIDATES - out.length)) {
124
+ out.push(`${file.path}:${match.line}: ${clipLine(match.text)}`);
125
+ }
126
+ }
127
+ const omitted = truncated || files.reduce((total, file) => total + file.matches.length, 0) > out.length;
128
+ if (omitted)
129
+ out.push('...(还有更多候选)');
130
+ out.push('未提供编辑原文。请收窄搜索,或对选中的路径和行号使用 read_file。');
131
+ return out.join('\n');
132
+ }
133
+ async function renderEditContext(files, truncated, maxCandidates, signal) {
134
+ const matchCount = files.reduce((total, file) => total + file.matches.length, 0);
135
+ if (truncated || matchCount === 0 || matchCount > maxCandidates)
136
+ return renderEditCandidates(files, truncated);
137
+ const excerpts = [];
138
+ for (const file of files) {
139
+ let absolutePath;
140
+ try {
141
+ absolutePath = jailResolve(file.path);
142
+ }
143
+ catch {
144
+ // 路径可能在搜索与读取之间变成越界链接。
145
+ }
146
+ if (!absolutePath)
147
+ return renderEditCandidates(files, truncated);
148
+ const excerpt = await readSearchEditExcerpts(absolutePath, file.matches, signal);
149
+ if (!excerpt)
150
+ return renderEditCandidates(files, truncated);
151
+ excerpts.push(excerpt);
152
+ }
153
+ const output = excerpts.join('\n\n');
154
+ return matchCount > 1 && output.length > MAX_MULTI_EDIT_CONTEXT_CHARS
155
+ ? renderEditCandidates(files, truncated)
156
+ : output;
157
+ }
87
158
  /**
88
- * Node 兜底:rg 二进制不可用(可选依赖缺失且 PATH 无 rg)时走旧路径。
89
- * 与旧实现的唯一差异——每两个文件之间检查 abort 信号,使 Ctrl+C / 超时墙能即时打断。
159
+ * Node 兜底:rg 二进制不可用时用 fast-glob 枚举,再按行查找。
90
160
  */
91
- async function nodeFallback(pattern, glob, maxPerFile, context, signal, externalSignal) {
161
+ async function nodeFallback(pattern, glob, maxPerFile, editContext, filesOnly, signal, externalSignal) {
92
162
  let re;
93
163
  try {
94
164
  re = new RegExp(pattern);
@@ -102,12 +172,14 @@ async function nodeFallback(pattern, glob, maxPerFile, context, signal, external
102
172
  cwd,
103
173
  onlyFiles: true,
104
174
  dot: true,
105
- ignore: IGNORE,
175
+ ignore: glob.startsWith('.mocode/') ? IGNORE : [...IGNORE, '**/.mocode/**'],
106
176
  stats: true,
107
177
  followSymbolicLinks: false,
108
178
  throwErrorOnBrokenSymbolicLink: false,
109
179
  })).filter((entry) => isInsideRoot(entry.path)); // 后置兜底:仅留牢内
110
180
  const files = [];
181
+ const paths = [];
182
+ let truncated = false;
111
183
  let scanned = 0;
112
184
  let skippedTooLarge = 0;
113
185
  const abortNote = () => externalSignal?.aborted
@@ -118,9 +190,8 @@ async function nodeFallback(pattern, glob, maxPerFile, context, signal, external
118
190
  retryable: false,
119
191
  output: `错误:grep 超过 ${GREP_TIMEOUT_MS / 1000}s 超时墙已被中止(收窄 glob 后重试)`,
120
192
  };
121
- for (let fi = 0; fi < entries.length; fi++) {
122
- const entry = entries[fi];
123
- if ((fi & 31) === 0 && signal.aborted)
193
+ for (const entry of entries) {
194
+ if (signal.aborted)
124
195
  return abortNote();
125
196
  if (entry.stats && entry.stats.size > MAX_FILE_BYTES) {
126
197
  skippedTooLarge++;
@@ -128,7 +199,7 @@ async function nodeFallback(pattern, glob, maxPerFile, context, signal, external
128
199
  }
129
200
  let content;
130
201
  try {
131
- content = await readFile(jailResolve(entry.path), 'utf8');
202
+ content = await readFile(jailResolve(entry.path), { encoding: 'utf8', signal });
132
203
  }
133
204
  catch {
134
205
  continue;
@@ -137,6 +208,16 @@ async function nodeFallback(pattern, glob, maxPerFile, context, signal, external
137
208
  if (isProbablyBinary(content))
138
209
  continue;
139
210
  const lines = content.split(/\r?\n/);
211
+ if (filesOnly) {
212
+ if (!lines.some((line) => re.test(line)))
213
+ continue;
214
+ if (paths.length === MAX_RESULTS) {
215
+ truncated = true;
216
+ break;
217
+ }
218
+ paths.push(entry.path);
219
+ continue;
220
+ }
140
221
  const matches = [];
141
222
  for (let i = 0; i < lines.length; i++) {
142
223
  if (re.test(lines[i]))
@@ -147,12 +228,16 @@ async function nodeFallback(pattern, glob, maxPerFile, context, signal, external
147
228
  }
148
229
  if (signal.aborted)
149
230
  return abortNote();
231
+ if (filesOnly) {
232
+ const output = renderMatchedPaths(paths, truncated);
233
+ return skippedTooLarge ? `${output}\n...(跳过 ${skippedTooLarge} 个超过 2MiB 的文件)` : output;
234
+ }
150
235
  if (files.length === 0) {
151
236
  const note = skippedTooLarge ? `,跳过 ${skippedTooLarge} 个超过 2MiB 的文件` : '';
152
237
  return `无匹配(扫描了 ${scanned} 个文件${note})`;
153
238
  }
154
239
  // 兜底路径无 context 事件来源(rg 缺失),context 参数退化为只给命中行。
155
- const out = renderResults(files, maxPerFile, 0, false);
240
+ const out = editContext ? renderEditCandidates(files, false) : renderResults(files, maxPerFile, 0, false);
156
241
  return skippedTooLarge ? `${out}\n...(跳过 ${skippedTooLarge} 个超过 2MiB 的文件)` : out;
157
242
  }
158
243
  // ---------- grep ----------
@@ -160,13 +245,29 @@ export const grepTool = {
160
245
  name: 'grep',
161
246
  description: 'Search file contents by regex (recursive; powered by ripgrep: respects .gitignore, skips binaries).\n' +
162
247
  'Output: per-file header "<path>: N matches, lines [l1, l2, ...]" plus rendered lines with ORIGINAL INDENTATION kept.\n' +
163
- 'Pass context=2..5 to include neighbouring lines inline (like ripgrep -C) instead of following each hit with a read_file round-trip. Hard wall 120s; narrow the glob if a tree contains network mounts. Use read_file when you need a whole region or exact edit text.\n' +
248
+ 'For tasks that only need to know which files contain a match, use mode="files" to list paths once per file.\n' +
249
+ 'Pass context=2..5 for neighbouring lines. For an edit in an unknown file, use edit_context=true with a narrow pattern. Use max_edit_candidates=3 when definitions, tests or other versions may share the same match. An [edit_context ...] block gives exact text; use the chosen block’s path and hash as expected_hash in edit_file. Searches over budget return locations only. Hard wall 120s.\n' +
164
250
  'Note: .mocode/ is gitignored; to search session data (e.g. .mocode/sessions/<id>/compacted archived history) you MUST narrow glob to that path, e.g. glob=".mocode/sessions/**".',
165
251
  parameters: {
166
252
  type: 'object',
167
253
  properties: {
168
254
  pattern: { type: 'string', description: 'Regular expression (ripgrep/Rust regex syntax)' },
169
255
  glob: { type: 'string', description: 'Optional, restrict to a file glob, e.g. *.ts' },
256
+ mode: {
257
+ type: 'string',
258
+ enum: ['matches', 'files'],
259
+ description: 'Default matches returns lines. Files lists paths only, ignores context and max_per_file, and cannot be combined with edit_context=true.',
260
+ },
261
+ edit_context: {
262
+ type: 'boolean',
263
+ description: 'Return exact edit excerpts within max_edit_candidates and a shared output budget, or a short candidate list. Ignores context and max_per_file.',
264
+ },
265
+ max_edit_candidates: {
266
+ type: 'integer',
267
+ minimum: 1,
268
+ maximum: MAX_EDIT_EXCERPTS,
269
+ description: 'Match limit for edit_context, default 1. Set 3 to request original text for a small set of candidates.',
270
+ },
170
271
  max_per_file: {
171
272
  type: 'integer',
172
273
  description: 'Max MATCHED lines rendered per file (default 15, cap 50); their context lines are extra. Line-number list is always full.',
@@ -182,6 +283,20 @@ export const grepTool = {
182
283
  async execute(args, ctx) {
183
284
  const pattern = String(args.pattern);
184
285
  const glob = String(args.glob ?? '**/*');
286
+ const editContext = args.edit_context === true;
287
+ const filesOnly = args.mode === 'files';
288
+ if (filesOnly && editContext) {
289
+ return {
290
+ status: 'error',
291
+ code: 'INVALID_ARGUMENTS',
292
+ retryable: false,
293
+ output: '错误:mode="files" 只返回路径;获取可编辑原文时用 mode="matches" 与 edit_context=true。',
294
+ };
295
+ }
296
+ const requestedCandidates = Number(args.max_edit_candidates ?? 1);
297
+ const maxEditCandidates = Number.isInteger(requestedCandidates)
298
+ ? Math.max(1, Math.min(MAX_EDIT_EXCERPTS, requestedCandidates))
299
+ : 1;
185
300
  const maxPerFile = Math.min(Math.max(Number(args.max_per_file ?? 15), 1), 50);
186
301
  const contextRaw = Number(args.context ?? 0);
187
302
  const context = Number.isFinite(contextRaw) ? Math.min(Math.max(Math.trunc(contextRaw), 0), MAX_CONTEXT_LINES) : 0;
@@ -203,29 +318,33 @@ export const grepTool = {
203
318
  try {
204
319
  // glob 显式限定到 .mocode(gitignore 内)时放开 VCS ignore,否则 rg 零文件退出。
205
320
  const noIgnoreVcs = glob === '.mocode/**' || glob.startsWith('.mocode/');
206
- const result = await runRipgrep({ pattern, glob, context, noIgnoreVcs }, controller.signal);
321
+ const result = await runRipgrep({
322
+ pattern,
323
+ glob,
324
+ context: editContext ? 0 : context,
325
+ noIgnoreVcs,
326
+ maxMatches: editContext ? MAX_EDIT_CANDIDATES : MAX_RESULTS,
327
+ ...(filesOnly ? { maxFiles: MAX_RESULTS } : {}),
328
+ }, controller.signal);
207
329
  switch (result.status) {
330
+ case 'paths':
331
+ return renderMatchedPaths(result.paths, result.truncated);
208
332
  case 'regex_error':
209
333
  return `错误:非法正则 ${pattern}: ${result.message}`;
210
334
  case 'no-match': {
211
335
  const trunc = result.truncated ? '\n...(输出截断,缩小 glob 或收窄正则后重试)' : '';
212
336
  return `无匹配(扫描了 ${result.scanned} 个文件)${trunc}`;
213
337
  }
214
- case 'ok':
215
- return renderResults(result.files, maxPerFile, context, result.truncated);
338
+ case 'ok': {
339
+ if (!editContext)
340
+ return renderResults(result.files, maxPerFile, context, result.truncated);
341
+ const output = await renderEditContext(result.files, result.truncated, maxEditCandidates, controller.signal);
342
+ return controller.signal.aborted ? abortedResult(timedOut) : output;
343
+ }
216
344
  case 'unavailable':
217
- return nodeFallback(pattern, glob, maxPerFile, context, controller.signal, external);
345
+ return await nodeFallback(pattern, glob, maxPerFile, editContext, filesOnly, controller.signal, external);
218
346
  case 'aborted':
219
- if (timedOut) {
220
- return {
221
- status: 'error',
222
- code: 'TIMEOUT',
223
- retryable: false,
224
- output: `错误:grep 超过 ${GREP_TIMEOUT_MS / 1000}s 超时墙已被中止(收窄 glob 或确认无网络盘挂载后重试)`,
225
- };
226
- }
227
- // 外部 Ctrl+C:返回中断串,tool-runtime 见 signal.aborted 会归一为 aborted。
228
- return '已中断';
347
+ return abortedResult(timedOut);
229
348
  }
230
349
  }
231
350
  finally {
@@ -1,3 +1,4 @@
1
+ import { PLAN_USAGE_GUIDANCE } from '../../agent/work-discipline.js';
1
2
  import { PLAN_MAX_STEPS, readActivePlanTitle, renderPlanSection, writePlanToNotes, } from '../../session/notes.js';
2
3
  const VALID_STATUSES = ['pending', 'in_progress', 'completed'];
3
4
  function err(message) {
@@ -18,7 +19,8 @@ function normalizeStatus(raw) {
18
19
  }
19
20
  export const planUpdateTool = {
20
21
  name: 'plan_update',
21
- description: 'Record and update the session execution plan (the `## Plan:` block in notes.md). Use for any task with 3+ steps or context-loss risk. REPLACES the whole plan each call — always pass the full steps array. At most one step in_progress; mark a step completed as soon as its work is done, not batched to end of turn. Each step: short `title` (≤20 chars, shown in the status bar) + `content` self-contained enough to survive compaction (target file/symbol, change, verification). All steps completed → auto-settles to `## Done:`. Creates notes.md if missing. Safe in PLAN mode (writes only the session notepad).',
22
+ description: `Record and update the session execution plan in notes.md. ${PLAN_USAGE_GUIDANCE} ` +
23
+ 'REPLACES the whole plan each call — always pass the full steps array. At most one step in_progress; mark a step completed as soon as its work is done. Each step needs a short title (≤20 chars) and self-contained content. All steps completed → auto-settles to `## Done:`. Safe in PLAN mode (writes only the session notepad).',
22
24
  risk: 'safe',
23
25
  parameters: {
24
26
  type: 'object',
@@ -44,7 +46,7 @@ export const planUpdateTool = {
44
46
  },
45
47
  content: {
46
48
  type: 'string',
47
- description: 'Self-contained step: target file/symbol, the change, and how to verify it.',
49
+ description: 'Self-contained step: target file/symbol and the change. Add the check only when the step deserves one — small local edits need none.',
48
50
  },
49
51
  status: {
50
52
  type: 'string',