mkit-cli 0.4.1

The mkit command-line tool: a content-addressed VCS with native attestation support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
//! Integration tests for the CLI-WIRE commands (9 subcommands).
//!
//! Each command gets at least one happy-path and one error-path test.
//! We spawn the real `mkit` binary so full argv → dispatch → library
//! path is exercised.
#![allow(clippy::unwrap_used)] // unwrap is the assertion in test helpers

use std::fs;
use std::path::Path;
use std::process::Command;

fn mkit_bin() -> &'static str {
    env!("CARGO_BIN_EXE_mkit")
}

fn run_in(cwd: &Path, args: &[&str]) -> std::process::Output {
    // Empty XDG_CONFIG_HOME per call so the developer's real user
    // config does not bleed into tests.
    let xdg = tempfile::tempdir().expect("xdg tempdir");
    let out = Command::new(mkit_bin())
        .args(args)
        .current_dir(cwd)
        .env("XDG_CONFIG_HOME", xdg.path())
        .output()
        .expect("spawn mkit");
    drop(xdg);
    out
}

fn init_repo(td: &Path) {
    assert!(run_in(td, &["init"]).status.success());
    // we removed auto-keygen on `mkit commit`.
    assert!(run_in(td, &["keygen"]).status.success());
}

fn make_commit(td: &Path, file: &str, body: &[u8], msg: &str) {
    fs::write(td.join(file), body).unwrap();
    assert!(run_in(td, &["add", file]).status.success());
    let out = run_in(td, &["commit", "-m", msg]);
    assert!(out.status.success(), "commit failed: {out:?}");
}

fn head_hash(td: &Path) -> String {
    ref_hash(td, "main")
}

fn ref_hash(td: &Path, branch: &str) -> String {
    fs::read_to_string(td.join(".mkit/refs/heads").join(branch))
        .unwrap()
        .trim()
        .to_string()
}

// ---------- clone ---------------------------------------------------------

#[test]
fn clone_errors_on_missing_url() {
    let td = tempfile::tempdir().unwrap();
    let out = run_in(td.path(), &["clone"]);
    assert!(!out.status.success());
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.to_lowercase().contains("usage"),
        "expected usage diagnostic on stderr, got: {stderr}"
    );
}

#[test]
fn clone_from_file_url_roundtrips() {
    // FileTransport expects a bare-ish layout with `refs/heads/...` and
    // `packs/...` directly under its root URL — NOT the in-repo `.mkit/`
    // layout. We set up a bare directory, push alice's refs into it,
    // then clone from the bare URL.
    let alice = tempfile::tempdir().unwrap();
    init_repo(alice.path());
    make_commit(alice.path(), "a.txt", b"hi from alice\n", "first");

    let bare = tempfile::tempdir().unwrap();
    let url = format!("mkit+file://{}", bare.path().display());
    // Publish alice's main ref into the bare remote.
    assert!(
        run_in(alice.path(), &["remote", "add", &url])
            .status
            .success()
    );
    let out = run_in(alice.path(), &["push"]);
    assert!(out.status.success(), "push failed: {out:?}");

    let parent = tempfile::tempdir().unwrap();
    let out = Command::new(mkit_bin())
        .args(["clone", &url, "bob"])
        .current_dir(parent.path())
        .output()
        .expect("spawn");
    assert!(out.status.success(), "clone failed: {out:?}");
    let bob = parent.path().join("bob");
    assert!(bob.join(".mkit/refs/heads/main").is_file());
    assert_eq!(
        fs::read_to_string(alice.path().join(".mkit/refs/heads/main"))
            .unwrap()
            .trim(),
        fs::read_to_string(bob.join(".mkit/refs/heads/main"))
            .unwrap()
            .trim(),
    );
}

// ---------- merge ---------------------------------------------------------

#[test]
fn merge_errors_on_missing_branch() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["merge", "nope"]);
    assert!(!out.status.success());
}

#[test]
fn merge_fast_forwards_when_current_is_ancestor() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"1\n", "c1");
    let c1 = head_hash(td.path());
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());
    // Advance feature ahead of main.
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(td.path(), "a.txt", b"2\n", "c2");
    // Go back to main — main still at c1 — and merge feature (ff).
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    // Only assert merge ran; check it claims fast-forward.
    let out = run_in(td.path(), &["merge", "feature"]);
    assert!(out.status.success(), "merge failed: {out:?}");
    // Confirmation prose now lives on stderr.
    let stderr = String::from_utf8(out.stderr).unwrap();
    let lower = stderr.to_lowercase();
    assert!(
        lower.contains("fast-forward") || lower.contains("up to date"),
        "unexpected merge output: {stderr}"
    );
    // main should have moved off c1.
    assert_ne!(head_hash(td.path()), c1);
}

#[test]
fn merge_preserves_ignored_untracked_files() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"1\n", "c1");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(td.path(), "a.txt", b"2\n", "c2");
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());

    fs::write(td.path().join(".mkitignore"), "local.txt\n").unwrap();
    fs::write(td.path().join("local.txt"), b"local only\n").unwrap();

    let out = run_in(td.path(), &["merge", "feature"]);
    assert!(out.status.success(), "merge failed: {out:?}");
    assert_eq!(
        fs::read(td.path().join("local.txt")).unwrap(),
        b"local only\n"
    );
    assert_eq!(
        fs::read_to_string(td.path().join(".mkitignore")).unwrap(),
        "local.txt\n"
    );
}

// ---------- cherry-pick ---------------------------------------------------

#[test]
fn cherry_pick_errors_on_bad_hash() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["cherry-pick", "not-a-hash"]);
    assert!(!out.status.success());
}

#[test]
fn cherry_pick_restores_worktree_and_advances_ref() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "base.txt", b"base\n", "base");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(td.path(), "picked.txt", b"picked\n", "picked");
    let picked = ref_hash(td.path(), "feature");
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    let main_before = head_hash(td.path());

    let out = run_in(td.path(), &["cherry-pick", &picked]);
    assert!(out.status.success(), "cherry-pick failed: {out:?}");
    assert_eq!(fs::read(td.path().join("picked.txt")).unwrap(), b"picked\n");
    assert_ne!(head_hash(td.path()), main_before);
}

// ---------- rebase --------------------------------------------------------

#[test]
fn rebase_errors_when_no_rebase_in_progress() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["rebase", "--continue"]);
    assert!(!out.status.success());
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(stderr.contains("no rebase in progress"));
}

#[test]
fn rebase_onto_same_head_is_noop() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"1\n", "c1");
    // Create a feature branch at HEAD and rebase onto it — nothing to replay.
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());
    let out = run_in(td.path(), &["rebase", "feature"]);
    assert!(out.status.success(), "rebase failed: {out:?}");
    // Confirmation prose lives on stderr.
    let stderr = String::from_utf8(out.stderr).unwrap();
    let lower = stderr.to_lowercase();
    assert!(
        lower.contains("rebased") || lower.contains("up to date"),
        "unexpected rebase output: {stderr}"
    );
}

#[test]
fn rebase_abort_restores_original_branch_ref_and_worktree() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"base\n", "base");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());

    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(td.path(), "a.txt", b"feature\n", "feature change");
    let feature_before = ref_hash(td.path(), "feature");

    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    make_commit(td.path(), "a.txt", b"main\n", "main change");

    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    let rebase = run_in(td.path(), &["rebase", "main"]);
    assert!(!rebase.status.success(), "rebase should pause on conflict");
    assert!(td.path().join(".mkit/rebase-apply").exists());

    let abort = run_in(td.path(), &["rebase", "--abort"]);
    assert!(abort.status.success(), "abort failed: {abort:?}");
    assert_eq!(ref_hash(td.path(), "feature"), feature_before);
    assert_eq!(fs::read(td.path().join("a.txt")).unwrap(), b"feature\n");
    assert!(!td.path().join(".mkit/rebase-apply").exists());
}

// ---------- bisect --------------------------------------------------------

#[test]
fn bisect_errors_on_unknown_subcommand() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["bisect", "wat"]);
    assert!(!out.status.success());
}

#[test]
fn bisect_start_creates_state_file() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"1\n", "c1");
    let out = run_in(td.path(), &["bisect", "start"]);
    assert!(out.status.success(), "bisect start failed: {out:?}");
    assert!(td.path().join(".mkit/bisect").is_file());
    // Clean up so the repo can be dropped cleanly.
    assert!(run_in(td.path(), &["bisect", "reset"]).status.success());
}

#[test]
fn bisect_run_converges_to_first_bad_commit() {
    // #528: `bisect run <cmd>` drives the loop automatically — it checks
    // out each candidate, runs the command, and maps the exit code (0=good,
    // 1-127≠125=bad) until it prints the first bad commit. Bug is introduced
    // at c3 (marker flips to BAD); the run must converge to c3.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c2");
    make_commit(td.path(), "marker.txt", b"BAD\n", "c3");
    let c3 = head_hash(td.path());
    make_commit(td.path(), "marker.txt", b"BAD\n", "c4");
    make_commit(td.path(), "marker.txt", b"BAD\n", "c5");
    let c5 = head_hash(td.path());

    assert!(run_in(td.path(), &["bisect", "start"]).status.success());
    assert!(run_in(td.path(), &["bisect", "good", &c1]).status.success());
    assert!(run_in(td.path(), &["bisect", "bad", &c5]).status.success());

    // `! grep -q BAD marker.txt` exits 0 (good) when marker is "ok",
    // 1 (bad) when it is "BAD".
    let out = run_in(
        td.path(),
        &["bisect", "run", "sh", "-c", "! grep -q BAD marker.txt"],
    );
    assert!(out.status.success(), "bisect run failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert_eq!(
        stdout.trim(),
        &c3[..12],
        "bisect run must converge to the first bad commit c3: {stdout:?}"
    );
    let _ = run_in(td.path(), &["bisect", "reset"]);
}

#[test]
fn bisect_run_skips_untestable_candidate_and_still_converges() {
    // #528: exit 125 marks a candidate untestable (skip). The bug is at c3;
    // c4 (above the first-bad) is untestable. Skipping c4 is bypassed as the
    // range narrows below it, so the run still converges to c3. (A skip that
    // STRANDED the answer next to `bad` would instead be ambiguous — see
    // `bisect_run_reports_ambiguity_when_all_candidates_skipped`.)
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c2");
    make_commit(td.path(), "marker.txt", b"BAD\n", "c3");
    let c3 = head_hash(td.path());
    make_commit(td.path(), "marker.txt", b"SKIP\n", "c4");
    make_commit(td.path(), "marker.txt", b"BAD\n", "c5");
    let c5 = head_hash(td.path());

    assert!(run_in(td.path(), &["bisect", "start"]).status.success());
    assert!(run_in(td.path(), &["bisect", "good", &c1]).status.success());
    assert!(run_in(td.path(), &["bisect", "bad", &c5]).status.success());

    // 125 (skip) when marker is SKIP; 1 (bad) when BAD; 0 (good) otherwise.
    let script = "grep -q SKIP marker.txt && exit 125; grep -q BAD marker.txt && exit 1; exit 0";
    let out = run_in(td.path(), &["bisect", "run", "sh", "-c", script]);
    assert!(out.status.success(), "bisect run failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert_eq!(
        stdout.trim(),
        &c3[..12],
        "bisect run must bypass the c4 skip and converge to c3: {stdout:?}"
    );
    let _ = run_in(td.path(), &["bisect", "reset"]);
}

#[test]
fn bisect_run_survives_test_command_dirtying_a_tracked_file() {
    // Review #1: the test command modifies a tracked file each iteration
    // (as `cargo test` refreshing Cargo.lock, or a snapshot writer, would).
    // The per-candidate checkout is forced, discarding the scribbles, so the
    // run still converges instead of aborting on the second candidate.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c2");
    make_commit(td.path(), "marker.txt", b"BAD\n", "c3");
    let c3 = head_hash(td.path());
    make_commit(td.path(), "marker.txt", b"BAD\n", "c4");
    make_commit(td.path(), "tracked.txt", b"v0\n", "c5-track");
    let c5 = head_hash(td.path());

    assert!(run_in(td.path(), &["bisect", "start"]).status.success());
    assert!(run_in(td.path(), &["bisect", "good", &c1]).status.success());
    assert!(run_in(td.path(), &["bisect", "bad", &c5]).status.success());

    // The command appends to the tracked file, then classifies from marker.
    let script = "echo scribble >> tracked.txt; ! grep -q BAD marker.txt";
    let out = run_in(td.path(), &["bisect", "run", "sh", "-c", script]);
    assert!(
        out.status.success(),
        "bisect run must survive a tracked-file-dirtying command: {out:?}"
    );
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert_eq!(stdout.trim(), &c3[..12], "converges to c3: {stdout:?}");
    let _ = run_in(td.path(), &["bisect", "reset"]);
}

#[test]
fn bisect_run_reports_ambiguity_when_all_candidates_skipped() {
    // Review #3: when every remaining candidate is skipped, the run must NOT
    // print `bad` as a definitive first-bad — it reports ambiguity (like
    // git) and exits non-zero.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "marker.txt", b"ok\n", "c1");
    let c1 = head_hash(td.path());
    for c in ["c2", "c3", "c4"] {
        make_commit(td.path(), "marker.txt", b"BAD\n", c);
    }
    let c4 = head_hash(td.path());

    assert!(run_in(td.path(), &["bisect", "start"]).status.success());
    assert!(run_in(td.path(), &["bisect", "good", &c1]).status.success());
    assert!(run_in(td.path(), &["bisect", "bad", &c4]).status.success());

    // Every candidate is untestable (exit 125).
    let out = run_in(td.path(), &["bisect", "run", "sh", "-c", "exit 125"]);
    assert!(
        !out.status.success(),
        "all-skipped run must exit non-zero: {out:?}"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("only skipped commits left"),
        "must report ambiguity like git: {stderr}"
    );
    let _ = run_in(td.path(), &["bisect", "reset"]);
}

// ---------- stash ---------------------------------------------------------

#[test]
fn stash_list_on_empty_repo_prints_none_marker() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["stash", "list"]);
    assert!(out.status.success(), "stash list failed: {out:?}");
    // Empty stash listing → empty stdout; the "(no stash entries)"
    // marker is human-readable diagnostic on stderr.
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.is_empty(),
        "empty stash list must produce empty stdout: {stdout:?}"
    );
    // git prints nothing at all for an empty stash list — match that.
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.is_empty(),
        "empty stash list must be silent (git-shaped): {stderr:?}"
    );
}

#[test]
fn stash_show_on_empty_stash_errors_out_of_range() {
    // `stash show` defaults to entry 0; with no stash entries that
    // index is out of range and must fail with GENERAL_ERROR (1) and a
    // diagnostic naming the bad index — not panic, and not exit 0.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["stash", "show"]);
    assert_eq!(
        out.status.code(),
        Some(1),
        "empty-stash `stash show` must exit GENERAL_ERROR: {out:?}"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("stash index 0 is out of range"),
        "expected the out-of-range diagnostic, got: {stderr}"
    );
}

// ---------- blame ---------------------------------------------------------

#[test]
fn blame_errors_on_missing_file() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "real.txt", b"x\n", "r1");
    let out = run_in(td.path(), &["blame", "nope.txt"]);
    assert!(!out.status.success());
}

#[test]
fn blame_on_single_commit_attributes_every_line_to_it() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"one\ntwo\nthree\n", "first");
    let out = run_in(td.path(), &["blame", "f.txt"]);
    assert!(out.status.success(), "blame failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    // Three lines, each with short_hash \t <line_num> \t <text>.
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 3, "expected 3 blame lines, got {stdout:?}");
    assert!(lines[0].ends_with("\tone"));
    assert!(lines[1].ends_with("\ttwo"));
    assert!(lines[2].ends_with("\tthree"));
    // Short hash is 12 hex chars.
    let first_short: &str = lines[0].split('\t').next().unwrap();
    assert_eq!(first_short.len(), 12);
    assert!(first_short.chars().all(|c| c.is_ascii_hexdigit()));
}

#[test]
fn blame_l_range_slices_lines_and_keeps_numbering() {
    // `-L <start>,<end>` restricts output to that inclusive range while
    // preserving the file's own 1-based line numbers, matching git.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\nc\nd\ne\n", "first");
    let out = run_in(td.path(), &["blame", "-L", "2,4", "f.txt"]);
    assert!(out.status.success(), "blame -L failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 3, "expected lines 2..=4, got {stdout:?}");
    // Line numbers are the file's own (2,3,4), not 1,2,3.
    assert!(lines[0].contains("\t2\t") && lines[0].ends_with("\tb"));
    assert!(lines[1].contains("\t3\t") && lines[1].ends_with("\tc"));
    assert!(lines[2].contains("\t4\t") && lines[2].ends_with("\td"));
}

#[test]
fn blame_l_plus_offset_counts_lines() {
    // `-L <start>,+<n>` is n lines starting at <start>: `2,+1` → line 2.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\nc\n", "first");
    let out = run_in(td.path(), &["blame", "-L", "2,+1", "f.txt"]);
    assert!(out.status.success(), "blame -L +n failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 1, "expected just line 2, got {stdout:?}");
    assert!(lines[0].contains("\t2\t") && lines[0].ends_with("\tb"));
}

#[test]
fn blame_l_minus_offset_counts_lines_ending_at_start() {
    // `-L <start>,-<n>` is n lines *ending* at <start>: `4,-2` → lines 3,4.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\nc\nd\ne\n", "first");
    let out = run_in(td.path(), &["blame", "-L", "4,-2", "f.txt"]);
    assert!(out.status.success(), "blame -L -n failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 2, "expected lines 3,4, got {stdout:?}");
    assert!(lines[0].contains("\t3\t") && lines[0].ends_with("\tc"));
    assert!(lines[1].contains("\t4\t") && lines[1].ends_with("\td"));
}

#[test]
fn blame_l_start_past_eof_is_usage_error() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\n", "first");
    let out = run_in(td.path(), &["blame", "-L", "9,10", "f.txt"]);
    assert!(!out.status.success(), "expected failure on out-of-range -L");
    let stderr = String::from_utf8(out.stderr).unwrap();
    // git-faithful, colon-free phrasing: `file f.txt has only 2 lines`.
    assert!(
        stderr.contains("file f.txt has only 2 lines"),
        "expected git-faithful line-count diagnostic, got: {stderr}"
    );
}

#[test]
fn blame_l_zero_line_number_errors_without_panicking() {
    // Regression: `-L ,0` once panicked (exit 101) via an inverted-range
    // swap that produced line 0. It must be a clean usage error instead.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\nc\n", "first");
    let out = run_in(td.path(), &["blame", "-L", ",0", "f.txt"]);
    assert!(!out.status.success(), "expected failure on -L ,0");
    assert_ne!(
        out.status.code(),
        Some(101),
        "must not panic; got a 101 exit"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("-L invalid line number: 0"),
        "expected git-exact zero-line diagnostic, got: {stderr}"
    );
    // A negative start must reach the parser (allow_hyphen_values), not be
    // intercepted by clap as an unknown flag — git reports it by token.
    let neg = run_in(td.path(), &["blame", "-L", "-3,5", "f.txt"]);
    assert!(!neg.status.success());
    assert!(
        String::from_utf8(neg.stderr)
            .unwrap()
            .contains("-L invalid line number: -3"),
        "negative start should yield the git-exact diagnostic"
    );
}

#[test]
fn blame_at_explicit_revision_uses_that_commit() {
    // `mkit blame <rev> <file>` blames the file as of <rev>, not HEAD.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\nc\n", "first");
    let first = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"a\nMOD\nc\n", "second");

    // At HEAD, line 2 is attributed to the second commit.
    let head = run_in(td.path(), &["blame", "f.txt"]);
    let head_out = String::from_utf8(head.stdout).unwrap();
    assert!(head_out.lines().nth(1).unwrap().ends_with("\tMOD"));

    // At the first commit, the file is the original three lines, all
    // attributed to `first`.
    let out = run_in(td.path(), &["blame", &first, "f.txt"]);
    assert!(out.status.success(), "blame <rev> failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 3);
    assert!(
        lines[1].ends_with("\tb"),
        "expected pre-MOD content: {stdout:?}"
    );
    let short = &first[..12];
    assert!(
        lines.iter().all(|l| l.starts_with(short)),
        "every line should be attributed to the first commit: {stdout:?}"
    );
}

#[test]
fn blame_unknown_revision_errors() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "first");
    let out = run_in(td.path(), &["blame", "no-such-rev", "f.txt"]);
    assert!(
        !out.status.success(),
        "expected failure on unknown revision"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("unknown revision"),
        "expected unknown-revision diagnostic, got: {stderr}"
    );
}

#[test]
fn blame_w_ignores_whitespace_only_change() {
    // A whitespace-only edit reattributes the line by default, but `-w`
    // keeps the original commit while still printing the current bytes.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"foo(a, b)\n", "first");
    let first = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"foo(a,b)\n", "reformat");
    let second = head_hash(td.path());

    // Default: the reformat commit owns the line.
    let plain = run_in(td.path(), &["blame", "f.txt"]);
    let plain_out = String::from_utf8(plain.stdout).unwrap();
    assert!(
        plain_out.starts_with(&second[..12]),
        "default blame should attribute to the reformat commit: {plain_out:?}"
    );

    // -w: the original commit owns it, output shows the current bytes.
    let out = run_in(td.path(), &["blame", "-w", "f.txt"]);
    assert!(out.status.success(), "blame -w failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.starts_with(&first[..12]),
        "-w should keep the original commit: {stdout:?}"
    );
    assert!(
        stdout.trim_end().ends_with("\tfoo(a,b)"),
        "-w output should still show current bytes: {stdout:?}"
    );
}

#[test]
fn blame_m_attributes_within_file_move() {
    // A long line (over the 20-char -M threshold) moved to the end of the
    // file is credited to its original commit under -M.
    let long = "let quick_brown_fox_total = 1;";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(
        td.path(),
        "f.txt",
        format!("{long}\nB\nC\n").as_bytes(),
        "first",
    );
    let first = head_hash(td.path());
    make_commit(
        td.path(),
        "f.txt",
        format!("B\nC\n{long}\n").as_bytes(),
        "shuffle",
    );
    let second = head_hash(td.path());

    let plain = run_in(td.path(), &["blame", "f.txt"]);
    let plain_out = String::from_utf8(plain.stdout).unwrap();
    let plain_line = plain_out.lines().find(|l| l.ends_with(long)).unwrap();
    assert!(
        plain_line.starts_with(&second[..12]),
        "default: moved line is new: {plain_out:?}"
    );

    let out = run_in(td.path(), &["blame", "-M", "f.txt"]);
    assert!(out.status.success(), "blame -M failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let line = stdout.lines().find(|l| l.ends_with(long)).unwrap();
    assert!(
        line.starts_with(&first[..12]),
        "-M credits the moved line to its origin: {stdout:?}"
    );
}

#[test]
fn blame_m_merge_credits_move_from_second_parent() {
    // A long line lives only on the SECOND merge parent (feature); the merge
    // resolution moves it to the file's end, so neither parent's matcher
    // explains it in place. `git blame -M` credits the moved line to the
    // feature commit, NOT the merge — the detector must run against the
    // second parent. (Pinned against real `git blame -M`, git 2.50.1.)
    let long = "let quick_brown_fox_total = 1;";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"HEAD\nX\nY\n", "base");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());

    // First parent (main): a conflicting edit to line 1, no long line.
    make_commit(td.path(), "f.txt", b"MAIN\nX\nY\n", "p1edit");

    // Second parent (feature): writes the long line at the top.
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(
        td.path(),
        "f.txt",
        format!("{long}\nX\nY\n").as_bytes(),
        "feature writes long",
    );
    let feature = ref_hash(td.path(), "feature");

    // Merge conflicts on line 1; resolve by moving the long line to the end.
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    let merge = run_in(td.path(), &["merge", "feature"]);
    assert!(!merge.status.success(), "merge should conflict: {merge:?}");
    fs::write(td.path().join("f.txt"), format!("X\nY\n{long}\n")).unwrap();
    assert!(run_in(td.path(), &["add", "f.txt"]).status.success());
    let cont = run_in(td.path(), &["merge", "--continue"]);
    assert!(cont.status.success(), "merge --continue failed: {cont:?}");

    let out = run_in(td.path(), &["blame", "-M", "f.txt"]);
    assert!(out.status.success(), "blame -M failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let line = stdout.lines().find(|l| l.ends_with(long)).unwrap();
    assert!(
        line.starts_with(&feature[..12]),
        "-M credits the move to the 2nd-parent (feature) origin, not the merge: {stdout:?}"
    );
}

#[test]
fn blame_c_merge_conflict_edit_keeps_copy_tie_on_merge() {
    // End-to-end `-C` at a conflicted merge: the SAME copyable block is
    // added as a new file on BOTH merge sides (main's s1.txt, feature's
    // s2.txt) while f.txt itself CONFLICTS (edited on both sides) and is
    // resolved by appending the block. Because f.txt differs on the two
    // parents, BOTH keep their porigins — neither is deduped into the
    // whole-tree search — and s1.txt/s2.txt are unchanged at the merge, so
    // they are invisible to the modified-files channel: the block stays on
    // the MERGE, and the resolved "MAIN" line is credited to main's edit.
    // Pinned against real git 2.50.1 (contrast with mkit-core's
    // `blame_c_merge_copy_tie_prefers_deduped_second_parent`, where the
    // blamed file is UNCHANGED on both sides, the second parent's porigin
    // is deduped, and its whole tree — including the source — is
    // searched). This proves the porigin mechanism end-to-end through
    // `mkit merge --continue` and the real CLI `blame -C -C` path.
    let b1 = "fn handler_alpha() { compute(); }";
    let b2 = "fn handler_bravo() { compute(); }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"TOP\n", "base");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());

    // First parent (main): conflicting edit to f.txt, plus its OWN copy of
    // the block in s1.txt.
    fs::write(td.path().join("f.txt"), b"MAIN\n").unwrap();
    fs::write(td.path().join("s1.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(
        run_in(td.path(), &["add", "f.txt", "s1.txt"])
            .status
            .success()
    );
    assert!(
        run_in(td.path(), &["commit", "-m", "main edit + s1"])
            .status
            .success()
    );

    // Second parent (feature): a different conflicting edit to f.txt, plus
    // the SAME block duplicated in s2.txt (the tie).
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    fs::write(td.path().join("f.txt"), b"FEAT\n").unwrap();
    fs::write(td.path().join("s2.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(
        run_in(td.path(), &["add", "f.txt", "s2.txt"])
            .status
            .success()
    );
    assert!(
        run_in(td.path(), &["commit", "-m", "feature edit + s2"])
            .status
            .success()
    );
    let feature = ref_hash(td.path(), "feature");

    // Merge conflicts on f.txt; resolve by keeping main's line and
    // appending the block (present verbatim on both sides' new files).
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    let merge = run_in(td.path(), &["merge", "feature"]);
    assert!(!merge.status.success(), "merge should conflict: {merge:?}");
    fs::write(td.path().join("f.txt"), format!("MAIN\n{b1}\n{b2}\n")).unwrap();
    assert!(run_in(td.path(), &["add", "f.txt"]).status.success());
    let cont = run_in(td.path(), &["merge", "--continue"]);
    assert!(cont.status.success(), "merge --continue failed: {cont:?}");
    let merge_hash = head_hash(td.path());

    let out = run_in(td.path(), &["blame", "-C", "-C", "f.txt"]);
    assert!(out.status.success(), "blame -C -C failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert!(
        lines[1].starts_with(&merge_hash[..12]) && lines[2].starts_with(&merge_hash[..12]),
        "both parents keep their porigins (f.txt conflicted), so the \
         unchanged sources are invisible and the block stays on the merge \
         (git parity): {stdout:?}"
    );
    assert!(
        lines.iter().all(|l| !l.starts_with(&feature[..12])),
        "the second parent's unchanged s2.txt must not be credited: {stdout:?}"
    );
}

#[test]
fn blame_ignore_rev_merge_falls_through_to_second_parent() {
    // An ignored merge resolves a modify/delete conflict by keeping a noise
    // version of the feature line. The first parent (main) DELETED that line,
    // so the fall-through must cross to the SECOND parent (feature) that wrote
    // the content. `blame --ignore-rev <merge>` credits feature, not the
    // merge. (Pinned against real `git blame --ignore-rev`, git 2.50.1.)
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"TOP\nMID\nBOT\n", "base");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());

    // First parent (main): deletes MID.
    make_commit(td.path(), "f.txt", b"TOP\nBOT\n", "p1 deletes mid");

    // Second parent (feature): rewrites MID to real content.
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(
        td.path(),
        "f.txt",
        b"TOP\nREAL_CONTENT_OF_B_LINE\nBOT\n",
        "feature rewrites mid",
    );
    let feature = ref_hash(td.path(), "feature");

    // Merge conflicts (modify/delete); resolve to a noise version of the line.
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    let merge = run_in(td.path(), &["merge", "feature"]);
    assert!(!merge.status.success(), "merge should conflict: {merge:?}");
    fs::write(
        td.path().join("f.txt"),
        b"TOP\n  REAL_CONTENT_OF_B_LINE  X\nBOT\n",
    )
    .unwrap();
    assert!(run_in(td.path(), &["add", "f.txt"]).status.success());
    let cont = run_in(td.path(), &["merge", "--continue"]);
    assert!(cont.status.success(), "merge --continue failed: {cont:?}");
    let merge_hash = head_hash(td.path());

    let out = run_in(td.path(), &["blame", "--ignore-rev", &merge_hash, "f.txt"]);
    assert!(out.status.success(), "blame --ignore-rev failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert!(
        lines[1].starts_with(&feature[..12]),
        "ignored merge falls through across to the 2nd parent (feature): {stdout:?}"
    );
    assert!(
        lines.iter().all(|l| !l.starts_with(&merge_hash[..12])),
        "no line is credited to the ignored merge: {stdout:?}"
    );
}

#[test]
fn blame_ignore_rev_falls_through_to_prior_commit() {
    // `--ignore-rev <reformat>` skips the noise commit: line 2's blame
    // falls through to the commit that previously changed it, while the
    // output still shows the reformatted bytes. Mirrors real
    // `git blame --ignore-rev`.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"alpha\nbeta\ngamma\n", "first");
    let first = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"alpha\n  beta  \ngamma\n", "reformat");
    let reformat = head_hash(td.path());

    // Default: the reformat commit owns line 2.
    let plain = run_in(td.path(), &["blame", "f.txt"]);
    let plain_out = String::from_utf8(plain.stdout).unwrap();
    assert!(
        plain_out
            .lines()
            .nth(1)
            .unwrap()
            .starts_with(&reformat[..12])
    );

    let out = run_in(td.path(), &["blame", "--ignore-rev", &reformat, "f.txt"]);
    assert!(out.status.success(), "blame --ignore-rev failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert!(
        lines[1].starts_with(&first[..12]),
        "ignored reformat falls through to the first commit: {stdout:?}"
    );
    assert!(
        lines[1].ends_with("\t  beta  "),
        "output still shows the reformatted bytes: {stdout:?}"
    );
    assert!(
        lines.iter().all(|l| !l.starts_with(&reformat[..12])),
        "no line is credited to the ignored commit: {stdout:?}"
    );
}

#[test]
fn blame_c_attributes_copy_from_other_file() {
    // A block (over the 40-char -C threshold) is moved from a.txt into a
    // new b.txt; both files change in the commit, so -C (level 1) credits
    // b.txt's lines to the original commit.
    let b1 = "fn handler_alpha() { compute(); }";
    let b2 = "fn handler_bravo() { compute(); }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(
        td.path(),
        "a.txt",
        format!("{b1}\n{b2}\nzzz\n").as_bytes(),
        "first",
    );
    let first = head_hash(td.path());

    // Second commit: shrink a.txt and add b.txt with the block.
    fs::write(td.path().join("a.txt"), b"zzz\n").unwrap();
    fs::write(td.path().join("b.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(
        run_in(td.path(), &["add", "a.txt", "b.txt"])
            .status
            .success()
    );
    assert!(
        run_in(td.path(), &["commit", "-m", "split"])
            .status
            .success()
    );
    let second = head_hash(td.path());

    let plain = run_in(td.path(), &["blame", "b.txt"]);
    let plain_out = String::from_utf8(plain.stdout).unwrap();
    assert!(
        plain_out.lines().all(|l| l.starts_with(&second[..12])),
        "default: copied block is new: {plain_out:?}"
    );

    let out = run_in(td.path(), &["blame", "-C", "b.txt"]);
    assert!(out.status.success(), "blame -C failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.lines().all(|l| l.starts_with(&first[..12])),
        "-C credits the copied block to its origin commit: {stdout:?}"
    );
}

#[test]
fn blame_ignore_revs_file_skips_listed_commits() {
    // `--ignore-revs-file` reads full hex object names, skipping blank
    // lines and `#` comments (including inline) — verified against git.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"alpha\nbeta\n", "first");
    let first = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"alpha\n  beta  \n", "reformat");
    let reformat = head_hash(td.path());

    let revs = format!("# noise commits\n\n{reformat}  # the reformat\n");
    fs::write(td.path().join("revs.txt"), revs).unwrap();
    let out = run_in(
        td.path(),
        &["blame", "--ignore-revs-file", "revs.txt", "f.txt"],
    );
    assert!(
        out.status.success(),
        "blame --ignore-revs-file failed: {out:?}"
    );
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.lines().nth(1).unwrap().starts_with(&first[..12]),
        "listed reformat is skipped; line 2 falls through: {stdout:?}"
    );
}

#[test]
fn blame_c_c_widens_to_unchanged_source_file() {
    // `-C -C` (level 2) end-to-end: dst.txt copies a block from src.txt,
    // which is NOT modified in the copying commit. Level 1 misses it;
    // level 2 searches every parent file and credits the original commit.
    let b1 = "fn handler_alpha() { compute(); }";
    let b2 = "fn handler_bravo() { compute(); }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(
        td.path(),
        "src.txt",
        format!("{b1}\n{b2}\n").as_bytes(),
        "first",
    );
    let first = head_hash(td.path());

    // src.txt unchanged; dst.txt added with the same block.
    fs::write(td.path().join("dst.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(run_in(td.path(), &["add", "dst.txt"]).status.success());
    assert!(
        run_in(td.path(), &["commit", "-m", "copy"])
            .status
            .success()
    );
    let second = head_hash(td.path());

    // -C (level 1) ignores the unchanged source.
    let l1 = run_in(td.path(), &["blame", "-C", "dst.txt"]);
    let l1_out = String::from_utf8(l1.stdout).unwrap();
    assert!(
        l1_out.lines().all(|l| l.starts_with(&second[..12])),
        "-C level 1 misses the unchanged source: {l1_out:?}"
    );

    // -C -C (level 2) finds it.
    let l2 = run_in(td.path(), &["blame", "-C", "-C", "dst.txt"]);
    assert!(l2.status.success(), "blame -C -C failed: {l2:?}");
    let l2_out = String::from_utf8(l2.stdout).unwrap();
    assert!(
        l2_out.lines().all(|l| l.starts_with(&first[..12])),
        "-C -C credits the copied block to its origin: {l2_out:?}"
    );
}

#[test]
fn blame_c_inline_threshold_flips_copy_attribution() {
    // #525: inline `-C<num>` sets the similarity threshold (an alphanumeric
    // char count). The copied block is EXACTLY 40 alnum chars, so a
    // threshold at or below 40 detects the copy (credit the origin) while
    // 41 misses it (the block reads as new) — the boundary flip git's
    // `-C<num>` produces. The `%` form parses and, since mkit has no
    // similarity-ratio model, is treated as the same char count.
    let block = "abcdefghijklmnopqrstuvwxyzabcdefghijklmn"; // 40 alnum chars
    assert_eq!(block.chars().filter(|c| c.is_alphanumeric()).count(), 40);
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(
        td.path(),
        "a.txt",
        format!("{block}\nkeeper\n").as_bytes(),
        "first",
    );
    let first = head_hash(td.path());

    // Second commit: remove the block from a.txt, add it verbatim in b.txt.
    fs::write(td.path().join("a.txt"), b"keeper\n").unwrap();
    fs::write(td.path().join("b.txt"), format!("{block}\n")).unwrap();
    assert!(
        run_in(td.path(), &["add", "a.txt", "b.txt"])
            .status
            .success()
    );
    assert!(
        run_in(td.path(), &["commit", "-m", "split"])
            .status
            .success()
    );
    let second = head_hash(td.path());

    // Threshold above the block size: copy is NOT detected.
    let above = run_in(td.path(), &["blame", "-C41", "b.txt"]);
    assert!(above.status.success(), "blame -C41 failed: {above:?}");
    let above_out = String::from_utf8(above.stdout).unwrap();
    assert!(
        above_out.lines().all(|l| l.starts_with(&second[..12])),
        "-C41 (> 40-char block) misses the copy: {above_out:?}"
    );

    // Threshold at the block size: copy IS detected (git uses `>=`).
    let at = run_in(td.path(), &["blame", "-C40", "b.txt"]);
    assert!(at.status.success(), "blame -C40 failed: {at:?}");
    let at_out = String::from_utf8(at.stdout).unwrap();
    assert!(
        at_out.lines().all(|l| l.starts_with(&first[..12])),
        "-C40 (== block) credits the origin commit: {at_out:?}"
    );

    // The percent form parses and behaves like the bare number.
    let pct = run_in(td.path(), &["blame", "-C40%", "b.txt"]);
    assert!(pct.status.success(), "blame -C40% failed: {pct:?}");
    let pct_out = String::from_utf8(pct.stdout).unwrap();
    assert_eq!(
        pct_out, at_out,
        "-C40% is treated as the same char-count threshold as -C40"
    );

    // A non-numeric inline value is a clean value error, not a silent no-op.
    let bad = run_in(td.path(), &["blame", "-Cxyz", "b.txt"]);
    assert!(!bad.status.success(), "-Cxyz must be rejected");
}

#[test]
fn blame_c_inline_threshold_composes_with_repeat() {
    // #525: a numeric `-C<num>` still counts toward the copy *level*, so
    // `-C<num> -C` reaches level 2 (whole-parent search) with the given
    // threshold. The source file is UNCHANGED in the copying commit, so
    // only level 2 can find it — proving the repeat composed — and the
    // threshold from the numeric form still governs the match.
    let b1 = "fn handler_alpha() { compute(); }";
    let b2 = "fn handler_bravo() { compute(); }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(
        td.path(),
        "src.txt",
        format!("{b1}\n{b2}\n").as_bytes(),
        "first",
    );
    let first = head_hash(td.path());

    fs::write(td.path().join("dst.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(run_in(td.path(), &["add", "dst.txt"]).status.success());
    assert!(
        run_in(td.path(), &["commit", "-m", "copy"])
            .status
            .success()
    );
    let second = head_hash(td.path());

    // A single numeric `-C20` is only level 1 → misses the unchanged source.
    let l1 = run_in(td.path(), &["blame", "-C20", "dst.txt"]);
    let l1_out = String::from_utf8(l1.stdout).unwrap();
    assert!(
        l1_out.lines().all(|l| l.starts_with(&second[..12])),
        "-C20 (level 1) misses the unchanged source: {l1_out:?}"
    );

    // `-C20 -C` → level 2 with threshold 20 → finds the unchanged source.
    let l2 = run_in(td.path(), &["blame", "-C20", "-C", "dst.txt"]);
    assert!(l2.status.success(), "blame -C20 -C failed: {l2:?}");
    let l2_out = String::from_utf8(l2.stdout).unwrap();
    assert!(
        l2_out.lines().all(|l| l.starts_with(&first[..12])),
        "-C20 -C reaches level 2 and credits the origin: {l2_out:?}"
    );
}

#[test]
fn blame_c_c_c_searches_whole_parent_tree_for_unmodified_source() {
    // #526: git's third -C ("copies from other files in any commit")
    // whole-tree-searches at EVERY walk step, not just the file-creating
    // commit. Here a block is appended to a PERSISTING file (main.txt, which
    // has a porigin) and copied from an UNMODIFIED src.txt. -C -C only
    // searches files modified in the commit → misses (block stays on the
    // append commit c2); -C -C -C searches the whole parent tree → credits
    // the source's origin c1. Pinned against git 2.50.1.
    let b1 = "fn compute_alpha_beta_gamma() { let x = 1234567; }";
    let b2 = "fn compute_delta_epsilon_ze() { let y = 7654321; }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    // c1: a persisting file + the (never-again-modified) copy source.
    fs::write(td.path().join("main.txt"), b"header line one here\n").unwrap();
    fs::write(td.path().join("src.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(run_in(td.path(), &["add", "-A"]).status.success());
    assert!(run_in(td.path(), &["commit", "-m", "c1"]).status.success());
    let c1 = head_hash(td.path());
    // c2: append the block to main.txt; src.txt untouched.
    fs::write(
        td.path().join("main.txt"),
        format!("header line one here\n{b1}\n{b2}\n"),
    )
    .unwrap();
    assert!(run_in(td.path(), &["add", "main.txt"]).status.success());
    assert!(run_in(td.path(), &["commit", "-m", "c2"]).status.success());
    let c2 = head_hash(td.path());

    // Level 2 misses the unmodified source: appended block stays on c2.
    let l2 = run_in(td.path(), &["blame", "-C", "-C", "main.txt"]);
    assert!(l2.status.success(), "blame -C -C failed: {l2:?}");
    let l2_out = String::from_utf8(l2.stdout).unwrap();
    assert!(
        l2_out.lines().nth(1).unwrap().starts_with(&c2[..12]),
        "-C -C leaves the appended block on the append commit c2: {l2_out:?}"
    );

    // Level 3 whole-tree-searches the parent: block credited to c1/src.txt.
    let l3 = run_in(td.path(), &["blame", "-C", "-C", "-C", "main.txt"]);
    assert!(l3.status.success(), "blame -C -C -C failed: {l3:?}");
    let l3_out = String::from_utf8(l3.stdout).unwrap();
    assert!(
        l3_out.lines().nth(1).unwrap().starts_with(&c1[..12]),
        "-C -C -C credits the unmodified source's origin c1 ({}), not c2 ({}): {l3_out:?}",
        &c1[..12],
        &c2[..12]
    );
}

#[test]
fn blame_stacked_short_flags_reach_clap() {
    // Review #2: the inline-threshold pre-scan must only consume a *numeric*
    // glued value; stacked short clusters where `-M`/`-C` leads (`-CC` =
    // `-C -C`, `-Mw` = `-M -w`) must still reach clap, not be misread as a
    // threshold. `-CC` on an unchanged source is level 2 and credits the
    // origin; a genuinely bad flag (`-Cxyz`) is a clap USAGE error, not a
    // silent no-op or a DATAERR.
    let b1 = "fn handler_alpha() { compute(); }";
    let b2 = "fn handler_bravo() { compute(); }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(
        td.path(),
        "src.txt",
        format!("{b1}\n{b2}\n").as_bytes(),
        "c1",
    );
    let first = head_hash(td.path());
    fs::write(td.path().join("dst.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(run_in(td.path(), &["add", "dst.txt"]).status.success());
    assert!(run_in(td.path(), &["commit", "-m", "c2"]).status.success());

    // `-CC` == `-C -C` (level 2) → finds the unchanged source.
    let cc = run_in(td.path(), &["blame", "-CC", "dst.txt"]);
    assert!(cc.status.success(), "blame -CC failed: {cc:?}");
    let cc_out = String::from_utf8(cc.stdout).unwrap();
    assert!(
        cc_out.lines().all(|l| l.starts_with(&first[..12])),
        "-CC is level 2 and credits the origin: {cc_out:?}"
    );
    // `-Mw` == `-M -w` → succeeds (move detection + ignore-whitespace).
    assert!(
        run_in(td.path(), &["blame", "-Mw", "dst.txt"])
            .status
            .success(),
        "-Mw (= -M -w) must be accepted"
    );
    // A non-numeric glued value that isn't a valid cluster is a clap error.
    let bad = run_in(td.path(), &["blame", "-Cxyz", "dst.txt"]);
    assert_eq!(
        bad.status.code(),
        Some(64),
        "a bad -C value is a clap USAGE error (64), not DATAERR: {bad:?}"
    );
}

#[test]
fn blame_c_copy_tiebreak_prefers_older_ancestor_source() {
    // #527: two equally-similar copy sources. git credits the source that
    // traces to the OLDER (ancestor) commit — blame's push-back bias — not
    // the first candidate in path order. Here the older source (committed
    // first) is alphabetically LAST (src_z), so a path-order pick would
    // wrongly credit the newer src_a. Pinned against git 2.50.1:
    // `git blame -C -C dst.txt` credits c1.
    let b1 = "fn compute_alpha_beta_gamma() { let x = 1234567; }";
    let b2 = "fn compute_delta_epsilon_ze() { let y = 7654321; }";
    let block = format!("{b1}\n{b2}\n");
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    // c1 introduces src_z.txt (older; alphabetically last).
    make_commit(td.path(), "src_z.txt", block.as_bytes(), "c1");
    let c1 = head_hash(td.path());
    // c2 introduces an identical src_a.txt (newer; alphabetically first).
    make_commit(td.path(), "src_a.txt", block.as_bytes(), "c2");
    let c2 = head_hash(td.path());
    // c3 adds dst.txt copying the block; both sources are unchanged in c3,
    // so only -C -C (level 2, whole-tree) sees them as candidates.
    make_commit(td.path(), "dst.txt", block.as_bytes(), "c3");

    let out = run_in(td.path(), &["blame", "-C", "-C", "dst.txt"]);
    assert!(out.status.success(), "blame -C -C failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.lines().all(|l| l.starts_with(&c1[..12])),
        "tie-break must credit the older ancestor source (c1/src_z), not \
         the newer src_a ({}): {stdout:?}",
        &c2[..12]
    );
}

#[test]
fn blame_c_copy_tiebreak_older_source_wins_regardless_of_path_order() {
    // #527 guard: the mirror of the tracer — the older source is now
    // alphabetically FIRST (src_a). git still credits the older commit, so
    // the tie-break must pick by ancestry, not "prefer the last candidate."
    // Pinned against git 2.50.1: `git blame -C -C dst.txt` credits c1.
    let b1 = "fn compute_alpha_beta_gamma() { let x = 1234567; }";
    let b2 = "fn compute_delta_epsilon_ze() { let y = 7654321; }";
    let block = format!("{b1}\n{b2}\n");
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "src_a.txt", block.as_bytes(), "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "src_z.txt", block.as_bytes(), "c2");
    let c2 = head_hash(td.path());
    make_commit(td.path(), "dst.txt", block.as_bytes(), "c3");

    let out = run_in(td.path(), &["blame", "-C", "-C", "dst.txt"]);
    assert!(out.status.success(), "blame -C -C failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.lines().all(|l| l.starts_with(&c1[..12])),
        "tie-break must credit the older ancestor source (c1/src_a), not \
         the newer src_z ({}): {stdout:?}",
        &c2[..12]
    );
}

#[test]
fn blame_porcelain_matches_git_field_block_with_boundary() {
    // #524: grouped porcelain. c1 introduces 3 lines (a boundary/root
    // commit); c2 edits line 2 and appends line 4. Field ordering and
    // grouping are pinned against git 2.50.1 (mkit's documented divergences:
    // 64-hex ids, Identity author, empty *-mail, +0000 tz, no `previous`).
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"alpha\nbravo\ncharlie\n", "c1 initial");
    make_commit(
        td.path(),
        "f.txt",
        b"alpha\nBRAVO2\ncharlie\ndelta\n",
        "c2 edit+add",
    );

    let out = run_in(td.path(), &["blame", "--porcelain", "f.txt"]);
    assert!(out.status.success(), "blame --porcelain failed: {out:?}");
    let s = String::from_utf8(out.stdout).unwrap();
    let rows: Vec<&str> = s.lines().collect();

    // First header: "<64-hex> <orig> <final> <group-len>" then git's exact
    // field-block ordering, with the boundary marker on the root commit.
    let h0: Vec<&str> = rows[0].split(' ').collect();
    assert_eq!(h0.len(), 4, "header shape: {:?}", rows[0]);
    assert_eq!(h0[0].len(), 64, "mkit uses 64-hex ids");
    assert_eq!((h0[1], h0[2]), ("1", "1"), "orig+final line numbers");
    assert!(rows[1].starts_with("author ed25519:"), "{:?}", rows[1]);
    assert_eq!(rows[2], "author-mail <>");
    assert!(rows[3].starts_with("author-time "));
    assert_eq!(rows[4], "author-tz +0000");
    assert!(rows[5].starts_with("committer ed25519:"));
    assert_eq!(rows[6], "committer-mail <>");
    assert!(rows[7].starts_with("committer-time "));
    assert_eq!(rows[8], "committer-tz +0000");
    assert_eq!(rows[9], "summary c1 initial");
    assert_eq!(rows[10], "boundary");
    assert_eq!(rows[11], "filename f.txt");
    assert_eq!(rows[12], "\talpha");

    // Metadata is emitted once per commit (grouped): exactly 2 blocks.
    assert_eq!(
        s.lines().filter(|l| l.starts_with("author ")).count(),
        2,
        "grouped porcelain emits metadata once per commit"
    );
    // Only the root commit c1 is a boundary.
    assert_eq!(s.lines().filter(|l| *l == "boundary").count(), 1);
    // Content, in order, tab-prefixed.
    let content: Vec<&str> = s.lines().filter_map(|l| l.strip_prefix('\t')).collect();
    assert_eq!(content, ["alpha", "BRAVO2", "charlie", "delta"]);
}

#[test]
fn blame_line_porcelain_repeats_header_per_line() {
    // #524: --line-porcelain repeats the full metadata block for every line.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"alpha\nbravo\ncharlie\n", "c1");
    make_commit(td.path(), "f.txt", b"alpha\nBRAVO2\ncharlie\ndelta\n", "c2");

    let out = run_in(td.path(), &["blame", "--line-porcelain", "f.txt"]);
    assert!(
        out.status.success(),
        "blame --line-porcelain failed: {out:?}"
    );
    let s = String::from_utf8(out.stdout).unwrap();
    let content = s.lines().filter(|l| l.starts_with('\t')).count();
    let authors = s.lines().filter(|l| l.starts_with("author ")).count();
    assert_eq!(content, 4, "four content lines");
    assert_eq!(
        authors, content,
        "line-porcelain repeats the header for every line"
    );
}

#[test]
fn blame_porcelain_emits_copy_source_filename() {
    // #524: on a `-C` cross-file copy, the porcelain `filename` is the copy
    // SOURCE (git parity), and the block is credited to the source's origin.
    let b1 = "fn handler_alpha_beta_gamma() { compute_the_thing(); }";
    let b2 = "fn second_helper_delta_epsilon() { do_more(); }";
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", format!("{b1}\n{b2}\n").as_bytes(), "c1");
    // c2: shrink a.txt, add b.txt copying the block.
    fs::write(td.path().join("a.txt"), b"leftover\n").unwrap();
    fs::write(td.path().join("b.txt"), format!("{b1}\n{b2}\n")).unwrap();
    assert!(
        run_in(td.path(), &["add", "a.txt", "b.txt"])
            .status
            .success()
    );
    assert!(
        run_in(td.path(), &["commit", "-m", "c2 split"])
            .status
            .success()
    );

    let out = run_in(td.path(), &["blame", "-C", "--porcelain", "b.txt"]);
    assert!(out.status.success(), "blame -C --porcelain failed: {out:?}");
    let s = String::from_utf8(out.stdout).unwrap();
    assert!(
        s.lines().any(|l| l == "filename a.txt"),
        "copied block's porcelain filename is the source a.txt: {s}"
    );
    // Both copied lines are one group crediting the source's origin commit.
    let first = s.lines().next().unwrap();
    let h: Vec<&str> = first.split(' ').collect();
    assert_eq!(h[3], "2", "the two copied lines form one group: {first:?}");
}

#[test]
fn blame_ignore_rev_unknown_errors_like_git() {
    // git: `fatal: cannot find revision <rev> to ignore`. mkit matches the
    // text (with its own `error:` prefix and sysexits code, not git's 128).
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "first");
    let out = run_in(
        td.path(),
        &["blame", "--ignore-rev", "no-such-rev", "f.txt"],
    );
    assert!(
        !out.status.success(),
        "expected failure on unknown ignore-rev"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("cannot find revision no-such-rev to ignore"),
        "expected git-faithful ignore-rev diagnostic, got: {stderr}"
    );
}

#[test]
fn blame_ignore_revs_file_errors_are_git_faithful() {
    // A missing file and a malformed entry reproduce git's two messages.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "first");

    let missing = run_in(
        td.path(),
        &["blame", "--ignore-revs-file", "nope.txt", "f.txt"],
    );
    assert!(!missing.status.success());
    assert!(
        String::from_utf8(missing.stderr)
            .unwrap()
            .contains("could not open object name list: nope.txt"),
        "expected git-faithful missing-file diagnostic"
    );

    fs::write(td.path().join("bad.txt"), "zzznothex\n").unwrap();
    let bad = run_in(
        td.path(),
        &["blame", "--ignore-revs-file", "bad.txt", "f.txt"],
    );
    assert!(!bad.status.success());
    assert!(
        String::from_utf8(bad.stderr)
            .unwrap()
            .contains("invalid object name: zzznothex"),
        "expected git-faithful invalid-object-name diagnostic"
    );
}

#[test]
fn blame_ignore_rev_precise_requires_ignore_rev() {
    // `--ignore-rev-precise` only refines an active `--ignore-rev` /
    // `--ignore-revs-file` set; without one it has nothing to refine, so it
    // is a usage error rather than a silent no-op (#496).
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "first");
    let out = run_in(td.path(), &["blame", "--ignore-rev-precise", "f.txt"]);
    assert!(
        !out.status.success(),
        "expected --ignore-rev-precise without an ignore set to be rejected"
    );
    assert!(
        String::from_utf8(out.stderr)
            .unwrap()
            .contains("--ignore-rev-precise requires --ignore-rev or --ignore-revs-file"),
        "expected the documented usage error"
    );
}

#[test]
fn blame_ignore_rev_precise_diverges_from_positional_default() {
    // End-to-end (#496): a noise commit reorders three distinct-origin
    // lines around a fixed middle line and reindents them. Under -w the
    // matcher recognizes the middle-reordered line unchanged wherever it
    // landed, but the other two end up with no in-hunk counterpart at all,
    // so git's positional `--ignore-rev` default leaves them credited to
    // the noise commit. `--ignore-rev-precise` searches the whole parent
    // file by content and finds their true origins instead — a genuinely
    // divergent, documented mkit-only attribution. Mirrors the mkit-core
    // unit test `blame_ignore_rev_precise_reattributes_moved_reindented_lines`.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"keep\ntail\n", "c0");
    make_commit(td.path(), "f.txt", b"keep\nXXX\ntail\n", "c1");
    make_commit(td.path(), "f.txt", b"keep\nXXX\nYYY\ntail\n", "c2");
    make_commit(td.path(), "f.txt", b"keep\nXXX\nYYY\nZZZ\ntail\n", "c3");
    make_commit(
        td.path(),
        "f.txt",
        b"keep\n  ZZZ\n  YYY\n  XXX\ntail\n",
        "noise",
    );
    let noise = head_hash(td.path());

    let positional = run_in(td.path(), &["blame", "-w", "--ignore-rev", &noise, "f.txt"]);
    assert!(
        positional.status.success(),
        "positional blame failed: {positional:?}"
    );
    let positional_out = String::from_utf8(positional.stdout).unwrap();
    let positional_lines: Vec<&str> = positional_out.lines().collect();
    assert!(
        positional_lines[2].starts_with(&noise[..12]),
        "positional: YYY has no in-hunk counterpart, stays on the noise commit: {positional_lines:?}"
    );
    assert!(
        positional_lines[3].starts_with(&noise[..12]),
        "positional: XXX has no in-hunk counterpart, stays on the noise commit: {positional_lines:?}"
    );

    let precise = run_in(
        td.path(),
        &[
            "blame",
            "-w",
            "--ignore-rev",
            &noise,
            "--ignore-rev-precise",
            "f.txt",
        ],
    );
    assert!(
        precise.status.success(),
        "precise blame failed: {precise:?}"
    );
    let precise_out = String::from_utf8(precise.stdout).unwrap();
    let precise_lines: Vec<&str> = precise_out.lines().collect();
    assert!(
        !precise_lines[2].starts_with(&noise[..12]),
        "precise: YYY is reattributed off the noise commit: {precise_lines:?}"
    );
    assert!(
        !precise_lines[3].starts_with(&noise[..12]),
        "precise: XXX is reattributed off the noise commit: {precise_lines:?}"
    );
    assert_ne!(
        positional_out, precise_out,
        "precise mode must produce a genuinely different (divergent) attribution here"
    );
}

#[test]
fn blame_reverse_attributes_lines_to_last_surviving_commit() {
    // `--reverse <start>..<end>` blames the start version and attributes
    // each line to the last commit it survived in. Mirrors real
    // `git blame --reverse` (verified field-by-field).
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"keep\ndoomed\nalso\n", "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"keep\ndoomed\nalso\nextra\n", "c2");
    let c2 = head_hash(td.path());
    make_commit(
        td.path(),
        "f.txt",
        b"keep\nalso\nextra\n",
        "c3_removes_doomed",
    );
    make_commit(td.path(), "f.txt", b"keep\nalso\nextra2\n", "c4");
    let c4 = head_hash(td.path());

    let out = run_in(
        td.path(),
        &["blame", "--reverse", &format!("{c1}..{c4}"), "f.txt"],
    );
    assert!(out.status.success(), "blame --reverse failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 3, "blames the start (c1) version: {stdout:?}");
    assert!(lines[0].starts_with(&c4[..12]) && lines[0].ends_with("\tkeep"));
    assert!(
        lines[1].starts_with(&c2[..12]) && lines[1].ends_with("\tdoomed"),
        "doomed last existed in c2: {stdout:?}"
    );
    assert!(lines[2].starts_with(&c4[..12]) && lines[2].ends_with("\talso"));
}

#[test]
fn blame_reverse_open_end_defaults_to_head() {
    // `<start>..` defaults <end> to HEAD.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\n", "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"a\nB2\n", "c2");
    let c2 = head_hash(td.path());

    let out = run_in(
        td.path(),
        &["blame", "--reverse", &format!("{c1}.."), "f.txt"],
    );
    assert!(out.status.success(), "open-end reverse failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    let lines: Vec<&str> = stdout.lines().collect();
    // `a` survives to HEAD (c2); `b` is changed in c2 → last in c1.
    assert!(
        lines[0].starts_with(&c2[..12]),
        "a survives to HEAD: {stdout:?}"
    );
    assert!(
        lines[1].starts_with(&c1[..12]),
        "b last existed in c1: {stdout:?}"
    );
}

#[test]
fn blame_reverse_requires_a_range() {
    // Clear, non-cryptic errors (a deliberate divergence from git's
    // "dig up from" phrasing) for the three malformed-argument cases.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "c1");
    let c1 = head_hash(td.path());

    // No range at all.
    let none = run_in(td.path(), &["blame", "--reverse", "f.txt"]);
    assert!(!none.status.success());
    assert!(
        String::from_utf8(none.stderr)
            .unwrap()
            .contains("requires a <start>..<end>"),
        "expected a clear missing-range error"
    );
    // A bare revision (no `..`).
    let bare = run_in(td.path(), &["blame", "--reverse", &c1, "f.txt"]);
    assert!(!bare.status.success());
    assert!(
        String::from_utf8(bare.stderr)
            .unwrap()
            .contains("<start>..<end>"),
        "expected a clear bare-revision error"
    );
    // An open start.
    let open = run_in(
        td.path(),
        &["blame", "--reverse", &format!("..{c1}"), "f.txt"],
    );
    assert!(!open.status.success());
    assert!(
        String::from_utf8(open.stderr)
            .unwrap()
            .contains("explicit <start>"),
        "expected a clear open-start error"
    );
}

#[test]
fn blame_reverse_rejects_malformed_and_empty_ranges() {
    // Review: triple-dot / extra-dot, an omitted file, and an empty range
    // each get a clear error instead of a cryptic revspec failure or a
    // silent success.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "c1");
    let c1 = head_hash(td.path());
    make_commit(td.path(), "f.txt", b"a\nb\n", "c2");
    let c2 = head_hash(td.path());

    // Triple-dot (git's symmetric range) is not supported.
    let triple = run_in(
        td.path(),
        &["blame", "--reverse", &format!("{c1}...{c2}"), "f.txt"],
    );
    assert!(!triple.status.success());
    assert!(
        String::from_utf8(triple.stderr)
            .unwrap()
            .contains("single <start>..<end>"),
        "expected a clear triple-dot error"
    );
    // Extra `..` (a..b..c).
    let extra = run_in(
        td.path(),
        &["blame", "--reverse", &format!("{c1}..{c2}..{c1}"), "f.txt"],
    );
    assert!(!extra.status.success());
    assert!(
        String::from_utf8(extra.stderr)
            .unwrap()
            .contains("single <start>..<end>"),
        "expected a clear extra-dot error"
    );
    // File omitted: the lone `a..b` positional is swallowed as the filename.
    let no_file = run_in(td.path(), &["blame", "--reverse", &format!("{c1}..{c2}")]);
    assert!(!no_file.status.success());
    assert!(
        String::from_utf8(no_file.stderr)
            .unwrap()
            .contains("missing <file>"),
        "expected a missing-file hint, not a bogus range error"
    );
    // Empty range (start == end) is rejected, matching git.
    let empty = run_in(
        td.path(),
        &["blame", "--reverse", &format!("{c1}..{c1}"), "f.txt"],
    );
    assert!(!empty.status.success());
    assert!(
        String::from_utf8(empty.stderr)
            .unwrap()
            .contains("empty revision range"),
        "expected an empty-range error"
    );
}

#[test]
fn blame_reverse_rejects_detection_flags() {
    // `--reverse` resolves survival via the LCS matcher only, so combining
    // it with -M/-C or --ignore-rev is rejected rather than silently
    // ignored.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"a\n", "c1");
    let c1 = head_hash(td.path());
    let range = format!("{c1}..");

    for flag in [vec!["-M"], vec!["-C"], vec!["--ignore-rev", &c1]] {
        let mut args = vec!["blame", "--reverse", &range, "f.txt"];
        args.extend(flag.iter().copied());
        let out = run_in(td.path(), &args);
        assert!(
            !out.status.success(),
            "expected --reverse + {flag:?} to be rejected"
        );
        assert!(
            String::from_utf8(out.stderr)
                .unwrap()
                .contains("--reverse cannot be combined"),
            "expected a clear combination error for {flag:?}"
        );
    }
}

#[test]
fn blame_merge_aware_vs_first_parent() {
    // base → {main adds a top line, feature appends a line} → merge.
    // Default blame credits the appended line to the feature commit
    // (merge-aware); --first-parent credits it to the merge. Verified
    // against real `git blame` / `git blame --first-parent`.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "f.txt", b"base1\nbase2\n", "base");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());
    assert!(run_in(td.path(), &["checkout", "feature"]).status.success());
    make_commit(td.path(), "f.txt", b"base1\nbase2\nfeature-line\n", "feat");
    let feat = ref_hash(td.path(), "feature"); // we are on `feature` here
    assert!(run_in(td.path(), &["checkout", "main"]).status.success());
    make_commit(td.path(), "f.txt", b"main-line\nbase1\nbase2\n", "main");
    let merge_out = run_in(td.path(), &["merge", "feature"]);
    assert!(merge_out.status.success(), "merge failed: {merge_out:?}");
    let merge = head_hash(td.path());

    // Default (merge-aware): the feature line traces to the feature commit.
    let def = run_in(td.path(), &["blame", "f.txt"]);
    assert!(def.status.success(), "blame failed: {def:?}");
    let dout = String::from_utf8(def.stdout).unwrap();
    let dlines: Vec<&str> = dout.lines().collect();
    assert_eq!(dlines.len(), 4, "merged file has 4 lines: {dout:?}");
    assert!(
        dlines[3].starts_with(&feat[..12]) && dlines[3].ends_with("\tfeature-line"),
        "default credits the feature line to the feature commit: {dout:?}"
    );
    assert!(
        dlines.iter().all(|l| !l.starts_with(&merge[..12])),
        "no line is credited to the merge under merge-aware blame: {dout:?}"
    );

    // --first-parent: the feature line first appears (to that walk) at the
    // merge, so it is credited there.
    let fp = run_in(td.path(), &["blame", "--first-parent", "f.txt"]);
    assert!(fp.status.success(), "blame --first-parent failed: {fp:?}");
    let fout = String::from_utf8(fp.stdout).unwrap();
    let flines: Vec<&str> = fout.lines().collect();
    assert!(
        flines[3].starts_with(&merge[..12]),
        "--first-parent credits the feature line to the merge: {fout:?}"
    );
}

// ---------- serve ---------------------------------------------------------

#[test]
fn serve_errors_on_missing_path() {
    // `mkit serve` without a path should fail with a usage error.
    // Clap renders "Usage:" (capital U) in its error output; match
    // case-insensitively so the test isn't tied to clap's exact
    // formatting.
    let td = tempfile::tempdir().unwrap();
    let out = run_in(td.path(), &["serve"]);
    assert!(!out.status.success());
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.to_lowercase().contains("usage"),
        "expected usage diagnostic on stderr, got: {stderr}"
    );
}

#[test]
fn serve_rejects_bad_handshake_and_exits() {
    use std::io::Write;
    use std::process::Stdio;

    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());

    let mut child = Command::new(mkit_bin())
        .args(["serve", td.path().to_str().unwrap()])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn serve");

    // Send a single frame with the wrong opcode (should be OP_HELLO = 0x00).
    // Frame = [op=0x01][len=0u32].
    let frame = [0x01, 0, 0, 0, 0];
    child.stdin.as_mut().unwrap().write_all(&frame).unwrap();
    drop(child.stdin.take());
    let out = child.wait_with_output().expect("wait serve");
    // The server rejects the bad handshake and exits with the specific
    // PROTOCOL_ERROR code (76) — not a panic (101), not a generic 1.
    assert_eq!(
        out.status.code(),
        Some(76),
        "serve must exit PROTOCOL_ERROR (76) on a bad handshake: {out:?}"
    );
}

// ---------- sparse-checkout ----------------------------------------------

#[test]
fn sparse_checkout_set_without_patterns_errors() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    let out = run_in(td.path(), &["sparse-checkout", "set"]);
    assert!(!out.status.success());
}

#[test]
fn sparse_checkout_roundtrips_patterns() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"x\n", "c1");
    assert!(
        run_in(td.path(), &["sparse-checkout", "set", "a.txt"])
            .status
            .success()
    );
    let out = run_in(td.path(), &["sparse-checkout", "list"]);
    assert!(out.status.success());
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("a.txt"));
    assert!(
        run_in(td.path(), &["sparse-checkout", "disable"])
            .status
            .success()
    );
}

#[test]
fn sparse_checkout_set_refuses_dirty_tracked_file_inside_sparse_set() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"v1\n", "c1");

    fs::write(td.path().join("a.txt"), b"local edit\n").unwrap();
    let out = run_in(td.path(), &["sparse-checkout", "set", "a.txt"]);

    assert!(!out.status.success(), "sparse set should fail: {out:?}");
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(stderr.contains("restore would overwrite local changes"));
    assert_eq!(fs::read(td.path().join("a.txt")).unwrap(), b"local edit\n");
    assert!(!td.path().join(".mkit/sparse-checkout").exists());
}

#[test]
fn sparse_checkout_set_allows_dirty_tracked_file_outside_sparse_set() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    fs::write(td.path().join("a.txt"), b"a\n").unwrap();
    fs::write(td.path().join("b.txt"), b"b\n").unwrap();
    assert!(run_in(td.path(), &["add", "."]).status.success());
    assert!(run_in(td.path(), &["commit", "-m", "c1"]).status.success());

    fs::write(td.path().join("b.txt"), b"local b\n").unwrap();
    let out = run_in(td.path(), &["sparse-checkout", "set", "a.txt"]);

    assert!(out.status.success(), "sparse set failed: {out:?}");
    assert_eq!(fs::read(td.path().join("b.txt")).unwrap(), b"local b\n");
    assert_eq!(
        fs::read_to_string(td.path().join(".mkit/sparse-checkout")).unwrap(),
        "a.txt\n"
    );
}

#[test]
fn sparse_checkout_disable_refuses_untracked_file_that_full_restore_would_remove() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"a\n", "c1");
    assert!(
        run_in(td.path(), &["sparse-checkout", "set", "a.txt"])
            .status
            .success()
    );

    fs::write(td.path().join("notes.txt"), b"local notes\n").unwrap();
    let out = run_in(td.path(), &["sparse-checkout", "disable"]);

    assert!(!out.status.success(), "sparse disable should fail: {out:?}");
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(stderr.contains("restore would remove untracked path"));
    assert_eq!(
        fs::read(td.path().join("notes.txt")).unwrap(),
        b"local notes\n"
    );
    assert_eq!(
        fs::read_to_string(td.path().join(".mkit/sparse-checkout")).unwrap(),
        "a.txt\n"
    );
}

// ---------- diff (revision resolver, #207) -------------------------------

#[test]
fn diff_head_tilde_one_shows_second_commit_change() {
    // PR-B / #207: `mkit diff HEAD~1` must resolve the revision to its
    // tree and emit a real diff against the worktree (which mirrors the
    // tip), NOT silently treat `HEAD~1` as a pathspec and exit empty.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");
    make_commit(td.path(), "b.txt", b"two\n", "c2");

    let out = run_in(td.path(), &["diff", "HEAD~1"]);
    assert!(out.status.success(), "diff HEAD~1 failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    // The worktree (== HEAD == c2) differs from HEAD~1 (== c1) by b.txt.
    assert!(
        stdout.contains("b.txt"),
        "expected b.txt in diff HEAD~1 output, got: {stdout:?}"
    );
}

#[test]
fn diff_branch_ref_resolves_and_diffs() {
    // `mkit diff <branch>` resolves the branch tip to its tree.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");
    assert!(run_in(td.path(), &["branch", "base"]).status.success());
    make_commit(td.path(), "b.txt", b"two\n", "c2");

    let out = run_in(td.path(), &["diff", "base"]);
    assert!(out.status.success(), "diff base failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.contains("b.txt"),
        "expected b.txt in diff base output, got: {stdout:?}"
    );
}

#[test]
fn diff_bad_revision_errors_not_silent_empty() {
    // A hash-shaped arg that resolves to nothing is a hard error (#207),
    // not a silent empty diff.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");

    let bogus = "ab".repeat(32);
    let out = run_in(td.path(), &["diff", &bogus]);
    assert!(!out.status.success(), "bad revision should fail: {out:?}");
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.to_lowercase().contains("revision"),
        "expected a revision diagnostic, got: {stderr}"
    );
}

#[test]
fn diff_staged_with_revision_is_usage_error() {
    // #223: `--staged` already fixes HEAD vs index; an explicit revision
    // is contradictory.
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");

    let out = run_in(td.path(), &["diff", "--staged", "HEAD"]);
    assert!(!out.status.success(), "--staged HEAD should fail: {out:?}");
}

// ---------- branch / tag ref-write safety (#206) -------------------------

#[test]
fn branch_create_collision_is_rejected() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");
    assert!(run_in(td.path(), &["branch", "feature"]).status.success());

    let out = run_in(td.path(), &["branch", "feature"]);
    assert!(
        !out.status.success(),
        "duplicate branch should fail: {out:?}"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("already exists"),
        "expected collision diagnostic, got: {stderr}"
    );
}

#[test]
fn branch_delete_current_is_rejected() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");
    // HEAD points at `main`; deleting it must be refused.
    let out = run_in(td.path(), &["branch", "-d", "main"]);
    assert!(
        !out.status.success(),
        "deleting current branch should fail: {out:?}"
    );
}

#[test]
fn tag_create_collision_is_rejected() {
    let td = tempfile::tempdir().unwrap();
    init_repo(td.path());
    make_commit(td.path(), "a.txt", b"one\n", "c1");
    assert!(run_in(td.path(), &["tag", "v1"]).status.success());

    let out = run_in(td.path(), &["tag", "v1"]);
    assert!(!out.status.success(), "duplicate tag should fail: {out:?}");
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("already exists"),
        "expected collision diagnostic, got: {stderr}"
    );
}