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24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
100
101
102
103
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
200
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
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
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
457
458
459
460
461
462
463
464
465
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import * as fsPromises from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
import * as crypto from 'node:crypto';
import * as Diff from 'diff';
import {
  BaseDeclarativeTool,
  BaseToolInvocation,
  Kind,
  type ToolCallConfirmationDetails,
  type ToolConfirmationOutcome,
  type ToolEditConfirmationDetails,
  type ToolInvocation,
  type ToolLocation,
  type ToolResult,
  type ToolResultDisplay,
  type PolicyUpdateOptions,
  type ExecuteOptions,
  type FileDiff,
} from './tools.js';
import { buildFilePathArgsPattern } from '../policy/utils.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import { ToolErrorType } from './tool-error.js';
import {
  makeRelative,
  shortenPath,
  resolveDefensiveToolPath,
  resolveToRealPath,
} from '../utils/paths.js';
import { isNodeError } from '../utils/errors.js';
import { correctPath } from '../utils/pathCorrector.js';
import type { Config } from '../config/config.js';
import { CoreToolCallStatus } from '../scheduler/types.js';

import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js';
import { getDiffContextSnippet } from './diff-utils.js';
import {
  type ModifiableDeclarativeTool,
  type ModifyContext,
} from './modifiable-tool.js';
import { IdeClient } from '../ide/ide-client.js';
import { FixLLMEditWithInstruction } from '../utils/llm-edit-fixer.js';
import { safeLiteralReplace, detectLineEnding } from '../utils/textUtils.js';
import { EditStrategyEvent, EditCorrectionEvent } from '../telemetry/types.js';
import {
  logEditStrategy,
  logEditCorrectionEvent,
} from '../telemetry/loggers.js';

import { EDIT_TOOL_NAME, EDIT_DISPLAY_NAME } from './tool-names.js';
import { debugLogger } from '../utils/debugLogger.js';
import levenshtein from 'fast-levenshtein';
import { EDIT_DEFINITION } from './definitions/coreTools.js';
import { resolveToolDeclaration } from './definitions/resolver.js';
import { detectOmissionPlaceholders } from './omissionPlaceholderDetector.js';
import { discoverJitContext, appendJitContext } from './jit-context.js';
import { resolveAndValidatePlanPath } from '../utils/planUtils.js';
import { isBuildFile } from '../utils/buildFileUtils.js';
import { recordModifiedBuildFile } from '../utils/untrustedContextTracker.js';

const ENABLE_FUZZY_MATCH_RECOVERY = true;
const FUZZY_MATCH_THRESHOLD = 0.1; // Allow up to 10% weighted difference
const WHITESPACE_PENALTY_FACTOR = 0.1; // Whitespace differences cost 10% of a character difference
interface ReplacementContext {
  params: EditToolParams;
  currentContent: string;
  abortSignal: AbortSignal;
}

interface ReplacementResult {
  newContent: string;
  occurrences: number;
  finalOldString: string;
  finalNewString: string;
  strategy?: 'exact' | 'flexible' | 'regex' | 'fuzzy';
  matchRanges?: Array<{ start: number; end: number }>;
}

export function applyReplacement(
  currentContent: string | null,
  oldString: string,
  newString: string,
  isNewFile: boolean,
): string {
  if (isNewFile) {
    return newString;
  }
  if (currentContent === null) {
    // Should not happen if not a new file, but defensively return empty or newString if oldString is also empty
    return oldString === '' ? newString : '';
  }
  // If oldString is empty and it's not a new file, do not modify the content.
  if (oldString === '' && !isNewFile) {
    return currentContent;
  }

  // Use intelligent replacement that handles $ sequences safely
  return safeLiteralReplace(currentContent, oldString, newString);
}

/**
 * Creates a SHA256 hash of the given content.
 * @param content The string content to hash.
 * @returns A hex-encoded hash string.
 */
function hashContent(content: string): string {
  return crypto.createHash('sha256').update(content).digest('hex');
}

function restoreTrailingNewline(
  originalContent: string,
  modifiedContent: string,
): string {
  const hadTrailingNewline = originalContent.endsWith('\n');
  if (hadTrailingNewline && !modifiedContent.endsWith('\n')) {
    return modifiedContent + '\n';
  } else if (!hadTrailingNewline && modifiedContent.endsWith('\n')) {
    return modifiedContent.replace(/\n$/, '');
  }
  return modifiedContent;
}

/**
 * Escapes characters with special meaning in regular expressions.
 * @param str The string to escape.
 * @returns The escaped string.
 */
function escapeRegex(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

async function calculateExactReplacement(
  context: ReplacementContext,
): Promise<ReplacementResult | null> {
  const { currentContent, params } = context;
  const { old_string, new_string } = params;

  const normalizedCode = currentContent;
  const normalizedSearch = old_string.replace(/\r\n/g, '\n');
  const normalizedReplace = new_string.replace(/\r\n/g, '\n');

  const exactOccurrences = normalizedCode.split(normalizedSearch).length - 1;

  if (!params.allow_multiple && exactOccurrences > 1) {
    return {
      newContent: currentContent,
      occurrences: exactOccurrences,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace,
    };
  }

  if (exactOccurrences > 0) {
    let modifiedCode = safeLiteralReplace(
      normalizedCode,
      normalizedSearch,
      normalizedReplace,
    );
    modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
    return {
      newContent: modifiedCode,
      occurrences: exactOccurrences,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace,
    };
  }

  return null;
}

async function calculateFlexibleReplacement(
  context: ReplacementContext,
): Promise<ReplacementResult | null> {
  const { currentContent, params } = context;
  const { old_string, new_string } = params;

  const normalizedCode = currentContent;
  const normalizedSearch = old_string.replace(/\r\n/g, '\n');
  const normalizedReplace = new_string.replace(/\r\n/g, '\n');

  const sourceLines = normalizedCode.match(/.*(?:\n|$)/g)?.slice(0, -1) ?? [];
  const searchLinesStripped = normalizedSearch
    .split('\n')
    .map((line: string) => line.trim());
  const replaceLines = normalizedReplace.split('\n');

  let flexibleOccurrences = 0;
  let i = 0;
  while (i <= sourceLines.length - searchLinesStripped.length) {
    const window = sourceLines.slice(i, i + searchLinesStripped.length);
    const windowStripped = window.map((line: string) => line.trim());
    const isMatch = windowStripped.every(
      (line: string, index: number) => line === searchLinesStripped[index],
    );

    if (isMatch) {
      flexibleOccurrences++;
      const firstLineInMatch = window[0];
      const indentationMatch = firstLineInMatch.match(/^([ \t]*)/);
      const indentation = indentationMatch ? indentationMatch[1] : '';
      const newBlockWithIndent = applyIndentation(replaceLines, indentation);

      let replacementText = newBlockWithIndent.join('\n');
      if (
        new_string !== '' &&
        window[window.length - 1].endsWith('\n') &&
        !replacementText.endsWith('\n')
      ) {
        replacementText += '\n';
      }

      sourceLines.splice(i, searchLinesStripped.length, replacementText);
    }
    i++;
  }

  if (flexibleOccurrences > 0) {
    let modifiedCode = sourceLines.join('');
    modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
    return {
      newContent: modifiedCode,
      occurrences: flexibleOccurrences,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace,
    };
  }

  return null;
}

async function calculateRegexReplacement(
  context: ReplacementContext,
): Promise<ReplacementResult | null> {
  const { currentContent, params } = context;
  const { old_string, new_string } = params;

  // Normalize line endings for consistent processing.
  const normalizedSearch = old_string.replace(/\r\n/g, '\n');
  const normalizedReplace = new_string.replace(/\r\n/g, '\n');

  // This logic is ported from your Python implementation.
  // It builds a flexible, multi-line regex from a search string.
  const delimiters = ['(', ')', ':', '[', ']', '{', '}', '>', '<', '='];

  let processedString = normalizedSearch;
  for (const delim of delimiters) {
    processedString = processedString.split(delim).join(` ${delim} `);
  }

  // Split by any whitespace and remove empty strings.
  const tokens = processedString.split(/\s+/).filter(Boolean);

  if (tokens.length === 0) {
    return null;
  }

  const escapedTokens = tokens.map(escapeRegex);
  // Join tokens with `\s*` to allow for flexible whitespace between them.
  const pattern = escapedTokens.join('\\s*');

  // The final pattern captures leading whitespace (indentation) and then matches the token pattern.
  // 'm' flag enables multi-line mode, so '^' matches the start of any line.
  const finalPattern = `^([ \t]*)${pattern}`;

  // Always use a global regex to count all potential occurrences for accurate validation.
  const globalRegex = new RegExp(finalPattern, 'gm');
  const matches = currentContent.match(globalRegex);

  if (!matches) {
    return null;
  }

  const occurrences = matches.length;
  const newLines = normalizedReplace.split('\n');

  // Use the appropriate regex for replacement based on allow_multiple.
  const replaceRegex = new RegExp(
    finalPattern,
    params.allow_multiple ? 'gm' : 'm',
  );

  const modifiedCode = currentContent.replace(
    replaceRegex,
    (_match, indentation) =>
      applyIndentation(newLines, indentation || '').join('\n'),
  );

  return {
    newContent: restoreTrailingNewline(currentContent, modifiedCode),
    occurrences,
    finalOldString: normalizedSearch,
    finalNewString: normalizedReplace,
  };
}

export async function calculateReplacement(
  config: Config,
  context: ReplacementContext,
): Promise<ReplacementResult> {
  const { currentContent, params } = context;
  const { old_string, new_string } = params;
  const normalizedSearch = old_string.replace(/\r\n/g, '\n');
  const normalizedReplace = new_string.replace(/\r\n/g, '\n');

  if (normalizedSearch === '') {
    return {
      newContent: currentContent,
      occurrences: 0,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace,
    };
  }

  const exactResult = await calculateExactReplacement(context);
  if (exactResult) {
    const event = new EditStrategyEvent('exact');
    logEditStrategy(config, event);
    return exactResult;
  }

  const flexibleResult = await calculateFlexibleReplacement(context);
  if (flexibleResult) {
    const event = new EditStrategyEvent('flexible');
    logEditStrategy(config, event);
    return flexibleResult;
  }

  const regexResult = await calculateRegexReplacement(context);
  if (regexResult) {
    const event = new EditStrategyEvent('regex');
    logEditStrategy(config, event);
    return regexResult;
  }

  let fuzzyResult;
  if (
    ENABLE_FUZZY_MATCH_RECOVERY &&
    (fuzzyResult = await calculateFuzzyReplacement(config, context))
  ) {
    return fuzzyResult;
  }

  return {
    newContent: currentContent,
    occurrences: 0,
    finalOldString: normalizedSearch,
    finalNewString: normalizedReplace,
  };
}

export function getErrorReplaceResult(
  params: EditToolParams,
  occurrences: number,
  finalOldString: string,
  finalNewString: string,
) {
  let error: { display: string; raw: string; type: ToolErrorType } | undefined =
    undefined;
  if (occurrences === 0) {
    error = {
      display: `Could not find an exact match for old_string in '${params.file_path}'.`,
      raw: `Could not find an exact match for 'old_string' in '${params.file_path}'. If previous edits modified the file or you are modifying lines outside your recent read window, please use ReadFile to inspect the target lines before retrying with an exact 'old_string'.`,
      type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
    };
  } else if (!params.allow_multiple && occurrences !== 1) {
    error = {
      display: `Failed to edit, expected 1 occurrence but found ${occurrences}.`,
      raw: `Failed to edit, Expected 1 occurrence but found ${occurrences} for old_string in file: ${params.file_path}. If you intended to replace multiple occurrences, set 'allow_multiple' to true.`,
      type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
    };
  } else if (finalOldString === finalNewString) {
    error = {
      display: `No changes to apply. The old_string and new_string are identical.`,
      raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
      type: ToolErrorType.EDIT_NO_CHANGE,
    };
  }
  return error;
}

/**
 * Parameters for the Edit tool
 */
export interface EditToolParams {
  /**
   * The path to the file to modify
   */
  file_path: string;

  /**
   * The text to replace
   */
  old_string: string;

  /**
   * The text to replace it with
   */
  new_string: string;

  /**
   * If true, the tool will replace all occurrences of `old_string` with `new_string`.
   * If false (default), the tool will only succeed if exactly one occurrence is found.
   */
  allow_multiple?: boolean;

  /**
   * The instruction for what needs to be done.
   */
  instruction?: string;

  /**
   * Whether the edit was modified manually by the user.
   */
  modified_by_user?: boolean;

  /**
   * Initially proposed content.
   */
  ai_proposed_content?: string;
}

export function isEditToolParams(args: unknown): args is EditToolParams {
  if (typeof args !== 'object' || args === null) {
    return false;
  }
  return (
    'file_path' in args &&
    typeof args.file_path === 'string' &&
    'old_string' in args &&
    typeof args.old_string === 'string' &&
    'new_string' in args &&
    typeof args.new_string === 'string'
  );
}

function fileDiffToSummary(diff: FileDiff, editData: CalculatedEdit) {
  return diff.diffStat
    ? `${diff.diffStat.model_added_lines} added, ${diff.diffStat.model_removed_lines} removed`
    : `${editData.occurrences} replacements`;
}

interface CalculatedEdit {
  currentContent: string | null;
  newContent: string;
  occurrences: number;
  error?: { display: string; raw: string; type: ToolErrorType };
  isNewFile: boolean;
  originalLineEnding: '\r\n' | '\n';
  strategy?: 'exact' | 'flexible' | 'regex' | 'fuzzy';
  matchRanges?: Array<{ start: number; end: number }>;
}

class EditToolInvocation
  extends BaseToolInvocation<EditToolParams, ToolResult>
  implements ToolInvocation<EditToolParams, ToolResult>
{
  private readonly resolvedPath: string;

  constructor(
    private readonly config: Config,
    params: EditToolParams,
    messageBus: MessageBus,
    toolName?: string,
    displayName?: string,
  ) {
    super(
      params,
      messageBus,
      toolName,
      displayName,
      undefined,
      undefined,
      true,
      () => this.config.getApprovalMode(),
    );
    if (this.config.isPlanMode()) {
      try {
        const cleanFilePath = this.params.file_path.replace(/\0/g, '');
        const planPath = resolveAndValidatePlanPath(
          cleanFilePath,
          this.config.storage.getPlansDir(),
          this.config.getProjectRoot(),
        );
        this.resolvedPath = resolveToRealPath(planPath);
      } catch (e) {
        debugLogger.error(
          'Failed to resolve plan path during EditTool invocation setup',
          e,
        );
        // Validation fails, set resolvedPath to something that will fail validation downstream or just the raw path.
        // It's safer to store it so validation in execute() or getConfirmationDetails() catches it.
        this.resolvedPath = this.params.file_path.replace(/\0/g, '');
      }
    } else if (!path.isAbsolute(this.params.file_path)) {
      const result = correctPath(this.params.file_path, this.config);
      if (result.success) {
        try {
          this.resolvedPath = resolveToRealPath(result.correctedPath);
        } catch {
          this.resolvedPath = result.correctedPath;
        }
      } else {
        const sanitizedPath = resolveDefensiveToolPath(
          this.params.file_path,
          this.config.getTargetDir(),
        );
        try {
          this.resolvedPath = resolveToRealPath(
            path.resolve(this.config.getTargetDir(), sanitizedPath),
          );
        } catch {
          this.resolvedPath = path.resolve(
            this.config.getTargetDir(),
            sanitizedPath,
          );
        }
      }
    } else {
      const cleanPath = this.params.file_path.replace(/\0/g, '');
      try {
        this.resolvedPath = resolveToRealPath(cleanPath);
      } catch {
        this.resolvedPath = cleanPath;
      }
    }
  }

  override toolLocations(): ToolLocation[] {
    return [{ path: this.resolvedPath }];
  }

  override getPolicyUpdateOptions(
    _outcome: ToolConfirmationOutcome,
  ): PolicyUpdateOptions | undefined {
    return {
      argsPattern: buildFilePathArgsPattern(this.params.file_path),
    };
  }

  private async attemptSelfCorrection(
    params: EditToolParams,
    currentContent: string,
    initialError: { display: string; raw: string; type: ToolErrorType },
    abortSignal: AbortSignal,
    originalLineEnding: '\r\n' | '\n',
  ): Promise<CalculatedEdit> {
    // Fail fast without invoking FixLLMEditWithInstruction when old_string is empty
    if (!params.old_string || params.old_string.trim() === '') {
      return {
        currentContent,
        newContent: currentContent,
        occurrences: 0,
        isNewFile: false,
        error: {
          display: "Edit failed: 'old_string' cannot be empty.",
          raw: "The 'old_string' parameter is required. The Edit tool performs localized search-and-replace. If you are modifying a section of the file you have not viewed recently, call ReadFile on the target line range to inspect the current code, then provide the exact matching lines in 'old_string'.",
          type: ToolErrorType.INVALID_TOOL_PARAMS,
        },
        originalLineEnding,
      };
    }

    // In order to keep from clobbering edits made outside our system,
    // check if the file has been modified since we first read it.
    let errorForLlmEditFixer = initialError.raw;
    let contentForLlmEditFixer = currentContent;

    const initialContentHash = hashContent(currentContent);
    const onDiskContent = await this.config
      .getFileSystemService()
      .readTextFile(this.resolvedPath);
    const onDiskContentHash = hashContent(onDiskContent.replace(/\r\n/g, '\n'));

    if (initialContentHash !== onDiskContentHash) {
      // The file has changed on disk since we first read it.
      // Use the latest content for the correction attempt.
      contentForLlmEditFixer = onDiskContent.replace(/\r\n/g, '\n');
      errorForLlmEditFixer = `The initial edit attempt failed with the following error: "${initialError.raw}". However, the file has been modified by either the user or an external process since that edit attempt. The file content provided to you is the latest version. Please base your correction on this new content.`;
    }

    const fixedEdit = await FixLLMEditWithInstruction(
      params.instruction ?? 'Apply the requested edit.',
      params.old_string,
      params.new_string,
      errorForLlmEditFixer,
      contentForLlmEditFixer,
      this.config.getBaseLlmClient(),
      abortSignal,
    );

    // If the self-correction attempt timed out, return the original error.
    if (fixedEdit === null) {
      return {
        currentContent: contentForLlmEditFixer,
        newContent: currentContent,
        occurrences: 0,
        isNewFile: false,
        error: initialError,
        originalLineEnding,
      };
    }

    if (fixedEdit.noChangesRequired) {
      return {
        currentContent,
        newContent: currentContent,
        occurrences: 0,
        isNewFile: false,
        error: {
          display: `No changes required. The file already meets the specified conditions.`,
          raw: `A secondary check by an LLM determined that no changes were necessary to fulfill the instruction. Explanation: ${fixedEdit.explanation}. Original error with the parameters given: ${initialError.raw}`,
          type: ToolErrorType.EDIT_NO_CHANGE_LLM_JUDGEMENT,
        },
        originalLineEnding,
      };
    }

    const secondAttemptResult = await calculateReplacement(this.config, {
      params: {
        ...params,
        old_string: fixedEdit.search,
        new_string: fixedEdit.replace,
      },
      currentContent: contentForLlmEditFixer,
      abortSignal,
    });

    const secondError = getErrorReplaceResult(
      params,
      secondAttemptResult.occurrences,
      secondAttemptResult.finalOldString,
      secondAttemptResult.finalNewString,
    );

    if (secondError) {
      // The fix failed, log failure and return the original error
      const event = new EditCorrectionEvent('failure');
      logEditCorrectionEvent(this.config, event);

      return {
        currentContent: contentForLlmEditFixer,
        newContent: currentContent,
        occurrences: 0,
        isNewFile: false,
        error: initialError,
        originalLineEnding,
      };
    }

    const event = new EditCorrectionEvent(CoreToolCallStatus.Success);
    logEditCorrectionEvent(this.config, event);

    return {
      currentContent: contentForLlmEditFixer,
      newContent: secondAttemptResult.newContent,
      occurrences: secondAttemptResult.occurrences,
      isNewFile: false,
      error: undefined,
      originalLineEnding,
      strategy: secondAttemptResult.strategy,
      matchRanges: secondAttemptResult.matchRanges,
    };
  }

  /**
   * Calculates the potential outcome of an edit operation.
   * @param params Parameters for the edit operation
   * @returns An object describing the potential edit outcome
   * @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
   */
  private async calculateEdit(
    params: EditToolParams,
    abortSignal: AbortSignal,
  ): Promise<CalculatedEdit> {
    let currentContent: string | null = null;
    let fileExists = false;
    let originalLineEnding: '\r\n' | '\n' = '\n'; // Default for new files

    try {
      currentContent = await this.config
        .getFileSystemService()
        .readTextFile(this.resolvedPath);
      originalLineEnding = detectLineEnding(currentContent);
      currentContent = currentContent.replace(/\r\n/g, '\n');
      fileExists = true;
    } catch (err: unknown) {
      if (!isNodeError(err) || err.code !== 'ENOENT') {
        throw err;
      }
      fileExists = false;
    }

    const isNewFile = params.old_string === '' && !fileExists;

    if (isNewFile) {
      return {
        currentContent,
        newContent: params.new_string,
        occurrences: 1,
        isNewFile: true,
        error: undefined,
        originalLineEnding,
      };
    }

    // after this point, it's not a new file/edit
    if (!fileExists) {
      return {
        currentContent,
        newContent: '',
        occurrences: 0,
        isNewFile: false,
        error: {
          display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
          raw: `File not found: ${this.resolvedPath}`,
          type: ToolErrorType.FILE_NOT_FOUND,
        },
        originalLineEnding,
      };
    }

    if (currentContent === null) {
      return {
        currentContent,
        newContent: '',
        occurrences: 0,
        isNewFile: false,
        error: {
          display: `Failed to read content of file.`,
          raw: `Failed to read content of existing file: ${this.resolvedPath}`,
          type: ToolErrorType.READ_CONTENT_FAILURE,
        },
        originalLineEnding,
      };
    }

    if (params.old_string === '') {
      return {
        currentContent,
        newContent: currentContent,
        occurrences: 0,
        isNewFile: false,
        error: {
          display: `Failed to edit. Attempted to create a file that already exists.`,
          raw: `File already exists, cannot create: ${this.resolvedPath}`,
          type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE,
        },
        originalLineEnding,
      };
    }

    const replacementResult = await calculateReplacement(this.config, {
      params,
      currentContent,
      abortSignal,
    });

    const initialError = getErrorReplaceResult(
      params,
      replacementResult.occurrences,
      replacementResult.finalOldString,
      replacementResult.finalNewString,
    );

    if (!initialError) {
      return {
        currentContent,
        newContent: replacementResult.newContent,
        occurrences: replacementResult.occurrences,
        isNewFile: false,
        error: undefined,
        originalLineEnding,
        strategy: replacementResult.strategy,
        matchRanges: replacementResult.matchRanges,
      };
    }

    const fileExt = path.extname(this.resolvedPath).toLowerCase();
    const isJsonOrIpynb = ['.json', '.ipynb', '.jsonc', '.json5'].includes(
      fileExt,
    );

    if (this.config.getDisableLLMCorrection() || isJsonOrIpynb) {
      return {
        currentContent,
        newContent: currentContent,
        occurrences: replacementResult.occurrences,
        isNewFile: false,
        error: initialError,
        originalLineEnding,
      };
    }

    // If there was an error, try to self-correct.
    return this.attemptSelfCorrection(
      params,
      currentContent,
      initialError,
      abortSignal,
      originalLineEnding,
    );
  }

  /**
   * Handles the confirmation prompt for the Edit tool in the CLI.
   * It needs to calculate the diff to show the user.
   */
  protected override async getConfirmationDetails(
    abortSignal: AbortSignal,
  ): Promise<ToolCallConfirmationDetails | false> {
    let editData: CalculatedEdit;
    try {
      editData = await this.calculateEdit(this.params, abortSignal);
    } catch (error) {
      if (abortSignal.aborted) {
        throw error;
      }
      const errorMsg = error instanceof Error ? error.message : String(error);
      debugLogger.log(`Error preparing edit: ${errorMsg}`);
      return false;
    }

    if (editData.error) {
      debugLogger.log(`Error: ${editData.error.display}`);
      return false;
    }

    const fileName = path.basename(this.resolvedPath);
    const fileDiff = Diff.createPatch(
      fileName,
      editData.currentContent ?? '',
      editData.newContent,
      'Current',
      'Proposed',
      DEFAULT_DIFF_OPTIONS,
    );
    const ideClient = await IdeClient.getInstance();
    const ideConfirmation =
      this.config.getIdeMode() && ideClient.isDiffingEnabled()
        ? ideClient.openDiff(this.resolvedPath, editData.newContent)
        : undefined;

    const confirmationDetails: ToolEditConfirmationDetails = {
      type: 'edit',
      title: `Confirm Edit: ${shortenPath(makeRelative(this.resolvedPath, this.config.getTargetDir()))}`,
      fileName,
      filePath: this.resolvedPath,
      fileDiff,
      originalContent: editData.currentContent,
      newContent: editData.newContent,
      isBuildFile: isBuildFile(this.resolvedPath),
      onConfirm: async (_outcome: ToolConfirmationOutcome) => {
        // Mode transitions (e.g. AUTO_EDIT) and policy updates are now
        // handled centrally by the scheduler.

        if (ideConfirmation) {
          const result = await ideConfirmation;
          if (result.status === 'accepted' && result.content) {
            // TODO(chrstn): See https://github.com/google-gemini/gemini-cli/pull/5618#discussion_r2255413084
            // for info on a possible race condition where the file is modified on disk while being edited.
            this.params.old_string = editData.currentContent ?? '';
            this.params.new_string = result.content;
          }
        }
      },
      ideConfirmation,
    };
    return confirmationDetails;
  }

  getDescription(): string {
    const relativePath = makeRelative(
      this.resolvedPath,
      this.config.getTargetDir(),
    );
    if (this.params.old_string === '') {
      return `Create ${shortenPath(relativePath)}`;
    }

    const oldStringSnippet =
      this.params.old_string.split('\n')[0].substring(0, 30) +
      (this.params.old_string.length > 30 ? '...' : '');
    const newStringSnippet =
      this.params.new_string.split('\n')[0].substring(0, 30) +
      (this.params.new_string.length > 30 ? '...' : '');

    if (this.params.old_string === this.params.new_string) {
      return `No file changes to ${shortenPath(relativePath)}`;
    }
    return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
  }

  /**
   * Executes the edit operation with the given parameters.
   * @param params Parameters for the edit operation
   * @returns Result of the edit operation
   */
  async execute({ abortSignal: signal }: ExecuteOptions): Promise<ToolResult> {
    const validationError = this.config.validatePathAccess(this.resolvedPath);
    if (validationError) {
      return {
        llmContent: validationError,
        returnDisplay: 'Error: Path not in workspace.',
        error: {
          message: validationError,
          type: ToolErrorType.PATH_NOT_IN_WORKSPACE,
        },
      };
    }

    let editData: CalculatedEdit;
    try {
      editData = await this.calculateEdit(this.params, signal);
    } catch (error) {
      if (signal.aborted) {
        throw error;
      }
      const errorMsg = error instanceof Error ? error.message : String(error);
      return {
        llmContent: `Error preparing edit: ${errorMsg}`,
        returnDisplay: `Error preparing edit: ${errorMsg}`,
        error: {
          message: errorMsg,
          type: ToolErrorType.EDIT_PREPARATION_FAILURE,
        },
      };
    }

    if (editData.error) {
      return {
        llmContent: editData.error.raw,
        returnDisplay: `Error: ${editData.error.display}`,
        error: {
          message: editData.error.raw,
          type: editData.error.type,
        },
      };
    }

    try {
      await this.ensureParentDirectoriesExistAsync(this.resolvedPath);
      let finalContent = editData.newContent;

      // Restore original line endings if they were CRLF, or use OS default for new files
      const useCRLF =
        (!editData.isNewFile && editData.originalLineEnding === '\r\n') ||
        (editData.isNewFile && os.EOL === '\r\n');

      if (useCRLF) {
        finalContent = finalContent.replace(/\r?\n/g, '\r\n');
      }
      await this.config
        .getFileSystemService()
        .writeTextFile(this.resolvedPath, finalContent);

      if (isBuildFile(this.resolvedPath)) {
        recordModifiedBuildFile(this.resolvedPath, this.config);
      }

      let displayResult: ToolResultDisplay;
      if (editData.isNewFile) {
        displayResult = `Created ${shortenPath(makeRelative(this.resolvedPath, this.config.getTargetDir()))}`;
      } else {
        // Generate diff for display, even though core logic doesn't technically need it
        // The CLI wrapper will use this part of the ToolResult
        const fileName = path.basename(this.resolvedPath);
        const fileDiff = Diff.createPatch(
          fileName,
          editData.currentContent ?? '', // Should not be null here if not isNewFile
          editData.newContent,
          'Current',
          'Proposed',
          DEFAULT_DIFF_OPTIONS,
        );

        // Determine the full content as originally proposed by the AI to ensure accurate diff stats.
        let fullAiProposedContent = editData.newContent;
        if (
          this.params.modified_by_user &&
          this.params.ai_proposed_content !== undefined
        ) {
          try {
            const aiReplacement = await calculateReplacement(this.config, {
              params: {
                ...this.params,
                new_string: this.params.ai_proposed_content,
              },
              currentContent: editData.currentContent ?? '',
              abortSignal: signal,
            });
            fullAiProposedContent = aiReplacement.newContent;
          } catch (error) {
            const errorMsg =
              error instanceof Error ? error.message : String(error);
            debugLogger.log(`AI replacement fallback: ${errorMsg}`);
            // Fallback to newContent if speculative calculation fails
            fullAiProposedContent = editData.newContent;
          }
        }

        const diffStat = getDiffStat(
          fileName,
          editData.currentContent ?? '',
          fullAiProposedContent,
          editData.newContent,
        );
        displayResult = {
          fileDiff,
          fileName,
          filePath: this.resolvedPath,
          originalContent: editData.currentContent,
          newContent: editData.newContent,
          diffStat,
          isNewFile: editData.isNewFile,
          isBuildFile: isBuildFile(this.resolvedPath),
        };
      }

      const llmSuccessMessageParts = [
        editData.isNewFile
          ? `Created new file: ${this.resolvedPath} with provided content.`
          : `Successfully modified file: ${this.resolvedPath} (${editData.occurrences} replacements).`,
      ];

      // Return a diff of the file before and after the write so that the agent
      // can avoid the need to spend a turn doing a verification read.
      const snippet = getDiffContextSnippet(
        editData.currentContent ?? '',
        finalContent,
        5,
      );
      llmSuccessMessageParts.push(`Here is the updated code:
${snippet}`);
      const fuzzyFeedback = getFuzzyMatchFeedback(editData);
      if (fuzzyFeedback) {
        llmSuccessMessageParts.push(fuzzyFeedback);
      }
      if (this.params.modified_by_user) {
        llmSuccessMessageParts.push(
          `The confirmation step modified the \`new_string\` content to be: ${this.params.new_string}.`,
        );
      }

      // Discover JIT subdirectory context for the edited file path
      const jitContext = await discoverJitContext(
        this.config,
        this.resolvedPath,
      );
      let llmContent = llmSuccessMessageParts.join(' ');
      if (jitContext) {
        llmContent = appendJitContext(llmContent, jitContext);
      }

      const resultSummary =
        typeof displayResult === 'string'
          ? displayResult
          : fileDiffToSummary(displayResult, editData);

      return {
        llmContent,
        display: {
          name: this._toolDisplayName,
          description: this.getDescription(),
          resultSummary,
          result: {
            type: 'diff',
            path: this.resolvedPath,
            beforeText: editData.currentContent ?? '',
            afterText: editData.newContent,
          },
        },
        returnDisplay: displayResult,
      };
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);
      return {
        llmContent: `Error executing edit: ${errorMsg}`,
        returnDisplay: `Error writing file: ${errorMsg}`,
        error: {
          message: errorMsg,
          type: ToolErrorType.FILE_WRITE_FAILURE,
        },
      };
    }
  }

  /**
   * Creates parent directories if they don't exist
   */
  private async ensureParentDirectoriesExistAsync(
    filePath: string,
  ): Promise<void> {
    const dirName = path.dirname(filePath);
    try {
      await fsPromises.access(dirName);
    } catch {
      await fsPromises.mkdir(dirName, { recursive: true });
    }
  }
}

/**
 * Implementation of the Edit tool logic
 */
export class EditTool
  extends BaseDeclarativeTool<EditToolParams, ToolResult>
  implements ModifiableDeclarativeTool<EditToolParams>
{
  static readonly Name = EDIT_TOOL_NAME;

  constructor(
    private readonly config: Config,
    messageBus: MessageBus,
  ) {
    super(
      EditTool.Name,
      EDIT_DISPLAY_NAME,
      EDIT_DEFINITION.base.description!,
      Kind.Edit,
      EDIT_DEFINITION.base.parametersJsonSchema,
      messageBus,
      true, // isOutputMarkdown
      false, // canUpdateOutput
    );
  }

  /**
   * Validates the parameters for the Edit tool
   * @param params Parameters to validate
   * @returns Error message string or null if valid
   */
  protected override validateToolParamValues(
    params: EditToolParams,
  ): string | null {
    if (!params.file_path) {
      return "The 'file_path' parameter must be non-empty.";
    }

    let resolvedPath: string;
    if (this.config.isPlanMode()) {
      try {
        const cleanFilePath = params.file_path.replace(/\0/g, '');
        const planPath = resolveAndValidatePlanPath(
          cleanFilePath,
          this.config.storage.getPlansDir(),
          this.config.getProjectRoot(),
        );
        resolvedPath = resolveToRealPath(planPath);
      } catch (err) {
        return err instanceof Error ? err.message : String(err);
      }
    } else if (!path.isAbsolute(params.file_path)) {
      const result = correctPath(params.file_path, this.config);
      if (result.success) {
        try {
          resolvedPath = resolveToRealPath(result.correctedPath);
        } catch (err) {
          return err instanceof Error ? err.message : String(err);
        }
      } else {
        const sanitizedPath = resolveDefensiveToolPath(
          params.file_path,
          this.config.getTargetDir(),
        );
        try {
          resolvedPath = resolveToRealPath(
            path.resolve(this.config.getTargetDir(), sanitizedPath),
          );
        } catch (err) {
          return err instanceof Error ? err.message : String(err);
        }
      }
    } else {
      const cleanPath = params.file_path.replace(/\0/g, '');
      try {
        resolvedPath = resolveToRealPath(cleanPath);
      } catch (err) {
        return err instanceof Error ? err.message : String(err);
      }
    }
    const newPlaceholders = detectOmissionPlaceholders(params.new_string);
    if (newPlaceholders.length > 0) {
      const oldPlaceholders = new Set(
        detectOmissionPlaceholders(params.old_string),
      );

      for (const placeholder of newPlaceholders) {
        if (!oldPlaceholders.has(placeholder)) {
          return "`new_string` contains an omission placeholder (for example 'rest of methods ...'). Provide exact literal replacement text.";
        }
      }
    }

    return this.config.validatePathAccess(resolvedPath);
  }

  protected createInvocation(
    params: EditToolParams,
    messageBus: MessageBus,
  ): ToolInvocation<EditToolParams, ToolResult> {
    return new EditToolInvocation(
      this.config,
      params,
      messageBus,
      this.name,
      this.displayName,
    );
  }

  override getSchema(modelId?: string) {
    return resolveToolDeclaration(EDIT_DEFINITION, modelId);
  }

  getModifyContext(_: AbortSignal): ModifyContext<EditToolParams> {
    const resolvePath = (params: EditToolParams): string => {
      let pathBeforeRealResolve: string;

      try {
        if (this.config.isPlanMode()) {
          const cleanFilePath = params.file_path.replace(/\0/g, '');
          pathBeforeRealResolve = resolveAndValidatePlanPath(
            cleanFilePath,
            this.config.storage.getPlansDir(),
            this.config.getProjectRoot(),
          );
        } else if (!path.isAbsolute(params.file_path)) {
          const result = correctPath(params.file_path, this.config);
          if (result.success) {
            pathBeforeRealResolve = result.correctedPath;
          } else {
            const sanitizedPath = resolveDefensiveToolPath(
              params.file_path,
              this.config.getTargetDir(),
            );
            pathBeforeRealResolve = path.resolve(
              this.config.getTargetDir(),
              sanitizedPath,
            );
          }
        } else {
          pathBeforeRealResolve = params.file_path.replace(/\0/g, '');
        }
      } catch (err) {
        throw new Error(
          'Failed to resolve path: ' +
            (err instanceof Error ? err.message : String(err)),
        );
      }

      let resolved: string;
      try {
        resolved = resolveToRealPath(pathBeforeRealResolve);
      } catch (err) {
        throw new Error(
          'Failed to resolve path: ' +
            (err instanceof Error ? err.message : String(err)),
        );
      }

      const validationError = this.config.validatePathAccess(resolved);
      if (validationError) {
        throw new Error(validationError);
      }
      return resolved;
    };

    return {
      getFilePath: (params: EditToolParams) => params.file_path,
      getCurrentContent: async (params: EditToolParams): Promise<string> => {
        try {
          const resolvedPath = resolvePath(params);
          return await this.config
            .getFileSystemService()
            .readTextFile(resolvedPath);
        } catch (err) {
          if (!isNodeError(err) || err.code !== 'ENOENT') throw err;
          return '';
        }
      },
      getProposedContent: async (params: EditToolParams): Promise<string> => {
        try {
          const resolvedPath = resolvePath(params);
          const currentContent = await this.config
            .getFileSystemService()
            .readTextFile(resolvedPath);
          return applyReplacement(
            currentContent,
            params.old_string,
            params.new_string,
            params.old_string === '' && currentContent === '',
          );
        } catch (err) {
          if (!isNodeError(err) || err.code !== 'ENOENT') throw err;
          return '';
        }
      },
      createUpdatedParams: (
        oldContent: string,
        modifiedProposedContent: string,
        originalParams: EditToolParams,
      ): EditToolParams => {
        const content = originalParams.new_string;
        return {
          ...originalParams,
          ai_proposed_content: content,
          old_string: oldContent,
          new_string: modifiedProposedContent,
          modified_by_user: true,
        };
      },
    };
  }
}

function stripWhitespace(str: string): string {
  return str.replace(/\s/g, '');
}

/**
 * Applies the target indentation to the lines, while preserving relative indentation.
 * It identifies the common indentation of the provided lines and replaces it with the target indentation.
 */
function applyIndentation(
  lines: string[],
  targetIndentation: string,
): string[] {
  if (lines.length === 0) return [];

  // Use the first line as the reference for indentation, even if it's empty/whitespace.
  // This is because flexible/fuzzy matching identifies the indentation of the START of the match.
  const referenceLine = lines[0];
  const refIndentMatch = referenceLine.match(/^([ \t]*)/);
  const refIndent = refIndentMatch ? refIndentMatch[1] : '';

  return lines.map((line) => {
    if (line.trim() === '') {
      return '';
    }
    if (line.startsWith(refIndent)) {
      return targetIndentation + line.slice(refIndent.length);
    }
    return targetIndentation + line.trimStart();
  });
}

function getFuzzyMatchFeedback(editData: CalculatedEdit): string | null {
  if (
    editData.strategy === 'fuzzy' &&
    editData.matchRanges &&
    editData.matchRanges.length > 0
  ) {
    const ranges = editData.matchRanges
      .map((r) => (r.start === r.end ? `${r.start}` : `${r.start}-${r.end}`))
      .join(', ');
    return `Applied fuzzy match at line${editData.matchRanges.length > 1 ? 's' : ''} ${ranges}.`;
  }
  return null;
}

async function calculateFuzzyReplacement(
  config: Config,
  context: ReplacementContext,
): Promise<ReplacementResult | null> {
  const { currentContent, params } = context;
  const { old_string, new_string } = params;

  // Pre-check: Don't fuzzy match very short strings to avoid false positives
  if (old_string.length < 10) {
    return null;
  }

  const normalizedCode = currentContent.replace(/\r\n/g, '\n');
  const normalizedSearch = old_string.replace(/\r\n/g, '\n');
  const normalizedReplace = new_string.replace(/\r\n/g, '\n');

  const sourceLines = normalizedCode.match(/.*(?:\n|$)/g)?.slice(0, -1) ?? [];
  const searchLines = normalizedSearch
    .match(/.*(?:\n|$)/g)
    ?.slice(0, -1)
    .map((l) => l.trimEnd()); // Trim end of search lines to be more robust

  // Limit the scope of the fuzzy match to reduce impact on responsivesness.
  // Each comparison takes roughly O(L^2) time.
  // We perform sourceLines.length comparisons (sliding window).
  // Total complexity proxy: sourceLines.length * old_string.length^2
  // Limit to 4e8 for < 1 second.
  if (sourceLines.length * Math.pow(old_string.length, 2) > 400_000_000) {
    return null;
  }

  if (!searchLines || searchLines.length === 0) {
    return null;
  }

  const N = searchLines.length;
  const candidates: Array<{ index: number; score: number }> = [];
  const searchBlock = searchLines.join('\n');

  // Sliding window
  for (let i = 0; i <= sourceLines.length - N; i++) {
    const windowLines = sourceLines.slice(i, i + N);
    const windowText = windowLines.map((l) => l.trimEnd()).join('\n'); // Normalized join for comparison

    // Length Heuristic Optimization
    const lengthDiff = Math.abs(windowText.length - searchBlock.length);
    if (
      lengthDiff / searchBlock.length >
      FUZZY_MATCH_THRESHOLD / WHITESPACE_PENALTY_FACTOR
    ) {
      continue;
    }

    // Tiered Scoring
    const d_raw = levenshtein.get(windowText, searchBlock);
    const d_norm = levenshtein.get(
      stripWhitespace(windowText),
      stripWhitespace(searchBlock),
    );

    const weightedDist = d_norm + (d_raw - d_norm) * WHITESPACE_PENALTY_FACTOR;
    const score = weightedDist / searchBlock.length;

    if (score <= FUZZY_MATCH_THRESHOLD) {
      candidates.push({ index: i, score });
    }
  }

  if (candidates.length === 0) {
    return null;
  }

  // Select best non-overlapping matches
  // Sort by score ascending. If scores equal, prefer earlier index (stable sort).
  candidates.sort((a, b) => a.score - b.score || a.index - b.index);

  const selectedMatches: Array<{ index: number; score: number }> = [];
  for (const candidate of candidates) {
    // Check for overlap with already selected matches
    // Two windows overlap if their start indices are within N lines of each other
    // (Assuming window size N. Actually overlap is |i - j| < N)
    const overlaps = selectedMatches.some(
      (m) => Math.abs(m.index - candidate.index) < N,
    );
    if (!overlaps) {
      selectedMatches.push(candidate);
    }
  }

  // If we found matches, apply them
  if (selectedMatches.length > 0) {
    const event = new EditStrategyEvent('fuzzy');
    logEditStrategy(config, event);

    // Calculate match ranges before sorting for replacement
    // Indices in selectedMatches are 0-based line indices
    const matchRanges = selectedMatches
      .map((m) => ({ start: m.index + 1, end: m.index + N }))
      .sort((a, b) => a.start - b.start);

    // Sort matches by index descending to apply replacements from bottom to top
    // so that indices remain valid
    selectedMatches.sort((a, b) => b.index - a.index);

    const newLines = normalizedReplace.split('\n');

    for (const match of selectedMatches) {
      // If we want to preserve the indentation of the first line of the match:
      const firstLineMatch = sourceLines[match.index];
      const indentationMatch = firstLineMatch.match(/^([ \t]*)/);
      const indentation = indentationMatch ? indentationMatch[1] : '';

      const indentedReplaceLines = applyIndentation(newLines, indentation);

      let replacementText = indentedReplaceLines.join('\n');
      // If the last line of the match had a newline, preserve it in the replacement
      // to avoid merging with the next line or losing a blank line separator.
      if (sourceLines[match.index + N - 1].endsWith('\n')) {
        replacementText += '\n';
      }

      sourceLines.splice(match.index, N, replacementText);
    }

    let modifiedCode = sourceLines.join('');
    modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);

    return {
      newContent: modifiedCode,
      occurrences: selectedMatches.length,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace,
      strategy: 'fuzzy',
      matchRanges,
    };
  }

  return null;
}