@hncode/hncode 0.8.1 → 0.8.3

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 (52) hide show
  1. package/README.md +18 -0
  2. package/README_CN.md +14 -0
  3. package/bin/hncode +54 -8
  4. package/package.json +1 -1
  5. package/src/agent-task.js +356 -337
  6. package/src/agent.js +1465 -1405
  7. package/src/animate.js +56 -0
  8. package/src/colors.js +615 -593
  9. package/src/config.js +50 -7
  10. package/src/context-bar.js +280 -278
  11. package/src/doctor.js +4 -3
  12. package/src/file-tree.js +4 -3
  13. package/src/highlight.js +20 -6
  14. package/src/i18n.js +1432 -389
  15. package/src/image-row.js +11 -2
  16. package/src/index.js +218 -6
  17. package/src/keybindings.js +2 -1
  18. package/src/llm.js +146 -21
  19. package/src/log-file.js +112 -0
  20. package/src/markdown.js +646 -567
  21. package/src/mcp-server.js +409 -0
  22. package/src/mcp.js +279 -29
  23. package/src/memory-profile.js +19 -16
  24. package/src/migrate-index.js +175 -0
  25. package/src/migrate.js +392 -0
  26. package/src/panels.js +9 -7
  27. package/src/plan.js +7 -5
  28. package/src/plugin.js +37 -21
  29. package/src/registry-browser.js +17 -15
  30. package/src/rows-plan-bg.js +3 -2
  31. package/src/rows-status.js +20 -6
  32. package/src/rows-tool-result.js +242 -208
  33. package/src/screen-paint.js +153 -128
  34. package/src/session-recover.js +317 -0
  35. package/src/session.js +203 -13
  36. package/src/settings-schema.js +9 -0
  37. package/src/swarm-progress.js +6 -2
  38. package/src/tasks-browser.js +37 -36
  39. package/src/team-panel.js +12 -11
  40. package/src/term.js +57 -21
  41. package/src/text.js +254 -149
  42. package/src/tool-line.js +7 -2
  43. package/src/tool-result.js +400 -327
  44. package/src/tools/agent.js +7 -2
  45. package/src/tools/ask-user-question.js +1 -2
  46. package/src/tools/bash.js +446 -434
  47. package/src/tools/edit.js +653 -665
  48. package/src/tools/goal.js +130 -93
  49. package/src/tools/read.js +141 -133
  50. package/src/tools/tasks.js +214 -214
  51. package/src/tools/utils.js +143 -104
  52. package/src/tui.js +20887 -19942
package/src/tools/edit.js CHANGED
@@ -1,665 +1,653 @@
1
- // Edit tool — mirrors the hncode Edit tool schema & behavior.
2
- // Snippet-based exact replacement (old_string -> new_string), NOT a whole-file rewrite,
3
- // so edits stay token-cheap (unlike kimi-code-cli's whole-file Edit).
4
-
5
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import { resolvePath, ensureDir, checkpointBeforeWrite } from './utils.js';
8
- import { hashStr, normalizeText } from './read.js';
9
-
10
- // Typographic quotes -> straight quotes. A model almost always emits ASCII
11
- // quotes, but docs/blog/markdown often use curly ones; without this the edit
12
- // fails with "old_string not found" even though the text is visibly there.
13
- // Mirrors Claude Code's normalizeQuotes.
14
- const CURLY = [
15
- ['\u2018', "'"], ['\u2019', "'"], // ‘ ’
16
- ['\u201c', '"'], ['\u201d', '"'], // “ ”
17
- ];
18
- export function normalizeQuotes(s) {
19
- let out = String(s);
20
- for (const [from, to] of CURLY) out = out.split(from).join(to);
21
- return out;
22
- }
23
-
24
- // Re-exported from read.js so the staleness guard has ONE definition of the
25
- // region hash. Previously read.js and edit.js each had their own copy; any
26
- // drift between them would silently disable staleness detection.
27
- import { hashRegion as hashLines } from './read.js';
28
-
29
- export const spec = {
30
- name: 'Edit',
31
- description: `Edit a file. Three shapes: LINE-RANGE (path + start_line + end_line + new_string),
32
- SUBSTRING (path + old_string + new_string, unique unless replace_all), RANGED SUBSTRING (the same plus
33
- start_line + end_line, which narrows where old_string is searched).
34
-
35
- BOTH BOUNDS ARE INCLUSIVE: start_line=3, end_line=5 covers lines 3, 4 and 5 — three lines, so new_string must
36
- have exactly three lines.
37
-
38
- TO DELETE, SEND AN EMPTY new_string. start_line=7, end_line=7 with new_string="" removes line 7 and nothing
39
- else. That is the ONLY correct way to delete. Restating the next line as the replacement COPIES it, the file
40
- then holds that line twice, and because the duplicate looks like damage the retry restates another neighbour —
41
- the duplicates multiply. Never copy a neighbouring line into new_string to stand in for deleting.
42
-
43
- new_string is written VERBATIM — no indentation is added, removed or re-derived. Every line carries its own
44
- leading whitespace, the FIRST one included; copy it from the Read output after the tab that follows each line
45
- number (Read prints '12' then a tab, then the indented code, so you send the leading spaces yourself).
46
-
47
- COUNT FIRST: in line-range mode new_string must have exactly end_line - start_line + 1 lines, and every line
48
- you write must be one you are replacing. A line outside the range is not deleted and survives as a duplicate.
49
-
50
- Omitting new_string entirely is an error — pass "" to delete.
51
-
52
- AFTER A SUCCESSFUL EDIT, the result quotes the file around what you wrote — five lines either side, in the same
53
- numbered form Read uses. So editing a region you have just edited does NOT need another Read of it: the previous
54
- Edit already shows you those lines as they are on disk now. Read again when you need a part of the file the edit
55
- did not show, or when a different tool or the user has changed the file since.`,
56
- parameters: {
57
- type: 'object',
58
- properties: {
59
- path: { type: 'string', description: 'Path to the file to edit.' },
60
- old_string: { type: 'string', description: 'Exact text to replace, including whitespace and newlines. Omit for pure line-range mode. COMBINE it with start_line/end_line to replace only the occurrence inside that range.' },
61
- new_string: { type: 'string', description: 'Replacement text, written VERBATIM in BOTH modes — no indentation is added, removed, or re-derived. Write the leading spaces on EVERY line yourself, including the FIRST one, copying them from the Read output after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`). In LINE-RANGE mode it must contain EXACTLY the lines being replaced: a line that sits outside [start_line, end_line] is not deleted, so restating it here leaves a duplicate. Count them first: new_string must have exactly end_line - start_line + 1 lines. In SUBSTRING mode it replaces old_string, which is itself matched exactly including its own indentation.' },
62
-
63
- replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string.' },
64
- start_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based first line to replace, INCLUSIVE — the range covers start_line and end_line and every line between them. Requires end_line and new_string. With old_string too, it is the first line to SEARCH for it in.' },
65
- end_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based last line to replace, INCLUSIVE (requires start_line). start_line=3, end_line=5 replaces lines 3, 4 AND 5 — three lines, so new_string must have three lines. If your new_string has four, one of them is outside the range and will survive as a duplicate. With old_string too, it is the last line to search in.' },
66
- },
67
- // Three accepted shapes:
68
- // line-range start_line + end_line + new_string
69
- // exact-substring old_string + new_string
70
- // rangedToWindow-substring start_line + end_line + old_string + new_string
71
- // Line-range is the preferred route; the third exists for "one of several copies".
72
- anyOf: [
73
- { required: ['path', 'start_line', 'end_line', 'new_string'] },
74
- { required: ['path', 'old_string', 'new_string'] },
75
- ],
76
- },
77
- async execute(args, ctx) {
78
- // Validate BEFORE resolving the path. `resolvePath(undefined)` resolves to the
79
- // workspace root rather than failing, so a truncated tool call (agent.js falls
80
- // back to `{ raw, _rawLen }` when the streamed JSON will not parse) could
81
- // target a DIRECTORY and produce a confusing EISDIR/ENOENT instead of "retry
82
- // the call".
83
- if (typeof args.path !== 'string' || !args.path.trim()) {
84
- const truncated = args && args.raw
85
- ? ` The arguments did not parse as JSON${args._rawLen ? ` (${args._rawLen} characters received)` : ''} — the call was most likely truncated. Retry, and keep \`old_string\` / \`new_string\` small (edit in several passes rather than one large replacement).`
86
- : '';
87
- return `Error: \`path\` is required and must be a non-empty string.${truncated}`;
88
- }
89
- let p;
90
- try { p = resolvePath(args.path, ctx); } catch (e) { return e.message; }
91
- // A Jupyter notebook is JSON, not text: a snippet edit corrupts it. Point the
92
- // model at the notebook-aware tool instead (mirrors Claude Code errorCode 5).
93
- if (String(p).toLowerCase().endsWith('.ipynb')) {
94
- return `Error: ${args.path} is a Jupyter notebook, and its .ipynb is JSON — a text replacement would corrupt it. Use NotebookEdit instead: \`{ path: ${JSON.stringify(args.path)}, action: "list" }\` to see the cells, then action "replace" with the cell index.`;
95
- }
96
- let content;
97
- try {
98
- content = fs.readFileSync(p, 'utf8');
99
- } catch (e) {
100
- if (e && e.code === 'ENOENT') {
101
- return `Error reading ${args.path}: file does not exist.${similarFileHint(p)}`;
102
- }
103
- return `Error reading ${args.path}: ${e.message}`;
104
- }
105
- const { start_line, end_line } = args;
106
- // THREE shapes, not two.
107
- //
108
- // line-range start_line + end_line + new_string
109
- // substring old_string + new_string
110
- // RANGED SUB start_line + end_line + old_string + new_string
111
- //
112
- // The third is what the first two cannot express: replace ONE occurrence of a snippet that
113
- // appears several times, without `replace_all` (which would hit every copy) and without
114
- // counting lines by hand. The range narrows WHERE to look; `old_string` says WHAT to replace
115
- // inside it. Rejecting the combination sent callers to `replace_all` as their only option,
116
- // which is how the wrong copy gets edited.
117
- //
118
- // `old_string` alongside a range is therefore not a mistake — but a range with NEITHER
119
- // old_string nor new_string still is, and is reported below.
120
- const hasRangeKeys = args.start_line != null || args.end_line != null;
121
- const hasSubKeys = args.old_string != null;
122
- const hasNewString = (args.new_string != null) || (args.new_content != null);
123
- if (hasRangeKeys && hasSubKeys && !hasNewString) {
124
- return 'Error: a rangedToWindow edit needs new_string as well as old_string.';
125
- }
126
-
127
- // ---- RANGED SUBSTRING ---------------------------------------------------
128
- // A range AND an old_string: search for the snippet only INSIDE the range. Handled here,
129
- // before the pure line-range path, because that path replaces whole lines and would ignore
130
- // the snippet entirely — the very ambiguity the old mutual-exclusion check was avoiding.
131
- //
132
- // The range is validated, then the substring path below does the matching with the search
133
- // window clamped to it. Splitting the work this way keeps ONE implementation of matching
134
- // (quote-normalized retry, staleness, whitespace tolerance) instead of a second, weaker copy.
135
- // A HALF-GIVEN RANGE with an old_string is not a reason to refuse: the snippet locates the
136
- // edit by itself, and the single bound is a hint that failed to pair. Callers add `start_line`
137
- // from the schema's own wording ("1-based first line to replace") expecting it to help, so
138
- // refusing rejected a request that was already complete.
139
- //
140
- // `rangedToWindow` is set even though no window is applied. It means "the range question has been
141
- // settled", which is what the line-range guard below tests — leaving it false made that guard
142
- // see the same unpaired bound and reject the call one block later.
143
- let searchFrom = 0;
144
- let searchTo = 0; // 0,0 = the whole file
145
- // A real window was validated, so the search below is confined to it. Distinct from
146
- // `rangeHandled`: this one means "clamp", and setting it for a snippet with no window made
147
- // every search run inside 0..0 and find nothing.
148
- let rangedToWindow = false;
149
- // The range question is answered — either a window was applied, or the caller gave an
150
- // `old_string` that locates the edit on its own and a half-given bound was ignored.
151
- let rangeHandled = hasSubKeys;
152
- if (hasRangeKeys && hasSubKeys && hasNewString) {
153
- if ((start_line != null) !== (end_line != null)) {
154
- // Ignore the unpaired bound; `searchFrom`/`searchTo` stay at the whole file and `rangedToWindow`
155
- // was already set above.
156
- searchFrom = 0;
157
- searchTo = 0;
158
- } else {
159
- // The range was given in full: validate it, then confine the search to it.
160
- const start = Number(start_line) | 0, end = Number(end_line) | 0;
161
- if (!Number.isFinite(start) || !Number.isFinite(end) || start < 1 || end < start) {
162
- return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
163
- }
164
- {
165
- const all = content.split(/\r\n|\r|\n/);
166
- if (end > all.length) {
167
- return `Error: end_line ${end_line} exceeds file length (${all.length} lines).`;
168
- }
169
- }
170
- rangedToWindow = true;
171
- rangeHandled = true;
172
- searchFrom = start;
173
- searchTo = end;
174
- }
175
- }
176
-
177
- // ---- LINE-RANGE mode ---------------------------------------------------
178
- // `start_line`..`end_line` replace the lines at those 1-based positions,
179
- // with NO old_string involved at all. This is the path for "change line 12"
180
- // where spelling out the exact current text is awkward.
181
- if (!rangeHandled && (start_line != null) !== (end_line != null)) {
182
- return 'Error: line-range mode needs BOTH start_line and end_line.';
183
- }
184
- if (!rangeHandled && start_line != null && end_line != null) {
185
- // Accept both spellings so old new_content callers keep working.
186
- const new_string = args.new_string != null ? args.new_string : args.new_content;
187
- // new_string is required — a missing one would put the literal string
188
- // "undefined" in the file.
189
- if (new_string == null) return `Error: new_string is required for line-range mode (pass an empty string to delete the lines).`;
190
- if (typeof new_string !== 'string') {
191
- return `Error: new_string must be a string (got ${new_string === null ? 'null' : typeof new_string}).`;
192
- }
193
- const start = Number(start_line) | 0, end = Number(end_line) | 0;
194
- if (start < 1 || end < start) {
195
- return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
196
- }
197
- const eol = content.includes('\r\n') ? '\r\n' : '\n';
198
- const lines = content.split(/\r\n|\r|\n/);
199
- if (end > lines.length) {
200
- return `Error: end_line ${end_line} exceeds file length (${lines.length} lines).`;
201
- }
202
- // STALENESS: the range must sit inside a region this turn actually Read and
203
- // that still matches. Same guarantee as the substring path, checked here
204
- // directly (no old_string to search for).
205
- const stale = checkStaleRange(p, lines, start, end, ctx);
206
- if (stale) return stale;
207
-
208
- // AN EMPTY new_string DELETES THE RANGE. No line survives, so the replacement is nothing at all.
209
- //
210
- // `''.split('\n')` is `['']` — ONE EMPTY STRING — not an empty array. The splice therefore replaced the
211
- // range with a single blank line, so "delete these lines" left a hole and shifted everything below it.
212
- // Deleting has to mean deleting: when there is no replacement text, the range is removed outright.
213
- //
214
- // This is also the answer to the mistake that keeps appearing in edits: to remove one line, send an EMPTY
215
- // new_string over that one line. Restating the neighbour instead copies it, and the file ends up with the
216
- // line twice — the duplicate is a symptom of having no delete, not of carelessness.
217
- const inserted = new_string === '' ? [] : normalizeText(new_string).split('\n');
218
-
219
- // The lines being REPLACED, captured before the splice. The TUI renders an Edit's diff from the tool
220
- // ARGUMENTS, and line-range mode has no `old_string` to diff against — so without reporting them here the
221
- // edit drew NO diff at all.
222
- const replacedText = lines.slice(start - 1, end).join('\n');
223
- const out = [...lines.slice(0, start - 1), ...inserted, ...lines.slice(end)];
224
- const normUpdated = out.join('\n');
225
- const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
226
-
227
- // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
228
- checkpointBeforeWrite(p, ctx);
229
- try {
230
- ensureDir(p);
231
- fs.writeFileSync(p, updated, 'utf8');
232
- } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
233
- // The returned excerpt is read from disk after the write. Refresh the snapshot for precisely those returned
234
- // lines, so a follow-up edit inside the excerpt needs no separate Read; regions outside it remain untrusted.
235
- const removed = end - start + 1;
236
- if (ctx) ctx.lastEditDiff = buildEditDiff({ fileLines: lines, oldText: replacedText, newText: inserted.join('\n'), startLine: start, filePath: p });
237
- const written = Math.max(1, inserted.length);
238
- const excerpt = readAfterEdit(p, start, written, ctx);
239
- return `Edited ${args.path}: replaced lines ${start}-${end} (${removed} line${removed === 1 ? '' : 's'}) with ${inserted.length} line${inserted.length === 1 ? '' : 's'}.\n\n${excerpt}`.trimEnd();
240
- }
241
-
242
- // ---- SUBSTRING mode (old_string -> new_string) --------------------------
243
- // `new_content` is accepted as an alias of `new_string` — the validation above
244
- // already counts it, so refusing it here sent a confusing "new_string is
245
- // required" for an argument the mode's own checks accepted.
246
- let { old_string, new_string, replace_all = false } = args;
247
- if (new_string == null && args.new_content != null) new_string = args.new_content;
248
- // Reaching here means neither mode was usable: line-range needs
249
- // start_line+end_line (handled above) and substring needs old_string. When
250
- // BOTH are absent, say so — "old_string must not be empty" sends the model
251
- // hunting for a stray empty string it never sent.
252
- if (old_string == null && new_string == null) {
253
- return 'Error: no edit mode given. Pass EITHER (start_line, end_line, new_string) OR (old_string, new_string).';
254
- }
255
- if (old_string === '' || old_string == null) return `Error: old_string must not be empty.`;
256
- if (new_string == null) return `Error: new_string is required for substring mode.`;
257
-
258
- // --- Newline normalization (Windows CRLF) ---
259
- // The Read tool normalizes \r\n -> \n, so an agent builds old_string/new_string
260
- // with LF. But the file on disk may be CRLF, making a raw LF match fail. We
261
- // normalize the FILE content to LF for matching, then restore the file's own
262
- // line ending style when writing back, so we never corrupt or mix endings.
263
- const eol = content.includes('\r\n') ? '\r\n' : '\n';
264
- const normContent = content.split(/\r\n|\r|\n/).join('\n');
265
- const normOld = normalizeText(old_string);
266
- const normNew = normalizeText(new_string);
267
-
268
- // A RANGED edit searches only inside the given lines. `windowStart` is the character offset of
269
- // the range's first line in `normContent`, and `windowEnd` the end of its last line; the whole
270
- // file is the window when no range was given. Every match, count and replacement below uses
271
- // this window, so a snippet that appears elsewhere in the file is neither found nor touched —
272
- // which is the entire point, and what `replace_all` cannot express.
273
- let windowStart = 0;
274
- let windowEnd = normContent.length;
275
- if (rangedToWindow) {
276
- const allLines = normContent.split('\n');
277
- // Offset of line N's first character: the sum of the lengths of lines 1..N-1 plus their
278
- // newlines. Computed by walking, because a single `indexOf` would find the wrong copy of a
279
- // line that also occurs earlier in the file.
280
- const offsetOfLine = (n) => {
281
- let at = 0;
282
- for (let i = 0; i < n - 1 && i < allLines.length; i++) at += allLines[i].length + 1;
283
- return at;
284
- };
285
- windowStart = offsetOfLine(searchFrom);
286
- const lastLineStart = offsetOfLine(searchTo);
287
- windowEnd = Math.min(normContent.length, lastLineStart + (allLines[searchTo - 1] || '').length);
288
- }
289
- /** Occurrences of `needle` inside the window. */
290
- const countInWindow = (needle) => {
291
- if (!needle) return 0;
292
- const seg = normContent.slice(windowStart, windowEnd);
293
- return seg.split(needle).length - 1;
294
- };
295
-
296
- let matchOld = normOld; // the string that will actually be matched/replaced
297
- let matchNew = normNew;
298
- let count = countInWindow(matchOld);
299
- if (count === 0) {
300
- // Quote-normalized retry: the file may use curly quotes while the model sent
301
- // straight ones. Match on the normalized forms, then replace the ACTUAL
302
- // substring found in the file so typography is preserved. normalizeQuotes is
303
- // 1 char -> 1 char, so indices line up between the two strings.
304
- const normFileQ = normalizeQuotes(normContent);
305
- if (normFileQ !== normContent) {
306
- const normOldQ = normalizeQuotes(normOld);
307
- // Search the NORMALIZED window for the normalized snippet, then take the real text at
308
- // that place so the replacement keeps the file's own typography.
309
- const idx = normFileQ.indexOf(normOldQ, windowStart);
310
- if (idx >= 0 && idx + normOldQ.length <= windowEnd) {
311
- matchOld = normContent.slice(idx, idx + normOldQ.length);
312
- matchNew = normNew; // keep the model's new_string as written
313
- count = countInWindow(matchOld);
314
- }
315
- }
316
- }
317
- if (count === 0) {
318
- if (rangedToWindow) {
319
- // Say WHERE it was looked for, so a snippet that exists elsewhere is not reported as
320
- // missing outright — that sends the caller hunting for a typo that is not there.
321
- const elsewhere = normContent.split(normOld).length - 1;
322
- const hint = elsewhere
323
- ? ` It appears ${elsewhere} time(s) elsewhere in the file, outside lines ${searchFrom}-${searchTo}. Broaden the range, or correct the range.`
324
- : '';
325
- return `Error: old_string not found within lines ${searchFrom}-${searchTo} of ${args.path}.${hint}`;
326
- }
327
- const near = nearestLineHint(normContent, normOld);
328
- return `Error: old_string not found in ${args.path}.${near}`;
329
- }
330
- if (count > 1 && !replace_all) {
331
- if (rangedToWindow) {
332
- return `Error: old_string matched ${count} occurrences within lines ${searchFrom}-${searchTo} of ${args.path}. Narrow the range, or use replace_all=true to change all of them.`;
333
- }
334
- return `Error: old_string matched ${count} occurrences in ${args.path}. Use replace_all=true or make old_string unique.`;
335
- }
336
- // --- Staleness guard: the AI must edit against content it actually Read.
337
- // We stored per-region + whole-file hashes in ctx.readPool when Read ran.
338
- // If the file changed on disk since (external edit, stream, Ctrl-C side
339
- // effect), reject so a snippet edit cannot silently corrupt the file. ---
340
- const stale = checkStale(p, normContent, matchOld, ctx);
341
- if (stale) return stale;
342
-
343
- // Replace INSIDE the window only. A rangedToWindow edit must not touch an identical snippet sitting
344
- // before or after the range — replacing across the whole file is the failure the range exists
345
- // to prevent. With no range the window IS the whole file, so non-rangedToWindow callers are unchanged.
346
- //
347
- // The replacement is passed as a FUNCTION: a string second argument makes JS interpret
348
- // `$&`, `` $` ``, `$'` and `$$` in the NEW text, so an edit whose new_string contains them
349
- // (regex examples, Makefile `$$`, shell code) silently wrote the wrong file.
350
- const normUpdated = (() => {
351
- const head = normContent.slice(0, windowStart);
352
- const body = normContent.slice(windowStart, windowEnd);
353
- const tail = normContent.slice(windowEnd);
354
- const literal = () => matchNew;
355
- return head + (replace_all ? body.replaceAll(matchOld, literal) : body.replace(matchOld, literal)) + tail;
356
- })();
357
- // The replaced text's actual character offset in normContent (first occurrence
358
- // inside the window — guaranteed >= 0, the count above found it). Everything
359
- // before the match is unchanged, so this one offset anchors BOTH the diff and
360
- // the Read-pool re-arm below to the real edit site. Locating the site by
361
- // matching its first LINE (the old approach) collapsed to line 1 when
362
- // old_string starts mid-line, and pointed at an earlier copy when the file
363
- // repeats that line — the diff then drew context from the top of the file.
364
- const matchAt = normContent.indexOf(matchOld, windowStart);
365
- const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
366
- // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
367
- checkpointBeforeWrite(p, ctx);
368
- try {
369
- ensureDir(p);
370
- fs.writeFileSync(p, updated, 'utf8');
371
- } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
372
- // Only the post-edit excerpt returned below refreshes the Read snapshot. An unrelated part of the file is not
373
- // made trusted merely because this replacement succeeded.
374
- const occurrences = replace_all ? count : 1;
375
- // Publish the diff for the UI (same contract as the line-range path above).
376
- // `startLine` comes from the actual match offset, so a snippet that starts
377
- // mid-line or a file with repeated lines still anchors the context rows at
378
- // the place that was really edited.
379
- if (ctx) {
380
- const startLine = matchAt >= 0 ? normContent.slice(0, matchAt).split('\n').length : 1;
381
- ctx.lastEditDiff = buildEditDiff({
382
- fileLines: normContent.split('\n'),
383
- oldText: old_string,
384
- newText: new_string,
385
- startLine,
386
- filePath: p,
387
- });
388
- }
389
- // Quote the result the same way the line-range path does, so neither mode leaves the model guessing.
390
- const editedAt = matchAt >= 0 ? normContent.slice(0, matchAt).split('\n').length : 1;
391
- // replace_all may change distant copies too. One excerpt cannot vouch for them, so do not authorize another
392
- // edit based on an incomplete view; the caller must Read the desired region after a bulk replacement.
393
- const writtenLines = normalizeText(new_string).split('\n').length;
394
- const excerpt = readAfterEdit(p, editedAt, writtenLines, replace_all ? null : ctx);
395
- if (replace_all && ctx && ctx.readPool) ctx.readPool.delete(p);
396
- return `Edited ${args.path}: replaced ${occurrences} occurrence(s).\n\n${excerpt}`.trimEnd();
397
- },
398
- };
399
-
400
- /** How many unchanged lines to show on each side of a changed region. */
401
- const DIFF_CONTEXT = 5;
402
-
403
-
404
-
405
- /** The line's leading whitespace, for the same-indent closer rule. */
406
- function leadingWs(s) {
407
- const m = /^\s*/.exec(String(s == null ? '' : s));
408
- return m ? m[0] : '';
409
- }
410
-
411
-
412
- /**
413
- * Build the diff payload, including the unchanged lines around the change.
414
- *
415
- * The replaced lines alone do not tell a reader WHERE the edit landed: a four-line block quoted with no
416
- * surroundings could be anywhere in a 500-line file, so neither the model nor the user could tell a
417
- * correct edit from one applied at the right text in the wrong place — and with repeated code (several
418
- * similar blocks, two `}` in a row) the same text appears in many places.
419
- *
420
- * `context` carries the file's own lines so the renderer can draw them unmarked, above and below.
421
- *
422
- * `fileLines` is the content BEFORE the edit, for the replaced region's START LINE to be meaningful:
423
- * `startLine` is a line number in that same file.
424
- */
425
- /** How many lines of the file to show on each side of a freshly edited region. */
426
- const READ_AFTER_CONTEXT = 5;
427
-
428
- /**
429
- * The file around the region an edit just wrote, in the same `N<TAB>text` form the Read tool uses.
430
- *
431
- * WHY THE EDIT RETURNS IT: the result used to be one sentence — "replaced lines 5-7" — which tells the model what
432
- * it asked for but not what the file now says. Every follow-up edit therefore began with a Read of the same lines,
433
- * a whole round trip whose only purpose was to learn something the edit already knew.
434
- *
435
- * The excerpt is read from disk after the write, then precisely that region is registered in the Read pool. This
436
- * makes the advertised "no second Read" path real without trusting the edit arguments or any unseen file region.
437
- *
438
- * Returns '' when the post-write read fails, leaving the old snapshot unchanged.
439
- */
440
- function readAfterEdit(filePath, firstLine, lineCount, ctx) {
441
- let text;
442
- try { text = fs.readFileSync(filePath, 'utf8'); } catch { return ''; }
443
- const lines = normalizeText(text).split('\n');
444
- if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
445
- const total = lines.length;
446
- const start = Math.max(1, firstLine - READ_AFTER_CONTEXT);
447
- const end = Math.min(total, firstLine + Math.max(1, lineCount) - 1 + READ_AFTER_CONTEXT);
448
- if (ctx && ctx.readPool) {
449
- // The file changed, so every older region for this path is invalid; only the lines actually returned below
450
- // may authorize a follow-up edit. Keep the same normalized hashing convention as Read.
451
- ctx.readPool.set(filePath, {
452
- fileHash: hashStr(text), lines: total,
453
- regions: [{ start, end, hash: hashLines(lines, start, end) }],
454
- });
455
- }
456
- const out = [];
457
- for (let i = start; i <= end; i++) out.push(`${i}\t${lines[i - 1]}`);
458
- return out.join('\n');
459
- }
460
-
461
- function buildEditDiff({ fileLines, oldText, newText, startLine, filePath }) {
462
- const lines = Array.isArray(fileLines) ? fileLines : [];
463
- const before = [];
464
- const after = [];
465
- const replacedCount = normalizeText(oldText).split('\n').length;
466
- // `startLine` is 1-based; the replaced block occupies [startLine, startLine + n - 1].
467
- const lastReplaced = startLine + replacedCount - 1;
468
- for (let n = startLine - DIFF_CONTEXT; n < startLine; n++) {
469
- if (n >= 1 && n <= lines.length) before.push({ n, text: lines[n - 1] });
470
- }
471
- // The AFTER context is drawn from the file BEFORE the edit, but its line numbers must describe the file
472
- // AFTER it — that is the file a reader has open when they read the diff.
473
- //
474
- // Using the pre-edit numbers looked right for a same-size replacement and drifted by one per added line
475
- // otherwise: an edit that grew the file by three shifted every context row, so the diff showed line
476
- // numbers that did not exist where it claimed, or repeated ones that did.
477
- //
478
- // `net` is the number of lines the edit added (negative when it shrank the file), so every line below
479
- // the replaced block moves by exactly that much.
480
- // AN EMPTY REPLACEMENT IS ZERO LINES, NOT ONE. `''.split('\n')` is `['']`, so a deletion counted itself as
481
- // a one-line replacement and `net` came out 0 instead of -1 — the AFTER context was then numbered as if
482
- // nothing had been removed, and the diff carried a phantom `+` row holding an empty string, which reads as an
483
- // insertion where the file in fact lost a line.
484
- const newLines = normalizeText(newText) === '' ? [] : normalizeText(newText).split('\n');
485
- const net = newLines.length - replacedCount;
486
- for (let n = lastReplaced + 1; n <= lastReplaced + DIFF_CONTEXT; n++) {
487
- if (n >= 1 && n <= lines.length) after.push({ n: n + net, text: lines[n - 1] });
488
- }
489
- return {
490
- old: normalizeText(oldText),
491
- new: normalizeText(newText),
492
- startLine,
493
- // The file the change belongs to, so the viewer can pick a syntax highlighter from its extension. Without it
494
- // the diff had no way to know whether it was looking at JavaScript or a Makefile.
495
- path: filePath || '',
496
- context: { before, after },
497
- };
498
- }
499
-
500
- // Suggest a near-miss filename when a path does not exist: same directory, an
501
- // exact case-insensitive match, same stem with a different extension, or a
502
- // prefix match. Saves the model a round-trip of guessing (Claude Code's
503
- // "Did you mean X?").
504
- function similarFileHint(missingPath) {
505
- const dir = path.dirname(missingPath);
506
- const base = path.basename(missingPath);
507
- const stem = base.replace(/\.[^.]*$/, '').toLowerCase();
508
- let entries;
509
- try { entries = fs.readdirSync(dir); } catch { return ''; }
510
- const lower = base.toLowerCase();
511
- // Levenshtein distance, capped — enough to catch a typo (confg -> config).
512
- const lev = (a, b) => {
513
- const m = a.length, n = b.length;
514
- if (Math.abs(m - n) > 2) return 3;
515
- let prev = Array.from({ length: n + 1 }, (_, j) => j);
516
- for (let i = 1; i <= m; i++) {
517
- const cur = [i];
518
- for (let j = 1; j <= n; j++) {
519
- cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
520
- }
521
- prev = cur;
522
- }
523
- return prev[n];
524
- };
525
- let cand = entries.find((e) => e.toLowerCase() === lower);
526
- if (!cand) {
527
- let best = null, bestD = 3;
528
- for (const e of entries) {
529
- const d = lev(stem, e.replace(/\.[^.]*$/, '').toLowerCase());
530
- if (d < bestD) { bestD = d; best = e; }
531
- }
532
- cand = best;
533
- }
534
- if (cand && cand !== base) return ` Did you mean "${path.join(dir, cand)}"?`;
535
- return '';
536
- }
537
-
538
- // When old_string is not found, look for the closest line in the file and name
539
- // it, so the model can see what the text actually is instead of guessing.
540
- function nearestLineHint(content, oldStr) {
541
- const want = String(oldStr).split('\n')[0].trim();
542
- if (!want || want.length < 3) return '';
543
- const lines = String(content).split('\n');
544
- // Character bigrams: robust to small differences and cheap on long lines.
545
- const grams = (s) => {
546
- const set = new Set();
547
- for (let i = 0; i + 1 < s.length; i++) set.add(s.slice(i, i + 2));
548
- return set;
549
- };
550
- const wantGrams = grams(want);
551
- if (!wantGrams.size) return '';
552
- let best = -1, bestScore = 0;
553
- for (let i = 0; i < lines.length; i++) {
554
- const g = grams(lines[i].trim());
555
- if (!g.size) continue;
556
- let hit = 0;
557
- for (const t of wantGrams) if (g.has(t)) hit++;
558
- const score = hit / wantGrams.size;
559
- if (score > bestScore) { bestScore = score; best = i; }
560
- }
561
- if (best >= 0 && bestScore >= 0.5) {
562
- return ` The closest line is line ${best + 1}: ${JSON.stringify(lines[best].trim().slice(0, 120))}`;
563
- }
564
- return '';
565
- }
566
-
567
- // Returns an error message when the edit is stale, else null (safe to edit).
568
- function checkStale(p, normContent, normOld, ctx) {
569
- if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
570
- const entry = ctx.readPool.get(p);
571
- if (!entry) return null; // this file was never Read this turn; allow
572
-
573
- const curLines = normContent.split('\n');
574
- const curFileHash = hashStr(normContent);
575
-
576
- // Locate the edit target's first line in the CURRENT file (1-based).
577
- //
578
- // An EXACT line match first, then a line that merely CONTAINS it. The exact match alone
579
- // missed every edit whose `old_string` begins mid-line — `old_string: "return 1;"` against
580
- // a line ` return 1;` found nothing, so `editLine` was -1 and step (1) below was skipped
581
- // entirely: the edit was then reported as stale (branch 2) or, with the whole-file hash
582
- // also differing, rejected as though the file had changed. Two-line `old_string`s are the
583
- // common case for a range edit, and their first line usually IS whole, which is why this
584
- // only showed up on single-line and indented-prefix edits.
585
- const firstLine = String(normOld).split('\n')[0];
586
- let idx = curLines.indexOf(firstLine);
587
- if (idx < 0 && firstLine) idx = curLines.findIndex((l) => l.includes(firstLine));
588
- const editLine = idx >= 0 ? idx + 1 : -1;
589
-
590
- // (1) The edit target must sit inside a region the AI actually Read, and that
591
- // region's content must still match what was Read. Reading the WHOLE file
592
- // records a region covering every line, so this also covers "read full,
593
- // edit a part". This is what rejects "read lines 1-3, edit line 7".
594
- if (editLine > 0) {
595
- const coveredByIntactRegion = entry.regions.some(
596
- (r) => editLine >= r.start && editLine <= r.end && hashLines(curLines, r.start, r.end) === r.hash,
597
- );
598
- if (coveredByIntactRegion) return null;
599
- }
600
-
601
- // (2) Whole file unchanged since Read, but the edit target was never Read
602
- // (no region covers it). Name the exact lines so the model reads the right
603
- // window instead of guessing.
604
- if (curFileHash === entry.fileHash) {
605
- const span = String(normOld).split('\n').length;
606
- const at = editLine > 0 ? editLine : 1;
607
- return `Edit rejected: you have not read the lines you are editing in ${p}. The target is around line ${at} (${span} line${span === 1 ? '' : 's'}). Read it first — ${args_readHint(p, at, span)} — then Edit.`;
608
- }
609
-
610
- // (3) The file changed on disk since it was Read and the edit target is not in
611
- // an intact Read region. Reject so a stale snippet cannot corrupt the file.
612
- const at3 = editLine > 0 ? ` (target line ${editLine})` : '';
613
- return `Edit rejected: ${p} changed since it was Read${at3}, and the edited region is not in an intact Read snapshot. Re-run ${args_readHint(p, editLine > 0 ? editLine : 1, String(normOld).split('\n').length)} to get the current content, then Edit.`;
614
- }
615
-
616
- // A ready-to-use Read call for the hint. Keeps the model from guessing line ranges.
617
- function args_readHint(p, at, span) {
618
- const from = Math.max(1, at - 3);
619
- const n = Math.max(span + 6, 10);
620
- return `Read { path: ${JSON.stringify(p)}, start_line: ${from}, end_line: ${from + n - 1} }`;
621
- }
622
- // ---- helpers for the line-range path ---------------------------------------
623
-
624
- // Same guarantee as checkStale, but for an explicit [start, end] line range:
625
- // every line in the range must sit inside a region that was Read this turn and
626
- // whose content still matches. Returns an error string, or null when safe.
627
- function checkStaleRange(p, curLines, start, end, ctx) {
628
- if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
629
- const entry = ctx.readPool.get(p);
630
- if (!entry) return null; // never Read this turn; allow
631
-
632
- const normContent = curLines.join('\n');
633
- const curFileHash = hashStr(normContent);
634
-
635
- // A range is "read" when the regions the model has SEEN cover it — not only when
636
- // a single region spans it. A file read in two passes (5-10 then 11-16) must
637
- // allow editing 5-16: the two slices are contiguous, both still intact, so the
638
- // written range is fully known. Requiring one enclosing region rejected that
639
- // perfectly safe edit and forced a third Read.
640
- //
641
- // Only regions whose hash STILL matches count: a region whose text changed is no
642
- // longer what the model saw, so it cannot vouch for anything. The cover must also
643
- // be SEAMLESS — a gap (5-10 and 12-16 with 11 unread) leaves 11 unknown, so it
644
- // does NOT count, and the edit is correctly refused.
645
- const intact = entry.regions
646
- .filter((r) => hashLines(curLines, r.start, r.end) === r.hash)
647
- .sort((a, b) => a.start - b.start);
648
- let reach = start - 1; // highest line known to be covered
649
- for (const r of intact) {
650
- if (r.end < start) continue; // entirely before the target
651
- if (r.start > reach + 1) break; // a gap opens before this region: stop
652
- if (r.end > reach) reach = r.end;
653
- if (reach >= end) return null; // reached the end: fully covered
654
- }
655
-
656
- if (curFileHash === entry.fileHash) {
657
- // No "(read so far: …)" listing: the range is what the model must act on, and
658
- // echoing the regions it HAS read only invited it to reason about them instead
659
- // of re-reading the target lines.
660
- return `Edit rejected: lines ${start}-${end} were not read in ${p}. Read them first — ${args_readHint(p, start, end - start + 1)} — then Edit.`;
661
- }
662
- return `Edit rejected: ${p} changed since it was Read (lines ${start}-${end} are not in an intact Read snapshot). Re-run ${args_readHint(p, start, end - start + 1)} to get the current content, then Edit.`;
663
- }
664
-
665
-
1
+ // Edit tool — mirrors the hncode Edit tool schema & behavior.
2
+ // Snippet-based exact replacement (old_string -> new_string), NOT a whole-file rewrite,
3
+ // so edits stay token-cheap (unlike kimi-code-cli's whole-file Edit).
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { resolvePath, ensureDir, checkpointBeforeWrite , similarFileHint } from './utils.js';
8
+ import { hashStr, normalizeText } from './read.js';
9
+
10
+ // Typographic quotes -> straight quotes. A model almost always emits ASCII
11
+ // quotes, but docs/blog/markdown often use curly ones; without this the edit
12
+ // fails with "old_string not found" even though the text is visibly there.
13
+ // Mirrors Claude Code's normalizeQuotes.
14
+ const CURLY = [
15
+ ['\u2018', "'"], ['\u2019', "'"], // ‘ ’
16
+ ['\u201c', '"'], ['\u201d', '"'], // “ ”
17
+ ];
18
+ export function normalizeQuotes(s) {
19
+ let out = String(s);
20
+ for (const [from, to] of CURLY) out = out.split(from).join(to);
21
+ return out;
22
+ }
23
+
24
+ // Re-exported from read.js so the staleness guard has ONE definition of the
25
+ // region hash. Previously read.js and edit.js each had their own copy; any
26
+ // drift between them would silently disable staleness detection.
27
+ import { hashRegion as hashLines } from './read.js';
28
+
29
+ export const spec = {
30
+ name: 'Edit',
31
+ description: `Edit a file. Three shapes: LINE-RANGE (path + start_line + end_line + new_string),
32
+ SUBSTRING (path + old_string + new_string, unique unless replace_all), RANGED SUBSTRING (the same plus
33
+ start_line + end_line, which narrows where old_string is searched).
34
+
35
+ BOTH BOUNDS ARE INCLUSIVE: start_line=3, end_line=5 covers lines 3, 4 and 5 — three lines, so new_string must
36
+ have exactly three lines.
37
+
38
+ TO DELETE, SEND AN EMPTY new_string. start_line=7, end_line=7 with new_string="" removes line 7 and nothing
39
+ else. That is the ONLY correct way to delete. Restating the next line as the replacement COPIES it, the file
40
+ then holds that line twice, and because the duplicate looks like damage the retry restates another neighbour —
41
+ the duplicates multiply. Never copy a neighbouring line into new_string to stand in for deleting.
42
+
43
+ new_string is written VERBATIM — no indentation is added, removed or re-derived. Every line carries its own
44
+ leading whitespace, the FIRST one included; copy it from the Read output after the tab that follows each line
45
+ number (Read prints '12' then a tab, then the indented code, so you send the leading spaces yourself).
46
+
47
+ COUNT FIRST: in line-range mode new_string must have exactly end_line - start_line + 1 lines, and every line
48
+ you write must be one you are replacing. A line outside the range is not deleted and survives as a duplicate.
49
+
50
+ SUBSTRING MODE — new_string CONTAINS ONLY THE REPLACEMENT FOR old_string, NOTHING BEFORE OR AFTER IT.
51
+ If old_string is one line, new_string is one line, or "" to delete that line. NEVER place the line ABOVE or
52
+ BELOW old_string into new_string "for context" or "as replacement" — those lines are not part of old_string, so
53
+ they get written a SECOND time. Example: to change line 12 to "x = 1", send old_string = " x = 2" and
54
+ new_string = " x = 1" — just that one line. Sending new_string = " y = 0\\n x = 1" duplicates " y = 0",
55
+ because " y = 0" was never in old_string. If the result shows a duplicated line, the cause is almost always
56
+ this: you restated a neighbour. Fix it by removing that neighbour from new_string, NOT by restating another
57
+ one — that multiplies the duplicates.
58
+
59
+ Omitting new_string entirely is an error — pass "" to delete.
60
+
61
+ AFTER A SUCCESSFUL EDIT, the result quotes the file around what you wrote — five lines either side, in the same
62
+ numbered form Read uses. So editing a region you have just edited does NOT need another Read of it: the previous
63
+ Edit already shows you those lines as they are on disk now. Read again when you need a part of the file the edit
64
+ did not show, or when a different tool or the user has changed the file since.
65
+
66
+ LINE NUMBERS GO STALE THE MOMENT YOU EDIT. Every edit shifts the lines below it, so the numbers you read
67
+ a moment ago are wrong for the next one. Read the file again before the NEXT edit, or work from the lines
68
+ the previous edit printed — those are current.
69
+
70
+ THE FAILURE THIS PREVENTS: an edit whose range was off by a line or two wrote the neighbouring line a second
71
+ time, because the range covered a line the replacement did not. The file then held a duplicate, the
72
+ duplicate looked like damage, and the fix restated another neighbour — the duplicates multiplied until the
73
+ file was unusable. The cause is almost never the content; it is a range that no longer matched the file.
74
+
75
+ SO: one edit at a time. Make ONE change, look at the result, then make the next. Several edits in a row
76
+ without a Read in between are several chances to act on stale line numbers. And if an edit produced a
77
+ duplicate, the fix is to remove the duplicated line — never to restate another one.`,
78
+ parameters: {
79
+ type: 'object',
80
+ properties: {
81
+ path: { type: 'string', description: 'Path to the file to edit.' },
82
+ old_string: { type: 'string', description: 'Exact text to replace, including whitespace and newlines. Omit for pure line-range mode. COMBINE it with start_line/end_line to replace only the occurrence inside that range.' },
83
+ new_string: { type: 'string', description: 'Replacement text, written VERBATIM in BOTH modes — no indentation is added, removed, or re-derived. Write the leading spaces on EVERY line yourself, including the FIRST one, copying them from the Read output after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`). In LINE-RANGE mode it must contain EXACTLY the lines being replaced: a line that sits outside [start_line, end_line] is not deleted, so restating it here leaves a duplicate. Count them first: new_string must have exactly end_line - start_line + 1 lines. In SUBSTRING mode it replaces ONLY old_string — NEVER include the line above or below old_string in new_string; those lines are not being replaced and are written a second time. To delete a line, make old_string that line and new_string "".' },
84
+
85
+ replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string.' },
86
+ start_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based first line to replace, INCLUSIVE — the range covers start_line and end_line and every line between them. Requires end_line and new_string. With old_string too, it is the first line to SEARCH for it in.' },
87
+ end_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based last line to replace, INCLUSIVE (requires start_line). start_line=3, end_line=5 replaces lines 3, 4 AND 5 — three lines, so new_string must have three lines. If your new_string has four, one of them is outside the range and will survive as a duplicate. With old_string too, it is the last line to search in.' },
88
+ },
89
+ // Three accepted shapes:
90
+ // line-range start_line + end_line + new_string
91
+ // exact-substring old_string + new_string
92
+ // rangedToWindow-substring start_line + end_line + old_string + new_string
93
+ // Line-range is the preferred route; the third exists for "one of several copies".
94
+ anyOf: [
95
+ { required: ['path', 'start_line', 'end_line', 'new_string'] },
96
+ { required: ['path', 'old_string', 'new_string'] },
97
+ ],
98
+ },
99
+ async execute(args, ctx) {
100
+ // Validate BEFORE resolving the path. `resolvePath(undefined)` resolves to the
101
+ // workspace root rather than failing, so a truncated tool call (agent.js falls
102
+ // back to `{ raw, _rawLen }` when the streamed JSON will not parse) could
103
+ // target a DIRECTORY and produce a confusing EISDIR/ENOENT instead of "retry
104
+ // the call".
105
+ if (typeof args.path !== 'string' || !args.path.trim()) {
106
+ const truncated = args && args.raw
107
+ ? ` The arguments did not parse as JSON${args._rawLen ? ` (${args._rawLen} characters received)` : ''} — the call was most likely truncated. Retry, and keep \`old_string\` / \`new_string\` small (edit in several passes rather than one large replacement).`
108
+ : '';
109
+ return `Error: \`path\` is required and must be a non-empty string.${truncated}`;
110
+ }
111
+ let p;
112
+ try { p = resolvePath(args.path, ctx); } catch (e) { return e.message; }
113
+ // A Jupyter notebook is JSON, not text: a snippet edit corrupts it. Point the
114
+ // model at the notebook-aware tool instead (mirrors Claude Code errorCode 5).
115
+ if (String(p).toLowerCase().endsWith('.ipynb')) {
116
+ return `Error: ${args.path} is a Jupyter notebook, and its .ipynb is JSON — a text replacement would corrupt it. Use NotebookEdit instead: \`{ path: ${JSON.stringify(args.path)}, action: "list" }\` to see the cells, then action "replace" with the cell index.`;
117
+ }
118
+ let content;
119
+ try {
120
+ content = fs.readFileSync(p, 'utf8');
121
+ } catch (e) {
122
+ if (e && e.code === 'ENOENT') {
123
+ return `Error reading ${args.path}: file does not exist.${similarFileHint(p)}`;
124
+ }
125
+ return `Error reading ${args.path}: ${e.message}`;
126
+ }
127
+ const { start_line, end_line } = args;
128
+ // THREE shapes, not two.
129
+ //
130
+ // line-range start_line + end_line + new_string
131
+ // substring old_string + new_string
132
+ // RANGED SUB start_line + end_line + old_string + new_string
133
+ //
134
+ // The third is what the first two cannot express: replace ONE occurrence of a snippet that
135
+ // appears several times, without `replace_all` (which would hit every copy) and without
136
+ // counting lines by hand. The range narrows WHERE to look; `old_string` says WHAT to replace
137
+ // inside it. Rejecting the combination sent callers to `replace_all` as their only option,
138
+ // which is how the wrong copy gets edited.
139
+ //
140
+ // `old_string` alongside a range is therefore not a mistake — but a range with NEITHER
141
+ // old_string nor new_string still is, and is reported below.
142
+ const hasRangeKeys = args.start_line != null || args.end_line != null;
143
+ const hasSubKeys = args.old_string != null;
144
+ const hasNewString = (args.new_string != null) || (args.new_content != null);
145
+ if (hasRangeKeys && hasSubKeys && !hasNewString) {
146
+ return 'Error: a rangedToWindow edit needs new_string as well as old_string.';
147
+ }
148
+
149
+ // ---- RANGED SUBSTRING ---------------------------------------------------
150
+ // A range AND an old_string: search for the snippet only INSIDE the range. Handled here,
151
+ // before the pure line-range path, because that path replaces whole lines and would ignore
152
+ // the snippet entirely — the very ambiguity the old mutual-exclusion check was avoiding.
153
+ //
154
+ // The range is validated, then the substring path below does the matching with the search
155
+ // window clamped to it. Splitting the work this way keeps ONE implementation of matching
156
+ // (quote-normalized retry, staleness, whitespace tolerance) instead of a second, weaker copy.
157
+ // A HALF-GIVEN RANGE with an old_string is not a reason to refuse: the snippet locates the
158
+ // edit by itself, and the single bound is a hint that failed to pair. Callers add `start_line`
159
+ // from the schema's own wording ("1-based first line to replace") expecting it to help, so
160
+ // refusing rejected a request that was already complete.
161
+ //
162
+ // `rangedToWindow` is set even though no window is applied. It means "the range question has been
163
+ // settled", which is what the line-range guard below tests — leaving it false made that guard
164
+ // see the same unpaired bound and reject the call one block later.
165
+ let searchFrom = 0;
166
+ let searchTo = 0; // 0,0 = the whole file
167
+ // A real window was validated, so the search below is confined to it. Distinct from
168
+ // `rangeHandled`: this one means "clamp", and setting it for a snippet with no window made
169
+ // every search run inside 0..0 and find nothing.
170
+ let rangedToWindow = false;
171
+ // The range question is answered — either a window was applied, or the caller gave an
172
+ // `old_string` that locates the edit on its own and a half-given bound was ignored.
173
+ let rangeHandled = hasSubKeys;
174
+ if (hasRangeKeys && hasSubKeys && hasNewString) {
175
+ if ((start_line != null) !== (end_line != null)) {
176
+ // Ignore the unpaired bound; `searchFrom`/`searchTo` stay at the whole file and `rangedToWindow`
177
+ // was already set above.
178
+ searchFrom = 0;
179
+ searchTo = 0;
180
+ } else {
181
+ // The range was given in full: validate it, then confine the search to it.
182
+ const start = Number(start_line) | 0, end = Number(end_line) | 0;
183
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 1 || end < start) {
184
+ return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
185
+ }
186
+ {
187
+ const all = content.split(/\r\n|\r|\n/);
188
+ if (end > all.length) {
189
+ return `Error: end_line ${end_line} exceeds file length (${all.length} lines).`;
190
+ }
191
+ }
192
+ rangedToWindow = true;
193
+ rangeHandled = true;
194
+ searchFrom = start;
195
+ searchTo = end;
196
+ }
197
+ }
198
+
199
+ // ---- LINE-RANGE mode ---------------------------------------------------
200
+ // `start_line`..`end_line` replace the lines at those 1-based positions,
201
+ // with NO old_string involved at all. This is the path for "change line 12"
202
+ // where spelling out the exact current text is awkward.
203
+ if (!rangeHandled && (start_line != null) !== (end_line != null)) {
204
+ return 'Error: line-range mode needs BOTH start_line and end_line.';
205
+ }
206
+ if (!rangeHandled && start_line != null && end_line != null) {
207
+ // Accept both spellings so old new_content callers keep working.
208
+ const new_string = args.new_string != null ? args.new_string : args.new_content;
209
+ // new_string is required — a missing one would put the literal string
210
+ // "undefined" in the file.
211
+ if (new_string == null) return `Error: new_string is required for line-range mode (pass an empty string to delete the lines).`;
212
+ if (typeof new_string !== 'string') {
213
+ return `Error: new_string must be a string (got ${new_string === null ? 'null' : typeof new_string}).`;
214
+ }
215
+ const start = Number(start_line) | 0, end = Number(end_line) | 0;
216
+ if (start < 1 || end < start) {
217
+ return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
218
+ }
219
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
220
+ const lines = content.split(/\r\n|\r|\n/);
221
+ if (end > lines.length) {
222
+ return `Error: end_line ${end_line} exceeds file length (${lines.length} lines).`;
223
+ }
224
+ // STALENESS: the range must sit inside a region this turn actually Read and
225
+ // that still matches. Same guarantee as the substring path, checked here
226
+ // directly (no old_string to search for).
227
+ const stale = checkStaleRange(p, lines, start, end, ctx);
228
+ if (stale) return stale;
229
+
230
+ // AN EMPTY new_string DELETES THE RANGE. No line survives, so the replacement is nothing at all.
231
+ //
232
+ // `''.split('\n')` is `['']` — ONE EMPTY STRING — not an empty array. The splice therefore replaced the
233
+ // range with a single blank line, so "delete these lines" left a hole and shifted everything below it.
234
+ // Deleting has to mean deleting: when there is no replacement text, the range is removed outright.
235
+ //
236
+ // This is also the answer to the mistake that keeps appearing in edits: to remove one line, send an EMPTY
237
+ // new_string over that one line. Restating the neighbour instead copies it, and the file ends up with the
238
+ // line twice — the duplicate is a symptom of having no delete, not of carelessness.
239
+ const inserted = new_string === '' ? [] : normalizeText(new_string).split('\n');
240
+
241
+ // The lines being REPLACED, captured before the splice. The TUI renders an Edit's diff from the tool
242
+ // ARGUMENTS, and line-range mode has no `old_string` to diff against — so without reporting them here the
243
+ // edit drew NO diff at all.
244
+ const replacedText = lines.slice(start - 1, end).join('\n');
245
+ const out = [...lines.slice(0, start - 1), ...inserted, ...lines.slice(end)];
246
+ const normUpdated = out.join('\n');
247
+ const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
248
+
249
+ // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
250
+ checkpointBeforeWrite(p, ctx);
251
+ try {
252
+ ensureDir(p);
253
+ fs.writeFileSync(p, updated, 'utf8');
254
+ } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
255
+ // The returned excerpt is read from disk after the write. Refresh the snapshot for precisely those returned
256
+ // lines, so a follow-up edit inside the excerpt needs no separate Read; regions outside it remain untrusted.
257
+ const removed = end - start + 1;
258
+ if (ctx) ctx.lastEditDiff = buildEditDiff({ fileLines: lines, oldText: replacedText, newText: inserted.join('\n'), startLine: start, filePath: p });
259
+ const written = Math.max(1, inserted.length);
260
+ const excerpt = readAfterEdit(p, start, written, ctx);
261
+ return `Edited ${args.path}: replaced lines ${start}-${end} (${removed} line${removed === 1 ? '' : 's'}) with ${inserted.length} line${inserted.length === 1 ? '' : 's'}.\n\n${excerpt}`.trimEnd();
262
+ }
263
+
264
+ // ---- SUBSTRING mode (old_string -> new_string) --------------------------
265
+ // `new_content` is accepted as an alias of `new_string` — the validation above
266
+ // already counts it, so refusing it here sent a confusing "new_string is
267
+ // required" for an argument the mode's own checks accepted.
268
+ let { old_string, new_string, replace_all = false } = args;
269
+ if (new_string == null && args.new_content != null) new_string = args.new_content;
270
+ // Reaching here means neither mode was usable: line-range needs
271
+ // start_line+end_line (handled above) and substring needs old_string. When
272
+ // BOTH are absent, say so — "old_string must not be empty" sends the model
273
+ // hunting for a stray empty string it never sent.
274
+ if (old_string == null && new_string == null) {
275
+ return 'Error: no edit mode given. Pass EITHER (start_line, end_line, new_string) OR (old_string, new_string).';
276
+ }
277
+ if (old_string === '' || old_string == null) return `Error: old_string must not be empty.`;
278
+ if (new_string == null) return `Error: new_string is required for substring mode.`;
279
+
280
+ // --- Newline normalization (Windows CRLF) ---
281
+ // The Read tool normalizes \r\n -> \n, so an agent builds old_string/new_string
282
+ // with LF. But the file on disk may be CRLF, making a raw LF match fail. We
283
+ // normalize the FILE content to LF for matching, then restore the file's own
284
+ // line ending style when writing back, so we never corrupt or mix endings.
285
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
286
+ const normContent = content.split(/\r\n|\r|\n/).join('\n');
287
+ const normOld = normalizeText(old_string);
288
+ const normNew = normalizeText(new_string);
289
+
290
+ // A RANGED edit searches only inside the given lines. `windowStart` is the character offset of
291
+ // the range's first line in `normContent`, and `windowEnd` the end of its last line; the whole
292
+ // file is the window when no range was given. Every match, count and replacement below uses
293
+ // this window, so a snippet that appears elsewhere in the file is neither found nor touched —
294
+ // which is the entire point, and what `replace_all` cannot express.
295
+ let windowStart = 0;
296
+ let windowEnd = normContent.length;
297
+ if (rangedToWindow) {
298
+ const allLines = normContent.split('\n');
299
+ // Offset of line N's first character: the sum of the lengths of lines 1..N-1 plus their
300
+ // newlines. Computed by walking, because a single `indexOf` would find the wrong copy of a
301
+ // line that also occurs earlier in the file.
302
+ const offsetOfLine = (n) => {
303
+ let at = 0;
304
+ for (let i = 0; i < n - 1 && i < allLines.length; i++) at += allLines[i].length + 1;
305
+ return at;
306
+ };
307
+ windowStart = offsetOfLine(searchFrom);
308
+ const lastLineStart = offsetOfLine(searchTo);
309
+ windowEnd = Math.min(normContent.length, lastLineStart + (allLines[searchTo - 1] || '').length);
310
+ }
311
+ /** Occurrences of `needle` inside the window. */
312
+ const countInWindow = (needle) => {
313
+ if (!needle) return 0;
314
+ const seg = normContent.slice(windowStart, windowEnd);
315
+ return seg.split(needle).length - 1;
316
+ };
317
+
318
+ let matchOld = normOld; // the string that will actually be matched/replaced
319
+ let matchNew = normNew;
320
+ let count = countInWindow(matchOld);
321
+ if (count === 0) {
322
+ // Quote-normalized retry: the file may use curly quotes while the model sent
323
+ // straight ones. Match on the normalized forms, then replace the ACTUAL
324
+ // substring found in the file so typography is preserved. normalizeQuotes is
325
+ // 1 char -> 1 char, so indices line up between the two strings.
326
+ const normFileQ = normalizeQuotes(normContent);
327
+ if (normFileQ !== normContent) {
328
+ const normOldQ = normalizeQuotes(normOld);
329
+ // Search the NORMALIZED window for the normalized snippet, then take the real text at
330
+ // that place so the replacement keeps the file's own typography.
331
+ const idx = normFileQ.indexOf(normOldQ, windowStart);
332
+ if (idx >= 0 && idx + normOldQ.length <= windowEnd) {
333
+ matchOld = normContent.slice(idx, idx + normOldQ.length);
334
+ matchNew = normNew; // keep the model's new_string as written
335
+ count = countInWindow(matchOld);
336
+ }
337
+ }
338
+ }
339
+ if (count === 0) {
340
+ if (rangedToWindow) {
341
+ // Say WHERE it was looked for, so a snippet that exists elsewhere is not reported as
342
+ // missing outright — that sends the caller hunting for a typo that is not there.
343
+ const elsewhere = normContent.split(normOld).length - 1;
344
+ const hint = elsewhere
345
+ ? ` It appears ${elsewhere} time(s) elsewhere in the file, outside lines ${searchFrom}-${searchTo}. Broaden the range, or correct the range.`
346
+ : '';
347
+ return `Error: old_string not found within lines ${searchFrom}-${searchTo} of ${args.path}.${hint}`;
348
+ }
349
+ const near = nearestLineHint(normContent, normOld);
350
+ return `Error: old_string not found in ${args.path}.${near}`;
351
+ }
352
+ if (count > 1 && !replace_all) {
353
+ if (rangedToWindow) {
354
+ return `Error: old_string matched ${count} occurrences within lines ${searchFrom}-${searchTo} of ${args.path}. Narrow the range, or use replace_all=true to change all of them.`;
355
+ }
356
+ return `Error: old_string matched ${count} occurrences in ${args.path}. Use replace_all=true or make old_string unique.`;
357
+ }
358
+ // --- Staleness guard: the AI must edit against content it actually Read.
359
+ // We stored per-region + whole-file hashes in ctx.readPool when Read ran.
360
+ // If the file changed on disk since (external edit, stream, Ctrl-C side
361
+ // effect), reject so a snippet edit cannot silently corrupt the file. ---
362
+ const stale = checkStale(p, normContent, matchOld, ctx);
363
+ if (stale) return stale;
364
+
365
+ // Replace INSIDE the window only. A rangedToWindow edit must not touch an identical snippet sitting
366
+ // before or after the range — replacing across the whole file is the failure the range exists
367
+ // to prevent. With no range the window IS the whole file, so non-rangedToWindow callers are unchanged.
368
+ //
369
+ // The replacement is passed as a FUNCTION: a string second argument makes JS interpret
370
+ // `$&`, `` $` ``, `$'` and `$$` in the NEW text, so an edit whose new_string contains them
371
+ // (regex examples, Makefile `$$`, shell code) silently wrote the wrong file.
372
+ const normUpdated = (() => {
373
+ const head = normContent.slice(0, windowStart);
374
+ const body = normContent.slice(windowStart, windowEnd);
375
+ const tail = normContent.slice(windowEnd);
376
+ const literal = () => matchNew;
377
+ return head + (replace_all ? body.replaceAll(matchOld, literal) : body.replace(matchOld, literal)) + tail;
378
+ })();
379
+ // The replaced text's actual character offset in normContent (first occurrence
380
+ // inside the window — guaranteed >= 0, the count above found it). Everything
381
+ // before the match is unchanged, so this one offset anchors BOTH the diff and
382
+ // the Read-pool re-arm below to the real edit site. Locating the site by
383
+ // matching its first LINE (the old approach) collapsed to line 1 when
384
+ // old_string starts mid-line, and pointed at an earlier copy when the file
385
+ // repeats that line — the diff then drew context from the top of the file.
386
+ const matchAt = normContent.indexOf(matchOld, windowStart);
387
+ const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
388
+ // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
389
+ checkpointBeforeWrite(p, ctx);
390
+ try {
391
+ ensureDir(p);
392
+ fs.writeFileSync(p, updated, 'utf8');
393
+ } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
394
+ // Only the post-edit excerpt returned below refreshes the Read snapshot. An unrelated part of the file is not
395
+ // made trusted merely because this replacement succeeded.
396
+ const occurrences = replace_all ? count : 1;
397
+ // Publish the diff for the UI (same contract as the line-range path above).
398
+ // `startLine` comes from the actual match offset, so a snippet that starts
399
+ // mid-line or a file with repeated lines still anchors the context rows at
400
+ // the place that was really edited.
401
+ if (ctx) {
402
+ const startLine = matchAt >= 0 ? normContent.slice(0, matchAt).split('\n').length : 1;
403
+ ctx.lastEditDiff = buildEditDiff({
404
+ fileLines: normContent.split('\n'),
405
+ oldText: old_string,
406
+ newText: new_string,
407
+ startLine,
408
+ filePath: p,
409
+ });
410
+ }
411
+ // Quote the result the same way the line-range path does, so neither mode leaves the model guessing.
412
+ const editedAt = matchAt >= 0 ? normContent.slice(0, matchAt).split('\n').length : 1;
413
+ // replace_all may change distant copies too. One excerpt cannot vouch for them, so do not authorize another
414
+ // edit based on an incomplete view; the caller must Read the desired region after a bulk replacement.
415
+ const writtenLines = normalizeText(new_string).split('\n').length;
416
+ const excerpt = readAfterEdit(p, editedAt, writtenLines, replace_all ? null : ctx);
417
+ if (replace_all && ctx && ctx.readPool) ctx.readPool.delete(p);
418
+ return `Edited ${args.path}: replaced ${occurrences} occurrence(s).\n\n${excerpt}`.trimEnd();
419
+ },
420
+ };
421
+
422
+ /** How many unchanged lines to show on each side of a changed region. */
423
+ const DIFF_CONTEXT = 5;
424
+
425
+
426
+
427
+ /** The line's leading whitespace, for the same-indent closer rule. */
428
+ function leadingWs(s) {
429
+ const m = /^\s*/.exec(String(s == null ? '' : s));
430
+ return m ? m[0] : '';
431
+ }
432
+
433
+
434
+ /**
435
+ * Build the diff payload, including the unchanged lines around the change.
436
+ *
437
+ * The replaced lines alone do not tell a reader WHERE the edit landed: a four-line block quoted with no
438
+ * surroundings could be anywhere in a 500-line file, so neither the model nor the user could tell a
439
+ * correct edit from one applied at the right text in the wrong place — and with repeated code (several
440
+ * similar blocks, two `}` in a row) the same text appears in many places.
441
+ *
442
+ * `context` carries the file's own lines so the renderer can draw them unmarked, above and below.
443
+ *
444
+ * `fileLines` is the content BEFORE the edit, for the replaced region's START LINE to be meaningful:
445
+ * `startLine` is a line number in that same file.
446
+ */
447
+ /** How many lines of the file to show on each side of a freshly edited region. */
448
+ const READ_AFTER_CONTEXT = 5;
449
+
450
+ /**
451
+ * The file around the region an edit just wrote, in the same `N<TAB>text` form the Read tool uses.
452
+ *
453
+ * WHY THE EDIT RETURNS IT: the result used to be one sentence — "replaced lines 5-7" — which tells the model what
454
+ * it asked for but not what the file now says. Every follow-up edit therefore began with a Read of the same lines,
455
+ * a whole round trip whose only purpose was to learn something the edit already knew.
456
+ *
457
+ * The excerpt is read from disk after the write, then precisely that region is registered in the Read pool. This
458
+ * makes the advertised "no second Read" path real without trusting the edit arguments or any unseen file region.
459
+ *
460
+ * Returns '' when the post-write read fails, leaving the old snapshot unchanged.
461
+ */
462
+ function readAfterEdit(filePath, firstLine, lineCount, ctx) {
463
+ let text;
464
+ try { text = fs.readFileSync(filePath, 'utf8'); } catch { return ''; }
465
+ const lines = normalizeText(text).split('\n');
466
+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
467
+ const total = lines.length;
468
+ const start = Math.max(1, firstLine - READ_AFTER_CONTEXT);
469
+ const end = Math.min(total, firstLine + Math.max(1, lineCount) - 1 + READ_AFTER_CONTEXT);
470
+ if (ctx && ctx.readPool) {
471
+ // The file changed, so every older region for this path is invalid; only the lines actually returned below
472
+ // may authorize a follow-up edit. Keep the same normalized hashing convention as Read.
473
+ ctx.readPool.set(filePath, {
474
+ fileHash: hashStr(text), lines: total,
475
+ regions: [{ start, end, hash: hashLines(lines, start, end) }],
476
+ });
477
+ }
478
+ const out = [];
479
+ for (let i = start; i <= end; i++) out.push(`${i}\t${lines[i - 1]}`);
480
+ return out.join('\n');
481
+ }
482
+
483
+ function buildEditDiff({ fileLines, oldText, newText, startLine, filePath }) {
484
+ const lines = Array.isArray(fileLines) ? fileLines : [];
485
+ const before = [];
486
+ const after = [];
487
+ const replacedCount = normalizeText(oldText).split('\n').length;
488
+ // `startLine` is 1-based; the replaced block occupies [startLine, startLine + n - 1].
489
+ const lastReplaced = startLine + replacedCount - 1;
490
+ for (let n = startLine - DIFF_CONTEXT; n < startLine; n++) {
491
+ if (n >= 1 && n <= lines.length) before.push({ n, text: lines[n - 1] });
492
+ }
493
+ // The AFTER context is drawn from the file BEFORE the edit, but its line numbers must describe the file
494
+ // AFTER it — that is the file a reader has open when they read the diff.
495
+ //
496
+ // Using the pre-edit numbers looked right for a same-size replacement and drifted by one per added line
497
+ // otherwise: an edit that grew the file by three shifted every context row, so the diff showed line
498
+ // numbers that did not exist where it claimed, or repeated ones that did.
499
+ //
500
+ // `net` is the number of lines the edit added (negative when it shrank the file), so every line below
501
+ // the replaced block moves by exactly that much.
502
+ // AN EMPTY REPLACEMENT IS ZERO LINES, NOT ONE. `''.split('\n')` is `['']`, so a deletion counted itself as
503
+ // a one-line replacement and `net` came out 0 instead of -1 — the AFTER context was then numbered as if
504
+ // nothing had been removed, and the diff carried a phantom `+` row holding an empty string, which reads as an
505
+ // insertion where the file in fact lost a line.
506
+ const newLines = normalizeText(newText) === '' ? [] : normalizeText(newText).split('\n');
507
+ const net = newLines.length - replacedCount;
508
+ for (let n = lastReplaced + 1; n <= lastReplaced + DIFF_CONTEXT; n++) {
509
+ if (n >= 1 && n <= lines.length) after.push({ n: n + net, text: lines[n - 1] });
510
+ }
511
+ return {
512
+ old: normalizeText(oldText),
513
+ new: normalizeText(newText),
514
+ startLine,
515
+ // The file the change belongs to, so the viewer can pick a syntax highlighter from its extension. Without it
516
+ // the diff had no way to know whether it was looking at JavaScript or a Makefile.
517
+ path: filePath || '',
518
+ context: { before, after },
519
+ };
520
+ }
521
+
522
+ // Suggest a near-miss filename when a path does not exist: same directory, an
523
+ // exact case-insensitive match, same stem with a different extension, or a
524
+ // prefix match. Saves the model a round-trip of guessing (Claude Code's
525
+ // "Did you mean X?").
526
+ // When old_string is not found, look for the closest line in the file and name
527
+ // it, so the model can see what the text actually is instead of guessing.
528
+ function nearestLineHint(content, oldStr) {
529
+ const want = String(oldStr).split('\n')[0].trim();
530
+ if (!want || want.length < 3) return '';
531
+ const lines = String(content).split('\n');
532
+ // Character bigrams: robust to small differences and cheap on long lines.
533
+ const grams = (s) => {
534
+ const set = new Set();
535
+ for (let i = 0; i + 1 < s.length; i++) set.add(s.slice(i, i + 2));
536
+ return set;
537
+ };
538
+ const wantGrams = grams(want);
539
+ if (!wantGrams.size) return '';
540
+ let best = -1, bestScore = 0;
541
+ for (let i = 0; i < lines.length; i++) {
542
+ const g = grams(lines[i].trim());
543
+ if (!g.size) continue;
544
+ let hit = 0;
545
+ for (const t of wantGrams) if (g.has(t)) hit++;
546
+ const score = hit / wantGrams.size;
547
+ if (score > bestScore) { bestScore = score; best = i; }
548
+ }
549
+ if (best >= 0 && bestScore >= 0.5) {
550
+ return ` The closest line is line ${best + 1}: ${JSON.stringify(lines[best].trim().slice(0, 120))}`;
551
+ }
552
+ return '';
553
+ }
554
+
555
+ // Returns an error message when the edit is stale, else null (safe to edit).
556
+ function checkStale(p, normContent, normOld, ctx) {
557
+ if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
558
+ const entry = ctx.readPool.get(p);
559
+ if (!entry) return null; // this file was never Read this turn; allow
560
+
561
+ const curLines = normContent.split('\n');
562
+ const curFileHash = hashStr(normContent);
563
+
564
+ // Locate the edit target's first line in the CURRENT file (1-based).
565
+ //
566
+ // An EXACT line match first, then a line that merely CONTAINS it. The exact match alone
567
+ // missed every edit whose `old_string` begins mid-line — `old_string: "return 1;"` against
568
+ // a line ` return 1;` found nothing, so `editLine` was -1 and step (1) below was skipped
569
+ // entirely: the edit was then reported as stale (branch 2) or, with the whole-file hash
570
+ // also differing, rejected as though the file had changed. Two-line `old_string`s are the
571
+ // common case for a range edit, and their first line usually IS whole, which is why this
572
+ // only showed up on single-line and indented-prefix edits.
573
+ const firstLine = String(normOld).split('\n')[0];
574
+ let idx = curLines.indexOf(firstLine);
575
+ if (idx < 0 && firstLine) idx = curLines.findIndex((l) => l.includes(firstLine));
576
+ const editLine = idx >= 0 ? idx + 1 : -1;
577
+
578
+ // (1) The edit target must sit inside a region the AI actually Read, and that
579
+ // region's content must still match what was Read. Reading the WHOLE file
580
+ // records a region covering every line, so this also covers "read full,
581
+ // edit a part". This is what rejects "read lines 1-3, edit line 7".
582
+ if (editLine > 0) {
583
+ const coveredByIntactRegion = entry.regions.some(
584
+ (r) => editLine >= r.start && editLine <= r.end && hashLines(curLines, r.start, r.end) === r.hash,
585
+ );
586
+ if (coveredByIntactRegion) return null;
587
+ }
588
+
589
+ // (2) Whole file unchanged since Read, but the edit target was never Read
590
+ // (no region covers it). Name the exact lines so the model reads the right
591
+ // window instead of guessing.
592
+ if (curFileHash === entry.fileHash) {
593
+ const span = String(normOld).split('\n').length;
594
+ const at = editLine > 0 ? editLine : 1;
595
+ return `Edit rejected: you have not read the lines you are editing in ${p}. The target is around line ${at} (${span} line${span === 1 ? '' : 's'}). Read it first — ${args_readHint(p, at, span)} — then Edit.`;
596
+ }
597
+
598
+ // (3) The file changed on disk since it was Read and the edit target is not in
599
+ // an intact Read region. Reject so a stale snippet cannot corrupt the file.
600
+ const at3 = editLine > 0 ? ` (target line ${editLine})` : '';
601
+ return `Edit rejected: ${p} changed since it was Read${at3}, and the edited region is not in an intact Read snapshot. Re-run ${args_readHint(p, editLine > 0 ? editLine : 1, String(normOld).split('\n').length)} to get the current content, then Edit.`;
602
+ }
603
+
604
+ // A ready-to-use Read call for the hint. Keeps the model from guessing line ranges.
605
+ function args_readHint(p, at, span) {
606
+ const from = Math.max(1, at - 3);
607
+ const n = Math.max(span + 6, 10);
608
+ return `Read { path: ${JSON.stringify(p)}, start_line: ${from}, end_line: ${from + n - 1} }`;
609
+ }
610
+ // ---- helpers for the line-range path ---------------------------------------
611
+
612
+ // Same guarantee as checkStale, but for an explicit [start, end] line range:
613
+ // every line in the range must sit inside a region that was Read this turn and
614
+ // whose content still matches. Returns an error string, or null when safe.
615
+ function checkStaleRange(p, curLines, start, end, ctx) {
616
+ if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
617
+ const entry = ctx.readPool.get(p);
618
+ if (!entry) return null; // never Read this turn; allow
619
+
620
+ const normContent = curLines.join('\n');
621
+ const curFileHash = hashStr(normContent);
622
+
623
+ // A range is "read" when the regions the model has SEEN cover it — not only when
624
+ // a single region spans it. A file read in two passes (5-10 then 11-16) must
625
+ // allow editing 5-16: the two slices are contiguous, both still intact, so the
626
+ // written range is fully known. Requiring one enclosing region rejected that
627
+ // perfectly safe edit and forced a third Read.
628
+ //
629
+ // Only regions whose hash STILL matches count: a region whose text changed is no
630
+ // longer what the model saw, so it cannot vouch for anything. The cover must also
631
+ // be SEAMLESS — a gap (5-10 and 12-16 with 11 unread) leaves 11 unknown, so it
632
+ // does NOT count, and the edit is correctly refused.
633
+ const intact = entry.regions
634
+ .filter((r) => hashLines(curLines, r.start, r.end) === r.hash)
635
+ .sort((a, b) => a.start - b.start);
636
+ let reach = start - 1; // highest line known to be covered
637
+ for (const r of intact) {
638
+ if (r.end < start) continue; // entirely before the target
639
+ if (r.start > reach + 1) break; // a gap opens before this region: stop
640
+ if (r.end > reach) reach = r.end;
641
+ if (reach >= end) return null; // reached the end: fully covered
642
+ }
643
+
644
+ if (curFileHash === entry.fileHash) {
645
+ // No "(read so far: …)" listing: the range is what the model must act on, and
646
+ // echoing the regions it HAS read only invited it to reason about them instead
647
+ // of re-reading the target lines.
648
+ return `Edit rejected: lines ${start}-${end} were not read in ${p}. Read them first — ${args_readHint(p, start, end - start + 1)} — then Edit.`;
649
+ }
650
+ return `Edit rejected: ${p} changed since it was Read (lines ${start}-${end} are not in an intact Read snapshot). Re-run ${args_readHint(p, start, end - start + 1)} to get the current content, then Edit.`;
651
+ }
652
+
653
+