brygge 0.8.1

Carry version-control history from one system to another: decode Git, Mercurial, Subversion and CVS into a portable, verifiable IR artifact, with every inference marked and every loss recorded, and encode it into a target.
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
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
//! Command integration tests (handoff `cli-and-verify-handoff-v2.md` §5): build fixture repos, then
//! decode → inspect → verify, asserting outcomes, exit classes, and — for `verify` — that every check can
//! actually fail. Git/hg/svnadmin-dependent tests skip when the tool is absent.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command as PCommand;
use std::sync::atomic::{AtomicU64, Ordering};

use super::*;
use crate::cli::{Format, SourceKind};
use brygge_ir::builder::{AtomDraft, IrBuilder};
use brygge_ir::model::{
    ChangedPart, CopyRecord, DropRecord, Identity, ImportProvenance, LossBoundary, MetadataClaims,
    RefRecord, TransformRecord,
};

static COUNTER: AtomicU64 = AtomicU64::new(0);

fn git_available() -> bool {
    PCommand::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

struct TempRepo {
    dir: PathBuf,
}

impl Drop for TempRepo {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

impl TempRepo {
    fn new() -> Self {
        let r = Self::new_plain();
        r.git(&["init", "-q", "--initial-branch=main"]);
        r
    }

    /// A fresh temporary directory with no `git init` — for sources (CVS: a plain directory of `,v`
    /// files) that have no real dependency on git, so their tests run with no `git` on `PATH` (review
    /// 082 F-4).
    fn new_plain() -> Self {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "brygge-cli-test-{}-{nanos}-{n}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        Self { dir }
    }

    fn path(&self) -> &Path {
        &self.dir
    }

    fn git(&self, args: &[&str]) -> String {
        let out = PCommand::new("git")
            .current_dir(&self.dir)
            .args(args)
            .env("GIT_AUTHOR_NAME", "A U Thor")
            .env("GIT_AUTHOR_EMAIL", "author@example.com")
            .env("GIT_AUTHOR_DATE", "2005-04-07T22:13:13 +0000")
            .env("GIT_COMMITTER_NAME", "C O Mitter")
            .env("GIT_COMMITTER_EMAIL", "committer@example.com")
            .env("GIT_COMMITTER_DATE", "2005-04-07T22:13:13 +0000")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .output()
            .expect("run git");
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    fn commit(&self, file: &str, contents: &str, msg: &str) {
        std::fs::write(self.dir.join(file), contents).unwrap();
        self.git(&["add", "-A"]);
        self.git(&["-c", "commit.gpgsign=false", "commit", "-q", "-m", msg]);
    }
}

fn simple_repo(seed: &str) -> TempRepo {
    let r = TempRepo::new();
    r.commit("a.txt", &format!("{seed} one\n"), "c1");
    r.commit("a.txt", &format!("{seed} two\n"), "c2");
    r
}

/// Removes a directory on drop, even if a test panics on an assertion before reaching its own explicit
/// cleanup (CR-16 review A-1).
struct CleanupDir(PathBuf);

impl Drop for CleanupDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn tmp_ir_path(tag: &str) -> PathBuf {
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir().join(format!("brygge-cli-{tag}-{}-{n}.ir", std::process::id()))
}

// ---- decode / inspect / verify roundtrip -----------------------------------------------------------

// ---- --spill-dir (RFC 015 D-3/D-3a) ----------------------------------------------------------------

#[test]
fn spill_dir_missing_is_a_usage_error() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("spill-missing");
    let out = repo.dir.join("out.ir");
    let missing = repo.dir.join("does-not-exist");
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        Some(&missing),
        Format::Machine,
    );
    assert_eq!(code, exit::USAGE);
    assert!(!out.exists(), "no artifact on a usage error");
}

#[test]
fn spill_dir_a_file_not_a_directory_is_a_usage_error() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("spill-file");
    let out = repo.dir.join("out.ir");
    let file = repo.dir.join("a-plain-file");
    std::fs::write(&file, b"not a directory").unwrap();
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        Some(&file),
        Format::Machine,
    );
    assert_eq!(code, exit::USAGE);
    assert!(!out.exists(), "no artifact on a usage error");
}

#[test]
fn spill_dir_given_a_good_directory_is_used_and_the_artifact_is_byte_identical() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("spill-good");
    let default_out = repo.dir.join("default.ir");
    let spill_out = repo.dir.join("spill.ir");
    let spill_dir = repo.dir.join("spill");
    std::fs::create_dir_all(&spill_dir).unwrap();

    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &default_out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &spill_out,
            false,
            false,
            false,
            Some(&spill_dir),
            Format::Machine
        ),
        exit::CLEAN
    );
    assert_eq!(
        std::fs::read(&default_out).unwrap(),
        std::fs::read(&spill_out).unwrap(),
        "--spill-dir never changes the artifact"
    );
    assert_eq!(
        std::fs::read_dir(&spill_dir).unwrap().count(),
        0,
        "the spill file is never left behind"
    );
}

#[test]
fn verify_spill_dir_missing_is_a_usage_error() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("verify-spill-missing");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let missing = repo.dir.join("does-not-exist");
    let code = run_verify(
        &out,
        Some(repo.path()),
        None,
        Some(&missing),
        Format::Machine,
    );
    assert_eq!(code, exit::USAGE);
}

#[test]
fn verify_spill_dir_a_file_not_a_directory_is_a_usage_error() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("verify-spill-file");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let file = repo.dir.join("a-plain-file");
    std::fs::write(&file, b"not a directory").unwrap();
    let code = run_verify(&out, Some(repo.path()), None, Some(&file), Format::Machine);
    assert_eq!(code, exit::USAGE);
}

#[test]
fn verify_spill_dir_given_a_good_directory_is_used_and_left_empty_and_the_verdict_is_unchanged() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("verify-spill-good");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let spill_dir = repo.dir.join("spill");
    std::fs::create_dir_all(&spill_dir).unwrap();

    let without_spill_dir = run_verify(&out, Some(repo.path()), None, None, Format::Machine);
    let with_spill_dir = run_verify(
        &out,
        Some(repo.path()),
        None,
        Some(&spill_dir),
        Format::Machine,
    );
    assert_eq!(
        without_spill_dir, with_spill_dir,
        "--spill-dir never changes the verdict"
    );
    assert_eq!(with_spill_dir, exit::CLEAN);
    assert_eq!(
        std::fs::read_dir(&spill_dir).unwrap().count(),
        0,
        "the spill file is never left behind"
    );
}

#[test]
fn decode_inspect_verify_roundtrip() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("x");
    let out = repo.dir.join("out.ir");

    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    assert!(out.exists(), "the artifact was written");
    assert_eq!(run_inspect(&out, false, Format::Human), exit::CLEAN);
    assert_eq!(run_inspect(&out, true, Format::Machine), exit::CLEAN);
    assert_eq!(
        run_verify(&out, None, None, None, Format::Machine),
        exit::CLEAN
    );
    assert_eq!(
        run_verify(&out, Some(repo.path()), None, None, Format::Human),
        exit::CLEAN,
        "the artifact corresponds to its source (VF-2)"
    );
}

#[test]
fn verify_internal_catches_tamper_with_no_source() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("y");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );

    let mut bytes = std::fs::read(&out).unwrap();
    let last = bytes.len() - 1;
    bytes[last] ^= 0xff; // corrupt the final blob byte
    std::fs::write(&out, &bytes).unwrap();

    assert_eq!(
        run_verify(&out, None, None, None, Format::Machine),
        exit::VERIFY_FAILED,
        "a tampered artifact fails integrity, no source needed (VF-3)"
    );
}

#[test]
fn verify_against_source_detects_a_mismatch() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("x");
    let other = simple_repo("z"); // different content and history
    let other_out = other.dir.join("o.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            other.path(),
            &other_out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );

    // Verifying one repo's artifact against a different source must fail.
    assert_eq!(
        run_verify(&other_out, Some(repo.path()), None, None, Format::Human),
        exit::VERIFY_FAILED
    );
}

#[test]
fn a_failing_internal_check_with_a_corresponding_source_still_reports_against_source_separately() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("sep");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    // Corrupt the artifact (integrity fails) but keep the original source around.
    let mut bytes = std::fs::read(&out).unwrap();
    let last = bytes.len() - 1;
    bytes[last] ^= 0xff;
    std::fs::write(&out, &bytes).unwrap();

    // The two claims are independent (VF-4): a broken internal check does not skip against-source, but
    // integrity failure means there is no decoded Ir to re-derive against, so against-source is not-run
    // and the overall result is still fail (exit 50) from the internal side alone.
    assert_eq!(
        run_verify(&out, Some(repo.path()), None, None, Format::Human),
        exit::VERIFY_FAILED
    );
}

#[test]
fn against_source_with_a_nonexistent_path_is_not_checked_not_a_mismatch() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("nonexistent-source");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let bogus = std::env::temp_dir().join("brygge-cli-does-not-exist-at-all");
    assert_eq!(
        run_verify(&out, Some(&bogus), None, None, Format::Machine),
        exit::FAILURE,
        "a source that cannot be re-decoded is 'not checked' — a runtime failure (exit 1), never a \
         claimed mismatch (review 003 R-1)"
    );
}

#[test]
fn a_genuine_internal_failure_dominates_the_exit_even_when_against_source_is_also_not_checked() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let a1 = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    // A `Modify` of a path that was never added is a genuine `replay` failure, but the artifact still
    // decodes (integrity passes), so `ir_opt` is `Some` and against-source is actually attempted. (A
    // duplicate ref used to serve here; the builder and the reader now both refuse one, so it never
    // reaches `verify`.)
    b.add_atom(AtomDraft {
        parents: vec![a1],
        ops: vec![PathOp::Modify {
            path: "never-added".into(),
            blob,
            mode: 0o100_644,
            status: EpistemicStatus::Stated,
        }],
        copies: vec![],
        metadata: MetadataClaims::default(),
        source: src(brygge_ir::SourceKind::Git, b"c2"),
        status: EpistemicStatus::Stated,
    })
    .unwrap();
    let ir = b.finish().unwrap();
    let path = tmp_ir_path("notchecked-plus-fail");
    std::fs::write(&path, brygge_ir::to_bytes(&ir)).unwrap();

    let bogus = std::env::temp_dir().join("brygge-cli-does-not-exist-at-all-2");
    assert_eq!(
        run_verify(&path, Some(&bogus), None, None, Format::Machine),
        exit::VERIFY_FAILED,
        "a genuine internal failure dominates the exit class even though against-source also could \
         not be checked (review 003 R-1)"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn decode_a_real_clone_succeeds_and_verifies_against_source() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let origin = simple_repo("clone-src");
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let clone_dir =
        std::env::temp_dir().join(format!("brygge-cli-clone-{}-{n}", std::process::id()));
    let _cleanup = CleanupDir(clone_dir.clone());
    let status = PCommand::new("git")
        .args(["clone", "-q"])
        .arg(origin.path())
        .arg(&clone_dir)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .status()
        .expect("run git clone");
    assert!(status.success(), "git clone failed");
    assert!(
        clone_dir.join(".git/refs/remotes/origin/HEAD").exists(),
        "a real clone creates the exact symbolic ref CR-16 covers"
    );

    let clone_out = clone_dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            &clone_dir,
            &clone_out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN,
        "a clone's symbolic HEAD is a representation-class drop, still a clean import (CR-16)"
    );
    assert!(clone_out.exists());
    assert_eq!(
        run_verify(&clone_out, Some(&clone_dir), None, None, Format::Human),
        exit::CLEAN,
        "verify --against-source succeeds on a real clone (CR-16)"
    );

    let origin_out = origin.dir.join("origin-out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            origin.path(),
            &origin_out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let origin_ir = brygge_ir::from_bytes(&std::fs::read(&origin_out).unwrap())
        .unwrap()
        .ir;
    let clone_ir = brygge_ir::from_bytes(&std::fs::read(&clone_out).unwrap())
        .unwrap()
        .ir;
    let origin_ids: std::collections::BTreeSet<_> = origin_ir
        .atoms
        .iter()
        .map(|a| a.source.atom_id.clone())
        .collect();
    let clone_ids: std::collections::BTreeSet<_> = clone_ir
        .atoms
        .iter()
        .map(|a| a.source.atom_id.clone())
        .collect();
    assert_eq!(
        origin_ids, clone_ids,
        "the clone carries exactly the origin's commits"
    );
}

#[test]
fn guard_decoder_catches_a_panic_and_returns_a_typed_fault() {
    let result = guard_decoder(|| -> u32 { panic!("boom") });
    match result {
        Err(msg) => {
            assert!(msg.contains("internal decoder fault"), "{msg}");
            assert!(msg.contains("boom"), "{msg}");
            assert!(msg.contains("brygge bug"), "{msg}");
        }
        Ok(_) => panic!("expected the panic to be caught, not propagated"),
    }
}

#[test]
fn guard_decoder_passes_through_a_normal_result() {
    assert_eq!(guard_decoder(|| 42u32), Ok(42));
}

#[test]
fn decode_of_a_submodule_exits_floor_refusal() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("s");
    let head = repo.git(&["rev-parse", "HEAD"]);
    repo.git(&[
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("160000,{head},sub"),
    ]);
    repo.git(&[
        "-c",
        "commit.gpgsign=false",
        "commit",
        "-q",
        "-m",
        "add gitlink",
    ]);
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Human
        ),
        exit::FLOOR_REFUSAL
    );
    assert!(!out.exists(), "no artifact is written on a refusal");
}

// ---- RFC 010 §2.6: a ResourceLimit from any decoder maps to exit 20 --------------------------------

#[test]
fn a_resource_limit_from_every_decoder_maps_to_floor_refusal_with_the_stated_message() {
    let (code, msg) = map_cvs_error(CvsError::ResourceLimit {
        what: "an RCS file".to_string(),
        ceiling: "100 bytes".to_string(),
    });
    assert_eq!(code, exit::FLOOR_REFUSAL);
    assert_eq!(
        msg,
        "refused: an RCS file exceeds brygge's ceiling (100 bytes)"
    );

    let (code, msg) = map_svn_error(SvnError::ResourceLimit {
        what: "the dumpstream".to_string(),
        ceiling: "100 bytes".to_string(),
    });
    assert_eq!(code, exit::FLOOR_REFUSAL);
    assert_eq!(
        msg,
        "refused: the dumpstream exceeds brygge's ceiling (100 bytes)"
    );

    let (code, msg) = map_git_error(GitError::ResourceLimit {
        what: "a blob".to_string(),
        ceiling: "100 bytes".to_string(),
    });
    assert_eq!(code, exit::FLOOR_REFUSAL);
    assert_eq!(msg, "refused: a blob exceeds brygge's ceiling (100 bytes)");

    let (code, msg) = map_hg_error(HgError::ResourceLimit {
        what: "a decompressed revision".to_string(),
        ceiling: "100 bytes".to_string(),
    });
    assert_eq!(code, exit::FLOOR_REFUSAL);
    assert_eq!(
        msg,
        "refused: a decompressed revision exceeds brygge's ceiling (100 bytes)"
    );
}

// ---- review 159 C-2: a `ResourceLimit` from `transform authors`'s own `Edit::finish` maps to the ----
// ---- same exit 20 a decoder's does, not the generic runtime-failure code ----------------------------

#[test]
fn a_resource_limit_from_transform_authors_finish_maps_to_floor_refusal() {
    let (code, msg) = map_transform_finish_err(brygge_ir::Error::ResourceLimit {
        what: "the path-operation total in this artifact".to_string(),
        ceiling: "100 operations".to_string(),
    });
    assert_eq!(code, exit::FLOOR_REFUSAL);
    assert_eq!(
        msg,
        "refused: the path-operation total in this artifact exceeds brygge's ceiling (100 operations)"
    );
}

#[test]
fn every_other_transform_finish_error_stays_a_plain_failure() {
    let (code, msg) = map_transform_finish_err(brygge_ir::Error::Invariant("x".to_string()));
    assert_eq!(code, exit::FAILURE);
    assert_eq!(
        msg,
        "the transform's own output was refused: brygge-ir invariant violated: x"
    );
}

#[test]
fn missing_artifact_is_a_plain_failure() {
    let missing = std::env::temp_dir().join("brygge-cli-nope-does-not-exist.ir");
    assert_eq!(run_inspect(&missing, false, Format::Human), exit::FAILURE);
    assert_eq!(
        run_verify(&missing, None, None, None, Format::Machine),
        exit::FAILURE
    );
}

// ---- CR-21: the before-the-run faithfulness statement ----------------------------------------------

#[test]
fn faithfulness_statement_text_per_source() {
    let git = faithfulness_statement(SourceKind::Git);
    assert!(git.starts_with("Git:"));
    assert!(git.contains("--infer-renames"));
    assert!(git.contains("Unverifiable"));

    let hg = faithfulness_statement(SourceKind::Hg);
    assert!(hg.starts_with("Mercurial:"));
    assert!(hg.contains("Unverifiable"));

    let svn = faithfulness_statement(SourceKind::Svn);
    assert!(svn.starts_with("Subversion:"));
    assert!(svn.contains("--reconstruct-refs"));
    assert!(svn.contains("Unverifiable"));

    let cvs = faithfulness_statement(SourceKind::Cvs);
    assert!(cvs.starts_with("CVS has no atomic commits"));
    assert!(cvs.contains("Unverifiable"));
    // CVS corrections handoff §2.1: the main-line-only limitation is stated up front, every run; RFC 013 D-3
    // says when branches are imported.
    assert!(cvs.contains("Branch history is imported only with --reconstruct-refs"));
    assert!(cvs.contains("otherwise the main line is."));
}

// A subprocess test proving the statement reaches real stderr even when decode then fails lives in
// `tests/cli_integration.rs` (unit tests in `src/` cannot see `CARGO_BIN_EXE_brygge`).

// ---- CR-13: atomic artifact writes ------------------------------------------------------------------

fn tmp_siblings(dir: &Path) -> Vec<PathBuf> {
    std::fs::read_dir(dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.contains(".brygge-tmp-"))
        })
        .collect()
}

#[test]
fn a_pre_existing_artifact_survives_a_failing_decode_and_leaves_no_temp_file() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("atomic");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let good_bytes = std::fs::read(&out).unwrap();

    // Now make the same repo un-decodable (a submodule) and decode again to the same --out.
    let head = repo.git(&["rev-parse", "HEAD"]);
    repo.git(&[
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("160000,{head},sub"),
    ]);
    repo.git(&[
        "-c",
        "commit.gpgsign=false",
        "commit",
        "-q",
        "-m",
        "break it",
    ]);
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::FLOOR_REFUSAL
    );

    assert_eq!(
        std::fs::read(&out).unwrap(),
        good_bytes,
        "the pre-existing artifact is untouched by a failed decode"
    );
    assert!(
        tmp_siblings(&repo.dir).is_empty(),
        "no temp file remains after a failure"
    );
}

#[test]
fn a_successful_decode_replaces_the_existing_artifact_and_leaves_no_temp_file() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("replace");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let first_bytes = std::fs::read(&out).unwrap();

    repo.commit("a.txt", "a third state\n", "c3");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let second_bytes = std::fs::read(&out).unwrap();
    assert_ne!(first_bytes, second_bytes, "the artifact was replaced");
    assert!(tmp_siblings(&repo.dir).is_empty(), "no temp file remains");
}

// ---- inspect (CL-02) --------------------------------------------------------------------------------

#[test]
fn inspect_default_equals_decodes_end_of_run_report() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("eq");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    // `decode`'s end-of-run report and `inspect`'s default report both call
    // `brygge_ir::honesty::summary(&ir).render_*()` on the same artifact, so they are the same text by
    // construction; confirm it directly against the artifact read back from disk (FS-02).
    let ir = brygge_ir::from_bytes(&std::fs::read(&out).unwrap())
        .unwrap()
        .ir;
    assert_eq!(
        brygge_ir::honesty::summary(&ir).render_human(),
        brygge_ir::honesty::summary(&ir).render_human(),
        "reproducible (FS-02)"
    );
}

#[test]
fn inspect_atoms_adds_the_listing_and_reads_the_artifact_once() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("atoms");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let ir = brygge_ir::from_bytes(&std::fs::read(&out).unwrap())
        .unwrap()
        .ir;
    let human = render_atoms_human(&ir, brygge_ir::version::CURRENT);
    assert!(human.contains("atoms (topological order):"));
    assert!(human.contains("refs:") || ir.refs.is_empty());
    assert!(human.contains("loss boundary:"));
    let machine = render_atoms_machine(&ir, brygge_ir::version::CURRENT);
    assert!(machine.starts_with("inspect_version=4\n"));
    assert!(machine.contains("atom.0.id="));
}

#[test]
fn inspect_report_says_unverifiable_never_unverified() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("unverifiable");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let ir = brygge_ir::from_bytes(&std::fs::read(&out).unwrap())
        .unwrap()
        .ir;
    let human = brygge_ir::honesty::summary(&ir).render_human();
    assert!(human.contains("Unverifiable"));
    assert!(!human.contains("Unverified"));
}

#[test]
fn representation_drops_appear_only_on_the_not_history_line() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("split");
    let out = repo.dir.join("out.ir");
    assert_eq!(
        run_decode(
            SourceKind::Git,
            repo.path(),
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let ir = brygge_ir::from_bytes(&std::fs::read(&out).unwrap())
        .unwrap()
        .ir;
    let human = brygge_ir::honesty::summary(&ir).render_human();
    assert!(human.contains("not history (no content or claim lost):"));
    let after_split = human
        .split("dropped (recorded loss):")
        .nth(1)
        .expect("section present");
    assert!(!after_split.contains("representation"));
}

// ---- verify (CL-04, CR-02): every check can fail, built with IrBuilder -----------------------------

fn blank_provenance(kind: brygge_ir::SourceKind, decoder: &str) -> ImportProvenance {
    ImportProvenance {
        source: brygge_ir::SourceIdentity {
            kind,
            repo_id: b"r".to_vec(),
            atom_id: b"r".to_vec(),
            signatures: Vec::new(),
            extras: Vec::new(),
        },
        brygge_version: "0.1.0".into(),
        decoder: decoder.into(),
        decoder_version: "0.1.0".into(),
        params: BTreeMap::new(),
    }
}

fn src(kind: brygge_ir::SourceKind, atom: &[u8]) -> brygge_ir::SourceIdentity {
    brygge_ir::SourceIdentity {
        kind,
        repo_id: b"r".to_vec(),
        atom_id: atom.to_vec(),
        signatures: Vec::new(),
        extras: Vec::new(),
    }
}

fn stated_add(path: &str, blob: brygge_ir::BlobId) -> PathOp {
    PathOp::Add {
        path: path.into(),
        blob,
        mode: 0o100_644,
        status: EpistemicStatus::Stated,
    }
}

fn verify_bytes(bytes: &[u8]) -> i32 {
    let path = tmp_ir_path("verify-check");
    std::fs::write(&path, bytes).unwrap();
    let code = run_verify(&path, None, None, None, Format::Machine);
    let _ = std::fs::remove_file(&path);
    code
}

#[test]
fn verify_integrity_fails_on_a_flipped_byte() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    let mut bytes = brygge_ir::to_bytes(&ir);
    let last = bytes.len() - 1;
    bytes[last] ^= 0xFF;
    assert_eq!(verify_bytes(&bytes), exit::VERIFY_FAILED);
}

#[test]
fn verify_structure_fails_on_a_dangling_parent() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let bogus_parent = brygge_ir::AtomId([0xABu8; 32]);
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![bogus_parent],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn verify_fails_on_a_duplicate_ref_in_a_hand_built_artifact() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let a1 = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    // The builder refuses a repeated `(name, kind)` (`finish` is an `Invariant`), so the duplicate is made
    // by hand on the finished `Ir`; the reader then refuses the bytes (`integrity`).
    b.add_ref(RefRecord {
        name: "main".into(),
        kind: RefKind::Branch,
        target: a1,
        status: EpistemicStatus::Stated,
        source: None,

        annotation: None,
    })
    .unwrap();
    b.add_ref(RefRecord {
        name: "other".into(),
        kind: RefKind::Branch,
        target: a1,
        status: EpistemicStatus::Stated,
        source: None,

        annotation: None,
    })
    .unwrap();
    let mut ir = b.finish().unwrap();
    let dup = ir.refs[0].clone();
    ir.refs.push(dup);
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn two_ops_for_one_path_is_now_rejected_at_build_time_not_verify_time() {
    // Before RFC 011, `IrBuilder::add_atom` was infallible and this scenario could only be caught
    // later, by `verify`'s own `structure` check, on a hand-crafted artifact. RFC 011's
    // `IrBuilder::add_atom` now validates this itself (and brygge-ir's own canonical decode also
    // enforces ops being strictly ascending by path — RFC 011 §2.5), so the same invariant is caught
    // earlier and a malformed artifact of this shape can no longer even be constructed through the
    // builder to exercise the CLI's `structure` check directly. This test confirms the earlier,
    // stricter rejection fires through the exact path the CLI itself uses.
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let blob2 = b.add_blob(b"y".to_vec()).unwrap();
    let err = b.add_atom(AtomDraft {
        parents: vec![],
        ops: vec![
            stated_add("a", blob),
            PathOp::Modify {
                path: "a".into(),
                blob: blob2,
                mode: 0o100_644,
                status: EpistemicStatus::Stated,
            },
        ],
        copies: vec![],
        metadata: MetadataClaims::default(),
        source: src(brygge_ir::SourceKind::Git, b"c1"),
        status: EpistemicStatus::Stated,
    });
    assert!(
        err.is_err(),
        "two ops on one path must be rejected at add_atom"
    );
}

#[test]
fn verify_replay_fails_on_modify_of_an_absent_path() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![PathOp::Modify {
                path: "never-added".into(),
                blob,
                mode: 0o100_644,
                status: EpistemicStatus::Stated,
            }],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn verify_replay_fails_on_add_of_a_present_path() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let a1 = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![a1],
            ops: vec![stated_add("a", blob)], // re-adds the same, already-present path
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c2"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

fn derivation_missing_params(kind: DerivationKind) -> Derivation {
    Derivation {
        kind,
        by: "d".into(),
        decoder_version: "0.1.0".into(),
        params: BTreeMap::new(),
        confidence: Some(100),
    }
}

#[test]
fn verify_derivations_fails_on_a_missing_required_param() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Derived(derivation_missing_params(
                DerivationKind::InferredRename,
            )),
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn verify_derivations_fails_on_confidence_over_100() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let mut d = derivation_missing_params(DerivationKind::NormalizedMetadata);
    d.confidence = Some(101);
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Derived(d),
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn verify_source_invariants_fails_when_a_cvs_atom_is_stripped_to_stated() {
    // The stripped-honesty case (C-3a): a CVS atom that lost its Derived(ReconstructedChangeset) marking.
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Cvs,
        "brygge-decode-cvs",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Cvs, b"a@1.1"),
            status: EpistemicStatus::Stated, // should be Derived(ReconstructedChangeset) for CVS
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn verify_source_invariants_accepts_a_cvs_branch_point_atom() {
    // RFC 013 D-3: a branch-point atom is brygge's construction (`Derived(ReconstructedBranch)`), and it may
    // stand beside the reconstructed changesets. A CVS atom that is `Stated` still fails (the test above).
    use brygge_ir::status::{Derivation, DerivationKind};
    let derived = |kind: DerivationKind, params: &[(&str, &str)]| {
        EpistemicStatus::Derived(Derivation {
            kind,
            by: "brygge-decode-cvs".to_string(),
            decoder_version: "0.3.0".to_string(),
            params: params
                .iter()
                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                .collect(),
            confidence: None,
        })
    };
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Cvs,
        "brygge-decode-cvs",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let root = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Cvs, b"a@1.1"),
            status: {
                let mut d = derived(
                    DerivationKind::ReconstructedChangeset,
                    &[
                        ("window_secs", "180"),
                        ("cluster_keys", "author,log"),
                        ("confidence_rule", "span-overlap-v1"),
                        ("date_rule", "latest-per-file"),
                    ],
                );
                if let EpistemicStatus::Derived(x) = &mut d {
                    x.confidence = Some(100);
                }
                d
            },
        })
        .unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![root],
            ops: vec![stated_add("b", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Cvs, b"branch-point:BR"),
            status: derived(
                DerivationKind::ReconstructedBranch,
                &[("source", "cvs-symbol"), ("line", "BR")],
            ),
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert!(matches!(check_source_invariants(&ir), CheckOutcome::Pass));
}

#[test]
fn verify_provenance_fails_on_an_empty_decoder() {
    let mut b = IrBuilder::new(blank_provenance(brygge_ir::SourceKind::Git, ""));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn verify_loss_boundary_fails_on_an_empty_what() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    b.set_loss(LossBoundary {
        dropped: vec![DropRecord {
            class: LossClass::Representation,
            what: String::new(),
            reason: "something".into(),
            step: None,
        }],
    });
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
}

#[test]
fn a_well_formed_artifact_passes_every_check() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let a1 = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims {
                author: Some(Identity {
                    name: brygge_ir::model::Text::utf8("A"),
                    email: Some(brygge_ir::model::Text::utf8("a@example.com")),
                }),
                ..MetadataClaims::default()
            },
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    b.add_ref(RefRecord {
        name: "main".into(),
        kind: RefKind::Branch,
        target: a1,
        status: EpistemicStatus::Stated,
        source: None,

        annotation: None,
    })
    .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::CLEAN);
}

// ---- replay memory bound (handoff §5.6) --------------------------------------------------------------

#[test]
fn replay_of_a_linear_10000_atom_history_clones_nothing_and_peaks_at_one() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let mut parent = None;
    for i in 0..10_000u32 {
        let blob = b.add_blob(format!("content-{i}").into_bytes()).unwrap();
        let path = format!("f{i}.txt");
        let atom = b
            .add_atom(AtomDraft {
                parents: parent.into_iter().collect(),
                ops: vec![stated_add(&path, blob)],
                copies: vec![],
                metadata: MetadataClaims::default(),
                source: src(brygge_ir::SourceKind::Git, format!("c{i}").as_bytes()),
                status: EpistemicStatus::Stated,
            })
            .unwrap();
        parent = Some(atom);
    }
    let ir = b.finish().unwrap();
    let (outcome, stats) = replay_ir(&ir);
    assert!(matches!(outcome, CheckOutcome::Pass));
    assert_eq!(
        stats.peak, 1,
        "a linear history retains exactly one tree at a time (review 003 R-3)"
    );
    assert_eq!(
        stats.clones, 0,
        "a linear history clones no tree at all — every reference is a last reference (review 003 R-3)"
    );
}

#[test]
fn replay_of_a_branch_point_clones_once_for_the_earlier_sibling_only() {
    // One parent, two children: the first child processed must clone (the second still needs the
    // original); the second (last) reference takes it instead.
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"root".to_vec()).unwrap();
    let root = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("root.txt", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"root"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let blob_a = b.add_blob(b"a".to_vec()).unwrap();
    let _child_a = b
        .add_atom(AtomDraft {
            parents: vec![root],
            ops: vec![stated_add("a.txt", blob_a)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"a"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let blob_b = b.add_blob(b"b".to_vec()).unwrap();
    let _child_b = b
        .add_atom(AtomDraft {
            parents: vec![root],
            ops: vec![stated_add("b.txt", blob_b)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"b"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    let (outcome, stats) = replay_ir(&ir);
    assert!(
        matches!(outcome, CheckOutcome::Pass),
        "both children replay correctly against independent copies of the root's tree"
    );
    assert_eq!(
        stats.clones, 1,
        "exactly one of the two children clones; the other takes the original"
    );
}

// ---- CR-19: untrusted text is neutralized in every output --------------------------------------------

#[test]
fn a_hostile_commit_message_renders_escaped_in_inspect_atoms_human() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims {
                message: Some(brygge_ir::model::Text::utf8(
                    "clear\x1b[2J and \u{202E}reordered",
                )),
                ..MetadataClaims::default()
            },
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    let human = render_atoms_human(&ir, brygge_ir::version::CURRENT);
    assert!(!human.contains('\x1b'), "the raw ESC byte must not appear");
    assert!(
        !human.contains('\u{202E}'),
        "the raw RLO char must not appear"
    );
    assert!(human.contains("\\u{001b}"));
    assert!(human.contains("\\u{202e}"));
}

#[test]
fn a_line_separator_in_a_commit_subject_renders_escaped_in_inspect_atoms_human() {
    // U+2028 LINE SEPARATOR is not a `str::lines()` boundary, so it survives into the rendered
    // "subject" line intact unless `display::human` escapes it (review 003 R-2) — it could otherwise
    // forge what looks like a second output line in a terminal or a log viewer.
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims {
                message: Some(brygge_ir::model::Text::utf8(
                    "subject\u{2028}forged second line",
                )),
                ..MetadataClaims::default()
            },
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    let ir = b.finish().unwrap();
    let human = render_atoms_human(&ir, brygge_ir::version::CURRENT);
    assert!(
        !human.contains('\u{2028}'),
        "the raw line separator must not appear"
    );
    assert!(human.contains("\\u{2028}"));
}

#[test]
fn a_ref_named_with_equals_cannot_forge_a_machine_key() {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let a1 = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    b.add_ref(RefRecord {
        name: "a=b".into(),
        kind: RefKind::Branch,
        target: a1,
        status: EpistemicStatus::Stated,
        source: None,

        annotation: None,
    })
    .unwrap();
    let ir = b.finish().unwrap();
    let machine = render_atoms_machine(&ir, brygge_ir::version::CURRENT);
    assert!(machine.contains("ref.0.name=a%3Db"));
    // The name never appears as a raw key or unescaped value.
    for line in machine.lines() {
        if let Some((key, _)) = line.split_once('=') {
            assert!(!key.contains("a=b"), "line: {line}");
        }
    }
}

// ---- Subversion (RFC 006) -------------------------------------------------------------------------

fn svnadmin_available() -> bool {
    PCommand::new("svnadmin")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// A property block (`K <len>\n<key>\nV <len>\n<value>\n...PROPS-END\n`).
fn svn_props(pairs: &[(&str, &str)]) -> Vec<u8> {
    let mut b = Vec::new();
    for (k, v) in pairs {
        b.extend(format!("K {}\n", k.len()).into_bytes());
        b.extend(k.as_bytes());
        b.push(b'\n');
        b.extend(format!("V {}\n", v.len()).into_bytes());
        b.extend(v.as_bytes());
        b.push(b'\n');
    }
    b.extend(b"PROPS-END\n");
    b
}

fn svn_revision(buf: &mut Vec<u8>, num: u64, props: &[(&str, &str)]) {
    let p = svn_props(props);
    buf.extend(format!("Revision-number: {num}\n").into_bytes());
    buf.extend(format!("Prop-content-length: {}\n", p.len()).into_bytes());
    buf.extend(format!("Content-length: {}\n\n", p.len()).into_bytes());
    buf.extend(p);
    buf.extend(b"\n");
}

fn svn_add_file(buf: &mut Vec<u8>, path: &str, content: &[u8]) {
    let p = svn_props(&[]);
    buf.extend(format!("Node-path: {path}\nNode-kind: file\nNode-action: add\n").into_bytes());
    buf.extend(format!("Prop-content-length: {}\n", p.len()).into_bytes());
    buf.extend(format!("Text-content-length: {}\n", content.len()).into_bytes());
    buf.extend(format!("Content-length: {}\n\n", p.len() + content.len()).into_bytes());
    buf.extend(p);
    buf.extend(content);
    buf.extend(b"\n\n");
}

fn svn_add_dir(buf: &mut Vec<u8>, path: &str, copyfrom: Option<(u64, &str)>) {
    buf.extend(format!("Node-path: {path}\nNode-kind: dir\nNode-action: add\n").into_bytes());
    if let Some((r, p)) = copyfrom {
        buf.extend(format!("Node-copyfrom-rev: {r}\nNode-copyfrom-path: {p}\n").into_bytes());
    }
    buf.extend(b"\n\n");
}

/// A dump with a trunk and a branch copy (so ref reconstruction has something to find).
fn svn_dump_with_branch() -> Vec<u8> {
    let mut b = Vec::new();
    b.extend(b"SVN-fs-dump-format-version: 2\n\n");
    b.extend(b"UUID: 33333333-4444-5555-6666-777777777777\n\n");
    svn_revision(&mut b, 0, &[("svn:date", "2024-02-01T00:00:00.000000Z")]);
    svn_revision(
        &mut b,
        1,
        &[
            ("svn:author", "carol"),
            ("svn:date", "2024-02-02T00:00:00.000000Z"),
            ("svn:log", "trunk"),
        ],
    );
    svn_add_dir(&mut b, "trunk", None);
    svn_add_file(&mut b, "trunk/a.txt", b"one\n");
    svn_revision(
        &mut b,
        2,
        &[
            ("svn:author", "carol"),
            ("svn:date", "2024-02-03T00:00:00.000000Z"),
            ("svn:log", "branch"),
        ],
    );
    svn_add_dir(&mut b, "branches", None);
    svn_add_dir(&mut b, "branches/x", Some((1, "trunk")));
    b
}

fn write_temp_dump(bytes: &[u8]) -> PathBuf {
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let path = std::env::temp_dir().join(format!("brygge-cli-svn-{}-{n}.dump", std::process::id()));
    std::fs::write(&path, bytes).unwrap();
    path
}

#[test]
fn decode_svn_from_a_dumpfile_reconstructs_refs_and_verifies() {
    let dump = write_temp_dump(&svn_dump_with_branch());
    let out = tmp_ir_path("svn");

    let code = run_decode(
        SourceKind::Svn,
        &dump,
        &out,
        false,
        true,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    assert!(out.exists());

    assert_eq!(run_inspect(&out, false, Format::Human), exit::CLEAN);
    assert_eq!(
        run_verify(&out, None, None, None, Format::Machine),
        exit::CLEAN
    );
    assert_eq!(
        run_verify(&out, Some(&dump), None, None, Format::Human),
        exit::CLEAN,
        "the artifact corresponds to its dumpfile (VF-2)"
    );

    let _ = std::fs::remove_file(&dump);
    let _ = std::fs::remove_file(&out);
}

#[test]
fn decode_svn_flat_layout_with_reconstruct_is_a_convention_violation() {
    let mut b = Vec::new();
    b.extend(b"SVN-fs-dump-format-version: 2\n\n");
    b.extend(b"UUID: 88888888-9999-0000-1111-222222222222\n\n");
    svn_revision(&mut b, 0, &[("svn:date", "2024-02-01T00:00:00.000000Z")]);
    svn_revision(
        &mut b,
        1,
        &[
            ("svn:log", "flat"),
            ("svn:date", "2024-02-02T00:00:00.000000Z"),
        ],
    );
    svn_add_file(&mut b, "main.c", b"x\n");
    let dump = write_temp_dump(&b);
    let out = tmp_ir_path("svn-flat");

    let code = run_decode(
        SourceKind::Svn,
        &dump,
        &out,
        false,
        true,
        false,
        None,
        Format::Machine,
    );
    assert_eq!(code, exit::CONVENTION_VIOLATION);
    let _ = std::fs::remove_file(&dump);
    let _ = std::fs::remove_file(&out);
}

#[test]
fn decode_svn_from_a_live_repository_via_svnadmin() {
    if !svnadmin_available() {
        eprintln!("skipping: svnadmin not on PATH");
        return;
    }
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let repo = std::env::temp_dir().join(format!("brygge-cli-svnrepo-{}-{n}", std::process::id()));
    let _ = std::fs::remove_dir_all(&repo);
    assert!(
        PCommand::new("svnadmin")
            .arg("create")
            .arg(&repo)
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    );
    use std::io::Write as _;
    let mut child = PCommand::new("svnadmin")
        .arg("load")
        .arg(&repo)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .expect("spawn svnadmin load");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(&svn_dump_with_branch())
        .unwrap();
    assert!(child.wait().map(|s| s.success()).unwrap_or(false));

    let out = repo.join("out.ir");
    let code = run_decode(
        SourceKind::Svn,
        &repo,
        &out,
        false,
        true,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    assert!(out.exists());
    assert_eq!(
        run_verify(&out, None, None, None, Format::Machine),
        exit::CLEAN
    );

    let _ = std::fs::remove_dir_all(&repo);
}

#[test]
fn cr_07_6_verifying_a_dumpfile_decode_against_a_live_repository_is_not_checked() {
    // CR-07.6: the artifact records which form (dumpfile vs live `svnadmin dump`) it was decoded from.
    // Comparing against the *other* form is not a meaningful check — `verify` must report `not-checked`
    // (never a claimed mismatch) and exit 1, per the three-valued verdict (review 003 R-5).
    if !svnadmin_available() {
        eprintln!("skipping: svnadmin not on PATH");
        return;
    }
    let dump = write_temp_dump(&svn_dump_with_branch());
    let out = tmp_ir_path("svn-form-mismatch");
    let code = run_decode(
        SourceKind::Svn,
        &dump,
        &out,
        false,
        true,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    assert!(out.exists());

    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let repo = std::env::temp_dir().join(format!(
        "brygge-cli-svn-form-mismatch-{}-{n}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&repo);
    assert!(
        PCommand::new("svnadmin")
            .arg("create")
            .arg(&repo)
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    );
    use std::io::Write as _;
    let mut child = PCommand::new("svnadmin")
        .arg("load")
        .arg(&repo)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .expect("spawn svnadmin load");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(&svn_dump_with_branch())
        .unwrap();
    assert!(child.wait().map(|s| s.success()).unwrap_or(false));

    // The artifact was decoded from a dumpfile (`source_form=dumpfile`); verifying it against the live
    // repository *directory* is a different form — `not-checked`, not a mismatch, exit 1/`incomplete`.
    assert_eq!(
        run_verify(&out, Some(&repo), None, None, Format::Machine),
        exit::FAILURE,
        "a cross-form comparison must be incomplete, never pass or fail"
    );

    // Review 010 R-3.3: assert the exact verdict and reason directly, not just the exit code (which any
    // runtime error would also give).
    let ir = read_ir(&out).unwrap().ir;
    let against = run_against_source(&ir, &repo, &brygge_ir::Storage::Memory);
    assert_eq!(against.machine_label(), "not-checked");
    assert_eq!(
        against.detail(),
        Some("the artifact was made from a dumpfile; verify against the same form")
    );
    let verdict = Verdict::from(true, &against, &AgainstTargetOutcome::NotRun);
    assert_eq!(verdict.machine_label(), "incomplete");

    let _ = std::fs::remove_file(&dump);
    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_dir_all(&repo);
}

#[test]
fn cr_07_6_r1_an_svnadmin_version_difference_alone_does_not_fail_verification() {
    // Review 010 R-1: `svnadmin`'s own version is a fact about the tool, not the history, so an upgrade
    // between two decodes must never by itself make `verify --against-source` report a mismatch. Exercises
    // the comparison helpers directly on hand-built IRs — no real `svnadmin` binary needed.
    let dump = write_temp_dump(&svn_dump_with_branch());
    let out = tmp_ir_path("svn-version-note");
    let code = run_decode(
        SourceKind::Svn,
        &dump,
        &out,
        false,
        true,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    // `Ir` is not `Clone` (RFC 015 D-3: its content store may be a spill file), so each variant below is
    // its own fresh read of the same artifact, not a clone of one shared `ir1` — independent IRs with
    // the same content either way, which is all this test needs.
    let fresh = |version: &str, brygge_version: Option<&str>| {
        let mut ir = read_ir(&out).unwrap().ir;
        ir.provenance
            .params
            .insert("svnadmin_version".to_string(), version.to_string());
        if let Some(v) = brygge_version {
            ir.provenance.brygge_version = v.to_string();
        }
        ir
    };

    // Same version: no note, and alignment is a no-op.
    assert_eq!(
        svn_version_note(&fresh("1.14.1", None), &fresh("1.14.1", None)),
        None
    );
    assert_eq!(
        align_svnadmin_version(&fresh("1.14.1", None), fresh("1.14.1", None)),
        fresh("1.14.1", None)
    );

    // Different version, otherwise identical: a note, and alignment makes them equal (`Corresponds`).
    assert_eq!(
        svn_version_note(&fresh("1.14.1", None), &fresh("1.14.2", None)),
        Some("1.14.1 vs 1.14.2".to_string())
    );
    let aligned = align_svnadmin_version(&fresh("1.14.1", None), fresh("1.14.2", None));
    assert_eq!(
        fresh("1.14.1", None),
        aligned,
        "aligning the version param must make an otherwise-identical IR equal"
    );

    // A real difference alongside the version difference must still be caught after alignment.
    let ir3 = fresh("1.14.2", Some("9.9.9-different"));
    let aligned3 = align_svnadmin_version(&fresh("1.14.1", None), ir3);
    assert_ne!(
        fresh("1.14.1", None),
        aligned3,
        "a genuine content difference must survive version alignment"
    );

    let _ = std::fs::remove_file(&dump);
    let _ = std::fs::remove_file(&out);
}

#[test]
fn a_version_note_on_success_is_its_own_key_never_a_failure_detail() {
    // Review 010 F-4, re-keyed by part-2 §5.4: "corresponds" plus a detail could be read as a problem, so
    // the informational svnadmin-version note is `verify.against_source.note`, and no `.detail` appears.
    let checks: Vec<(&'static str, CheckOutcome)> = vec![("integrity", CheckOutcome::Pass)];
    let against = AgainstSourceOutcome::Corresponds(Some("1.14.1 vs 1.14.2".to_string()));
    let verdict = Verdict::from(true, &against, &AgainstTargetOutcome::NotRun);
    let lines = verify_machine_lines(
        &checks,
        true,
        &against,
        &AgainstTargetOutcome::NotRun,
        &verdict,
        0,
    );
    assert!(lines.contains(&"verify.against_source=corresponds".to_string()));
    assert!(lines.contains(&"verify.against_source.note=1.14.1%20vs%201.14.2".to_string()));
    assert!(lines.contains(&"verify.result=pass".to_string()));
    assert!(
        !lines.iter().any(|l| l.contains(".detail")),
        "a note is not a failure detail: {lines:?}"
    );

    // A failure uses `.detail`, and carries no `note`.
    let against = AgainstSourceOutcome::DoesNotCorrespond("atom count differs".to_string());
    let verdict = Verdict::from(true, &against, &AgainstTargetOutcome::NotRun);
    let lines = verify_machine_lines(
        &checks,
        true,
        &against,
        &AgainstTargetOutcome::NotRun,
        &verdict,
        0,
    );
    assert!(
        lines
            .iter()
            .any(|l| l == "verify.against_source.detail=atom%20count%20differs")
    );
    assert!(!lines.iter().any(|l| l.contains(".note")));
}

// ---- CVS (RFC 007) --------------------------------------------------------------------------------

/// A single-revision (`1.1`) RCS `,v` with full text.
fn cvs_single_rev(author: &str, date: &str, log: &str, content: &str) -> Vec<u8> {
    format!(
        "head\t1.1;\naccess;\nsymbols;\nlocks; strict;\n\n\n\
1.1\ndate\t{date};\tauthor {author};\tstate Exp;\nbranches;\nnext\t;\n\n\n\
desc\n@@\n\n\n\
1.1\nlog\n@{log}@\ntext\n@{content}@\n"
    )
    .into_bytes()
}

fn cvs_repo() -> TempRepo {
    // A CVS fixture is a plain directory of `,v` files — no `git init` needed (review 082 F-4).
    TempRepo::new_plain()
}

fn write_vfile(repo: &TempRepo, rel: &str, bytes: &[u8]) {
    let p = repo.dir.join(format!("{rel},v"));
    if let Some(parent) = p.parent() {
        std::fs::create_dir_all(parent).unwrap();
    }
    std::fs::write(p, bytes).unwrap();
}

#[test]
fn decode_cvs_reconstructs_derived_changesets_and_reproduces() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    write_vfile(
        &repo,
        "b.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.01", "add", "bbb\n"),
    );
    let out = repo.dir.join("out.ir");

    let code = run_decode(
        SourceKind::Cvs,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    assert!(out.exists());

    assert_eq!(run_inspect(&out, false, Format::Human), exit::CLEAN);
    assert_eq!(
        run_verify(&out, None, None, None, Format::Machine),
        exit::CLEAN
    );
    assert_eq!(
        run_verify(&out, Some(repo.path()), None, None, Format::Human),
        exit::CLEAN,
        "the CVS reconstruction reproduces from its repository (VF-1)"
    );
}

/// A `,v` with `1.1`, `1.2` on the trunk, the branch symbol `BR:1.2.0.2`, and one branch revision `1.2.2.1`.
fn cvs_with_one_branch_revision() -> Vec<u8> {
    "head\t1.2;\naccess;\nsymbols\n\tBR:1.2.0.2;\nlocks; strict;\n\n\n\
1.2\ndate\t2024.01.02.00.00.00;\tauthor alice;\tstate Exp;\nbranches\n\t1.2.2.1;\nnext\t1.1;\n\n\
1.1\ndate\t2024.01.01.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n\
1.2.2.1\ndate\t2024.01.03.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n\n\
desc\n@@\n\n\
1.2\nlog\n@two@\ntext\n@two\n@\n\n\
1.1\nlog\n@one@\ntext\n@d1 1\na1 1\none\n@\n\n\
1.2.2.1\nlog\n@on the branch@\ntext\n@d1 1\na1 1\nbr\n@\n"
        .as_bytes()
        .to_vec()
}

/// Batch I: a CVS repository with a branch revision records drops of two classes (`Representation` and
/// `Other`). The artifact used to fail its own `verify` `integrity` (exit 50), because the reader ordered
/// drops by the Debug name of the class, not by the specified variant number (`Other` sorts first by name).
#[test]
fn a_cvs_repository_with_a_branch_revision_verifies_its_own_artifact() {
    let repo = cvs_repo();
    write_vfile(&repo, "a.txt", &cvs_with_one_branch_revision());
    let out = repo.dir.join("out.ir");

    let code = run_decode(
        SourceKind::Cvs,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let ir = brygge_ir::from_bytes(&std::fs::read(&out).unwrap())
        .unwrap()
        .ir;
    assert!(
        ir.loss
            .dropped
            .iter()
            .any(|d| d.class == brygge_ir::model::LossClass::Other),
        "the branch revision is recorded as a drop"
    );
    let code = run_verify(&out, None, None, None, Format::Machine);
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "verify must not fail integrity (exit 50): got {code}"
    );
}

/// A `,v` with a branch `BR` (`1.2.0.2`, revisions `1.2.2.1` and `1.2.2.2`), a branch `NEST` cut from the
/// branch revision `1.2.2.1` (`1.2.2.1.0.2`, one revision) when `nest_on_branch`, or from the trunk (`1.2.0.4`)
/// otherwise. `p` prefixes every text.
fn cvs_with_a_nested_branch(p: &str, nest_on_branch: bool) -> Vec<u8> {
    let (sym, brs, nest_admin) = if nest_on_branch {
        ("NEST:1.2.2.1.0.2", "branches\n\t1.2.2.1.2.1;\n", true)
    } else {
        ("NEST:1.2.0.4", "branches;\n", false)
    };
    let mut s = format!(
        "head\t1.2;\naccess;\nsymbols\n\tBR:1.2.0.2\n\t{sym};\nlocks; strict;\n\n\n\
1.2\ndate\t2024.01.02.00.00.00;\tauthor alice;\tstate Exp;\nbranches\n\t1.2.2.1;\nnext\t1.1;\n\n\
1.1\ndate\t2024.01.01.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n\
1.2.2.1\ndate\t2024.02.01.00.00.00;\tauthor alice;\tstate Exp;\n{brs}next\t1.2.2.2;\n\n\
1.2.2.2\ndate\t2024.02.03.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n"
    );
    if nest_admin {
        s.push_str("1.2.2.1.2.1\ndate\t2024.03.01.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n");
    }
    s.push_str(&format!(
        "\ndesc\n@@\n\n\
1.2\nlog\n@edit@\ntext\n@{p}2\n@\n\n\
1.1\nlog\n@start@\ntext\n@d1 1\na1 1\n{p}1\n@\n\n\
1.2.2.1\nlog\n@br one@\ntext\n@d1 1\na1 1\n{p}b1\n@\n\n\
1.2.2.2\nlog\n@br two@\ntext\n@d1 1\na1 1\n{p}b2\n@\n"
    ));
    if nest_admin {
        s.push_str(&format!(
            "\n1.2.2.1.2.1\nlog\n@nest@\ntext\n@d1 1\na1 1\n{p}n1\n@\n"
        ));
    }
    s.into_bytes()
}

/// Handoff §7 determinism, for test 10: a nested branch and a mixed-working-copy symbol decode twice to the
/// same bytes, and `verify --against-source` answers that the artifact reproduces.
#[test]
fn decode_cvs_nested_and_mixed_branches_reproduce_and_verify_against_source() {
    let repo = cvs_repo();
    write_vfile(&repo, "a.c", &cvs_with_a_nested_branch("a", true));
    write_vfile(&repo, "b.c", &cvs_with_a_nested_branch("b", true));
    write_vfile(&repo, "c.c", &cvs_with_a_nested_branch("c", false));
    let one = repo.dir.join("one.ir");
    let two = repo.dir.join("two.ir");
    for out in [&one, &two] {
        let code = run_decode(
            SourceKind::Cvs,
            repo.path(),
            out,
            false,
            true,
            false,
            None,
            Format::Machine,
        );
        assert_eq!(
            code,
            exit::CONVENTION_VIOLATION,
            "the mixed symbol is an approximate branch point (exit 30)"
        );
    }
    assert_eq!(
        std::fs::read(&one).unwrap(),
        std::fs::read(&two).unwrap(),
        "two decodes are identical"
    );
    let ir = brygge_ir::from_bytes(&std::fs::read(&one).unwrap())
        .unwrap()
        .ir;
    assert!(ir.refs.iter().any(|r| r.name == "NEST"));
    assert_eq!(
        run_verify(&one, None, None, None, Format::Machine),
        exit::CLEAN
    );
    assert_eq!(
        run_verify(&one, Some(repo.path()), None, None, Format::Human),
        exit::CLEAN,
        "the branch reconstruction reproduces from its repository (VF-1)"
    );
}

#[test]
fn decode_cvs_whole_import_under_floor_is_refused() {
    let repo = cvs_repo();
    for i in 0..10 {
        let date = format!("2024.03.01.00.{:02}.00", i);
        write_vfile(
            &repo,
            &format!("f{i}.c"),
            &cvs_single_rev("alice", &date, "big", "x\n"),
        );
    }
    let out = repo.dir.join("out.ir");
    let code = run_decode(
        SourceKind::Cvs,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert_eq!(code, exit::FLOOR_REFUSAL);
    assert!(!out.exists());
}

#[test]
fn decode_cvs_partial_under_floor_imports_and_exits_convention_violation() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "x.c",
        &cvs_single_rev("alice", "2024.01.01.00.00.00", "tidy", "x\n"),
    );
    write_vfile(
        &repo,
        "y.c",
        &cvs_single_rev("alice", "2024.01.01.00.00.01", "tidy", "y\n"),
    );
    write_vfile(
        &repo,
        "p.c",
        &cvs_single_rev("bob", "2024.02.01.00.00.00", "sprawl", "p\n"),
    );
    write_vfile(
        &repo,
        "q.c",
        &cvs_single_rev("bob", "2024.02.01.00.01.40", "sprawl", "q\n"),
    );
    write_vfile(
        &repo,
        "r.c",
        &cvs_single_rev("bob", "2024.02.01.00.03.20", "sprawl", "r\n"),
    );

    let out = repo.dir.join("out.ir");
    let code = run_decode(
        SourceKind::Cvs,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert_eq!(code, exit::CONVENTION_VIOLATION);
    assert!(
        out.exists(),
        "the import still writes (confident changesets imported)"
    );
}

#[test]
fn decode_cvs_cr01_branch_revision_exits_recorded_loss() {
    // CVS corrections handoff §1/§4.1 (review 008 R-7): the §1 reproduction fixture, exercised through
    // the CLI end to end — a trunk 1.1 -> 1.2 -> 1.3 history with a branch revision 1.2.2.1 excludes the
    // branch revision and exits 10 (recorded loss), never silently landing it in the main line.
    let repo = cvs_repo();
    let content = b"head\t1.3;\naccess;\nsymbols;\nlocks; strict;\n\n\n\
1.3\ndate\t2024.01.03.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t1.2;\n\n\
1.2\ndate\t2024.01.02.00.00.00;\tauthor alice;\tstate Exp;\nbranches\n\t1.2.2.1;\nnext\t1.1;\n\n\
1.2.2.1\ndate\t2024.01.02.12.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n\
1.1\ndate\t2024.01.01.00.00.00;\tauthor alice;\tstate Exp;\nbranches;\nnext\t;\n\n\n\
desc\n@@\n\n\n\
1.3\nlog\n@trunk r3@\ntext\n@line1\nline2\nline3\n@\n\n\n\
1.2\nlog\n@trunk r2@\ntext\n@d3 1\n@\n\n\n\
1.2.2.1\nlog\n@branch commit@\ntext\n@d1 2\na2 1\nBRANCH CONTENT\n@\n\n\n\
1.1\nlog\n@trunk r1@\ntext\n@d2 1\n@\n";
    write_vfile(&repo, "f.c", content);
    let out = repo.dir.join("out.ir");
    let code = run_decode(
        SourceKind::Cvs,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert_eq!(code, exit::RECORDED_LOSS);
    assert!(out.exists());
}

#[test]
fn verify_cvs_derivations_requires_confidence_rule_as_well_as_date_rule() {
    // CVS corrections handoff §2.2 (review 008 R-8): `confidence_rule` is required for
    // `ReconstructedChangeset` alongside `date_rule` — a confidence without the rule that produced it
    // cannot be reviewed. Every other required param is present; only `confidence_rule` is missing.
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Cvs,
        "brygge-decode-cvs",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let mut params = BTreeMap::new();
    params.insert("window_secs".to_string(), "180".to_string());
    params.insert("cluster_keys".to_string(), "author,log".to_string());
    params.insert("date_rule".to_string(), "latest-per-file".to_string());
    let derivation = Derivation {
        kind: DerivationKind::ReconstructedChangeset,
        by: "brygge-decode-cvs".into(),
        decoder_version: "0.1.0".into(),
        params,
        confidence: Some(90),
    };
    let _ = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("a", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Cvs, b"a@1.1"),
            status: EpistemicStatus::Derived(derivation),
        })
        .unwrap();
    let ir = b.finish().unwrap();
    assert_eq!(verify_bytes(&brygge_ir::to_bytes(&ir)), exit::VERIFY_FAILED);
    // Review 008 F-5: exit 50 alone would also come from any other failure — the check's own detail must
    // name the missing param.
    let outcome = check_derivations(&ir);
    assert!(outcome.is_fail());
    assert_eq!(
        outcome.detail(),
        Some("a ReconstructedChangeset derivation is missing required param 'confidence_rule'")
    );
}

// ---- Mercurial (RFC 005) --------------------------------------------------------------------------

fn hg_available() -> bool {
    PCommand::new("hg")
        .arg("--version")
        .env("HGRCPATH", "/dev/null")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

struct HgRepo {
    dir: PathBuf,
}

impl Drop for HgRepo {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

impl HgRepo {
    fn new() -> Self {
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("brygge-cli-hg-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let r = Self { dir };
        r.run(&["init", r.dir.to_str().unwrap()]);
        r
    }

    fn path(&self) -> &Path {
        &self.dir
    }

    fn run(&self, args: &[&str]) {
        let ok = PCommand::new("hg")
            .env("HGRCPATH", "/dev/null")
            .arg("--cwd")
            .arg(&self.dir)
            .arg("-R")
            .arg(&self.dir)
            .arg("--config")
            .arg("ui.username=A U Thor <a@example.com>")
            .args(args)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        assert!(ok, "hg {args:?} failed");
    }

    fn commit(&self, rel: &str, contents: &str, epoch: &str, msg: &str) {
        std::fs::write(self.dir.join(rel), contents).unwrap();
        self.run(&["add"]);
        self.run(&["commit", "-d", &format!("{epoch} 0"), "-m", msg]);
    }
}

#[test]
fn decode_hg_and_verify_a_good_artifact_from_every_decoder() {
    if !hg_available() {
        eprintln!("skipping: hg not on PATH");
        return;
    }
    let repo = HgRepo::new();
    repo.commit("a.txt", "one\n", "1700000000", "c1");
    repo.commit("a.txt", "two\n", "1700000100", "c2");
    let out = tmp_ir_path("hg");

    let code = run_decode(
        SourceKind::Hg,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    assert!(out.exists());
    assert_eq!(
        run_verify(&out, None, None, None, Format::Machine),
        exit::CLEAN
    );
    assert_eq!(
        run_verify(&out, Some(repo.path()), None, None, Format::Human),
        exit::CLEAN,
        "the artifact corresponds to its hg source (VF-2)"
    );
    let _ = std::fs::remove_file(&out);
}

// ---- release prep §5: the temp path is created exclusively ------------------------------------------

fn scratch_dir(tag: &str) -> PathBuf {
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let d = std::env::temp_dir().join(format!("brygge-atomic-{tag}-{}-{n}", std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    d
}

fn planted_tmp_path(dir: &Path, name: &str) -> PathBuf {
    dir.join(format!(".{name}.brygge-tmp-{}", std::process::id()))
}

/// A `write_body` for `atomic_write` that just writes `bytes` verbatim — these tests are about the
/// atomic-write mechanism (the temp file, the rename, cleanup on failure), not about what gets encoded
/// into it, so a literal byte string stands in for a real artifact.
fn write_bytes(bytes: &'static [u8]) -> impl FnOnce(&mut std::fs::File) -> std::io::Result<u64> {
    move |f| {
        f.write_all(bytes)?;
        Ok(bytes.len() as u64)
    }
}

#[cfg(unix)]
#[test]
fn a_planted_symlink_at_the_temp_path_fails_the_write_and_its_target_is_untouched() {
    let dir = scratch_dir("symlink");
    let victim = dir.join("victim.txt");
    std::fs::write(&victim, b"precious").unwrap();
    let out = dir.join("out.ir");
    let tmp = planted_tmp_path(&dir, "out.ir");
    std::os::unix::fs::symlink(&victim, &tmp).unwrap();

    let err = atomic_write(&out, write_bytes(b"artifact bytes")).unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
    assert_eq!(
        std::fs::read(&victim).unwrap(),
        b"precious",
        "the target was written through"
    );
    assert!(!out.exists(), "no artifact may be produced");
    // Not ours, so not removed either: the planted link is still there.
    assert!(
        std::fs::symlink_metadata(&tmp)
            .unwrap()
            .file_type()
            .is_symlink()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_planted_regular_file_at_the_temp_path_is_not_truncated_or_removed() {
    let dir = scratch_dir("file");
    let out = dir.join("out.ir");
    let tmp = planted_tmp_path(&dir, "out.ir");
    std::fs::write(&tmp, b"planted").unwrap();

    assert!(atomic_write(&out, write_bytes(b"artifact bytes")).is_err());
    assert_eq!(std::fs::read(&tmp).unwrap(), b"planted");
    assert!(!out.exists());
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_normal_write_still_succeeds_and_leaves_no_temp_file() {
    let dir = scratch_dir("ok");
    let out = dir.join("out.ir");
    atomic_write(&out, write_bytes(b"artifact bytes")).unwrap();
    assert_eq!(std::fs::read(&out).unwrap(), b"artifact bytes");
    assert!(tmp_siblings(&dir).is_empty());
    let _ = std::fs::remove_dir_all(&dir);
}

// macOS file systems (APFS, HFS+) refuse a file name that is not valid UTF-8 (`EILSEQ`), so the property cannot
// be set up there: the name can never exist on that platform.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn a_non_utf8_output_file_name_is_written_without_a_lossy_conversion() {
    use std::os::unix::ffi::OsStrExt;
    let dir = scratch_dir("nonutf8");
    let out = dir.join(std::ffi::OsStr::from_bytes(b"out-\xff.ir"));
    atomic_write(&out, write_bytes(b"x")).unwrap();
    assert_eq!(std::fs::read(&out).unwrap(), b"x");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn help_lists_flagged_in_the_vocabulary_and_no_internal_ids() {
    let help = crate::cli::USAGE;
    assert!(help.contains("VOCABULARY:") && help.contains("flagged"));
    for id in ["FS-", "VF-", "CL-", "CR-", "PR-", "INV-", "RFC"] {
        assert!(!help.contains(id), "--help mentions the internal id {id}");
    }
}

// ---- part-2 §5: the machine output (naming rule, one key one line, raw bytes, details, skips, Other) ----

/// A hand-built IR that exercises every key family the machine output can print: a derived copy, an
/// `Other` derivation kind on an atom, a copy and a ref, an `Other` ref kind, a non-UTF-8 message, a drop
/// and a flag.
fn machine_output_fixture() -> Ir {
    use brygge_ir::model::{CopyRecord, Flag, FlagKind, LossClass, Text};
    let other = |name: &str| {
        EpistemicStatus::Derived(Derivation {
            kind: DerivationKind::Other(name.to_string()),
            by: "d".into(),
            decoder_version: "0".into(),
            params: BTreeMap::new(),
            confidence: None,
        })
    };
    let renamed = EpistemicStatus::Derived(Derivation {
        kind: DerivationKind::InferredRename,
        by: "d".into(),
        decoder_version: "0".into(),
        params: BTreeMap::new(),
        confidence: Some(90),
    });
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    let a1 = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("old", blob)],
            copies: vec![],
            metadata: MetadataClaims {
                message: Some(Text {
                    bytes: b"caf\xe9 100%\nsecond line".to_vec(),
                    encoding: None,
                }),
                ..MetadataClaims::default()
            },
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: other("bespoke kind = x"),
        })
        .unwrap();
    let a2 = b
        .add_atom(AtomDraft {
            parents: vec![a1],
            ops: vec![
                PathOp::Delete {
                    path: "old".into(),
                    status: EpistemicStatus::Stated,
                },
                stated_add("new", blob),
            ],
            copies: vec![
                CopyRecord {
                    from: "old".into(),
                    from_atom: a1,
                    to: "new".into(),
                    status: renamed,
                },
                CopyRecord {
                    from: "old".into(),
                    from_atom: a1,
                    to: "newer".into(),
                    status: other("odd copy"),
                },
            ],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c2"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    b.add_ref(RefRecord {
        name: "refs/odd".into(),
        kind: RefKind::Other("phase: draft".into()),
        target: a2,
        status: other("ref made up"),
        source: None,
        annotation: None,
    })
    .unwrap();
    b.set_loss(LossBoundary {
        dropped: vec![DropRecord {
            class: LossClass::AdvisoryUnreliable,
            what: "mergeinfo".into(),
            reason: "advisory".into(),
            step: None,
        }],
    });
    b.add_flag(Flag {
        kind: FlagKind::BelowConfidenceFloor,
        what: "changesets".into(),
        count: 2,
        reason: "low".into(),
    });
    b.finish().unwrap()
}

/// Every machine line is `key=value` with a key of dot-separated `[a-z0-9_]` segments (hand-rolled: no
/// regex dependency). Returns the keys, so a test can assert on them.
fn assert_machine_keys_follow_the_rule(text: &str) -> Vec<String> {
    let mut keys = Vec::new();
    for line in text.lines() {
        let (key, _) = line
            .split_once('=')
            .unwrap_or_else(|| panic!("a machine line without `=`: {line:?}"));
        assert!(!key.is_empty(), "empty key in {line:?}");
        for seg in key.split('.') {
            assert!(
                !seg.is_empty()
                    && seg
                        .bytes()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_'),
                "key {key:?} breaks `^[a-z0-9_]+(\\.[a-z0-9_]+)*$` (line {line:?})"
            );
        }
        keys.push(key.to_string());
    }
    keys
}

fn every_verify_line_shape() -> Vec<String> {
    // Passing, failing and could-not-run checks, plus a source comparison with a note.
    let checks: Vec<(&'static str, CheckOutcome)> = CHECK_NAMES
        .iter()
        .enumerate()
        .map(|(i, n)| {
            let o = match i {
                0 => CheckOutcome::Pass,
                1 => CheckOutcome::Fail("a detail = with\nweird bytes".to_string()),
                _ => CheckOutcome::NotChecked("the artifact failed to decode".to_string()),
            };
            (*n, o)
        })
        .collect();
    let against = AgainstSourceOutcome::Corresponds(Some("1.14.1 vs 1.14.2".to_string()));
    let verdict = Verdict::from(false, &against, &AgainstTargetOutcome::NotRun);
    verify_machine_lines(
        &checks,
        false,
        &against,
        &AgainstTargetOutcome::NotRun,
        &verdict,
        2,
    )
}

#[test]
fn part2_5_1_keys_that_embed_a_label_are_snake_case_and_values_stay_kebab_case() {
    let ir = machine_output_fixture();
    let report = brygge_ir::honesty::summary(&ir).render_machine();
    for key in [
        "derived.inferred_rename=",
        "derived.other=",
        "dropped.advisory_unreliable=",
        "flagged.below_confidence_floor=",
    ] {
        assert!(
            report.lines().any(|l| l.starts_with(key)),
            "{key} in\n{report}"
        );
    }
    let lines = every_verify_line_shape();
    assert!(
        lines
            .iter()
            .any(|l| l.starts_with("verify.check.source_invariants="))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.starts_with("verify.check.loss_boundary="))
    );
    // Values keep kebab-case: the status value and the not-checked word.
    let atoms = render_atoms_machine(&ir, brygge_ir::version::CURRENT);
    assert!(atoms.contains("atom.1.copy.0.status=derived:inferred-rename"));
    assert!(lines.iter().any(|l| l == "verify.check.replay=not-checked"));
}

#[test]
fn part2_5_2_inspect_atoms_does_not_repeat_the_atoms_key() {
    let ir = machine_output_fixture();
    let report = brygge_ir::honesty::summary(&ir).render_machine();
    let atoms = render_atoms_machine(&ir, brygge_ir::version::CURRENT);
    assert_eq!(
        report.lines().filter(|l| l.starts_with("atoms=")).count(),
        1
    );
    assert!(
        !atoms.lines().any(|l| l.starts_with("atoms=")),
        "the listing repeats `atoms=`:\n{atoms}"
    );
    // ... and so the two concatenated (what `inspect --atoms --format machine` prints) have no duplicate key.
    let all = format!("{report}{atoms}");
    let keys = assert_machine_keys_follow_the_rule(&all);
    let mut seen = std::collections::BTreeSet::new();
    for k in &keys {
        assert!(seen.insert(k.clone()), "duplicate key {k}");
    }
}

#[test]
fn part2_5_3_atom_message_is_the_raw_bytes_percent_encoded_once() {
    let ir = machine_output_fixture();
    let atoms = render_atoms_machine(&ir, brygge_ir::version::CURRENT);
    // "caf\xe9 100%\nsecond line": the non-UTF-8 byte, the space, the literal `%` and the newline.
    assert!(
        atoms.contains("atom.0.message=caf%E9%20100%25%0Asecond%20line\n"),
        "{atoms}"
    );
    // Not prepared for the terminal first (the old form escaped, or replaced non-UTF-8 by a placeholder).
    assert!(!atoms.contains("byte(s)") && !atoms.contains("\\u{"));
    // The human form keeps its display escaping: a non-UTF-8 message is not echoed as raw bytes.
    let human = render_atoms_human(&ir, brygge_ir::version::CURRENT);
    assert!(!human.contains('\u{fffd}'));
    // An absent message is an empty value.
    assert!(atoms.contains("atom.1.message=\n"));
}

#[test]
fn part2_5_4_details_belong_to_their_check_and_follow_its_line() {
    let lines = every_verify_line_shape();
    let at = |prefix: &str| {
        lines
            .iter()
            .position(|l| l.starts_with(prefix))
            .unwrap_or_else(|| panic!("no {prefix} in {lines:?}"))
    };
    let structure = at("verify.check.structure=");
    assert_eq!(
        at("verify.check.structure.detail="),
        structure + 1,
        "the detail follows its own check's line"
    );
    // A passing check prints no detail.
    assert!(
        !lines
            .iter()
            .any(|l| l.starts_with("verify.check.integrity.detail"))
    );
    // The old numbered form is gone, and the source comparison has its own keys.
    assert!(
        !lines
            .iter()
            .any(|l| l.starts_with("verify.detail.") || l.starts_with("verify.note."))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.starts_with("verify.against_source.note="))
    );
    assert!(
        !lines
            .iter()
            .any(|l| l.starts_with("verify.against_source.detail"))
    );
    // The detail is escaped like every other value.
    assert!(lines.contains(
        &"verify.check.structure.detail=a%20detail%20%3D%20with%0Aweird%20bytes".to_string()
    ));
}

#[test]
fn part2_5_5_a_check_that_could_not_run_is_not_checked_never_n_a() {
    let lines = every_verify_line_shape();
    assert!(lines.contains(&"verify.check.provenance=not-checked".to_string()));
    assert!(!lines.iter().any(|l| l.contains("n/a")));
    assert_eq!(
        CheckOutcome::NotChecked(String::new()).label(),
        "not-checked"
    );
    // `against_source` uses the same word for "requested but could not run", and `not-run` still means
    // "not requested".
    assert_eq!(
        AgainstSourceOutcome::NotChecked(String::new()).machine_label(),
        "not-checked"
    );
    assert_eq!(AgainstSourceOutcome::NotRun.machine_label(), "not-run");
}

#[test]
fn part2_5_6_skipped_non_critical_fields_are_visible_to_machines() {
    let ir = machine_output_fixture();
    let report = brygge_ir::honesty::summary(&ir);
    assert!(
        report
            .render_machine()
            .lines()
            .any(|l| l == "skipped_non_critical_fields=0")
    );
    assert!(
        report
            .with_skipped_non_critical_fields(4)
            .render_machine()
            .lines()
            .any(|l| l == "skipped_non_critical_fields=4")
    );
    let lines = every_verify_line_shape();
    assert!(lines.contains(&"verify.skipped_non_critical_fields=2".to_string()));
    let none = verify_machine_lines(
        &[("integrity", CheckOutcome::Pass)],
        true,
        &AgainstSourceOutcome::NotRun,
        &AgainstTargetOutcome::NotRun,
        &Verdict::Pass,
        0,
    );
    assert!(none.contains(&"verify.skipped_non_critical_fields=0".to_string()));
}

#[test]
fn part2_5_7_other_is_not_flattened_the_label_is_other_and_the_name_has_a_companion_key() {
    let ir = machine_output_fixture();
    let atoms = render_atoms_machine(&ir, brygge_ir::version::CURRENT);
    for expected in [
        "atom.0.status=derived:other\n",
        "atom.0.status_other=bespoke%20kind%20%3D%20x\n",
        "atom.1.copy.1.status=derived:other\n",
        "atom.1.copy.1.status_other=odd%20copy\n",
        "ref.0.kind=other\n",
        "ref.0.kind_other=phase:%20draft\n",
        "ref.0.status=derived:other\n",
        "ref.0.status_other=ref%20made%20up\n",
    ] {
        assert!(atoms.contains(expected), "missing {expected:?} in\n{atoms}");
    }
    // A named (non-Other) kind or status gets no companion key.
    assert!(!atoms.contains("atom.1.status_other"));
    assert!(!atoms.contains("atom.1.copy.0.status_other"));
}

#[test]
fn part2_5_versions_are_bumped() {
    assert_eq!(brygge_ir::honesty::REPORT_VERSION, 3);
    assert_eq!(INSPECT_VERSION, 4);
    assert_eq!(VERIFY_VERSION, 5);
    assert!(every_verify_line_shape().contains(&"verify_version=5".to_string()));
    assert!(
        render_atoms_machine(&machine_output_fixture(), brygge_ir::version::CURRENT)
            .starts_with("inspect_version=4\n")
    );
}

#[test]
fn part2_5_every_machine_key_matches_the_key_rule_across_every_key_family() {
    let ir = machine_output_fixture();
    let mut keys =
        assert_machine_keys_follow_the_rule(&brygge_ir::honesty::summary(&ir).render_machine());
    keys.extend(assert_machine_keys_follow_the_rule(&render_atoms_machine(
        &ir,
        brygge_ir::version::CURRENT,
    )));
    keys.extend(assert_machine_keys_follow_the_rule(
        &every_verify_line_shape().join("\n"),
    ));
    // The families are all actually present (so the rule is checked on real keys, not on nothing).
    for family in [
        "report_version",
        "skipped_non_critical_fields",
        "derived.inferred_rename",
        "dropped.advisory_unreliable",
        "flagged.below_confidence_floor",
        "inspect_version",
        "atom.0.status_other",
        "atom.1.copy.0.from_atom",
        "ref.0.kind_other",
        "loss.0.class",
        "flag.0.count",
        "verify.check.source_invariants",
        "verify.check.structure.detail",
        "verify.against_source.note",
        "verify.skipped_non_critical_fields",
        "verify.result",
    ] {
        assert!(
            keys.iter().any(|k| k == family),
            "family {family} not exercised: {keys:?}"
        );
    }
}

// ---- part-2 §2: an hg artifact claims no rename inference, because none happens ---------------------

#[test]
fn an_hg_artifacts_params_carry_no_rename_or_infer_keys() {
    if !hg_available() {
        eprintln!("skipping: hg not on PATH");
        return;
    }
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let repo = std::env::temp_dir().join(format!("brygge-cli-hg-{}-{n}", std::process::id()));
    let _guard = CleanupDir(repo.clone());
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(&repo).unwrap();
    let hg = |args: &[&str]| {
        let out = PCommand::new("hg")
            .current_dir(&repo)
            .args(args)
            .env("HGRCPATH", "/dev/null")
            .env("HGUSER", "A U Thor <a@example.com>")
            .output()
            .expect("run hg");
        assert!(
            out.status.success(),
            "hg {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    };
    hg(&["init"]);
    std::fs::write(repo.join("a.txt"), "one\n").unwrap();
    hg(&["add", "a.txt"]);
    hg(&["commit", "-d", "0 0", "-m", "c1"]);
    hg(&["mv", "a.txt", "b.txt"]);
    hg(&["commit", "-d", "1 0", "-m", "c2 (a recorded rename)"]);

    let out = repo
        .join("..")
        .join(format!("brygge-hg-params-{}-{n}.ir", std::process::id()));
    assert_eq!(
        run_decode(
            SourceKind::Hg,
            &repo,
            &out,
            false,
            false,
            false,
            None,
            Format::Machine
        ),
        exit::CLEAN
    );
    let ir = brygge_ir::from_bytes(&std::fs::read(&out).unwrap())
        .unwrap()
        .ir;
    let keys: Vec<&String> = ir.provenance.params.keys().collect();
    assert!(
        !keys
            .iter()
            .any(|k| k.starts_with("rename_") || k.as_str() == "infer_renames"),
        "an hg artifact must not claim an inference that never ran: {keys:?}"
    );
    // The recorded rename is still carried, as Stated (Mercurial states it).
    assert!(
        ir.atoms
            .iter()
            .flat_map(|a| &a.copies)
            .any(|c| c.from == "a.txt" && c.to == "b.txt" && !c.status.is_derived())
    );
    // And `verify --against-source` re-decodes it without reading any inference parameter.
    assert_eq!(
        run_verify(&out, Some(&repo), None, None, Format::Machine),
        exit::CLEAN
    );
    let _ = std::fs::remove_file(&out);
}

// ---- a source path that does not exist (0.3.0 cut prep) --------------------------------------------------

fn plain_opts() -> SourceOpts {
    SourceOpts {
        infer_renames: false,
        reconstruct_refs: false,
        branch_lines: false,
        carry_extra_namespaces: Vec::new(),
        layout: LayoutPolicy::default(),
        cvs_window: 300,
        cvs_floor: 50,
    }
}

const ALL_KINDS: [SourceKind; 4] = [
    SourceKind::Git,
    SourceKind::Hg,
    SourceKind::Svn,
    SourceKind::Cvs,
];

/// One rule, one wording, for every source kind: a path that does not exist is `source not found: <path>`, an
/// open error (exit 1), and `decode svn` no longer runs `svnadmin` on it.
#[test]
fn a_missing_source_path_is_source_not_found_for_every_kind() {
    let missing = std::env::temp_dir().join(format!("brygge-cli-missing-{}", std::process::id()));
    let want = format!("source not found: {}", missing.display());
    for kind in ALL_KINDS {
        match decode_source(kind, &missing, &plain_opts(), &brygge_ir::Storage::Memory) {
            Err((code, msg)) => {
                assert_eq!(code, exit::FAILURE, "{kind:?}");
                assert!(msg.contains(&want), "{kind:?}: {msg}");
                assert!(!msg.contains("svnadmin"), "{kind:?} ran nothing: {msg}");
            }
            Ok(_) => panic!("{kind:?}: decoded a source that does not exist"),
        }
    }
}

/// The remote refusal keeps precedence and its text: exit 20 (`svn` and `cvs` name a URL as remote).
#[test]
fn a_url_is_still_a_floor_refusal_not_source_not_found() {
    match decode_source(
        SourceKind::Svn,
        Path::new("svn://example.org/r"),
        &plain_opts(),
        &brygge_ir::Storage::Memory,
    ) {
        Err((code, msg)) => {
            assert_eq!(code, exit::FLOOR_REFUSAL);
            assert!(msg.contains("remote-source"), "{msg}");
            assert!(msg.contains("svnrdump dump <url> > repo.dump"), "{msg}");
            assert!(!msg.contains("source not found"), "{msg}");
        }
        Ok(_) => panic!("decoded a URL"),
    }
    match decode_source(
        SourceKind::Cvs,
        Path::new(":pserver:x@example.org:/cvs"),
        &plain_opts(),
        &brygge_ir::Storage::Memory,
    ) {
        Err((code, _)) => assert_eq!(code, exit::FLOOR_REFUSAL),
        Ok(_) => panic!("decoded a :pserver: source"),
    }
}

#[cfg(unix)]
#[test]
fn an_svn_fifo_is_neither_a_dumpfile_nor_a_repository_and_does_not_block() {
    let path = std::env::temp_dir().join(format!("brygge-cli-fifo-{}", std::process::id()));
    if !PCommand::new("mkfifo")
        .arg(&path)
        .status()
        .is_ok_and(|s| s.success())
    {
        eprintln!("skipping: mkfifo is not available");
        return;
    }
    let (tx, rx) = std::sync::mpsc::channel();
    let p = path.clone();
    std::thread::spawn(move || {
        let _ = tx.send(
            decode_source(
                SourceKind::Svn,
                &p,
                &plain_opts(),
                &brygge_ir::Storage::Memory,
            )
            .map(|_| ()),
        );
    });
    let got = rx
        .recv_timeout(std::time::Duration::from_secs(10))
        .expect("refused without blocking on the FIFO");
    let _ = std::fs::remove_file(&path);
    match got {
        Err((code, msg)) => {
            assert_eq!(code, exit::FAILURE);
            assert!(
                msg.contains("SVN source is neither a dumpfile nor a repository directory"),
                "{msg}"
            );
        }
        Ok(()) => panic!("decoded a FIFO"),
    }
}

/// `verify --against-source <missing>` re-decodes through the same code, so its `not-checked` detail carries
/// the same wording, for every kind: for an SVN artifact made from a dumpfile as well (a missing path has no
/// "form" to mismatch).
#[test]
fn against_source_with_a_missing_path_is_not_checked_with_the_same_wording() {
    let missing =
        std::env::temp_dir().join(format!("brygge-cli-missing-vs-{}", std::process::id()));
    let want = format!("source not found: {}", missing.display());
    for (kind, decoder) in [
        (brygge_ir::SourceKind::Git, "brygge-decode-git"),
        (brygge_ir::SourceKind::Hg, "brygge-decode-hg"),
        (brygge_ir::SourceKind::Svn, "brygge-decode-svn"),
        (brygge_ir::SourceKind::Cvs, "brygge-decode-cvs"),
    ] {
        let is_svn = kind == brygge_ir::SourceKind::Svn;
        let label = decoder;
        let mut prov = blank_provenance(kind, decoder);
        if is_svn {
            prov.params.insert("source_form".into(), "dumpfile".into());
        }
        let ir = IrBuilder::new(prov).finish().unwrap();
        match run_against_source(&ir, &missing, &brygge_ir::Storage::Memory) {
            AgainstSourceOutcome::NotChecked(detail) => {
                assert!(detail.contains(&want), "{label}: {detail}");
                assert!(
                    !detail.contains("verify against the same form"),
                    "{label}: {detail}"
                );
            }
            _ => panic!("{label}: expected NotChecked"),
        }
    }
}

// ---- RFC 018, review 099 R-4: this build still verifies a 0.2.0 artifact against its real source ----

/// `crates/brygge/tests/data/contract-0.2.0-simple-repo.ir`: a **contract 0.2.0** artifact (RFC 018
/// D-7: this build writes only 0.3.0, but still reads 0.2.0), decoded by the 0.6.0 release's own
/// `brygge` (commit `2f1e659`) from exactly the fixture below — two commits, `a.txt` changed once, the
/// same pinned author/committer identity and date `TempRepo::git` always uses, so rebuilding this same
/// repository here reproduces the *exact* history that artifact records. Frozen rather than regenerated
/// by this build (which could not write contract 0.2.0 even if asked): it is the one artifact in this
/// crate's own tests that proves `verify --against-source` still works on the contract this build no
/// longer writes.
#[test]
fn verify_against_source_corresponds_on_a_0_2_0_artifact() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let r = TempRepo::new();
    r.commit("a.txt", "cli-0.2.0-fixture one\n", "c1");
    r.commit("a.txt", "cli-0.2.0-fixture two\n", "c2");

    let fixture =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/contract-0.2.0-simple-repo.ir");
    let bytes = std::fs::read(&fixture).unwrap();
    assert_eq!(
        &bytes[9..12],
        &[0u8, 2, 0],
        "the fixture is contract 0.2.0 (major 0, minor 2, patch 0)"
    );

    assert_eq!(
        run_verify(&fixture, Some(r.path()), None, None, Format::Human),
        exit::CLEAN,
        "verify --against-source corresponds on a 0.2.0 artifact, against the repository it was \
         decoded from (review 099 R-4)"
    );

    // Review 106 V-1: this fixture's provenance names brygge 0.6.0 (confirmed in the fixture's own
    // test below); this build is usually a different version, but not always — `main` carries this
    // fix before the 0.7.0 version bump itself lands (a separate, later commit), and CI runs this
    // suite on both sides of that bump. `assert_version_note` below handles either case. Direct
    // `run_against_source`, through the real reader (`from_file`), proves the comparison restamps
    // rather than falsely reporting tampering.
    let decoded = brygge_ir::from_file(&fixture).unwrap();
    match run_against_source(&decoded.ir, r.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::Corresponds(note) => assert_version_note("0.6.0", note),
        other => panic!("expected Corresponds across brygge versions, got {other:?}"),
    }
}

/// Review 106 V-1/V-2: whether `run_against_source` adds a version note depends on whether *this
/// build's* version actually differs from `fixture_version` — true whenever these fixtures (made by
/// brygge 0.6.0) are compared on a build that is genuinely a different version, but **not** on a
/// checkout of this very fix that sits on `main` before the separate version-bump commit lands (the
/// fixtures and this fix are reviewed and pushed first; see review 107's "Then"). Asserts whichever
/// is actually true, rather than assuming the gap, so these tests pass on both sides of that bump.
fn assert_version_note(fixture_version: &str, note: Option<String>) {
    let this_version = env!("CARGO_PKG_VERSION");
    if this_version == fixture_version {
        assert_eq!(
            note, None,
            "this build's own version equals the fixture's: no version gap, no note"
        );
    } else {
        assert_eq!(
            note,
            Some(format!(
                "decoded by brygge {fixture_version}, re-derived by {this_version}; the history is identical"
            )),
            "the note names both versions and says the history is identical"
        );
    }
}

/// Review 140: a decoder's floor is a fact about the decoder, not about the history (CR-07.6's pattern,
/// generalized beyond `svnadmin`) — two decodes that both succeeded prove the source holds nothing
/// either floor refuses, so `run_against_source` aligns `provenance.params["floor"]` exactly as it
/// aligns `svnadmin_version`, and never lets a floor difference alone read as tampering.
#[test]
fn verify_against_source_reproduces_when_only_the_decoder_floor_changed() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    write_vfile(
        &repo,
        "b.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.01", "add", "bbb\n"),
    );

    let mut ir1 = brygge_decode_cvs::decode(
        &brygge_decode_cvs::Source::LocalRepo(repo.path().to_path_buf()),
        &brygge_decode_cvs::Options::default(),
    )
    .unwrap();
    let real_floor = ir1.provenance.params.get("floor").cloned().unwrap();
    let older_floor: String = real_floor
        .split(',')
        .filter(|f| *f != "reconstruct-refs-trunk-collision")
        .collect::<Vec<_>>()
        .join(",");
    assert_ne!(
        older_floor, real_floor,
        "the test needs a real floor item to remove"
    );
    ir1.provenance
        .params
        .insert("floor".to_string(), older_floor);

    match run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::Reproduces(Some(note)) => {
            assert!(note.contains("added"), "{note}");
            assert!(note.contains("reconstruct-refs-trunk-collision"), "{note}");
        }
        other => panic!("expected Reproduces with a floor note, got {other:?}"),
    }
}

/// Review 140: the floor note is informational only — when the history also genuinely differs, the
/// outcome and its detail are exactly what the history difference alone gives, with no mention of the
/// (aligned, so irrelevant) floor.
#[test]
fn verify_against_source_ignores_the_floor_note_when_the_history_also_differs() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    write_vfile(
        &repo,
        "b.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.01", "add", "bbb\n"),
    );

    let mut ir1 = brygge_decode_cvs::decode(
        &brygge_decode_cvs::Source::LocalRepo(repo.path().to_path_buf()),
        &brygge_decode_cvs::Options::default(),
    )
    .unwrap();
    let real_floor = ir1.provenance.params.get("floor").cloned().unwrap();
    let older_floor: String = real_floor
        .split(',')
        .filter(|f| *f != "reconstruct-refs-trunk-collision")
        .collect::<Vec<_>>()
        .join(",");
    ir1.provenance
        .params
        .insert("floor".to_string(), older_floor);
    // A real history difference too: an extra ref nothing in the source has.
    let target = ir1.atoms[0].id;
    ir1.refs.push(RefRecord {
        name: "bogus".to_string(),
        kind: brygge_ir::RefKind::Tag,
        target,
        status: brygge_ir::EpistemicStatus::Stated,
        source: None,
        annotation: None,
    });

    match run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::DoesNotReproduce(detail) => {
            assert!(detail.contains("refs differ"), "{detail}");
            assert!(
                !detail.contains("floor"),
                "the floor difference must not appear: {detail}"
            );
        }
        other => panic!("expected DoesNotReproduce from the real ref difference, got {other:?}"),
    }
}

/// Review 140: `align_decoder_floor` touches only the `"floor"` key — every other `params` key (the
/// decoder's actual options) still compares, and a change there is still a real difference.
#[test]
fn verify_against_source_still_differs_when_a_non_floor_option_changes() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    write_vfile(
        &repo,
        "b.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.01", "add", "bbb\n"),
    );

    let mut ir1 = brygge_decode_cvs::decode(
        &brygge_decode_cvs::Source::LocalRepo(repo.path().to_path_buf()),
        &brygge_decode_cvs::Options::default(),
    )
    .unwrap();
    ir1.provenance
        .params
        .insert("window_secs".to_string(), "not-a-real-value".to_string());

    match run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::DoesNotReproduce(detail) => {
            assert!(!detail.contains("floor"), "{detail}");
        }
        other => {
            panic!("expected DoesNotReproduce (a non-floor param still differs), got {other:?}")
        }
    }
}

/// `crates/brygge/tests/data/contract-0.2.0-cvs-repro.ir`: review 106 V-2 — the architect's own runs
/// (reviews 106/107) showed what this would prove; this test brings that proof into the permanent
/// suite. Decoded by the 0.6.0 release's own `brygge` (commit `2f1e659`, built in a separate worktree)
/// from exactly the CVS repository [`decode_cvs_reconstructs_derived_changesets_and_reproduces`] above
/// builds: a plain directory with `a.c,v`/`b.c,v`, each `cvs_single_rev("alice", <date>, "add",
/// <content>)` — `("alice", "2024.01.01.12.00.00", "add", "aaa\n")` and `("alice",
/// "2024.01.01.12.00.01", "add", "bbb\n")`. Rebuild recipe: `cargo run -p brygge --bin brygge -- decode
/// cvs <that repository> --out contract-0.2.0-cvs-repro.ir`, run from a `2f1e659` worktree. CVS's
/// reconstructed changeset carries a `Derivation` (`by: "brygge-decode-cvs"`), so this exercises
/// `restamped`'s `Derived`-restamping path, not only `Stated` content.
///
/// Decoded **without** `--reconstruct-refs` (`provenance.params["reconstruct_refs"] == "false"`, 0 refs
/// at 0.6.0), so RFC 019's `trunk`-ref refinement (review 136 F-3) does not apply to this fixture at
/// all — an earlier note here wrongly attributed this test's one-time `NotChecked` result to the trunk
/// ref; the real cause was 071's own new floor item (review 140), changing
/// `provenance.params["floor"]` for every CVS decode, not only `--reconstruct-refs` ones.
/// `run_against_source` now aligns the decoder's `floor` param (review 140) exactly as it already
/// aligned `svnadmin_version` (CR-07.6), so this real cross-version case correctly `Reproduces` again,
/// with both the brygge-version note and the floor note.
#[test]
fn verify_against_source_reproduces_on_a_0_2_0_cvs_artifact_across_brygge_versions() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    write_vfile(
        &repo,
        "b.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.01", "add", "bbb\n"),
    );

    let fixture =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/contract-0.2.0-cvs-repro.ir");
    let decoded = brygge_ir::from_file(&fixture).unwrap();
    assert_eq!(decoded.contract, brygge_ir::ContractVersion::new(0, 2, 0));
    assert_eq!(
        decoded
            .ir
            .provenance
            .params
            .get("reconstruct_refs")
            .map(String::as_str),
        Some("false"),
        "this fixture was made without --reconstruct-refs, so the trunk-ref refinement never applies to it"
    );
    assert!(decoded.ir.refs.is_empty());

    match run_against_source(&decoded.ir, repo.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::Reproduces(note) => {
            let note = note.expect("both a version gap (0.6.0 vs 0.7.1) and a floor change apply");
            assert!(note.contains("0.6.0"), "{note}");
            assert!(note.contains("the history is identical"), "{note}");
            assert!(note.contains("floor changed"), "{note}");
            assert!(note.contains("reconstruct-refs-trunk-collision"), "{note}");
        }
        other => panic!("expected Reproduces across brygge versions, got {other:?}"),
    }
}

/// `crates/brygge/tests/data/contract-0.3.0-cvs-repro-0.7.1.ir`: review 139/140 C-2 — the fixture above
/// now documents a real, intentional decoder difference (the `trunk` ref, review 136 F-3), so this keeps
/// a CVS cross-version case that still reproduces: decoded **without** `--reconstruct-refs`, which the
/// main-line-ref change does not touch at all. Made with the published 0.7.1 binary
/// (`fixtures/previous-release/0.7.1/brygge`, never a local rebuild, per review 111 N-1), from exactly
/// the same repository as the test above: a plain directory with `a.c,v`/`b.c,v`, each
/// `cvs_single_rev("alice", <date>, "add", <content>)` — `("alice", "2024.01.01.12.00.00", "add",
/// "aaa\n")` and `("alice", "2024.01.01.12.00.01", "add", "bbb\n")`. Rebuild recipe: `fixtures/previous-
/// release/0.7.1/brygge decode cvs <that repository> --out contract-0.3.0-cvs-repro-0.7.1.ir` (no
/// `--reconstruct-refs`). This reproduces only because `run_against_source` now aligns the decoder's
/// `floor` param (review 140): 071's own new floor item would otherwise have made even this
/// mainline-only fixture diverge, on `main` today (equal version strings) as `does-not-reproduce`, and
/// after the 0.8.0 bump as `not-checked` — neither of which is true of the history.
#[test]
fn verify_against_source_reproduces_on_a_0_3_0_cvs_artifact_made_without_reconstruct_refs() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    write_vfile(
        &repo,
        "b.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.01", "add", "bbb\n"),
    );

    let fixture =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/contract-0.3.0-cvs-repro-0.7.1.ir");
    let decoded = brygge_ir::from_file(&fixture).unwrap();
    assert_eq!(decoded.contract, brygge_ir::ContractVersion::new(0, 3, 0));
    assert!(
        decoded.ir.refs.is_empty(),
        "made without --reconstruct-refs: no refs, so the trunk-ref change cannot affect this fixture"
    );

    match run_against_source(&decoded.ir, repo.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::Reproduces(note) => {
            let note = note.expect("today's build still carries 0.7.1, but the floor differs");
            assert!(note.contains("floor changed"), "{note}");
            assert!(note.contains("reconstruct-refs-trunk-collision"), "{note}");
        }
        other => panic!("expected Reproduces across brygge versions, got {other:?}"),
    }
}

/// `crates/brygge/tests/data/contract-0.2.0-git-rename.ir`: review 106 V-2's other fixture, with an
/// inferred rename (so a `Derived` *copy* record is restamped too, not just an atom's own status).
/// Decoded by the 0.6.0 release's own `brygge` (commit `2f1e659`) with `--infer-renames`, from a
/// three-commit repository using `TempRepo`'s own pinned identity/date (as
/// [`verify_against_source_corresponds_on_a_0_2_0_artifact`] above uses): `c1` adds `a.txt`
/// ("rename-fixture one\n"), `c2` adds `b.txt` ("rename-fixture two\n"), `c3` is `git mv a.txt c.txt`
/// alone. Rebuild recipe: build this exact repository with `TempRepo` (below), then `cargo run -p
/// brygge --bin brygge -- decode git <that repository> --out contract-0.2.0-git-rename.ir
/// --infer-renames`, run from a `2f1e659` worktree.
#[test]
fn verify_against_source_corresponds_on_a_0_2_0_git_rename_artifact_across_brygge_versions() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let r = TempRepo::new();
    r.commit("a.txt", "rename-fixture one\n", "c1");
    r.commit("b.txt", "rename-fixture two\n", "c2");
    r.git(&["mv", "a.txt", "c.txt"]);
    r.git(&[
        "-c",
        "commit.gpgsign=false",
        "commit",
        "-q",
        "-m",
        "c3-rename",
    ]);

    let fixture =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/contract-0.2.0-git-rename.ir");
    let decoded = brygge_ir::from_file(&fixture).unwrap();
    assert_eq!(decoded.contract, brygge_ir::ContractVersion::new(0, 2, 0));

    match run_against_source(&decoded.ir, r.path(), &brygge_ir::Storage::Memory) {
        AgainstSourceOutcome::Corresponds(note) => assert_version_note("0.6.0", note),
        other => panic!("expected Corresponds across brygge versions, got {other:?}"),
    }
}

/// Review 099 R-4 ("small"): `encode`'s own test plugin-interface accepts a contract-0.2.0 artifact too
/// (the CHANGELOG's "brygge still reads contract 0.2.0 artifacts" line covers `encode`, not only
/// `inspect`/`verify`) — `encode` hands either contract to the plugin unchanged, since it works from the
/// decoded `Ir`, never the artifact's own bytes.
#[test]
fn encode_accepts_a_0_2_0_artifact() {
    let fixture =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/contract-0.2.0-simple-repo.ir");
    let decoded = brygge_ir::from_file(&fixture).expect("the 0.2.0 fixture decodes");
    assert_eq!(decoded.contract, brygge_ir::ContractVersion::new(0, 2, 0));
    // `encode`'s own mandatory verify-first gate (OQ-4): the exact function it calls before handing an
    // artifact to a plugin. Proving it passes, and exits clean, on this 0.2.0 fixture is the
    // contract-acceptance claim `encode` makes — the plugin/built-in step itself (round-trip correctness)
    // is `crates/brygge/tests/encode_integration.rs`'s and `encode_git_fast_import.rs`'s own concern, not
    // duplicated here.
    let (_, exit_code) = verify_internal_report(&fixture, Format::Human);
    assert_eq!(
        exit_code,
        exit::CLEAN,
        "a 0.2.0 artifact's internal checks must pass before `encode` would run a plugin on it"
    );
}

// ---- RFC 018 D-5, §8 item 4: `verify --against-source` on an artifact with a transform chain ----

/// Rebuilds `ir` through `IrBuilder`, atom by atom in canonical order, remapping every parent/copy
/// `from_atom`/ref `target` through the new ids `add_atom` returns as it goes — every `AtomId` is
/// recomputed over whatever changed, so this is exactly the by-hand work review 102 T-1 pointed out a
/// real transform author has to repeat today (batch P's handoff will give `brygge-ir` a helper for it).
/// Atom 0's author claim is always changed, so the result genuinely differs in *content* from `ir`, not
/// only in a status wrapper. When `mark` is `Some(consumed)`, atom 0's status also becomes
/// `Transformed { step: 0, changed: [Author], prior: <its own original status> }` and one
/// `TransformRecord` naming `consumed` is added — a well-formed, honestly-marked chain (review 102
/// T-1). When `mark` is `None`, the status is left exactly as it was and no transform record is added:
/// a well-formed artifact that simply does not say anything changed — the lying forgery review 102 T-2
/// asks for, as opposed to the malformed one the original (now-replaced) test used.
fn rebuild_with_root_author_changed(ir: &brygge_ir::Ir, mark: Option<[u8; 32]>) -> brygge_ir::Ir {
    let mut b = IrBuilder::new(ir.provenance.clone());
    for id in ir.content.ids() {
        // Content-addressed: re-inserting the same bytes yields the same `BlobId`, so no blob
        // remapping is needed, only atom/ref ids.
        let bytes = ir.content.get(id).unwrap().unwrap();
        b.add_blob(bytes).unwrap();
    }
    if let Some(consumed) = mark {
        b.add_transform(TransformRecord {
            name: "rename-fixer".into(),
            version: "1.0.0".into(),
            params: BTreeMap::new(),
            consumed,
        });
    }
    let mut id_map: BTreeMap<brygge_ir::AtomId, brygge_ir::AtomId> = BTreeMap::new();
    for (i, atom) in ir.atoms.iter().enumerate() {
        let parents = atom
            .parents
            .iter()
            .map(|p| *id_map.get(p).expect("parents precede their children"))
            .collect();
        let copies = atom
            .copies
            .iter()
            .map(|c| CopyRecord {
                from: c.from.clone(),
                from_atom: *id_map
                    .get(&c.from_atom)
                    .expect("a copy's from_atom precedes it"),
                to: c.to.clone(),
                status: c.status.clone(),
            })
            .collect();
        let mut metadata = atom.metadata.clone();
        let mut status = atom.status.clone();
        if i == 0 {
            metadata.author = Some(Identity {
                name: brygge_ir::Text::utf8("Transformed Author"),
                email: Some(brygge_ir::Text::utf8("transformed@example.com")),
            });
            if mark.is_some() {
                status = EpistemicStatus::Transformed {
                    step: 0,
                    changed: vec![ChangedPart::Author],
                    prior: Box::new(status),
                };
            }
        }
        let new_id = b
            .add_atom(AtomDraft {
                parents,
                ops: atom.ops.clone(),
                copies,
                metadata,
                source: atom.source.clone(),
                status,
            })
            .unwrap();
        id_map.insert(atom.id, new_id);
    }
    for rf in &ir.refs {
        b.add_ref(RefRecord {
            name: rf.name.clone(),
            kind: rf.kind.clone(),
            target: *id_map.get(&rf.target).expect("a ref's target precedes it"),
            status: rf.status.clone(),
            source: rf.source.clone(),
            annotation: rf.annotation.clone(),
        })
        .unwrap();
    }
    b.set_loss(ir.loss.clone());
    for flag in &ir.flags {
        b.add_flag(flag.clone());
    }
    b.finish().unwrap()
}

fn write_ir_to(ir: &brygge_ir::Ir, path: &Path) {
    std::fs::write(path, brygge_ir::to_bytes(ir)).unwrap();
}

#[test]
fn verify_against_source_root_corresponds_and_wrong_consumed_through_the_real_reader() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("transform-fixture");
    let out = tmp_ir_path("transform-root");
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let fresh = read_ir(&out).unwrap().ir;
    let consumed = brygge_ir::digest_of(&fresh).unwrap();

    // A chain whose root really does correspond to a fresh decode: written through `to_bytes`, read
    // back through `brygge_ir::from_file` (so `check_structure` genuinely ran on it), then compared —
    // `root-corresponds`, same exit as plain `corresponds`.
    let honest = tmp_ir_path("transform-root-honest");
    write_ir_to(
        &rebuild_with_root_author_changed(&fresh, Some(consumed)),
        &honest,
    );
    let ir1 = read_ir(&honest).unwrap().ir;
    let against = run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory);
    assert_eq!(against.machine_label(), "root-corresponds");
    assert_eq!(
        Verdict::from(true, &against, &AgainstTargetOutcome::NotRun).machine_label(),
        "pass"
    );
    assert_eq!(
        Verdict::from(true, &against, &AgainstTargetOutcome::NotRun).exit_code(),
        exit::CLEAN
    );
    assert!(
        against
            .note()
            .is_some_and(|n| n.contains("1 transform(s) after it were not re-run")),
        "{:?}",
        against.note()
    );
    assert_eq!(
        run_verify(&honest, Some(repo.path()), None, None, Format::Machine),
        exit::CLEAN,
        "the real reader, check_structure, and the comparison together must still reach root-corresponds"
    );

    // A chain whose `consumed` names the wrong artifact: `does-not-correspond`, with the root detail —
    // again through a real write and a real read back.
    let wrong = tmp_ir_path("transform-root-wrong");
    write_ir_to(
        &rebuild_with_root_author_changed(&fresh, Some([0u8; 32])),
        &wrong,
    );
    let ir2 = read_ir(&wrong).unwrap().ir;
    let against = run_against_source(&ir2, repo.path(), &brygge_ir::Storage::Memory);
    assert_eq!(against.machine_label(), "does-not-correspond");
    assert_eq!(
        against.detail(),
        Some("the chain's root is not this source's decode")
    );
    assert_eq!(
        run_verify(&wrong, Some(repo.path()), None, None, Format::Machine),
        exit::VERIFY_FAILED
    );

    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&honest);
    let _ = std::fs::remove_file(&wrong);
}

/// Review 102 T-2: the forgery that actually matters is not a malformed artifact (a reader refuses that
/// outright, before any comparison — see
/// [`a_malformed_transform_chain_is_refused_by_the_reader_not_given_a_verdict`] below) but a
/// **well-formed** one that simply lies: the content changed, but the status stays `Stated` and no
/// transform record says so at all — indistinguishable from the decoder's own original by structure
/// alone. `verify`'s internal checks pass it (it is well-formed); `--against-source` is what catches it.
#[test]
fn verify_against_source_rejects_a_well_formed_artifact_that_lies_about_being_unchanged() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("transform-forgery");
    let out = tmp_ir_path("transform-forgery-base");
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let fresh = read_ir(&out).unwrap().ir;

    let lie = tmp_ir_path("transform-forgery-lie");
    write_ir_to(&rebuild_with_root_author_changed(&fresh, None), &lie);

    // Well-formed: the internal checks (structure, replay, derivations, source-invariants, provenance,
    // loss-boundary) all pass — nothing about this artifact's own shape is wrong.
    let (checks, internal_pass) = compute_internal_checks(&brygge_ir::from_file(&lie));
    let failing: Vec<&str> = checks
        .iter()
        .filter(|(_, outcome)| outcome.label() != "pass")
        .map(|(name, _)| *name)
        .collect();
    assert!(
        internal_pass,
        "a lying-but-well-formed artifact must still pass every internal check: {failing:?}"
    );

    let liar_ir = read_ir(&lie).unwrap().ir;
    let against = run_against_source(&liar_ir, repo.path(), &brygge_ir::Storage::Memory);
    assert_eq!(
        against.machine_label(),
        "does-not-correspond",
        "the content really did change, even though nothing in the artifact admits it"
    );
    assert_eq!(
        run_verify(&lie, Some(repo.path()), None, None, Format::Machine),
        exit::VERIFY_FAILED
    );

    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&lie);
}

/// Rebuild `ir` with its provenance's `brygge_version`/`decoder_version` set to the given strings,
/// otherwise identical (review 106 V-1's tests) — built independently of [`brygge_ir::Ir::restamped`]
/// itself, through the same `IrBuilder` pattern [`rebuild_with_root_author_changed`] uses, so these
/// tests do not exercise the function under test to build their own fixtures.
fn rebuild_with_version(
    ir: &brygge_ir::Ir,
    brygge_version: &str,
    decoder_version: &str,
) -> brygge_ir::Ir {
    let mut provenance = ir.provenance.clone();
    provenance.brygge_version = brygge_version.to_string();
    provenance.decoder_version = decoder_version.to_string();
    let mut b = IrBuilder::new(provenance);
    for id in ir.content.ids() {
        let bytes = ir.content.get(id).unwrap().unwrap();
        b.add_blob(bytes).unwrap();
    }
    for t in &ir.transforms {
        b.add_transform(t.clone());
    }
    let mut id_map: BTreeMap<brygge_ir::AtomId, brygge_ir::AtomId> = BTreeMap::new();
    for atom in &ir.atoms {
        let parents = atom
            .parents
            .iter()
            .map(|p| *id_map.get(p).expect("parents precede their children"))
            .collect();
        let copies = atom
            .copies
            .iter()
            .map(|c| CopyRecord {
                from: c.from.clone(),
                from_atom: *id_map
                    .get(&c.from_atom)
                    .expect("a copy's from_atom precedes it"),
                to: c.to.clone(),
                status: c.status.clone(),
            })
            .collect();
        let new_id = b
            .add_atom(AtomDraft {
                parents,
                ops: atom.ops.clone(),
                copies,
                metadata: atom.metadata.clone(),
                source: atom.source.clone(),
                status: atom.status.clone(),
            })
            .unwrap();
        id_map.insert(atom.id, new_id);
    }
    for rf in &ir.refs {
        b.add_ref(RefRecord {
            name: rf.name.clone(),
            kind: rf.kind.clone(),
            target: *id_map.get(&rf.target).expect("a ref's target precedes it"),
            status: rf.status.clone(),
            source: rf.source.clone(),
            annotation: rf.annotation.clone(),
        })
        .unwrap();
    }
    b.set_loss(ir.loss.clone());
    for flag in &ir.flags {
        b.add_flag(flag.clone());
    }
    b.finish().unwrap()
}

/// Review 106 V-1: a brygge/decoder-version difference is a fact about the tool, never itself evidence
/// of tampering. An artifact recorded as made by a (hypothetical) older brygge, whose history really
/// has changed since, must be `not-checked` — never `does-not-correspond` — with a detail naming the
/// version to re-run with, and the verdict `incomplete` (exit 1, never `pass`, never `fail`'s exit 50).
#[test]
fn verify_against_source_not_checked_when_recorded_version_differs_and_history_does_too() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("version-mismatch");
    let out = tmp_ir_path("version-mismatch-base");
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let fresh = read_ir(&out).unwrap().ir;

    // Both the recorded version and the history itself differ from a fresh decode — exactly the one
    // case the restamped comparison cannot resolve either way, so it must not guess.
    let edited = tmp_ir_path("version-mismatch-edited");
    write_ir_to(
        &rebuild_with_version(
            &rebuild_with_root_author_changed(&fresh, None),
            "0.0.1",
            "0.0.1",
        ),
        &edited,
    );

    let ir1 = read_ir(&edited).unwrap().ir;
    let against = run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory);
    assert_eq!(against.machine_label(), "not-checked");
    let detail = against.detail().expect("not-checked carries a detail");
    assert!(
        detail.contains("decoded by brygge 0.0.1"),
        "names the artifact's own version: {detail:?}"
    );
    assert!(
        detail.contains("run `verify --against-source` with brygge 0.0.1"),
        "says which brygge to re-run with: {detail:?}"
    );
    assert_eq!(
        Verdict::from(true, &against, &AgainstTargetOutcome::NotRun).machine_label(),
        "incomplete"
    );
    assert_eq!(
        run_verify(&edited, Some(repo.path()), None, None, Format::Machine),
        exit::FAILURE,
        "incomplete is never pass (0), and never fail's exit 50 either"
    );

    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&edited);
}

/// Review 106 V-1's third bullet: the root comparison of a chained artifact follows the same rule.
#[test]
fn verify_against_source_root_corresponds_with_both_notes_across_brygge_versions() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("version-chain");
    let out = tmp_ir_path("version-chain-base");
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let fresh = read_ir(&out).unwrap().ir;
    // What a (hypothetical) brygge 0.0.1 would have written for this exact repository: same content,
    // a different version stamp. The chain's `consumed` must cite *this* digest, not `fresh`'s own
    // (`digest_of` covers the provenance too) — exactly what a real 0.0.1 decode's chain would cite.
    let root_at_0_0_1 = rebuild_with_version(&fresh, "0.0.1", "0.0.1");
    let consumed = brygge_ir::digest_of(&root_at_0_0_1).unwrap();

    // An honest chain whose root really is this source's decode, recorded as made by that older
    // brygge: the chain's own author-change is real content; the version gap is not.
    let honest = tmp_ir_path("version-chain-honest");
    write_ir_to(
        &rebuild_with_root_author_changed(&root_at_0_0_1, Some(consumed)),
        &honest,
    );
    let ir1 = read_ir(&honest).unwrap().ir;
    let against = run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory);
    assert_eq!(against.machine_label(), "root-corresponds");
    let note = against.note().expect("root-corresponds carries a note");
    assert!(
        note.contains("1 transform(s) after it were not re-run"),
        "keeps the existing chain note: {note:?}"
    );
    assert!(
        note.contains("decoded by brygge 0.0.1"),
        "and adds the version note: {note:?}"
    );
    assert!(note.ends_with("the history is identical"), "{note:?}");
    assert_eq!(
        Verdict::from(true, &against, &AgainstTargetOutcome::NotRun).machine_label(),
        "pass"
    );
    assert_eq!(
        run_verify(&honest, Some(repo.path()), None, None, Format::Machine),
        exit::CLEAN
    );

    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&honest);
}

/// Review 102 T-2's other half: the chain-removed case the previous version of this test used is not a
/// forgery `--against-source` should ever see — it is a malformed artifact (`Transformed { step: 0,
/// .. }` with an empty `Ir.transforms`, so `step` is not less than the chain's own length `0`), refused
/// by the reader itself, before any source comparison runs at all. A read failure, not a verdict:
/// `verify`'s own exit code for "this does not even decode", not one of `--against-source`'s outcomes.
#[test]
fn a_malformed_transform_chain_is_refused_by_the_reader_not_given_a_verdict() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let repo = simple_repo("transform-malformed");
    let out = tmp_ir_path("transform-malformed-base");
    let code = run_decode(
        SourceKind::Git,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let fresh = read_ir(&out).unwrap().ir;
    let consumed = brygge_ir::digest_of(&fresh).unwrap();

    let mut malformed = rebuild_with_root_author_changed(&fresh, Some(consumed));
    malformed.transforms.clear(); // the status still claims step 0; the chain no longer has one.

    let bad = tmp_ir_path("transform-malformed-bytes");
    write_ir_to(&malformed, &bad);

    match brygge_ir::from_file(&bad) {
        Err(brygge_ir::Error::NonCanonical(m)) => assert!(m.contains("step"), "{m}"),
        other => panic!("expected a NonCanonical refusal, got {other:?}"),
    }
    assert_eq!(
        run_verify(&bad, Some(repo.path()), None, None, Format::Machine),
        exit::VERIFY_FAILED,
        "a read failure must still exit as a failure, never silently as a verdict of any kind"
    );

    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&bad);
}

#[test]
fn verify_against_source_root_reproduces_for_cvs() {
    let repo = cvs_repo();
    write_vfile(
        &repo,
        "a.c",
        &cvs_single_rev("alice", "2024.01.01.12.00.00", "add", "aaa\n"),
    );
    let out = repo.dir.join("out.ir");
    let code = run_decode(
        SourceKind::Cvs,
        repo.path(),
        &out,
        false,
        false,
        false,
        None,
        Format::Machine,
    );
    assert!(
        code == exit::CLEAN || code == exit::RECORDED_LOSS,
        "unexpected exit {code}"
    );
    let fresh = read_ir(&out).unwrap().ir;
    let consumed = brygge_ir::digest_of(&fresh).unwrap();

    let honest = repo.dir.join("transformed.ir");
    write_ir_to(
        &rebuild_with_root_author_changed(&fresh, Some(consumed)),
        &honest,
    );
    let ir1 = read_ir(&honest).unwrap().ir;
    let against = run_against_source(&ir1, repo.path(), &brygge_ir::Storage::Memory);
    assert_eq!(against.machine_label(), "root-reproduces");
    assert_eq!(
        Verdict::from(true, &against, &AgainstTargetOutcome::NotRun).machine_label(),
        "pass"
    );
    assert_eq!(
        run_verify(&honest, Some(repo.path()), None, None, Format::Machine),
        exit::CLEAN
    );
}

/// RFC 018 D-5 §5: `inspect`'s own transforms overview — shown regardless of `--atoms`, with each
/// step's name/version/consumed digest and how many atoms/refs/drops it changed.
#[test]
fn inspect_shows_the_transform_chain_overview() {
    let ir = rebuild_with_root_author_changed(&machine_output_fixture(), Some([0x11; 32]));

    let human = render_transforms_human(&ir, false);
    assert!(human.contains("transforms: 1"), "{human}");
    assert!(
        human.contains("0. rename-fixer 1.0.0 — consumed sha256:"),
        "{human}"
    );
    assert!(human.contains("changed 1 atom(s)"), "{human}");
    assert!(
        !human.contains("      "),
        "params are not shown without --atoms: {human}"
    );

    let with_params = render_transforms_human(&ir, true);
    assert!(with_params.contains("transforms: 1"), "{with_params}");

    let machine = render_transforms_machine(&ir);
    assert!(machine.contains("transforms=1"), "{machine}");
    assert!(
        machine.contains("transform.0.name=rename-fixer"),
        "{machine}"
    );
    assert!(machine.contains("transform.0.version=1.0.0"), "{machine}");
    assert!(machine.contains("transform.0.changed_atoms=1"), "{machine}");
    assert!(machine.contains("transform.0.changed_refs=0"), "{machine}");
    assert!(machine.contains("transform.0.dropped=0"), "{machine}");

    // A decoder's own report (no chain) is unchanged: neither renderer prints anything at all.
    assert_eq!(render_transforms_human(&machine_output_fixture(), true), "");
    assert_eq!(render_transforms_machine(&machine_output_fixture()), "");
}

// ---- `encode git`'s in-process check (RFC 019 D-6, batch G2) ----------------------------------------

/// A minimal, otherwise-valid one-atom Git-sourced artifact: one file, one branch ref — everything
/// `encode git`'s own pre-flight accepts, so the only thing that can refuse it is the injected check.
fn minimal_git_artifact_for_encode() -> brygge_ir::Ir {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"hello\n".to_vec()).unwrap();
    let atom = b
        .add_atom(AtomDraft {
            parents: vec![],
            ops: vec![stated_add("f.txt", blob)],
            copies: vec![],
            metadata: MetadataClaims::default(),
            source: src(brygge_ir::SourceKind::Git, b"c1"),
            status: EpistemicStatus::Stated,
        })
        .unwrap();
    b.add_ref(RefRecord {
        name: "main".to_string(),
        kind: RefKind::Branch,
        target: atom,
        status: EpistemicStatus::Stated,
        source: None,
        annotation: None,
    })
    .unwrap();
    b.finish().unwrap()
}

/// RFC 019 D-6 §3: proves the refusal path through the internal seam (never an environment variable or
/// a flag in the shipped product — [`run_encode_git`] always passes the real check; only this test
/// injects a different one), with a real `git init`/`fast-import` underneath: a failed comparison must
/// remove the partial working directory and write nothing at `<dir>` or `<dir>.brygge-report`.
#[test]
fn a_failed_check_removes_the_partial_directory_and_writes_nothing() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let ir = minimal_git_artifact_for_encode();
    let artifact_path = tmp_ir_path("encode-git-check-refusal");
    std::fs::write(&artifact_path, brygge_ir::to_bytes(&ir)).unwrap();

    let dir = scratch_dir("encode-git-check-refusal");
    let out = dir.join("repo.git");

    let always_fails = |_ir: &Ir,
                        _digest: &[u8; 32],
                        _partial: &Path,
                        _git: &Path,
                        _env: &GitEnv,
                        _default_branch_ref: &str| {
        encode_git::Comparison::DoesNotCorrespond(vec!["a fake, injected difference".to_string()])
    };
    let code = run_encode_git_with_check(&artifact_path, &out, Format::Machine, always_fails);
    assert_eq!(code, exit::FAILURE);
    assert!(!out.exists(), "nothing must be written at <dir>");
    let report_path = {
        let mut p = out.as_os_str().to_os_string();
        p.push(".brygge-report");
        PathBuf::from(p)
    };
    assert!(
        !report_path.exists(),
        "nothing must be written at the report path either"
    );

    // No `.partial-*` sibling left behind either — the fake check's refusal must have cleaned it up,
    // just as a real `does-not-correspond` from the production check would.
    let entries: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name())
        .collect();
    assert!(
        entries.is_empty(),
        "a .partial directory was left behind: {entries:?}"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// The honest-copy path: when the injected check says `Corresponds`, the repository and report are
/// written normally — proving the seam's two outcomes are both real, not just the refusal one.
#[test]
fn a_passing_check_writes_the_repository_and_report_normally() {
    if !git_available() {
        eprintln!("skipping: git not on PATH");
        return;
    }
    let ir = minimal_git_artifact_for_encode();
    let artifact_path = tmp_ir_path("encode-git-check-pass");
    std::fs::write(&artifact_path, brygge_ir::to_bytes(&ir)).unwrap();

    let dir = scratch_dir("encode-git-check-pass");
    let out = dir.join("repo.git");

    let always_passes =
        |_ir: &Ir,
         _digest: &[u8; 32],
         _partial: &Path,
         _git: &Path,
         _env: &GitEnv,
         _default_branch_ref: &str| encode_git::Comparison::Corresponds;
    let code = run_encode_git_with_check(&artifact_path, &out, Format::Machine, always_passes);
    assert!(out.exists(), "the repository must be written");
    let report_path = {
        let mut p = out.as_os_str().to_os_string();
        p.push(".brygge-report");
        PathBuf::from(p)
    };
    let report = std::fs::read_to_string(&report_path).expect("the report must be written");
    assert!(report.contains("encode_git.check=corresponds"), "{report}");
    assert_ne!(code, exit::FAILURE);
    let _ = std::fs::remove_dir_all(&dir);
}

/// RFC 019 D-6 §4 (batch G2): a self-measuring helper for the memory/time proof, run only when invoked
/// by name (never part of the ordinary suite — it needs `BRYGGE_G2_MEASURE_ARTIFACT`/`_OUT` set to real
/// paths). It calls [`run_encode_git_with_check`] with the check bypassed (the internal seam, never an
/// environment variable or flag in the shipped product — only this test build reaches it), then prints
/// its own peak RSS (`VmHWM`, from `/proc/self/status`; `brygge-ir` forbids `unsafe_code`, so this test
/// binary cannot call `getrusage`/`wait4` either, the same reason `release-corpus.py` is Python) so a
/// parent process measuring wall time around this one child gets both figures with no extra plumbing.
#[test]
fn g2_measure_encode_alone_check_bypassed() {
    let Ok(artifact) = std::env::var("BRYGGE_G2_MEASURE_ARTIFACT") else {
        return;
    };
    let out =
        std::env::var("BRYGGE_G2_MEASURE_OUT").expect("BRYGGE_G2_MEASURE_OUT must be set too");
    let bypass = |_ir: &Ir,
                  _digest: &[u8; 32],
                  _partial: &Path,
                  _git: &Path,
                  _env: &GitEnv,
                  _default_branch_ref: &str| encode_git::Comparison::Corresponds;
    let code = run_encode_git_with_check(
        Path::new(&artifact),
        Path::new(&out),
        Format::Machine,
        bypass,
    );
    assert_ne!(
        code,
        exit::FAILURE,
        "the bypassed encode itself must still succeed"
    );
    let status = std::fs::read_to_string("/proc/self/status").expect("read /proc/self/status");
    let peak_kib = status
        .lines()
        .find_map(|l| l.strip_prefix("VmHWM:"))
        .and_then(|rest| rest.split_whitespace().next())
        .expect("VmHWM line");
    println!("g2_measure_peak_kib={peak_kib}");
}

// ---- transform authors (RFC 019 D-4, batch G3): level 1, hand-built Irs --------------------------

/// A one-atom `Ir` with a bare-name (no email) author claim — the Subversion/CVS shape, built on
/// `SourceKind::Git` so the hand-built atom needs no `Derived` status of its own (the model requires
/// every CVS-kind atom to be `Derived(ReconstructedChangeset|ReconstructedBranch)`; the source kind
/// itself is incidental to what this test exercises — the map's bare-name matching rule).
fn bare_author_atom_ir(name: &str) -> Ir {
    let mut b = IrBuilder::new(blank_provenance(
        brygge_ir::SourceKind::Git,
        "brygge-decode-git",
    ));
    let blob = b.add_blob(b"x".to_vec()).unwrap();
    b.add_atom(AtomDraft {
        parents: vec![],
        ops: vec![stated_add("a", blob)],
        copies: vec![],
        metadata: MetadataClaims {
            author: Some(Identity {
                name: Text::utf8(name),
                email: None,
            }),
            ..MetadataClaims::default()
        },
        source: src(brygge_ir::SourceKind::Git, b"c1"),
        status: EpistemicStatus::Stated,
    })
    .unwrap();
    b.finish().unwrap()
}

fn write_map(contents: &str) -> PathBuf {
    let path = tmp_ir_path("authors-map").with_extension("map");
    std::fs::write(&path, contents).unwrap();
    path
}

#[test]
fn transform_authors_maps_a_bare_name_identity() {
    let ir = bare_author_atom_ir("alice");
    let artifact = tmp_ir_path("authors-in");
    std::fs::write(&artifact, brygge_ir::to_bytes(&ir)).unwrap();
    let map = write_map("alice = Alice Example <alice@example.invalid>\n");
    let out = tmp_ir_path("authors-out");

    let code = run_transform_authors(&artifact, &map, &out, true, Format::Human);
    assert_ne!(
        code,
        exit::USAGE,
        "a full map must not refuse --require-all"
    );
    assert!(out.exists(), "the mapped artifact must be written");

    let output = brygge_ir::from_file(&out).unwrap();
    let atom = &output.ir.atoms[0];
    let author = atom.metadata.author.as_ref().unwrap();
    assert_eq!(author.name.as_utf8(), Some("Alice Example"));
    assert_eq!(
        author.email.as_ref().and_then(Text::as_utf8),
        Some("alice@example.invalid")
    );
    match &atom.status {
        EpistemicStatus::Transformed { changed, .. } => {
            assert_eq!(changed, &vec![ChangedPart::Author]);
        }
        other => panic!("expected Transformed, got {other:?}"),
    }

    let _ = std::fs::remove_file(&artifact);
    let _ = std::fs::remove_file(&map);
    let _ = std::fs::remove_file(&out);
}

#[test]
fn transform_authors_require_all_refuses_an_unmapped_identity_and_writes_nothing() {
    let ir = bare_author_atom_ir("bob");
    let artifact = tmp_ir_path("authors-in-unmapped");
    std::fs::write(&artifact, brygge_ir::to_bytes(&ir)).unwrap();
    // A map with no entry for "bob" at all.
    let map = write_map("alice = Alice Example <alice@example.invalid>\n");
    let out = tmp_ir_path("authors-out-unmapped");

    let code = run_transform_authors(&artifact, &map, &out, true, Format::Human);
    assert_eq!(
        code,
        exit::USAGE,
        "--require-all must refuse an unmapped identity"
    );
    assert!(!out.exists(), "nothing must be written on refusal");

    let _ = std::fs::remove_file(&artifact);
    let _ = std::fs::remove_file(&map);
}

#[test]
fn transform_authors_without_require_all_writes_the_unmapped_identity_unchanged() {
    let ir = bare_author_atom_ir("bob");
    let artifact = tmp_ir_path("authors-in-partial");
    std::fs::write(&artifact, brygge_ir::to_bytes(&ir)).unwrap();
    let map = write_map("alice = Alice Example <alice@example.invalid>\n");
    let out = tmp_ir_path("authors-out-partial");

    let code = run_transform_authors(&artifact, &map, &out, false, Format::Human);
    assert_ne!(code, exit::USAGE);
    assert!(
        out.exists(),
        "the artifact is still written without --require-all"
    );

    let output = brygge_ir::from_file(&out).unwrap();
    let atom = &output.ir.atoms[0];
    // "bob" was never touched, so it keeps its original (unmarked) status.
    assert_eq!(atom.status, EpistemicStatus::Stated);
    let author = atom.metadata.author.as_ref().unwrap();
    assert_eq!(author.name.as_utf8(), Some("bob"));
    assert_eq!(author.email, None);

    let _ = std::fs::remove_file(&artifact);
    let _ = std::fs::remove_file(&map);
    let _ = std::fs::remove_file(&out);
}

#[test]
fn render_inspect_authors_human_is_already_in_map_file_form() {
    let identities = vec![
        authors::IdentityCount {
            identity: Identity {
                name: Text::utf8("deraadt"),
                email: None,
            },
            author: 812,
            committer: 812,
            tagger: 0,
        },
        authors::IdentityCount {
            identity: Identity {
                name: Text::utf8("Alice Example"),
                email: Some(Text::utf8("alice@example.org")),
            },
            author: 4,
            committer: 0,
            tagger: 0,
        },
    ];
    let s = render_inspect_authors_human(&identities);
    assert!(
        s.starts_with("# brygge inspect --authors: 2 identities;"),
        "{s}"
    );
    assert!(s.contains("deraadt ="), "{s}");
    assert!(s.contains("812 author, 812 committer"), "{s}");
    assert!(s.contains("Alice Example <alice@example.org> ="), "{s}");
    assert!(s.contains("4 author"), "{s}");
    // Already in map-file form: fill in each right side and it parses straight back.
    let filled = s.replace("deraadt =", "deraadt = Theo <t@x>").replace(
        "Alice Example <alice@example.org> =",
        "Alice Example <alice@example.org> = Alice A. <a@x>",
    );
    let map = crate::authors::parse_map(filled.as_bytes()).unwrap();
    assert_eq!(map.mappings.len(), 2);
}

#[test]
fn render_inspect_authors_machine_carries_the_counts_per_role() {
    let identities = vec![authors::IdentityCount {
        identity: Identity {
            name: Text::utf8("deraadt"),
            email: None,
        },
        author: 812,
        committer: 3,
        tagger: 1,
    }];
    let s = render_inspect_authors_machine(&identities);
    assert!(s.starts_with("inspect_authors_version=1\n"), "{s}");
    assert!(s.contains("authors.0.name=deraadt"), "{s}");
    assert!(!s.contains("authors.0.email="), "no email, no key: {s}");
    assert!(s.contains("authors.0.count.author=812"), "{s}");
    assert!(s.contains("authors.0.count.committer=3"), "{s}");
    assert!(s.contains("authors.0.count.tagger=1"), "{s}");
}

#[test]
fn transform_authors_result_text_machine_is_keyed_and_versioned() {
    let summary = brygge_ir::transform::StepSummary {
        step: 0,
        atoms_changed: 1,
        ops_changed: 0,
        refs_changed: 0,
        dropped: 0,
    };
    let s = transform_authors_result_text(Format::Machine, &summary, 1, 0);
    assert!(s.contains("transform_authors_version=1"), "{s}");
    assert!(s.contains("transform.step=0"), "{s}");
    assert!(s.contains("transform.authors.mapped=1"), "{s}");
    assert!(s.contains("transform.authors.unmapped=0"), "{s}");
}