patchloom 0.20.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
//! Multi-strategy fallback chain for edit resolution.
//!
//! When a primary edit operation fails (e.g., target text not found), this
//! module provides progressively looser matching strategies before giving up.
//!
//! The fallback chain:
//! 1. **Exact match** (primary, handled by the caller)
//! 2. **Anchor-based matching** (structural landmarks around the edit target)
//! 3. **Similarity scoring** (Jaro-Winkler on surrounding lines)
//! 4. **Structured error** (diagnosis with suggestions)
//!
//! # Examples
//!
//! Suggest similar targets when a search misses:
//!
//! ```rust
//! use patchloom::fallback::{EditError, EditErrorKind, find_similar_targets};
//!
//! let content = "fn process_request() {}\nfn process_response() {}\n";
//! let similar = find_similar_targets(content, "process_requst", 3);
//! assert!(similar.iter().any(|s| s.contains("process_request")));
//! ```
//!
//! Run the full fallback chain (exact, anchor, similarity, structured error):
//!
//! ```rust
//! use patchloom::fallback::{resolve_with_fallback, MatchStrategy};
//!
//! let content = "fn setup() {}\nfn proccess_data(x: i32) {}\nfn cleanup() {}\n";
//! let result = resolve_with_fallback(
//!     content,
//!     "fn process_data(x: i32) {}",
//!     Some("fn setup() {}"),
//!     Some("fn cleanup() {}"),
//!).expect("anchor match should succeed");
//! assert_eq!(result.strategy, MatchStrategy::Anchor);
//! assert!(result.matched_text.contains("proccess_data"));
//! ```
//!
//! Validate an edit before applying it:
//!
//! ```rust
//! use patchloom::fallback::validate_edit;
//!
//! let json = r#"{"key": "value"}"#;
//! let result = validate_edit(json, "value", "new_value", Some("config.json"));
//! assert!(result.valid);
//! ```
//!
//! Validate with `--nth` semantics (only replace the Nth occurrence):
//!
//! ```rust
//! use patchloom::fallback::validate_edit_nth;
//!
//! let json = r#"{"a": "val", "b": "val"}"#;
//! let result = validate_edit_nth(json, "val", "new", Some("data.json"), Some(1));
//! assert!(result.valid);
//! ```
//!
//! size-waiver: accepted single-domain bulk (policy #1408). Multi-strategy edit recovery chain is one conceptual unit; do not split for LOC alone.

use serde::{Deserialize, Serialize};

/// Structured error type for edit operations with actionable diagnosis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EditError {
    /// What kind of error occurred.
    pub kind: EditErrorKind,
    /// Human-readable error message.
    pub message: String,
    /// A suggestion for how to fix the issue (if available).
    pub suggestion: Option<String>,
    /// Similar targets found in the file (for "did you mean?" hints).
    pub similar_targets: Vec<String>,
}

impl std::fmt::Display for EditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.kind, self.message)?;
        if let Some(ref suggestion) = self.suggestion {
            write!(f, " (suggestion: {suggestion})")?;
        }
        if !self.similar_targets.is_empty() {
            write!(f, " [similar: {}]", self.similar_targets.join(", "))?;
        }
        Ok(())
    }
}

impl std::error::Error for EditError {}

/// Classification of edit errors.
///
/// Marked `non_exhaustive` so new honesty kinds (for example [`Self::TypeError`])
/// can land in minor releases without breaking external exhaustive matches.
///
/// **Append-only variants:** new kinds must be added **after** the last existing
/// variant. Inserting in the middle shifts discriminants of later variants and
/// fails `cargo-semver-checks` (`enum_no_repr_variant_discriminant_changed`),
/// which blocks patch releases (see #1950 order fix for #1951).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum EditErrorKind {
    /// The edit target matched multiple locations in the file.
    AmbiguousTarget,
    /// The edit target was not found in the file.
    NoMatch,
    /// The edit would produce invalid syntax.
    SyntaxInvalid,
    /// Another edit already modified this region (for batch operations).
    ConflictingEdit,
    /// The file could not be parsed.
    ParseError,
    /// Path rejected by workspace PathGuard (#1492).
    GuardRejected,
    /// Invalid arguments or options for the edit.
    InvalidInput,
    /// Wrong value type for a doc selector (multi-document YAML bare key,
    /// navigate into array as object, etc.). CLI JSON uses `error_kind:
    /// "type_error"`. Distinct from [`Self::InvalidInput`] so hosts can
    /// recover with `0.key` / `[0].key` without scraping English (#1883).
    TypeError,
    /// I/O or other operational failure.
    OperationFailed,
    /// Post-write format/lint hook failed (`format_failed` / #1663).
    /// Distinct from generic [`Self::OperationFailed`] so hosts can branch
    /// without scraping English.
    FormatFailed,
    /// Create/rename destination already exists without force.
    /// CLI JSON uses `error_kind: "already_exists"`. Distinct from
    /// [`Self::InvalidInput`] (empty path, directory target) and content SoftSkip
    /// ([`Self::Binary`] / [`Self::InvalidEncoding`]) so hosts can hint
    /// `overwrite`/`force` without scraping English (#1947 / #1963).
    /// Appended after [`Self::FormatFailed`] so 0.18.0 discriminants stay stable.
    AlreadyExists,
    /// Path not found (`std::io::ErrorKind::NotFound`). CLI JSON uses
    /// `error_kind: "not_found"`. Distinct from generic [`Self::OperationFailed`]
    /// so hosts can treat missing paths separately from other I/O failures.
    NotFound,
    /// Patch/apply produced merge conflict markers. CLI JSON uses
    /// `error_kind: "conflicts"`. Distinct from [`Self::ConflictingEdit`]
    /// (batch region overlap) and generic [`Self::OperationFailed`].
    Conflicts,
    /// Check/preview reported pending changes, or soft assert-count mismatch
    /// (`error_kind: "changes_detected"`, exit 2). Distinct from
    /// [`Self::OperationFailed`] so hosts can mirror CLI exit-2 semantics
    /// without scraping English.
    ChangesDetected,
    /// Target contains NUL in the binary probe window (not agent-editable text).
    /// CLI JSON uses `error_kind: "binary"`. Distinct from [`Self::InvalidInput`]
    /// (empty path, directory target, empty pattern) so hosts can recover
    /// overwrite/delete/rename without treating all invalid input as binary (#1963).
    /// Appended after [`Self::ChangesDetected`] so 0.18/0.19 discriminants stay stable.
    Binary,
    /// Target is not valid UTF-8 (and not binary by NUL probe). CLI JSON uses
    /// `error_kind: "invalid_encoding"`. Distinct from [`Self::Binary`] and
    /// [`Self::InvalidInput`] (#1963).
    InvalidEncoding,
}

impl std::fmt::Display for EditErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EditErrorKind::AmbiguousTarget => write!(f, "ambiguous_target"),
            EditErrorKind::NoMatch => write!(f, "no_match"),
            EditErrorKind::SyntaxInvalid => write!(f, "syntax_invalid"),
            EditErrorKind::ConflictingEdit => write!(f, "conflicting_edit"),
            EditErrorKind::ParseError => write!(f, "parse_error"),
            EditErrorKind::GuardRejected => write!(f, "guard_rejected"),
            EditErrorKind::InvalidInput => write!(f, "invalid_input"),
            EditErrorKind::TypeError => write!(f, "type_error"),
            EditErrorKind::OperationFailed => write!(f, "operation_failed"),
            EditErrorKind::FormatFailed => write!(f, "format_failed"),
            EditErrorKind::AlreadyExists => write!(f, "already_exists"),
            EditErrorKind::NotFound => write!(f, "not_found"),
            EditErrorKind::Conflicts => write!(f, "conflicts"),
            EditErrorKind::ChangesDetected => write!(f, "changes_detected"),
            EditErrorKind::Binary => write!(f, "binary"),
            EditErrorKind::InvalidEncoding => write!(f, "invalid_encoding"),
        }
    }
}

impl EditError {
    /// Build a structured edit error.
    pub fn new(kind: EditErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            suggestion: None,
            similar_targets: Vec::new(),
        }
    }

    /// PathGuard rejection as an `anyhow` error (`edit_error_kind` → [`EditErrorKind::GuardRejected`]).
    ///
    /// Prefer this over [`crate::exit::InvalidInputError`] for guard failures so
    /// library hosts and CLI JSON can branch on `guard_rejected` without scraping
    /// English (#1935 / engine PathGuard paths).
    pub fn guard_rejected(detail: impl std::fmt::Display) -> anyhow::Error {
        Self::new(
            EditErrorKind::GuardRejected,
            format!("path rejected by workspace guard: {detail}"),
        )
        .into()
    }

    /// Attach similar-target suggestions (did-you-mean).
    pub fn with_similar(mut self, similar: Vec<String>) -> Self {
        self.similar_targets = similar;
        self
    }

    /// Attach a single suggestion string.
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestion = Some(suggestion.into());
        self
    }
}

/// Downcast an `anyhow` error chain to [`EditErrorKind`] when present.
///
/// Peels both [`EditError`] and the CLI/tx typed errors in [`crate::exit`]
/// (`InvalidInputError`, `NoMatchError`, …) so library hosts can branch on
/// kind without caring which construction path produced the failure.
///
/// Hosts that do **not** depend on `anyhow` should use [`classify_error`]
/// on a `dyn Error` instead (#1659).
pub fn edit_error_kind(err: &anyhow::Error) -> Option<EditErrorKind> {
    for cause in err.chain() {
        if let Some(kind) = classify_error(cause) {
            return Some(kind);
        }
    }
    None
}

/// Downcast an `anyhow` error chain to [`EditError`] when present.
pub fn edit_error_ref(err: &anyhow::Error) -> Option<&EditError> {
    for cause in err.chain() {
        if let Some(e) = classify_error_ref(cause) {
            return Some(e);
        }
    }
    None
}

/// Classify a bare `dyn Error` (no `anyhow` required) into [`EditErrorKind`].
///
/// Walks `source()` and peels [`EditError`] plus the CLI/tx typed errors
/// (`NoMatchError`, `InvalidInputError`, `AmbiguousError`, …). Use this from
/// non-anyhow agent hosts that store `Box<dyn Error>` or `Arc<dyn Error>`.
///
/// ```rust
/// use patchloom::fallback::{classify_error, EditError, EditErrorKind};
///
/// let err: Box<dyn std::error::Error + Send + Sync> =
///     Box::new(EditError::new(EditErrorKind::NoMatch, "no matches for \"x\""));
/// assert_eq!(classify_error(err.as_ref()), Some(EditErrorKind::NoMatch));
/// ```
///
/// See #1659.
pub fn classify_error(err: &(dyn std::error::Error + 'static)) -> Option<EditErrorKind> {
    let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
    while let Some(e) = current {
        if let Some(edit) = e.downcast_ref::<EditError>() {
            return Some(edit.kind);
        }
        if e.downcast_ref::<crate::exit::NoMatchError>().is_some() {
            return Some(EditErrorKind::NoMatch);
        }
        if e.downcast_ref::<crate::exit::AmbiguousError>().is_some() {
            return Some(EditErrorKind::AmbiguousTarget);
        }
        if e.downcast_ref::<crate::exit::InvalidInputError>().is_some() {
            return Some(EditErrorKind::InvalidInput);
        }
        if e.downcast_ref::<crate::exit::AlreadyExistsError>()
            .is_some()
        {
            return Some(EditErrorKind::AlreadyExists);
        }
        if e.downcast_ref::<crate::exit::TypeErrorError>().is_some() {
            return Some(EditErrorKind::TypeError);
        }
        if e.downcast_ref::<crate::exit::ParseErrorError>().is_some() {
            return Some(EditErrorKind::ParseError);
        }
        if e.downcast_ref::<crate::exit::FormatFailedError>().is_some() {
            return Some(EditErrorKind::FormatFailed);
        }
        if e.downcast_ref::<crate::exit::ConflictsError>().is_some() {
            return Some(EditErrorKind::Conflicts);
        }
        if e.downcast_ref::<crate::exit::ChangesDetectedError>()
            .is_some()
        {
            return Some(EditErrorKind::ChangesDetected);
        }
        if e.downcast_ref::<crate::exit::BinaryError>().is_some() {
            return Some(EditErrorKind::Binary);
        }
        if e.downcast_ref::<crate::exit::InvalidEncodingError>()
            .is_some()
        {
            return Some(EditErrorKind::InvalidEncoding);
        }
        if e.downcast_ref::<std::io::Error>()
            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
        {
            return Some(EditErrorKind::NotFound);
        }
        current = e.source();
    }
    None
}

/// Same stable kind string CLI JSON uses (`already_exists`, `guard_rejected`, …).
///
/// Library hosts that mirror agent JSON envelopes should use this instead of
/// re-implementing [`crate::exit::classify_typed_error`] or scraping Display
/// (#1948). Returns `None` when the chain has no recognized typed kind.
///
/// Prefer this over matching only [`edit_error_kind`] when you need CLI-stable
/// strings (for example `no_matches` vs Display `no_match`).
#[must_use]
pub fn error_kind_str(err: &anyhow::Error) -> Option<&'static str> {
    crate::exit::classify_typed_error(err).map(|(kind, _)| kind)
}

/// Whether the error peels as dest-exists create/rename conflict.
///
/// True for both [`crate::exit::AlreadyExistsError`] and
/// [`EditError`] with [`EditErrorKind::AlreadyExists`], so the bool matches
/// what hosts get from [`edit_error_kind`] (#1947).
#[must_use]
pub fn is_already_exists(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::AlreadyExists)
}

/// Whether the error peels as missing path I/O ([`EditErrorKind::NotFound`]).
///
/// Matches IO `NotFound` (including through `anyhow::Context`) and
/// [`EditError`] with [`EditErrorKind::NotFound`]. Prefer this over scraping
/// Display for host recovery when a path is simply absent.
#[must_use]
pub fn is_not_found(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::NotFound)
}

/// Whether the error peels as patch/apply merge conflict markers
/// ([`EditErrorKind::Conflicts`]). Distinct from batch
/// [`EditErrorKind::ConflictingEdit`].
#[must_use]
pub fn is_conflicts(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::Conflicts)
}

/// Whether the error peels as check/preview pending changes or soft
/// assert-count mismatch ([`EditErrorKind::ChangesDetected`], CLI exit 2).
#[must_use]
pub fn is_changes_detected(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::ChangesDetected)
}

/// Whether the error peels as multi-doc / wrong-root type mismatch
/// ([`EditErrorKind::TypeError`]). Distinct from [`EditErrorKind::InvalidInput`].
#[must_use]
pub fn is_type_error(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::TypeError)
}

/// Whether the error peels as post-write format/lint failure
/// ([`EditErrorKind::FormatFailed`]). Files may already be written.
#[must_use]
pub fn is_format_failed(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::FormatFailed)
}

/// Whether the error peels as PathGuard / `--contain` rejection
/// ([`EditErrorKind::GuardRejected`]).
#[must_use]
pub fn is_guard_rejected(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::GuardRejected)
}

/// Whether the error peels as invalid arguments / sole binary / bad options
/// ([`EditErrorKind::InvalidInput`]).
#[must_use]
pub fn is_invalid_input(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::InvalidInput)
}

/// Whether the error peels as soft no-match ([`EditErrorKind::NoMatch`]).
/// CLI JSON kind is `no_matches` via [`error_kind_str`].
#[must_use]
pub fn is_no_match(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::NoMatch)
}

/// Whether the error peels as multi-match / unique-mode ambiguity
/// ([`EditErrorKind::AmbiguousTarget`]). Distinct from soft [`is_no_match`].
///
/// Hosts with `unique: true` / `require_change` multi-hit recovery should prefer
/// this over scraping Display.
#[must_use]
pub fn is_ambiguous(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::AmbiguousTarget)
}

/// Whether the error peels as binary/NUL content ([`EditErrorKind::Binary`]).
///
/// Distinct from [`is_invalid_input`] (argument mistakes) and
/// [`is_invalid_encoding`] (non-UTF-8 text without NUL). Hosts that recover
/// overwrite of non-text priors should branch on this (or [`is_invalid_encoding`])
/// rather than all of `InvalidInput` (#1963).
#[must_use]
pub fn is_binary(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::Binary)
}

/// Whether the error peels as invalid UTF-8 content
/// ([`EditErrorKind::InvalidEncoding`]). Distinct from [`is_binary`] and
/// [`is_invalid_input`] (#1963).
#[must_use]
pub fn is_invalid_encoding(err: &anyhow::Error) -> bool {
    edit_error_kind(err) == Some(EditErrorKind::InvalidEncoding)
}

/// One-shot peel of a library/CLI error for host tool envelopes (#1964).
///
/// Combines [`error_kind_str`], [`edit_error_ref`], and agent-facing message
/// so embedders do not reimplement `edit_error_kind` + `error_kind_str` +
/// Display formatting. Returns `None` when the chain has no recognized kind.
#[derive(Debug, Clone)]
pub struct PeeledError {
    /// CLI-stable kind string (`already_exists`, `binary`, …).
    pub kind_str: &'static str,
    /// Agent-facing message (same as CLI JSON `error` when possible).
    pub message: String,
    /// Optional suggestion from [`EditError`].
    pub suggestion: Option<String>,
    /// Similar targets from [`EditError`] (did-you-mean).
    pub similar_targets: Vec<String>,
}

/// Peel kind string + message + optional suggestion from an error chain (#1964).
#[must_use]
pub fn peel_error(err: &anyhow::Error) -> Option<PeeledError> {
    let kind_str = error_kind_str(err)?;
    let (suggestion, similar_targets) = match edit_error_ref(err) {
        Some(e) => (e.suggestion.clone(), e.similar_targets.clone()),
        None => (None, Vec::new()),
    };
    Some(PeeledError {
        kind_str,
        message: crate::exit::agent_error_message(err),
        suggestion,
        similar_targets,
    })
}

/// Downcast a bare `dyn Error` chain to [`EditError`] when present (#1659).
///
/// Prefer this when you need `similar_targets` / `suggestion` without
/// depending on `anyhow`.
pub fn classify_error_ref<'a>(err: &'a (dyn std::error::Error + 'static)) -> Option<&'a EditError> {
    let mut current: Option<&'a (dyn std::error::Error + 'static)> = Some(err);
    while let Some(e) = current {
        if let Some(edit) = e.downcast_ref::<EditError>() {
            return Some(edit);
        }
        current = e.source();
    }
    None
}

/// Result of `validate_edit()`: whether the edit would produce valid output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Whether the edit produces valid output.
    pub valid: bool,
    /// Syntax errors found (if invalid).
    pub errors: Vec<String>,
    /// Suspicious but technically valid issues.
    pub warnings: Vec<String>,
}

/// Validate whether a replacement would produce valid output, without applying.
///
/// Performs the replacement in memory and checks basic structural validity
/// of the resulting content (JSON, YAML, TOML validation for structured files).
///
/// When `nth` is `Some(n)`, only the Nth (1-based) occurrence is replaced,
/// matching the behavior of the replace command's `--nth` flag. When `None`,
/// all occurrences are replaced.
pub fn validate_edit(
    content: &str,
    from: &str,
    to: &str,
    file_path: Option<&str>,
) -> ValidationResult {
    validate_edit_nth(content, from, to, file_path, None)
}

/// Like [`validate_edit`] but with an explicit `nth` occurrence parameter.
pub fn validate_edit_nth(
    content: &str,
    from: &str,
    to: &str,
    file_path: Option<&str>,
    nth: Option<usize>,
) -> ValidationResult {
    if from.is_empty() {
        return ValidationResult {
            valid: false,
            errors: vec!["empty search pattern".into()],
            warnings: vec![],
        };
    }

    if !content.contains(from) {
        return ValidationResult {
            valid: false,
            errors: vec![format!(
                "pattern '{}' not found in content",
                truncate_str(from, 60)
            )],
            warnings: vec![],
        };
    }

    let new_content = match nth {
        Some(0) => {
            return ValidationResult {
                valid: false,
                errors: vec!["nth must be >= 1 (1-based indexing)".into()],
                warnings: vec![],
            };
        }
        Some(n) => {
            // Replace only the Nth (1-based) occurrence.
            let mut count = 0usize;
            let mut result = String::with_capacity(content.len());
            let mut remaining = content;
            while let Some(pos) = remaining.find(from) {
                count += 1;
                if count == n {
                    result.push_str(&remaining[..pos]);
                    result.push_str(to);
                    result.push_str(&remaining[pos + from.len()..]);
                    break;
                }
                result.push_str(&remaining[..pos + from.len()]);
                remaining = &remaining[pos + from.len()..];
            }
            if count < n {
                return ValidationResult {
                    valid: false,
                    errors: vec![format!(
                        "occurrence {n} not found (only {count} occurrence{} exist{})",
                        if count == 1 { "" } else { "s" },
                        if count == 1 { "s" } else { "" },
                    )],
                    warnings: vec![],
                };
            }
            result
        }
        None => content.replace(from, to),
    };
    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    // If we can detect the file format, validate the result.
    if let Some(path) = file_path
        && let Ok(fmt) = crate::ops::doc::detect_format(path)
    {
        let parse_err = match fmt {
            crate::ops::doc::FileFormat::Json => {
                serde_json::from_str::<serde_json::Value>(&new_content)
                    .err()
                    .map(|e| format!("result would be invalid JSON: {e}"))
            }
            crate::ops::doc::FileFormat::Yaml => {
                serde_yaml_ng::from_str::<serde_json::Value>(&new_content)
                    .err()
                    .map(|e| format!("result would be invalid YAML: {e}"))
            }
            crate::ops::doc::FileFormat::Toml => {
                toml_edit::de::from_str::<serde_json::Value>(&new_content)
                    .err()
                    .map(|e| format!("result would be invalid TOML: {e}"))
            }
        };
        if let Some(msg) = parse_err {
            errors.push(msg);
        }
    }

    // Warn if the replacement creates unbalanced brackets/braces.
    let open_parens =
        new_content.matches('(').count() as i64 - new_content.matches(')').count() as i64;
    let open_braces =
        new_content.matches('{').count() as i64 - new_content.matches('}').count() as i64;
    let open_brackets =
        new_content.matches('[').count() as i64 - new_content.matches(']').count() as i64;

    if open_parens != 0 {
        warnings.push(format!("unbalanced parentheses (delta: {open_parens})"));
    }
    if open_braces != 0 {
        warnings.push(format!("unbalanced braces (delta: {open_braces})"));
    }
    if open_brackets != 0 {
        warnings.push(format!("unbalanced brackets (delta: {open_brackets})"));
    }

    ValidationResult {
        valid: errors.is_empty(),
        errors,
        warnings,
    }
}

/// Minimum Jaro-Winkler score for a did-you-mean candidate.
///
/// Kept in line with anchor matching (0.85). The previous 0.7 floor
/// admitted noise like `nold` for long unrelated patterns when scanning
/// large trees (fixrealloop stress, 2026-07-23).
const SIMILAR_TARGET_MIN_SCORE: f64 = 0.85;

/// Whether `candidate` is a plausible typo of `target` by length.
///
/// Jaro-Winkler can score short tokens above the floor against long
/// strings (shared characters / prefixes). Reject extreme length skew
/// so agents do not chase nonsense suggestions.
fn similar_target_length_plausible(candidate: &str, target: &str) -> bool {
    let (ca, ta) = (candidate.len(), target.len());
    if ca == 0 || ta == 0 {
        return false;
    }
    let (shorter, longer) = if ca < ta { (ca, ta) } else { (ta, ca) };
    // Allow ~2x length difference, or a small absolute gap for short ids.
    shorter.saturating_mul(2) >= longer || longer - shorter <= 3
}

/// Find similar text targets in file content using Jaro-Winkler similarity.
///
/// Extracts identifiers and substrings from the content and returns the top
/// `max_results` matches sorted by similarity score (descending).
pub fn find_similar_targets(content: &str, target: &str, max_results: usize) -> Vec<String> {
    if target.is_empty() || content.is_empty() {
        return vec![];
    }

    let mut candidates: Vec<(String, f64)> = Vec::new();
    let mut seen = std::collections::HashSet::new();

    // Extract word-like tokens from the content.
    for line in content.lines() {
        for word in extract_identifiers(line) {
            if !seen.insert(word.clone()) {
                continue;
            }
            if word == target || !similar_target_length_plausible(&word, target) {
                continue;
            }
            let score = strsim::jaro_winkler(&word, target);
            if score > SIMILAR_TARGET_MIN_SCORE {
                candidates.push((word, score));
            }
        }
    }

    // Also try matching against whole lines for multi-word patterns.
    if target.contains(' ') || target.len() > 20 {
        for line in content.lines() {
            let trimmed = line.trim().to_string();
            if trimmed.is_empty() || seen.contains(&trimmed) {
                continue;
            }
            seen.insert(trimmed.clone());
            if trimmed == target || !similar_target_length_plausible(&trimmed, target) {
                continue;
            }
            let score = strsim::jaro_winkler(&trimmed, target);
            if score > SIMILAR_TARGET_MIN_SCORE {
                candidates.push((trimmed, score));
            }
        }
    }

    candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
    candidates.truncate(max_results);
    candidates.into_iter().map(|(s, _)| s).collect()
}

/// Try anchor-based matching: find the target text using surrounding context lines.
///
/// If `target` is not found exactly, looks for lines that share anchor text
/// (the lines immediately before and after the target in the original context)
/// and returns the matching region.
pub fn anchor_match(
    content: &str,
    target: &str,
    before_context: Option<&str>,
    after_context: Option<&str>,
) -> Option<AnchorMatchResult> {
    if target.is_empty() {
        return None;
    }

    // If exact match exists, return it directly.
    if let Some(pos) = content.find(target) {
        return Some(AnchorMatchResult {
            matched_text: target.to_string(),
            start_offset: pos,
            strategy: MatchStrategy::Exact,
            score: None,
        });
    }

    // Try anchor-based matching using before/after context.
    let lines: Vec<&str> = content.lines().collect();
    let target_lines: Vec<&str> = target.lines().collect();

    // Compute byte offset of each line start for accurate slicing,
    // avoiding CRLF vs LF mismatch (the old code used a global
    // heuristic that broke on mixed or CRLF line endings).
    let mut line_byte_starts: Vec<usize> = vec![0];
    for (i, b) in content.bytes().enumerate() {
        if b == b'\n' {
            line_byte_starts.push(i + 1);
        }
    }

    if target_lines.is_empty() {
        return None;
    }

    let first_target = target_lines[0].trim();
    let last_target = target_lines.last().map(|l| l.trim()).unwrap_or("");

    // Anchor matching requires at least one piece of structural context
    // (before_context or after_context). Without context, it would
    // degenerate into the same Jaro-Winkler line scan that the
    // similarity path already does, making the fallback chain redundant.
    if before_context.is_none() && after_context.is_none() {
        return None;
    }

    // Find candidate positions by matching the first line with anchors.
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();

        // Check if this line is similar to the first target line.
        if strsim::jaro_winkler(trimmed, first_target) < 0.85 {
            continue;
        }

        // For multi-line targets, also verify the last line of the
        // candidate region is similar to the last target line.
        if target_lines.len() > 1 {
            let end_idx = i + target_lines.len();
            if end_idx > lines.len() {
                continue;
            }
            let candidate_last = lines[end_idx - 1].trim();
            if strsim::jaro_winkler(candidate_last, last_target) < 0.85 {
                continue;
            }
        }

        // If we have before_context, verify the preceding line matches.
        // For multi-line context, compare only the last line (the one
        // immediately before the target region).
        if let Some(before) = before_context {
            if i == 0 {
                continue;
            }
            let prev = lines[i - 1].trim();
            let before_line = before.lines().last().unwrap_or(before).trim();
            if strsim::jaro_winkler(prev, before_line) < 0.8 {
                continue;
            }
        }

        // If we have after_context, check the line after the candidate region.
        // For multi-line context, compare only the first line (the one
        // immediately after the target region).
        if let Some(after) = after_context {
            let end_idx = i + target_lines.len();
            if end_idx >= lines.len() {
                continue;
            }
            let next = lines[end_idx].trim();
            let after_line = after.lines().next().unwrap_or(after).trim();
            if strsim::jaro_winkler(next, after_line) < 0.8 {
                continue;
            }
        }

        // Found a match. Extract the matched region directly from the
        // original content so line endings are preserved exactly.
        let end_idx = (i + target_lines.len()).min(lines.len());
        let start_offset = line_byte_starts[i];
        let end_offset = if end_idx < line_byte_starts.len() {
            line_byte_starts[end_idx]
        } else {
            content.len()
        };
        // Strip exactly one trailing line ending to match the format
        // of exact-match results (which carry no trailing newline).
        let slice = &content[start_offset..end_offset];
        let matched_text = slice
            .strip_suffix("\r\n")
            .or_else(|| slice.strip_suffix('\n'))
            .unwrap_or(slice)
            .to_string();

        return Some(AnchorMatchResult {
            matched_text,
            start_offset,
            strategy: MatchStrategy::Anchor,
            score: None,
        });
    }

    None
}

/// Result of anchor-based matching.
#[derive(Debug, Clone)]
pub struct AnchorMatchResult {
    /// The text that was matched.
    pub matched_text: String,
    /// Byte offset of the match start in the content.
    pub start_offset: usize,
    /// Which matching strategy succeeded.
    pub strategy: MatchStrategy,
    /// Similarity score when [`MatchStrategy::Similarity`] succeeded (#1662).
    pub score: Option<f64>,
}

/// Which matching strategy found the result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MatchStrategy {
    /// Exact literal match.
    Exact,
    /// Anchor-based matching using surrounding context.
    Anchor,
    /// Similarity-based fuzzy matching.
    Similarity,
}

impl std::fmt::Display for MatchStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MatchStrategy::Exact => write!(f, "exact"),
            MatchStrategy::Anchor => write!(f, "anchor"),
            MatchStrategy::Similarity => write!(f, "similarity"),
        }
    }
}

/// Run the full fallback chain: exact -> anchor -> similarity -> structured error.
///
/// Returns the first successful match or a structured error with diagnosis.
///
/// Stable 4-arg surface. Callers that already enforced a stricter exact path
/// (for example `--word-boundary`) should use [`resolve_with_fallback_skip_exact`]
/// so bare `find` does not re-accept a substring the primary path rejected.
pub fn resolve_with_fallback(
    content: &str,
    target: &str,
    before_context: Option<&str>,
    after_context: Option<&str>,
) -> Result<AnchorMatchResult, EditError> {
    resolve_with_fallback_skip_exact(content, target, before_context, after_context, false)
}

/// Like [`resolve_with_fallback`], with control over the bare Exact tier.
///
/// When `skip_exact` is true, bare `find` Exact matching is skipped. Callers that
/// already ran a stricter exact path (for example `--word-boundary`) must set
/// this so fallback does not re-accept a substring that word boundaries rejected
/// (#1755). Similarity and anchor strategies still run (whole-token typo recovery).
pub fn resolve_with_fallback_skip_exact(
    content: &str,
    target: &str,
    before_context: Option<&str>,
    after_context: Option<&str>,
    skip_exact: bool,
) -> Result<AnchorMatchResult, EditError> {
    // Step 1: Exact match (unless caller already enforced a stricter exact path).
    if !skip_exact && let Some(pos) = content.find(target) {
        return Ok(AnchorMatchResult {
            matched_text: target.to_string(),
            start_offset: pos,
            strategy: MatchStrategy::Exact,
            score: None,
        });
    }

    // Step 2: Anchor-based matching.
    if let Some(result) = anchor_match(content, target, before_context, after_context) {
        // anchor_match may still surface Exact via its own find; reject that when
        // the caller asked to skip bare exact (word_boundary).
        if !(skip_exact && result.strategy == MatchStrategy::Exact) {
            return Ok(result);
        }
    }

    // Step 3: Similarity-based matching (#1694).
    //
    // Single-token targets (identifiers / typos) must match **tokens**, not whole
    // lines. Jaro-Winkler on a full source line vs a short identifier scores high
    // because of shared prefixes, then the apply path replaces the entire line and
    // deletes surrounding syntax (`const`, types, etc.).
    let target_lines: Vec<&str> = target.lines().collect();
    if target_lines.len() == 1 {
        let target_trim = target.trim();
        if is_token_like_target(target_trim) {
            if let Some(hit) = best_token_similarity(content, target_trim) {
                return Ok(hit);
            }
            // Do not fall through to whole-line similarity for token-like targets.
        } else if let Some(hit) = best_line_similarity(content, target_trim) {
            return Ok(hit);
        }
    }

    // Step 4: Structured error with diagnosis.
    let similar = find_similar_targets(content, target.lines().next().unwrap_or(target), 5);
    let suggestion = if !similar.is_empty() {
        Some(format!("did you mean: {}?", similar[0]))
    } else {
        None
    };

    Err(EditError {
        kind: EditErrorKind::NoMatch,
        message: format!("target not found: '{}'", truncate_str(target, 80)),
        suggestion,
        similar_targets: similar,
    })
}

/// Whether a fuzzy match should be rejected by `min_fuzzy_score` (#1687).
///
/// Fail closed when score is missing: hosts that set a floor must not apply
/// unscored fuzzy matches (anchor/legacy paths without a score cannot prove
/// they clear the floor).
pub(crate) fn fuzzy_fails_min_floor(score: Option<f64>, min: f64) -> bool {
    match score {
        Some(s) => s < min,
        None => true,
    }
}

/// #1758: refuse Similarity/fuzzy apply when exact `old` was absent unless opt-in.
///
/// Anchored (explicit context) matches are not refused here — the host supplied
/// landmarks. Only when the host opted into `fuzzy` and the resolve path returns
/// Similarity/Fuzzy mode do we fail closed by default. Context-only fallback
/// (before/after without `fuzzy`) may still land Similarity without this gate
/// so structural recovery stays usable.
pub(crate) fn should_refuse_fuzzy_absent_old(
    fuzzy_requested: bool,
    is_fuzzy_mode: bool,
    allow_absent_old: bool,
) -> bool {
    fuzzy_requested && is_fuzzy_mode && !allow_absent_old
}

/// Diagnostic when refusing fuzzy apply because exact `old` is not in the file.
pub(crate) fn fuzzy_absent_old_refuse_message(
    old: &str,
    matched_text: &str,
    score: Option<f64>,
) -> String {
    let score_s = score
        .map(|s| format!("{s:.3}"))
        .unwrap_or_else(|| "none".into());
    format!(
        "exact old absent for {:?}; best fuzzy candidate {:?} score {} \
         (set allow_absent_old / --allow-absent-old to apply)",
        truncate_str(old, 60),
        truncate_str(matched_text, 60),
        score_s
    )
}

/// True when `target` is a single identifier-like token (no whitespace).
///
/// Multi-word / snippet targets keep whole-line similarity. Token-like targets
/// use identifier-level matching so fuzzy typo recovery does not expand the
/// replace span to an entire source line (#1694).
fn is_token_like_target(target: &str) -> bool {
    if target.is_empty() || target.chars().any(|c| c.is_whitespace()) {
        return false;
    }
    // Match extract_identifiers: alphanumeric + underscore only. Hyphens would
    // mark the target as "token-like" while extraction splits on `-`, so a
    // kebab-case typo never matched a full token and skipped line fallback.
    target.chars().any(|c| c.is_alphanumeric())
        && target.chars().all(|c| c.is_alphanumeric() || c == '_')
}

/// Best identifier similarity hit, if score > 0.85.
fn best_token_similarity(content: &str, target: &str) -> Option<AnchorMatchResult> {
    let mut best_score = 0.0f64;
    let mut best_match = String::new();
    let mut best_offset = 0usize;
    let mut offset = 0usize;
    for line in content.lines() {
        for (ident, col) in extract_identifiers_with_offsets(line) {
            if ident == target {
                continue;
            }
            let score = strsim::jaro_winkler(&ident, target);
            if score > best_score {
                best_score = score;
                best_match = ident;
                best_offset = offset + col;
            }
        }
        offset = advance_line_offset(content, offset, line);
    }
    if best_score > 0.85 {
        Some(AnchorMatchResult {
            matched_text: best_match,
            start_offset: best_offset,
            strategy: MatchStrategy::Similarity,
            score: Some(best_score),
        })
    } else {
        None
    }
}

/// Whole-line similarity for multi-word / snippet targets.
///
/// Refuses a match when the line is much longer than the target (ratio > 2)
/// so accidental line expansion stays rare even for long snippets (#1694).
fn best_line_similarity(content: &str, target: &str) -> Option<AnchorMatchResult> {
    let mut best_score = 0.0f64;
    let mut best_match = String::new();
    let mut best_offset = 0usize;
    let mut offset = 0usize;
    for line in content.lines() {
        let score = strsim::jaro_winkler(line.trim(), target);
        if score > best_score {
            best_score = score;
            best_match = line.to_string();
            best_offset = offset;
        }
        offset = advance_line_offset(content, offset, line);
    }
    if best_score <= 0.85 {
        return None;
    }
    let line_len = best_match.trim().len();
    let target_len = target.len().max(1);
    if line_len > target_len.saturating_mul(2) && line_len > target_len + 16 {
        // Too expansive: treat as no similarity match (suggestions still help).
        return None;
    }
    Some(AnchorMatchResult {
        matched_text: best_match,
        start_offset: best_offset,
        strategy: MatchStrategy::Similarity,
        score: Some(best_score),
    })
}

fn advance_line_offset(content: &str, mut offset: usize, line: &str) -> usize {
    // Advance past the line content and the actual line ending (\r\n or \n).
    offset += line.len();
    if content.as_bytes().get(offset) == Some(&b'\r') {
        offset += 1;
    }
    if content.as_bytes().get(offset) == Some(&b'\n') {
        offset += 1;
    }
    offset
}

/// Extract identifier-like tokens from a line of code.
fn extract_identifiers(line: &str) -> Vec<String> {
    extract_identifiers_with_offsets(line)
        .into_iter()
        .map(|(s, _)| s)
        .collect()
}

/// Identifier tokens with byte offsets into `line` (#1694).
fn extract_identifiers_with_offsets(line: &str) -> Vec<(String, usize)> {
    let mut identifiers = Vec::new();
    let mut current = String::new();
    let mut start = 0usize;
    let mut i = 0usize;

    for ch in line.chars() {
        let clen = ch.len_utf8();
        if ch.is_alphanumeric() || ch == '_' {
            if current.is_empty() {
                start = i;
            }
            current.push(ch);
        } else {
            if current.len() >= 3 {
                identifiers.push((std::mem::take(&mut current), start));
            } else {
                current.clear();
            }
        }
        i += clen;
    }
    if current.len() >= 3 {
        identifiers.push((current, start));
    }

    identifiers
}

/// Truncate a string for display in error messages.
///
/// Truncates at the last char boundary at or before `max_len` bytes,
/// so this is safe for multi-byte UTF-8 input.
pub(crate) fn truncate_str(s: &str, max_len: usize) -> &str {
    if s.len() <= max_len {
        s
    } else {
        // Find the last char boundary at or before max_len.
        let mut end = max_len;
        while end > 0 && !s.is_char_boundary(end) {
            end -= 1;
        }
        &s[..end]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn edit_error_display() {
        let err = EditError {
            kind: EditErrorKind::NoMatch,
            message: "target not found".into(),
            suggestion: Some("try 'process_request'".into()),
            similar_targets: vec!["process_request".into()],
        };
        let display = err.to_string();
        assert!(display.contains("no_match"));
        assert!(display.contains("target not found"));
        assert!(display.contains("process_request"));
    }

    #[test]
    fn edit_error_kind_display() {
        assert_eq!(
            EditErrorKind::AmbiguousTarget.to_string(),
            "ambiguous_target"
        );
        assert_eq!(EditErrorKind::NoMatch.to_string(), "no_match");
        assert_eq!(EditErrorKind::SyntaxInvalid.to_string(), "syntax_invalid");
        assert_eq!(
            EditErrorKind::ConflictingEdit.to_string(),
            "conflicting_edit"
        );
        assert_eq!(EditErrorKind::ParseError.to_string(), "parse_error");
        assert_eq!(EditErrorKind::TypeError.to_string(), "type_error");
        assert_eq!(EditErrorKind::InvalidInput.to_string(), "invalid_input");
        assert_eq!(EditErrorKind::AlreadyExists.to_string(), "already_exists");
        assert_eq!(EditErrorKind::NotFound.to_string(), "not_found");
        assert_eq!(EditErrorKind::Conflicts.to_string(), "conflicts");
        assert_eq!(
            EditErrorKind::ChangesDetected.to_string(),
            "changes_detected"
        );
        assert_eq!(EditErrorKind::FormatFailed.to_string(), "format_failed");
        assert_eq!(EditErrorKind::Binary.to_string(), "binary");
        assert_eq!(
            EditErrorKind::InvalidEncoding.to_string(),
            "invalid_encoding"
        );
    }

    /// Locks discriminants published in 0.18.0 so new kinds stay append-only
    /// (`enum_no_repr_variant_discriminant_changed` / release PR #1951).
    #[test]
    fn edit_error_kind_stable_discriminants_since_0_18_0() {
        assert_eq!(EditErrorKind::AmbiguousTarget as u8, 0);
        assert_eq!(EditErrorKind::NoMatch as u8, 1);
        assert_eq!(EditErrorKind::SyntaxInvalid as u8, 2);
        assert_eq!(EditErrorKind::ConflictingEdit as u8, 3);
        assert_eq!(EditErrorKind::ParseError as u8, 4);
        assert_eq!(EditErrorKind::GuardRejected as u8, 5);
        assert_eq!(EditErrorKind::InvalidInput as u8, 6);
        assert_eq!(EditErrorKind::TypeError as u8, 7);
        assert_eq!(EditErrorKind::OperationFailed as u8, 8);
        assert_eq!(EditErrorKind::FormatFailed as u8, 9);
        // #1947/#1950 kinds must follow FormatFailed (never insert above).
        assert_eq!(EditErrorKind::AlreadyExists as u8, 10);
        assert_eq!(EditErrorKind::NotFound as u8, 11);
        assert_eq!(EditErrorKind::Conflicts as u8, 12);
        assert_eq!(EditErrorKind::ChangesDetected as u8, 13);
        // #1963 kinds append after ChangesDetected (never insert above).
        assert_eq!(EditErrorKind::Binary as u8, 14);
        assert_eq!(EditErrorKind::InvalidEncoding as u8, 15);
    }

    #[test]
    fn classify_error_peels_edit_error_and_typed() {
        use std::error::Error;
        let e = EditError::new(EditErrorKind::AmbiguousTarget, "many");
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::AmbiguousTarget)
        );
        let e = crate::exit::NoMatchError { msg: "none".into() };
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::NoMatch)
        );
        let e = crate::exit::FormatFailedError::new("fmt");
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::FormatFailed)
        );
        let e = crate::exit::TypeErrorError {
            msg: "parent is an array".into(),
        };
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::TypeError)
        );
        let e = crate::exit::AlreadyExistsError {
            msg: "exists".into(),
        };
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::AlreadyExists)
        );
        let e = crate::exit::ConflictsError {
            msg: "conflict".into(),
        };
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::Conflicts)
        );
        let e = crate::exit::ChangesDetectedError {
            msg: "would change".into(),
        };
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::ChangesDetected)
        );
        let e = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
        assert_eq!(
            classify_error(&e as &(dyn Error + 'static)),
            Some(EditErrorKind::NotFound)
        );
    }

    #[test]
    fn edit_error_kind_maps_exit_typed_errors() {
        let invalid: anyhow::Error = crate::exit::InvalidInputError {
            msg: "empty search pattern".into(),
        }
        .into();
        assert_eq!(edit_error_kind(&invalid), Some(EditErrorKind::InvalidInput));
        assert!(is_invalid_input(&invalid));
        assert!(!is_guard_rejected(&invalid));

        let no_match: anyhow::Error = crate::exit::NoMatchError {
            msg: "no matches".into(),
        }
        .into();
        assert_eq!(edit_error_kind(&no_match), Some(EditErrorKind::NoMatch));
        assert!(is_no_match(&no_match));
        assert_eq!(error_kind_str(&no_match), Some("no_matches"));
        assert!(!is_not_found(&no_match));

        let ambiguous: anyhow::Error = crate::exit::AmbiguousError {
            msg: "multiple matches".into(),
        }
        .into();
        assert_eq!(
            edit_error_kind(&ambiguous),
            Some(EditErrorKind::AmbiguousTarget)
        );
        assert!(is_ambiguous(&ambiguous));
        assert_eq!(error_kind_str(&ambiguous), Some("ambiguous"));
        assert!(!is_no_match(&ambiguous));

        let parse: anyhow::Error = crate::exit::ParseErrorError {
            msg: "bad yaml".into(),
        }
        .into();
        assert_eq!(edit_error_kind(&parse), Some(EditErrorKind::ParseError));

        let exists: anyhow::Error = crate::exit::AlreadyExistsError {
            msg: "file already exists".into(),
        }
        .into();
        assert_eq!(
            edit_error_kind(&exists),
            Some(EditErrorKind::AlreadyExists),
            "AlreadyExistsError must not collapse to InvalidInput (#1947)"
        );
        assert!(is_already_exists(&exists));
        assert_eq!(error_kind_str(&exists), Some("already_exists"));

        let exists_edit: anyhow::Error =
            EditError::new(EditErrorKind::AlreadyExists, "dest taken").into();
        assert!(
            is_already_exists(&exists_edit),
            "is_already_exists must match EditErrorKind::AlreadyExists too"
        );
        assert_eq!(
            edit_error_kind(&exists_edit),
            Some(EditErrorKind::AlreadyExists)
        );

        let type_err: anyhow::Error = crate::exit::TypeErrorError {
            msg: "parent is an array, not an object".into(),
        }
        .into();
        assert_eq!(
            edit_error_kind(&type_err),
            Some(EditErrorKind::TypeError),
            "TypeErrorError must not collapse to InvalidInput (#1883)"
        );
        assert!(is_type_error(&type_err));
        assert!(!is_invalid_input(&type_err));

        let format_failed: anyhow::Error =
            crate::exit::FormatFailedError::new("format command failed").into();
        assert_eq!(
            edit_error_kind(&format_failed),
            Some(EditErrorKind::FormatFailed)
        );
        assert!(is_format_failed(&format_failed));
        assert!(!is_type_error(&format_failed));

        let guard: anyhow::Error =
            EditError::new(EditErrorKind::GuardRejected, "path escapes").into();
        assert!(is_guard_rejected(&guard));
        assert_eq!(error_kind_str(&guard), Some("guard_rejected"));
        assert!(!is_invalid_input(&guard));

        let not_found: anyhow::Error =
            std::io::Error::new(std::io::ErrorKind::NotFound, "missing").into();
        let not_found = not_found.context("failed to read path");
        assert_eq!(
            edit_error_kind(&not_found),
            Some(EditErrorKind::NotFound),
            "IO NotFound must peel as NotFound not OperationFailed"
        );
        assert_eq!(error_kind_str(&not_found), Some("not_found"));
        assert!(
            is_not_found(&not_found),
            "is_not_found must match IO NotFound peel"
        );
        assert!(!is_already_exists(&not_found));

        let conflicts: anyhow::Error = crate::exit::ConflictsError {
            msg: "merge conflict".into(),
        }
        .into();
        assert_eq!(edit_error_kind(&conflicts), Some(EditErrorKind::Conflicts));
        assert_eq!(error_kind_str(&conflicts), Some("conflicts"));
        assert!(is_conflicts(&conflicts));
        assert!(!is_not_found(&conflicts));

        let changes: anyhow::Error = crate::exit::ChangesDetectedError {
            msg: "would change".into(),
        }
        .into();
        assert_eq!(
            edit_error_kind(&changes),
            Some(EditErrorKind::ChangesDetected)
        );
        assert_eq!(error_kind_str(&changes), Some("changes_detected"));
        assert!(is_changes_detected(&changes));
        assert!(!is_conflicts(&changes));

        // Intermediate .context() must not hide the typed kind.
        let wrapped = invalid.context("operation 1 (replace) failed");
        assert_eq!(edit_error_kind(&wrapped), Some(EditErrorKind::InvalidInput));

        let type_wrapped = type_err.context("operation 1 (doc.set) failed");
        assert_eq!(
            edit_error_kind(&type_wrapped),
            Some(EditErrorKind::TypeError)
        );

        let plain = anyhow::anyhow!("plain error");
        assert_eq!(edit_error_kind(&plain), None);
    }

    #[test]
    fn validate_edit_empty_pattern() {
        let result = validate_edit("content", "", "replacement", None);
        assert!(!result.valid);
        assert!(result.errors[0].contains("empty search pattern"));
    }

    #[test]
    fn validate_edit_pattern_not_found() {
        let result = validate_edit("hello world", "missing", "replacement", None);
        assert!(!result.valid);
        assert!(result.errors[0].contains("not found"));
    }

    #[test]
    fn validate_edit_valid_replacement() {
        let result = validate_edit("hello world", "hello", "goodbye", None);
        assert!(result.valid);
        assert!(result.errors.is_empty());
    }

    #[test]
    fn validate_edit_json_syntax_check() {
        let json = r#"{"key": "value"}"#;
        // Valid replacement.
        let result = validate_edit(json, "value", "new_value", Some("config.json"));
        assert!(result.valid);

        // Invalid replacement (breaks JSON).
        let result = validate_edit(json, "\"key\":", "broken", Some("config.json"));
        assert!(!result.valid);
        assert!(result.errors[0].contains("invalid JSON"));
    }

    #[test]
    fn validate_edit_yaml_syntax_check() {
        let yaml = "key: value\n";
        let result = validate_edit(yaml, "value", "new_value", Some("config.yaml"));
        assert!(result.valid);
    }

    #[test]
    fn validate_edit_warns_unbalanced_braces() {
        let content = "fn main() { hello }";
        let result = validate_edit(content, "{ hello }", "{ hello", None);
        assert!(result.valid); // Still valid (we can't know the language syntax).
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("unbalanced braces"))
        );
    }

    #[test]
    fn find_similar_targets_finds_typos() {
        let content = "fn process_request() {}\nfn process_response() {}\nfn handle_error() {}\n";
        let similar = find_similar_targets(content, "process_requst", 3);
        assert!(!similar.is_empty());
        assert!(similar.iter().any(|s| s.contains("process_request")));
    }

    #[test]
    fn find_similar_targets_rejects_length_skew_noise() {
        // Real multi-file no-match noise (fixrealloop stress): long invented
        // pattern vs short tokens like "nold" can clear a loose JW floor.
        let content = "fn nold() {}\nlet compute = 1;\nfn process_request() {}\n";
        let similar = find_similar_targets(content, "this_string_should_not_exist_xyzzy", 5);
        assert!(
            similar.is_empty(),
            "unrelated long pattern must not suggest short tokens: {similar:?}"
        );
        let similar = find_similar_targets(content, "completely_bogus_token_zzz", 5);
        assert!(
            !similar
                .iter()
                .any(|s| s == "compute" || s == "let" || s == "nold"),
            "bogus pattern must not surface weak short-token hints: {similar:?}"
        );
    }

    #[test]
    fn find_similar_targets_empty_content() {
        let similar = find_similar_targets("", "target", 3);
        assert!(similar.is_empty());
    }

    #[test]
    fn find_similar_targets_empty_target() {
        let similar = find_similar_targets("content", "", 3);
        assert!(similar.is_empty());
    }

    #[test]
    fn anchor_match_exact() {
        let content = "line1\nline2\nline3\n";
        let result = anchor_match(content, "line2", None, None).unwrap();
        assert_eq!(result.matched_text, "line2");
        assert_eq!(result.strategy, MatchStrategy::Exact);
    }

    #[test]
    fn anchor_match_with_context() {
        // Simulate a case where the target line changed slightly.
        let content = "fn setup() {}\nfn proccess_data(x: i32) {}\nfn cleanup() {}\n";
        let result = anchor_match(
            content,
            "fn process_data(x: i32) {}",
            Some("fn setup() {}"),
            Some("fn cleanup() {}"),
        );
        let r = result.expect("anchor match should find a fuzzy match");
        assert_eq!(r.strategy, MatchStrategy::Anchor);
        assert!(r.matched_text.contains("proccess_data"));
    }

    #[test]
    fn anchor_match_no_match() {
        let content = "completely different content\n";
        let result = anchor_match(content, "not here at all", None, None);
        assert!(result.is_none());
    }

    #[test]
    fn anchor_match_requires_context_for_fuzzy() {
        // Without context, anchor matching skips the fuzzy path and returns
        // None even if a similar line exists. This prevents anchor from
        // duplicating the similarity path in the fallback chain.
        let content = "fn process_request(x: i32) {}\n";
        let result = anchor_match(content, "fn process_requst(x: i32) {}", None, None);
        assert!(result.is_none());
    }

    #[test]
    fn anchor_match_multi_line_verifies_last_line() {
        // Multi-line anchor matching must check both the first and last
        // lines of the candidate region, not just the first.
        let content = "fn setup() {}\nfn process(x: i32) {}\nfn teardown() {}\nfn other() {}\n";
        // Target has a matching first line but wrong last line.
        let result = anchor_match(
            content,
            "fn process(x: i32) {}\nfn completely_wrong() {}",
            Some("fn setup() {}"),
            None,
        );
        assert!(result.is_none());
    }

    #[test]
    fn anchor_match_crlf_offset() {
        let content = "line1\r\nline2\r\nline3\r\n";
        let result = anchor_match(content, "line2", Some("line1"), None).unwrap();
        // "line1\r\n" is 7 bytes, so line2 starts at offset 7.
        assert_eq!(result.start_offset, 7);
    }

    /// Regression: anchor match on CRLF content must produce a matched_text
    /// that is an exact substring of the original content. The old code
    /// joined lines with "\n" which produced LF-only text, wrong for CRLF.
    #[test]
    fn anchor_match_crlf_matched_text_preserves_endings() {
        let content =
            "fn setup() {}\r\nfn proccess_data(x: i32) {}\r\nfn more() {}\r\nfn cleanup() {}\r\n";
        let result = anchor_match(
            content,
            "fn process_data(x: i32) {}\nfn more() {}",
            Some("fn setup() {}"),
            Some("fn cleanup() {}"),
        )
        .unwrap();
        // matched_text must be verifiable against the original content.
        let end = result.start_offset + result.matched_text.len();
        assert_eq!(
            &content[result.start_offset..end],
            result.matched_text,
            "matched_text must be an exact slice of the original content"
        );
        // And it should contain the CRLF between lines.
        assert!(
            result.matched_text.contains("\r\n"),
            "matched text should preserve CRLF line endings"
        );
    }

    /// Regression: anchor match on mixed line endings (some CRLF, some LF)
    /// must produce correct offsets for each line, not a global decision.
    #[test]
    fn anchor_match_mixed_endings_correct_offset() {
        let content = "header\r\nfn proccess(x: i32) {}\nfooter\n";
        let result = anchor_match(
            content,
            "fn process(x: i32) {}",
            Some("header"),
            Some("footer"),
        )
        .unwrap();
        // "header\r\n" is 8 bytes, so line 2 starts at offset 8.
        assert_eq!(result.start_offset, 8);
        let end = result.start_offset + result.matched_text.len();
        assert_eq!(&content[result.start_offset..end], result.matched_text);
    }

    #[test]
    fn resolve_with_fallback_exact_match() {
        let content = "fn hello() {}\n";
        let result = resolve_with_fallback(content, "fn hello()", None, None).unwrap();
        assert_eq!(result.strategy, MatchStrategy::Exact);
    }

    /// #1755: skip_exact must not re-accept a bare substring after a stricter
    /// primary path (e.g. word_boundary) already rejected it.
    #[test]
    fn resolve_with_fallback_skip_exact_rejects_substring() {
        let content = "process_data process_data_extra\n";
        // Without skip_exact, bare find would match "process_dat" inside process_data.
        let bare = resolve_with_fallback(content, "process_dat", None, None).unwrap();
        assert_eq!(bare.strategy, MatchStrategy::Exact);
        assert_eq!(bare.matched_text, "process_dat");

        // With skip_exact, Exact is skipped; token similarity may recover the
        // full identifier (process_data) or miss — but never the bare substring.
        match resolve_with_fallback_skip_exact(content, "process_dat", None, None, true) {
            Ok(hit) => {
                assert_ne!(
                    hit.strategy,
                    MatchStrategy::Exact,
                    "skip_exact must not return Exact"
                );
                assert_ne!(
                    hit.matched_text, "process_dat",
                    "must not re-accept word_boundary-rejected substring"
                );
            }
            Err(e) => assert_eq!(e.kind, EditErrorKind::NoMatch),
        }
    }

    /// Regression: similarity matching on CRLF content must compute
    /// correct byte offsets. The old code used `offset += line.len() + 1`
    /// which hardcoded LF (1 byte), wrong for CRLF (2 bytes).
    #[test]
    fn resolve_with_fallback_similarity_crlf_offset() {
        let content = "fn alpha() {}\r\nfn process_requets(data: &str) {}\r\nfn gamma() {}\r\n";
        let result =
            resolve_with_fallback(content, "fn process_requests(data: &str) {}", None, None)
                .unwrap();
        assert_eq!(result.strategy, MatchStrategy::Similarity);
        // "fn alpha() {}\r\n" is 15 bytes, so the match starts at offset 15.
        assert_eq!(result.start_offset, 15);
        // Verify the offset points to the correct position in content.
        assert!(
            content[result.start_offset..].starts_with(&result.matched_text),
            "start_offset must point to matched_text in content"
        );
    }

    #[test]
    fn resolve_with_fallback_similarity_match() {
        // Without context, anchor matching is skipped (it requires at least
        // before_context or after_context to avoid degenerating into the same
        // Jaro-Winkler scan that similarity already does). The similarity
        // path catches the misspelled target instead.
        let content = "fn process_request(data: &str) -> Result<()> {\n    Ok(())\n}\n";
        let result = resolve_with_fallback(
            content,
            "fn process_requets(data: &str) -> Result<()> {",
            None,
            None,
        );
        let r = result.expect("similarity fallback should succeed");
        assert_eq!(r.strategy, MatchStrategy::Similarity);
        // Multi-word snippet → whole-line match (not a bare identifier).
        assert!(
            r.matched_text.contains("process_request"),
            "snippet match: {:?}",
            r.matched_text
        );
    }

    /// #1694: single-token fuzzy must not expand to the whole source line.
    #[test]
    fn resolve_token_typo_does_not_match_whole_line() {
        let content = "const CONFIGURATION_VALUE_PRIMARY: i32 = 1;\nfn use_it() -> i32 { CONFIGURATION_VALUE_PRIMARY }\n";
        let r = resolve_with_fallback(content, "CONFIGURATION_VALUE_PRIMRY", None, None)
            .expect("token typo should fuzzy-match the identifier");
        assert_eq!(r.strategy, MatchStrategy::Similarity);
        assert_eq!(
            r.matched_text, "CONFIGURATION_VALUE_PRIMARY",
            "must match the identifier token only, not the whole line"
        );
        assert!(
            content[r.start_offset..].starts_with("CONFIGURATION_VALUE_PRIMARY"),
            "offset must point at the token"
        );
        // Surrounding syntax must still be outside the match span.
        assert!(!r.matched_text.contains("const"));
        assert!(!r.matched_text.contains("i32"));
    }

    /// #1694: intentional full-line target still uses line similarity.
    #[test]
    fn resolve_full_line_snippet_still_matches_line() {
        let content = "const FOO: i32 = 1;\n";
        let r = resolve_with_fallback(content, "const FO: i32 = 1;", None, None)
            .expect("near-full-line snippet should match the line");
        assert_eq!(r.strategy, MatchStrategy::Similarity);
        assert!(
            r.matched_text.contains("const") && r.matched_text.contains("FOO"),
            "line match: {:?}",
            r.matched_text
        );
    }

    /// Embedder-style identifier typos across real source shapes (#1694 contract).
    #[test]
    fn resolve_token_typo_matrix_preserves_non_identifier_syntax() {
        // (content, typo_target, expected_matched_token, must_not_be_in_match)
        let cases: &[(&str, &str, &str, &[&str])] = &[
            // Rust const + use site (Bline #1694 repro shape).
            (
                "const CONFIGURATION_VALUE_PRIMARY: i32 = 1;\nfn use_it() -> i32 { CONFIGURATION_VALUE_PRIMARY }\n",
                "CONFIGURATION_VALUE_PRIMRY",
                "CONFIGURATION_VALUE_PRIMARY",
                &["const", "i32", "fn"],
            ),
            // Rust function name typo (token, not full signature).
            (
                "fn process_request(data: &str) -> Result<()> {\n    Ok(())\n}\n",
                "process_requets",
                "process_request",
                &["fn", "Result", "data"],
            ),
            // Python def.
            (
                "def load_configuration_value():\n    return 1\n",
                "load_configration_value",
                "load_configuration_value",
                &["def", "return"],
            ),
            // JS/TS const + call.
            (
                "const getUserProfile = () => null;\nexport { getUserProfile };\n",
                "getUserProfle",
                "getUserProfile",
                &["const", "export"],
            ),
            // YAML-ish key in a line with punctuation (identifier extraction).
            (
                "server_port_primary: 8080\n",
                "server_port_primry",
                "server_port_primary",
                &[":", "8080"],
            ),
            // camelCase method.
            (
                "    obj.fetchUserDetails(id);\n",
                "fetchUserDetials",
                "fetchUserDetails",
                &["obj", "id"],
            ),
        ];

        for (content, typo, expected, forbidden) in cases {
            let r = resolve_with_fallback(content, typo, None, None)
                .unwrap_or_else(|e| panic!("token typo {typo:?} should match in {content:?}: {e}"));
            assert_eq!(r.strategy, MatchStrategy::Similarity, "typo={typo:?}");
            assert_eq!(
                r.matched_text, *expected,
                "typo={typo:?} content={content:?}"
            );
            assert!(
                content[r.start_offset..].starts_with(expected),
                "offset wrong for {typo:?}"
            );
            for bad in *forbidden {
                assert!(
                    !r.matched_text.contains(bad),
                    "span leaked {bad:?} for typo={typo:?} match={:?}",
                    r.matched_text
                );
            }
            // Token-like targets must never expand to multi-word spans.
            assert!(
                !r.matched_text.contains(' '),
                "token match must not contain spaces: {:?}",
                r.matched_text
            );
        }
    }

    #[test]
    fn resolve_token_typo_picks_first_best_occurrence() {
        let content = "FOO_PRIMARY=1\nFOO_PRIMARY=2\n";
        let r = resolve_with_fallback(content, "FOO_PRIMRY", None, None).unwrap();
        assert_eq!(r.matched_text, "FOO_PRIMARY");
        // First line occurrence (offset 0).
        assert_eq!(r.start_offset, 0);
    }

    #[test]
    fn resolve_token_unrelated_is_no_match() {
        let content = "const ALPHA: i32 = 1;\nconst BETA: i32 = 2;\n";
        let err =
            resolve_with_fallback(content, "ZZZZ_COMPLETELY_UNRELATED", None, None).unwrap_err();
        assert_eq!(err.kind, EditErrorKind::NoMatch);
    }

    #[test]
    fn is_token_like_target_classification() {
        assert!(is_token_like_target("CONFIGURATION_VALUE_PRIMRY"));
        assert!(is_token_like_target("getUserProfile"));
        // Hyphenated names are not identifier tokens (extraction splits on `-`).
        assert!(!is_token_like_target("kebab-case-name"));
        assert!(!is_token_like_target("fn process_data() {}"));
        assert!(!is_token_like_target("const FOO: i32 = 1;"));
        assert!(!is_token_like_target("server.port"));
        assert!(!is_token_like_target(""));
        assert!(!is_token_like_target("   "));
    }

    #[test]
    fn fuzzy_fails_min_floor_fail_closed_without_score() {
        assert!(fuzzy_fails_min_floor(None, 0.8));
        assert!(fuzzy_fails_min_floor(Some(0.5), 0.8));
        assert!(!fuzzy_fails_min_floor(Some(0.9), 0.8));
        assert!(!fuzzy_fails_min_floor(Some(0.8), 0.8));
    }

    /// Kebab-case targets use line similarity (not broken token path).
    #[test]
    fn resolve_kebab_case_uses_line_similarity_not_broken_token_path() {
        let content = "font-weight-primary: bold;\n";
        // Near-full-line typo; must still resolve (line path), not dead-end as token.
        let r = resolve_with_fallback(content, "font-weight-primry: bold;", None, None)
            .expect("kebab line snippet should match via line similarity");
        assert_eq!(r.strategy, MatchStrategy::Similarity);
        assert!(
            r.matched_text.contains("font-weight-primary"),
            "{:?}",
            r.matched_text
        );
    }

    #[test]
    fn resolve_with_fallback_structured_error() {
        let content = "fn alpha() {}\nfn beta() {}\n";
        let result = resolve_with_fallback(content, "fn completely_unrelated_xyz()", None, None);
        let err = result.unwrap_err();
        assert_eq!(err.kind, EditErrorKind::NoMatch);
        assert!(err.message.contains("target not found"));
    }

    #[test]
    fn resolve_with_fallback_anchor_over_similarity() {
        // When context is provided, anchor matching fires before similarity
        // and should win.
        let content = "fn setup() {}\nfn proces_data(x: i32) {}\nfn cleanup() {}\n";
        let result = resolve_with_fallback(
            content,
            "fn process_data(x: i32) {}",
            Some("fn setup() {}"),
            Some("fn cleanup() {}"),
        );
        let r = result.expect("anchor fallback should succeed");
        assert_eq!(r.strategy, MatchStrategy::Anchor);
    }

    #[test]
    fn edit_error_serializes_to_json() {
        let err = EditError {
            kind: EditErrorKind::AmbiguousTarget,
            message: "found 3 matches".into(),
            suggestion: Some("use --nth to select one".into()),
            similar_targets: vec!["match1".into(), "match2".into()],
        };
        let json = serde_json::to_string(&err).unwrap();
        let deserialized: EditError = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.kind, EditErrorKind::AmbiguousTarget);
        assert_eq!(deserialized.similar_targets.len(), 2);
    }

    #[test]
    fn match_strategy_display() {
        assert_eq!(MatchStrategy::Exact.to_string(), "exact");
        assert_eq!(MatchStrategy::Anchor.to_string(), "anchor");
        assert_eq!(MatchStrategy::Similarity.to_string(), "similarity");
    }

    #[test]
    fn extract_identifiers_from_code() {
        let line = "fn process_request(data: &str) -> Result<()> {";
        let ids = extract_identifiers(line);
        assert!(ids.contains(&"process_request".to_string()));
        assert!(ids.contains(&"data".to_string()));
        assert!(ids.contains(&"str".to_string()));
        assert!(ids.contains(&"Result".to_string()));
    }

    #[test]
    fn validation_result_serializes() {
        let result = ValidationResult {
            valid: true,
            errors: vec![],
            warnings: vec!["some warning".into()],
        };
        let json = serde_json::to_string(&result).unwrap();
        let deserialized: ValidationResult = serde_json::from_str(&json).unwrap();
        assert!(deserialized.valid);
        assert_eq!(deserialized.warnings.len(), 1);
    }

    #[test]
    fn truncate_safe_on_multibyte_utf8() {
        // "café" has bytes: c(1) a(1) f(1) é(2) = 5 bytes, 4 chars.
        let s = "café";
        assert_eq!(s.len(), 5);
        // Truncate at 4 would land in the middle of 'é' (bytes 3-4).
        // Must not panic; should truncate before the multi-byte char.
        let t = truncate_str(s, 4);
        assert_eq!(t, "caf");
        // Truncate at 5 returns the whole string.
        assert_eq!(truncate_str(s, 5), "café");
        // Truncate at 3 is a clean boundary.
        assert_eq!(truncate_str(s, 3), "caf");
        // Truncate at 0.
        assert_eq!(truncate_str(s, 0), "");
    }

    #[test]
    fn validate_edit_toml_syntax_check() {
        let toml = "[database]\nhost = \"localhost\"\n";
        // Valid replacement.
        let result = validate_edit(toml, "localhost", "remotehost", Some("config.toml"));
        assert!(result.valid);

        // Invalid replacement (breaks TOML).
        let result = validate_edit(
            toml,
            "[database]",
            "not valid toml {{{{",
            Some("config.toml"),
        );
        assert!(!result.valid);
        assert!(result.errors[0].contains("invalid TOML"));
    }

    #[test]
    fn find_similar_targets_multi_word_pattern() {
        let content = "fn process_all_requests(data: &str) -> bool {\n    true\n}\n";
        // Multi-word pattern triggers whole-line matching path.
        let similar = find_similar_targets(content, "fn process_all_reqests(data: &str)", 3);
        assert!(
            !similar.is_empty(),
            "should find similar multi-word targets"
        );
    }

    #[test]
    fn resolve_fallback_multi_line_no_similarity() {
        // Multi-line targets skip the similarity path and go to error.
        let content = "fn alpha() {}\nfn beta() {}\nfn gamma() {}\n";
        let result = resolve_with_fallback(content, "fn alphax() {}\nfn betax() {}", None, None);
        assert!(
            result.is_err(),
            "multi-line targets without context should not match via similarity"
        );
        let err = result.unwrap_err();
        assert_eq!(err.kind, EditErrorKind::NoMatch);
    }

    #[test]
    fn resolve_with_fallback_multi_line_anchor_match() {
        // Multi-line target with context should resolve via anchor matching
        // through the full fallback chain (not just the anchor_match helper).
        let content = "fn header() {}\nfn proccess_data(x: i32) {\n    x + 1\n}\nfn footer() {}\n";
        let result = resolve_with_fallback(
            content,
            "fn process_data(x: i32) {\n    x + 1\n}",
            Some("fn header() {}"),
            Some("fn footer() {}"),
        );
        let r = result.expect("multi-line anchor should succeed");
        assert_eq!(r.strategy, MatchStrategy::Anchor);
        assert!(r.matched_text.contains("proccess_data"));
        assert!(r.matched_text.contains("x + 1"));
    }

    #[test]
    fn validate_edit_yml_extension() {
        // The .yml extension (not just .yaml) should trigger YAML validation.
        let yaml = "key: value\nlist:\n  - item1\n";
        // Valid replacement.
        let result = validate_edit(yaml, "value", "new_value", Some("config.yml"));
        assert!(result.valid);

        // Invalid replacement that breaks YAML structure.
        let result = validate_edit(yaml, "key: value", ":\n  :\n  - :", Some("config.yml"));
        assert!(
            !result.valid,
            ".yml extension should trigger YAML validation"
        );
        assert!(
            result.errors[0].contains("invalid YAML"),
            "expected YAML error, got: {}",
            result.errors[0]
        );
    }

    // -- validate_edit_nth (#1061) -------------------------------------------

    #[test]
    fn validate_edit_nth_replaces_only_nth_occurrence() {
        // Two occurrences of "val"; replacing only the 1st is valid JSON.
        let json = r#"{"a": "val", "b": "val"}"#;
        let result = validate_edit_nth(json, "val", "new", Some("data.json"), Some(1));
        assert!(result.valid, "nth=1 should produce valid JSON");
    }

    #[test]
    fn validate_edit_nth_none_replaces_all() {
        // nth=None replaces all occurrences (same as validate_edit).
        let content = "aXbXc";
        let result = validate_edit_nth(content, "X", "Y", None, None);
        assert!(result.valid);
    }

    #[test]
    fn validate_edit_nth_out_of_range() {
        // nth=5 but only 2 occurrences: should return invalid with descriptive error.
        let content = "aXbXc";
        let result = validate_edit_nth(content, "X", "Y", None, Some(5));
        assert!(
            !result.valid,
            "nth beyond occurrence count should be invalid"
        );
        assert!(
            result.errors[0].contains("occurrence 5 not found"),
            "error should mention the missing occurrence: {:?}",
            result.errors
        );
    }

    #[test]
    fn validate_edit_nth_zero_rejected() {
        // nth=0 is invalid (1-based indexing); must not truncate content.
        let content = r#"{"a": "val"}"#;
        let result = validate_edit_nth(content, "val", "X", Some("f.json"), Some(0));
        assert!(!result.valid);
        assert!(result.errors[0].contains("nth must be >= 1"));
    }

    #[test]
    fn validate_edit_nth_detects_invalid_json_for_single_occurrence() {
        // Replacing only the 1st "value" with a broken fragment is invalid.
        let json = r#"{"a": "value", "b": "value"}"#;
        let result = validate_edit_nth(json, "\"value\"", "broken}", Some("config.json"), Some(1));
        assert!(!result.valid, "nth=1 should detect broken JSON");
    }

    // -- anchor_match and resolve_with_fallback edge cases (#978) -----------

    #[test]
    fn anchor_match_after_only_context() {
        // after_context without before_context hits the code path where
        // before_context is None but after_context is checked.
        let content = "fn setup() {}\nfn proccess_data(x: i32) {}\nfn cleanup() {}\n";
        let result = anchor_match(
            content,
            "fn process_data(x: i32) {}",
            None,
            Some("fn cleanup() {}"),
        );
        let r = result.expect("after-only context should find anchor match");
        assert_eq!(r.strategy, MatchStrategy::Anchor);
        assert!(r.matched_text.contains("proccess_data"));
    }

    #[test]
    fn anchor_match_multiple_candidates_returns_first() {
        // Target appears (fuzzily) twice; anchor_match returns the first match.
        let content = "fn header() {}\nfn proccess(x: i32) {}\nfn middle() {}\nfn proccess(y: bool) {}\nfn footer() {}\n";
        let result = anchor_match(
            content,
            "fn process(x: i32) {}",
            Some("fn header() {}"),
            Some("fn middle() {}"),
        );
        let r = result.expect("should match first candidate");
        assert_eq!(r.strategy, MatchStrategy::Anchor);
        // The first candidate contains "x: i32", not "y: bool".
        assert!(
            r.matched_text.contains("x: i32"),
            "should match first occurrence, got: {}",
            r.matched_text
        );
    }

    #[test]
    fn resolve_with_fallback_empty_content() {
        let result = resolve_with_fallback("", "fn hello()", None, None);
        let err = result.unwrap_err();
        assert_eq!(err.kind, EditErrorKind::NoMatch);
    }

    #[test]
    fn anchor_match_multiline_before_context() {
        // Multi-line before_context should use the last line for matching,
        // not the entire multi-line string.
        let content = "fn setup() {}\nfn target() {}\nfn cleanup() {}\n";
        let result = anchor_match(
            content,
            "fn target() {}",
            Some("fn other() {}\nfn setup() {}"),
            None,
        );
        assert!(
            result.is_some(),
            "anchor_match should match using the last line of multi-line before_context"
        );
        assert_eq!(result.unwrap().matched_text, "fn target() {}");
    }

    #[test]
    fn anchor_match_multiline_after_context() {
        // Multi-line after_context should use the first line for matching.
        let content = "fn setup() {}\nfn target() {}\nfn cleanup() {}\n";
        let result = anchor_match(
            content,
            "fn target() {}",
            None,
            Some("fn cleanup() {}\nfn extra() {}"),
        );
        assert!(
            result.is_some(),
            "anchor_match should match using the first line of multi-line after_context"
        );
        assert_eq!(result.unwrap().matched_text, "fn target() {}");
    }

    // Static assertions: types must be Send + Sync.
    const _: () = {
        fn _assert<T: Send + Sync>() {}
        let _ = _assert::<EditError>;
        let _ = _assert::<EditErrorKind>;
        let _ = _assert::<ValidationResult>;
        let _ = _assert::<AnchorMatchResult>;
        let _ = _assert::<MatchStrategy>;
    };
}