toha 0.3.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
use super::*;
use crate::snapshot::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()
}

/// Build a snapshot ref whose files/ holds `files` (target-relative path, bytes),
/// with the given id and target. Origins are all toha for merge tests.
fn make_snapshot(dir: &Path, id: &str, target: &str, files: &[(&str, &[u8])]) {
    let index = dir.join(format!(".idx-{id}"));
    let _ = std::fs::remove_file(&index);
    let git_idx = |args: &[&str]| {
        let out = Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .env("GIT_INDEX_FILE", &index)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_AUTHOR_NAME", "U")
            .env("GIT_AUTHOR_EMAIL", "u@x.invalid")
            .env("GIT_COMMITTER_NAME", "U")
            .env("GIT_COMMITTER_EMAIL", "u@x.invalid")
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).trim().to_owned()
    };
    let paths_json: String = files
        .iter()
        .map(|(p, _)| format!("    \"{p}\": {{ \"origin\": \"toha\" }}"))
        .collect::<Vec<_>>()
        .join(",\n");
    let json = format!(
        "{{\n  \"snapshot\": 1,\n  \"id\": \"{id}\",\n  \"template\": \"forge:catalog/receipt@stable\",\n  \"source\": \"forge:catalog/receipt\",\n  \"commit\": \"8be0d41c2f0000000000000000000000000000a1\",\n  \"target\": \"{target}\",\n  \"created\": \"2026-09-30T04:12:00Z\",\n  \"generated\": \"2026-03-14T09:26:53+00:00[UTC]\",\n  \"project\": {{ \"commit\": \"a41c0de00000000000000000000000000000beef\", \"branch\": \"main\" }},\n  \"built_from\": null,\n  \"submissions\": [],\n  \"paths\": {{\n{paths_json}\n  }}\n}}"
    );
    let json_oid = hash_object(dir, json.as_bytes());
    git_idx(&[
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("100644,{json_oid},snapshot.json"),
    ]);
    for (p, bytes) in files {
        let oid = hash_object(dir, bytes);
        git_idx(&[
            "update-index",
            "--add",
            "--cacheinfo",
            &format!("100644,{oid},files/{p}"),
        ]);
    }
    let tree = git_idx(&["write-tree"]);
    let commit = git(dir, &["commit-tree", &tree, "-m", "snapshot"]);
    git(
        dir,
        &["update-ref", &format!("refs/toha/snapshots/{id}"), &commit],
    );
    let _ = std::fs::remove_file(&index);
}

fn open(dir: &Path, sub: &str) -> Project {
    let target = canonical_target(&dir.join(sub)).unwrap();
    Project::open(&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::Snapshot(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::Snapshot(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::Snapshot(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.contains(BASE_ID), "base ref preserved");
    assert!(
        !refs.contains(NEW_ID),
        "candidate ref removed on unsuccessful exit: {refs}"
    );
}

fn read_snapshot(project: &Project, id: &str) -> Snapshot {
    let sid: SnapshotId = id.parse().unwrap();
    project.find(&sid.to_string()).unwrap()
}

#[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::Snapshot(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::Snapshot(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::Snapshot(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_into_worktree(
        &project,
        &Base::Snapshot(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    super::inject_fail::disarm();
    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.contains(NEW_ID) && refs.contains(BASE_ID),
        "candidate ref removed, base preserved: {refs}"
    );
}

#[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::Snapshot(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::Snapshot(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.
fn occupied_scenario(root: &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"]);
    write(&root.join("app/added.txt"), b"operator's own\n"); // occupies the add path
    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")],
    );
}

const FOREIGN_ID: &str = "01JA2B8M4R0C7W1Y5F3H9K2S71";

#[test]
fn behavior_31_ref_map_unchanged_except_candidate_on_unsuccessful_exit() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    occupied_scenario(root);
    // A foreign snapshot of another source must survive the failed merge.
    make_snapshot(root, FOREIGN_ID, "app", &[("keep.txt", b"k\n")]);

    let before = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    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::Snapshot(base),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    );
    assert!(matches!(result, Err(MergeError::Occupied(_))));

    let after = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    // The candidate ref is gone; base and the foreign ref remain unchanged.
    assert!(
        before.contains(NEW_ID) && !after.contains(NEW_ID),
        "candidate removed"
    );
    assert!(after.contains(BASE_ID), "base preserved");
    assert!(after.contains(FOREIGN_ID), "foreign snapshot preserved");
    // Only the candidate line differs.
    let before_no_cand: Vec<&str> = before.lines().filter(|l| !l.contains(NEW_ID)).collect();
    assert_eq!(
        before_no_cand,
        after.lines().collect::<Vec<_>>(),
        "ref map unchanged except the candidate"
    );
}

#[test]
fn behavior_31_cleanup_preserves_a_ref_replaced_since_publication() {
    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"]);
    make_snapshot(root, NEW_ID, "app", &[("keep.txt", b"k\n")]);

    let project = open(root, "app");
    let id: SnapshotId = NEW_ID.parse().unwrap();
    let current = super::published_commit(&project, &id).unwrap();
    let unrelated = gix::ObjectId::from_hex(git(root, &["rev-parse", "HEAD"]).as_bytes()).unwrap();
    assert_ne!(current, unrelated, "the commits differ");

    // Cleanup with a stale "published" commit (a concurrent replacement) preserves the ref.
    super::remove_candidate(&project, &id, unrelated).unwrap();
    assert!(
        git(root, &["for-each-ref", "refs/toha/snapshots/"]).contains(NEW_ID),
        "a ref replaced since publication is preserved"
    );

    // Cleanup with the real published commit removes it.
    super::remove_candidate(&project, &id, current).unwrap();
    assert!(
        !git(root, &["for-each-ref", "refs/toha/snapshots/"]).contains(NEW_ID),
        "the exact candidate is removed"
    );
}

#[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::Snapshot(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.contains(NEW_ID) && refs.contains(BASE_ID),
        "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::snapshot::capture::CaptureInputs {
    use crate::snapshot::record::{CommitId, FrozenNow, ProjectPoint, Revision, Timestamp};
    crate::snapshot::capture::CaptureInputs {
        id: SnapshotId::from_parts(seed as u64, [seed; 10]),
        template: "forge:catalog/receipt@stable".to_owned(),
        revision: Revision::Commit(
            CommitId::parse("8be0d41c2f0000000000000000000000000000a1").unwrap(),
        ),
        generated: FrozenNow::parse("2026-03-14T09:26:53+00:00[UTC]").unwrap(),
        created: Timestamp::parse("2026-09-30T04:12:00Z").unwrap(),
        project: ProjectPoint::new(CommitId::parse(head).unwrap(), Some("main".to_owned())),
        submissions: vec![],
    }
}

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

fn snapshot_inputs() -> crate::snapshot::SnapshotInputs {
    use crate::snapshot::record::{CommitId, FrozenNow, Revision};
    crate::snapshot::SnapshotInputs {
        template: "forge:catalog/receipt@stable".to_owned(),
        revision: Revision::Commit(
            CommitId::parse("8be0d41c2f0000000000000000000000000000a1").unwrap(),
        ),
        generated: FrozenNow::parse("2026-03-14T09:26:53+00:00[UTC]").unwrap(),
        submissions: vec![],
    }
}

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 {
        files,
        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::Snapshot(base),
        plan,
        capture_inputs(&head),
        true,
        &runner,
    )
    .unwrap();

    // The new snapshot captured template v2's both.txt (built through the checkout).
    assert_eq!(
        git(
            root,
            &[
                "show",
                &format!("refs/toha/snapshots/{}:files/both.txt", new.id())
            ]
        ),
        "one\ntwo\nthree\nfour\nFIVE",
    );

    // 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::Snapshot(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::Snapshot(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();
    let new_id = *new.id();

    let before = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(
        before.contains(&new_id.to_string()) && before.contains(BASE_ID),
        "the candidate ref exists before the merge: {before}"
    );

    let result = merge_into_worktree(
        &project,
        &Base::Snapshot(read_snapshot(&project, BASE_ID)),
        &new,
        &MergeOptions {
            trusted: true,
            dry_run: false,
        },
    )
    .unwrap();

    // The reported snapshot equals the captured candidate.
    match &result {
        Merged::Written { snapshot, .. } => {
            assert_eq!(*snapshot, new_id, "the report names the committed snapshot")
        }
        other => panic!("expected a written update, got {other:?}"),
    }

    // Post-commit: the candidate ref is preserved (a successful exit never cleans
    // it up), alongside the base — no ref was lost by the successful commit.
    let after = git(root, &["for-each-ref", "refs/toha/snapshots/"]);
    assert!(
        after.contains(&new_id.to_string()),
        "the committed snapshot ref is preserved: {after}"
    );
    assert!(
        after.contains(BASE_ID),
        "the base ref is preserved: {after}"
    );

    // 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::Snapshot(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(),
        snapshot_inputs().generated.to_string()
    );
    // 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::Snapshot(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::Snapshot(read_snapshot(&project, BASE_ID)),
        plan,
        capture_inputs_id(&head, 7),
        false,
        &FailingRunner,
    )
    .unwrap();

    // The candidate's own captured tree carries the new render, not the base's
    // stale bytes: a dry run must still produce an accurate preview, it just
    // must not run the hook.
    let captured = git(
        root,
        &[
            "show",
            &format!("{SNAPSHOT_REF_PREFIX}{}:files/app.txt", new.id()),
        ],
    );
    assert_eq!(
        captured, "v2",
        "the candidate must capture the new render, not the base's v1"
    );

    let result = merge_into_worktree(
        &project,
        &Base::Snapshot(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"
    );
    // A dry run saves nothing: removing the candidate (as merge_apply does) leaves no ref.
    let published = super::published_commit(&project, new.id()).unwrap();
    super::remove_candidate(&project, new.id(), published).unwrap();
    assert!(!git(root, &["for-each-ref", "refs/toha/snapshots/"]).contains(&new.id().to_string()));
}

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::Snapshot(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.contains(BASE_ID), "base preserved");
    // Only the base ref exists (the candidate was never published).
    assert_eq!(refs.lines().count(), 1, "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);
}