@hncode/hncode 0.5.0 → 0.5.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.
Files changed (48) hide show
  1. package/bin/install.cjs +24 -44
  2. package/bin/preinstall.cjs +0 -14
  3. package/package.json +1 -1
  4. package/src/agent-task.js +12 -1
  5. package/src/agent.js +115 -35
  6. package/src/cell-buffer.js +5 -0
  7. package/src/clipboard.js +42 -6
  8. package/src/colors.js +478 -387
  9. package/src/config.js +38 -11
  10. package/src/context-bar.js +46 -5
  11. package/src/doctor.js +214 -11
  12. package/src/git.js +35 -4
  13. package/src/llm.js +6 -0
  14. package/src/memory-profile.js +247 -0
  15. package/src/permissions.js +29 -7
  16. package/src/registry-browser.js +21 -6
  17. package/src/row-cache.js +147 -142
  18. package/src/session-core.js +203 -0
  19. package/src/session-host.js +213 -0
  20. package/src/session-hub.js +1 -0
  21. package/src/session-view.js +110 -0
  22. package/src/settings-schema.js +304 -0
  23. package/src/shell-safety.js +95 -6
  24. package/src/swarm-progress.js +348 -293
  25. package/src/tasks-browser.js +4 -1
  26. package/src/team/constants.js +20 -0
  27. package/src/team/context.js +89 -0
  28. package/src/team/mailbox.js +139 -0
  29. package/src/team/runner.js +347 -0
  30. package/src/team/spawn.js +247 -0
  31. package/src/team/store.js +145 -0
  32. package/src/team/tasks.js +164 -0
  33. package/src/team/team.js +311 -0
  34. package/src/team-panel.js +226 -0
  35. package/src/term.js +27 -0
  36. package/src/tool-result.js +279 -236
  37. package/src/tools/agent-swarm.js +114 -11
  38. package/src/tools/agent.js +53 -3
  39. package/src/tools/edit.js +591 -436
  40. package/src/tools/git.js +15 -3
  41. package/src/tools/index.js +2 -0
  42. package/src/tools/team.js +398 -0
  43. package/src/tools/web-search.js +88 -75
  44. package/src/tui.js +6187 -4780
  45. package/src/update.js +285 -115
  46. package/src/web-daemon.js +27 -4
  47. package/src/web-live.js +250 -0
  48. package/src/web.js +3 -1
package/src/tools/edit.js CHANGED
@@ -1,436 +1,591 @@
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. THE TWO MODES ARE MUTUALLY EXCLUSIVE — NEVER combine them:\n- LINE-RANGE mode: path + start_line + end_line + new_string. Replaces lines [start_line, end_line] with new_string.\nPREFERRED — use it whenever you have Read the file and know the line numbers.\n- EXACT-SUBSTRING mode: path + old_string + new_string. Replaces text exactly matching old_string. Use ONLY when the exact text is known and a line range is not convenient.\nLEADING WHITESPACE — SPELL IT OUT ON EVERY LINE, INCLUDING THE FIRST. new_string is written VERBATIM in both modes: nothing is re-indented, auto-indented, or trimmed, and there is no tolerance for a missing first-line indent. Reproduce the indentation the code SHOULD have; it need not match the surrounding block. Copy it from the Read output, after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`).\nWRONG — the first line has no indentation, so it lands at column 0 inside an indented block:\nnew_string: "return total;\\n total += 1;"\nRIGHT — every line carries the indentation it needs:\nnew_string: " return total;\\n total += 1;"\nThose are the same call; only the leading spaces on the FIRST line differ. The same applies to tabs, and to a line whose indentation changes partway through.\nRANGE HYGIENE — WRITE ONLY THE LINES YOU ARE REPLACING. Lines [start_line, end_line] are deleted and new_string is inserted in their place, so a line you leave OUTSIDE that range survives — and if you also restated it inside new_string you get TWO copies. Check what sits on end_line + 1 before deciding where the range ends.\nWRONG — end_line: 3 deletes lines 2-3, but line 4 is repeated because its content was also written into new_string:\nnew_string: "const a = 1;\\nconst b = 20;\\nconst c = 3;"\nRIGHT — the range covers exactly what is being replaced, and nothing beyond it is restated:\nnew_string: "const a = 1;\\nconst b = 20;"\nTo touch line 4 as well, set end_line: 4 and include its new content in new_string.\nIn SUBSTRING mode old_string is matched EXACTLY, including the indentation of its own first line.\nDo NOT pass start_line/end_line together with old_string/new_string in one call, and do NOT pass any of these four keys when you are not using that mode. Omitting new_string is an error, not an empty replacement (in line-range mode pass new_string; in substring mode pass old_string + new_string).\nMis-indented lines often still parse, so a green test run is not proof that an edit landed correctly — re-Read the region before editing it again.\',',
32
- parameters: {
33
- type: 'object',
34
- properties: {
35
- path: { type: 'string', description: 'Path to the file to edit.' },
36
- old_string: { type: 'string', description: 'Exact text to replace, including whitespace and newlines. Omit when using start_line/end_line.' },
37
- 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. In SUBSTRING mode it replaces old_string, which is itself matched exactly including its own indentation.' },
38
-
39
- replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string.' },
40
- start_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based first line to replace (requires end_line and new_string). Use this line-range mode first.' },
41
- end_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based last line to replace (inclusive; requires start_line).' },
42
- },
43
- // Either line-range mode (start_line+end_line+new_string) OR exact-substring
44
- // mode (old_string+new_string).
45
- // Line-range is the preferred route.
46
- anyOf: [
47
- { required: ['path', 'start_line', 'end_line', 'new_string'] },
48
- { required: ['path', 'old_string', 'new_string'] },
49
- ],
50
- },
51
- async execute(args, ctx) {
52
- // Validate BEFORE resolving the path. `resolvePath(undefined)` resolves to the
53
- // workspace root rather than failing, so a truncated tool call (agent.js falls
54
- // back to `{ raw, _rawLen }` when the streamed JSON will not parse) could
55
- // target a DIRECTORY and produce a confusing EISDIR/ENOENT instead of "retry
56
- // the call".
57
- if (typeof args.path !== 'string' || !args.path.trim()) {
58
- const truncated = args && args.raw
59
- ? ` 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).`
60
- : '';
61
- return `Error: \`path\` is required and must be a non-empty string.${truncated}`;
62
- }
63
- let p;
64
- try { p = resolvePath(args.path, ctx); } catch (e) { return e.message; }
65
- // A Jupyter notebook is JSON, not text: a snippet edit corrupts it. Point the
66
- // model at the notebook-aware tool instead (mirrors Claude Code errorCode 5).
67
- if (String(p).toLowerCase().endsWith('.ipynb')) {
68
- 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.`;
69
- }
70
- let content;
71
- try {
72
- content = fs.readFileSync(p, 'utf8');
73
- } catch (e) {
74
- if (e && e.code === 'ENOENT') {
75
- return `Error reading ${args.path}: file does not exist.${similarFileHint(p)}`;
76
- }
77
- return `Error reading ${args.path}: ${e.message}`;
78
- }
79
- const { start_line, end_line } = args;
80
- // The two modes are MUTUALLY EXCLUSIVE: sending line-range AND substring
81
- // parameters together is ambiguous — reject it rather than guessing which
82
- // one the caller meant. Only one family may be present in `args`.
83
- const hasRangeKeys = args.start_line != null || args.end_line != null;
84
- const hasSubKeys = args.old_string != null;
85
- if (hasRangeKeys && hasSubKeys) {
86
- return `Error: do not mix line-range mode and substring mode. Use EITHER (start_line/end_line/new_string) OR (old_string/new_string), never both.`;
87
- }
88
-
89
- // ---- LINE-RANGE mode ---------------------------------------------------
90
- // `start_line`..`end_line` replace the lines at those 1-based positions,
91
- // with NO old_string involved at all. This is the path for "change line 12"
92
- // where spelling out the exact current text is awkward. It is fully
93
- // self-contained: validate -> check the Read cache -> splice -> write ->
94
- // refresh the cache -> return.
95
- // ONE bound without the other is its own mistake and an easy one to make: the
96
- // call then falls past this block and reports a missing old_string, which
97
- // sends the model looking in the wrong place.
98
- if ((start_line != null) !== (end_line != null)) {
99
- return 'Error: line-range mode needs BOTH start_line and end_line.';
100
- }
101
- if (start_line != null && end_line != null) {
102
- // Accept both spellings so old new_content callers keep working.
103
- const new_string = args.new_string != null ? args.new_string : args.new_content;
104
- // new_string is required — a missing one would put the literal string
105
- // "undefined" in the file.
106
- if (new_string == null) return `Error: new_string is required for line-range mode (pass an empty string to delete the lines).`;
107
- if (typeof new_string !== 'string') {
108
- return `Error: new_string must be a string (got ${new_string === null ? 'null' : typeof new_string}).`;
109
- }
110
- const start = Number(start_line) | 0, end = Number(end_line) | 0;
111
- if (start < 1 || end < start) {
112
- return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
113
- }
114
- const eol = content.includes('\r\n') ? '\r\n' : '\n';
115
- const lines = content.split(/\r\n|\r|\n/);
116
- if (end > lines.length) {
117
- return `Error: end_line ${end_line} exceeds file length (${lines.length} lines).`;
118
- }
119
- // STALENESS: the range must sit inside a region this turn actually Read and
120
- // that still matches. Same guarantee as the substring path, checked here
121
- // directly (no old_string to search for).
122
- const stale = checkStaleRange(p, lines, start, end, ctx);
123
- if (stale) return stale;
124
-
125
- const inserted = normalizeText(new_string).split('\n');
126
- // The lines being REPLACED, captured before the splice. The TUI renders an
127
- // Edit's diff from the tool ARGUMENTS, and line-range mode has no
128
- // `old_string` to diff against — so without reporting them here the edit
129
- // drew NO diff at all (no +/- rows, no +N/-N counts). Reporting them lets
130
- // the caller diff the replaced region -> `new_string`.
131
- const replacedText = lines.slice(start - 1, end).join('\n');
132
- const out = [...lines.slice(0, start - 1), ...inserted, ...lines.slice(end)];
133
- const normUpdated = out.join('\n');
134
- const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
135
- // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
136
- checkpointBeforeWrite(p, ctx);
137
- try {
138
- ensureDir(p);
139
- fs.writeFileSync(p, updated, 'utf8');
140
- } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
141
- refreshReadPool(p, normUpdated, { start, end: start + inserted.length - 1 }, ctx);
142
- const removed = end - start + 1;
143
- // Publish the diff for the UI. The Edit line is drawn from these, so a
144
- // line-range edit shows the same +/- rows and +N/-N counts as a substring
145
- // edit instead of nothing. `ctx.lastEditDiff` is consumed (and cleared) by
146
- // the agent loop right after this tool returns.
147
- if (ctx) ctx.lastEditDiff = { old: replacedText, new: normalizeText(new_string), startLine: start };
148
- return `Edited ${args.path}: replaced lines ${start}-${end} (${removed} line${removed === 1 ? '' : 's'}) with ${inserted.length} line${inserted.length === 1 ? '' : 's'}.`;
149
- }
150
-
151
-
152
- // ---- SUBSTRING mode (old_string -> new_string) --------------------------
153
- let { old_string, new_string, replace_all = false } = args;
154
- // Reaching here means neither mode was usable: line-range needs
155
- // start_line+end_line (handled above) and substring needs old_string. When
156
- // BOTH are absent, say so — "old_string must not be empty" sends the model
157
- // hunting for a stray empty string it never sent.
158
- if (old_string == null && new_string == null) {
159
- return 'Error: no edit mode given. Pass EITHER (start_line, end_line, new_string) OR (old_string, new_string).';
160
- }
161
- if (old_string === '' || old_string == null) return `Error: old_string must not be empty.`;
162
- if (new_string == null) return `Error: new_string is required for substring mode.`;
163
-
164
- // --- Newline normalization (Windows CRLF) ---
165
- // The Read tool normalizes \r\n -> \n, so an agent builds old_string/new_string
166
- // with LF. But the file on disk may be CRLF, making a raw LF match fail. We
167
- // normalize the FILE content to LF for matching, then restore the file's own
168
- // line ending style when writing back, so we never corrupt or mix endings.
169
- const eol = content.includes('\r\n') ? '\r\n' : '\n';
170
- const normContent = content.split(/\r\n|\r|\n/).join('\n');
171
- const normOld = normalizeText(old_string);
172
- const normNew = normalizeText(new_string);
173
-
174
- let matchOld = normOld; // the string that will actually be matched/replaced
175
- let matchNew = normNew;
176
- let count = normContent.split(matchOld).length - 1;
177
- if (count === 0) {
178
- // Quote-normalized retry: the file may use curly quotes while the model sent
179
- // straight ones. Match on the normalized forms, then replace the ACTUAL
180
- // substring found in the file so typography is preserved.
181
- // Quote-normalized retry: the file may use curly quotes while the model sent
182
- // straight ones. Match on the normalized forms, then replace the ACTUAL
183
- // substring found in the file so typography is preserved. normalizeQuotes is
184
- // 1 char -> 1 char, so indices line up between the two strings.
185
- const normFileQ = normalizeQuotes(normContent);
186
- if (normFileQ !== normContent) {
187
- const normOldQ = normalizeQuotes(normOld);
188
- const idx = normFileQ.indexOf(normOldQ);
189
- if (idx >= 0) {
190
- matchOld = normContent.slice(idx, idx + normOldQ.length);
191
- matchNew = normNew; // keep the model's new_string as written
192
- count = normContent.split(matchOld).length - 1;
193
- }
194
- }
195
- }
196
- if (count === 0) {
197
- const near = nearestLineHint(normContent, normOld);
198
- return `Error: old_string not found in ${args.path}.${near}`;
199
- }
200
- if (count > 1 && !replace_all) {
201
- return `Error: old_string matched ${count} occurrences in ${args.path}. Use replace_all=true or make old_string unique.`;
202
- }
203
-
204
- // --- Staleness guard: the AI must edit against content it actually Read.
205
- // We stored per-region + whole-file hashes in ctx.readPool when Read ran.
206
- // If the file changed on disk since (external edit, stream, Ctrl-C side
207
- // effect), reject so a snippet edit cannot silently corrupt the file. ---
208
- const stale = checkStale(p, normContent, matchOld, ctx);
209
- if (stale) return stale;
210
-
211
- const normUpdated = replace_all
212
- ? normContent.replaceAll(matchOld, matchNew)
213
- : normContent.replace(matchOld, matchNew);
214
- const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
215
- // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
216
- checkpointBeforeWrite(p, ctx);
217
- try {
218
- ensureDir(p);
219
- fs.writeFileSync(p, updated, 'utf8');
220
- } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
221
- // Silently re-arm the Read snapshot for the edited region so the AI can keep
222
- // editing on top of its own change WITHOUT another Read: we recompute the
223
- // affected line range + hash from the NEW content and refresh the pool. We
224
- // also drop any previously-recorded region whose content no longer matches
225
- // (those are genuinely stale now). Nothing here is told to the model.
226
- if (ctx && ctx.readPool) {
227
- const entry = ctx.readPool.get(p);
228
- if (entry) {
229
- const newLines = normUpdated.split('\n');
230
- entry.fileHash = hashStr(normUpdated);
231
- entry.lines = newLines.length;
232
- // Locate the edit site in the NEW content: the first line of the new
233
- // text if present, else fall back to the old target's location.
234
- const anchor = String(matchNew).split('\n')[0];
235
- let at = newLines.indexOf(anchor);
236
- if (at < 0) at = newLines.indexOf(String(matchOld).split('\n')[0]);
237
- if (at >= 0) {
238
- const newSpan = String(matchNew).split('\n').length;
239
- const start = at + 1;
240
- const end = Math.min(newLines.length, at + Math.max(1, newSpan));
241
- // Re-hash every surviving old region against the new content, and add
242
- // the freshly-edited span. Regions that no longer match are dropped.
243
- const kept = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
244
- kept.push({ start, end, hash: hashLines(newLines, start, end) });
245
- entry.regions = kept;
246
- } else {
247
- // Could not locate the site: drop stale regions so nothing false stays.
248
- entry.regions = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
249
- }
250
- try { const st = fs.statSync(p); entry.size = st.size; entry.mtimeMs = st.mtimeMs; } catch {}
251
- }
252
- }
253
- const occurrences = replace_all ? count : 1;
254
- // Publish the diff for the UI (same contract as the line-range path above).
255
- if (ctx) {
256
- const startLine = (() => {
257
- const at = normContent.split('\n').indexOf(String(normOld).split('\n')[0]);
258
- return at >= 0 ? at + 1 : 1;
259
- })();
260
- ctx.lastEditDiff = { old: normalizeText(old_string), new: normalizeText(new_string), startLine };
261
- }
262
- return `Edited ${args.path}: replaced ${occurrences} occurrence(s).`;
263
- },
264
- };
265
-
266
- // Suggest a near-miss filename when a path does not exist: same directory, an
267
- // exact case-insensitive match, same stem with a different extension, or a
268
- // prefix match. Saves the model a round-trip of guessing (Claude Code's
269
- // "Did you mean X?").
270
- function similarFileHint(missingPath) {
271
- const dir = path.dirname(missingPath);
272
- const base = path.basename(missingPath);
273
- const stem = base.replace(/\.[^.]*$/, '').toLowerCase();
274
- let entries;
275
- try { entries = fs.readdirSync(dir); } catch { return ''; }
276
- const lower = base.toLowerCase();
277
- // Levenshtein distance, capped — enough to catch a typo (confg -> config).
278
- const lev = (a, b) => {
279
- const m = a.length, n = b.length;
280
- if (Math.abs(m - n) > 2) return 3;
281
- let prev = Array.from({ length: n + 1 }, (_, j) => j);
282
- for (let i = 1; i <= m; i++) {
283
- const cur = [i];
284
- for (let j = 1; j <= n; j++) {
285
- cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
286
- }
287
- prev = cur;
288
- }
289
- return prev[n];
290
- };
291
- let cand = entries.find((e) => e.toLowerCase() === lower);
292
- if (!cand) {
293
- let best = null, bestD = 3;
294
- for (const e of entries) {
295
- const d = lev(stem, e.replace(/\.[^.]*$/, '').toLowerCase());
296
- if (d < bestD) { bestD = d; best = e; }
297
- }
298
- cand = best;
299
- }
300
- if (cand && cand !== base) return ` Did you mean "${path.join(dir, cand)}"?`;
301
- return '';
302
- }
303
-
304
- // When old_string is not found, look for the closest line in the file and name
305
- // it, so the model can see what the text actually is instead of guessing.
306
- function nearestLineHint(content, oldStr) {
307
- const want = String(oldStr).split('\n')[0].trim();
308
- if (!want || want.length < 3) return '';
309
- const lines = String(content).split('\n');
310
- // Character bigrams: robust to small differences and cheap on long lines.
311
- const grams = (s) => {
312
- const set = new Set();
313
- for (let i = 0; i + 1 < s.length; i++) set.add(s.slice(i, i + 2));
314
- return set;
315
- };
316
- const wantGrams = grams(want);
317
- if (!wantGrams.size) return '';
318
- let best = -1, bestScore = 0;
319
- for (let i = 0; i < lines.length; i++) {
320
- const g = grams(lines[i].trim());
321
- if (!g.size) continue;
322
- let hit = 0;
323
- for (const t of wantGrams) if (g.has(t)) hit++;
324
- const score = hit / wantGrams.size;
325
- if (score > bestScore) { bestScore = score; best = i; }
326
- }
327
- if (best >= 0 && bestScore >= 0.5) {
328
- return ` The closest line is line ${best + 1}: ${JSON.stringify(lines[best].trim().slice(0, 120))}`;
329
- }
330
- return '';
331
- }
332
-
333
- // Returns an error message when the edit is stale, else null (safe to edit).
334
- function checkStale(p, normContent, normOld, ctx) {
335
- if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
336
- const entry = ctx.readPool.get(p);
337
- if (!entry) return null; // this file was never Read this turn; allow
338
-
339
- const curLines = normContent.split('\n');
340
- const curFileHash = hashStr(normContent);
341
-
342
- // Locate the edit target's first line in the CURRENT file (1-based).
343
- const firstLine = String(normOld).split('\n')[0];
344
- const idx = curLines.indexOf(firstLine);
345
- const editLine = idx >= 0 ? idx + 1 : -1;
346
-
347
- // (1) The edit target must sit inside a region the AI actually Read, and that
348
- // region's content must still match what was Read. Reading the WHOLE file
349
- // records a region covering every line, so this also covers "read full,
350
- // edit a part". This is what rejects "read lines 1-3, edit line 7".
351
- if (editLine > 0) {
352
- const coveredByIntactRegion = entry.regions.some(
353
- (r) => editLine >= r.start && editLine <= r.end && hashLines(curLines, r.start, r.end) === r.hash,
354
- );
355
- if (coveredByIntactRegion) return null;
356
- }
357
-
358
- // (2) Whole file unchanged since Read, but the edit target was never Read
359
- // (no region covers it). Name the exact lines so the model reads the right
360
- // window instead of guessing.
361
- if (curFileHash === entry.fileHash) {
362
- const span = String(normOld).split('\n').length;
363
- const at = editLine > 0 ? editLine : 1;
364
- 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.`;
365
- }
366
-
367
- // (3) The file changed on disk since it was Read and the edit target is not in
368
- // an intact Read region. Reject so a stale snippet cannot corrupt the file.
369
- const at3 = editLine > 0 ? ` (target line ${editLine})` : '';
370
- 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.`;
371
- }
372
-
373
- // A ready-to-use Read call for the hint. Keeps the model from guessing line ranges.
374
- function args_readHint(p, at, span) {
375
- const from = Math.max(1, at - 3);
376
- const n = Math.max(span + 6, 10);
377
- return `Read { path: ${JSON.stringify(p)}, line_offset: ${from}, n_lines: ${n} }`;
378
- }
379
- // ---- helpers for the line-range path ---------------------------------------
380
-
381
- // Same guarantee as checkStale, but for an explicit [start, end] line range:
382
- // every line in the range must sit inside a region that was Read this turn and
383
- // whose content still matches. Returns an error string, or null when safe.
384
- function checkStaleRange(p, curLines, start, end, ctx) {
385
- if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
386
- const entry = ctx.readPool.get(p);
387
- if (!entry) return null; // never Read this turn; allow
388
-
389
- const normContent = curLines.join('\n');
390
- const curFileHash = hashStr(normContent);
391
-
392
- // A range is "read" when the regions the model has SEEN cover it — not only when
393
- // a single region spans it. A file read in two passes (5-10 then 11-16) must
394
- // allow editing 5-16: the two slices are contiguous, both still intact, so the
395
- // written range is fully known. Requiring one enclosing region rejected that
396
- // perfectly safe edit and forced a third Read.
397
- //
398
- // Only regions whose hash STILL matches count: a region whose text changed is no
399
- // longer what the model saw, so it cannot vouch for anything. The cover must also
400
- // be SEAMLESS — a gap (5-10 and 12-16 with 11 unread) leaves 11 unknown, so it
401
- // does NOT count, and the edit is correctly refused.
402
- const intact = entry.regions
403
- .filter((r) => hashLines(curLines, r.start, r.end) === r.hash)
404
- .sort((a, b) => a.start - b.start);
405
- let reach = start - 1; // highest line known to be covered
406
- for (const r of intact) {
407
- if (r.end < start) continue; // entirely before the target
408
- if (r.start > reach + 1) break; // a gap opens before this region: stop
409
- if (r.end > reach) reach = r.end;
410
- if (reach >= end) return null; // reached the end: fully covered
411
- }
412
-
413
- if (curFileHash === entry.fileHash) {
414
- // No "(read so far: …)" listing: the range is what the model must act on, and
415
- // echoing the regions it HAS read only invited it to reason about them instead
416
- // of re-reading the target lines.
417
- return `Edit rejected: lines ${start}-${end} were not read in ${p}. Read them first — ${args_readHint(p, start, end - start + 1)} — then Edit.`;
418
- }
419
- 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.`;
420
- }
421
-
422
- // Refresh the region cache after a successful edit: drop regions that no longer
423
- // match the NEW content, and record the freshly-written span. Mirrors the
424
- // re-arm block used by the substring path.
425
- function refreshReadPool(p, normUpdated, written, ctx) {
426
- if (!ctx || !ctx.readPool) return;
427
- const entry = ctx.readPool.get(p);
428
- if (!entry) return;
429
- const newLines = normUpdated.split('\n');
430
- entry.fileHash = hashStr(normUpdated);
431
- entry.lines = newLines.length;
432
- const kept = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
433
- kept.push({ start: written.start, end: Math.min(newLines.length, Math.max(written.start, written.end)), hash: hashLines(newLines, written.start, Math.min(newLines.length, Math.max(written.start, written.end))) });
434
- entry.regions = kept;
435
- try { const st = fs.statSync(p); entry.size = st.size; entry.mtimeMs = st.mtimeMs; } catch {}
436
- }
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:\n- LINE-RANGE mode: path + start_line + end_line + new_string. Replaces lines [start_line, end_line] with new_string.\nPREFERRED — use it whenever you have Read the file and know the line numbers.\n- EXACT-SUBSTRING mode: path + old_string + new_string. Replaces text exactly matching old_string. Use when the exact text is known and a line range is not convenient.\n- RANGED SUBSTRING mode: path + start_line + end_line + old_string + new_string. Searches for old_string ONLY inside [start_line, end_line], and replaces only what it finds there. Use this when the same snippet appears several times and you need exactly one of them: replace_all changes every copy, while plain substring mode refuses an ambiguous match. The range says WHERE to look, old_string says WHAT to replace.\nLEADING WHITESPACE — SPELL IT OUT ON EVERY LINE, INCLUDING THE FIRST. new_string is written VERBATIM in both modes: nothing is re-indented, auto-indented, or trimmed, and there is no tolerance for a missing first-line indent. Reproduce the indentation the code SHOULD have; it need not match the surrounding block. Copy it from the Read output, after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`).\nWRONG — nothing between the quote and `return`, so the line lands at column 0 inside an indented block. Look at the SHAPE as well: the quote touches the first character, and spaces only turn up after the first newline.\nnew_string: "return total;\n total += 1;"\nRIGHT — four spaces, then `return`. The opening quote is followed by the indent as well, so every line carries its own indentation INCLUDING the first:\nnew_string: " return total;\n total += 1;"\nSame call, same words. The only difference is the spaces at the START of the first line, and that is the whole point — in the RIGHT form the indent sits between the quote and the code, exactly where it sits in the file you copied it from.\nThe same applies to tabs, and to a line whose indentation changes partway through.\nRANGE HYGIENE — WRITE ONLY THE LINES YOU ARE REPLACING. Lines [start_line, end_line] are deleted and new_string is inserted in their place, so a line you leave OUTSIDE that range survives — and if you also restated it inside new_string you get TWO copies. Check what sits on end_line + 1 before deciding where the range ends. In RANGED SUBSTRING mode this does not apply: only the snippet is replaced, not the whole range.\nWRONG — end_line: 3 deletes lines 2-3, but line 4 is repeated because its content was also written into new_string:\nnew_string: "const a = 1;\\nconst b = 20;\\nconst c = 3;"\nRIGHT — the range covers exactly what is being replaced, and nothing beyond it is restated:\nnew_string: "const a = 1;\\nconst b = 20;"\nTo touch line 4 as well, set end_line: 4 and include its new content in new_string.\nIn SUBSTRING and RANGED SUBSTRING modes old_string is matched EXACTLY, including the indentation of its own first line.\nOmitting new_string is an error, not an empty replacement.\nMis-indented lines often still parse, so a green test run is not proof that an edit landed correctly — re-Read the region before editing it again.\',',
32
+ parameters: {
33
+ type: 'object',
34
+ properties: {
35
+ path: { type: 'string', description: 'Path to the file to edit.' },
36
+ 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.' },
37
+ 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. In SUBSTRING mode it replaces old_string, which is itself matched exactly including its own indentation.' },
38
+
39
+ replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string.' },
40
+ start_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based first line to replace (requires end_line and new_string). With old_string too, it is the first line to SEARCH for it in.' },
41
+ end_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based last line to replace (inclusive; requires start_line). With old_string too, it is the last line to search in.' },
42
+ },
43
+ // Three accepted shapes:
44
+ // line-range start_line + end_line + new_string
45
+ // exact-substring old_string + new_string
46
+ // rangedToWindow-substring start_line + end_line + old_string + new_string
47
+ // Line-range is the preferred route; the third exists for "one of several copies".
48
+ anyOf: [
49
+ { required: ['path', 'start_line', 'end_line', 'new_string'] },
50
+ { required: ['path', 'old_string', 'new_string'] },
51
+ ],
52
+ },
53
+ async execute(args, ctx) {
54
+ // Validate BEFORE resolving the path. `resolvePath(undefined)` resolves to the
55
+ // workspace root rather than failing, so a truncated tool call (agent.js falls
56
+ // back to `{ raw, _rawLen }` when the streamed JSON will not parse) could
57
+ // target a DIRECTORY and produce a confusing EISDIR/ENOENT instead of "retry
58
+ // the call".
59
+ if (typeof args.path !== 'string' || !args.path.trim()) {
60
+ const truncated = args && args.raw
61
+ ? ` 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).`
62
+ : '';
63
+ return `Error: \`path\` is required and must be a non-empty string.${truncated}`;
64
+ }
65
+ let p;
66
+ try { p = resolvePath(args.path, ctx); } catch (e) { return e.message; }
67
+ // A Jupyter notebook is JSON, not text: a snippet edit corrupts it. Point the
68
+ // model at the notebook-aware tool instead (mirrors Claude Code errorCode 5).
69
+ if (String(p).toLowerCase().endsWith('.ipynb')) {
70
+ 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.`;
71
+ }
72
+ let content;
73
+ try {
74
+ content = fs.readFileSync(p, 'utf8');
75
+ } catch (e) {
76
+ if (e && e.code === 'ENOENT') {
77
+ return `Error reading ${args.path}: file does not exist.${similarFileHint(p)}`;
78
+ }
79
+ return `Error reading ${args.path}: ${e.message}`;
80
+ }
81
+ const { start_line, end_line } = args;
82
+ // THREE shapes, not two.
83
+ //
84
+ // line-range start_line + end_line + new_string
85
+ // substring old_string + new_string
86
+ // RANGED SUB start_line + end_line + old_string + new_string
87
+ //
88
+ // The third is what the first two cannot express: replace ONE occurrence of a snippet that
89
+ // appears several times, without `replace_all` (which would hit every copy) and without
90
+ // counting lines by hand. The range narrows WHERE to look; `old_string` says WHAT to replace
91
+ // inside it. Rejecting the combination sent callers to `replace_all` as their only option,
92
+ // which is how the wrong copy gets edited.
93
+ //
94
+ // `old_string` alongside a range is therefore not a mistake — but a range with NEITHER
95
+ // old_string nor new_string still is, and is reported below.
96
+ const hasRangeKeys = args.start_line != null || args.end_line != null;
97
+ const hasSubKeys = args.old_string != null;
98
+ const hasNewString = (args.new_string != null) || (args.new_content != null);
99
+ if (hasRangeKeys && hasSubKeys && !hasNewString) {
100
+ return 'Error: a rangedToWindow edit needs new_string as well as old_string.';
101
+ }
102
+
103
+ // ---- RANGED SUBSTRING ---------------------------------------------------
104
+ // A range AND an old_string: search for the snippet only INSIDE the range. Handled here,
105
+ // before the pure line-range path, because that path replaces whole lines and would ignore
106
+ // the snippet entirely — the very ambiguity the old mutual-exclusion check was avoiding.
107
+ //
108
+ // The range is validated, then the substring path below does the matching with the search
109
+ // window clamped to it. Splitting the work this way keeps ONE implementation of matching
110
+ // (quote-normalized retry, staleness, whitespace tolerance) instead of a second, weaker copy.
111
+ // A HALF-GIVEN RANGE with an old_string is not a reason to refuse: the snippet locates the
112
+ // edit by itself, and the single bound is a hint that failed to pair. Callers add `start_line`
113
+ // from the schema's own wording ("1-based first line to replace") expecting it to help, so
114
+ // refusing rejected a request that was already complete.
115
+ //
116
+ // `rangedToWindow` is set even though no window is applied. It means "the range question has been
117
+ // settled", which is what the line-range guard below tests — leaving it false made that guard
118
+ // see the same unpaired bound and reject the call one block later.
119
+ let searchFrom = 0;
120
+ let searchTo = 0; // 0,0 = the whole file
121
+ // A real window was validated, so the search below is confined to it. Distinct from
122
+ // `rangeHandled`: this one means "clamp", and setting it for a snippet with no window made
123
+ // every search run inside 0..0 and find nothing.
124
+ let rangedToWindow = false;
125
+ // The range question is answered — either a window was applied, or the caller gave an
126
+ // `old_string` that locates the edit on its own and a half-given bound was ignored.
127
+ let rangeHandled = hasSubKeys;
128
+ if (hasRangeKeys && hasSubKeys && hasNewString) {
129
+ if ((start_line != null) !== (end_line != null)) {
130
+ // Ignore the unpaired bound; `searchFrom`/`searchTo` stay at the whole file and `rangedToWindow`
131
+ // was already set above.
132
+ searchFrom = 0;
133
+ searchTo = 0;
134
+ } else {
135
+ // The range was given in full: validate it, then confine the search to it.
136
+ const start = Number(start_line) | 0, end = Number(end_line) | 0;
137
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 1 || end < start) {
138
+ return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
139
+ }
140
+ {
141
+ const all = content.split(/\r\n|\r|\n/);
142
+ if (end > all.length) {
143
+ return `Error: end_line ${end_line} exceeds file length (${all.length} lines).`;
144
+ }
145
+ }
146
+ rangedToWindow = true;
147
+ rangeHandled = true;
148
+ searchFrom = start;
149
+ searchTo = end;
150
+ }
151
+ }
152
+
153
+ // ---- LINE-RANGE mode ---------------------------------------------------
154
+ // `start_line`..`end_line` replace the lines at those 1-based positions,
155
+ // with NO old_string involved at all. This is the path for "change line 12"
156
+ // where spelling out the exact current text is awkward.
157
+ if (!rangeHandled && (start_line != null) !== (end_line != null)) {
158
+ return 'Error: line-range mode needs BOTH start_line and end_line.';
159
+ }
160
+ if (!rangeHandled && start_line != null && end_line != null) {
161
+ // Accept both spellings so old new_content callers keep working.
162
+ const new_string = args.new_string != null ? args.new_string : args.new_content;
163
+ // new_string is required — a missing one would put the literal string
164
+ // "undefined" in the file.
165
+ if (new_string == null) return `Error: new_string is required for line-range mode (pass an empty string to delete the lines).`;
166
+ if (typeof new_string !== 'string') {
167
+ return `Error: new_string must be a string (got ${new_string === null ? 'null' : typeof new_string}).`;
168
+ }
169
+ const start = Number(start_line) | 0, end = Number(end_line) | 0;
170
+ if (start < 1 || end < start) {
171
+ return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
172
+ }
173
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
174
+ const lines = content.split(/\r\n|\r|\n/);
175
+ if (end > lines.length) {
176
+ return `Error: end_line ${end_line} exceeds file length (${lines.length} lines).`;
177
+ }
178
+ // STALENESS: the range must sit inside a region this turn actually Read and
179
+ // that still matches. Same guarantee as the substring path, checked here
180
+ // directly (no old_string to search for).
181
+ const stale = checkStaleRange(p, lines, start, end, ctx);
182
+ if (stale) return stale;
183
+
184
+ const inserted = normalizeText(new_string).split('\n');
185
+ // The lines being REPLACED, captured before the splice. The TUI renders an
186
+ // Edit's diff from the tool ARGUMENTS, and line-range mode has no
187
+ // `old_string` to diff against — so without reporting them here the edit
188
+ // drew NO diff at all (no +/- rows, no +N/-N counts). Reporting them lets
189
+ // the caller diff the replaced region -> `new_string`.
190
+ const replacedText = lines.slice(start - 1, end).join('\n');
191
+ const out = [...lines.slice(0, start - 1), ...inserted, ...lines.slice(end)];
192
+ const normUpdated = out.join('\n');
193
+ const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
194
+ // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
195
+ checkpointBeforeWrite(p, ctx);
196
+ try {
197
+ ensureDir(p);
198
+ fs.writeFileSync(p, updated, 'utf8');
199
+ } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
200
+ refreshReadPool(p, normUpdated, { start, end: start + inserted.length - 1 }, ctx);
201
+ const removed = end - start + 1;
202
+ // Publish the diff for the UI. The Edit line is drawn from these, so a
203
+ // line-range edit shows the same +/- rows and +N/-N counts as a substring
204
+ // edit instead of nothing. `ctx.lastEditDiff` is consumed (and cleared) by
205
+ // the agent loop right after this tool returns.
206
+ //
207
+ // `lines` is the pre-edit content, which is what `start` indexes into.
208
+ if (ctx) ctx.lastEditDiff = buildEditDiff({ fileLines: lines, oldText: replacedText, newText: new_string, startLine: start });
209
+ return `Edited ${args.path}: replaced lines ${start}-${end} (${removed} line${removed === 1 ? '' : 's'}) with ${inserted.length} line${inserted.length === 1 ? '' : 's'}.`;
210
+ }
211
+
212
+
213
+ // ---- SUBSTRING mode (old_string -> new_string) --------------------------
214
+ let { old_string, new_string, replace_all = false } = args;
215
+ // Reaching here means neither mode was usable: line-range needs
216
+ // start_line+end_line (handled above) and substring needs old_string. When
217
+ // BOTH are absent, say so — "old_string must not be empty" sends the model
218
+ // hunting for a stray empty string it never sent.
219
+ if (old_string == null && new_string == null) {
220
+ return 'Error: no edit mode given. Pass EITHER (start_line, end_line, new_string) OR (old_string, new_string).';
221
+ }
222
+ if (old_string === '' || old_string == null) return `Error: old_string must not be empty.`;
223
+ if (new_string == null) return `Error: new_string is required for substring mode.`;
224
+
225
+ // --- Newline normalization (Windows CRLF) ---
226
+ // The Read tool normalizes \r\n -> \n, so an agent builds old_string/new_string
227
+ // with LF. But the file on disk may be CRLF, making a raw LF match fail. We
228
+ // normalize the FILE content to LF for matching, then restore the file's own
229
+ // line ending style when writing back, so we never corrupt or mix endings.
230
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
231
+ const normContent = content.split(/\r\n|\r|\n/).join('\n');
232
+ const normOld = normalizeText(old_string);
233
+ const normNew = normalizeText(new_string);
234
+
235
+ // A RANGED edit searches only inside the given lines. `windowStart` is the character offset of
236
+ // the range's first line in `normContent`, and `windowEnd` the end of its last line; the whole
237
+ // file is the window when no range was given. Every match, count and replacement below uses
238
+ // this window, so a snippet that appears elsewhere in the file is neither found nor touched —
239
+ // which is the entire point, and what `replace_all` cannot express.
240
+ let windowStart = 0;
241
+ let windowEnd = normContent.length;
242
+ if (rangedToWindow) {
243
+ const allLines = normContent.split('\n');
244
+ // Offset of line N's first character: the sum of the lengths of lines 1..N-1 plus their
245
+ // newlines. Computed by walking, because a single `indexOf` would find the wrong copy of a
246
+ // line that also occurs earlier in the file.
247
+ const offsetOfLine = (n) => {
248
+ let at = 0;
249
+ for (let i = 0; i < n - 1 && i < allLines.length; i++) at += allLines[i].length + 1;
250
+ return at;
251
+ };
252
+ windowStart = offsetOfLine(searchFrom);
253
+ const lastLineStart = offsetOfLine(searchTo);
254
+ windowEnd = Math.min(normContent.length, lastLineStart + (allLines[searchTo - 1] || '').length);
255
+ }
256
+ /** Occurrences of `needle` inside the window. */
257
+ const countInWindow = (needle) => {
258
+ if (!needle) return 0;
259
+ const seg = normContent.slice(windowStart, windowEnd);
260
+ return seg.split(needle).length - 1;
261
+ };
262
+
263
+ let matchOld = normOld; // the string that will actually be matched/replaced
264
+ let matchNew = normNew;
265
+ let count = countInWindow(matchOld);
266
+ if (count === 0) {
267
+ // Quote-normalized retry: the file may use curly quotes while the model sent
268
+ // straight ones. Match on the normalized forms, then replace the ACTUAL
269
+ // substring found in the file so typography is preserved. normalizeQuotes is
270
+ // 1 char -> 1 char, so indices line up between the two strings.
271
+ const normFileQ = normalizeQuotes(normContent);
272
+ if (normFileQ !== normContent) {
273
+ const normOldQ = normalizeQuotes(normOld);
274
+ // Search the NORMALIZED window for the normalized snippet, then take the real text at
275
+ // that place so the replacement keeps the file's own typography.
276
+ const idx = normFileQ.indexOf(normOldQ, windowStart);
277
+ if (idx >= 0 && idx + normOldQ.length <= windowEnd) {
278
+ matchOld = normContent.slice(idx, idx + normOldQ.length);
279
+ matchNew = normNew; // keep the model's new_string as written
280
+ count = countInWindow(matchOld);
281
+ }
282
+ }
283
+ }
284
+ if (count === 0) {
285
+ if (rangedToWindow) {
286
+ // Say WHERE it was looked for, so a snippet that exists elsewhere is not reported as
287
+ // missing outright — that sends the caller hunting for a typo that is not there.
288
+ const elsewhere = normContent.split(normOld).length - 1;
289
+ const hint = elsewhere
290
+ ? ` It appears ${elsewhere} time(s) elsewhere in the file, outside lines ${searchFrom}-${searchTo}. Broaden the range, or correct the range.`
291
+ : '';
292
+ return `Error: old_string not found within lines ${searchFrom}-${searchTo} of ${args.path}.${hint}`;
293
+ }
294
+ const near = nearestLineHint(normContent, normOld);
295
+ return `Error: old_string not found in ${args.path}.${near}`;
296
+ }
297
+ if (count > 1 && !replace_all) {
298
+ if (rangedToWindow) {
299
+ 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.`;
300
+ }
301
+ return `Error: old_string matched ${count} occurrences in ${args.path}. Use replace_all=true or make old_string unique.`;
302
+ }
303
+ // --- Staleness guard: the AI must edit against content it actually Read.
304
+ // We stored per-region + whole-file hashes in ctx.readPool when Read ran.
305
+ // If the file changed on disk since (external edit, stream, Ctrl-C side
306
+ // effect), reject so a snippet edit cannot silently corrupt the file. ---
307
+ const stale = checkStale(p, normContent, matchOld, ctx);
308
+ if (stale) return stale;
309
+
310
+ // Replace INSIDE the window only. A rangedToWindow edit must not touch an identical snippet sitting
311
+ // before or after the range — replacing across the whole file is the failure the range exists
312
+ // to prevent. With no range the window IS the whole file, so non-rangedToWindow callers are unchanged.
313
+ const normUpdated = (() => {
314
+ const head = normContent.slice(0, windowStart);
315
+ const body = normContent.slice(windowStart, windowEnd);
316
+ const tail = normContent.slice(windowEnd);
317
+ return head + (replace_all ? body.replaceAll(matchOld, matchNew) : body.replace(matchOld, matchNew)) + tail;
318
+ })();
319
+ const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
320
+ // Checkpoint the pre-edit content so /undo can put it back (file-history.js).
321
+ checkpointBeforeWrite(p, ctx);
322
+ try {
323
+ ensureDir(p);
324
+ fs.writeFileSync(p, updated, 'utf8');
325
+ } catch (e) { return `Error writing ${args.path}: ${e.message}`; }
326
+ // Silently re-arm the Read snapshot for the edited region so the AI can keep
327
+ // editing on top of its own change WITHOUT another Read: we recompute the
328
+ // affected line range + hash from the NEW content and refresh the pool. We
329
+ // also drop any previously-recorded region whose content no longer matches
330
+ // (those are genuinely stale now). Nothing here is told to the model.
331
+ if (ctx && ctx.readPool) {
332
+ const entry = ctx.readPool.get(p);
333
+ if (entry) {
334
+ const newLines = normUpdated.split('\n');
335
+ entry.fileHash = hashStr(normUpdated);
336
+ entry.lines = newLines.length;
337
+ // Locate the edit site in the NEW content: the first line of the new
338
+ // text if present, else fall back to the old target's location.
339
+ const anchor = String(matchNew).split('\n')[0];
340
+ let at = newLines.indexOf(anchor);
341
+ if (at < 0) at = newLines.indexOf(String(matchOld).split('\n')[0]);
342
+ if (at >= 0) {
343
+ const newSpan = String(matchNew).split('\n').length;
344
+ const start = at + 1;
345
+ const end = Math.min(newLines.length, at + Math.max(1, newSpan));
346
+ // Re-hash every surviving old region against the new content, and add
347
+ // the freshly-edited span. Regions that no longer match are dropped.
348
+ const kept = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
349
+ kept.push({ start, end, hash: hashLines(newLines, start, end) });
350
+ entry.regions = kept;
351
+ } else {
352
+ // Could not locate the site: drop stale regions so nothing false stays.
353
+ entry.regions = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
354
+ }
355
+ try { const st = fs.statSync(p); entry.size = st.size; entry.mtimeMs = st.mtimeMs; } catch {}
356
+ }
357
+ }
358
+ const occurrences = replace_all ? count : 1;
359
+ // Publish the diff for the UI (same contract as the line-range path above).
360
+ if (ctx) {
361
+ const at = normContent.split('\n').indexOf(String(normOld).split('\n')[0]);
362
+ const startLine = at >= 0 ? at + 1 : 1;
363
+ ctx.lastEditDiff = buildEditDiff({
364
+ fileLines: normContent.split('\n'),
365
+ oldText: old_string,
366
+ newText: new_string,
367
+ startLine,
368
+ });
369
+ }
370
+ return `Edited ${args.path}: replaced ${occurrences} occurrence(s).`;
371
+ },
372
+ };
373
+
374
+ /** How many unchanged lines to show on each side of a changed region. */
375
+
376
+ /** How many unchanged lines to show on each side of a changed region. */
377
+ const DIFF_CONTEXT = 5;
378
+
379
+ /**
380
+ * Build the diff payload, including the unchanged lines around the change.
381
+ *
382
+ * The replaced lines alone do not tell a reader WHERE the edit landed: a four-line block quoted
383
+ * with no surroundings could be anywhere in a 500-line file, so neither the model nor the user
384
+ * could tell a correct edit from one applied at the right text in the wrong place — and with
385
+ * repeated code (several similar blocks, two `}` in a row) the same text appears in many places.
386
+ * `context` carries the file's own lines so the renderer can draw them unmarked, above and below.
387
+ *
388
+ * `fileLines` is the content BEFORE the edit for the replaced region's START LINE to be
389
+ * meaningful: `startLine` is a line number in that same file.
390
+ */
391
+ function buildEditDiff({ fileLines, oldText, newText, startLine }) {
392
+ const lines = Array.isArray(fileLines) ? fileLines : [];
393
+ const before = [];
394
+ const after = [];
395
+ const replacedCount = normalizeText(oldText).split('\n').length;
396
+ // `startLine` is 1-based; the replaced block occupies [startLine, startLine + n - 1].
397
+ const lastReplaced = startLine + replacedCount - 1;
398
+ for (let n = startLine - DIFF_CONTEXT; n < startLine; n++) {
399
+ if (n >= 1 && n <= lines.length) before.push({ n, text: lines[n - 1] });
400
+ }
401
+ for (let n = lastReplaced + 1; n <= lastReplaced + DIFF_CONTEXT; n++) {
402
+ if (n >= 1 && n <= lines.length) after.push({ n, text: lines[n - 1] });
403
+ }
404
+ return {
405
+ old: normalizeText(oldText),
406
+ new: normalizeText(newText),
407
+ startLine,
408
+ context: { before, after },
409
+ };
410
+ }
411
+
412
+ // Suggest a near-miss filename when a path does not exist: same directory, an
413
+ // exact case-insensitive match, same stem with a different extension, or a
414
+ // prefix match. Saves the model a round-trip of guessing (Claude Code's
415
+ // "Did you mean X?").
416
+ function similarFileHint(missingPath) {
417
+ const dir = path.dirname(missingPath);
418
+ const base = path.basename(missingPath);
419
+ const stem = base.replace(/\.[^.]*$/, '').toLowerCase();
420
+ let entries;
421
+ try { entries = fs.readdirSync(dir); } catch { return ''; }
422
+ const lower = base.toLowerCase();
423
+ // Levenshtein distance, capped — enough to catch a typo (confg -> config).
424
+ const lev = (a, b) => {
425
+ const m = a.length, n = b.length;
426
+ if (Math.abs(m - n) > 2) return 3;
427
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
428
+ for (let i = 1; i <= m; i++) {
429
+ const cur = [i];
430
+ for (let j = 1; j <= n; j++) {
431
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
432
+ }
433
+ prev = cur;
434
+ }
435
+ return prev[n];
436
+ };
437
+ let cand = entries.find((e) => e.toLowerCase() === lower);
438
+ if (!cand) {
439
+ let best = null, bestD = 3;
440
+ for (const e of entries) {
441
+ const d = lev(stem, e.replace(/\.[^.]*$/, '').toLowerCase());
442
+ if (d < bestD) { bestD = d; best = e; }
443
+ }
444
+ cand = best;
445
+ }
446
+ if (cand && cand !== base) return ` Did you mean "${path.join(dir, cand)}"?`;
447
+ return '';
448
+ }
449
+
450
+ // When old_string is not found, look for the closest line in the file and name
451
+ // it, so the model can see what the text actually is instead of guessing.
452
+ function nearestLineHint(content, oldStr) {
453
+ const want = String(oldStr).split('\n')[0].trim();
454
+ if (!want || want.length < 3) return '';
455
+ const lines = String(content).split('\n');
456
+ // Character bigrams: robust to small differences and cheap on long lines.
457
+ const grams = (s) => {
458
+ const set = new Set();
459
+ for (let i = 0; i + 1 < s.length; i++) set.add(s.slice(i, i + 2));
460
+ return set;
461
+ };
462
+ const wantGrams = grams(want);
463
+ if (!wantGrams.size) return '';
464
+ let best = -1, bestScore = 0;
465
+ for (let i = 0; i < lines.length; i++) {
466
+ const g = grams(lines[i].trim());
467
+ if (!g.size) continue;
468
+ let hit = 0;
469
+ for (const t of wantGrams) if (g.has(t)) hit++;
470
+ const score = hit / wantGrams.size;
471
+ if (score > bestScore) { bestScore = score; best = i; }
472
+ }
473
+ if (best >= 0 && bestScore >= 0.5) {
474
+ return ` The closest line is line ${best + 1}: ${JSON.stringify(lines[best].trim().slice(0, 120))}`;
475
+ }
476
+ return '';
477
+ }
478
+
479
+ // Returns an error message when the edit is stale, else null (safe to edit).
480
+ function checkStale(p, normContent, normOld, ctx) {
481
+ if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
482
+ const entry = ctx.readPool.get(p);
483
+ if (!entry) return null; // this file was never Read this turn; allow
484
+
485
+ const curLines = normContent.split('\n');
486
+ const curFileHash = hashStr(normContent);
487
+
488
+ // Locate the edit target's first line in the CURRENT file (1-based).
489
+ //
490
+ // An EXACT line match first, then a line that merely CONTAINS it. The exact match alone
491
+ // missed every edit whose `old_string` begins mid-line — `old_string: "return 1;"` against
492
+ // a line ` return 1;` found nothing, so `editLine` was -1 and step (1) below was skipped
493
+ // entirely: the edit was then reported as stale (branch 2) or, with the whole-file hash
494
+ // also differing, rejected as though the file had changed. Two-line `old_string`s are the
495
+ // common case for a range edit, and their first line usually IS whole, which is why this
496
+ // only showed up on single-line and indented-prefix edits.
497
+ const firstLine = String(normOld).split('\n')[0];
498
+ let idx = curLines.indexOf(firstLine);
499
+ if (idx < 0 && firstLine) idx = curLines.findIndex((l) => l.includes(firstLine));
500
+ const editLine = idx >= 0 ? idx + 1 : -1;
501
+
502
+ // (1) The edit target must sit inside a region the AI actually Read, and that
503
+ // region's content must still match what was Read. Reading the WHOLE file
504
+ // records a region covering every line, so this also covers "read full,
505
+ // edit a part". This is what rejects "read lines 1-3, edit line 7".
506
+ if (editLine > 0) {
507
+ const coveredByIntactRegion = entry.regions.some(
508
+ (r) => editLine >= r.start && editLine <= r.end && hashLines(curLines, r.start, r.end) === r.hash,
509
+ );
510
+ if (coveredByIntactRegion) return null;
511
+ }
512
+
513
+ // (2) Whole file unchanged since Read, but the edit target was never Read
514
+ // (no region covers it). Name the exact lines so the model reads the right
515
+ // window instead of guessing.
516
+ if (curFileHash === entry.fileHash) {
517
+ const span = String(normOld).split('\n').length;
518
+ const at = editLine > 0 ? editLine : 1;
519
+ 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.`;
520
+ }
521
+
522
+ // (3) The file changed on disk since it was Read and the edit target is not in
523
+ // an intact Read region. Reject so a stale snippet cannot corrupt the file.
524
+ const at3 = editLine > 0 ? ` (target line ${editLine})` : '';
525
+ 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.`;
526
+ }
527
+
528
+ // A ready-to-use Read call for the hint. Keeps the model from guessing line ranges.
529
+ function args_readHint(p, at, span) {
530
+ const from = Math.max(1, at - 3);
531
+ const n = Math.max(span + 6, 10);
532
+ return `Read { path: ${JSON.stringify(p)}, line_offset: ${from}, n_lines: ${n} }`;
533
+ }
534
+ // ---- helpers for the line-range path ---------------------------------------
535
+
536
+ // Same guarantee as checkStale, but for an explicit [start, end] line range:
537
+ // every line in the range must sit inside a region that was Read this turn and
538
+ // whose content still matches. Returns an error string, or null when safe.
539
+ function checkStaleRange(p, curLines, start, end, ctx) {
540
+ if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
541
+ const entry = ctx.readPool.get(p);
542
+ if (!entry) return null; // never Read this turn; allow
543
+
544
+ const normContent = curLines.join('\n');
545
+ const curFileHash = hashStr(normContent);
546
+
547
+ // A range is "read" when the regions the model has SEEN cover it — not only when
548
+ // a single region spans it. A file read in two passes (5-10 then 11-16) must
549
+ // allow editing 5-16: the two slices are contiguous, both still intact, so the
550
+ // written range is fully known. Requiring one enclosing region rejected that
551
+ // perfectly safe edit and forced a third Read.
552
+ //
553
+ // Only regions whose hash STILL matches count: a region whose text changed is no
554
+ // longer what the model saw, so it cannot vouch for anything. The cover must also
555
+ // be SEAMLESS — a gap (5-10 and 12-16 with 11 unread) leaves 11 unknown, so it
556
+ // does NOT count, and the edit is correctly refused.
557
+ const intact = entry.regions
558
+ .filter((r) => hashLines(curLines, r.start, r.end) === r.hash)
559
+ .sort((a, b) => a.start - b.start);
560
+ let reach = start - 1; // highest line known to be covered
561
+ for (const r of intact) {
562
+ if (r.end < start) continue; // entirely before the target
563
+ if (r.start > reach + 1) break; // a gap opens before this region: stop
564
+ if (r.end > reach) reach = r.end;
565
+ if (reach >= end) return null; // reached the end: fully covered
566
+ }
567
+
568
+ if (curFileHash === entry.fileHash) {
569
+ // No "(read so far: …)" listing: the range is what the model must act on, and
570
+ // echoing the regions it HAS read only invited it to reason about them instead
571
+ // of re-reading the target lines.
572
+ return `Edit rejected: lines ${start}-${end} were not read in ${p}. Read them first — ${args_readHint(p, start, end - start + 1)} — then Edit.`;
573
+ }
574
+ 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.`;
575
+ }
576
+
577
+ // Refresh the region cache after a successful edit: drop regions that no longer
578
+ // match the NEW content, and record the freshly-written span. Mirrors the
579
+ // re-arm block used by the substring path.
580
+ function refreshReadPool(p, normUpdated, written, ctx) {
581
+ if (!ctx || !ctx.readPool) return;
582
+ const entry = ctx.readPool.get(p);
583
+ if (!entry) return;
584
+ const newLines = normUpdated.split('\n');
585
+ entry.fileHash = hashStr(normUpdated);
586
+ entry.lines = newLines.length;
587
+ const kept = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
588
+ kept.push({ start: written.start, end: Math.min(newLines.length, Math.max(written.start, written.end)), hash: hashLines(newLines, written.start, Math.min(newLines.length, Math.max(written.start, written.end))) });
589
+ entry.regions = kept;
590
+ try { const st = fs.statSync(p); entry.size = st.size; entry.mtimeMs = st.mtimeMs; } catch {}
591
+ }