@hncode/hncode 0.8.0 → 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/README.md +18 -0
- package/README_CN.md +14 -0
- package/package.json +1 -1
- package/src/agent-task.js +354 -337
- package/src/agent.js +19 -3
- package/src/animate.js +35 -0
- package/src/clipboard.js +54 -5
- package/src/config.js +25 -7
- package/src/file-tree.js +4 -3
- package/src/highlight.js +20 -6
- package/src/i18n.js +825 -0
- package/src/image-row.js +11 -2
- package/src/index.js +730 -610
- package/src/llm.js +146 -21
- package/src/log-file.js +112 -0
- package/src/markdown.js +619 -567
- package/src/migrate-index.js +175 -0
- package/src/migrate.js +392 -0
- package/src/panels.js +9 -7
- package/src/rows-plan-bg.js +3 -2
- package/src/rows-status.js +20 -6
- package/src/rows-tool-result.js +35 -8
- package/src/screen-paint.js +153 -128
- package/src/session-recover.js +317 -0
- package/src/session.js +203 -13
- package/src/swarm-progress.js +5 -1
- package/src/tasks-browser.js +9 -8
- package/src/team-panel.js +12 -11
- package/src/text.js +192 -149
- package/src/tool-line.js +7 -2
- package/src/tool-result.js +400 -327
- package/src/tools/ask-user-question.js +1 -2
- package/src/tools/bash.js +23 -11
- package/src/tools/edit.js +640 -665
- package/src/tools/goal.js +130 -93
- package/src/tools/read.js +141 -133
- package/src/tools/shell.js +28 -2
- package/src/tools/tasks.js +214 -214
- package/src/tools/utils.js +143 -104
- package/src/tui.js +20689 -19943
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
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
{
|
|
74
|
-
{
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
//
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
} catch (e) {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
return `Error
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
//
|
|
128
|
-
//
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
//
|
|
139
|
-
//
|
|
140
|
-
//
|
|
141
|
-
//
|
|
142
|
-
//
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
if (
|
|
200
|
-
return `Error:
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
//
|
|
212
|
-
//
|
|
213
|
-
//
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
//
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
if (new_string == null
|
|
257
|
-
|
|
258
|
-
//
|
|
259
|
-
//
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
//
|
|
269
|
-
//
|
|
270
|
-
//
|
|
271
|
-
//
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
//
|
|
346
|
-
//
|
|
347
|
-
//
|
|
348
|
-
//
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
//
|
|
358
|
-
//
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
//
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
//
|
|
373
|
-
|
|
374
|
-
const
|
|
375
|
-
//
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
*
|
|
423
|
-
*
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
*
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
*
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
const
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
//
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
//
|
|
481
|
-
//
|
|
482
|
-
//
|
|
483
|
-
//
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
//
|
|
503
|
-
//
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
return
|
|
524
|
-
};
|
|
525
|
-
|
|
526
|
-
if (!
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
const
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
//
|
|
568
|
-
|
|
569
|
-
if (
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
//
|
|
577
|
-
//
|
|
578
|
-
//
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
//
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
//
|
|
611
|
-
//
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
//
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
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
|
+
|