patchloom 0.37.2

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
use super::*;
use crate::cli::global::GlobalFlags;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use tempfile::TempDir;

// ---- read_file_content ----

#[test]
fn read_file_content_from_disk() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    std::fs::write(&file, "hello world").unwrap();

    let mut pending = HashMap::new();
    let mut existed = HashSet::new();

    let content = read_file_content(&mut pending, &mut existed, &file).unwrap();
    assert_eq!(content, "hello world");
    assert!(existed.contains(&file));
    assert!(pending.contains_key(&file));
    // Original and current should both be "hello world".
    let (orig, cur) = &pending[&file];
    assert_eq!(orig, "hello world");
    assert_eq!(cur, "hello world");
}

#[test]
fn read_file_content_from_pending() {
    let path = PathBuf::from("/fake/already_loaded.txt");
    let mut pending = HashMap::new();
    pending.insert(
        path.clone(),
        ("original".to_string(), "modified".to_string()),
    );
    let mut existed = HashSet::new();

    let content = read_file_content(&mut pending, &mut existed, &path).unwrap();
    assert_eq!(content, "modified");
    // Should not add to existed_before since it was already in pending.
    assert!(!existed.contains(&path));
}

#[test]
fn read_file_content_missing_file_errors() {
    let mut pending = HashMap::new();
    let mut existed = HashSet::new();
    let path = PathBuf::from("/nonexistent/file.txt");

    let result = read_file_content(&mut pending, &mut existed, &path);
    result.expect_err("expected error");
}

// ---- read_and_probe ----

#[test]
fn read_and_probe_text_file() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("text.txt");
    std::fs::write(&file, "text content").unwrap();

    let mut pending = HashMap::new();
    let mut existed = HashSet::new();

    assert!(read_and_probe(&mut pending, &mut existed, &file).unwrap());
    assert!(pending.contains_key(&file));
}

#[test]
fn read_and_probe_binary_file() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("binary.bin");
    // Write bytes with NUL to trigger binary detection.
    std::fs::write(&file, b"\x00\x01\x02\x03").unwrap();

    let mut pending = HashMap::new();
    let mut existed = HashSet::new();

    assert!(!read_and_probe(&mut pending, &mut existed, &file).unwrap());
    assert!(!pending.contains_key(&file));
}

#[test]
fn read_and_probe_invalid_utf8_soft_skips() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("bad.txt");
    std::fs::write(&file, b"hello \xff world").unwrap();
    let mut pending = HashMap::new();
    let mut existed = HashSet::new();
    assert!(!read_and_probe(&mut pending, &mut existed, &file).unwrap());
    assert!(pending.is_empty());
}

#[test]
fn read_and_probe_missing_is_hard_err() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("missing.txt");
    let mut pending = HashMap::new();
    let mut existed = HashSet::new();
    let err = read_and_probe(&mut pending, &mut existed, &file).unwrap_err();
    assert!(
        err.to_string().contains("failed to read") || err.to_string().contains("missing"),
        "{err:#}"
    );
    // NotFound must remain classifiable through the chain (not a bare string).
    assert!(
        crate::exit::is_io_not_found(&err),
        "expected is_io_not_found, got: {err:#}"
    );
}

/// Strict sole-path load must refuse binary (not rewrite as text) (#1894).
#[test]
fn read_file_content_rejects_binary() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("binary.bin");
    std::fs::write(&file, b"hello\x00world").unwrap();

    let mut pending = HashMap::new();
    let mut existed = HashSet::new();

    let err = read_file_content(&mut pending, &mut existed, &file).unwrap_err();
    assert!(crate::exit::is_binary(&err), "{err:#}");
    assert!(err.to_string().contains("binary"), "{err}");
    assert!(pending.is_empty());
}

#[test]
fn read_file_content_rejects_invalid_utf8() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("bad.txt");
    std::fs::write(&file, b"hello \xff world").unwrap();

    let mut pending = HashMap::new();
    let mut existed = HashSet::new();

    let err = read_file_content(&mut pending, &mut existed, &file).unwrap_err();
    assert!(crate::exit::is_invalid_encoding(&err), "{err:#}");
    assert!(err.to_string().contains("UTF-8"), "{err}");
    assert!(pending.is_empty());
}

#[test]
fn read_and_probe_already_loaded_skips() {
    let path = PathBuf::from("/fake/loaded.txt");
    let mut pending = HashMap::new();
    pending.insert(path.clone(), ("orig".to_string(), "cur".to_string()));
    let mut existed = HashSet::new();

    assert!(read_and_probe(&mut pending, &mut existed, &path).unwrap());
}

// ---- update_file_content ----

#[test]
fn update_file_content_existing_entry() {
    let path = PathBuf::from("/fake/file.txt");
    let mut pending = HashMap::new();
    let mut deletions = HashSet::new();
    let mut write_targets = HashSet::new();
    pending.insert(path.clone(), ("original".to_string(), "old".to_string()));

    update_file_content(
        &mut pending,
        &mut deletions,
        &mut write_targets,
        &path,
        "new content".into(),
    );

    let (orig, cur) = &pending[&path];
    assert_eq!(orig, "original"); // original preserved
    assert_eq!(cur, "new content");
    assert!(write_targets.contains(&path));
}

#[test]
fn update_file_content_new_entry() {
    let path = PathBuf::from("/fake/new_file.txt");
    let mut pending = HashMap::new();
    let mut deletions = HashSet::new();
    let mut write_targets = HashSet::new();

    update_file_content(
        &mut pending,
        &mut deletions,
        &mut write_targets,
        &path,
        "content".into(),
    );

    let (orig, cur) = &pending[&path];
    assert!(orig.is_empty()); // no original for new files
    assert_eq!(cur, "content");
    assert!(write_targets.contains(&path));
}

#[test]
fn update_file_content_clears_deletion() {
    let path = PathBuf::from("/fake/file.txt");
    let mut pending = HashMap::new();
    let mut deletions = HashSet::new();
    let mut write_targets = HashSet::new();
    deletions.insert(path.clone());

    update_file_content(
        &mut pending,
        &mut deletions,
        &mut write_targets,
        &path,
        "revived".into(),
    );

    assert!(!deletions.contains(&path));
    assert!(write_targets.contains(&path));
}

// ---- path_err ----

#[test]
fn path_err_wraps_message() {
    let wrapper = path_err("config.yaml");
    let err = wrapper(anyhow::anyhow!("invalid key"));
    assert_eq!(err.to_string(), "config.yaml: invalid key");
}

#[test]
fn path_err_preserves_io_not_found() {
    let io_err: anyhow::Error = std::io::Error::new(std::io::ErrorKind::NotFound, "nope").into();
    let err = path_err("missing.json")(io_err.context("failed to read"));
    assert!(
        crate::exit::is_io_not_found(&err),
        "path_err must keep NotFound: {err:#}"
    );
}

#[test]
fn flush_doc_cache_keeps_invalid_input_for_ini_key() {
    let path = PathBuf::from("t.ini");
    let mut pending = HashMap::new();
    let mut deletions = HashSet::new();
    let mut write_targets = HashSet::new();
    let mut policy_finalized = HashSet::new();
    let cached = CachedDoc {
        original_text: "[db]\nport=1\na=1\n".into(),
        old_value: serde_json::json!({"db": {"port": "1", "a": "1"}}),
        value: serde_json::json!({"db": {"port": "1", "a": "1", "a=b": "c"}}),
        format: crate::ops::doc::FileFormat::Ini,
    };
    let err = flush_doc_cache_entry(
        &mut pending,
        &mut deletions,
        &mut write_targets,
        &mut policy_finalized,
        path,
        cached,
    )
    .unwrap_err();
    assert!(crate::exit::is_invalid_input(&err), "{err}");
    assert!(
        pending.is_empty(),
        "rejected key must not stage text: {pending:?}"
    );
}

// ---- op_needs_doc_flush ----

#[test]
fn op_needs_doc_flush_for_replace() {
    let op = Operation::Replace {
        path: Some("f.txt".into()),
        glob: None,
        regex: false,
        old: "a".into(),
        new_text: Some("b".into()),
        nth: None,
        insert_before: None,
        insert_after: None,
        case_insensitive: false,
        multiline: false,
        whole_line: false,
        word_boundary: false,
        range: None,
        before_context: None,
        after_context: None,
        if_exists: false,
        unique: false,
        require_change: false,
        command_position: false,
        fuzzy: false,
        min_fuzzy_score: None,
        allow_absent_old: false,
    };
    assert!(op_needs_doc_flush(&op));
}

#[test]
fn op_needs_doc_flush_false_for_doc_set() {
    let op = Operation::DocSet {
        path: "f.json".into(),
        selector: "key".into(),
        value: serde_json::json!("val"),
        if_exists: false,
    };
    assert!(!op_needs_doc_flush(&op));
}

#[test]
fn op_needs_doc_flush_for_read() {
    let op = Operation::Read {
        path: "f.txt".into(),
        lines: None,
        offset: None,
        limit: None,
        start_line: None,
        end_line: None,
    };
    assert!(op_needs_doc_flush(&op));
}

#[test]
fn op_needs_doc_flush_for_search() {
    let op = Operation::Search {
        path: "src".into(),
        pattern: "TODO".into(),
        regex: false,
        case_insensitive: false,
        multiline: false,
        invert_match: false,
        context: None,
        before_context: None,
        after_context: None,
        assert_count: None,
        literal: false,
        globs: Vec::new(),
        max_results: 0,
        exclude_patterns: Vec::new(),
        custom_ignore_filenames: Vec::new(),
    };
    assert!(op_needs_doc_flush(&op));
}

/// Regression: appending to a file deleted earlier in the same tx must
/// fail, not silently resurrect the file.
#[test]
fn file_append_to_deleted_file_errors() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("victim.txt");
    std::fs::write(&file, "original").unwrap();

    let mut f = TxStateFixture::new();
    // Simulate: file was loaded and then deleted in this tx.
    let _ = read_file_content(&mut f.pending, &mut f.existed_before, &file).unwrap();
    f.deletions.insert(file.clone());

    let mut tx = f.state(dir.path());

    let op = Operation::FileAppend {
        path: "victim.txt".into(),
        content: "new stuff".into(),
    };
    let result = execute_file_op(&op, &mut tx);
    assert!(
        result.is_err(),
        "append to deleted file should error, not resurrect"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("deleted earlier"),
        "error message should mention deletion: {msg}"
    );
}

/// Same regression for prepend.
#[test]
fn file_prepend_to_deleted_file_errors() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("victim.txt");
    std::fs::write(&file, "original").unwrap();

    let mut f = TxStateFixture::new();
    let _ = read_file_content(&mut f.pending, &mut f.existed_before, &file).unwrap();
    f.deletions.insert(file.clone());

    let mut tx = f.state(dir.path());

    let op = Operation::FilePrepend {
        path: "victim.txt".into(),
        content: "prefix".into(),
    };
    let result = execute_file_op(&op, &mut tx);
    assert!(
        result.is_err(),
        "prepend to deleted file should error, not resurrect"
    );
}

#[test]
fn file_append_rejects_whitespace_only() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("a.txt");
    std::fs::write(&file, "hello\n").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::FileAppend {
        path: "a.txt".into(),
        content: "   ".into(),
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_invalid_input(&err),
        "expected InvalidInputError, got: {err:#}"
    );
    assert!(
        err.to_string().contains("whitespace-only"),
        "message should name whitespace: {err}"
    );
    assert!(
        f.pending.is_empty(),
        "must not stage a write for whitespace-only append"
    );
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "hello\n");
}

#[test]
fn file_create_rejects_whitespace_only() {
    let dir = TempDir::new().unwrap();
    let dest = dir.path().join("a.txt");

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::FileCreate {
        path: "a.txt".into(),
        content: "   ".into(),
        force: None,
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_invalid_input(&err),
        "expected InvalidInputError, got: {err:#}"
    );
    assert!(
        err.to_string().contains("whitespace-only"),
        "message should name whitespace: {err}"
    );
    assert!(
        f.pending.is_empty(),
        "must not stage a write for whitespace-only create"
    );
    assert!(
        !dest.exists(),
        "dest file must not exist after failed create"
    );
}

#[test]
fn file_prepend_rejects_whitespace_only() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("a.txt");
    std::fs::write(&file, "hello\n").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::FilePrepend {
        path: "a.txt".into(),
        content: "\t".into(),
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(crate::exit::is_invalid_input(&err), "got: {err:#}");
    assert!(
        f.pending.is_empty(),
        "must not stage a write for whitespace-only prepend"
    );
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "hello\n");
}

/// append/prepend must not rewrite binary (NUL) files as text.
#[test]
fn file_append_rejects_binary_file() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("data.bin");
    std::fs::write(&file, b"hello\x00world").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::FileAppend {
        path: "data.bin".into(),
        content: "evil\n".into(),
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_binary(&err),
        "expected BinaryError, got: {err:#}"
    );
    assert!(
        err.to_string().contains("binary file"),
        "message should name binary: {err}"
    );
    assert!(
        f.pending.is_empty(),
        "must not stage a write for a binary append"
    );
    assert_eq!(std::fs::read(&file).unwrap(), b"hello\x00world");
}

#[test]
fn file_prepend_rejects_binary_file() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("data.bin");
    std::fs::write(&file, b"hello\x00world").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::FilePrepend {
        path: "data.bin".into(),
        content: "evil\n".into(),
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(crate::exit::is_binary(&err), "got: {err:#}");
    assert_eq!(std::fs::read(&file).unwrap(), b"hello\x00world");
}

/// Sole-path replace must refuse binary (NUL) files; MCP/tx used to rewrite them.
#[test]
fn replace_rejects_sole_binary_file() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("data.bin");
    std::fs::write(&file, b"hello\x00world").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::Replace {
        glob: None,
        path: Some("data.bin".into()),
        regex: false,
        old: "hello".into(),
        new_text: Some("HELLO".into()),
        nth: None,
        insert_before: None,
        insert_after: None,
        case_insensitive: false,
        multiline: false,
        if_exists: false,
        whole_line: false,
        range: None,
        word_boundary: false,
        before_context: None,
        after_context: None,
        unique: false,
        require_change: false,
        command_position: false,
        fuzzy: false,
        min_fuzzy_score: None,
        allow_absent_old: false,
    };
    let err = crate::tx::replace_op::execute_replace_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_binary(&err),
        "expected BinaryError, got: {err:#}"
    );
    assert!(
        err.to_string().contains("binary file"),
        "message should name binary: {err}"
    );
    assert!(
        f.pending.is_empty() && f.write_targets.is_empty(),
        "must not stage a write for binary replace"
    );
    assert_eq!(std::fs::read(&file).unwrap(), b"hello\x00world");
}

/// file.create through a path component that is a file must fail with
/// InvalidInputError before staging (no bare tempfile / false backup).
#[test]
fn file_create_rejects_parent_that_is_a_file() {
    let dir = TempDir::new().unwrap();
    let blocking = dir.path().join("notdir");
    std::fs::write(&blocking, "file\n").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::FileCreate {
        path: "notdir/child.txt".into(),
        content: "x\n".into(),
        force: None,
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_invalid_input(&err),
        "expected InvalidInputError, got: {err:#}"
    );
    assert!(
        err.to_string().contains("not a directory"),
        "message should name the problem: {err}"
    );
    assert!(
        f.pending.is_empty(),
        "must not stage a write when parent is not a directory"
    );
}

#[test]
fn md_move_section_same_file_by_path_equality() {
    // Regression: MdMoveSection with to=Some(same_path) must detect
    // same-file via path equality, not just canonicalize (which fails
    // for files created in-tx that don't exist on disk).
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("doc.md");
    std::fs::write(&file, "# A\ntext a\n# B\ntext b\n").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());

    let op = Operation::MdMoveSection {
        path: "doc.md".into(),
        heading: "# A".into(),
        to: Some("doc.md".into()),
        before: None,
        after: Some("# B".into()),
    };
    execute_operation(&op, &mut tx).unwrap();
    drop(tx);
    // Section A should appear after B, not be duplicated
    let content = &f.pending[&file].1;
    let a_pos = content.find("# A").unwrap();
    let b_pos = content.find("# B").unwrap();
    assert!(a_pos > b_pos, "section A should be after B: {content}");
    // Section A should appear exactly once
    assert_eq!(
        content.matches("# A").count(),
        1,
        "section A should not be duplicated: {content}"
    );
}

#[test]
fn rename_deleted_source_is_rejected() {
    // Regression: FileRename of a source file deleted earlier in the
    // same transaction should error, not silently create an empty file.
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("victim.txt");
    std::fs::write(&file, "content").unwrap();

    let mut f = TxStateFixture::new();
    // Simulate deletion
    f.pending
        .insert(file.clone(), ("content".to_string(), String::new()));
    f.deletions.insert(file);
    f.existed_before.insert(dir.path().join("victim.txt"));

    let mut tx = f.state(dir.path());

    let op = Operation::FileRename {
        from: "victim.txt".into(),
        to: "dest.txt".into(),
        force: false,
    };
    let result = execute_file_op(&op, &mut tx);
    assert!(result.is_err(), "rename of deleted file should error");
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("deleted earlier"),
        "error should mention deletion: {msg}"
    );
}

/// Case-only rename (readme.md → README.md) must stage `tx.renames` so commit
/// uses `fs::rename`. Without that, write-dest + delete-src removes the only
/// inode on case-insensitive filesystems (macOS APFS); agents hit this via
/// plan/MCP while CLI bypasses the engine (#1167).
#[test]
fn case_only_rename_records_tx_renames() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("readme.md");
    std::fs::write(&file, "hello content\n").unwrap();

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let op = Operation::FileRename {
        from: "readme.md".into(),
        to: "README.md".into(),
        force: false,
    };
    execute_file_op(&op, &mut tx).expect("case-only rename should stage");
    drop(tx);
    assert!(
        !f.renames.is_empty(),
        "case-only rename must record tx.renames for fs::rename; got empty"
    );
    assert_eq!(
        f.renames[0].0.file_name().and_then(|n| n.to_str()),
        Some("readme.md")
    );
    assert_eq!(
        f.renames[0].1.file_name().and_then(|n| n.to_str()),
        Some("README.md")
    );
}

/// End-to-end: plan/tx case-only rename must leave content on disk (not delete).
#[test]
fn case_only_rename_plan_apply_preserves_content() {
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("readme.md");
    std::fs::write(&src, "hello content\n").unwrap();

    let plan = crate::plan::Plan {
        version: crate::plan::SCHEMA_VERSION,
        cwd: None,
        operations: vec![Operation::FileRename {
            from: "readme.md".into(),
            to: "README.md".into(),
            force: false,
        }],
        write_policy: None,
        strict: None,
        format: None,
        validate: None,
        verify: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).expect("plan ok");
    assert!(
        report.ok,
        "case-only rename plan should succeed: {report:?}"
    );
    // Content must still exist under either spelling (case-insensitive FS).
    let content = std::fs::read_to_string(dir.path().join("README.md"))
        .or_else(|_| std::fs::read_to_string(&src))
        .expect("file must still exist after case-only rename");
    assert_eq!(content, "hello content\n");
}

/// On a case-sensitive volume, `Keep.txt` and `keep.txt` are two files.
/// Rename without force must be `already_exists`, not a case-only overwrite (#2473).
#[test]
fn case_sibling_rename_without_force_is_already_exists() {
    let dir = TempDir::new().unwrap();
    let keep = dir.path().join("Keep.txt");
    let lower = dir.path().join("keep.txt");
    std::fs::write(&keep, "KEEP\n").unwrap();
    if std::fs::write(&lower, "lower\n").is_err()
        || std::fs::read(&keep).ok().as_deref() != Some(b"KEEP\n".as_ref())
        || std::fs::read(&lower).ok().as_deref() != Some(b"lower\n".as_ref())
    {
        // Case-insensitive volume: the two names are one inode.
        let _ = std::fs::remove_file(&keep);
        let _ = std::fs::remove_file(&lower);
        return;
    }

    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let op = Operation::FileRename {
        from: "Keep.txt".into(),
        to: "keep.txt".into(),
        force: false,
    };
    let err = execute_file_op(&op, &mut tx).expect_err("must not overwrite case sibling");
    assert!(
        crate::exit::is_already_exists(&err),
        "expected already_exists, got: {err:#}"
    );
    assert_eq!(std::fs::read_to_string(&keep).unwrap(), "KEEP\n");
    assert_eq!(std::fs::read_to_string(&lower).unwrap(), "lower\n");
}

/// Binary delete + empty create must not pair as a rename (#2469).
#[test]
fn binary_delete_plus_empty_create_does_not_rename_bytes() {
    let dir = TempDir::new().unwrap();
    let png = dir.path().join("image.png");
    let notes = dir.path().join("notes.txt");
    let png_bytes: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\0\0\0\0\0";
    std::fs::write(&png, png_bytes).unwrap();

    let plan = crate::plan::Plan {
        version: crate::plan::SCHEMA_VERSION,
        cwd: None,
        operations: vec![
            Operation::FileDelete {
                path: "image.png".into(),
                if_exists: false,
            },
            Operation::FileCreate {
                path: "notes.txt".into(),
                content: String::new(),
                force: None,
            },
        ],
        write_policy: None,
        strict: None,
        format: None,
        validate: None,
        verify: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).expect("plan ok");
    assert!(report.ok, "plan should succeed: {report:?}");
    assert!(!png.exists(), "binary source should be deleted");
    let dest = std::fs::read(&notes).expect("empty dest should exist");
    assert!(
        dest.is_empty(),
        "empty create must stay empty, not inherit binary bytes: {dest:?}"
    );
}

/// Regression: files loaded for Read/Search operations should not be
/// modified by write policy (e.g. ensure_final_newline) (#1108).
#[test]
fn read_only_files_skip_write_policy() {
    let dir = TempDir::new().unwrap();
    // Create a file WITHOUT a trailing newline.
    let file = dir.path().join("readonly.txt");
    std::fs::write(&file, "no trailing newline").unwrap();

    // Build a plan that only reads the file, with ensure_final_newline active.
    let plan = Plan {
        version: crate::plan::SCHEMA_VERSION,
        operations: vec![Operation::Read {
            path: "readonly.txt".into(),
            lines: None,
            offset: None,
            limit: None,
            start_line: None,
            end_line: None,
        }],
        write_policy: Some(crate::write::WritePolicyOverride {
            ensure_final_newline: Some(true),
            ..Default::default()
        }),
        strict: None,
        format: None,
        validate: None,
        verify: None,
        cwd: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };

    let global = GlobalFlags {
        ensure_final_newline: true,
        ..GlobalFlags::default()
    };
    let ctx = crate::tx::context::EngineContext::from_global(&global, dir.path().to_path_buf());
    let result = execute_and_collect(&plan, &ctx, true, false, None).unwrap();

    // The file should NOT appear in changes since it was only read.
    assert!(
        result.changes.is_empty(),
        "read-only file should not be modified by write policy, got {} changes",
        result.changes.len()
    );
    // Verify the file on disk is unchanged.
    let on_disk = std::fs::read_to_string(&file).unwrap();
    assert_eq!(
        on_disk, "no trailing newline",
        "file on disk should be unchanged"
    );
}

#[test]
fn execute_and_collect_preserves_no_match_error_kind() {
    // Missing doc.update target must remain NoMatchError (exit 3 path), not
    // a plain anyhow operation_failed, even after op-label wrapping.
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("data.json");
    std::fs::write(&file, r#"{"a":1}"#).unwrap();

    let plan = Plan {
        version: crate::plan::SCHEMA_VERSION,
        operations: vec![Operation::DocUpdate {
            path: "data.json".into(),
            selector: "missing.key".into(),
            value: serde_json::json!(2),
        }],
        write_policy: None,
        strict: None,
        format: None,
        validate: None,
        verify: None,
        cwd: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };
    let ctx = crate::tx::context::EngineContext::from_global(
        &GlobalFlags::default(),
        dir.path().to_path_buf(),
    );
    match execute_and_collect(&plan, &ctx, true, false, None) {
        Ok(_) => panic!("expected NoMatch for missing selector"),
        Err(err) => {
            assert!(
                crate::exit::is_no_match(&err),
                "NoMatch must survive execute wrap: {err:#}"
            );
            let msg = err.to_string();
            assert!(
                msg.contains("doc.update")
                    || msg.contains("matched nothing")
                    || msg.contains("missing"),
                "detail should remain: {msg}"
            );
        }
    }
}

#[test]
fn execute_and_collect_doc_update_typo_includes_did_you_mean() {
    // Strict doc.update no-match must keep NoMatchError and name the selector
    // plus a whole-key sibling hint (write path parity with doc get).
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("data.json");
    std::fs::write(&file, r#"{"database":{"port":5432}}"#).unwrap();

    let plan = Plan {
        version: crate::plan::SCHEMA_VERSION,
        operations: vec![Operation::DocUpdate {
            path: "data.json".into(),
            selector: "databse".into(),
            value: serde_json::json!({"port": 1}),
        }],
        write_policy: None,
        strict: None,
        format: None,
        validate: None,
        verify: None,
        cwd: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };
    let ctx = crate::tx::context::EngineContext::from_global(
        &GlobalFlags::default(),
        dir.path().to_path_buf(),
    );
    match execute_and_collect(&plan, &ctx, true, false, None) {
        Ok(_) => panic!("expected NoMatch for typo selector"),
        Err(err) => {
            assert!(
                crate::exit::is_no_match(&err),
                "NoMatch must survive execute wrap: {err:#}"
            );
            let msg = err.to_string();
            assert!(
                msg.contains("databse"),
                "expected selector in doc.update miss, got: {msg}"
            );
            assert!(
                msg.contains("did you mean: database?"),
                "expected sibling-key hint, got: {msg}"
            );
        }
    }
}

/// rename a→b then create a: both paths must exist with correct content.
/// Stale tx.renames used to fs::rename a→b and skip writing resurrected a.
#[test]
fn rename_then_create_preserves_both_paths() {
    let dir = TempDir::new().unwrap();
    let a = dir.path().join("lib.rs");
    std::fs::write(&a, "old body\n").unwrap();

    let plan = crate::plan::Plan {
        version: crate::plan::SCHEMA_VERSION,
        cwd: None,
        operations: vec![
            Operation::FileRename {
                from: "lib.rs".into(),
                to: "lib_old.rs".into(),
                force: false,
            },
            Operation::FileCreate {
                path: "lib.rs".into(),
                content: "new body\n".into(),
                force: Some(false),
            },
        ],
        write_policy: None,
        strict: None,
        format: None,
        validate: None,
        verify: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).expect("plan ok");
    assert!(report.ok, "rename-then-create should succeed: {report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("lib.rs")).unwrap(),
        "new body\n",
        "resurrected source must keep create content"
    );
    assert_eq!(
        std::fs::read_to_string(dir.path().join("lib_old.rs")).unwrap(),
        "old body\n",
        "rename dest must keep original content"
    );
}

/// rename a→b then delete b: neither path should remain.
#[test]
fn rename_then_delete_dest_removes_both() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("a.txt"), "content\n").unwrap();

    let plan = crate::plan::Plan {
        version: crate::plan::SCHEMA_VERSION,
        cwd: None,
        operations: vec![
            Operation::FileRename {
                from: "a.txt".into(),
                to: "b.txt".into(),
                force: false,
            },
            Operation::FileDelete {
                path: "b.txt".into(),
                if_exists: false,
            },
        ],
        write_policy: None,
        strict: None,
        format: None,
        validate: None,
        verify: None,
        for_each: None,
        agent_preset: false,
        expected_sha256: None,
    };
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).expect("plan ok");
    assert!(
        report.ok,
        "rename-then-delete-dest should succeed: {report:?}"
    );
    assert!(!dir.path().join("a.txt").exists(), "source must be gone");
    assert!(
        !dir.path().join("b.txt").exists(),
        "dest delete must stick (stale rename must not re-create b)"
    );
}

#[cfg(unix)]
#[test]
fn append_dangling_symlink_is_invalid_input() {
    let dir = TempDir::new().unwrap();
    let link = dir.path().join("dangling.txt");
    std::os::unix::fs::symlink(dir.path().join("missing-target"), &link).unwrap();
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let op = Operation::FileAppend {
        path: "dangling.txt".into(),
        content: "x\n".into(),
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_invalid_input(&err),
        "dangling symlink append must be invalid_input not not_found, got: {err}"
    );
}

#[cfg(unix)]
#[test]
fn prepend_dangling_symlink_is_invalid_input() {
    let dir = TempDir::new().unwrap();
    let link = dir.path().join("dangling.txt");
    std::os::unix::fs::symlink(dir.path().join("missing-target"), &link).unwrap();
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let op = Operation::FilePrepend {
        path: "dangling.txt".into(),
        content: "x\n".into(),
    };
    let err = execute_file_op(&op, &mut tx).unwrap_err();
    assert!(
        crate::exit::is_invalid_input(&err),
        "dangling symlink prepend must be invalid_input not not_found, got: {err}"
    );
}

// ---- if_exists on file.delete / doc.set (#2231) ----

#[test]
fn file_delete_if_exists_missing_path_soft_skips() {
    let dir = TempDir::new().unwrap();
    let op = Operation::FileDelete {
        path: "missing.txt".into(),
        if_exists: true,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let count = execute_file_op(&op, &mut tx).expect("if_exists soft-skip");
    assert_eq!(count, 0);
    assert!(tx.deletions.is_empty(), "soft-skip must not stage a delete");
}

#[test]
fn file_delete_missing_path_without_if_exists_errors() {
    let dir = TempDir::new().unwrap();
    let op = Operation::FileDelete {
        path: "missing.txt".into(),
        if_exists: false,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let err = execute_file_op(&op, &mut tx).expect_err("missing without if_exists");
    assert!(
        crate::exit::is_io_not_found(&err),
        "expected NotFound, got: {err:#}"
    );
}

#[test]
fn path_present_for_if_exists_treats_deleted_as_absent() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("gone.txt");
    std::fs::write(&file, "x").unwrap();
    let mut f = TxStateFixture::new();
    f.deletions.insert(file.clone());
    let tx = f.state(dir.path());
    assert!(
        !tx.path_present_for_if_exists(&file),
        "deleted-in-tx must look absent"
    );
}

#[test]
fn path_present_for_if_exists_pending_without_disk() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("staged.txt");
    let mut f = TxStateFixture::new();
    f.pending.insert(file.clone(), (String::new(), "hi".into()));
    let tx = f.state(dir.path());
    assert!(
        tx.path_present_for_if_exists(&file),
        "pending create must look present"
    );
}

#[test]
fn file_delete_if_exists_still_deletes_when_present() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("gone.txt");
    std::fs::write(&file, "x\n").unwrap();
    let op = Operation::FileDelete {
        path: "gone.txt".into(),
        if_exists: true,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    execute_file_op(&op, &mut tx).expect("delete existing");
    assert!(
        tx.deletions.contains(&file),
        "existing file must still be staged for delete"
    );
}

#[test]
fn doc_set_if_exists_missing_file_soft_skips() {
    let dir = TempDir::new().unwrap();
    let op = Operation::DocSet {
        path: "missing.json".into(),
        selector: "k".into(),
        value: serde_json::json!(1),
        if_exists: true,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    execute_doc_op(&op, &mut tx).expect("if_exists soft-skip");
    assert!(
        tx.doc_cache.is_empty(),
        "missing file must not be parsed or written"
    );
}

#[test]
fn doc_set_if_exists_key_found_writes() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("c.json");
    std::fs::write(&file, r#"{"k":1}"#).unwrap();
    let op = Operation::DocSet {
        path: "c.json".into(),
        selector: "k".into(),
        value: serde_json::json!(2),
        if_exists: true,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    execute_doc_op(&op, &mut tx).expect("set existing key");
    let cached = tx
        .doc_cache
        .get(&file)
        .expect("existing file should be cached");
    assert_eq!(cached.value["k"], serde_json::json!(2));
}

#[test]
fn doc_set_if_exists_key_missing_does_not_create() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("c.json");
    std::fs::write(&file, r#"{"k":1}"#).unwrap();
    let op = Operation::DocSet {
        path: "c.json".into(),
        selector: "missing".into(),
        value: serde_json::json!(2),
        if_exists: true,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    execute_doc_op(&op, &mut tx).expect("if_exists key miss");
    let cached = tx
        .doc_cache
        .get(&file)
        .expect("file is loaded before the key check");
    assert_eq!(
        cached.value,
        serde_json::json!({"k": 1}),
        "if_exists must not create a missing key"
    );
}

#[test]
fn doc_set_missing_file_without_if_exists_errors() {
    let dir = TempDir::new().unwrap();
    let op = Operation::DocSet {
        path: "missing.json".into(),
        selector: "k".into(),
        value: serde_json::json!(1),
        if_exists: false,
    };
    let mut f = TxStateFixture::new();
    let mut tx = f.state(dir.path());
    let err = execute_doc_op(&op, &mut tx).expect_err("missing without if_exists");
    assert!(
        crate::exit::is_io_not_found(&err),
        "expected NotFound, got: {err:#}"
    );
}

fn apply_ops(dir: &std::path::Path, ops: serde_json::Value) -> crate::tx::TxOutput {
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "operations": ops
    }))
    .expect("plan json");
    crate::tx::execute_plan_direct(plan, dir, None).expect("plan returns output")
}

/// Delete dest then rename a binary source onto it. Commit must `fs::rename`
/// the bytes, not write the soft-empty snapshot (#2497).
#[test]
fn delete_then_rename_binary_source_keeps_bytes() {
    let dir = TempDir::new().unwrap();
    let src_bytes: &[u8] = b"\x00\x01\x02BIN";
    std::fs::write(dir.path().join("a.bin"), src_bytes).unwrap();
    std::fs::write(dir.path().join("b.bin"), b"old").unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.delete", "path": "b.bin"},
            {"op": "file.rename", "from": "a.bin", "to": "b.bin"}
        ]),
    );
    assert!(
        report.ok,
        "delete-then-rename binary should succeed: {report:?}"
    );
    assert!(
        !dir.path().join("a.bin").exists(),
        "source must be gone after rename"
    );
    let dest = std::fs::read(dir.path().join("b.bin")).expect("dest must exist");
    assert_eq!(
        dest, src_bytes,
        "dest must keep the original binary bytes, not a 0-byte rewrite"
    );
}

/// Same as binary: a symlink source must stay a symlink at dest (#2497).
#[cfg(unix)]
#[test]
fn delete_then_rename_symlink_source_keeps_link() {
    let dir = TempDir::new().unwrap();
    let target = dir.path().join("target.txt");
    std::fs::write(&target, "pointee\n").unwrap();
    std::os::unix::fs::symlink(&target, dir.path().join("a.link")).unwrap();
    std::fs::write(dir.path().join("b.link"), b"old").unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.delete", "path": "b.link"},
            {"op": "file.rename", "from": "a.link", "to": "b.link"}
        ]),
    );
    assert!(
        report.ok,
        "delete-then-rename symlink should succeed: {report:?}"
    );
    assert!(
        !dir.path().join("a.link").exists(),
        "source link must be gone"
    );
    let dest = dir.path().join("b.link");
    let meta = std::fs::symlink_metadata(&dest).expect("dest must exist");
    assert!(
        meta.file_type().is_symlink(),
        "dest must remain a symlink, not a 0-byte regular file"
    );
    assert_eq!(std::fs::read_to_string(&dest).unwrap(), "pointee\n");
}

/// Text delete-then-rename must move the inode (hardlinks stay with dest) (#2497).
#[cfg(unix)]
#[test]
fn delete_then_rename_text_source_preserves_hardlink() {
    use std::os::unix::fs::MetadataExt;
    let dir = TempDir::new().unwrap();
    let a = dir.path().join("a.txt");
    let sibling = dir.path().join("a_link.txt");
    std::fs::write(&a, "hello text\n").unwrap();
    std::fs::hard_link(&a, &sibling).unwrap();
    let before_ino = std::fs::metadata(&a).unwrap().ino();
    std::fs::write(dir.path().join("b.txt"), "old\n").unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.delete", "path": "b.txt"},
            {"op": "file.rename", "from": "a.txt", "to": "b.txt"}
        ]),
    );
    assert!(
        report.ok,
        "delete-then-rename text should succeed: {report:?}"
    );
    let dest = dir.path().join("b.txt");
    assert_eq!(std::fs::read_to_string(&dest).unwrap(), "hello text\n");
    assert_eq!(
        std::fs::metadata(&dest).unwrap().ino(),
        before_ino,
        "dest must keep the source inode so hardlink siblings stay shared"
    );
    assert_eq!(std::fs::read_to_string(&sibling).unwrap(), "hello text\n");
}

/// Rename a binary then create the source path. Dest must keep the original
/// bytes; dropping the rename pair used to commit dest as empty (#2498).
#[test]
fn rename_then_create_binary_source_keeps_dest_bytes() {
    let dir = TempDir::new().unwrap();
    let src_bytes: &[u8] = b"\x00\x01\x02BIN";
    std::fs::write(dir.path().join("a.bin"), src_bytes).unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.rename", "from": "a.bin", "to": "b.bin"},
            {"op": "file.create", "path": "a.bin", "content": "new a\n"}
        ]),
    );
    assert!(
        report.ok,
        "rename-then-create binary should succeed: {report:?}"
    );
    let dest = std::fs::read(dir.path().join("b.bin")).expect("dest must exist");
    assert_eq!(
        dest, src_bytes,
        "dest must keep the original binary bytes after source resurrection"
    );
    assert_eq!(
        std::fs::read_to_string(dir.path().join("a.bin")).unwrap(),
        "new a\n",
        "resurrected source must hold create content"
    );
}

/// Append on a renamed binary dest must refuse (not overwrite with text) (#2499).
#[test]
fn append_on_renamed_binary_dest_is_binary() {
    let dir = TempDir::new().unwrap();
    let src_bytes: &[u8] = b"\x00\x01\x02BIN";
    std::fs::write(dir.path().join("a.bin"), src_bytes).unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.rename", "from": "a.bin", "to": "b.bin"},
            {"op": "file.append", "path": "b.bin", "content": "hello\n"}
        ]),
    );
    assert!(!report.ok, "append on renamed binary must fail: {report:?}");
    assert_eq!(
        report.error_kind.as_deref(),
        Some("binary"),
        "expected binary error_kind, got {report:?}"
    );
    assert!(
        dir.path().join("a.bin").exists(),
        "failed plan must not apply the rename"
    );
    assert_eq!(std::fs::read(dir.path().join("a.bin")).unwrap(), src_bytes);
}

/// Replace on a renamed binary dest must refuse (#2499).
#[test]
fn replace_on_renamed_binary_dest_is_binary() {
    let dir = TempDir::new().unwrap();
    let src_bytes: &[u8] = b"\x00\x01\x02BIN";
    std::fs::write(dir.path().join("a.bin"), src_bytes).unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.rename", "from": "a.bin", "to": "b.bin"},
            {"op": "replace", "path": "b.bin", "old": "^", "new": "hello\n", "regex": true}
        ]),
    );
    assert!(
        !report.ok,
        "replace on renamed binary must fail: {report:?}"
    );
    assert_eq!(
        report.error_kind.as_deref(),
        Some("binary"),
        "expected binary error_kind, got {report:?}"
    );
    assert_eq!(std::fs::read(dir.path().join("a.bin")).unwrap(), src_bytes);
}

/// Patch on a renamed binary dest must refuse (#2499).
#[test]
fn patch_on_renamed_binary_dest_is_binary() {
    let dir = TempDir::new().unwrap();
    let src_bytes: &[u8] = b"\x00\x01\x02BIN";
    std::fs::write(dir.path().join("a.bin"), src_bytes).unwrap();
    let diff = "--- a/b.bin\n+++ b/b.bin\n@@ -0,0 +1 @@\n+hello\n";

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.rename", "from": "a.bin", "to": "b.bin"},
            {"op": "patch.apply", "diff": diff}
        ]),
    );
    assert!(!report.ok, "patch on renamed binary must fail: {report:?}");
    assert_eq!(
        report.error_kind.as_deref(),
        Some("binary"),
        "expected binary error_kind, got {report:?}"
    );
    assert_eq!(std::fs::read(dir.path().join("a.bin")).unwrap(), src_bytes);
}

/// Two-link chain (a->b->c) then delete c must not leave b on disk (#2500).
#[test]
fn delete_chained_rename_dest_two_link_removes_all() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("a.txt"), "AAA\n").unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.rename", "from": "a.txt", "to": "b.txt"},
            {"op": "file.rename", "from": "b.txt", "to": "c.txt"},
            {"op": "file.delete", "path": "c.txt"}
        ]),
    );
    assert!(report.ok, "two-link delete should succeed: {report:?}");
    for name in ["a.txt", "b.txt", "c.txt"] {
        assert!(
            !dir.path().join(name).exists(),
            "{name} must not remain after deleting the chain dest"
        );
    }
}

/// Three-link chain a->b->c->d then delete d must not leave intermediates (#2500).
#[test]
fn delete_chained_rename_dest_three_link_removes_all() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("a.txt"), "AAA\n").unwrap();

    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "file.rename", "from": "a.txt", "to": "b.txt"},
            {"op": "file.rename", "from": "b.txt", "to": "c.txt"},
            {"op": "file.rename", "from": "c.txt", "to": "d.txt"},
            {"op": "file.delete", "path": "d.txt"}
        ]),
    );
    assert!(report.ok, "three-link delete should succeed: {report:?}");
    for name in ["a.txt", "b.txt", "c.txt", "d.txt"] {
        assert!(
            !dir.path().join(name).exists(),
            "{name} must not remain after deleting the chain dest"
        );
    }
}

#[test]
fn read_returns_whole_file_sha256_and_offset_window() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("f.txt"), "a\nb\nc\nd\n").unwrap();
    let report = apply_ops(
        dir.path(),
        serde_json::json!([
            {"op": "read", "path": "f.txt", "offset": 2, "limit": 2}
        ]),
    );
    assert!(report.ok, "{report:?}");
    let read = report.reads.first().expect("read");
    assert_eq!(read.content, "b\nc");
    assert_eq!(read.start_line, 2);
    assert_eq!(read.sha256, crate::ops::read::sha256_hex(b"a\nb\nc\nd\n"));
}

#[test]
fn read_past_eof_is_no_matches() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("f.txt"), "a\nb\nc\nd\n").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "operations": [{"op": "read", "path": "f.txt", "offset": 99, "limit": 1}]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert_eq!(
        report.error_kind.as_deref(),
        Some("no_matches"),
        "{report:?}"
    );
    assert!(!report.ok, "{report:?}");
}

#[test]
fn expected_sha256_mismatch_is_stale_and_does_not_write() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("f.txt"), "hello\n").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "expected_sha256": {"f.txt": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
        "operations": [{"op": "replace", "path": "f.txt", "old": "hello", "new": "bye"}]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert_eq!(report.error_kind.as_deref(), Some("stale"), "{report:?}");
    assert!(!report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("f.txt")).unwrap(),
        "hello\n"
    );
}

#[test]
fn expected_sha256_glob_mismatch_is_stale_and_does_not_write() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("a.txt"), "hello\n").unwrap();
    std::fs::write(dir.path().join("b.txt"), "hello\n").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "expected_sha256": {"a.txt": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
        "operations": [{"op": "replace", "glob": "*.txt", "old": "hello", "new": "bye"}]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert_eq!(report.error_kind.as_deref(), Some("stale"), "{report:?}");
    assert!(!report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("a.txt")).unwrap(),
        "hello\n"
    );
    assert_eq!(
        std::fs::read_to_string(dir.path().join("b.txt")).unwrap(),
        "hello\n"
    );
}

#[test]
fn expected_sha256_tidy_dir_mismatch_is_stale_and_does_not_write() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("sub").join("a.txt");
    std::fs::create_dir_all(file.parent().unwrap()).unwrap();
    std::fs::write(&file, "hello \n").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "expected_sha256": {"sub/a.txt": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
        "operations": [{"op": "tidy.fix", "path": "sub"}]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert_eq!(report.error_kind.as_deref(), Some("stale"), "{report:?}");
    assert!(!report.applied, "{report:?}");
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "hello \n");
}

#[test]
fn tidy_fix_directory_includes_hidden_files() {
    let dir = TempDir::new().unwrap();
    let sub = dir.path().join("sub");
    std::fs::create_dir_all(sub.join(".git")).unwrap();
    std::fs::write(sub.join(".gitignore"), "foo").unwrap();
    std::fs::write(sub.join("keep.txt"), "ok\n").unwrap();
    std::fs::write(sub.join(".git").join("config"), "bare").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "operations": [{"op": "tidy.fix", "path": "sub"}]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert!(report.ok, "{report:?}");
    assert!(report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(sub.join(".gitignore")).unwrap(),
        "foo\n"
    );
    assert_eq!(
        std::fs::read_to_string(sub.join(".git").join("config")).unwrap(),
        "bare"
    );
}

#[test]
fn expected_sha256_second_edit_uses_pre_plan_bytes() {
    let dir = TempDir::new().unwrap();
    let body = "hello\nworld\n";
    std::fs::write(dir.path().join("f.txt"), body).unwrap();
    let hash = crate::ops::read::sha256_hex(body.as_bytes());
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "expected_sha256": {"f.txt": hash},
        "operations": [
            {"op": "replace", "path": "f.txt", "old": "hello", "new": "HELLO"},
            {"op": "replace", "path": "f.txt", "old": "world", "new": "WORLD"}
        ]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert!(report.ok, "{report:?}");
    assert!(report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("f.txt")).unwrap(),
        "HELLO\nWORLD\n"
    );
}

#[test]
fn expected_sha256_for_each_two_edits_uses_pre_plan_bytes() {
    let dir = TempDir::new().unwrap();
    let body = "hello\nworld\n";
    std::fs::create_dir(dir.path().join("fe")).unwrap();
    std::fs::write(dir.path().join("fe/a.txt"), body).unwrap();
    let hash = crate::ops::read::sha256_hex(body.as_bytes());
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "expected_sha256": {"fe/a.txt": hash},
        "for_each": {"glob": "fe/*.txt"},
        "operations": [
            {"op": "replace", "path": "{path}", "old": "hello", "new": "HELLO"},
            {"op": "replace", "path": "{path}", "old": "world", "new": "WORLD"}
        ]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert!(report.ok, "{report:?}");
    assert!(report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("fe/a.txt")).unwrap(),
        "HELLO\nWORLD\n"
    );
}

#[test]
fn agent_preset_rejects_a_second_match() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("f.txt"), "foo\nfoo\n").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "agent_preset": true,
        "operations": [{"op": "replace", "path": "f.txt", "old": "foo", "new": "bar"}]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert_eq!(
        report.error_kind.as_deref(),
        Some("ambiguous"),
        "{report:?}"
    );
    assert!(!report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("f.txt")).unwrap(),
        "foo\nfoo\n"
    );
}

#[test]
fn agent_preset_command_position_replaces_one_token() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("sh.txt"), "pip install\n").unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "agent_preset": true,
        "operations": [{
            "op": "replace",
            "path": "sh.txt",
            "old": "pip",
            "new": "uv",
            "command_position": true
        }]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert!(report.ok, "{report:?}");
    assert!(report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("sh.txt")).unwrap(),
        "uv install\n"
    );
}

#[test]
fn command_position_explicit_fuzzy_stays_invalid_input() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("sh.txt"), "pip install\n").unwrap();
    for preset in [false, true] {
        let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
            "version": 1,
            "agent_preset": preset,
            "operations": [{
                "op": "replace",
                "path": "sh.txt",
                "old": "pip",
                "new": "uv",
                "command_position": true,
                "fuzzy": true
            }]
        }))
        .unwrap();
        let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
        assert_eq!(
            report.error_kind.as_deref(),
            Some("invalid_input"),
            "preset={preset}: {report:?}"
        );
        assert!(
            report
                .error
                .as_deref()
                .unwrap_or("")
                .contains("command_position cannot be combined"),
            "preset={preset}: {report:?}"
        );
        assert_eq!(
            std::fs::read_to_string(dir.path().join("sh.txt")).unwrap(),
            "pip install\n"
        );
    }
}

const NOTEBOOK: &str = r#"{
 "cells": [
  {
   "cell_type": "code",
   "id": "load",
   "metadata": {},
   "outputs": [],
   "source": ["import pandas\n"]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5
}
"#;

#[test]
fn notebook_edit_replaces_cell_source() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("a.ipynb"), NOTEBOOK).unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "operations": [{
            "op": "notebook.edit",
            "path": "a.ipynb",
            "cell_id": "load",
            "source": "import pandas as pd\n"
        }]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert!(report.applied, "{report:?}");
    let text = std::fs::read_to_string(dir.path().join("a.ipynb")).unwrap();
    let v: serde_json::Value = serde_json::from_str(&text).unwrap();
    assert_eq!(v["cells"][0]["source"][0], "import pandas as pd\n");
    assert_eq!(v["nbformat"], 4);
}

#[test]
fn notebook_edit_missing_cell_is_no_matches() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("a.ipynb"), NOTEBOOK).unwrap();
    let plan: crate::plan::Plan = serde_json::from_value(serde_json::json!({
        "version": 1,
        "operations": [{
            "op": "notebook.edit",
            "path": "a.ipynb",
            "id": "missing",
            "source": "x\n"
        }]
    }))
    .unwrap();
    let report = crate::tx::execute_plan_direct(plan, dir.path(), None).unwrap();
    assert_eq!(
        report.error_kind.as_deref(),
        Some("no_matches"),
        "{report:?}"
    );
    assert!(!report.applied, "{report:?}");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("a.ipynb")).unwrap(),
        NOTEBOOK
    );
}

fn copy_diff(from: &str, to: &str) -> crate::plan::Operation {
    crate::plan::Operation::PatchApply {
        diff: format!(
            "diff --git a/{from} b/{to}\nsimilarity index 100%\ncopy from {from}\ncopy to {to}\n"
        ),
        on_stale: Default::default(),
        allow_conflicts: false,
        replace_all: false,
    }
}

#[test]
fn patch_apply_guard_rejects_copy_from_outside_the_workspace() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("inside.txt"), "kept\n").unwrap();
    let guard = crate::containment::PathGuard::builder(dir.path().to_path_buf())
        .build()
        .unwrap();
    let err = enforce_guard_for_op(&guard, &copy_diff("../secret.txt", "inside.txt"))
        .expect_err("copy source outside the workspace");
    let msg = err.to_string();
    assert!(
        msg.contains("secret.txt"),
        "guard must name the copy source, got {msg}"
    );
}

#[test]
fn patch_apply_guard_allows_copy_from_inside_the_workspace() {
    let dir = TempDir::new().unwrap();
    std::fs::write(dir.path().join("src.rs"), "fn a() {}\n").unwrap();
    std::fs::write(dir.path().join("dst.rs"), "fn a() {}\n").unwrap();
    let guard = crate::containment::PathGuard::builder(dir.path().to_path_buf())
        .build()
        .unwrap();
    enforce_guard_for_op(&guard, &copy_diff("src.rs", "dst.rs"))
        .expect("in-workspace copy source stays allowed");
}