git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
use crate::core::repo;
use crate::core::test_helpers::TestRepo;
use crate::core::weave::Weave;

// ── Case 1: File(s) + Commit (Amend) ────────────────────────────────────

#[test]
fn fold_file_into_head() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Modify a file without committing
    test_repo.write_file("file1.txt", "modified content");

    let head_oid = test_repo.head_oid();

    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["file1.txt".to_string()],
        &head_oid.to_string(),
        false,
    );

    assert!(
        result.is_ok(),
        "fold_files_into_commit failed: {:?}",
        result
    );

    // HEAD should have been amended (same message, different hash)
    assert_eq!(test_repo.get_message(0), "Second commit");
    assert_ne!(test_repo.head_oid(), head_oid, "Hash should have changed");

    // The file content should be in the commit now
    assert_eq!(test_repo.read_file("file1.txt"), "modified content");
}

#[test]
fn fold_multiple_files_into_head() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");

    // Modify multiple files
    test_repo.write_file("file1.txt", "modified 1");
    test_repo.write_file("new_file.txt", "new content");

    let head_oid = test_repo.head_oid();

    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["file1.txt".to_string(), "new_file.txt".to_string()],
        &head_oid.to_string(),
        false,
    );

    assert!(result.is_ok(), "fold failed: {:?}", result);
    assert_eq!(test_repo.get_message(0), "First commit");
    assert_eq!(test_repo.read_file("file1.txt"), "modified 1");
    assert_eq!(test_repo.read_file("new_file.txt"), "new content");
}

#[test]
fn fold_file_into_non_head_commit() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Modify file1.txt (which was introduced in first commit)
    test_repo.write_file("file1.txt", "amended content");

    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["file1.txt".to_string()],
        &c1_oid.to_string(),
        false,
    );

    assert!(
        result.is_ok(),
        "fold_files_into_commit failed: {:?}",
        result
    );

    // Messages should be preserved
    assert_eq!(test_repo.get_message(0), "Second commit");
    assert_eq!(test_repo.get_message(1), "First commit");

    // The first commit's hash should have changed
    assert_ne!(test_repo.get_oid(1), c1_oid);
}

#[test]
fn fold_file_no_changes_fails() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");

    let head_oid = test_repo.head_oid();

    // file1.txt has no uncommitted changes
    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["file1.txt".to_string()],
        &head_oid.to_string(),
        false,
    );

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("no changes"));
}

#[test]
fn fold_file_into_non_head_with_other_changes_autostashed() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Modify two files but only fold one
    test_repo.write_file("file1.txt", "change 1");
    test_repo.write_file("file2.txt", "change 2");

    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["file1.txt".to_string()],
        &c1_oid.to_string(),
        false,
    );

    assert!(
        result.is_ok(),
        "fold should succeed with autostash: {:?}",
        result
    );

    // Other dirty file should be preserved after autostash
    assert_eq!(test_repo.read_file("file2.txt"), "change 2");
}

/// Bug: folding a file into a woven branch commit (non-HEAD) where both the
/// commit and working-tree modify the same file would leave unmerged paths.
/// The autostash would pop stale changes that conflict with rewritten history.
#[test]
fn fold_file_into_woven_branch_commit() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature branch with a commit that modifies feature1
    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.write_file("feature1", "initial feature content");
    test_repo.stage_files(&["feature1"]);
    test_repo.commit_staged("Feature 1");
    let feat1_oid = test_repo.head_oid();

    // Merge feat1 into integration branch
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feat1");

    // Modify feature1 in the working tree (same file as the commit)
    test_repo.write_file("feature1", "updated feature content");

    // Fold the working-tree changes into the feat1 commit
    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["feature1".to_string()],
        &feat1_oid.to_string(),
        false,
    );

    assert!(
        result.is_ok(),
        "fold_files_into_commit (woven branch) failed: {:?}",
        result
    );

    // The feat1 commit should have been rewritten
    let feat1_new_tip = test_repo.get_branch_target("feat1");
    assert_ne!(feat1_new_tip, feat1_oid, "feat1 should have been rewritten");

    // The file should have the updated content (now in the commit)
    assert_eq!(test_repo.read_file("feature1"), "updated feature content");

    // There should be no unmerged paths
    let status_output = test_repo.status_porcelain();
    assert!(
        !status_output.contains("UU") && !status_output.contains("AA"),
        "Working tree should have no merge conflicts, but status shows:\n{}",
        status_output
    );
}

// ── Case 1b: fold -p (skip_staging=true) — hunk-level precision ─────────

/// Read the content of a file from a specific commit tree.
fn read_file_from_commit(repo: &git2::Repository, commit_oid: git2::Oid, path: &str) -> String {
    let commit = repo.find_commit(commit_oid).unwrap();
    let tree = commit.tree().unwrap();
    let entry = tree.get_path(std::path::Path::new(path)).unwrap();
    let blob = repo.find_blob(entry.id()).unwrap();
    std::str::from_utf8(blob.content()).unwrap().to_string()
}

/// Regression test: `fold -p <commit>` must fold only staged hunks, not entire files.
///
/// Before the fix, `fold_files_into_commit` called `git stage_files` which
/// re-staged the whole file, overwriting the hunk-level staging set by
/// `apply_selections`.  With `skip_staging = true` the precise staging must be
/// preserved.
#[test]
fn fold_patch_only_staged_hunk_is_folded_into_head() {
    let test_repo = TestRepo::new();

    // Initial file with enough gap between sections to produce two hunks.
    let initial = "line 1\nline 2\nline 3\nline 4\nline 5\n\
                   line 6\nline 7\nline 8\nline 9\nline 10\n\
                   line 11\nline 12\nline 13\nline 14\nline 15\n";
    test_repo.write_file("file.txt", initial);
    test_repo.stage_files(&["file.txt"]);
    test_repo.commit_staged("initial");

    // Modify two distant regions — produces two separate hunks.
    let modified = "line 1\nMODIFIED TOP\nline 3\nline 4\nline 5\n\
                    line 6\nline 7\nline 8\nline 9\nline 10\n\
                    line 11\nline 12\nline 13\nMODIFIED BOTTOM\nline 15\n";
    test_repo.write_file("file.txt", modified);

    // Stage only the first hunk (top change) by applying a patch to the index.
    let first_hunk_patch = "--- a/file.txt\n+++ b/file.txt\n\
                             @@ -1,5 +1,5 @@\n line 1\n-line 2\n+MODIFIED TOP\n \
                             line 3\n line 4\n line 5\n";
    let workdir = test_repo.workdir();
    crate::git::apply_cached_patch(workdir.as_path(), first_hunk_patch).unwrap();

    let head_oid = test_repo.head_oid();
    let staged = crate::core::repo::get_staged_files(&test_repo.repo).unwrap();
    assert_eq!(staged, vec!["file.txt"]);

    let result =
        super::fold_files_into_commit(&test_repo.repo, &staged, &head_oid.to_string(), true);
    assert!(
        result.is_ok(),
        "fold_files_into_commit failed: {:?}",
        result
    );

    // The committed file must contain only the first hunk — not MODIFIED BOTTOM.
    let committed = read_file_from_commit(&test_repo.repo, test_repo.head_oid(), "file.txt");
    assert!(
        committed.contains("MODIFIED TOP"),
        "committed content should contain MODIFIED TOP"
    );
    assert!(
        !committed.contains("MODIFIED BOTTOM"),
        "committed content must NOT contain MODIFIED BOTTOM (whole-file bug)"
    );

    // The second change must still be in the working tree (not lost).
    let worktree = test_repo.read_file("file.txt");
    assert!(
        worktree.contains("MODIFIED BOTTOM"),
        "working tree should still have MODIFIED BOTTOM"
    );
}

/// Same regression but targeting a non-HEAD commit.
#[test]
fn fold_patch_only_staged_hunk_is_folded_into_non_head() {
    let test_repo = TestRepo::new_with_remote();

    let initial = "line 1\nline 2\nline 3\nline 4\nline 5\n\
                   line 6\nline 7\nline 8\nline 9\nline 10\n\
                   line 11\nline 12\nline 13\nline 14\nline 15\n";
    test_repo.write_file("file.txt", initial);
    test_repo.stage_files(&["file.txt"]);
    test_repo.commit_staged("target commit");
    let target_oid = test_repo.head_oid();

    // Add a second commit on top using CLI helpers to avoid index sync issues.
    test_repo.write_file("other.txt", "other content");
    test_repo.stage_files(&["other.txt"]);
    test_repo.commit_staged("second commit");

    // Modify two distant regions.
    let modified = "line 1\nMODIFIED TOP\nline 3\nline 4\nline 5\n\
                    line 6\nline 7\nline 8\nline 9\nline 10\n\
                    line 11\nline 12\nline 13\nMODIFIED BOTTOM\nline 15\n";
    test_repo.write_file("file.txt", modified);

    // Stage only the first hunk.
    let first_hunk_patch = "--- a/file.txt\n+++ b/file.txt\n\
                             @@ -1,5 +1,5 @@\n line 1\n-line 2\n+MODIFIED TOP\n \
                             line 3\n line 4\n line 5\n";
    let workdir = test_repo.workdir();
    crate::git::apply_cached_patch(workdir.as_path(), first_hunk_patch).unwrap();

    let staged = crate::core::repo::get_staged_files(&test_repo.repo).unwrap();
    let result =
        super::fold_files_into_commit(&test_repo.repo, &staged, &target_oid.to_string(), true);
    assert!(
        result.is_ok(),
        "fold_files_into_commit failed: {:?}",
        result
    );

    // Find the new OID of the rewritten target commit (it's now 1 step back).
    let new_target_oid = test_repo.get_oid(1);
    let committed = read_file_from_commit(&test_repo.repo, new_target_oid, "file.txt");
    assert!(
        committed.contains("MODIFIED TOP"),
        "committed content should contain MODIFIED TOP"
    );
    assert!(
        !committed.contains("MODIFIED BOTTOM"),
        "committed content must NOT contain MODIFIED BOTTOM (whole-file bug)"
    );
}

// ── Case 2: Commit + Commit (Fixup) ─────────────────────────────────────

#[test]
fn fold_commit_into_earlier_commit() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit("Original feature", "feature.txt");
    let c2_oid = test_repo.commit("Fix typo in feature", "feature.txt");

    let result =
        super::fold_commit_into_commit(&test_repo.repo, &c2_oid.to_string(), &c1_oid.to_string());

    assert!(
        result.is_ok(),
        "fold_commit_into_commit failed: {:?}",
        result
    );

    // Only one commit should remain (plus the initial commit)
    assert_eq!(test_repo.get_message(0), "Original feature");

    // The source commit should be gone (HEAD is now the target commit)
    // Hash should be different (rewritten)
    assert_ne!(test_repo.head_oid(), c1_oid);
    assert_ne!(test_repo.head_oid(), c2_oid);
}

#[test]
fn fold_commit_into_commit_preserves_other_commits() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit("First", "file1.txt");
    test_repo.commit("Second", "file2.txt");
    let c3_oid = test_repo.commit("Fix for first", "file1.txt");

    // Fold c3 into c1 (c3 is the fixup that should be part of c1)
    let result =
        super::fold_commit_into_commit(&test_repo.repo, &c3_oid.to_string(), &c1_oid.to_string());

    assert!(result.is_ok(), "fold failed: {:?}", result);

    // Should have 2 commits now (initial + First + Second; "Fix for first" absorbed)
    assert_eq!(test_repo.get_message(0), "Second");
    assert_eq!(test_repo.get_message(1), "First");
}

#[test]
fn fold_commit_same_commit_fails() {
    let test_repo = TestRepo::new();
    let c1_oid = test_repo.commit("First", "file1.txt");

    let result =
        super::fold_commit_into_commit(&test_repo.repo, &c1_oid.to_string(), &c1_oid.to_string());

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("same commit"));
}

#[test]
fn fold_commit_wrong_direction_fails() {
    let test_repo = TestRepo::new();
    let c1_oid = test_repo.commit("First", "file1.txt");
    let c2_oid = test_repo.commit("Second", "file2.txt");

    // Try to fold the older commit into the newer one (wrong direction)
    let result =
        super::fold_commit_into_commit(&test_repo.repo, &c1_oid.to_string(), &c2_oid.to_string());

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("newer than target")
    );
}

#[test]
fn fold_commit_dirty_working_tree_autostashed() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit("First", "file1.txt");
    let c2_oid = test_repo.commit("Second", "file2.txt");

    // Dirty the working tree
    test_repo.write_file("file1.txt", "dirty");

    let result =
        super::fold_commit_into_commit(&test_repo.repo, &c2_oid.to_string(), &c1_oid.to_string());

    assert!(
        result.is_ok(),
        "fold should succeed with autostash: {:?}",
        result
    );

    // Dirty changes should be preserved after autostash
    assert_eq!(test_repo.read_file("file1.txt"), "dirty");
}

// ── Case 3: Commit + Branch (Move) ──────────────────────────────────────

#[test]
fn fold_commit_to_branch() {
    // Set up an integration branch with two woven feature branches:
    //   origin/main → A1 (feature-a)
    //              ↘              ↘
    //               B1 --------→ merge → C1 (loose, to be moved)
    // After fold C1 to feature-a:
    //   origin/main → A1 → C1 (feature-a)
    //              ↘              ↘
    //               B1 --------→ merge
    let test_repo = TestRepo::new_with_remote();

    // Create commits for feature-a
    test_repo.commit("A1", "a1.txt");
    let a1_oid = test_repo.head_oid();

    // Create feature-a branch and weave it
    test_repo.create_branch_at("feature-a", &a1_oid.to_string());

    let base_oid = test_repo.find_remote_branch_target("origin/main");
    // Add a commit on integration line before merge
    test_repo.commit("B1", "b1.txt");

    // Manually set up merge topology:
    // Rebase B1 onto merge-base, then merge feature-a
    test_repo.rebase_onto(&base_oid.to_string(), &a1_oid.to_string());
    test_repo.merge_no_ff("feature-a");

    // Now add a loose commit on the integration line
    test_repo.commit("C1", "c1.txt");
    let c1_oid = test_repo.head_oid();

    // Move C1 to feature-a
    let result = super::fold_commit_to_branch(&test_repo.repo, &c1_oid.to_string(), "feature-a");

    assert!(result.is_ok(), "fold_commit_to_branch failed: {:?}", result);

    // C1 should now be on feature-a's branch (feature-a tip should have C1's message)
    assert_eq!(
        test_repo.branch_commit_summary("feature-a"),
        "C1",
        "C1 should now be at the tip of feature-a"
    );
}

#[test]
fn fold_commit_to_branch_via_short_ids() {
    // Regression: `run()` was missing TargetKind::Branch when resolving the
    // target, so `fold <commit-sid> <branch-sid>` would fail with
    // "'xx' did not resolve to a commit or commit file or file or unstaged changes".
    let test_repo = TestRepo::new_with_remote();

    test_repo.commit("A1", "a1.txt");
    let a1_oid = test_repo.head_oid();
    test_repo.create_branch_at("feature-a", &a1_oid.to_string());

    let base_oid = test_repo.find_remote_branch_target("origin/main");
    test_repo.commit("B1", "b1.txt");
    test_repo.rebase_onto(&base_oid.to_string(), &a1_oid.to_string());
    test_repo.merge_no_ff("feature-a");

    test_repo.commit("C1", "c1.txt");
    let c1_oid = test_repo.head_oid();

    // Get short IDs for the commit and branch
    let (commit_sid, branch_sid) = test_repo.in_dir(|| {
        let info = crate::core::repo::gather_repo_info(&test_repo.repo, false, 1).unwrap();
        let alloc = crate::core::shortid::IdAllocator::new(info.collect_entities());
        (
            alloc.get_commit(c1_oid).to_string(),
            alloc.get_branch("feature-a").to_string(),
        )
    });

    let result = test_repo.in_dir(|| {
        super::run(
            false,
            false,
            vec![commit_sid.clone(), branch_sid.clone()],
            &crate::core::graph::Theme::dark(),
        )
    });

    assert!(result.is_ok(), "fold via short IDs failed: {:?}", result);
    assert_eq!(
        test_repo.branch_commit_summary("feature-a"),
        "C1",
        "C1 should now be at the tip of feature-a"
    );
}

#[test]
fn fold_commit_to_branch_dirty_autostashed() {
    // Set up an integration branch with a woven feature branch and a loose commit
    let test_repo = TestRepo::new_with_remote();

    test_repo.commit("A1", "a1.txt");
    let a1_oid = test_repo.head_oid();

    test_repo.create_branch_at("feature-a", &a1_oid.to_string());

    let base_oid = test_repo.find_remote_branch_target("origin/main");
    test_repo.commit("B1", "b1.txt");

    test_repo.rebase_onto(&base_oid.to_string(), &a1_oid.to_string());
    test_repo.merge_no_ff("feature-a");

    let loose_oid = test_repo.commit("Loose", "loose.txt");

    // Dirty the working tree
    test_repo.write_file("a1.txt", "dirty");

    let result = super::fold_commit_to_branch(&test_repo.repo, &loose_oid.to_string(), "feature-a");

    assert!(
        result.is_ok(),
        "fold should succeed with autostash: {:?}",
        result
    );

    // Dirty changes should be preserved after autostash
    assert_eq!(test_repo.read_file("a1.txt"), "dirty");
}

#[test]
fn fold_commit_to_colocated_branch_only_affects_target() {
    // Reproduce: two co-located woven branches (feat2 and feat3 sharing the same
    // merge commit), plus a third branch (test) with commits.
    // Moving a commit from 'test' to 'feat3' should put it only on feat3,
    // NOT on feat2.
    //
    // Before:
    //   ╭─ [feat3]
    //   ├─ [feat2]
    //   ●  Feat2
    //    //   ╭─ [test]
    //   ●  Feat3
    //   ●  Feat1
    //    //
    // After fold Feat3 → feat3:
    //   ╭─ [feat3]
    //   ●  Feat3    ← only on feat3
    //   ├─ [feat2]
    //   ●  Feat2
    //    //   ╭─ [test]
    //   ●  Feat1
    //    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Build the 'test' branch with two commits: Feat1 and Feat3
    test_repo.create_branch_at("test", &base_oid.to_string());
    test_repo.switch_branch("test");
    test_repo.commit("Feat1", "feat1.txt");
    test_repo.commit("Feat3", "feat3.txt");
    let feat3_oid = test_repo.head_oid();
    test_repo.switch_branch("integration");

    // Weave the 'test' branch
    test_repo.merge_no_ff("test");

    // Build the 'feat2' branch with one commit: Feat2
    test_repo.create_branch_at("feat2", &base_oid.to_string());
    test_repo.switch_branch("feat2");
    test_repo.commit("Feat2", "feat2.txt");
    test_repo.switch_branch("integration");

    // Create feat3 as co-located with feat2 (same tip)
    let feat2_tip = test_repo.get_branch_target("feat2");
    test_repo.create_branch_at("feat3", &feat2_tip.to_string());

    // Weave feat2 (which also brings in feat3 since they're co-located)
    test_repo.merge_no_ff("feat2");

    // Now move the Feat3 commit from 'test' branch to 'feat3' branch
    let result = super::fold_commit_to_branch(&test_repo.repo, &feat3_oid.to_string(), "feat3");

    assert!(result.is_ok(), "fold_commit_to_branch failed: {:?}", result);

    // feat3 should have Feat3 at its tip (above feat2)
    assert_eq!(
        test_repo.branch_commit_summary("feat3"),
        "Feat3",
        "feat3 tip should be Feat3"
    );

    // feat2 should still have Feat2 at its tip (NOT Feat3)
    assert_eq!(
        test_repo.branch_commit_summary("feat2"),
        "Feat2",
        "feat2 tip should still be Feat2, not Feat3"
    );

    // feat3 should be stacked on feat2: feat3's parent should be feat2's tip
    let feat3_commit = test_repo.find_commit(test_repo.get_branch_target("feat3"));
    assert_eq!(
        feat3_commit.parent_id(0).unwrap(),
        test_repo.get_branch_target("feat2"),
        "feat3 should be stacked on feat2"
    );

    // The outermost merge commit (HEAD) should reference feat3, not feat2
    let head = test_repo.head_commit();
    assert!(
        head.summary().unwrap_or("").contains("feat3"),
        "HEAD merge message should reference 'feat3', got: {:?}",
        head.summary()
    );
}

#[test]
fn fold_commit_to_empty_branch() {
    // Reproduce: a branch at the merge-base (no commits, no merge in the
    // integration line) and another branch with commits. Moving a commit to
    // the empty branch should create a section+merge and update the ref.
    //
    // This is the real-world scenario: create feat-a with a commit, move it
    // away (leaving feat-a at base with no merge), then move another commit
    // back to feat-a.
    //
    // Before:
    //   ╭─ [feature-b]
    //   ●  B1
    //   ●  A1
    //    //   ● [feature-a]   ← at base, no merge in topology
    //
    // After fold A1 → feature-a:
    //   ╭─ [feature-a]
    //   ●  A1
    //    //   ╭─ [feature-b]
    //   ●  B1
    //    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature-a at base (empty branch, not woven)
    test_repo.create_branch_at("feature-a", &base_oid.to_string());

    // Create feature-b with two commits
    test_repo.create_branch_at("feature-b", &base_oid.to_string());
    test_repo.switch_branch("feature-b");
    test_repo.commit("A1", "a1.txt");
    let a1_oid = test_repo.head_oid();
    test_repo.commit("B1", "b1.txt");
    test_repo.switch_branch("integration");

    // Weave feature-b into the integration line
    test_repo.merge_no_ff("feature-b");

    // Verify feature-a has no section in the graph (it's at base, not woven)
    let graph = Weave::from_repo(&test_repo.repo).unwrap();
    assert!(
        !graph.branch_sections.iter().any(|s| s.label == "feature-a"),
        "feature-a should NOT have a section before the fold"
    );

    // Move A1 from feature-b to feature-a
    let result = super::fold_commit_to_branch(&test_repo.repo, &a1_oid.to_string(), "feature-a");
    assert!(result.is_ok(), "fold_commit_to_branch failed: {:?}", result);

    // feature-a should now point to a commit with message "A1"
    assert_eq!(
        test_repo.branch_commit_summary("feature-a"),
        "A1",
        "feature-a tip should be A1, but branch was not updated (still at base)"
    );

    // feature-a should NOT still be at the base
    assert_ne!(
        test_repo.get_branch_target("feature-a"),
        base_oid,
        "feature-a should have moved from the base commit"
    );
}

#[test]
fn fold_commit_to_existing_out_of_scope_branch_fails() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create an out-of-scope branch with its own commit (diverged from base)
    test_repo.create_branch_at("out-of-scope", &base_oid.to_string());
    test_repo.switch_branch("out-of-scope");
    test_repo.commit("Out of scope work", "oos.txt");
    test_repo.switch_branch("integration");

    // Create a woven branch with a commit
    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    let a1_oid = test_repo.head_oid();
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feature-a");

    // Try to move A1 to the out-of-scope branch — should fail
    let result = super::fold_commit_to_branch(&test_repo.repo, &a1_oid.to_string(), "out-of-scope");
    assert!(result.is_err(), "should reject out-of-scope branch");
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("not part of the current integration scope"),
        "error should mention scope, got: {}",
        err
    );
}

// ── Type dispatch / classify tests ───────────────────────────────────────

#[test]
fn classify_files_into_commit() {
    let sources = vec![repo::Target::File("f1.txt".into())];
    let target = repo::Target::Commit("abc123".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_ok());
}

#[test]
fn classify_commit_into_commit() {
    let sources = vec![repo::Target::Commit("abc123".into())];
    let target = repo::Target::Commit("def456".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_ok());
}

#[test]
fn classify_commit_into_branch() {
    let sources = vec![repo::Target::Commit("abc123".into())];
    let target = repo::Target::Branch("feature-a".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_ok());
}

#[test]
fn classify_branch_source_rejected() {
    let sources = vec![repo::Target::Branch("feature-a".into())];
    let target = repo::Target::Commit("abc123".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Cannot fold a branch")
    );
}

#[test]
fn classify_files_into_branch_rejected() {
    let sources = vec![repo::Target::File("f1.txt".into())];
    let target = repo::Target::Branch("feature-a".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Cannot fold files into a branch")
    );
}

#[test]
fn classify_mixed_sources_rejected() {
    let sources = vec![
        repo::Target::File("f1.txt".into()),
        repo::Target::Commit("abc123".into()),
    ];
    let target = repo::Target::Commit("def456".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Cannot mix"));
}

#[test]
fn classify_multiple_commit_sources_rejected() {
    let sources = vec![
        repo::Target::Commit("abc123".into()),
        repo::Target::Commit("def456".into()),
    ];
    let target = repo::Target::Commit("ghi789".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Only one commit"));
}

// ── Case 4: Commit + Unstaged (Uncommit) ─────────────────────────────────

#[test]
fn fold_commit_to_unstaged_head() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    let head_oid = test_repo.head_oid();

    let result = super::fold_commit_to_unstaged(&test_repo.repo, &head_oid.to_string());

    assert!(
        result.is_ok(),
        "fold_commit_to_unstaged failed: {:?}",
        result
    );

    // HEAD should now be "First commit"
    assert_eq!(test_repo.get_message(0), "First commit");

    // file2.txt should exist in working directory as unstaged change
    assert_eq!(test_repo.read_file("file2.txt"), "Second commit");

    // The old HEAD should be gone
    assert_ne!(test_repo.head_oid(), head_oid);
}

#[test]
fn fold_commit_to_unstaged_non_head() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    let result = super::fold_commit_to_unstaged(&test_repo.repo, &c1_oid.to_string());

    assert!(
        result.is_ok(),
        "fold_commit_to_unstaged (non-HEAD) failed: {:?}",
        result
    );

    // Only "Second commit" should remain
    assert_eq!(test_repo.get_message(0), "Second commit");

    // file1.txt should be in the working directory as unstaged
    assert_eq!(test_repo.read_file("file1.txt"), "First commit");
}

#[test]
fn fold_commit_to_unstaged_dirty_autostashed() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Dirty the working tree with an unrelated change
    test_repo.write_file("file1.txt", "dirty");

    let head_oid = test_repo.head_oid();

    let result = super::fold_commit_to_unstaged(&test_repo.repo, &head_oid.to_string());

    assert!(
        result.is_ok(),
        "fold should succeed with dirty tree: {:?}",
        result
    );

    // HEAD should now be "First commit"
    assert_eq!(test_repo.get_message(0), "First commit");

    // Existing dirty changes should be preserved
    assert_eq!(test_repo.read_file("file1.txt"), "dirty");

    // Uncommitted changes should appear
    assert_eq!(test_repo.read_file("file2.txt"), "Second commit");
}

#[test]
fn classify_commit_into_unstaged() {
    let sources = vec![repo::Target::Commit("abc123".into())];
    let target = repo::Target::Unstaged;
    let result = super::classify(&sources, &target);
    assert!(result.is_ok());
    assert!(matches!(
        result.unwrap(),
        super::FoldOp::CommitToUnstaged { .. }
    ));
}

#[test]
fn classify_files_into_unstaged_rejected() {
    let sources = vec![repo::Target::File("f1.txt".into())];
    let target = repo::Target::Unstaged;
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Cannot fold files into unstaged")
    );
}

#[test]
fn fold_unstaged_into_commit() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Modify files without staging
    test_repo.write_file("file1.txt", "modified 1");
    test_repo.write_file("file2.txt", "modified 2");

    let head_oid = test_repo.head_oid();

    // fold zz HEAD — should amend all changed files into HEAD
    let result = test_repo.in_dir(|| {
        super::run(
            false,
            false,
            vec!["zz".into(), "HEAD".into()],
            &crate::core::graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "fold zz HEAD failed: {:?}", result);

    assert_ne!(test_repo.head_oid(), head_oid, "Hash should have changed");
    assert_eq!(test_repo.read_file("file1.txt"), "modified 1");
    assert_eq!(test_repo.read_file("file2.txt"), "modified 2");
}

#[test]
fn fold_unstaged_clean_tree_fails() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");

    let result = test_repo.in_dir(|| {
        super::run(
            false,
            false,
            vec!["zz".into(), "HEAD".into()],
            &crate::core::graph::Theme::dark(),
        )
    });
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("working tree is clean"),
        "Expected clean-tree error"
    );
}

// ── Case 5: CommitFile + Unstaged (Uncommit file) ─────────────────────────

#[test]
fn fold_commit_file_to_unstaged_head() {
    let test_repo = TestRepo::new();

    // Commit has two files (use CLI for consistent index)
    test_repo.write_file("file1.txt", "content1");
    test_repo.write_file("file2.txt", "content2");
    test_repo.stage_files(&["file1.txt", "file2.txt"]);
    test_repo.commit_staged("Two files");

    let head_oid = test_repo.head_oid();

    let result =
        super::fold_commit_file_to_unstaged(&test_repo.repo, &head_oid.to_string(), "file1.txt");

    assert!(
        result.is_ok(),
        "fold_commit_file_to_unstaged failed: {:?}",
        result
    );

    // The commit should still exist but only contain file2.txt
    assert_eq!(test_repo.get_message(0), "Two files");

    // file1.txt should be in working directory (unstaged)
    assert_eq!(test_repo.read_file("file1.txt"), "content1");

    // file2.txt should still be committed
    assert_eq!(test_repo.read_file("file2.txt"), "content2");
}

#[test]
fn fold_commit_file_to_unstaged_non_head() {
    let test_repo = TestRepo::new_with_remote();

    // First commit has two files (use CLI for staging to avoid libgit2 index mismatch)
    test_repo.write_file("file1.txt", "content1");
    test_repo.write_file("file2.txt", "content2");
    test_repo.stage_files(&["file1.txt", "file2.txt"]);
    test_repo.commit_staged("Two files");
    let c1_oid = test_repo.head_oid();

    // Second commit (also via CLI to keep index consistent)
    test_repo.write_file("file3.txt", "content3");
    test_repo.stage_files(&["file3.txt"]);
    test_repo.commit_staged("Second commit");

    let result =
        super::fold_commit_file_to_unstaged(&test_repo.repo, &c1_oid.to_string(), "file1.txt");

    assert!(
        result.is_ok(),
        "fold_commit_file_to_unstaged (non-HEAD) failed: {:?}",
        result
    );

    // Both commits should still exist
    assert_eq!(test_repo.get_message(0), "Second commit");
    assert_eq!(test_repo.get_message(1), "Two files");

    // file1.txt should be in working directory as unstaged changes
    assert_eq!(test_repo.read_file("file1.txt"), "content1");

    // file2.txt should still be committed
    assert_eq!(test_repo.read_file("file2.txt"), "content2");
}

#[test]
fn fold_commit_file_to_unstaged_no_changes_fails() {
    let test_repo = TestRepo::new();
    test_repo.commit("A commit", "file1.txt");
    let head_oid = test_repo.head_oid();

    // Try to uncommit a file that doesn't exist in the commit
    let result = super::fold_commit_file_to_unstaged(
        &test_repo.repo,
        &head_oid.to_string(),
        "nonexistent.txt",
    );

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("no changes"));
}

// ── Case 6: CommitFile + Commit (Move file between commits) ──────────────

#[test]
fn fold_commit_file_to_commit() {
    let test_repo = TestRepo::new_with_remote();

    // First commit has two files (use CLI for staging)
    test_repo.write_file("file1.txt", "content1");
    test_repo.write_file("file2.txt", "content2");
    test_repo.stage_files(&["file1.txt", "file2.txt"]);
    test_repo.commit_staged("Source commit");
    let source_oid = test_repo.head_oid();

    // Second commit (target, also via CLI)
    test_repo.write_file("file3.txt", "content3");
    test_repo.stage_files(&["file3.txt"]);
    test_repo.commit_staged("Target commit");
    let target_oid = test_repo.head_oid();

    let result = super::fold_commit_file_to_commit(
        &test_repo.repo,
        &source_oid.to_string(),
        "file1.txt",
        &target_oid.to_string(),
    );

    assert!(
        result.is_ok(),
        "fold_commit_file_to_commit failed: {:?}",
        result
    );

    // Both commits should still exist
    assert_eq!(test_repo.get_message(0), "Target commit");
    assert_eq!(test_repo.get_message(1), "Source commit");

    // file1.txt should still exist in the repo (now in target commit)
    assert_eq!(test_repo.read_file("file1.txt"), "content1");
    // file2.txt should still be in the source commit
    assert_eq!(test_repo.read_file("file2.txt"), "content2");
}

#[test]
fn fold_commit_file_to_commit_same_commit_fails() {
    let test_repo = TestRepo::new();
    let c1_oid = test_repo.commit("A commit", "file1.txt");

    let result = super::fold_commit_file_to_commit(
        &test_repo.repo,
        &c1_oid.to_string(),
        "file1.txt",
        &c1_oid.to_string(),
    );

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("same commit"));
}

/// Bug: moving a file from a newer commit to an older commit should
/// remove the file from source and add it to target. Previously, the
/// reverse fixup was incorrectly applied to the source, creating a
/// backwards change instead of a no-op.
#[test]
fn fold_commit_file_to_older_commit() {
    let test_repo = TestRepo::new_with_remote();

    // C1 (older, target): adds file_a.txt
    test_repo.write_file("file_a.txt", "aaa");
    test_repo.stage_files(&["file_a.txt"]);
    test_repo.commit_staged("Add file_a");
    let c1_oid = test_repo.head_oid();

    // C2 (newer, source): adds file_b.txt and modifies file_a.txt
    test_repo.write_file("file_a.txt", "aaa modified");
    test_repo.write_file("file_b.txt", "bbb");
    test_repo.stage_files(&["file_a.txt", "file_b.txt"]);
    test_repo.commit_staged("Add file_b and modify file_a");
    let c2_oid = test_repo.head_oid();

    // Move file_a.txt changes from C2 (newer) to C1 (older)
    let result = super::fold_commit_file_to_commit(
        &test_repo.repo,
        &c2_oid.to_string(),
        "file_a.txt",
        &c1_oid.to_string(),
    );

    assert!(
        result.is_ok(),
        "fold_commit_file_to_commit (newer→older) failed: {:?}",
        result
    );

    // Both commits should still exist
    assert_eq!(test_repo.get_message(0), "Add file_b and modify file_a");
    assert_eq!(test_repo.get_message(1), "Add file_a");

    // C1 should now include the file_a modification
    // Final state should have file_a.txt as "aaa modified"
    assert_eq!(test_repo.read_file("file_a.txt"), "aaa modified");

    // file_b.txt should still be in C2
    assert_eq!(test_repo.read_file("file_b.txt"), "bbb");

    // Key assertion: C2's diff should NOT contain a reverse change to file_a.txt.
    // Verify by checking that C2's diff only touches file_b.txt.
    let c2_diff = test_repo.diff_commit(&test_repo.head_oid().to_string());
    assert!(
        !c2_diff.contains("file_a.txt"),
        "C2 should no longer have any changes to file_a.txt, but diff contains:\n{}",
        c2_diff
    );
}

/// Bug: fixupping a commit in a stacked branch should preserve the
/// middle branch's ref. Previously, `update-ref` was emitted before
/// the fixup in the todo, causing the branch to point to a replaced commit.
#[test]
fn fold_commit_file_to_unstaged_stacked_branch() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Build feature-a on its own branch
    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");

    test_repo.write_file("fa1.txt", "feature-a file 1");
    test_repo.write_file("fa2.txt", "feature-a file 2");
    test_repo.stage_files(&["fa1.txt", "fa2.txt"]);
    test_repo.commit_staged("A1: two files");

    // Build feature-b stacked on feature-a
    test_repo.create_branch_at("feature-b", &test_repo.head_oid().to_string());
    test_repo.switch_branch("feature-b");

    test_repo.write_file("fb1.txt", "feature-b file 1");
    test_repo.stage_files(&["fb1.txt"]);
    test_repo.commit_staged("B1: one file");

    // Switch to integration and merge feature-b (includes A1 and B1)
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feature-b");

    // Verify setup: both branches exist, working tree has all files
    assert!(
        test_repo.branch_exists("feature-a"),
        "feature-a should exist before fold"
    );
    assert!(
        test_repo.branch_exists("feature-b"),
        "feature-b should exist before fold"
    );
    assert_eq!(test_repo.read_file("fa1.txt"), "feature-a file 1");

    // Get feature-a's tip (A1)
    let fa_tip = test_repo.get_branch_target("feature-a");

    // Uncommit fa1.txt from the A1 commit
    let result =
        super::fold_commit_file_to_unstaged(&test_repo.repo, &fa_tip.to_string(), "fa1.txt");

    assert!(
        result.is_ok(),
        "fold_commit_file_to_unstaged (stacked branch) failed: {:?}",
        result
    );

    // Key assertion: feature-a branch must still exist
    assert!(
        test_repo.branch_exists("feature-a"),
        "feature-a branch should still exist after fold"
    );

    // feature-b should also still exist
    assert!(
        test_repo.branch_exists("feature-b"),
        "feature-b branch should still exist after fold"
    );

    // fa1.txt should be in the working directory (unstaged)
    assert_eq!(test_repo.read_file("fa1.txt"), "feature-a file 1");

    // fa2.txt should still be committed
    assert_eq!(test_repo.read_file("fa2.txt"), "feature-a file 2");

    // fb1.txt should still be committed
    assert_eq!(test_repo.read_file("fb1.txt"), "feature-b file 1");
}

/// Bug: moving a file between commits in a stacked branch should
/// preserve all branch refs. Tests moving from a newer branch commit
/// to an older branch commit (which triggers the direction bug).
#[test]
fn fold_commit_file_to_commit_stacked_branch() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Build feature-a branch
    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");

    test_repo.write_file("fa1.txt", "feature-a file 1");
    test_repo.stage_files(&["fa1.txt"]);
    test_repo.commit_staged("A1");
    let a1_oid = test_repo.head_oid();

    // Build feature-b stacked on feature-a
    test_repo.create_branch_at("feature-b", &a1_oid.to_string());
    test_repo.switch_branch("feature-b");

    test_repo.write_file("fb1.txt", "feature-b file 1");
    test_repo.write_file("fb2.txt", "feature-b file 2");
    test_repo.stage_files(&["fb1.txt", "fb2.txt"]);
    test_repo.commit_staged("B1");
    let b1_oid = test_repo.head_oid();

    // Merge into integration
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feature-b");

    // Move fb1.txt from B1 (newer) to A1 (older)
    let result = super::fold_commit_file_to_commit(
        &test_repo.repo,
        &b1_oid.to_string(),
        "fb1.txt",
        &a1_oid.to_string(),
    );

    assert!(
        result.is_ok(),
        "fold_commit_file_to_commit (stacked branch) failed: {:?}",
        result
    );

    // Both branches should still exist
    assert!(
        test_repo.branch_exists("feature-a"),
        "feature-a should still exist after fold"
    );
    assert!(
        test_repo.branch_exists("feature-b"),
        "feature-b should still exist after fold"
    );

    // fb1.txt should have moved to feature-a (A1)
    assert_eq!(test_repo.read_file("fb1.txt"), "feature-b file 1");

    // B1 should no longer have fb1.txt changes
    let b_tip = test_repo.get_branch_target("feature-b");
    let b_diff = test_repo.diff_commit(&b_tip.to_string());
    assert!(
        !b_diff.contains("fb1.txt"),
        "B1 should no longer have fb1.txt changes, but diff contains:\n{}",
        b_diff
    );
    assert!(
        b_diff.contains("fb2.txt"),
        "B1 should still have fb2.txt changes"
    );

    // Key assertion for Bug 1: feature-a's ref should point to the correct
    // commit (the one with fb1.txt included), not the pre-fixup version.
    let a_tip = test_repo.get_branch_target("feature-a");
    let a_diff = test_repo.diff_commit(&a_tip.to_string());
    assert!(
        a_diff.contains("fb1.txt"),
        "feature-a (A1) should now include fb1.txt, but diff is:\n{}",
        a_diff
    );
    assert!(
        a_diff.contains("fa1.txt"),
        "feature-a (A1) should still include fa1.txt"
    );
}

/// Bug: moving a file between commits in a multi-branch woven topology
/// should preserve all branch refs and not produce rebase conflicts.
/// Matches the real-world scenario: foo2 has one commit, foo3 is stacked
/// on foo2 with another commit. Both are woven via a single merge of foo3.
/// Moving a file from foo3's commit (newer) to foo2's commit (older)
/// exercises both the two-phase rebase and the update-ref deferral.
#[test]
fn fold_commit_file_to_commit_woven_branches() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Build foo1 branch with one commit
    test_repo.create_branch_at("foo1", &base_oid.to_string());
    test_repo.switch_branch("foo1");
    test_repo.write_file("feature1", "feat 1");
    test_repo.stage_files(&["feature1"]);
    test_repo.commit_staged("Feature 1");
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("foo1");

    // Build foo2 branch with one commit (on base, not on integration)
    test_repo.create_branch_at("foo2", &base_oid.to_string());
    test_repo.switch_branch("foo2");
    test_repo.write_file("feature2", "feat 2");
    test_repo.stage_files(&["feature2"]);
    test_repo.commit_staged("Feature 2");
    let foo2_tip = test_repo.head_oid();

    // Build foo3 stacked on foo2 with one commit that modifies feature2 and adds feature7
    test_repo.create_branch_at("foo3", &foo2_tip.to_string());
    test_repo.switch_branch("foo3");
    test_repo.write_file("feature2", "feat 2 updated");
    test_repo.write_file("feature7", "feat 7");
    test_repo.stage_files(&["feature2", "feature7"]);
    test_repo.commit_staged("Feature 2 fixup");
    let foo3_tip = test_repo.head_oid();

    // Only merge foo3 into integration (brings in both foo2 and foo3 commits)
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("foo3");

    // Now move 'feature7' from foo3 tip (newer) to foo2 tip (older)
    let result = super::fold_commit_file_to_commit(
        &test_repo.repo,
        &foo3_tip.to_string(),
        "feature7",
        &foo2_tip.to_string(),
    );

    assert!(
        result.is_ok(),
        "fold_commit_file_to_commit (woven branches) failed: {:?}",
        result
    );

    // All branches should still exist
    assert!(test_repo.branch_exists("foo1"), "foo1 should still exist");
    assert!(test_repo.branch_exists("foo2"), "foo2 should still exist");
    assert!(test_repo.branch_exists("foo3"), "foo3 should still exist");

    // feature7 should be accessible (moved to foo2's commit)
    assert_eq!(test_repo.read_file("feature7"), "feat 7");

    // foo2's commit should now include feature7
    let foo2_new_tip = test_repo.get_branch_target("foo2");
    let foo2_diff = test_repo.diff_commit(&foo2_new_tip.to_string());
    assert!(
        foo2_diff.contains("feature7"),
        "foo2 should now include feature7, but diff is:\n{}",
        foo2_diff
    );

    // foo3's commit should no longer include feature7
    let foo3_new_tip = test_repo.get_branch_target("foo3");
    let foo3_diff = test_repo.diff_commit(&foo3_new_tip.to_string());
    assert!(
        !foo3_diff.contains("feature7"),
        "foo3 should no longer include feature7, but diff contains:\n{}",
        foo3_diff
    );
    // foo3 should still have its other change (feature2 modification)
    assert!(
        foo3_diff.contains("feature2"),
        "foo3 should still have feature2 changes"
    );
}

// ── CommitFile classify tests ────────────────────────────────────────────

#[test]
fn classify_commit_file_into_unstaged() {
    let sources = vec![repo::Target::CommitFile {
        commit: "abc123".into(),
        path: "file.txt".into(),
    }];
    let target = repo::Target::Unstaged;
    let result = super::classify(&sources, &target);
    assert!(result.is_ok());
    assert!(matches!(
        result.unwrap(),
        super::FoldOp::CommitFileToUnstaged { .. }
    ));
}

#[test]
fn classify_commit_file_into_commit() {
    let sources = vec![repo::Target::CommitFile {
        commit: "abc123".into(),
        path: "file.txt".into(),
    }];
    let target = repo::Target::Commit("def456".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_ok());
    assert!(matches!(
        result.unwrap(),
        super::FoldOp::CommitFileToCommit { .. }
    ));
}

#[test]
fn classify_commit_file_into_branch_rejected() {
    let sources = vec![repo::Target::CommitFile {
        commit: "abc123".into(),
        path: "file.txt".into(),
    }];
    let target = repo::Target::Branch("feature-a".into());
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Cannot fold a commit file into a branch")
    );
}

#[test]
fn classify_commit_file_target_rejected() {
    let sources = vec![repo::Target::Commit("abc123".into())];
    let target = repo::Target::CommitFile {
        commit: "def456".into(),
        path: "file.txt".into(),
    };
    let result = super::classify(&sources, &target);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("not a commit file")
    );
}

// ── Resolve fold arg tests ───────────────────────────────────────────────

#[test]
fn resolve_fold_arg_filesystem_path() {
    let test_repo = TestRepo::new();
    test_repo.commit("commit", "file1.txt");

    // Modify a file — should resolve as Target::File via filesystem fallback
    test_repo.write_file("file1.txt", "changed");

    let result = test_repo
        .in_dir(|| repo::resolve_arg(&test_repo.repo, "file1.txt", &[repo::TargetKind::File]));
    assert!(result.is_ok(), "resolve failed: {:?}", result);
    assert!(matches!(result.unwrap(), repo::Target::File(_)));
}

#[test]
fn resolve_fold_arg_commit_hash() {
    let test_repo = TestRepo::new_with_remote();
    let c1_oid = test_repo.commit_empty("commit");

    let result = test_repo.in_dir(|| {
        repo::resolve_arg(
            &test_repo.repo,
            &c1_oid.to_string(),
            &[repo::TargetKind::Commit],
        )
    });
    assert!(result.is_ok());
    assert!(matches!(result.unwrap(), repo::Target::Commit(_)));
}

#[test]
fn resolve_fold_arg_branch_name() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit_empty("A1");
    let a1_oid = test_repo.head_oid();
    test_repo.create_branch_at_commit("feature-a", a1_oid);

    let result = test_repo
        .in_dir(|| repo::resolve_arg(&test_repo.repo, "feature-a", &[repo::TargetKind::Branch]));
    assert!(result.is_ok());
    assert!(matches!(result.unwrap(), repo::Target::Branch(_)));
}

#[test]
fn resolve_fold_arg_head() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit_empty("commit");

    let result = test_repo
        .in_dir(|| repo::resolve_arg(&test_repo.repo, "HEAD", &[repo::TargetKind::Commit]));
    assert!(result.is_ok());
    assert!(matches!(result.unwrap(), repo::Target::Commit(_)));
}

// ── fold --create ─────────────────────────────────────────────────────────

#[test]
fn fold_create_moves_commit_on_branch_to_new_branch() {
    // Set up an integration branch with a woven feature branch.
    // Move a commit from the feature branch into a brand new branch.
    //
    // Before:
    //   ╭─ [feature-a]
    //   ●  A1  ← move this to new-branch
    //    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    let a1_oid = test_repo.commit("A1", "a1.txt");
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feature-a");

    let result = super::run_create(
        &test_repo.repo,
        &[a1_oid.to_string(), "new-branch".to_string()],
    );
    assert!(result.is_ok(), "fold --create failed: {:?}", result);

    // new-branch should exist and point to A1
    assert_eq!(
        test_repo.branch_commit_summary("new-branch"),
        "A1",
        "new-branch should have A1 at its tip"
    );
}

#[test]
fn fold_create_warns_and_moves_to_existing_branch() {
    // When --create is used but the branch already exists, warn and move the commit.
    // Uses a non-woven feature-a at base and a loose commit on integration.
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // feature-a exists at base (not woven, no section in the graph)
    test_repo.create_branch_at("feature-a", &base_oid.to_string());

    // Add a loose commit on integration
    let loose_oid = test_repo.commit("Loose", "loose.txt");

    // feature-a already exists — should warn and move the commit anyway
    let result = super::run_create(
        &test_repo.repo,
        &[loose_oid.to_string(), "feature-a".to_string()],
    );
    assert!(
        result.is_ok(),
        "fold --create with existing branch should succeed: {:?}",
        result
    );
    assert_eq!(
        test_repo.branch_commit_summary("feature-a"),
        "Loose",
        "Loose commit should have moved to feature-a"
    );
}

#[test]
fn fold_create_rejects_non_commit_source() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.create_branch("feature-a");

    let result = super::run_create(
        &test_repo.repo,
        &["feature-a".to_string(), "new-branch".to_string()],
    );
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("commit"),
        "should error when source is a branch, got: {err}"
    );
}

// ── Single-arg: Staged files into commit ──────────────────────────────

#[test]
fn fold_staged_into_head() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Modify and stage a file
    test_repo.write_file("file1.txt", "staged content");
    test_repo.stage_files(&["file1.txt"]);

    let head_oid = test_repo.head_oid();

    let result = super::run_staged(&test_repo.repo, &head_oid.to_string());
    assert!(result.is_ok(), "run_staged failed: {:?}", result);

    // HEAD should have been amended
    assert_eq!(test_repo.get_message(0), "Second commit");
    assert_ne!(test_repo.head_oid(), head_oid);
    assert_eq!(test_repo.read_file("file1.txt"), "staged content");
}

#[test]
fn fold_staged_nothing_staged_fails() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");

    let head_oid = test_repo.head_oid();

    let result = super::run_staged(&test_repo.repo, &head_oid.to_string());
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Nothing to commit"),
        "should error when nothing is staged"
    );
}

#[test]
fn fold_staged_only_uses_staged_not_unstaged() {
    let test_repo = TestRepo::new();
    test_repo.commit("First commit", "file1.txt");
    test_repo.commit("Second commit", "file2.txt");

    // Stage one file, leave another unstaged
    test_repo.write_file("file1.txt", "staged content");
    test_repo.write_file("file2.txt", "unstaged content");
    test_repo.stage_files(&["file1.txt"]);

    let head_oid = test_repo.head_oid();

    let result = super::run_staged(&test_repo.repo, &head_oid.to_string());
    assert!(result.is_ok(), "run_staged failed: {:?}", result);

    // Only file1.txt should be in the commit; file2.txt should remain as unstaged
    assert_eq!(test_repo.read_file("file1.txt"), "staged content");
    // file2.txt should still have working tree changes (not committed)
    assert_eq!(test_repo.read_file("file2.txt"), "unstaged content");
}

#[test]
fn fold_staged_non_commit_target_fails() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("First commit", "file1.txt");
    let a1_oid = test_repo.head_oid();
    test_repo.create_branch_at_commit("feature-a", a1_oid);

    test_repo.write_file("file1.txt", "staged content");
    test_repo.stage_files(&["file1.txt"]);

    // Passing a branch name when only Commit is accepted should fail
    let result = test_repo.in_dir(|| super::run_staged(&test_repo.repo, "feature-a"));
    assert!(result.is_err(), "should have failed");
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("commit"),
        "should error when target is not a commit, got: {err_msg}"
    );
}

// ── Abort preserves working state ────────────────────────────────────────

/// Regression: loom abort after a fold conflict must preserve staged changes
/// on other files, unstaged changes, and new untracked files.
///
/// Conflict setup: Commit A creates `shared.txt`; Commit B modifies it.
/// Folding the working-tree version of `shared.txt` into A rewrites A's
/// content; when B is replayed it expects A's original content → conflict.
#[test]
fn fold_abort_preserves_working_state() {
    let test_repo = TestRepo::new_with_remote();

    let a_oid = test_repo.commit("version-a", "shared.txt");
    test_repo.write_file("shared.txt", "version-b");
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Commit B");

    // Write the content we want to fold into A.
    // When B is replayed after modified-A it expects "version-a" → conflict.
    test_repo.write_file("shared.txt", "version-folded");

    // Bystander state — fold.rs saves other staged files via saved_staged_patch.
    test_repo.write_file("other-staged.txt", "staged-content");
    test_repo.stage_files(&["other-staged.txt"]);
    test_repo.write_file("other-unstaged.txt", "unstaged-content");
    test_repo.write_file("new-file.txt", "new-content");

    let result = super::fold_files_into_commit(
        &test_repo.repo,
        &["shared.txt".to_string()],
        &a_oid.to_string(),
        false,
    );
    assert!(
        result.is_ok(),
        "fold should pause on conflict: {:?}",
        result
    );

    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state must exist when fold is paused on conflict"
    );

    let workdir = test_repo.workdir();
    let git_dir = test_repo.repo.path().to_path_buf();
    crate::core::transaction::abort_cmd(&workdir, &git_dir).unwrap();

    assert_eq!(test_repo.read_file("other-staged.txt"), "staged-content");
    assert_eq!(
        test_repo.read_file("other-unstaged.txt"),
        "unstaged-content"
    );
    assert!(
        workdir.join("new-file.txt").exists(),
        "new untracked file must survive abort"
    );
    assert_eq!(test_repo.read_file("new-file.txt"), "new-content");
}