@hncode/hncode 0.8.1 → 0.8.2

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