toha 0.5.0

Generate projects and files from templates through one interview for people, scripts, agents, and Rust callers.
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
use super::*;
use crate::applied::{FrozenNow, Project};
use crate::staging::canonical_target;
use std::path::Path;
use std::process::Command;

fn git(repo: &Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(args)
        .env("GIT_AUTHOR_NAME", "Example User")
        .env("GIT_AUTHOR_EMAIL", "user@example.invalid")
        .env("GIT_COMMITTER_NAME", "Example User")
        .env("GIT_COMMITTER_EMAIL", "user@example.invalid")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .output()
        .expect("git runs");
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    if args.first() == Some(&"init") {
        git(repo, &["config", "core.autocrlf", "false"]);
    }
    String::from_utf8_lossy(&out.stdout).trim().to_owned()
}

fn write(path: &Path, content: &[u8]) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, content).unwrap();
}

fn hash_object(repo: &Path, bytes: &[u8]) -> String {
    use std::io::Write;
    let mut child = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["hash-object", "-w", "--stdin"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.take().unwrap().write_all(bytes).unwrap();
    String::from_utf8(child.wait_with_output().unwrap().stdout)
        .unwrap()
        .trim()
        .to_owned()
}

thread_local! { static APPLICATIONS: std::cell::RefCell<std::collections::BTreeMap<(std::path::PathBuf,String),Application>> = const { std::cell::RefCell::new(std::collections::BTreeMap::new()) }; }
fn make_snapshot(dir: &Path, id: &str, target: &str, files: &[(&str, &[u8])]) {
    let entries: Vec<_> = files
        .iter()
        .map(|(path, bytes)| (*path, *bytes, EntryKind::Blob))
        .collect();
    make_snapshot_entries(dir, id, target, &entries);
}

fn make_snapshot_entries(dir: &Path, id: &str, target: &str, files: &[(&str, &[u8], EntryKind)]) {
    let mut paths = Vec::new();
    let mut entries = std::collections::BTreeMap::new();
    for (path, bytes, kind) in files {
        let oid = gix::ObjectId::from_hex(hash_object(dir, bytes).as_bytes()).unwrap();
        paths.push(
            crate::applied::PathOwnership::new(
                crate::TargetPath::parse(path).unwrap(),
                Origin::Toha,
            )
            .with_blob(oid)
            .with_mode(*kind),
        );
        entries.insert((*path).to_owned(), (oid, *kind));
    }
    let mut application = Application::new(
        "forge:catalog/receipt@stable".into(),
        Revision::Commit(
            crate::applied::CommitId::parse("8be0d41c2f0000000000000000000000000000a1").unwrap(),
        ),
        RepoPath::parse(target).unwrap(),
        FrozenNow::parse("2026-03-14T09:26:53+00:00[UTC]").unwrap(),
        Default::default(),
        Default::default(),
        vec![],
        paths,
    );
    application.files = entries;
    APPLICATIONS.with(|apps| {
        apps.borrow_mut().insert(
            (
                dir.canonicalize().expect("canonical fixture repository"),
                id.to_owned(),
            ),
            application,
        )
    });
}
fn open(dir: &Path, sub: &str) -> Project {
    let target = canonical_target(&dir.join(sub)).unwrap();
    Project::open_isolated(&target).unwrap().unwrap()
}

const BASE_ID: &str = "01JA2B8M4R0C7W1Y5F3H9K2S6E";
const NEW_ID: &str = "01JA2B8M4R0C7W1Y5F3H9K2S6F";

#[test]
fn a_clean_three_way_merge_keeps_operator_and_template_lines() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    // Operator's committed state: line 1 edited by operator.
    write(&root.join("app/both.txt"), b"ONE\ntwo\nthree\nfour\nfive\n");
    write(&root.join("app/removed.txt"), b"bye\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);

    // Base = old template output; new = new template output (line 5 changed, removed.txt dropped, added.txt new).
    make_snapshot(
        root,
        BASE_ID,
        "app",
        &[
            ("both.txt", b"one\ntwo\nthree\nfour\nfive\n"),
            ("removed.txt", b"bye\n"),
        ],
    );
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[
            ("both.txt", b"one\ntwo\nthree\nfour\nFIVE\n"),
            ("added.txt", b"new\n"),
        ],
    );

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap();
    assert!(
        matches!(result, Merged::Written { .. }),
        "clean merge writes"
    );

    // Operator's line 1 and template's line 5 both survive; no conflict markers.
    let both = std::fs::read_to_string(root.join("app/both.txt")).unwrap();
    assert_eq!(
        both, "ONE\ntwo\nthree\nfour\nFIVE\n",
        "both edits merged: {both:?}"
    );
    // Template add present; operator's removed.txt deleted by the template.
    assert_eq!(
        std::fs::read_to_string(root.join("app/added.txt")).unwrap(),
        "new\n"
    );
    assert!(
        !root.join("app/removed.txt").exists(),
        "template removed an unedited file"
    );
    // git sees a normal (unconflicted) staged state.
    let status = git(root, &["status", "--porcelain"]);
    assert!(!status.contains("UU"), "no conflicts: {status}");
}

#[test]
fn a_template_removed_file_edited_by_the_operator_is_a_modify_delete_conflict() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/gone.txt"), b"bye\nuser edit\n"); // operator edited it
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);

    make_snapshot(root, BASE_ID, "app", &[("gone.txt", b"bye\n")]);
    make_snapshot(root, NEW_ID, "app", &[("keep.txt", b"k\n")]); // template dropped gone.txt

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap();

    // The operator's bytes stay on disk; git reports a delete/modify conflict.
    assert_eq!(
        std::fs::read_to_string(root.join("app/gone.txt")).unwrap(),
        "bye\nuser edit\n"
    );
    let status = git(root, &["status", "--porcelain"]);
    assert!(
        status.contains("gone.txt"),
        "gone.txt is unmerged: {status}"
    );
    let unmerged = git(root, &["ls-files", "-u"]);
    assert!(
        unmerged.contains("gone.txt"),
        "gone.txt has conflict stages: {unmerged}"
    );
}

#[test]
fn an_occupied_path_refuses_and_cleans_up_the_candidate_ref() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/keep.txt"), b"k\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    // An untracked file occupies the path the template adds.
    write(&root.join("app/added.txt"), b"operator's own\n");

    make_snapshot(root, BASE_ID, "app", &[("keep.txt", b"k\n")]);
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[("keep.txt", b"k\n"), ("added.txt", b"template\n")],
    );

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(
        matches!(result, Err(MergeError::Occupied(_))),
        "refuses the occupied path"
    );

    // The operator's file is untouched, and the candidate ref was removed (31).
    assert_eq!(
        std::fs::read_to_string(root.join("app/added.txt")).unwrap(),
        "operator's own\n"
    );
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(refs.is_empty(), "no refs are created");
    assert!(
        !refs.contains(NEW_ID),
        "candidate ref removed on unsuccessful exit: {refs}"
    );
}

fn read_snapshot(project: &Project, id: &str) -> Application {
    let root = project
        .repo()
        .workdir()
        .unwrap()
        .canonicalize()
        .expect("canonical fixture repository");
    APPLICATIONS.with(|apps| {
        apps.borrow()
            .get(&(root, id.to_owned()))
            .expect("fixture snapshot")
            .clone()
    })
}

#[test]
fn a_target_changed_since_the_start_refuses_with_nothing_written() {
    // Behavior 23: a drifted target fails the locked re-check; nothing is written
    // and the candidate ref is removed.
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/both.txt"), b"base\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);

    make_snapshot(root, BASE_ID, "app", &[("both.txt", b"base\n")]);
    make_snapshot(root, NEW_ID, "app", &[("both.txt", b"new-template\n")]);

    // The operator dirties the target after HEAD was recorded.
    write(&root.join("app/both.txt"), b"operator is editing\n");

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(
        matches!(result, Err(MergeError::Changed)),
        "refuses a changed target: {result:?}"
    );

    // Nothing was written and the candidate ref is gone.
    assert_eq!(
        std::fs::read_to_string(root.join("app/both.txt")).unwrap(),
        "operator is editing\n"
    );
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(!refs.contains(NEW_ID), "candidate ref removed on refusal");
}

#[test]
fn an_unrelated_dirty_file_in_the_target_fails_the_locked_re_check() {
    // Behavior 23, the re-check's UNIQUE job: the locked re-check refuses when the
    // target is dirty in a file the plan does not write. The per-file drift check
    // is scoped to written paths, so only the whole-target re-check catches this;
    // nothing is written.
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/both.txt"), b"base\n");
    write(&root.join("app/unrelated.txt"), b"committed\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    make_snapshot(
        root,
        BASE_ID,
        "app",
        &[("both.txt", b"base\n"), ("unrelated.txt", b"committed\n")],
    );
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[
            ("both.txt", b"new-template\n"),
            ("unrelated.txt", b"committed\n"),
        ],
    );

    // Dirty a file the update's plan does not touch. The per-file drift check for
    // both.txt would pass; only the whole-target re-check sees this.
    write(
        &root.join("app/unrelated.txt"),
        b"operator is editing unrelated\n",
    );

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(
        matches!(result, Err(MergeError::Changed)),
        "unrelated dirt fails the re-check: {result:?}"
    );
    // The plan target was not written and the candidate ref is removed.
    assert_eq!(
        std::fs::read_to_string(root.join("app/both.txt")).unwrap(),
        "base\n",
        "nothing written"
    );
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(!refs.contains(NEW_ID), "candidate ref removed on refusal");
}

#[test]
fn a_dirty_target_refuses_at_the_prewrite_recheck_and_writes_nothing() {
    // Behavior 23: an untracked path git does not ignore makes the target dirty,
    // so the locked re-check refuses with `Changed` before `write_all` runs —
    // nothing is written and no rollback is exercised. (Genuine rollback after a
    // real write is proved by the sibling
    // `a_failure_after_a_write_but_before_commit_rolls_the_transaction_back`.)
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/keep.txt"), b"k\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);

    // The template would add two files, but the operator has an untracked file at
    // `app/sub`, so the target is dirty before the update even plans a write.
    make_snapshot(root, BASE_ID, "app", &[("keep.txt", b"k\n")]);
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[
            ("keep.txt", b"k\n"),
            ("a.txt", b"added first\n"),
            ("sub/b.txt", b"needs a directory\n"),
        ],
    );
    // `app/sub` is an untracked file: the locked re-check sees the dirty target.
    write(&root.join("app/sub"), b"operator's file, not a directory\n");

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(
        matches!(result, Err(MergeError::Changed)),
        "the dirty target refuses at the locked re-check before any write: {result:?}"
    );

    // Nothing was written: the re-check refused before `write_all`, so the
    // template's first add never reached disk (not written, not rolled back).
    assert!(
        !root.join("app/a.txt").exists(),
        "nothing was written: a.txt never reached disk"
    );
    // The operator's file at app/sub is untouched.
    assert_eq!(
        std::fs::read_to_string(root.join("app/sub")).unwrap(),
        "operator's file, not a directory\n"
    );
    // The index was never written: keep.txt is the only tracked file, unstaged of a.txt.
    let staged = git(root, &["diff", "--cached", "--name-only"]);
    assert!(
        !staged.contains("a.txt"),
        "index unwritten, a.txt not staged: {staged}"
    );
    // The candidate ref is removed.
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(
        !refs.contains(NEW_ID),
        "candidate ref removed on the re-check refusal"
    );
}

#[test]
fn a_failure_after_a_write_but_before_commit_rolls_the_transaction_back() {
    // Behavior 24, isolating rollback itself: with a CLEAN tree the locked
    // re-check passes and the write transaction proceeds, so a failure injected
    // immediately after the first file is written (after done.push, before the
    // index is committed) must exercise rollback. We prove the write actually
    // happened, then that rollback restored the owned bytes, left the on-disk
    // index and outside-target entries untouched, and removed the candidate ref.
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/a.txt"), b"one\n");
    write(&root.join("app/b.txt"), b"one\n");
    write(&root.join("outside.txt"), b"outside\n"); // an entry outside the target
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let index_before = std::fs::read(root.join(".git/index")).unwrap();

    // Base = operator's committed content; new changes both files (both written).
    make_snapshot(
        root,
        BASE_ID,
        "app",
        &[("a.txt", b"one\n"), ("b.txt", b"one\n")],
    );
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[("a.txt", b"two\n"), ("b.txt", b"two\n")],
    );

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);

    // Fail after the first push: a.txt is written (BTreeMap order), then abort.
    super::inject_fail::arm(1);
    let result = merge_inner(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
        &[crate::TargetPath::parse("empty/nested").unwrap()],
    );
    super::inject_fail::disarm();
    assert!(!root.join("app/empty").exists());
    assert!(
        result.is_err(),
        "the injected transaction failure aborts: {result:?}"
    );

    // The raw on-disk index was never written by the aborted transaction — read
    // it BEFORE any git command (git status would refresh its stat cache). This
    // proves outside-target entries are intact byte-for-byte.
    assert_eq!(
        std::fs::read(root.join(".git/index")).unwrap(),
        index_before,
        "the on-disk index is unchanged (transaction never committed it)"
    );

    // The write ACTUALLY occurred: at the moment of failure a.txt held the
    // template bytes on disk (proving we reached write, not a pre-write refusal).
    let observed = super::inject_fail::observed();
    assert!(
        observed
            .iter()
            .any(|(p, b)| p == "app/a.txt" && b.as_deref() == Some(b"two\n".as_ref())),
        "a.txt was written before rollback: {observed:?}"
    );

    // Rollback restored the owned bytes: a.txt is back to HEAD, b.txt was never
    // reached, and the outside-target file is intact.
    assert_eq!(
        std::fs::read_to_string(root.join("app/a.txt")).unwrap(),
        "one\n",
        "a.txt restored to HEAD by rollback"
    );
    assert_eq!(
        std::fs::read_to_string(root.join("app/b.txt")).unwrap(),
        "one\n"
    );
    assert_eq!(
        std::fs::read_to_string(root.join("outside.txt")).unwrap(),
        "outside\n"
    );
    // Nothing is left modified — worktree is clean (index and worktree agree).
    let status = git(root, &["status", "--porcelain"]);
    assert!(
        status.is_empty(),
        "worktree clean after rollback: {status:?}"
    );

    // The candidate ref was cleaned up (ref-map restored to just the base).
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(
        refs.is_empty(),
        "candidate ref removed, base preserved: {refs}"
    );
}

#[test]
fn a_stop_during_the_write_loop_writes_no_later_file_and_rolls_back() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    for name in ["a.txt", "b.txt", "c.txt"] {
        write(&root.join("app").join(name), b"one\n");
    }
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let index_before = std::fs::read(root.join(".git/index")).unwrap();
    let files: [(&str, &[u8]); 3] = [
        ("a.txt", b"one\n"),
        ("b.txt", b"one\n"),
        ("c.txt", b"one\n"),
    ];
    make_snapshot(root, BASE_ID, "app", &files);
    let files: [(&str, &[u8]); 3] = [
        ("a.txt", b"two\n"),
        ("b.txt", b"two\n"),
        ("c.txt", b"two\n"),
    ];
    make_snapshot(root, NEW_ID, "app", &files);
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);

    // The caller's signal fires once a.txt is written (BTreeMap order).
    let signal = crate::stop::StopSignal::new();
    super::inject_fail::stop_after(1, signal.clone());
    let result = crate::stop::with_stop_signal(signal, || {
        merge_inner(
            &project,
            &Base::Application(base),
            &new,
            &MergeOptions {
                trusted: true,
                dry_run: false,
            },
            &[crate::TargetPath::parse("empty").unwrap()],
        )
    });
    let written = super::inject_fail::count();
    super::inject_fail::disarm();
    assert!(matches!(result, Err(MergeError::Stopped)), "{result:?}");
    assert_eq!(written, 1, "no path after a.txt was written");
    for name in ["a.txt", "b.txt", "c.txt"] {
        assert_eq!(
            std::fs::read_to_string(root.join("app").join(name)).unwrap(),
            "one\n",
            "{name} holds HEAD: a.txt restored, the others never written"
        );
    }
    assert!(!root.join("app/empty").exists());
    assert!(!root.join(".toha.json").exists(), "no applied record");
    assert_eq!(
        std::fs::read(root.join(".git/index")).unwrap(),
        index_before
    );
    assert!(git(root, &["status", "--porcelain"]).is_empty());
}

/// Fires the caller's stop signal while it runs the candidate's hook.
struct StoppingRunner(crate::stop::StopSignal);
impl crate::hook::HookRunner for StoppingRunner {
    fn run(
        &self,
        _hook: &crate::plan::PlannedHook,
        _target: &Path,
    ) -> Result<crate::hook::HookOutcome, crate::hook::HookError> {
        self.0.stop();
        Ok(crate::hook::HookOutcome {
            success: true,
            code: Some(0),
            stdout: None,
            stderr: None,
        })
    }
}

#[test]
fn a_stop_while_the_candidate_is_built_leaves_the_worktree_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/main.txt"), b"one\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let index_before = std::fs::read(root.join(".git/index")).unwrap();
    make_snapshot(root, BASE_ID, "app", &[("main.txt", b"one\n")]);
    let source = tempfile::tempdir().unwrap();
    write(
        &source.path().join("template.yml"),
        // The first hook fires the signal, so the candidate's apply stops
        // before the second.
        b"name: example\ninterview: []\nhooks:\n  - run: [tool]\n  - run: [tool]\n",
    );
    write(&source.path().join("template/main.txt"), b"two\n");
    let template = crate::template::Template::load(source.path()).unwrap();
    let seed = crate::interview::Seed {
        now: "2026-03-14T09:26:53+00:00[UTC]".parse().unwrap(),
        defaults: Default::default(),
        context: crate::context::InvocationContext::for_target(
            canonical_target(&root.join("app")).unwrap(),
        ),
    };
    let crate::interview::Interview::Complete(completed) =
        crate::interview::Interview::start(&template, seed).unwrap()
    else {
        panic!("the template has no questions");
    };
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let signal = crate::stop::StopSignal::new();
    let result = crate::stop::with_stop_signal(signal.clone(), || {
        merge_apply(
            &project,
            Base::Application(base),
            &template,
            &completed,
            snapshot_inputs(),
            MergeOptions {
                trusted: true,
                dry_run: false,
            },
            &StoppingRunner(signal.clone()),
        )
    });
    assert!(matches!(result, Err(MergeError::Stopped)), "{result:?}");
    assert_eq!(std::fs::read(root.join("app/main.txt")).unwrap(), b"one\n");
    assert!(!root.join(".toha.json").exists());
    assert_eq!(
        std::fs::read(root.join(".git/index")).unwrap(),
        index_before
    );
}

#[test]
fn the_write_index_drops_the_stale_cache_tree_extension() {
    // remove_tree() is required: gix-index writes the TREE (cache-tree) extension
    // as-is, so once the transaction replaces index entries the stale cache-tree
    // must be dropped — otherwise a later git operation trusts it and computes a
    // tree that disagrees with the working tree. Seed a populated cache-tree, run
    // the merge, and assert the on-disk TREE extension is gone, read via gix
    // BEFORE any git command could rebuild it.
    use gix::hash::Kind;
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/a.txt"), b"one\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    // Seed a populated cache-tree into the on-disk index.
    git(root, &["write-tree"]);
    let idx = root.join(".git/index");
    let seeded = gix::index::File::at(&idx, Kind::Sha1, false, Default::default()).unwrap();
    assert!(
        seeded.tree().is_some(),
        "the seeded index carries a populated cache-tree"
    );

    make_snapshot(root, BASE_ID, "app", &[("a.txt", b"one\n")]);
    make_snapshot(root, NEW_ID, "app", &[("a.txt", b"two\n")]);
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap();
    assert!(matches!(result, Merged::Written { .. }), "the merge writes");

    // Read the DISK index via gix, before any git command could rebuild the
    // cache-tree. The write transaction must have dropped the stale extension.
    let after = gix::index::File::at(&idx, Kind::Sha1, false, Default::default()).unwrap();
    assert!(
        after.tree().is_none(),
        "the write transaction dropped the stale cache-tree extension (remove_tree)"
    );
}

fn action_of(result: &Merged, path: &str) -> Option<Action> {
    if let Merged::Written { changes, .. } = result {
        changes
            .iter()
            .find(|c| c.path.as_str() == path)
            .map(|c| c.action)
    } else {
        None
    }
}

fn run_merge(root: &Path) -> Merged {
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap()
}

#[test]
fn an_add_add_conflict_keeps_operator_bytes_and_is_classified() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/keep.txt"), b"k\n");
    write(&root.join("app/conf.txt"), b"operator\n"); // operator added conf.txt
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);

    make_snapshot(root, BASE_ID, "app", &[("keep.txt", b"k\n")]); // base has no conf.txt
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[("keep.txt", b"k\n"), ("conf.txt", b"template\n")],
    );

    let result = run_merge(root);
    assert_eq!(
        action_of(&result, "app/conf.txt"),
        Some(Action::Conflicted(ConflictKind::AddAdd))
    );
    assert_eq!(
        std::fs::read_to_string(root.join("app/conf.txt")).unwrap(),
        "operator\n",
        "operator bytes kept"
    );
    assert!(
        git(root, &["ls-files", "-u"]).contains("conf.txt"),
        "conflict stages present"
    );
}

#[test]
fn a_modify_delete_conflict_is_classified() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/gone.txt"), b"bye\nuser edit\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    make_snapshot(root, BASE_ID, "app", &[("gone.txt", b"bye\n")]);
    make_snapshot(root, NEW_ID, "app", &[("keep.txt", b"k\n")]);

    let result = run_merge(root);
    assert_eq!(
        action_of(&result, "app/gone.txt"),
        Some(Action::Conflicted(ConflictKind::ModifyDelete))
    );
    assert_eq!(
        std::fs::read_to_string(root.join("app/gone.txt")).unwrap(),
        "bye\nuser edit\n"
    );
}

#[test]
fn a_binary_changed_on_both_sides_is_classified_and_keeps_operator_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/logo.bin"), b"\x89BIN\x00user\x00");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    make_snapshot(root, BASE_ID, "app", &[("logo.bin", b"\x89BIN\x00v1\x00")]);
    make_snapshot(root, NEW_ID, "app", &[("logo.bin", b"\x89BIN\x00v2\x00")]);

    let result = run_merge(root);
    assert_eq!(
        action_of(&result, "app/logo.bin"),
        Some(Action::Conflicted(ConflictKind::Binary))
    );
    assert_eq!(
        std::fs::read(root.join("app/logo.bin")).unwrap(),
        b"\x89BIN\x00user\x00",
        "operator bytes kept"
    );
    let unmerged = git(root, &["ls-files", "-u"]);
    assert!(
        unmerged.contains(" 1\tapp/logo.bin") && unmerged.contains(" 3\tapp/logo.bin"),
        "stages 1/2/3: {unmerged}"
    );
}

#[test]
fn a_file_replaced_by_a_directory_is_a_file_directory_conflict() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-b", "main", "-q"]);
    write(&root.join("app/item"), b"operator file\n"); // operator keeps it a file
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    make_snapshot(root, BASE_ID, "app", &[("item", b"base file\n")]);
    // The template turns `item` into a directory.
    make_snapshot(root, NEW_ID, "app", &[("item/sub.txt", b"now a dir\n")]);

    let result = run_merge(root);
    // `app/item` (the operator's file) is a file/directory conflict.
    assert_eq!(
        action_of(&result, "app/item"),
        Some(Action::Conflicted(ConflictKind::FileDirectory))
    );
    assert_eq!(
        std::fs::read_to_string(root.join("app/item")).unwrap(),
        "operator file\n",
        "operator file kept"
    );
}

#[test]
fn a_driver_attributed_path_is_a_driver_conflict_keeping_operator_bytes() {
    // Behavior 29 (merge side): a path whose attributes name a merge driver is
    // never merged; the operator's bytes stay and it becomes a driver conflict
    // with stages 1/2/3 — no driver program runs (drivers are stripped on open).
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    git(root, &["config", "merge.secret.driver", "false %O %A %B"]);
    write(&root.join(".gitattributes"), b"*.cf merge=secret\n");
    write(&root.join("app/conf.cf"), b"operator\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);

    make_snapshot(root, BASE_ID, "app", &[("conf.cf", b"base\n")]);
    make_snapshot(root, NEW_ID, "app", &[("conf.cf", b"template\n")]);

    let result = run_merge(root);
    assert_eq!(
        action_of(&result, "app/conf.cf"),
        Some(Action::Conflicted(ConflictKind::Driver)),
        "attributed path is a driver conflict"
    );
    assert_eq!(
        std::fs::read_to_string(root.join("app/conf.cf")).unwrap(),
        "operator\n",
        "operator bytes kept"
    );
    let unmerged = git(root, &["ls-files", "-u"]);
    assert!(
        unmerged.contains(" 1\tapp/conf.cf")
            && unmerged.contains(" 2\tapp/conf.cf")
            && unmerged.contains(" 3\tapp/conf.cf"),
        "stages 1/2/3 present: {unmerged}"
    );
}

/// Set up an occupied-path failure scenario with a base and new snapshot plus a
/// foreign third snapshot, returning the project ready to merge.
#[test]
fn behavior_31_a_held_index_lock_refuses_and_removes_the_candidate() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/both.txt"), b"base\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    make_snapshot(root, BASE_ID, "app", &[("both.txt", b"base\n")]);
    make_snapshot(root, NEW_ID, "app", &[("both.txt", b"template\n")]);

    // Another program holds the index lock.
    std::fs::write(root.join(".git/index.lock"), b"").unwrap();

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(result.is_err(), "a held index lock refuses: {result:?}");
    // Nothing written, candidate removed, base preserved, foreign lock untouched.
    assert_eq!(
        std::fs::read_to_string(root.join("app/both.txt")).unwrap(),
        "base\n"
    );
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(refs.is_empty(), "candidate removed, base preserved");
    assert!(
        root.join(".git/index.lock").exists(),
        "the foreign lock is left in place"
    );
}

// --------------------------------------------------------------------------
// The shared candidate-tree builder end to end (checkout -> apply -> capture -> merge).
// --------------------------------------------------------------------------

fn capture_inputs_id(_head: &str, _seed: u8) -> crate::applied::capture::CaptureInputs {
    crate::applied::capture::CaptureInputs {
        template: "forge:catalog/receipt@stable".to_owned(),
        revision: Revision::Commit(
            crate::applied::CommitId::parse("8be0d41c2f0000000000000000000000000000a1").unwrap(),
        ),
        generated: FrozenNow::parse("2026-03-14T09:26:53+00:00[UTC]").unwrap(),
        answers: Default::default(),
        context: Default::default(),
        parts: vec![],
    }
}

fn capture_inputs(head: &str) -> crate::applied::capture::CaptureInputs {
    capture_inputs_id(head, 9)
}

fn snapshot_inputs() -> crate::applied::RecordInputs {
    use crate::applied::record::{CommitId, Revision};
    crate::applied::RecordInputs {
        template: "forge:catalog/receipt@stable".to_owned(),
        revision: Revision::Commit(
            CommitId::parse("8be0d41c2f0000000000000000000000000000a1").unwrap(),
        ),
    }
}

fn plan_file(src_dir: &Path, path: &str, content: &str) -> crate::plan::PlannedFile {
    // Plan::apply reads the source file's metadata for the executable bit, so the
    // source must exist; a plain template file suffices.
    let source = src_dir.join(path);
    write(&source, content.as_bytes());
    crate::plan::PlannedFile {
        path: crate::plan::TargetPath::parse(path).unwrap(),
        content: crate::plan::Content::Rendered(content.to_owned()),
        source,
    }
}

fn plan_of(files: Vec<crate::plan::PlannedFile>) -> crate::plan::Plan {
    crate::plan::Plan {
        record: None,
        files,
        directories: vec![],
        edits: vec![],
        conflicts: vec![],
        hooks: vec![],
        before_apply: None,
        after_apply: None,
        result_seed: vec![],
        git: None,
    }
}

#[test]
fn the_candidate_builder_and_merge_apply_a_from_update_end_to_end() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    // Operator committed template v1 output, then edited line 1 of both.txt.
    write(&root.join("app/both.txt"), b"ONE\ntwo\nthree\nfour\nfive\n");
    write(&root.join("app/main.txt"), b"keep\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let head = git(root, &["rev-parse", "HEAD"]);

    // Base snapshot = template v1 output.
    make_snapshot(
        root,
        BASE_ID,
        "app",
        &[
            ("both.txt", b"one\ntwo\nthree\nfour\nfive\n"),
            ("main.txt", b"keep\n"),
        ],
    );

    // Template v2 changes line 5 of both.txt.
    let src = tempfile::tempdir().unwrap();
    let plan = plan_of(vec![
        plan_file(src.path(), "both.txt", "one\ntwo\nthree\nfour\nFIVE\n"),
        plan_file(src.path(), "main.txt", "keep\n"),
    ]);

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let runner = crate::hook::ProcessRunner;
    let new = super::build_candidate(
        &project,
        &Base::Application(base),
        plan,
        capture_inputs(&head),
        true,
        &runner,
    )
    .unwrap();

    assert_eq!(
        project
            .repo()
            .find_blob(new.files["both.txt"].0)
            .unwrap()
            .data,
        b"one\ntwo\nthree\nfour\nFIVE\n"
    );

    // Merge the update into the operator: line 1 (operator) and line 5 (template) both apply.
    let base2 = read_snapshot(&project, BASE_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base2),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap();
    assert!(matches!(result, Merged::Written { .. }));
    assert_eq!(
        std::fs::read_to_string(root.join("app/both.txt")).unwrap(),
        "ONE\ntwo\nthree\nfour\nFIVE\n",
        "operator's line 1 and template's line 5 both merged",
    );
}

#[test]
fn a_successful_update_preserves_the_committed_snapshot_ref_and_reports_it() {
    // Behavior 31, post-commit side: a successful write is NOT an unsuccessful
    // exit, so its candidate ref is preserved (not cleaned up), the reported
    // `Written.snapshot` equals the surviving ref, and the committed index tree
    // equals the working tree for the target (`git commit` succeeds cleanly).
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/both.txt"), b"ONE\ntwo\nthree\nfour\nfive\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let head = git(root, &["rev-parse", "HEAD"]);
    make_snapshot(
        root,
        BASE_ID,
        "app",
        &[("both.txt", b"one\ntwo\nthree\nfour\nfive\n")],
    );

    let src = tempfile::tempdir().unwrap();
    let project = open(root, "app");
    // Template v2 changes only line 5 — a clean merge with the operator's line 1.
    let new = super::build_candidate(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        plan_of(vec![plan_file(
            src.path(),
            "both.txt",
            "one\ntwo\nthree\nfour\nFIVE\n",
        )]),
        capture_inputs(&head),
        true,
        &crate::hook::ProcessRunner,
    )
    .unwrap();
    assert!(git(root, &["for-each-ref", "refs/toha/"]).is_empty());
    let result = merge_into_worktree(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap();

    assert!(matches!(result, Merged::Written { .. }));
    let record = project.read_record().unwrap();
    assert_eq!(record.applications()[0].to_value(), new.to_value());
    assert!(git(root, &["for-each-ref", "refs/toha/"]).is_empty());

    // The committed result is consistent: staging the merged worktree and
    // committing succeeds with no unmerged paths, and the merged bytes are on disk.
    assert_eq!(
        std::fs::read_to_string(root.join("app/both.txt")).unwrap(),
        "ONE\ntwo\nthree\nfour\nFIVE\n",
    );
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "apply update"]);
    let committed = git(root, &["show", "HEAD:app/both.txt"]);
    assert_eq!(
        committed, "ONE\ntwo\nthree\nfour\nFIVE",
        "the committed tree equals the merged working tree",
    );
}

#[test]
fn an_already_current_update_reports_no_change_and_carries_the_frozen_instant() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/app.txt"), b"v1\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let head = git(root, &["rev-parse", "HEAD"]);
    make_snapshot(root, BASE_ID, "app", &[("app.txt", b"v1\n")]);

    let project = open(root, "app");
    let src = tempfile::tempdir().unwrap();

    // A plan that reproduces the same content builds a snapshot equal to the base.
    let new = super::build_candidate(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        plan_of(vec![plan_file(src.path(), "app.txt", "v1\n")]),
        capture_inputs_id(&head, 5),
        true,
        &crate::hook::ProcessRunner,
    )
    .unwrap();

    // Behavior 16: the new snapshot carries the frozen `generated` instant.
    assert_eq!(
        new.generated().to_string(),
        "2026-03-14T09:26:53+00:00[UTC]"
    );
    // Behavior 15: it is already current.
    assert!(
        super::is_already_current(
            &project,
            &read_snapshot(&project, BASE_ID),
            &new,
            &snapshot_inputs()
        )
        .unwrap()
    );

    // A different (edited) template output is NOT already current.
    let src2 = tempfile::tempdir().unwrap();
    let new2 = super::build_candidate(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        plan_of(vec![plan_file(src2.path(), "app.txt", "v2\n")]),
        capture_inputs_id(&head, 6),
        true,
        &crate::hook::ProcessRunner,
    )
    .unwrap();
    assert!(
        !super::is_already_current(
            &project,
            &read_snapshot(&project, BASE_ID),
            &new2,
            &snapshot_inputs()
        )
        .unwrap()
    );
}

#[test]
fn a_dry_run_previews_the_change_and_saves_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/app.txt"), b"v1\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let head = git(root, &["rev-parse", "HEAD"]);
    make_snapshot(root, BASE_ID, "app", &[("app.txt", b"v1\n")]);

    let project = open(root, "app");
    let src = tempfile::tempdir().unwrap();
    // Behavior 20: a dry run runs NO hooks. The plan carries a hook that always
    // fails, and the runner would error if it were invoked — so building the
    // candidate with `run_hooks = false` must skip it and succeed. (If a dry run
    // ran the hook, build_candidate would return the hook's failure here.)
    let mut plan = plan_of(vec![plan_file(src.path(), "app.txt", "v2\n")]);
    plan.hooks.push(failing_hook());
    let new = super::build_candidate(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        plan,
        capture_inputs_id(&head, 7),
        false,
        &FailingRunner,
    )
    .unwrap();

    assert_eq!(
        project
            .repo()
            .find_blob(new.files["app.txt"].0)
            .unwrap()
            .data,
        b"v2\n"
    );

    let result = merge_into_worktree(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: true,
        },
    )
    .unwrap();
    assert!(
        matches!(result, Merged::Planned { .. }),
        "a dry run previews"
    );
    // The operator's working tree is untouched.
    assert_eq!(
        std::fs::read_to_string(root.join("app/app.txt")).unwrap(),
        "v1\n"
    );
    assert!(git(root, &["for-each-ref", "refs/toha/"]).is_empty());
    assert!(!root.join(".toha.json").exists());
}

struct FailingRunner;
impl crate::hook::HookRunner for FailingRunner {
    fn run(
        &self,
        _hook: &crate::plan::PlannedHook,
        _target: &Path,
    ) -> Result<crate::hook::HookOutcome, crate::hook::HookError> {
        Ok(crate::hook::HookOutcome {
            success: false,
            code: Some(1),
            stdout: None,
            stderr: None,
        })
    }
}

fn failing_hook() -> crate::plan::Planned<crate::plan::PlannedHook> {
    crate::plan::Planned::Ready(crate::plan::PlannedHook {
        program: crate::plan::PlannedProgram::Run(vec!["true".to_owned()]),
        cwd: None,
        template_root: std::path::PathBuf::new(),
        id: None,
        capture: crate::template::Capture::default(),
        allow_failure: false,
        parse_json: false,
        status_id: None,
    })
}

#[test]
fn a_hook_failure_leaves_the_project_unchanged_and_saves_no_ref() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/app.txt"), b"v1\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    let head = git(root, &["rev-parse", "HEAD"]);
    make_snapshot(root, BASE_ID, "app", &[("app.txt", b"v1\n")]);

    let project = open(root, "app");
    let src = tempfile::tempdir().unwrap();
    let mut plan = plan_of(vec![plan_file(src.path(), "app.txt", "v2\n")]);
    plan.hooks.push(failing_hook());

    // The hook fails in the throwaway checkout.
    let result = super::build_candidate(
        &project,
        &Base::Application(read_snapshot(&project, BASE_ID)),
        plan,
        capture_inputs_id(&head, 8),
        true,
        &FailingRunner,
    );
    assert!(
        result.is_err(),
        "a hook failure aborts the build: {result:?}"
    );

    // The operator's project is unchanged (only the throwaway checkout was touched),
    // and no new candidate ref was saved.
    assert_eq!(
        std::fs::read_to_string(root.join("app/app.txt")).unwrap(),
        "v1\n"
    );
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(refs.is_empty(), "no Toha refs");
    // Only the base ref exists (the candidate was never published).
    assert!(refs.is_empty(), "no candidate ref saved: {refs}");
}

#[test]
fn atomic_write_preserves_an_unrelated_temporary_filename() {
    let dir = tempfile::tempdir().unwrap();
    write(&dir.path().join("note.md"), b"old output");
    write(&dir.path().join("note.toha-tmp"), b"operator data");
    super::write_atomically(
        dir.path(),
        "note.md",
        b"new output",
        gix::index::entry::Mode::FILE,
    )
    .unwrap();
    assert_eq!(
        std::fs::read(dir.path().join("note.md")).unwrap(),
        b"new output"
    );
    assert_eq!(
        std::fs::read(dir.path().join("note.toha-tmp")).unwrap(),
        b"operator data"
    );
    assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2);
}

#[cfg(unix)]
#[test]
fn symlink_write_failures_restore_nodes_record_and_index() {
    // Cover retarget, addition and deletion, including dangling links. Fail only
    // after a real write, and retain an operator file outside the target.
    for operation in ["retarget", "add", "delete", "refused"] {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        git(root, &["init", "-q", "-b", "main"]);
        write(&root.join("app/z.txt"), b"before\n");
        write(&root.join("outside.txt"), b"operator\n");
        if operation != "add" {
            std::os::unix::fs::symlink("first", root.join("app/a.txt")).unwrap();
        }
        git(root, &["add", "."]);
        git(root, &["commit", "-qm", "example"]);
        let mut base_files = vec![("z.txt", b"before\n".as_slice(), EntryKind::Blob)];
        if operation != "add" {
            base_files.push(("a.txt", b"first", EntryKind::Link));
        }
        let mut new_files = if operation == "refused" {
            vec![("z.txt", b"invalid\0target".as_slice(), EntryKind::Link)]
        } else {
            vec![("z.txt", b"after\n".as_slice(), EntryKind::Blob)]
        };
        if operation != "delete" {
            new_files.push(("a.txt", b"second", EntryKind::Link));
        }
        make_snapshot_entries(root, BASE_ID, "app", &base_files);
        make_snapshot_entries(root, NEW_ID, "app", &new_files);
        let project = open(root, "app");
        let base = read_snapshot(&project, BASE_ID);
        let new = read_snapshot(&project, NEW_ID);
        project.write_application(base.clone()).unwrap();
        git(root, &["add", "."]);
        git(root, &["commit", "-qm", "record"]);
        let record_before = std::fs::read(root.join(".toha.json")).unwrap();
        let index_before = std::fs::read(root.join(".git/index")).unwrap();
        // Deletions run after writes, so fail after both z.txt and the deletion.
        if operation != "refused" {
            super::inject_fail::arm(if operation == "delete" { 2 } else { 1 });
        }
        let result = merge_into_worktree(
            &project,
            &Base::Application(base),
            &new,
            &MergeOptions {
                trusted: true,
                dry_run: false,
            },
        );
        super::inject_fail::disarm();
        if operation == "refused" {
            assert!(
                matches!(result, Err(MergeError::Io(ref message)) if !message.contains("injected")),
                "{result:?}"
            );
        } else {
            assert!(
                matches!(result, Err(MergeError::Io(ref message)) if message == "injected transaction failure after push"),
                "{operation}: {result:?}"
            );
            let observed = super::inject_fail::observed();
            assert!(
                observed.iter().any(|(path, bytes)| path == "app/a.txt"
                    && if operation == "delete" {
                        bytes.is_none()
                    } else {
                        bytes.as_deref() == Some(b"second")
                    }),
                "write/deletion reached: {operation}: {observed:?}"
            );
        }
        assert_eq!(
            std::fs::read(root.join(".git/index")).unwrap(),
            index_before,
            "{operation}"
        );
        assert_eq!(
            std::fs::read(root.join(".toha.json")).unwrap(),
            record_before,
            "{operation}"
        );
        if operation == "add" {
            assert!(std::fs::symlink_metadata(root.join("app/a.txt")).is_err());
        } else {
            assert_eq!(
                std::fs::read_link(root.join("app/a.txt")).unwrap(),
                Path::new("first"),
                "{operation}"
            );
        }
        assert_eq!(std::fs::read(root.join("app/z.txt")).unwrap(), b"before\n");
        assert_eq!(
            std::fs::read(root.join("outside.txt")).unwrap(),
            b"operator\n"
        );
        assert!(
            git(root, &["status", "--porcelain"]).is_empty(),
            "{operation}"
        );
    }
}

#[cfg(unix)]
#[test]
fn refused_symlink_creation_preserves_existing_operator_node() {
    let dir = tempfile::tempdir().unwrap();
    let full = dir.path().join("node");
    for link in [false, true] {
        if link {
            std::os::unix::fs::symlink("operator", &full).unwrap();
        } else {
            std::fs::write(&full, b"operator\n").unwrap();
        }
        let result = write_atomically(
            dir.path(),
            "node",
            b"invalid\0target",
            gix::index::entry::Mode::SYMLINK,
        );
        assert!(matches!(result, Err(MergeError::Io(_))), "{result:?}");
        if link {
            assert_eq!(std::fs::read_link(&full).unwrap(), Path::new("operator"));
        } else {
            assert_eq!(std::fs::read(&full).unwrap(), b"operator\n");
        }
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
        std::fs::remove_file(&full).unwrap();
    }
}

#[test]
fn symlink_blob_bytes_bypass_worktree_text_conversion() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join(".gitattributes"), b"link text eol=crlf\n");
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "example"]);
    let repo = gix::open_opts(root, gix::open::Options::isolated()).unwrap();
    let (mut pipeline, _) = repo.filter_pipeline(None).unwrap();
    let id = repo.write_blob(b"target\n").unwrap().detach();
    // Prove that this attribute would transform a regular file's bytes.
    assert_eq!(
        worktree_bytes(
            &repo,
            &mut pipeline,
            id,
            "link",
            gix::index::entry::Mode::FILE
        )
        .unwrap(),
        b"target\r\n"
    );
    assert_eq!(
        worktree_bytes(
            &repo,
            &mut pipeline,
            id,
            "link",
            gix::index::entry::Mode::SYMLINK
        )
        .unwrap(),
        b"target\n"
    );
}

#[cfg(unix)]
#[test]
fn a_dangling_operator_link_is_occupied_before_any_update_write() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join("app/keep.txt"), b"k\n");
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "operator"]);
    // An untracked file occupies the path the template adds.
    std::os::unix::fs::symlink("missing-operator-target", root.join("app/added.txt")).unwrap();

    make_snapshot(root, BASE_ID, "app", &[("keep.txt", b"k\n")]);
    make_snapshot(
        root,
        NEW_ID,
        "app",
        &[("keep.txt", b"k\n"), ("added.txt", b"template\n")],
    );

    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    let result = merge_into_worktree(
        &project,
        &Base::Application(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(
        matches!(result, Err(MergeError::Occupied(_))),
        "refuses the occupied path"
    );

    // The operator's file is untouched, and the candidate ref was removed (31).
    assert_eq!(
        std::fs::read_link(root.join("app/added.txt")).unwrap(),
        std::path::Path::new("missing-operator-target")
    );
    let refs = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(refs.is_empty(), "no refs are created");
    assert!(
        !refs.contains(NEW_ID),
        "candidate ref removed on unsuccessful exit: {refs}"
    );
}

#[cfg(unix)]
#[test]
fn snapshot_fixture_keys_follow_canonical_repository_identity() {
    let container = tempfile::tempdir().unwrap();
    let real = container.path().join("real");
    std::fs::create_dir(&real).unwrap();
    git(&real, &["init", "-q", "-b", "main"]);
    write(&real.join("seed.txt"), b"seed\n");
    git(&real, &["add", "."]);
    git(&real, &["commit", "-q", "-m", "seed"]);
    let alias = container.path().join("alias");
    std::os::unix::fs::symlink(&real, &alias).unwrap();
    make_snapshot(&alias, BASE_ID, "app", &[("note.txt", b"base\n")]);
    let project = open(&alias, "app");
    let application = read_snapshot(&project, BASE_ID);
    assert_eq!(application.target().as_str(), "app");
}

#[test]
fn normalized_application_identity_preserves_symlink_targets() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    git(root, &["config", "core.autocrlf", "true"]);
    write(&root.join(".gitattributes"), b"app/link text eol=crlf\n");
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "attributes"]);
    make_snapshot_entries(
        root,
        BASE_ID,
        "app",
        &[("link", b"target\n", EntryKind::Link)],
    );
    make_snapshot_entries(
        root,
        NEW_ID,
        "app",
        &[("link", b"target\r\n", EntryKind::Link)],
    );
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    assert_ne!(
        normalized_files(&project, &base).unwrap(),
        normalized_files(&project, &new).unwrap(),
        "link targets are byte identities even with text attributes"
    );
}

#[test]
fn an_already_current_normalized_update_writes_no_loose_objects() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(&root.join(".gitattributes"), b"app/app.txt text eol=lf\n");
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "attributes"]);
    // Both captured forms normalize to a third blob that is not in the
    // operator repository. Comparing them must not store that third blob.
    make_snapshot(root, BASE_ID, "app", &[("app.txt", b"one\r\ntwo\n")]);
    make_snapshot(root, NEW_ID, "app", &[("app.txt", b"one\ntwo\r\n")]);
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    let new = read_snapshot(&project, NEW_ID);
    assert_ne!(base.files, new.files);
    let normalized = gix::objs::compute_hash(
        project.repo().object_hash(),
        gix::objs::Kind::Blob,
        b"one\ntwo\n",
    )
    .unwrap();
    assert!(
        project
            .repo()
            .try_find_object(normalized)
            .unwrap()
            .is_none()
    );
    let before = git(root, &["count-objects", "-v"]);
    // This check is shared by dry-run and real updates before either merges.
    assert!(is_already_current(&project, &base, &new, &snapshot_inputs()).unwrap());
    assert_eq!(git(root, &["count-objects", "-v"]), before);
    assert!(
        project
            .repo()
            .try_find_object(normalized)
            .unwrap()
            .is_none()
    );
}

#[test]
fn merge_apply_keeps_an_already_current_normalized_update_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(
        &root.join(".gitattributes"),
        b"app/app.txt text=auto eol=lf\n",
    );
    write(&root.join("app/app.txt"), b"operator bytes\r\n");
    git(root, &["add", "."]);
    // Preserve a historical CRLF index entry. Auto-text capture respects this
    // entry, whereas normalized_files deliberately compares with an empty index.
    let operator_blob = hash_object(root, b"operator bytes\r\n");
    git(
        root,
        &[
            "update-index",
            "--cacheinfo",
            "100644",
            &operator_blob,
            "app/app.txt",
        ],
    );
    git(root, &["commit", "-qm", "operator"]);
    // The base and candidate have different captured bytes, but both normalize
    // to a third blob absent from the repository.
    make_snapshot(root, BASE_ID, "app", &[("app.txt", b"one\r\ntwo\n")]);
    git(root, &["config", "core.safecrlf", "true"]);
    let project = open(root, "app");
    assert_local_safecrlf(&project);
    let base = read_snapshot(&project, BASE_ID);
    project.write_application(base.clone()).unwrap();
    git(root, &["add", ".toha.json"]);
    git(root, &["commit", "-qm", "record"]);

    let source = tempfile::tempdir().unwrap();
    write(
        &source.path().join("template.yml"),
        b"name: example\ninterview: []\nstatic: ['**']\n",
    );
    let source_file = source.path().join("template/app.txt");
    write(&source_file, b"one\ntwo\r\n");
    let template = crate::template::Template::load(source.path()).unwrap();
    let seed = crate::interview::Seed {
        now: "2026-03-14T09:26:53+00:00[UTC]".parse().unwrap(),
        defaults: Default::default(),
        context: crate::context::InvocationContext::for_target(
            canonical_target(&root.join("app")).unwrap(),
        ),
    };
    let crate::interview::Interview::Complete(completed) =
        crate::interview::Interview::start(&template, seed).unwrap()
    else {
        panic!("the template has no questions");
    };
    let normalized = gix::objs::compute_hash(
        project.repo().object_hash(),
        gix::objs::Kind::Blob,
        b"one\ntwo\n",
    )
    .unwrap();
    assert!(
        project
            .repo()
            .try_find_object(normalized)
            .unwrap()
            .is_none()
    );
    let paths = [
        root.join("app/app.txt"),
        source_file,
        root.join(".gitattributes"),
        root.join(".toha.json"),
        root.join(".git/index"),
        root.join(".git/config"),
    ];
    let before = paths.each_ref().map(|path| std::fs::read(path).unwrap());
    let modes_before = paths
        .each_ref()
        .map(|path| std::fs::metadata(path).unwrap().permissions());
    let refs_before = git(root, &["for-each-ref"]);
    let staged_before = git(root, &["ls-files", "--stage"]);
    let lock = root.join(".git/index.lock");
    assert!(!lock.exists());

    for dry_run in [true, false] {
        let outcome = merge_apply(
            &project,
            Base::Application(base.clone()),
            &template,
            &completed,
            snapshot_inputs(),
            MergeOptions {
                trusted: true,
                dry_run,
            },
            &crate::hook::ProcessRunner,
        )
        .unwrap();

        assert!(matches!(outcome, Merged::AlreadyCurrent), "{outcome:?}");
        assert_eq!(git(root, &["for-each-ref"]), refs_before);
        assert_eq!(git(root, &["ls-files", "--stage"]), staged_before);
        for ((path, bytes), mode) in paths.iter().zip(&before).zip(&modes_before) {
            assert_eq!(
                std::fs::metadata(path).unwrap().permissions(),
                *mode,
                "{}",
                path.display()
            );
            assert_eq!(&std::fs::read(path).unwrap(), bytes, "{}", path.display());
        }
        assert!(!lock.exists(), "the index lock remains absent");
        assert_local_safecrlf(&project);
        // Candidate capture may write objects; only the comparison's normalized
        // blob must remain absent.
        assert!(
            project
                .repo()
                .try_find_object(normalized)
                .unwrap()
                .is_none()
        );
    }
}

fn assert_local_safecrlf(project: &Project) {
    let config = project.repo().config_snapshot();
    assert_eq!(config.boolean("core.safecrlf"), Some(true));
    let (_, section) = config
        .raw_values_with_sections_by("core", None::<&gix::bstr::BStr>, "safecrlf")
        .unwrap()
        .pop()
        .unwrap();
    assert_eq!(section.meta().source, gix::config::Source::Local);
    let options = gix::filter::Pipeline::options(project.repo()).unwrap();
    assert!(matches!(
        options.crlf_roundtrip_check,
        gix::filter::plumbing::pipeline::CrlfRoundTripCheck::Fail
    ));
    eprintln!("core.safecrlf: effective=true source=Local pipeline=Fail");
}

fn safecrlf_merge_fixture(reject: bool) {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    git(root, &["init", "-q", "-b", "main"]);
    write(
        &root.join(".gitattributes"),
        b"app/*.txt text=auto eol=lf\n",
    );
    let operator = b"ONE\r\ntwo\nthree\nfour\nfive\n";
    write(&root.join("app/app.txt"), operator);
    git(root, &["add", "."]);
    let operator_blob = hash_object(root, operator);
    git(
        root,
        &[
            "update-index",
            "--cacheinfo",
            "100644",
            &operator_blob,
            "app/app.txt",
        ],
    );
    git(root, &["commit", "-qm", "operator"]);
    make_snapshot(
        root,
        BASE_ID,
        "app",
        &[("app.txt", b"one\r\ntwo\nthree\nfour\nfive\n")],
    );
    let project = open(root, "app");
    let base = read_snapshot(&project, BASE_ID);
    project.write_application(base.clone()).unwrap();
    git(root, &["add", ".toha.json"]);
    git(root, &["commit", "-qm", "record"]);
    git(root, &["config", "core.safecrlf", "true"]);
    let project = open(root, "app");
    assert_local_safecrlf(&project);

    let source = tempfile::tempdir().unwrap();
    write(
        &source.path().join("template.yml"),
        b"name: example\ninterview: []\nstatic: ['**']\n",
    );
    let source_file = source.path().join("template/app.txt");
    write(&source_file, b"one\ntwo\r\nthree\nfour\nFIVE\n");
    // This new path has no historical CRLF index entry. Capture must still
    // enforce safecrlf on its actual admission, before any merge takes place.
    if reject {
        write(&source.path().join("template/new.txt"), b"new\r\n");
    }
    let template = crate::template::Template::load(source.path()).unwrap();
    let seed = crate::interview::Seed {
        now: "2026-03-14T09:26:53+00:00[UTC]".parse().unwrap(),
        defaults: Default::default(),
        context: crate::context::InvocationContext::for_target(
            canonical_target(&root.join("app")).unwrap(),
        ),
    };
    let crate::interview::Interview::Complete(completed) =
        crate::interview::Interview::start(&template, seed).unwrap()
    else {
        panic!("the template has no questions");
    };
    let mut paths = vec![
        root.join("app/app.txt"),
        root.join(".toha.json"),
        root.join(".git/index"),
        root.join(".git/config"),
        source_file,
        root.join(".gitattributes"),
        source.path().join("template.yml"),
    ];
    if reject {
        paths.push(source.path().join("template/new.txt"));
    }
    let before = paths
        .iter()
        .map(|path| std::fs::read(path).unwrap())
        .collect::<Vec<_>>();
    let modes = paths
        .iter()
        .map(|path| std::fs::metadata(path).unwrap().permissions())
        .collect::<Vec<_>>();
    let refs = git(root, &["for-each-ref"]);
    let staged = git(root, &["ls-files", "--stage"]);
    assert!(!root.join(".git/index.lock").exists());
    let result = merge_apply(
        &project,
        Base::Application(base),
        &template,
        &completed,
        snapshot_inputs(),
        MergeOptions {
            trusted: true,
            dry_run: false,
        },
        &crate::hook::ProcessRunner,
    );
    if reject {
        let error = result.unwrap_err().to_string();
        assert!(error.contains("CRLF would be replaced by LF"), "{error}");
        assert!(error.contains("app/new.txt"), "{error}");
        eprintln!("candidate admission refused: {error}");
        for ((path, bytes), mode) in paths.iter().zip(before).zip(modes) {
            assert_eq!(std::fs::read(path).unwrap(), bytes, "{}", path.display());
            assert_eq!(std::fs::metadata(path).unwrap().permissions(), mode);
        }
        assert!(!root.join("app/new.txt").exists());
        assert_eq!(git(root, &["ls-files", "--stage"]), staged);
    } else {
        let outcome = result.unwrap();
        assert!(
            matches!(outcome, Merged::Written { ref conflicted, .. } if conflicted.is_empty()),
            "{outcome:?}"
        );
        assert_eq!(
            std::fs::read(root.join("app/app.txt")).unwrap(),
            b"ONE\ntwo\nthree\nfour\nFIVE\n"
        );
        assert_eq!(
            git(root, &["show", ":app/app.txt"]),
            "ONE\ntwo\nthree\nfour\nFIVE"
        );
        assert_ne!(std::fs::read(root.join(".toha.json")).unwrap(), before[1]);
        assert_eq!(std::fs::read(&paths[3]).unwrap(), before[3]);
        assert_eq!(std::fs::read(&paths[4]).unwrap(), before[4]);
    }
    assert_eq!(git(root, &["for-each-ref"]), refs);
    assert!(!root.join(".git/index.lock").exists());
    assert_local_safecrlf(&project);
}

#[test]
fn safecrlf_allows_a_real_merge_of_historical_crlf_inputs() {
    safecrlf_merge_fixture(false);
}

#[test]
fn safecrlf_still_rejects_candidate_admission_without_changing_operator_state() {
    safecrlf_merge_fixture(true);
}

#[test]
fn directory_rollback_preserves_existing_and_concurrent_contents() {
    let root = tempfile::tempdir().unwrap();
    std::fs::create_dir(root.path().join("existing")).unwrap();
    {
        let mut created = CreatedDirectories::default();
        created
            .create(
                root.path(),
                &crate::TargetPath::parse("existing/empty").unwrap(),
            )
            .unwrap();
        created
            .create(
                root.path(),
                &crate::TargetPath::parse("new/nested").unwrap(),
            )
            .unwrap();
        std::fs::write(root.path().join("new/nested/concurrent.txt"), "keep").unwrap();
    }
    assert!(root.path().join("existing").is_dir());
    assert!(!root.path().join("existing/empty").exists());
    assert_eq!(
        std::fs::read_to_string(root.path().join("new/nested/concurrent.txt")).unwrap(),
        "keep"
    );
}