smackdebt 0.3.0

Find costly code debt and see whether your changes make it better
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
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
// The hermetic pinning and the edge-row invariant are shared with the unified
// suite; only those helpers are mapped in, because this suite builds its
// commands directly.
#[path = "support/edges.rs"]
mod edges;
#[path = "support/hermetic.rs"]
mod support;

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

use edges::assert_no_dependency_edge_rows;
use support::hermetic_env;

const SOURCE_ENGINE_FIXTURE: &str =
    concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/source-engine");
const STATIC_ARCHITECTURE_FIXTURE: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/tests/fixtures/static-architecture"
);

#[test]
fn serial_and_parallel_codebase_output_match() {
    let project = fixture();
    let serial = run(["--jobs", "1", project.path().to_str().unwrap()]);
    let parallel = run(["--jobs", "4", project.path().to_str().unwrap()]);
    assert_eq!(serial, parallel);
    let text = String::from_utf8(serial).unwrap();
    assert!(text.starts_with("smackdebt · "), "{text}");
    assert!(text.contains(" high · "), "{text}");
    assert!(text.contains(" checked"), "{text}");
    assert!(!text.contains("AREAS"));
    assert!(!text.contains("FINDINGS"));
}

#[test]
fn serial_and_parallel_json_match_and_follow_schema_four() {
    let project = fixture();
    let path = project.path().to_str().unwrap();
    let serial = run(["--json", "--jobs", "1", path]);
    let parallel = run(["--json", "--jobs", "4", path]);
    assert_eq!(serial, parallel);
    let report: serde_json::Value = serde_json::from_slice(&serial).unwrap();
    assert_eq!(report["schema_version"], 4);
    assert_eq!(report["mode"], "codebase");
    assert!(report["findings"].is_array());
    validate_schema(&report);
    assert_index_integrity(&report);
}

#[test]
fn mixed_language_parallel_cutover_preserves_terminal_and_json_bytes() {
    let project = mixed_fixture(100);
    let path = project.path().to_str().unwrap();
    assert_eq!(
        run(["--jobs", "1", "--color", "never", path]),
        run(["--jobs", "4", "--color", "never", path])
    );
    assert_eq!(
        run(["--json", "--jobs", "1", path]),
        run(["--json", "--jobs", "4", path])
    );
}

#[test]
fn diff_reports_metric_changes_from_the_worktree() {
    let project = fixture();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: initial source"]);
    fs::write(
        project.path().join("src/work.rb"),
        "def work(items)\n  items.each do |item|\n    if item.ready?\n      if item.large?\n        ship(item)\n      end\n    end\n  end\nend\n",
    )
    .unwrap();

    let output = run([
        "diff",
        "main",
        project.path().to_str().unwrap(),
        "--json",
        "--jobs",
        "1",
    ]);
    let report: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(report["mode"], "diff");
    assert!(!report["comparisons"].as_array().unwrap().is_empty());
    validate_schema(&report);
    assert_index_integrity(&report);
    assert!(!report["comparisons"].as_array().unwrap().is_empty());
}

/// A repository with no recognizable default branch cannot pick one for the
/// user, so the bare `diff` states the one fixable value on standard error.
#[test]
fn a_diff_with_no_comparison_branch_names_the_fix() {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "trunk"]);
    fs::write(project.path().join("work.rs"), "pub fn work() {}\n").unwrap();
    commit_as(
        project.path(),
        "Smackdebt Test",
        "smackdebt@example.invalid",
        "base",
    );
    smackdebt()
        .current_dir(project.path())
        .arg("diff")
        .assert()
        .code(1)
        .stdout("")
        .stderr(
            "smackdebt: no comparison branch was found; pass one, for example `smackdebt diff main`\n",
        );
}

#[test]
fn anonymous_diff_matching_is_safe_and_worker_output_is_equal() {
    let project = anonymous_diff_fixture();
    let terminal = |jobs| {
        let output = smackdebt()
            .current_dir(project.path())
            .env("COLUMNS", "120")
            .args(["diff", "HEAD", "--all", "--color", "never", "--jobs", jobs])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        output.stdout
    };
    let serial_terminal = terminal("1");
    let automatic_terminal = terminal("4");
    assert_eq!(serial_terminal, automatic_terminal);
    let text = String::from_utf8(serial_terminal).unwrap();
    assert_eq!(
        text.matches("1 file has anonymous units that could not be matched safely")
            .count(),
        1,
        "{text}"
    );

    let machine = |jobs| {
        let output = smackdebt()
            .current_dir(project.path())
            .args(["diff", "HEAD", "--json", "--jobs", jobs])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        output.stdout
    };
    let serial_json = machine("1");
    let automatic_json = machine("4");
    assert_eq!(serial_json, automatic_json);
    let report: serde_json::Value = serde_json::from_slice(&serial_json).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    let kinds: Vec<_> = report["comparisons"]
        .as_array()
        .unwrap()
        .iter()
        .map(|value| value["kind"].as_str().unwrap())
        .collect();
    assert_eq!(kinds.iter().filter(|kind| **kind == "ambiguous").count(), 1);
    assert_eq!(kinds.iter().filter(|kind| **kind == "added").count(), 2);
    assert_eq!(kinds.iter().filter(|kind| **kind == "removed").count(), 3);
    assert_eq!(
        kinds
            .iter()
            .filter(|kind| **kind == "metric_changed")
            .count(),
        1
    );
    assert_eq!(
        report["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|value| value["kind"] == "ambiguous_identity")
            .count(),
        1
    );
    let json_text = String::from_utf8(serial_json).unwrap();
    assert!(!json_text.contains("binding:"));
    assert!(!json_text.contains("argument:"));
    assert!(
        report["comparisons"]
            .as_array()
            .unwrap()
            .iter()
            .all(|value| value["name"] != "steady"),
        "the unchanged moved callback must disappear"
    );
}

/// A Grape API edits one endpoint. Every block enclosing that endpoint is now
/// written differently, so exact syntax alone loses the whole resource and one
/// edit reads as several blocks added and several removed. The call chain each
/// block hangs under follows them through the edit instead.
#[test]
fn a_ruby_dsl_edit_pairs_its_blocks_instead_of_counting_one_change_twice() {
    let project = ruby_dsl_diff_fixture();
    let terminal = smackdebt()
        .current_dir(project.path())
        .env("COLUMNS", "120")
        .args(["diff", "HEAD", "--all", "--color", "never"])
        .output()
        .unwrap();
    assert!(terminal.status.success());
    let terminal = String::from_utf8(terminal.stdout).unwrap();
    assert!(!terminal.contains("anonymous units"), "{terminal}");

    let output = smackdebt()
        .current_dir(project.path())
        .args(["diff", "HEAD", "--json"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    let comparisons = report["comparisons"].as_array().unwrap();
    assert!(
        comparisons
            .iter()
            .all(|value| value["kind"] != "added" && value["kind"] != "removed"),
        "{comparisons:?}"
    );
    let changed: Vec<_> = comparisons
        .iter()
        .filter(|value| value["kind"] == "metric_changed" || value["kind"] == "regressed")
        .collect();
    assert_eq!(changed.len(), 1, "{comparisons:?}");
    assert!(changed[0]["before"].is_object() && changed[0]["after"].is_object());
    assert!(
        report["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .all(|value| value["kind"] != "ambiguous_identity")
    );
}

fn diff_terminal(project: &Path, all: bool) -> String {
    let mut arguments = vec!["diff", "HEAD", "--color", "never"];
    if all {
        arguments.push("--all");
    }
    let output = smackdebt()
        .current_dir(project)
        .env("COLUMNS", "120")
        .args(arguments)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap()
}

/// An anonymous unit was rewritten past recognition, so the matcher holds one
/// unpaired unit on each side. The report states that, keeps both as machine
/// record and `--all` context, and moves debt in neither direction on them.
#[test]
fn an_unpairable_anonymous_edit_is_stated_and_counted_in_no_direction() {
    let project = unpairable_anonymous_fixture();
    let terminal = |all: bool| diff_terminal(project.path(), all);
    let default = terminal(false);
    assert!(
        default.contains("1 file has anonymous units that could not be matched safely"),
        "{default}"
    );
    assert!(default.contains("No debt changed."), "{default}");
    assert!(
        default.contains("worse 0 · better 0 · changed 0"),
        "{default}"
    );
    assert!(!default.contains("FINDINGS"), "{default}");
    let all = terminal(true);
    assert!(all.contains("handlers.js · closure"), "{all}");
    assert!(!all.contains("  worse "), "{all}");
    assert!(!all.contains("  better "), "{all}");

    let output = smackdebt()
        .current_dir(project.path())
        .args(["diff", "HEAD", "--json"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    let unpaired: Vec<_> = report["comparisons"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|value| value["kind"] == "added" || value["kind"] == "removed")
        .collect();
    assert_eq!(unpaired.len(), 2, "{unpaired:?}");
    assert!(
        unpaired
            .iter()
            .all(|value| value["participation"] == "context" && value["direction"] == "changed"),
        "{unpaired:?}"
    );
    assert!(
        unpaired
            .iter()
            .any(|value| value["ratings"]["after"] == "watch")
            && unpaired
                .iter()
                .any(|value| value["ratings"]["before"] == "watch"),
        "the rule has to bite on rated units: {unpaired:?}"
    );
    assert_eq!(
        report["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|value| value["kind"] == "ambiguous_identity")
            .count(),
        1
    );
}

/// The same broken pair, plus a block that is genuinely new. Withholding the
/// pair must not swallow the addition with it: one unpaired removal answers
/// for one unpaired addition, and the second addition is debt this diff added.
#[test]
fn a_genuinely_new_unit_beside_an_unpairable_one_still_increases_debt() {
    let project = unpairable_beside_a_new_unit_fixture();
    let default = diff_terminal(project.path(), false);
    assert!(default.contains("Debt increased."), "{default}");
    assert!(
        default.contains("1 file has anonymous units that could not be matched safely"),
        "{default}"
    );

    let output = smackdebt()
        .current_dir(project.path())
        .args(["diff", "HEAD", "--json"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    let unpaired: Vec<_> = report["comparisons"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|value| value["kind"] == "added" || value["kind"] == "removed")
        .collect();
    assert_eq!(unpaired.len(), 3, "{unpaired:?}");
    let counted: Vec<_> = unpaired
        .iter()
        .filter(|value| value["participation"] == "verdict")
        .collect();
    assert_eq!(counted.len(), 1, "{unpaired:?}");
    assert_eq!(counted[0]["kind"], "added");
    assert_eq!(counted[0]["direction"], "worse");
    assert_eq!(
        report["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|value| value["kind"] == "ambiguous_identity")
            .count(),
        1
    );
}

#[test]
fn repeated_declared_names_do_not_emit_an_anonymous_warning() {
    let project = named_duplicate_fixture();
    let terminal = smackdebt()
        .current_dir(project.path())
        .args(["diff", "HEAD", "--all", "--color", "never"])
        .output()
        .unwrap();
    assert!(terminal.status.success());
    let terminal = String::from_utf8(terminal.stdout).unwrap();
    assert!(!terminal.contains("anonymous units"), "{terminal}");

    let output = smackdebt()
        .current_dir(project.path())
        .args(["diff", "HEAD", "--json"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(
        report["comparisons"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|value| value["kind"] == "ambiguous")
            .count(),
        1
    );
    assert!(
        report["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .all(|value| value["kind"] != "ambiguous_identity")
    );
}

#[test]
fn added_and_removed_diff_cards_state_the_measurements_of_the_side_that_exists() {
    let project = one_sided_diff_fixture();
    let output = smackdebt()
        .current_dir(project.path())
        .env("COLUMNS", "120")
        .args(["diff", "HEAD", "--all", "--color", "never"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let terminal = String::from_utf8(output.stdout).unwrap();
    // An added unit has an after side only, so the card states it absolutely.
    assert!(
        terminal.contains(
            "        added · cognitive 3 · cyclomatic 3 · statements 2 · nesting 2 · parameters 1\n"
        ),
        "{terminal}"
    );
    // A removed unit has a before side only, stated the same way.
    assert!(
        terminal.contains(
            "        removed · cognitive 3 · cyclomatic 3 · statements 2 · nesting 2 · parameters 2\n"
        ),
        "{terminal}"
    );
    // The card carries facts, never arithmetic, for a side that does not exist.
    assert!(!terminal.contains('→'), "{terminal}");
}

#[test]
fn invalid_project_config_uses_argument_exit_code() {
    let project = fixture();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[thresholds.cognitive]\nwatch = 25\nhigh = 10\n",
    )
    .unwrap();
    smackdebt()
        .arg(project.path())
        .assert()
        .code(2)
        .stderr(predicates::str::contains("high greater than watch"));
}

#[test]
fn same_level_source_role_conflict_has_exact_argument_failure_streams() {
    let project = fixture();
    fs::write(
        project.path().join("conflict.js"),
        "export function work() { return 1; }\n",
    )
    .unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[source_roles]\ntest = ['*.js']\nfixture = ['conflict.js']\n",
    )
    .unwrap();

    smackdebt()
        .arg(project.path())
        .assert()
        .code(2)
        .stdout("")
        .stderr(
            "smackdebt: source roles conflict for conflict.js: test, fixture; update .smackdebt.toml\n",
        );
}

const GATE_BASELINE_HEADERS: &str = "# smackdebt gate baseline v1\npath\tsignal\thigh\twatch\n";

/// One High-cognitive JavaScript unit under a lowered threshold, so the
/// observed gate snapshot carries exactly one cognitive key.
fn gate_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("work.js"),
        "export function work(x) {\n  if (x) {\n    if (x > 1) {\n      return 2;\n    }\n  }\n  return 1;\n}\n",
    )
    .unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[thresholds.cognitive]\nwatch = 1\nhigh = 2\n",
    )
    .unwrap();
    project
}

#[test]
fn a_missing_gate_baseline_has_exact_argument_failure_streams() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    smackdebt()
        .arg("gate")
        .arg(project.path())
        .assert()
        .code(2)
        .stdout("")
        .stderr(format!(
            "smackdebt: baseline not found: {}; rerun this gate with --update to create it\n",
            baseline.display()
        ));
}

#[test]
fn a_clean_gate_states_zero_totals_and_succeeds() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    fs::write(
        &baseline,
        format!("{GATE_BASELINE_HEADERS}work.js\tcognitive\t1\t0\n"),
    )
    .unwrap();
    smackdebt()
        .arg("gate")
        .arg(project.path())
        .assert()
        .code(0)
        .stdout(format!(
            "smackdebt gate · {}\n  Passed. Debt stayed within the baseline.\n0 regressions · 0 improvements\n",
            baseline.display()
        ))
        .stderr("");
}

/// The bare `gate` reads the working directory and names its baseline with
/// the same relative path a checked-in pipeline would commit.
#[test]
fn a_gate_without_a_path_reads_the_working_directory() {
    let project = gate_fixture();
    fs::write(
        project.path().join(".smackdebt-baseline.tsv"),
        format!("{GATE_BASELINE_HEADERS}work.js\tcognitive\t1\t0\n"),
    )
    .unwrap();
    smackdebt()
        .current_dir(project.path())
        .args(["gate", "--jobs", "1"])
        .assert()
        .code(0)
        .stdout("smackdebt gate · .smackdebt-baseline.tsv\n  Passed. Debt stayed within the baseline.\n0 regressions · 0 improvements\n")
        .stderr("");
}

#[test]
fn a_regressed_gate_names_the_offending_row_and_exits_three() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    fs::write(&baseline, GATE_BASELINE_HEADERS).unwrap();
    smackdebt()
        .arg("gate")
        .arg(project.path())
        .assert()
        .code(3)
        .stdout(format!(
            concat!(
                "smackdebt gate · {}\n",
                "  Failed. Debt exceeded the baseline.\n",
                "1 regression · 0 improvements\n",
                "\nFINDINGS\n",
                "  worse work.js · cognitive · high 0 → 1\n",
                "\n",
                "  next: Review these changes. Fix regressions, or rerun this gate with --update to accept them.\n",
            ),
            baseline.display()
        ))
        .stderr("");
}

#[test]
fn a_looser_gate_baseline_reports_improvements_and_stays_untouched() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    let written =
        format!("{GATE_BASELINE_HEADERS}gone.js\tcognitive\t1\t0\nwork.js\tcognitive\t1\t0\n");
    fs::write(&baseline, &written).unwrap();
    smackdebt()
        .arg("gate")
        .arg(project.path())
        .assert()
        .code(0)
        .stdout(format!(
            concat!(
                "smackdebt gate · {}\n",
                "  Passed. Debt stayed within the baseline.\n",
                "0 regressions · 1 improvement\n",
                "\nFINDINGS\n",
                "  better gone.js · cognitive · high 1 → 0\n",
            ),
            baseline.display()
        ))
        .stderr("");
    assert_eq!(fs::read_to_string(&baseline).unwrap(), written);
}

#[test]
fn a_baseline_update_is_byte_stable_and_idempotent() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    smackdebt()
        .arg("gate")
        .arg("--update")
        .arg(project.path())
        .assert()
        .code(0)
        .stdout(format!("Baseline saved: {}\n", baseline.display()))
        .stderr("");
    let written = fs::read_to_string(&baseline).unwrap();
    assert_eq!(
        written,
        format!("{GATE_BASELINE_HEADERS}work.js\tcognitive\t1\t0\n")
    );
    smackdebt()
        .arg("gate")
        .arg("--update")
        .arg(project.path())
        .assert()
        .code(0)
        .stdout(format!("Baseline saved: {}\n", baseline.display()))
        .stderr("");
    assert_eq!(fs::read_to_string(&baseline).unwrap(), written);
    // The written baseline immediately gates its own tree clean.
    smackdebt()
        .arg("gate")
        .arg(project.path())
        .assert()
        .code(0)
        .stdout(format!(
            "smackdebt gate · {}\n  Passed. Debt stayed within the baseline.\n0 regressions · 0 improvements\n",
            baseline.display()
        ))
        .stderr("");
}

#[test]
fn a_regressed_gate_json_result_follows_its_checked_schema() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    fs::write(&baseline, GATE_BASELINE_HEADERS).unwrap();
    let output = smackdebt()
        .arg("gate")
        .arg("--json")
        .arg(project.path())
        .assert()
        .code(3)
        .stderr("")
        .get_output()
        .stdout
        .clone();
    let result: serde_json::Value = serde_json::from_slice(&output).unwrap();
    validate_gate_schema(&result);
    assert_eq!(result["schema_version"], 1);
    assert_eq!(result["status"], "regressed");
    assert_eq!(result["baseline"], baseline.display().to_string());
    let regressions = result["regressions"].as_array().unwrap();
    assert_eq!(regressions.len(), 1);
    assert_eq!(regressions[0]["path"], "work.js");
    assert_eq!(regressions[0]["signal"], "cognitive");
    assert_eq!(regressions[0]["baseline_high"], 0);
    assert_eq!(regressions[0]["high"], 1);
    assert_eq!(regressions[0]["baseline_watch"], 0);
    assert_eq!(regressions[0]["watch"], 0);
    assert!(result["improvements"].as_array().unwrap().is_empty());
    assert_eq!(result["totals"]["regressions"], 1);
    assert_eq!(result["totals"]["improvements"], 0);
}

#[test]
fn a_clean_gate_json_result_states_its_status_and_exits_zero() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    fs::write(
        &baseline,
        format!("{GATE_BASELINE_HEADERS}work.js\tcognitive\t1\t0\n"),
    )
    .unwrap();
    let output = smackdebt()
        .arg("gate")
        .arg("--json")
        .arg(project.path())
        .assert()
        .code(0)
        .stderr("")
        .get_output()
        .stdout
        .clone();
    let result: serde_json::Value = serde_json::from_slice(&output).unwrap();
    validate_gate_schema(&result);
    assert_eq!(result["status"], "clean");
    assert!(result["regressions"].as_array().unwrap().is_empty());
    assert!(result["improvements"].as_array().unwrap().is_empty());
}

#[test]
fn a_malformed_gate_baseline_never_passes() {
    let project = gate_fixture();
    let baseline = project.path().join(".smackdebt-baseline.tsv");
    fs::write(
        &baseline,
        format!("{GATE_BASELINE_HEADERS}work.js\tcoupling\t1\t0\n"),
    )
    .unwrap();
    smackdebt()
        .arg("gate")
        .arg(project.path())
        .assert()
        .code(2)
        .stdout("")
        .stderr("smackdebt: baseline line 3: unknown signal 'coupling'\n");
}

#[test]
fn configured_source_role_overrides_the_generic_path_role() {
    let project = fixture();
    fs::create_dir_all(project.path().join("tests")).unwrap();
    fs::write(
        project.path().join("tests/work.js"),
        "export function work() { return 1; }\n",
    )
    .unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[source_roles]\nexample = ['tests/work.js']\n",
    )
    .unwrap();

    let output = run(["--json", project.path().to_str().unwrap()]);
    let report: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let paths = report["paths"].as_array().unwrap();
    let file = report["files"]
        .as_array()
        .unwrap()
        .iter()
        .find(|file| paths[file["path"].as_u64().unwrap() as usize] == "tests/work.js")
        .unwrap();
    assert_eq!(file["role"], "example");
}

#[test]
fn rails_schema_findings_stay_visible_without_entering_default_verdicts() {
    let project = tempfile::tempdir().unwrap();
    fs::create_dir_all(project.path().join("db")).unwrap();
    fs::create_dir_all(project.path().join("app/models")).unwrap();
    fs::write(
        project.path().join("Gemfile"),
        "source 'https://example.invalid'\n",
    )
    .unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[thresholds.cognitive]\nwatch = 1\nhigh = 2\n[thresholds.cyclomatic]\nwatch = 1\nhigh = 2\n[thresholds.function_lines]\nwatch = 1\nhigh = 2\n",
    )
    .unwrap();
    let schema = "def generated_schema(one, two)\n  if one\n    if two\n      create_table(:items)\n    end\n  end\nend\n";
    fs::write(project.path().join("db/schema.rb"), schema).unwrap();
    fs::write(
        project.path().join("app/models/schema.rb"),
        "def user_schema; :kept; end\n",
    )
    .unwrap();

    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    let paths = report["paths"].as_array().unwrap();
    let file_for = |path: &str| {
        report["files"]
            .as_array()
            .unwrap()
            .iter()
            .find(|file| paths[file["path"].as_u64().unwrap() as usize] == path)
            .unwrap()
    };
    let generated = file_for("db/schema.rb");
    let user = file_for("app/models/schema.rb");
    assert_eq!(generated["role"], "generated");
    let generated_health = &report["health"][generated["health"].as_u64().unwrap() as usize];
    assert_eq!(generated_health["watch"], 0);
    assert_eq!(generated_health["high"], 0);
    assert_eq!(generated["coverage"]["context_files"], 1);
    assert_eq!(user["role"], "primary");
    let user_health = &report["health"][user["health"].as_u64().unwrap() as usize];
    assert!(
        report["findings"]
            .as_array()
            .unwrap()
            .iter()
            .any(|finding| {
                finding["name"] == "generated_schema"
                    && finding["rating"] == "high"
                    && finding["role"] == "generated"
            })
    );
    let root_health = &report["health"][report["scopes"][0]["health"].as_u64().unwrap() as usize];
    for field in ["healthy", "watch", "high"] {
        assert_eq!(root_health[field], user_health[field], "{field}");
    }

    let default = String::from_utf8(run_in(project.path(), ["--color", "never"])).unwrap();
    assert!(!default.contains("db/schema.rb"));
    let detailed =
        String::from_utf8(run_in(project.path(), ["--all", "--color", "never"])).unwrap();
    assert!(detailed.contains("db/schema.rb"));
    assert!(detailed.contains("generated"));

    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: schema base"]);
    fs::write(
        project.path().join("db/schema.rb"),
        schema.replace("create_table(:items)", "create_table(:orders)"),
    )
    .unwrap();
    let diff: serde_json::Value = serde_json::from_slice(&run_in(
        project.path(),
        ["diff", "main", "--json", "--jobs", "1"],
    ))
    .unwrap();
    assert!(diff["comparisons"].as_array().unwrap().is_empty());
    assert_eq!(diff["scopes"][0]["diff"]["total"], 0);
    assert!(diff["findings"].as_array().unwrap().iter().any(|finding| {
        finding["name"] == "generated_schema" && finding["role"] == "generated"
    }));
}

#[test]
fn terminal_color_can_be_forced_or_disabled_through_a_pipe() {
    let project = fixture();
    let path = project.path().to_str().unwrap();
    let colored = run(["--color", "always", path]);
    assert!(colored.windows(2).any(|bytes| bytes == b"\x1b["));

    let plain = run(["--color", "never", path]);
    assert!(!plain.windows(2).any(|bytes| bytes == b"\x1b["));
    // Forcing color also forces decoration, so the plain report is what
    // remains once the glyphs, the tier bar, and the styling are removed.
    assert_eq!(strip_decorations(&strip_ansi(&colored)), plain);
    assert!(private_use_codepoints(&plain).is_empty());
}

#[test]
fn color_controls_work_for_every_command_without_polluting_json() {
    let project = gate_fixture();
    smackdebt()
        .args(["gate", "--color", "never", "--update"])
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicates::str::contains("Baseline saved"));
    smackdebt()
        .args(["gate", "--color", "always"])
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicates::str::contains("\x1b["));
    smackdebt()
        .args(["gate", "--json", "--color", "always"])
        .arg(project.path())
        .assert()
        .code(2);
    smackdebt()
        .args(["--color", "never", "init", "--help"])
        .assert()
        .success()
        .stdout(predicates::boolean::NotPredicate::new(
            predicates::str::contains("\x1b"),
        ));
}

#[test]
fn global_color_before_a_subcommand_also_conflicts_with_json() {
    for command in ["diff", "gate"] {
        smackdebt()
            .args(["--color", "never", command, "--json"])
            .assert()
            .code(2)
            .stdout("")
            .stderr(predicates::str::contains(
                "--color cannot be used with --json",
            ));
    }
}

#[test]
fn explicit_color_is_rejected_for_json() {
    let project = fixture();
    smackdebt()
        .args(["--json", "--color", "always"])
        .arg(project.path())
        .assert()
        .code(2)
        .stderr(predicates::str::contains("cannot be used with"));
}

#[test]
fn source_engine_terminal_snapshot_is_reviewed() {
    let project = source_engine_fixture();
    let actual = run_in(project.path(), ["--jobs", "1", "--color", "never"]);
    assert_snapshot(
        "source-engine.terminal.txt",
        &actual,
        include_bytes!("snapshots/source-engine.terminal.txt"),
    );
}

#[test]
fn source_engine_json_snapshot_is_reviewed_and_matches_schema() {
    let project = source_engine_fixture();
    let actual = run_in(project.path(), ["--json", "--jobs", "1"]);
    assert_snapshot(
        "source-engine.json",
        &actual,
        include_bytes!("snapshots/source-engine.json"),
    );
    let report: serde_json::Value = serde_json::from_slice(&actual).unwrap();
    validate_schema(&report);
}

#[test]
fn the_global_gitignore_excludes_candidates() {
    let project = tempfile::tempdir().unwrap();
    fs::write(project.path().join("kept.js"), "export const kept = 1;\n").unwrap();
    fs::write(
        project.path().join("machine-wide-ignored.js"),
        "export const dropped = 1;\n",
    )
    .unwrap();
    // Every child process shares one pinned home; the global gitignore lives
    // at git/ignore under it. The pattern names one file unique to this test.
    let home = hermetic_env(&mut Command::new("git"));
    fs::create_dir_all(home.join("git")).unwrap();
    fs::write(home.join("git/ignore"), "machine-wide-ignored.js\n").unwrap();

    let output = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let paths: Vec<&str> = report["paths"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|path| path.as_str())
        .collect();
    assert!(paths.contains(&"kept.js"), "{paths:?}");
    assert!(!paths.contains(&"machine-wide-ignored.js"), "{paths:?}");
}

#[test]
fn ancestor_ignore_files_never_swallow_the_committed_source_engine_fixture() {
    // The committed fixture lives inside this workspace, so with git ignore
    // semantics every ancestor ignore file up to the workspace root applies
    // to it. This exact evidence fails loudly if a future edit to the
    // workspace `.gitignore` starts matching fixture files.
    let output = run(["--json", "--jobs", "1", SOURCE_ENGINE_FIXTURE]);
    let report: serde_json::Value = serde_json::from_slice(&output).unwrap();
    let scope = &report["scopes"][report["selected_scope"].as_u64().unwrap() as usize];
    assert_eq!(
        report["paths"][scope["path"].as_u64().unwrap() as usize],
        "crates/cli/tests/fixtures/source-engine"
    );
    assert_eq!(scope["coverage"]["selected_files"], 1);
    assert_eq!(scope["coverage"]["analyzed_files"], 1);
}

#[test]
fn nested_git_checkouts_are_pruned_and_disclosed() {
    let project = nested_checkout_fixture();

    // Default output discloses the pruned checkouts without detail flags.
    let terminal = run_in(project.path(), ["--jobs", "1", "--color", "never"]);
    assert_snapshot(
        "nested-checkout.terminal.txt",
        &terminal,
        include_bytes!("snapshots/nested-checkout.terminal.txt"),
    );
    let text = String::from_utf8(terminal).unwrap();
    assert!(
        text.contains("2 nested repositories were not analyzed"),
        "{text}"
    );

    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    let messages: Vec<&str> = report["diagnostics"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|diagnostic| diagnostic["kind"] == "nested_repository")
        .map(|diagnostic| diagnostic["message"].as_str().unwrap())
        .collect();
    assert_eq!(
        messages,
        [
            "clone is a nested repository",
            "worktree is a nested repository"
        ]
    );
    let paths: Vec<&str> = report["paths"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|path| path.as_str())
        .collect();
    assert!(paths.contains(&"kept.js"), "{paths:?}");
    assert!(!paths.iter().any(|path| path.contains("lost")), "{paths:?}");
}

#[test]
fn a_mostly_unsupported_selection_qualifies_its_verdict() {
    let project = unsupported_share_fixture();

    // The qualifier row renders in default output, directly under the tier
    // sentence, without any detail flag.
    let terminal = run_in(project.path(), ["--jobs", "1", "--color", "never"]);
    assert_snapshot(
        "unsupported-share.terminal.txt",
        &terminal,
        include_bytes!("snapshots/unsupported-share.terminal.txt"),
    );
    let text = String::from_utf8(terminal).unwrap();
    assert!(text.contains("Not all source was checked."), "{text}");
    assert!(
        text.contains("1 of 2 source files were analyzed."),
        "{text}"
    );

    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    let qualifier = &report["verdict"]["qualifier"];
    assert_eq!(qualifier["sentence"], "Not all source was checked.");
    assert_eq!(qualifier["detail"], "1 of 2 source files were analyzed.");
    assert_eq!(qualifier["selected_files"], 2);
    assert_eq!(qualifier["analyzed_files"], 1);
    assert_eq!(qualifier["share_permille"], 625);
    assert_eq!(qualifier["largest_language"], "Swift");
    let coverage = &report["scopes"][0]["coverage"];
    assert_eq!(coverage["selected_bytes"], 104);
    assert_eq!(coverage["unsupported_bytes"], 65);
    // The qualifier informs the reader only; the tier is still selected from
    // the checked units alone.
    assert_eq!(report["verdict"]["tier"], "clean");
}

#[test]
fn fully_analyzed_coverage_leaves_the_verdict_head_unqualified() {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("kept.js"),
        "export function kept() {\n  return 1;\n}\n",
    )
    .unwrap();
    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert!(
        report["verdict"].get("qualifier").is_none(),
        "{}",
        report["verdict"]
    );
}

fn explicit_scope_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::create_dir_all(project.path().join("src")).unwrap();
    fs::create_dir(project.path().join("empty")).unwrap();
    fs::write(
        project.path().join("src/good.js"),
        "export function good() { return 1; }\n",
    )
    .unwrap();
    fs::write(
        project.path().join("src/page.astro"),
        "---\nconst title = 'Hello';\n---\n<h1>{title}</h1>\n",
    )
    .unwrap();
    fs::write(project.path().join("README.txt"), "notes\n").unwrap();
    git(project.path(), ["init", "-q"]);
    project
}

#[test]
fn explicit_source_scopes_are_exact_and_absolute_input_keeps_repository_identity() {
    let project = explicit_scope_fixture();
    for (path, expected_kind, selected, analyzed) in [
        ("src/good.js", "file", 1, 1),
        ("src/page.astro", "file", 1, 0),
        ("src", "directory", 2, 1),
    ] {
        let output = smackdebt()
            .current_dir(project.path())
            .args([path, "--json", "--jobs", "1"])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}: {}",
            path,
            String::from_utf8_lossy(&output.stderr)
        );
        let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
        validate_schema(&report);
        let scope = &report["scopes"][report["selected_scope"].as_u64().unwrap() as usize];
        assert_eq!(scope["kind"], expected_kind, "{path}");
        assert_eq!(
            report["paths"][scope["path"].as_u64().unwrap() as usize],
            path
        );
        assert_eq!(scope["coverage"]["selected_files"], selected);
        assert_eq!(scope["coverage"]["analyzed_files"], analyzed);
    }

    let absolute = project.path().join("src/good.js");
    let absolute_output = smackdebt()
        .current_dir(project.path())
        .args([absolute.as_os_str(), std::ffi::OsStr::new("--json")])
        .output()
        .unwrap();
    assert!(absolute_output.status.success());
    let absolute_report: serde_json::Value =
        serde_json::from_slice(&absolute_output.stdout).unwrap();
    let selected = absolute_report["selected_scope"].as_u64().unwrap() as usize;
    let scope = &absolute_report["scopes"][selected];
    assert_eq!(
        absolute_report["paths"][scope["path"].as_u64().unwrap() as usize],
        "src/good.js"
    );
    assert!(
        !String::from_utf8_lossy(&absolute_output.stdout)
            .contains(project.path().to_str().unwrap())
    );
}

#[test]
fn modified_astro_diff_retains_coverage_and_counts_one_unsupported_file() {
    let project = explicit_scope_fixture();
    let astro = smackdebt()
        .current_dir(project.path())
        .args(["src/page.astro", "--json", "--jobs", "1"])
        .output()
        .unwrap();
    let report: serde_json::Value = serde_json::from_slice(&astro.stdout).unwrap();
    // The report is the repository; the selected scope is the one file asked
    // about, and it is the file whose coverage the verdict qualifies.
    let selected = report["selected_scope"].clone();
    let file = report["files"]
        .as_array()
        .unwrap()
        .iter()
        .find(|file| file["scope"] == selected)
        .unwrap();
    assert_eq!(file["language"], "astro");
    assert_eq!(report["verdict"]["qualifier"]["selected_files"], 1);
    assert_eq!(report["verdict"]["qualifier"]["analyzed_files"], 0);
    assert_eq!(
        report["verdict"]["qualifier"]["detail"],
        "0 of 1 source files were analyzed."
    );

    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-qm", "test: add source"]);
    fs::write(
        project.path().join("src/page.astro"),
        "---\nconst title = 'Changed';\n---\n<h1>{title}</h1>\n",
    )
    .unwrap();
    let diff = smackdebt()
        .current_dir(project.path())
        .args(["diff", "HEAD", "--json", "--jobs", "1"])
        .output()
        .unwrap();
    assert!(
        diff.status.success(),
        "{}",
        String::from_utf8_lossy(&diff.stderr)
    );
    let diff: serde_json::Value = serde_json::from_slice(&diff.stdout).unwrap();
    validate_schema(&diff);
    assert!(
        diff["files"]
            .as_array()
            .unwrap()
            .iter()
            .any(|file| file["language"] == "astro")
    );
    assert_eq!(diff["scopes"][0]["coverage"]["selected_files"], 1);
    assert_eq!(diff["scopes"][0]["coverage"]["analyzed_files"], 0);
    let diff_terminal = String::from_utf8(run_in(
        project.path(),
        ["diff", "HEAD", "--color", "never", "--jobs", "1"],
    ))
    .unwrap();
    assert!(
        diff_terminal.contains("warning 1 source file uses an unsupported language"),
        "{diff_terminal}"
    );
    assert!(!diff_terminal.contains("2 source files"), "{diff_terminal}");
}

#[test]
fn invalid_and_source_free_paths_return_exact_errors_without_repository_fallback() {
    let project = explicit_scope_fixture();
    for (path, message) in [
        ("empty", "smackdebt: no source files found under: empty\n"),
        ("README.txt", "smackdebt: not a source file: README.txt\n"),
        ("missing", "smackdebt: path not found: missing\n"),
    ] {
        let output = smackdebt()
            .current_dir(project.path())
            .arg(path)
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(1), "{path}");
        assert!(output.stdout.is_empty(), "{path}");
        assert_eq!(String::from_utf8(output.stderr).unwrap(), message, "{path}");
    }
}

/// A path inside a repository is a scope of that repository's report, so its
/// High count is framed by the repository total the same walk measured.
#[test]
fn explicit_scopes_inside_a_repository_state_the_measured_share() {
    let packages = problem_pattern_fixture();
    let root = packages.path().to_str().unwrap().to_owned();
    let god = packages.path().join("god");
    let god = god.to_str().unwrap();

    let root_terminal = String::from_utf8(run(["--color", "never", &root])).unwrap();
    assert!(
        !root_terminal.contains("live here."),
        "the repository root frames nothing: {root_terminal}"
    );
    let root_report: serde_json::Value = serde_json::from_slice(&run(["--json", &root])).unwrap();
    validate_schema(&root_report);
    assert!(
        root_report["verdict"].get("share").is_none(),
        "{}",
        root_report["verdict"]
    );

    let package_terminal = String::from_utf8(run(["--color", "never", god])).unwrap();
    let package_lines: Vec<&str> = package_terminal.lines().collect();
    assert_eq!(package_lines[0], "smackdebt · god");
    assert_eq!(package_lines[1], "  Worn in the usual places.");
    assert_eq!(
        package_lines[2],
        "  3 of the repository's 4 high live here."
    );
    assert!(package_lines[3].contains(" high · "), "{package_terminal}");
    let package_report: serde_json::Value = serde_json::from_slice(&run(["--json", god])).unwrap();
    validate_schema(&package_report);
    // The selected result answers the package and states the repository total
    // it was divided by, because one walk measured both.
    assert_eq!(package_report["summary"]["high"], 3);
    assert_eq!(root_report["summary"]["high"], 4);
    assert_eq!(package_report["verdict"]["share"]["high"], 3);
    assert_eq!(package_report["verdict"]["share"]["repository_high"], 4);
    assert_eq!(package_report["verdict"]["tier"], "worn");

    // The frame holds wherever the debt sits, including a directory that holds
    // none of it.
    let split = split_debt_fixture();
    let messy = split.path().join("messy");
    let messy = messy.to_str().unwrap();
    let clean = split.path().join("clean");
    let clean = clean.to_str().unwrap();
    let messy_terminal = String::from_utf8(run(["--color", "never", messy])).unwrap();
    assert!(messy_terminal.contains("live here."), "{messy_terminal}");
    let messy_report: serde_json::Value = serde_json::from_slice(&run(["--json", messy])).unwrap();
    validate_schema(&messy_report);
    let repository_high = messy_report["verdict"]["share"]["repository_high"].clone();
    assert_eq!(messy_report["verdict"]["share"]["high"], repository_high);
    let clean_report: serde_json::Value = serde_json::from_slice(&run(["--json", clean])).unwrap();
    validate_schema(&clean_report);
    assert_eq!(clean_report["verdict"]["share"]["high"], 0);
    assert_eq!(
        clean_report["verdict"]["share"]["repository_high"],
        repository_high
    );
}

/// A repository without High debt has no fraction to divide, so no sub-scope
/// states a zero-of-zero sentence.
#[test]
fn a_repository_without_high_debt_frames_no_sub_scope() {
    let project = tempfile::tempdir().unwrap();
    fs::create_dir(project.path().join("src")).unwrap();
    fs::write(
        project.path().join("src/kept.js"),
        "export function kept() {\n  return 1;\n}\n",
    )
    .unwrap();
    let terminal = String::from_utf8(run_in(
        project.path(),
        ["--color", "never", "--jobs", "1", "src"],
    ))
    .unwrap();
    assert!(!terminal.contains("live here."), "{terminal}");
    let report: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--jobs", "1", "src"])).unwrap();
    validate_schema(&report);
    assert_eq!(report["summary"]["high"], 0);
    assert!(
        report["verdict"].get("share").is_none(),
        "{}",
        report["verdict"]
    );
}

#[test]
fn static_architecture_codebase_snapshots_are_reviewed() {
    let project = static_architecture_fixture();
    let terminal = run_in(project.path(), ["--jobs", "1", "--color", "never"]);
    assert_snapshot(
        "static-architecture.terminal.txt",
        &terminal,
        include_bytes!("snapshots/static-architecture.terminal.txt"),
    );
    let detailed = run_in(project.path(), ["--all", "--jobs", "1", "--color", "never"]);
    assert_snapshot(
        "static-architecture-all.terminal.txt",
        &detailed,
        include_bytes!("snapshots/static-architecture-all.terminal.txt"),
    );
    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    assert_snapshot(
        "static-architecture.json",
        &json,
        include_bytes!("snapshots/static-architecture.json"),
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    assert_eq!(report["architecture_findings"].as_array().unwrap().len(), 2);
    assert_eq!(report["dependency_coverage"]["external"], 1);
    assert_eq!(report["dependency_coverage"]["unresolved"], 1);
    assert_eq!(report["dependency_coverage"]["ambiguous"], 1);
    assert_eq!(
        report["dependency_coverage"]["module_ownership_relations"],
        1
    );
    let partition_total: u64 = [
        "resolved_internal_uses",
        "unresolved_internal_uses",
        "ambiguous_internal_uses",
        "external_uses",
        "unresolved_package_uses",
        "module_ownership_relations",
        "context_relations",
    ]
    .iter()
    .map(|field| report["dependency_coverage"][field].as_u64().unwrap())
    .sum();
    assert_eq!(
        partition_total,
        report["dependency_coverage"]["total"].as_u64().unwrap()
    );
    assert!(
        report["package_graph"]
            .as_array()
            .unwrap()
            .iter()
            .any(|package| package["fan_in"] == 1 && package["fan_out"] == 1)
    );
    // `--all` shows all useful debt; raw dependency edges live in JSON only,
    // which every terminal result in this suite carries as an invariant.
    let detailed_text = String::from_utf8(detailed).unwrap();
    assert!(!detailed_text.contains("primary/trusted"));
}

#[test]
fn long_fact_families_keep_their_meaning_at_fifty_columns() {
    let project = long_responsive_fixture();
    let output = smackdebt()
        .current_dir(project.path())
        .env("COLUMNS", "50")
        .args(["--all", "--color", "never", "--history", "36500d"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_snapshot(
        "long-responsive-50.terminal.txt",
        &output.stdout,
        include_bytes!("snapshots/long-responsive-50.terminal.txt"),
    );
    let terminal = String::from_utf8(output.stdout).unwrap();
    assert_narrow(&terminal, 50);
    for fact in ["method · test", "statements 56"] {
        assert!(terminal.contains(fact), "missing {fact}: {terminal}");
    }
    let lines = terminal.lines().collect::<Vec<_>>();
    assert!(terminal.contains("high circular dependency"), "{terminal}");
    // The card states the witness step by step first and its member count
    // last, and a narrow width stacks a long path over several lines.
    let head = lines
        .iter()
        .position(|line| line.contains("circular dependency"))
        .unwrap_or_else(|| panic!("{terminal}"));
    let members = lines[head..]
        .iter()
        .position(|line| line.trim().ends_with(" in the cycle"))
        .map(|offset| head + offset)
        .unwrap_or_else(|| panic!("{terminal}"));
    assert!(members > head + 1, "{terminal}");
    let witness = lines[head + 1..members]
        .iter()
        .map(|line| line.trim().trim_start_matches("→ ").to_owned())
        .collect::<Vec<_>>()
        .join("");
    assert!(
        witness.starts_with("very-long-source-package-name/"),
        "{terminal}"
    );
    assert!(
        witness.ends_with("very-long-source-package-name/very-long-source-directory-name/very-long-source-file-name.js"),
        "{terminal}"
    );

    // A path view keeps the relationships that explain one package, still at
    // fifty columns and still without losing a fact.
    let path = smackdebt()
        .current_dir(project.path())
        .env("COLUMNS", "50")
        .args([
            "very-long-source-package-name",
            "--all",
            "--color",
            "never",
            "--history",
            "36500d",
        ])
        .output()
        .unwrap();
    assert!(
        path.status.success(),
        "{}",
        String::from_utf8_lossy(&path.stderr)
    );
    assert_snapshot(
        "long-responsive-path-50.terminal.txt",
        &path.stdout,
        include_bytes!("snapshots/long-responsive-path-50.terminal.txt"),
    );
    let path = String::from_utf8(path.stdout).unwrap();
    assert_narrow(&path, 50);
    // `--all` keeps the imports that could not be followed; the resolved uses
    // beside them are graph facts and stay in the machine report.
    for fact in ["could not be matched", "matched more than one file"] {
        assert!(path.contains(fact), "missing {fact}: {path}");
    }
    assert_no_dependency_edge_rows(&path, "long responsive path view");
    // References outside the repository are not debt and never reach a human.
    assert!(!path.contains("external"), "{path}");

    // Module wiring is a relationship too, so no ownership row survives.
    let owned = String::from_utf8(run_in(
        project.path(),
        [
            "very-long-rust-ownership-package-name",
            "--all",
            "--color",
            "never",
        ],
    ))
    .unwrap();
    assert!(!owned.contains(" owns "), "{owned}");
}

/// Every line fits the requested width and none reached the safety shortening.
fn assert_narrow(terminal: &str, width: usize) {
    for line in terminal.lines() {
        assert!(
            unicode_width::UnicodeWidthStr::width(line) <= width,
            "{line}"
        );
        assert!(!line.ends_with('…'), "safety fallback clipped: {line}");
    }
}

#[test]
fn architecture_path_drill_shows_findings_without_edge_rows() {
    let project = static_architecture_fixture();
    git(project.path(), ["init", "-b", "main"]);
    let output = run_in(project.path(), ["app", "--all", "--color", "never"]);
    let text = String::from_utf8(output).unwrap();
    // The selection is a scope of the repository, so a cycle that leaves it is
    // a finding it can state — as a witness, never as a dependency edge row.
    assert!(!text.contains("core/main.js → app/main.js"), "{text}");
    assert!(!text.contains("app/main.js → core/main.js"), "{text}");
    assert!(
        text.contains("watch circular dependency · app/choice.js"),
        "{text}"
    );
    assert!(
        text.contains("high circular dependency · app/main.js"),
        "{text}"
    );
    assert!(text.contains("        → core/main.js"), "{text}");
    assert!(text.contains("2 imports could not be followed"), "{text}");
    assert!(!text.contains("native/src/helper.rs"));

    // Module wiring is a relationship too: a Rust package states no ownership.
    let native = String::from_utf8(run_in(
        project.path(),
        ["native", "--all", "--color", "never"],
    ))
    .unwrap();
    assert!(!native.contains(" owns "), "{native}");
    assert!(!native.contains("native/src/helper.rs"), "{native}");
}

#[test]
fn selected_path_scopes_import_warning_counts() {
    let project = static_architecture_fixture();
    // Both causes in one scope: the total row carries one fact per cause.
    let app = String::from_utf8(run_in(project.path(), ["app", "--color", "never"])).unwrap();
    assert!(
        app.contains("warning 3 imports could not be followed"),
        "{app}"
    );
    assert!(app.contains("2 named nothing in the repository"), "{app}");
    assert!(app.contains("1 matched more than one file"), "{app}");

    // A single cause states the total and that cause only.
    let core = String::from_utf8(run_in(project.path(), ["core", "--color", "never"])).unwrap();
    assert!(
        core.contains("warning 1 import could not be followed · 1 named nothing in the repository"),
        "{core}"
    );
    assert!(!core.contains("matched more than one file"), "{core}");

    let native = String::from_utf8(run_in(project.path(), ["native", "--color", "never"])).unwrap();
    assert!(!native.contains("could not be followed"), "{native}");
}

#[test]
fn diff_and_path_views_state_findings_without_current_edges() {
    let project = static_architecture_fixture();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: architecture base"]);
    fs::write(
        project.path().join("app/main.js"),
        "import core from '../core/main';\nimport coreAgain from '../core/main';\n\nexport function app() { return core(coreAgain); }\n",
    )
    .unwrap();

    // Adding one import moves no rated debt, so every diff view is the
    // verdict block and nothing else.
    let root =
        String::from_utf8(run_in(project.path(), ["diff", "main", "--color", "never"])).unwrap();
    assert!(root.contains("No debt changed."), "{root}");
    assert!(!root.contains("ARCHITECTURE"), "{root}");
    for arguments in [
        ["diff", "main", "app", "--color", "never"],
        ["diff", "main", "core", "--color", "never"],
    ] {
        let terminal = String::from_utf8(run_in(project.path(), arguments)).unwrap();
        assert!(terminal.contains("No debt changed."), "{terminal}");
        assert!(!terminal.contains("ARCHITECTURE"), "{terminal}");
        assert!(!terminal.contains("HISTORY"), "{terminal}");
        assert!(!terminal.contains("WARNINGS"), "{terminal}");
    }
    let app = String::from_utf8(run_in(project.path(), ["app", "--color", "never"])).unwrap();
    assert!(!app.contains("app/main.js → core/main.js"), "{app}");
    assert!(
        app.contains("watch circular dependency · app/choice.js"),
        "{app}"
    );
    let core = String::from_utf8(run_in(project.path(), ["core", "--color", "never"])).unwrap();
    assert!(!core.contains("app/main.js → core/main.js"), "{core}");
    // The cycle runs through this package, so its scope states the finding
    // without ever printing the edges the finding was built from.
    assert!(core.contains("circular dependency"), "{core}");
    assert_no_dependency_edge_rows(&core, "static architecture core drill");
}

#[test]
fn unresolved_and_ambiguous_relations_reach_a_file_scope_and_all_only() {
    let project = tempfile::tempdir().unwrap();
    fs::create_dir(project.path().join("app")).unwrap();
    fs::write(project.path().join("app/package.json"), "{}\n").unwrap();
    fs::write(
        project.path().join("app/main.js"),
        "import local from './choice';\nimport library from 'external-library';\nconst late = require(moduleName);\nexport function value() { return local + library + late; }\n",
    )
    .unwrap();
    fs::write(project.path().join("app/choice.js"), "export default 1;\n").unwrap();
    fs::write(project.path().join("app/choice.ts"), "export default 2;\n").unwrap();
    // An asset the repository really holds, imported for its bytes. Discovery
    // never inventories it as source, so no lookup could match it and calling
    // the import unfollowed would be false evidence.
    fs::write(project.path().join("app/settings.yaml"), "name: app\n").unwrap();
    // A directory inside the package gives the third scope kind the rule names.
    fs::create_dir(project.path().join("app/inner")).unwrap();
    fs::write(
        project.path().join("app/inner/main.js"),
        "import missing from './missing';\nimport settings from '../settings.yaml?raw';\nexport function inner() { return missing + settings; }\n",
    )
    .unwrap();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: relation-only base"]);
    fs::write(
        project.path().join("app/main.js"),
        "import local from './choice';\nimport library from 'external-library';\nconst late = require(moduleName);\nexport function value() { return local + library + late + 1; }\n",
    )
    .unwrap();

    // A file scope and `--all` state each import that could not be followed;
    // a package and a directory scope keep the grouped sentence alone.
    for (scope, sentence) in [
        ("app", "warning 3 imports could not be followed"),
        ("app/inner", "warning 1 import could not be followed"),
    ] {
        let grouped =
            String::from_utf8(run_in(project.path(), [scope, "--color", "never"])).unwrap();
        assert!(!grouped.contains("\nARCHITECTURE\n"), "{grouped}");
        // The grouped sentence is the whole terminal presence of those
        // imports, so the section states it and nothing per file.
        assert!(grouped.contains("\nWARNINGS\n"), "{grouped}");
        assert!(grouped.contains(sentence), "{grouped}");
        for row in [
            "app/main.js:1 → ./choice",
            "app/main.js:3 → require(",
            "app/inner/main.js:1 → ./missing",
        ] {
            assert!(!grouped.contains(row), "{grouped}");
        }
        // The counts above are the whole point: the asset import beside the
        // missing one is followed as far as an asset goes, so it neither joins
        // the sentence nor names itself anywhere in the terminal.
        assert!(!grouped.contains("settings.yaml"), "{grouped}");
    }
    // The same directory states its rows once `--all` is asked for.
    let detailed = String::from_utf8(run_in(
        project.path(),
        ["app/inner", "--all", "--color", "never"],
    ))
    .unwrap();
    assert!(
        detailed.contains("app/inner/main.js:1 → ./missing · could not be matched"),
        "{detailed}"
    );
    assert!(!detailed.contains("settings.yaml"), "{detailed}");

    // The machine report keeps the asset reference under its own reason, and
    // graph evidence counts the missing source and the computed require target.
    // The asset does not add uncertainty to the source graph.
    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    let assets: Vec<_> = report["resolution_diagnostics"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|value| value["kind"] == "asset")
        .collect();
    assert_eq!(assets.len(), 1, "{}", report["resolution_diagnostics"]);
    assert_eq!(assets[0]["target"], "../settings.yaml?raw");
    assert_eq!(assets[0]["reason"], "target is an asset");
    assert_eq!(report["graph_evidence"]["unresolved_internal"], 2);
    assert_eq!(report["dependency_coverage"]["unresolved_internal_uses"], 2);

    for (case, arguments) in [
        vec!["app/main.js", "--color", "never"],
        vec!["app", "--all", "--color", "never"],
    ]
    .into_iter()
    .enumerate()
    {
        let output = smackdebt()
            .current_dir(project.path())
            .args(arguments)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "case {case}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let terminal = String::from_utf8(output.stdout).unwrap();
        assert_no_dependency_edge_rows(&terminal, &format!("case {case}"));
        // A per-import row is diagnostic detail, so it joins the grouped
        // sentence it explains rather than a debt section.
        assert!(terminal.contains("\nWARNINGS\n"), "case {case}: {terminal}");
        assert!(
            !terminal.contains("\nARCHITECTURE\n"),
            "case {case}: {terminal}"
        );
        // References outside the repository are not debt, so no external row
        // reaches a human view again.
        assert!(
            !terminal.contains("external-library"),
            "case {case}: {terminal}"
        );
        for relation in [
            "app/main.js:1 → ./choice",
            "app/main.js:3 → require(moduleName)",
        ] {
            assert_eq!(
                terminal.matches(relation).count(),
                1,
                "case {case}: {terminal}"
            );
        }
        // The warning breakdown may repeat a cause's words, so each relation's
        // own status is matched together with its target. Both scopes resolve
        // against the same repository index, so one relation has one status
        // wherever it is read.
        for status in [
            "./choice · matched more than one file",
            "require(moduleName) · could not be matched",
        ] {
            assert_eq!(
                terminal.matches(status).count(),
                1,
                "case {case}: {terminal}"
            );
        }
    }
}

#[test]
fn static_architecture_diff_snapshot_uses_unchanged_return_edges() {
    let project = static_architecture_fixture();
    fs::write(
        project.path().join("core/main.js"),
        "export default function core(value) {\n  return value;\n}\n",
    )
    .unwrap();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: acyclic base"]);
    fs::write(
        project.path().join("core/main.js"),
        "import app from '../app/main';\n\nexport default function core(value) {\n  return app(value);\n}\n",
    )
    .unwrap();

    let json = run_in(
        project.path(),
        [
            "diff",
            "main",
            "--json",
            "--jobs",
            "1",
            "--history",
            "36500d",
        ],
    );
    let terminal = run_in(
        project.path(),
        [
            "diff",
            "main",
            "--jobs",
            "1",
            "--color",
            "never",
            "--history",
            "36500d",
        ],
    );
    assert_snapshot(
        "static-architecture-diff.terminal.txt",
        &terminal,
        include_bytes!("snapshots/static-architecture-diff.terminal.txt"),
    );
    assert_snapshot(
        "static-architecture-diff.json",
        &json,
        include_bytes!("snapshots/static-architecture-diff.json"),
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert!(
        report["architecture_comparisons"]
            .as_array()
            .unwrap()
            .iter()
            .any(|comparison| comparison["kind"] == "cycle_introduced"
                && comparison["direction"] == "worse")
    );
    // The contradiction case: no source comparison moved and the diff is
    // still worse, because the new package cycle is the debt that moved.
    assert!(report["comparisons"].as_array().unwrap().is_empty());
    let text = String::from_utf8(terminal).unwrap();
    assert!(text.contains("Debt increased."), "{text}");
    assert!(text.contains("worse 1 · better 0 · changed 0"), "{text}");
    assert!(
        text.contains("worse package dependency cycle introduced"),
        "{text}"
    );
}

#[test]
fn diff_discloses_current_graph_suppression_without_reporting_reach_movement() {
    let project = tempfile::tempdir().unwrap();
    fs::write(project.path().join("package.json"), "{}\n").unwrap();
    for index in 0..20 {
        fs::write(
            project.path().join(format!("f{index}.ts")),
            format!("export const f{index} = {index};\n"),
        )
        .unwrap();
    }
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: complete base"]);
    fs::write(
        project.path().join("f1.ts"),
        "import { f0 } from './f0.js';\nimport missing from './missing.js';\nexport const f1 = f0 + missing;\n",
    )
    .unwrap();

    let json = run_in(project.path(), ["diff", "main", "--json", "--jobs", "1"]);
    let terminal = String::from_utf8(run_in(
        project.path(),
        ["diff", "main", "--jobs", "1", "--color", "never"],
    ))
    .unwrap();
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);

    assert_eq!(
        report["diff_graph_evidence"]["current"]["status"],
        "incomplete"
    );
    assert_eq!(report["diff_graph_evidence"]["base"]["status"], "complete");
    assert_eq!(
        report["diff_graph_evidence"]["suppressed_propagation"],
        serde_json::json!({"total": 1, "current": 1, "base": 0})
    );
    assert!(
        report["propagation_comparisons"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert_eq!(report["summary"]["debt_diff"]["total"], 0);
    assert!(terminal.contains("No debt changed."), "{terminal}");
    assert!(
        terminal.contains("1 dependency comparison withheld after the change"),
        "{terminal}"
    );
    assert!(!terminal.contains("change reach"), "{terminal}");
}

#[test]
fn static_architecture_removed_cycle_snapshot_is_reviewed() {
    let project = static_architecture_fixture();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: cyclic base"]);
    fs::write(
        project.path().join("core/main.js"),
        "export default function core(value) {\n  return value;\n}\n",
    )
    .unwrap();

    let json = run_in(
        project.path(),
        [
            "diff",
            "main",
            "--json",
            "--jobs",
            "1",
            "--history",
            "36500d",
        ],
    );
    assert_snapshot(
        "static-architecture-removed-cycle.json",
        &json,
        include_bytes!("snapshots/static-architecture-removed-cycle.json"),
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert!(
        report["architecture_comparisons"]
            .as_array()
            .unwrap()
            .iter()
            .any(|comparison| comparison["kind"] == "cycle_removed"
                && comparison["direction"] == "better")
    );
}

#[test]
fn evolutionary_analysis_is_exact_private_and_deterministic() {
    let project = evolutionary_fixture();
    let serial_json = run_in(
        project.path(),
        ["--json", "--jobs", "1", "--history", "36500d"],
    );
    let parallel_json = run_in(
        project.path(),
        ["--json", "--jobs", "4", "--history", "36500d"],
    );
    assert_eq!(serial_json, parallel_json);
    let serial_terminal = run_in(
        project.path(),
        ["--jobs", "1", "--color", "never", "--history", "36500d"],
    );
    let parallel_terminal = run_in(
        project.path(),
        ["--jobs", "4", "--color", "never", "--history", "36500d"],
    );
    assert_eq!(serial_terminal, parallel_terminal);
    assert_snapshot(
        "evolutionary-analysis.json",
        &serial_json,
        include_bytes!("snapshots/evolutionary-analysis.json"),
    );
    assert_snapshot(
        "evolutionary-analysis.terminal.txt",
        &serial_terminal,
        include_bytes!("snapshots/evolutionary-analysis.terminal.txt"),
    );
    let report: serde_json::Value = serde_json::from_slice(&serial_json).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    assert_eq!(report["history_coverage"]["availability"], "complete");
    assert_eq!(report["history_coverage"]["commits"], 6);
    assert_eq!(report["change_coupling"][0]["shared_commits"], 3);
    assert_eq!(report["change_coupling"][0]["union_commits"], 6);
    // The operands are published; a consumer derives 3/6 at its own precision.
    assert_eq!(report["change_coupling"][0]["shared_commits"], 3);
    assert_eq!(report["change_coupling"][0]["union_commits"], 6);
    assert_eq!(report["change_coupling"].as_array().unwrap().len(), 1);
    assert_eq!(report["evolutionary_findings"].as_array().unwrap().len(), 1);
    let terminal_text = String::from_utf8(serial_terminal.clone()).unwrap();
    assert_eq!(
        terminal_text
            .matches(
                "  watch packages change together · a ↔ b\n        changed together in 3 of 6 commits · 50% · no code dependency\n"
            )
            .count(),
        1
    );
    assert!(!terminal_text.contains("touches"));
    assert!(!terminal_text.contains("top share"));
    assert!(!terminal_text.contains("a ↔ c"));
    for private_value in [
        "Alice Example",
        "alice@example.invalid",
        "Alias Person",
        "alias@example.invalid",
        "Bob Example",
        "bob@example.invalid",
    ] {
        assert!(
            !serial_json
                .windows(private_value.len())
                .any(|window| window == private_value.as_bytes())
        );
        assert!(
            !serial_terminal
                .windows(private_value.len())
                .any(|window| window == private_value.as_bytes())
        );
    }
}

#[test]
fn an_indirect_dependency_path_is_named_without_suppressing_the_finding() {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    for package in ["a", "b", "c"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
    }
    // The dependency chain runs a → b → c with no direct a → c relation.
    fs::write(
        project.path().join("a/main.js"),
        "import { b } from '../b/main';\nexport const a = b;\n",
    )
    .unwrap();
    fs::write(
        project.path().join("b/main.js"),
        "import { c } from '../c/main';\nexport const b = c;\n",
    )
    .unwrap();
    fs::write(project.path().join("c/main.js"), "export const c = 0;\n").unwrap();
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "initial",
    );
    for version in 1..=3 {
        fs::write(
            project.path().join("a/main.js"),
            format!("import {{ b }} from '../b/main';\nexport const a = b + {version};\n"),
        )
        .unwrap();
        fs::write(
            project.path().join("c/main.js"),
            format!("export const c = {version};\n"),
        )
        .unwrap();
        commit_as(
            project.path(),
            "History Test",
            "history@example.invalid",
            &format!("a and c together {version}"),
        );
    }

    let terminal = String::from_utf8(run_in(
        project.path(),
        ["--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    // The Watch finding is created exactly as when no path exists; only the
    // wording distinguishes the indirect link and names the first
    // intermediate on the path.
    assert!(
        terminal.contains(
            "  watch packages change together · a ↔ c\n        changed together in 4 of 4 commits · 100% · no direct dependency · linked via b\n"
        ),
        "{terminal}"
    );
    assert!(!terminal.contains("no code dependency"), "{terminal}");
}

/// Every frozen pattern, every anchor kind, and every evidence kind reaches a
/// committed human view and a committed machine view together.
#[test]
fn every_problem_pattern_reaches_a_committed_terminal_and_machine_view() {
    let project = problem_pattern_fixture();
    let terminal = run_in(
        project.path(),
        [
            "--all",
            "--jobs",
            "1",
            "--color",
            "never",
            "--history",
            "36500d",
        ],
    );
    assert_snapshot(
        "problem-patterns.terminal.txt",
        &terminal,
        include_bytes!("snapshots/problem-patterns.terminal.txt"),
    );
    let json = run_in(
        project.path(),
        ["--json", "--jobs", "1", "--history", "36500d"],
    );
    assert_snapshot(
        "problem-patterns.json",
        &json,
        include_bytes!("snapshots/problem-patterns.json"),
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    let cards = report["problems"].as_array().unwrap();
    let value = |card: &serde_json::Value, key: &str| card[key].as_str().unwrap().to_owned();
    let patterns: Vec<String> = cards.iter().map(|card| value(card, "pattern")).collect();
    for pattern in ["god_file", "hub", "hot_mess", "bus_risk", "measured"] {
        assert!(patterns.contains(&pattern.to_owned()), "{patterns:?}");
    }
    let anchors: Vec<String> = cards
        .iter()
        .map(|card| value(&card["anchor"], "kind"))
        .collect();
    assert!(anchors.contains(&"package".to_owned()), "{anchors:?}");
    let evidence: Vec<String> = cards
        .iter()
        .flat_map(|card| card["evidence"].as_array().unwrap())
        .map(|fact| value(fact, "kind"))
        .collect();
    for kind in ["fan_in", "fan_out", "hot", "rated_units", "size_findings"] {
        assert!(evidence.contains(&kind.to_owned()), "{evidence:?}");
    }

    let text = String::from_utf8(terminal).unwrap();
    for head in [
        "  high does too much · god/god.js\n",
        "  watch everything depends on this · hub/hub.js\n",
        "  high hot and complex · hot/hot.js\n",
        "  watch one author · hot\n",
    ] {
        assert!(text.contains(head), "{head}: {text}");
    }
    for fact in [
        "        10 files import this\n",
        "        imports 10 files\n",
        "        hot (11 commits)\n",
        "        one contributor made 11 of 11 commits\n",
    ] {
        assert!(text.contains(fact), "{fact}: {text}");
    }
    // The hub card states the heat that corroborates its degree, so a reader
    // sees why the degree is worth naming.
    assert!(
        text.contains(
            "  watch everything depends on this · hub/hub.js\n        hub/hub.js:1 · function · cyclomatic 2\n        10 files import this\n        hot (4 commits)\n"
        ),
        "{text}"
    );
    // The file that imports nine others and never changes with them carries
    // debt, and nothing corroborates its breadth, so it is named by that debt
    // rather than by a degree a reader cannot act on.
    assert!(
        text.contains("  watch spread · function · hub/spread.js:11\n"),
        "{text}"
    );
    assert!(!text.contains("depends on many files"), "{text}");
    // A size finding states its subject and its measured value, and a card
    // that heads on one names the file in the identity-then-kind form a
    // finding head takes and states the value alone.
    assert!(
        text.lines()
            .any(|line| line.starts_with("        file · ") && line.ends_with(" lines")),
        "{text}"
    );
    assert!(
        text.contains("  watch god/long.js · file\n        41 lines\n"),
        "{text}"
    );
    // A grouped sentence agrees with its count in its verb and its object.
    assert!(
        text.contains("  warning 2 source files use unsupported languages\n"),
        "{text}"
    );
    // A warning detail row names its file once: the row states the path and
    // the diagnostic states what happened to it.
    assert!(
        text.contains("  hub/first.swift: uses an unsupported language\n"),
        "{text}"
    );
    assert!(!text.contains("hub/first.swift: hub/first.swift"), "{text}");
    // A recovered file's whole debt is advisory, so its card states that trust
    // and cannot be one of the two names reserved for debt that moves a
    // verdict.
    assert!(
        text.contains("  high recovered · function · advisory · god/recovered.js:1\n"),
        "{text}"
    );
    // The machine view carries the same pair: the parse is disclosed as
    // recovered and the trust it cost is stated beside it.
    let paths = report["paths"].as_array().unwrap();
    let recovered = report["files"]
        .as_array()
        .unwrap()
        .iter()
        .find(|file| paths[file["path"].as_u64().unwrap() as usize] == "god/recovered.js")
        .expect("the recovered fixture file has a row");
    assert_eq!(recovered["parse_outcome"], "recovered");
    assert_eq!(recovered["trust"], "advisory");

    // The same fixture rendered by default withholds exactly the cards whose
    // debt cannot move a verdict, and states the ones whose debt can.
    let default_view = String::from_utf8(run_in(
        project.path(),
        ["--jobs", "1", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    // A warning may still name one of those files: a file the parser recovered
    // from is a disclosure about what was read, not a card about its debt, and
    // the grouped sentence names the first path a reader should open.
    let cards: Vec<&str> = default_view
        .lines()
        .skip_while(|line| *line != "PROBLEMS")
        .take_while(|line| *line != "WARNINGS")
        .collect();
    for detail in ["god/recovered.js", "god/long.js"] {
        assert!(
            !cards.iter().any(|line| line.contains(detail)),
            "{detail}: {default_view}"
        );
    }
    assert!(
        default_view.contains("  high does too much · god/god.js\n"),
        "{default_view}"
    );
    // Every measured-unit total reaches a reader in words it can act on, with
    // a noun that agrees with its own count.
    assert!(text.contains(" functions measured\n"), "{text}");
    assert!(!text.contains("rated unit"), "{text}");
}

#[test]
fn every_actionable_coupling_reaches_a_card_in_the_problem_rank() {
    let project = history_strength_order_fixture();
    let json = run_in(project.path(), ["--json", "--history", "36500d"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    let package_path = |id: u64| report["packages"][id as usize]["path"].as_str().unwrap();
    let stored_pairs = report["evolutionary_findings"]
        .as_array()
        .unwrap()
        .iter()
        .map(|finding| {
            (
                package_path(finding["left"].as_u64().unwrap()),
                package_path(finding["right"].as_u64().unwrap()),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(
        stored_pairs,
        [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e")]
    );

    let terminal = run_in(project.path(), ["--color", "never", "--history", "36500d"]);
    assert_snapshot(
        "history-strength-order.terminal.txt",
        &terminal,
        include_bytes!("snapshots/history-strength-order.terminal.txt"),
    );
    let terminal = String::from_utf8(terminal).unwrap();
    // Every pair is a card ranked against every other problem, so the
    // section-local limit that hid the fourth pair is gone. The four cards
    // tie on every rank key before the anchor, so the anchor package orders
    // them.
    let mut previous = 0;
    for pair in ["a ↔ b", "b ↔ c", "c ↔ d", "d ↔ e"] {
        let at = terminal.find(pair).unwrap_or_else(|| panic!("{terminal}"));
        assert!(at > previous, "{pair}: {terminal}");
        previous = at;
    }
}

#[test]
fn commits_that_landed_outside_a_narrow_window_never_reach_the_report() {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    fs::write(project.path().join("package.json"), "{}\n").unwrap();
    fs::write(project.path().join("main.js"), "export const value = 1;\n").unwrap();
    commit_landed(
        project.path(),
        Some("2000-01-02T03:04:05Z"),
        "far outside every selectable window",
    );
    fs::write(project.path().join("main.js"), "export const value = 2;\n").unwrap();
    commit_landed(project.path(), None, "inside the narrow window");

    let complete = run_in(project.path(), ["--json", "--history", "36500d"]);
    let complete: serde_json::Value = serde_json::from_slice(&complete).unwrap();
    assert_eq!(complete["history_coverage"]["commits"], 2);

    let narrow = run_in(project.path(), ["--json", "--history", "90d"]);
    let narrow: serde_json::Value = serde_json::from_slice(&narrow).unwrap();
    validate_schema(&narrow);
    // The old commit never reaches the report: the streamed set is the
    // windowed set and the boundary check rejects nothing.
    assert_eq!(narrow["history_coverage"]["window_days"], 90);
    assert_eq!(narrow["history_coverage"]["commits"], 1);
    assert_eq!(narrow["history_coverage"]["window_excluded_commits"], 0);
    let touches = |report: &serde_json::Value| {
        report["file_history"]
            .as_array()
            .unwrap()
            .iter()
            .map(|history| history["touches"].as_u64().unwrap())
            .sum::<u64>()
    };
    assert_eq!(touches(&complete), 2);
    assert_eq!(touches(&narrow), 1);
}

#[test]
fn an_empty_history_window_is_disclosed() {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    fs::write(project.path().join("package.json"), "{}\n").unwrap();
    fs::write(
        project.path().join("lib.js"),
        "export function value(item) {\n  return item ? 1 : 2;\n}\n",
    )
    .unwrap();
    fs::write(
        project.path().join("main.js"),
        "import { value } from './lib';\nexport function doubled(item) {\n  return value(item) * 2;\n}\n",
    )
    .unwrap();
    commit_landed(
        project.path(),
        Some("2000-01-02T03:04:05Z"),
        "older than every selectable window",
    );

    let terminal = run_in(
        project.path(),
        ["--color", "never", "--jobs", "1", "--history", "90d"],
    );
    assert_snapshot(
        "empty-history-window.terminal.txt",
        &terminal,
        include_bytes!("snapshots/empty-history-window.terminal.txt"),
    );
    let text = String::from_utf8(terminal).unwrap();
    assert!(text.contains("No commits in the last 90 days."), "{text}");

    let json = run_in(
        project.path(),
        ["--json", "--jobs", "1", "--history", "90d"],
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    // The stream is complete; the selected window simply contains nothing.
    assert_eq!(report["history_coverage"]["availability"], "complete");
    assert_eq!(report["history_coverage"]["window_days"], 90);
    assert_eq!(report["history_coverage"]["commits"], 0);
    // Source and static architecture results survive the empty window.
    let root = report["root"].as_u64().unwrap() as usize;
    let coverage = &report["scopes"][root]["coverage"];
    assert_eq!(coverage["selected_files"], 2);
    assert_eq!(coverage["analyzed_files"], 2);
    assert_ne!(report["verdict"]["tier"], "empty");
    assert_eq!(report["dependency_coverage"]["internal"], 1);
}

#[test]
fn diff_uses_history_as_context_and_can_explain_coupling() {
    let project = evolutionary_fixture();
    fs::write(
        project.path().join("b/main.js"),
        "import { a } from '../a/main';\nexport const b = a;\n",
    )
    .unwrap();
    let json = run_in(
        project.path(),
        [
            "diff",
            "main",
            "--json",
            "--jobs",
            "1",
            "--history",
            "36500d",
        ],
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert_eq!(report["change_coupling"][0]["shared_commits"], 3);
    assert_eq!(report["change_coupling"][0]["union_commits"], 6);
    assert!(
        report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(
        report["evolutionary_comparisons"]
            .as_array()
            .unwrap()
            .iter()
            .any(|value| { value["kind"] == "finding_removed" && value["direction"] == "better" })
    );
    let default_terminal = String::from_utf8(run_in(
        project.path(),
        ["diff", "main", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(
        default_terminal.contains("Debt increased in some places and decreased in others."),
        "{default_terminal}"
    );
    assert!(
        default_terminal.contains("worse 1 · better 1 · changed 0"),
        "{default_terminal}"
    );
    assert!(
        default_terminal.contains("worse change reaches more code · a · 1 of 3 → 2 of 3"),
        "{default_terminal}"
    );
    assert!(default_terminal.contains("a ↔ b no longer change together without a code dependency"));
    let detailed_terminal = String::from_utf8(run_in(
        project.path(),
        [
            "diff",
            "main",
            "--all",
            "--color",
            "never",
            "--history",
            "36500d",
        ],
    ))
    .unwrap();
    // The change touched `b` alone, so the standing pair is not this change's
    // history however much detail is asked for. It stays whole in JSON, which
    // is where a consumer reads the repository's own coupling table.
    assert!(
        !detailed_terminal.contains("a ↔ b changed together"),
        "{detailed_terminal}"
    );
    assert_eq!(report["change_coupling"][0]["shared_commits"], 3);
    assert!(
        detailed_terminal.contains("a ↔ b no longer change together without a code dependency")
    );
    assert!(!detailed_terminal.contains("coupling finding"));
}

#[test]
fn diff_says_when_packages_now_change_together_without_a_code_dependency() {
    let project = evolutionary_fixture();
    fs::write(
        project.path().join("b/main.js"),
        "import { a } from '../a/main';\nexport const b = a;\n",
    )
    .unwrap();
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "explain coupling",
    );
    fs::write(project.path().join("b/main.js"), "export const b = 6;\n").unwrap();

    let terminal = run_in(
        project.path(),
        ["diff", "HEAD", "--color", "never", "--history", "36500d"],
    );
    assert_snapshot(
        "evolutionary-introduced.terminal.txt",
        &terminal,
        include_bytes!("snapshots/evolutionary-introduced.terminal.txt"),
    );
    let terminal = String::from_utf8(terminal).unwrap();
    assert!(terminal.contains("a ↔ b now change together without a code dependency"));
    assert!(!terminal.contains("coupling finding"));
}

#[test]
fn ref_and_worktree_diffs_apply_the_same_coupling_policy() {
    let project = evolutionary_fixture();
    git(project.path(), ["branch", "base"]);
    fs::write(
        project.path().join("b/main.js"),
        "import { a } from '../a/main';\nexport const b = a;\n",
    )
    .unwrap();
    let worktree: serde_json::Value = serde_json::from_slice(&run_in(
        project.path(),
        ["diff", "base", "--json", "--history", "36500d"],
    ))
    .unwrap();
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "explain coupling",
    );
    let committed: serde_json::Value = serde_json::from_slice(&run_in(
        project.path(),
        ["diff", "base", "--json", "--history", "36500d"],
    ))
    .unwrap();

    for report in [&worktree, &committed] {
        assert!(
            report["evolutionary_findings"]
                .as_array()
                .unwrap()
                .is_empty()
        );
        assert_eq!(
            report["evolutionary_comparisons"][0]["kind"],
            "finding_removed"
        );
        assert_eq!(report["evolutionary_comparisons"][0]["direction"], "better");
    }
}

#[test]
fn fixture_and_generated_history_stays_descriptive_without_findings() {
    let project = contextual_history_fixture();
    let json = run_in(project.path(), ["--json", "--history", "36500d"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert_eq!(report["change_coupling"].as_array().unwrap().len(), 3);
    assert!(
        report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert_eq!(report["files"][0]["role"], "primary");
    assert_eq!(report["files"][1]["role"], "fixture");
    assert_eq!(report["files"][2]["role"], "generated");
    assert_eq!(report["file_history"][0]["touches"], 3);
    assert_eq!(report["file_history"][0]["role"], "primary");
    assert_eq!(report["file_history"][0]["trust"], "trusted");
    assert_eq!(report["file_history"][1]["touches"], 3);
    assert_eq!(report["file_history"][1]["role"], "fixture");
    assert_eq!(report["file_history"][2]["touches"], 3);
    assert_eq!(report["file_history"][2]["role"], "generated");
    assert_eq!(report["history_coverage"]["eligible_commits"], 3);
    assert_eq!(report["history_coverage"]["mapped_eligible_changes"], 3);
    assert_eq!(report["history_coverage"]["context_changes"], 6);
    assert_eq!(report["change_coupling"][0]["left_role"], "primary");
    assert_eq!(report["change_coupling"][0]["right_role"], "fixture");

    let default = String::from_utf8(run_in(
        project.path(),
        ["--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(!default.contains("a ↔ b"), "{default}");
    assert!(!default.contains("a ↔ c"), "{default}");
    // Codebase debt is problem cards, and only an actionable finding makes
    // one, so a pair a fixture or generated role explains has no card at any
    // detail level and stays a complete row in the machine report.
    let detailed = String::from_utf8(run_in(
        project.path(),
        ["--all", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    // The substring covers both co-change patterns, so neither the package
    // wording nor the file wording can return with a fixture-explained pair.
    assert!(!detailed.contains("change together"), "{detailed}");
    assert!(!detailed.contains("a ↔ b"), "{detailed}");
    assert!(!detailed.contains("a ↔ c"), "{detailed}");
}

#[test]
fn generated_history_cannot_change_eligible_history_or_concentration() {
    let project = generated_heavy_history_fixture();
    let report: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--history", "36500d"])).unwrap();
    validate_schema(&report);
    assert_index_integrity(&report);
    let diff_report: serde_json::Value = serde_json::from_slice(&run_in(
        project.path(),
        ["diff", "HEAD", "--json", "--history", "36500d"],
    ))
    .unwrap();
    for field in [
        "history_coverage",
        "file_history",
        "change_coupling",
        "contributor_concentration",
        "evolutionary_findings",
    ] {
        assert_eq!(
            report[field], diff_report[field],
            "{field} differs in diff mode"
        );
    }
    let nonempty_package_history = |value: &serde_json::Value| {
        value["package_history"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|row| row["touches"] != 0)
            .cloned()
            .collect::<Vec<_>>()
    };
    assert_eq!(
        nonempty_package_history(&report),
        nonempty_package_history(&diff_report)
    );

    let coverage = &report["history_coverage"];
    assert_eq!(coverage["commits"], 10);
    assert_eq!(coverage["eligible_commits"], 3);
    assert_eq!(coverage["mapped_eligible_changes"], 6);
    assert_eq!(coverage["context_changes"], 16);
    assert_eq!(coverage["excluded_changes"], 3);
    assert_eq!(coverage["textual_changes"], 22);
    assert_eq!(coverage["uncounted_changes"], 0);

    let package_history = report["package_history"].as_array().unwrap();
    for package in 0..=1 {
        let eligible = package_history
            .iter()
            .find(|row| row["package"] == package && row["role"] == "primary")
            .unwrap();
        let context = package_history
            .iter()
            .find(|row| row["package"] == package && row["role"] == "generated")
            .unwrap();
        assert_eq!(eligible["touches"], 3);
        assert_eq!(context["touches"], 8);
    }
    let concentration = report["contributor_concentration"].as_array().unwrap();
    for package in 0..=1 {
        let eligible = concentration
            .iter()
            .find(|row| row["package"] == package && row["role"] == "primary")
            .unwrap();
        let context = concentration
            .iter()
            .find(|row| row["package"] == package && row["role"] == "generated")
            .unwrap();
        assert_eq!(eligible["contributor_count"], 1);
        assert_eq!(eligible["numerator"], 3);
        assert_eq!(eligible["denominator"], 3);
        assert_eq!(context["contributor_count"], 8);
        assert_eq!(context["numerator"], 1);
        assert_eq!(context["denominator"], 8);
    }
    let coupling = report["change_coupling"].as_array().unwrap();
    assert_eq!(coupling.len(), 1, "{coupling:?}");
    assert_eq!(coupling[0]["left_role"], "primary");
    assert_eq!(coupling[0]["right_role"], "primary");
    assert_eq!(coupling[0]["shared_commits"], 10);
    assert_eq!(coupling[0]["union_commits"], 10);
    assert_eq!(report["evolutionary_findings"][0]["shared_commits"], 3);
    assert_eq!(report["evolutionary_findings"][0]["union_commits"], 3);

    let default = String::from_utf8(run_in(
        project.path(),
        ["--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(!default.contains("eligible mapping"));
    assert!(!default.contains("touches"));
    assert!(!default.contains("top share"));
    assert!(!default.contains("generated/trusted"));
    assert!(!default.contains("a · 8 touches"));

    let detailed = String::from_utf8(run_in(
        project.path(),
        ["--all", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    // Churn dumps left the terminal; the actionable coupling finding stayed.
    assert!(!detailed.contains("a · 8 commits"), "{detailed}");
    assert!(!detailed.contains("shared commits"));
    assert!(
        detailed.contains(
            "  watch packages change together · a ↔ b\n        changed together in 3 of 3 commits · 100% · no code dependency\n"
        ),
        "{detailed}"
    );
}

#[test]
fn complete_stream_without_eligible_mapping_cannot_create_findings() {
    let project = generated_only_history_fixture();
    let report: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--history", "36500d"])).unwrap();
    assert_eq!(report["history_coverage"]["availability"], "complete");
    assert_eq!(report["history_coverage"]["eligible_commits"], 0);
    assert_eq!(report["history_coverage"]["mapped_eligible_changes"], 0);
    assert_eq!(report["history_coverage"]["context_changes"], 6);
    assert!(
        report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert_eq!(report["change_coupling"][0]["shared_commits"], 3);

    let terminal = String::from_utf8(run_in(
        project.path(),
        ["--all", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(!terminal.contains("complete local stream"));
    assert!(!terminal.contains("eligible mapping"));
    assert!(!terminal.contains(''));
}

#[test]
fn package_churn_stays_in_json_instead_of_repeating_in_the_terminal() {
    let project = eligible_role_history_fixture();
    let default = String::from_utf8(run_in(
        project.path(),
        ["--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(!default.contains("HISTORY"));

    let detailed = String::from_utf8(run_in(
        project.path(),
        ["--all", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(!detailed.contains("a · 2 commits"), "{detailed}");
    let report: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--history", "36500d"])).unwrap();
    assert_eq!(
        report["package_history"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|row| row["touches"] == 2)
            .count(),
        2
    );
}

#[test]
fn weak_coupling_stays_in_json_only() {
    let project = weak_history_fixture();
    let report: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--history", "36500d"])).unwrap();
    assert_eq!(report["change_coupling"].as_array().unwrap().len(), 1);
    assert_eq!(report["change_coupling"][0]["shared_commits"], 2);
    assert_eq!(report["change_coupling"][0]["union_commits"], 4);
    assert!(
        report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );

    for terminal in [
        run_in(project.path(), ["--color", "never", "--history", "36500d"]),
        run_in(
            project.path(),
            ["--all", "--color", "never", "--history", "36500d"],
        ),
        run_in(
            project.path(),
            ["a", "--all", "--color", "never", "--history", "36500d"],
        ),
    ] {
        let terminal = String::from_utf8(terminal).unwrap();
        assert!(!terminal.contains("a ↔ b"), "{terminal}");
    }
}

#[test]
fn a_selected_package_states_actionable_history_only() {
    let project = evolutionary_fixture();
    fs::write(
        project.path().join("b/main.js"),
        "import { a } from '../a/main';\nexport const b = a;\n",
    )
    .unwrap();
    let terminal = run_in(
        project.path(),
        ["a", "--all", "--color", "never", "--history", "36500d"],
    );
    assert_snapshot(
        "evolutionary-package.terminal.txt",
        &terminal,
        include_bytes!("snapshots/evolutionary-package.terminal.txt"),
    );
    let text = String::from_utf8(terminal).unwrap();
    assert!(!text.contains("a/main.js · 5 commits"), "{text}");
    // Codebase debt is problem cards, and a pair a code dependency explains
    // is not a finding, so nothing states it here; the complete pair table
    // stays in the machine report.
    assert!(!text.contains("a ↔ b"), "{text}");
    assert!(!text.contains("c/main.js"));
    assert!(!text.contains("  c ·"));
    // The selection answers one package of the repository report, so the pair
    // table the terminal declines to state is the repository's own.
    let report: serde_json::Value = serde_json::from_slice(&run_in(
        project.path(),
        ["a", "--json", "--history", "36500d"],
    ))
    .unwrap();
    let root: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--history", "36500d"])).unwrap();
    assert!(!report["change_coupling"].as_array().unwrap().is_empty());
    assert_eq!(report["change_coupling"], root["change_coupling"]);
}

#[test]
fn selected_diff_package_shows_only_relevant_evolution_context() {
    let project = evolutionary_fixture();
    fs::write(
        project.path().join("b/main.js"),
        "import { a } from '../a/main';\nexport const b = a;\n",
    )
    .unwrap();
    let terminal = run_in(
        project.path(),
        [
            "diff",
            "main",
            "b",
            "--all",
            "--color",
            "never",
            "--history",
            "36500d",
        ],
    );
    assert_snapshot(
        "evolutionary-diff-package.terminal.txt",
        &terminal,
        include_bytes!("snapshots/evolutionary-diff-package.terminal.txt"),
    );
    let text = String::from_utf8(terminal).unwrap();
    assert!(!text.contains("b · 4 commits"), "{text}");
    assert!(!text.contains("b/main.js · 4 commits"), "{text}");
    // A view of `b` cannot name what `a` did, so the standing pair leaves even
    // this detail view; the coupling that moved is what the change did and
    // stays wherever the verdict counted it.
    assert!(!text.contains("a ↔ b changed together"), "{text}");
    assert!(text.contains("a ↔ b no longer change together without a code dependency"));
    assert!(!text.contains("c/main.js"));
    assert!(!text.contains("  c ·"));
}

#[test]
fn empty_git_history_is_unavailable_in_coverage_terminal_and_diagnostics() {
    let project = fixture();
    git(project.path(), ["init", "-b", "main"]);
    let json = run_in(project.path(), ["--json", "--jobs", "1"]);
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert_eq!(report["history_coverage"]["availability"], "unavailable");
    assert_eq!(
        report["history_coverage"]["reason"],
        "repository has no commits"
    );
    assert!(
        report["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .any(|diagnostic| {
                diagnostic["message"] == "Git history unavailable: repository has no commits"
            })
    );
    let terminal = String::from_utf8(run_in(project.path(), ["--color", "never"])).unwrap();
    assert!(terminal.contains("WARNINGS"));
    assert!(terminal.contains("History is unavailable."));
    assert!(!terminal.contains("History is incomplete."));
}

#[test]
fn shallow_history_is_reported_as_incomplete() {
    let checkout = shallow_evolutionary_fixture();
    let json = run_in(
        checkout.path(),
        ["--json", "--jobs", "1", "--history", "36500d"],
    );
    let report: serde_json::Value = serde_json::from_slice(&json).unwrap();
    validate_schema(&report);
    assert_eq!(report["history_coverage"]["availability"], "incomplete");
    assert_eq!(
        report["history_coverage"]["reason"],
        "repository history is shallow"
    );
    assert_eq!(report["history_coverage"]["commits"], 6);
    assert!(report["history_coverage"].get("revision").is_some());
    assert!(report["history_coverage"].get("newest_timestamp").is_some());
    assert!(report["history_coverage"].get("oldest_timestamp").is_some());
    assert!(report["history_coverage"].get("textual_changes").is_some());
    assert!(
        report["history_coverage"]
            .get("uncounted_changes")
            .is_some()
    );
    assert!(report["history_coverage"].get("eligible_commits").is_some());
    assert!(
        report["history_coverage"]
            .get("mapped_eligible_changes")
            .is_some()
    );
    assert!(report["history_coverage"].get("context_changes").is_some());
    assert!(report["history_coverage"].get("excluded_changes").is_some());
    assert!(report["history_coverage"].get("rename_gaps").is_some());
    assert!(
        report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(!report["files"].as_array().unwrap().is_empty());
}

#[test]
fn changed_dependency_with_shallow_history_shows_only_the_relevant_trust_warning() {
    let checkout = shallow_evolutionary_fixture();
    fs::write(
        checkout.path().join("b/main.test.js"),
        "import { a } from '../a/main';\nexport const expected = a;\n",
    )
    .unwrap();

    let terminal = String::from_utf8(run_in(
        checkout.path(),
        ["diff", "HEAD", "--color", "never", "--history", "36500d"],
    ))
    .unwrap();
    assert!(terminal.contains("No debt changed."), "{terminal}");
    assert!(
        terminal.contains("warning History is incomplete."),
        "{terminal}"
    );
    assert!(!terminal.contains("HISTORY"), "{terminal}");
    assert!(!terminal.contains("changed together"), "{terminal}");
    // Nothing moved, so the report has no path to point at.
    assert!(!terminal.contains("next:"), "{terminal}");
}

/// A path-selected machine head answers the question the terminal answers for
/// the same invocation, so `--json | head` and the human report never
/// disagree about which scope was asked about.
#[test]
fn a_path_selected_json_head_answers_the_selected_scope_like_the_terminal() {
    let project = split_debt_fixture();
    let clean = project.path().join("clean");
    let clean = clean.to_str().unwrap();
    let repository: serde_json::Value =
        serde_json::from_slice(&run(["--json", project.path().to_str().unwrap()])).unwrap();
    let selected: serde_json::Value = serde_json::from_slice(&run(["--json", clean])).unwrap();
    let terminal = String::from_utf8(run(["--color", "never", "--all", clean])).unwrap();

    assert_ne!(
        selected["verdict"]["tier"], repository["verdict"]["tier"],
        "the head answers the selected scope, not the repository"
    );
    assert!(
        terminal.contains(selected["verdict"]["sentence"].as_str().unwrap()),
        "{terminal}"
    );
    let summary = &selected["summary"];
    let counts = format!(
        "{} high · {} watch · {} checked",
        summary["high"].as_u64().unwrap(),
        summary["watch"].as_u64().unwrap(),
        summary["checked"].as_u64().unwrap()
    );
    assert!(terminal.contains(&counts), "{terminal}");
    match summary["worst"].as_array().unwrap().first() {
        Some(worst) => assert!(
            terminal.contains(&format!("worst: {}", worst["path"].as_str().unwrap())),
            "{terminal}"
        ),
        None => assert!(!terminal.contains("worst: "), "{terminal}"),
    }
    validate_schema(&selected);
    assert_index_integrity(&selected);
}

/// A reader that stops reading, which is what `| head` is, ends the run
/// quietly the way every other Unix tool ends it.
#[test]
fn a_report_piped_into_head_is_quiet_and_successful() {
    // The report has to outgrow one buffered write, which is when the reader
    // has already left by the time the next write happens.
    let project = tangled_fixture(400);
    let binary = assert_cmd::cargo::cargo_bin("smackdebt");
    let mut shell = Command::new("sh");
    // The pipeline inherits the pinned environment through the shell.
    hermetic_env(&mut shell);
    let output = shell
        .arg("-c")
        .arg(format!(
            "'{}' --all '{}' | head -1",
            binary.display(),
            project.path().display()
        ))
        .output()
        .unwrap();
    assert_eq!(String::from_utf8_lossy(&output.stderr), "");
    assert!(output.status.success());
    assert!(
        String::from_utf8_lossy(&output.stdout).starts_with("smackdebt · "),
        "{}",
        String::from_utf8_lossy(&output.stdout)
    );
}

fn assert_snapshot(name: &str, actual: &[u8], expected: &[u8]) {
    if name.ends_with(".terminal.txt") {
        assert_no_dependency_edge_rows(&String::from_utf8_lossy(actual), name);
    }
    if std::env::var_os("SMACKDEBT_UPDATE_SNAPSHOTS").is_some() {
        assert_eq!(
            std::env::var_os("SMACKDEBT_UPDATE_COMMAND").as_deref(),
            Some(std::ffi::OsStr::new("1")),
            "snapshot updates require the named developer command"
        );
        fs::write(
            Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/snapshots")
                .join(name),
            actual,
        )
        .unwrap();
        return;
    }
    assert_eq!(actual, expected, "snapshot {name} changed");
}

fn validate_schema(report: &serde_json::Value) {
    let schema: serde_json::Value =
        serde_json::from_str(include_str!("../../../schemas/report-v4.schema.json")).unwrap();
    jsonschema::validator_for(&schema)
        .unwrap()
        .validate(report)
        .unwrap();
}

fn validate_gate_schema(result: &serde_json::Value) {
    let schema: serde_json::Value =
        serde_json::from_str(include_str!("../../../schemas/gate-v1.schema.json")).unwrap();
    jsonschema::validator_for(&schema)
        .unwrap()
        .validate(result)
        .unwrap();
}

/// The denormalized head duplicates table facts on purpose, so every value in
/// it is compared with the table it came from.
fn assert_head_agrees_with_tables(report: &serde_json::Value) {
    let mode = report["mode"].as_str().unwrap();
    assert_eq!(report["verdict"]["mode"], mode);
    assert!(!report["verdict"]["tier"].as_str().unwrap().is_empty());
    assert!(
        report["verdict"]["sentence"]
            .as_str()
            .unwrap()
            .ends_with('.')
    );
    let summary = &report["summary"];
    // The head answers the selected scope, which is the repository unless a
    // path was asked about.
    let Some(answered) = report["selected_scope"]
        .as_u64()
        .or_else(|| report["root"].as_u64())
        .map(|scope| scope as usize)
    else {
        assert_eq!(summary["checked"], 0);
        return;
    };
    let health = report["scopes"][answered]["health"].as_u64().unwrap() as usize;
    let coverage = &report["scopes"][answered]["coverage"];
    match report["verdict"].get("qualifier") {
        Some(qualifier) => {
            assert_eq!(qualifier["selected_files"], coverage["selected_files"]);
            assert_eq!(qualifier["analyzed_files"], coverage["analyzed_files"]);
            assert!(
                coverage["analyzed_files"].as_u64().unwrap()
                    < coverage["selected_files"].as_u64().unwrap()
            );
        }
        None => assert_eq!(coverage["analyzed_files"], coverage["selected_files"]),
    }
    let counts = &report["health"][health];
    assert_eq!(summary["high"], counts["high"]);
    assert_eq!(summary["watch"], counts["watch"]);
    assert_eq!(
        summary["checked"].as_u64().unwrap(),
        counts["healthy"].as_u64().unwrap()
            + counts["watch"].as_u64().unwrap()
            + counts["high"].as_u64().unwrap()
    );
    let architecture = report["scopes"][answered]["architecture_findings"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|id| {
            report["architecture_findings"][id.as_u64().unwrap() as usize]["rating"] == "high"
        })
        .count() as u64;
    assert_eq!(summary["high_architecture"].as_u64(), Some(architecture));
    let paths: Vec<&str> = report["paths"]
        .as_array()
        .unwrap()
        .iter()
        .map(|path| path.as_str().unwrap())
        .collect();
    let worst = summary["worst"].as_array().unwrap();
    assert!(worst.len() <= 3);
    for offender in worst {
        let path = offender["path"].as_str().unwrap();
        assert!(
            paths.contains(&path),
            "worst path {path} is not a real path"
        );
    }
}

fn assert_index_integrity(report: &serde_json::Value) {
    let paths = report["paths"].as_array().unwrap();
    let scopes = report["scopes"].as_array().unwrap();
    let files = report["files"].as_array().unwrap();
    let findings = report["findings"].as_array().unwrap();
    let comparisons = report["comparisons"].as_array().unwrap();
    let health = report["health"].as_array().unwrap();
    let activity = report["activity"].as_array().unwrap();
    let dependency_edges = report["dependency_edges"].as_array().unwrap();
    let package_edges = report["package_edges"].as_array().unwrap();
    let architecture_findings = report["architecture_findings"].as_array().unwrap();
    let architecture_comparisons = report["architecture_comparisons"].as_array().unwrap();
    let file_history = report["file_history"].as_array().unwrap();
    let package_history = report["package_history"].as_array().unwrap();
    let change_coupling = report["change_coupling"].as_array().unwrap();
    let contributor_concentration = report["contributor_concentration"].as_array().unwrap();
    let evolutionary_findings = report["evolutionary_findings"].as_array().unwrap();
    let evolutionary_comparisons = report["evolutionary_comparisons"].as_array().unwrap();
    let package_graph = report["package_graph"].as_array().unwrap();
    let external_dependencies = report["external_dependencies"].as_array().unwrap();
    let resolution_diagnostics = report["resolution_diagnostics"].as_array().unwrap();

    assert_head_agrees_with_tables(report);
    for field in ["root", "selected_scope"] {
        if let Some(index) = report[field].as_u64() {
            assert!(
                (index as usize) < scopes.len(),
                "{field} points outside scopes"
            );
        }
    }
    assert_eq!(health.len(), scopes.len() + files.len());
    assert_eq!(activity.len(), files.len());

    for (index, scope) in scopes.iter().enumerate() {
        assert_eq!(scope["id"], index);
        assert!(scope.get("name").is_none());
        if let Some(path) = scope["path"].as_u64() {
            assert!((path as usize) < paths.len());
        }
        assert!((scope["health"].as_u64().unwrap() as usize) < health.len());
        if let Some(parent) = scope["parent"].as_u64() {
            let parent = parent as usize;
            assert!(parent < scopes.len());
            assert!(
                scopes[parent]["children"]
                    .as_array()
                    .unwrap()
                    .contains(&scope["id"])
            );
        }
        for child in scope["children"].as_array().unwrap() {
            let child = child.as_u64().unwrap() as usize;
            assert!(child < scopes.len());
            assert_eq!(scopes[child]["parent"], index);
        }
        for finding in scope["findings"].as_array().unwrap() {
            assert!((finding.as_u64().unwrap() as usize) < findings.len());
        }
        for comparison in scope["comparisons"].as_array().unwrap() {
            assert!((comparison.as_u64().unwrap() as usize) < comparisons.len());
        }
        for finding in scope["architecture_findings"].as_array().unwrap() {
            assert!((finding.as_u64().unwrap() as usize) < architecture_findings.len());
        }
        for comparison in scope["architecture_comparisons"].as_array().unwrap() {
            assert!((comparison.as_u64().unwrap() as usize) < architecture_comparisons.len());
        }
        for finding in scope["evolutionary_findings"].as_array().unwrap() {
            assert!((finding.as_u64().unwrap() as usize) < evolutionary_findings.len());
        }
        for comparison in scope["evolutionary_comparisons"].as_array().unwrap() {
            assert!((comparison.as_u64().unwrap() as usize) < evolutionary_comparisons.len());
        }
    }
    for (index, file) in files.iter().enumerate() {
        assert_eq!(file["id"], index);
        assert!(file.get("path_id").is_none());
        if let Some(path) = file["path"].as_u64() {
            assert!((path as usize) < paths.len());
        }
        assert!((file["scope"].as_u64().unwrap() as usize) < scopes.len());
        assert!((file["health"].as_u64().unwrap() as usize) < health.len());
        assert!((file["activity"].as_u64().unwrap() as usize) < activity.len());
        if let Some(package) = file["package"].as_u64() {
            assert!((package as usize) < package_graph.len());
        }
    }
    for (index, finding) in findings.iter().enumerate() {
        assert_eq!(finding["id"], index);
        assert!((finding["file"].as_u64().unwrap() as usize) < files.len());
        assert!(finding["kind"].is_string());
    }
    for (index, comparison) in comparisons.iter().enumerate() {
        assert_eq!(comparison["id"], index);
        assert!(comparison["unit_kind"].is_string());
        assert!(matches!(
            comparison["participation"].as_str(),
            Some("verdict" | "context")
        ));
        if let Some(file) = comparison["file"].as_u64() {
            assert!((file as usize) < files.len());
        }
    }
    for (index, record) in health.iter().enumerate() {
        assert_eq!(record["id"], index);
    }
    for (index, record) in activity.iter().enumerate() {
        assert_eq!(record["id"], index);
        assert!((record["file"].as_u64().unwrap() as usize) < files.len());
    }
    for (index, edge) in dependency_edges.iter().enumerate() {
        assert_eq!(edge["id"], index);
        assert!((edge["source"].as_u64().unwrap() as usize) < files.len());
        assert!((edge["target"].as_u64().unwrap() as usize) < files.len());
    }
    for (index, edge) in package_edges.iter().enumerate() {
        assert_eq!(edge["id"], index);
        assert!((edge["source"].as_u64().unwrap() as usize) < package_graph.len());
        assert!((edge["target"].as_u64().unwrap() as usize) < package_graph.len());
        for file_edge in edge["file_edges"].as_array().unwrap() {
            assert!((file_edge.as_u64().unwrap() as usize) < dependency_edges.len());
        }
    }
    for (index, finding) in architecture_findings.iter().enumerate() {
        assert_eq!(finding["id"], index);
        for file in finding["files"].as_array().unwrap() {
            assert!((file.as_u64().unwrap() as usize) < files.len());
        }
        for package in finding["packages"].as_array().unwrap() {
            assert!((package.as_u64().unwrap() as usize) < package_graph.len());
        }
        for edge in finding["witness_edges"].as_array().unwrap() {
            assert!((edge.as_u64().unwrap() as usize) < dependency_edges.len());
        }
    }
    for (index, comparison) in architecture_comparisons.iter().enumerate() {
        assert_eq!(comparison["id"], index);
        for field in ["packages", "witness"] {
            for package in comparison[field].as_array().unwrap() {
                assert!((package.as_u64().unwrap() as usize) < package_graph.len());
            }
        }
        for file in comparison["files"].as_array().unwrap() {
            assert!((file.as_u64().unwrap() as usize) < files.len());
        }
    }
    for (index, measurement) in package_graph.iter().enumerate() {
        assert_eq!(measurement["package"], index);
    }
    assert_eq!(file_history.len(), files.len());
    let mut files_with_history = HashSet::new();
    for history in file_history {
        let file = history["file"].as_u64().unwrap() as usize;
        assert!(file < files.len());
        assert!(
            files_with_history.insert(file),
            "duplicate file history row"
        );
    }
    assert_eq!(files_with_history.len(), files.len());

    let mut packages_with_history = HashSet::new();
    let mut package_history_keys = HashSet::new();
    for history in package_history {
        let package = history["package"].as_u64().unwrap() as usize;
        assert!(package < package_graph.len());
        let role = history["role"].as_str().unwrap();
        let trust = history["trust"].as_str().unwrap();
        assert!(
            package_history_keys.insert((package, role, trust)),
            "duplicate package history evidence row"
        );
        packages_with_history.insert(package);
    }
    assert_eq!(packages_with_history.len(), package_graph.len());

    let mut coupling_pairs = HashSet::new();
    for coupling in change_coupling {
        let left = coupling["left"].as_u64().unwrap() as usize;
        let right = coupling["right"].as_u64().unwrap() as usize;
        assert!(left < package_graph.len());
        assert!(right < package_graph.len());
        assert!(left < right, "coupling pair identity is not stable");
        let left_role = coupling["left_role"].as_str().unwrap();
        let left_trust = coupling["left_trust"].as_str().unwrap();
        let right_role = coupling["right_role"].as_str().unwrap();
        let right_trust = coupling["right_trust"].as_str().unwrap();
        assert!(
            coupling_pairs.insert((left, right, left_role, left_trust, right_role, right_trust,)),
            "duplicate coupling evidence pair"
        );
    }

    // A retained file pair names the lower file identity first, crosses a
    // directory boundary, and compares two counts drawn from one population.
    let mut previous_pair = None;
    for pair in report["file_change_coupling"].as_array().unwrap() {
        let left = pair["left"].as_u64().unwrap();
        let right = pair["right"].as_u64().unwrap();
        assert!((left as usize) < files.len(), "pair left index is invalid");
        assert!(
            (right as usize) < files.len(),
            "pair right index is invalid"
        );
        assert!(left < right, "a pair names the lower file identity first");
        let key = Some((left, right));
        assert!(previous_pair < key, "pairs are ordered by file identity");
        previous_pair = key;
        let shared = pair["shared_commits"].as_u64().unwrap();
        let union = pair["union_commits"].as_u64().unwrap();
        assert!(shared >= 3, "a retained pair clears the support floor");
        assert!(shared <= union, "shared commits are part of the union");
        assert!(shared * 10 >= union, "a retained pair clears one tenth");
        assert!(
            pair["distance"].as_u64().unwrap() >= 1,
            "a same-directory pair is never stored"
        );
        assert!(pair.get("similarity").is_none(), "no ratio is serialized");
    }

    let mut concentration_packages = HashSet::new();
    for concentration in contributor_concentration {
        let package = concentration["package"].as_u64().unwrap() as usize;
        assert!(package < package_graph.len());
        let role = concentration["role"].as_str().unwrap();
        let trust = concentration["trust"].as_str().unwrap();
        assert!(
            concentration_packages.insert((package, role, trust)),
            "duplicate concentration evidence row"
        );
    }

    for (index, finding) in evolutionary_findings.iter().enumerate() {
        assert_eq!(finding["id"], index);
        let left = finding["left"].as_u64().unwrap() as usize;
        let right = finding["right"].as_u64().unwrap() as usize;
        assert!(left < package_graph.len());
        assert!(right < package_graph.len());
        assert!(left < right);
        assert!(finding["shared_commits"].as_u64().unwrap() >= 3);
        assert_eq!(finding["kind"], "unexplained_coupling");
    }
    for (index, comparison) in evolutionary_comparisons.iter().enumerate() {
        assert_eq!(comparison["id"], index);
        let left = comparison["left"].as_u64().unwrap() as usize;
        let right = comparison["right"].as_u64().unwrap() as usize;
        assert!(left < package_graph.len());
        assert!(right < package_graph.len());
        assert!(left < right);
        assert!(comparison["shared_commits"].as_u64().unwrap() >= 3);
    }
    for dependency in external_dependencies {
        assert!((dependency["file"].as_u64().unwrap() as usize) < files.len());
    }
    for diagnostic in resolution_diagnostics {
        assert!((diagnostic["file"].as_u64().unwrap() as usize) < files.len());
    }
}

#[test]
fn index_audit_rejects_a_nested_architecture_reference() {
    let project = static_architecture_fixture();
    let bytes = run(["--json", project.path().to_str().unwrap()]);
    let mut report: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert!(
        !report["architecture_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(
        !report["architecture_findings"][0]["witness_edges"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    report["architecture_findings"][0]["witness_edges"][0] = 999_999.into();
    assert!(std::panic::catch_unwind(|| assert_index_integrity(&report)).is_err());
}

#[test]
fn index_audit_rejects_a_nested_evolution_reference() {
    let project = evolutionary_fixture();
    let bytes = run([
        "--json",
        "--history",
        "36500d",
        project.path().to_str().unwrap(),
    ]);
    let mut report: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert!(
        !report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    report["evolutionary_findings"][0]["right"] = 999_999.into();
    assert!(std::panic::catch_unwind(|| assert_index_integrity(&report)).is_err());
}

#[test]
fn report_schema_has_no_contributor_identity_fields_or_tables() {
    let schema: serde_json::Value =
        serde_json::from_str(include_str!("../../../schemas/report-v4.schema.json")).unwrap();
    assert_schema_omits_identity_keys(&schema);
}

fn assert_schema_omits_identity_keys(value: &serde_json::Value) {
    const FORBIDDEN_KEYS: &[&str] = &[
        "source_text",
        "commit_message",
        "author",
        "authors",
        "author_name",
        "author_address",
        "author_email",
        "author_identity",
        "raw_author",
        "raw_author_name",
        "raw_author_address",
        "raw_author_email",
        "address",
        "email",
        "email_address",
        "contributor_id",
        "contributor_ids",
        "contributor_identity",
        "contributor_identities",
        "contributor_name",
        "contributor_address",
        "contributor_email",
    ];
    match value {
        serde_json::Value::Object(object) => {
            for (key, child) in object {
                assert!(
                    !FORBIDDEN_KEYS.contains(&key.as_str()),
                    "schema exposes contributor identity key {key}"
                );
                assert_schema_omits_identity_keys(child);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                assert_schema_omits_identity_keys(item);
            }
        }
        _ => {}
    }
}

#[test]
fn json_schema_rejects_nested_field_type_drift() {
    let project = fixture();
    let bytes = run(["--json", project.path().to_str().unwrap()]);
    let mut report: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    report["scopes"][0]["coverage"]["selected_files"] = "one".into();
    let schema: serde_json::Value =
        serde_json::from_str(include_str!("../../../schemas/report-v4.schema.json")).unwrap();
    assert!(
        jsonschema::validator_for(&schema)
            .unwrap()
            .validate(&report)
            .is_err()
    );
}

#[test]
fn json_schema_rejects_weak_evolution_verdict_thresholds() {
    let project = evolutionary_fixture();
    let finding_report: serde_json::Value =
        serde_json::from_slice(&run_in(project.path(), ["--json", "--history", "36500d"])).unwrap();
    assert!(
        !finding_report["evolutionary_findings"]
            .as_array()
            .unwrap()
            .is_empty()
    );

    fs::write(
        project.path().join("b/main.js"),
        "import { a } from '../a/main';\nexport const b = a;\n",
    )
    .unwrap();
    let comparison_report: serde_json::Value = serde_json::from_slice(&run_in(
        project.path(),
        ["diff", "main", "--json", "--history", "36500d"],
    ))
    .unwrap();
    assert!(
        !comparison_report["evolutionary_comparisons"]
            .as_array()
            .unwrap()
            .is_empty()
    );

    let schema: serde_json::Value =
        serde_json::from_str(include_str!("../../../schemas/report-v4.schema.json")).unwrap();
    let validator = jsonschema::validator_for(&schema).unwrap();
    for (table, report) in [
        ("evolutionary_findings", finding_report),
        ("evolutionary_comparisons", comparison_report),
    ] {
        let mut weak_commits = report.clone();
        weak_commits[table][0]["shared_commits"] = 2.into();
        assert!(validator.validate(&weak_commits).is_err(), "{table}");

        // Version 4 publishes operands only, so a re-added float is rejected.
        let mut float_operand = report;
        float_operand[table][0]["similarity"] = 0.19.into();
        assert!(validator.validate(&float_operand).is_err(), "{table}");
    }
}

/// Every private-use codepoint, which may never reach a machine consumer.
fn private_use_codepoints(value: &[u8]) -> Vec<char> {
    String::from_utf8_lossy(value)
        .chars()
        .filter(|character| ('\u{e000}'..='\u{f8ff}').contains(character))
        .collect()
}

/// Removes each decoration, restoring the cells it filled.
fn strip_decorations(value: &[u8]) -> Vec<u8> {
    String::from_utf8_lossy(value)
        .chars()
        .map(|character| {
            // A decoration fills the two cells an undecorated report leaves
            // blank, so removing it restores those two spaces.
            if ('\u{e000}'..='\u{f8ff}').contains(&character) || character == '\u{258c}' {
                ' '
            } else {
                character
            }
        })
        .collect::<String>()
        .into_bytes()
}

fn strip_ansi(value: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(value.len());
    let mut index = 0;
    while index < value.len() {
        if value[index..].starts_with(b"\x1b[") {
            index += 2;
            while index < value.len() && !(b'@'..=b'~').contains(&value[index]) {
                index += 1;
            }
            index += usize::from(index < value.len());
        } else {
            result.push(value[index]);
            index += 1;
        }
    }
    result
}

/// The built command with its environment pinned to the hermetic home.
fn smackdebt() -> assert_cmd::Command {
    let mut command = Command::new(assert_cmd::cargo::cargo_bin("smackdebt"));
    hermetic_env(&mut command);
    assert_cmd::Command::from_std(command)
}

fn run<const N: usize>(arguments: [&str; N]) -> Vec<u8> {
    let stdout = smackdebt().args(arguments).output().unwrap().stdout;
    // Every human result this suite produces carries the invariant, so a flow
    // without a committed result cannot reintroduce edge rows either.
    if !arguments.contains(&"--json") {
        assert_no_dependency_edge_rows(
            &String::from_utf8_lossy(&stdout),
            &format!("{arguments:?}"),
        );
    }
    stdout
}

fn run_in<const N: usize>(directory: &Path, arguments: [&str; N]) -> Vec<u8> {
    let stdout = smackdebt()
        .current_dir(directory)
        .args(arguments)
        .output()
        .unwrap()
        .stdout;
    // Every human result this suite produces carries the invariant, so a flow
    // without a committed result cannot reintroduce edge rows either.
    if !arguments.contains(&"--json") {
        assert_no_dependency_edge_rows(
            &String::from_utf8_lossy(&stdout),
            &format!("{arguments:?}"),
        );
    }
    stdout
}

fn source_engine_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::create_dir(project.path().join("src")).unwrap();
    fs::copy(
        Path::new(SOURCE_ENGINE_FIXTURE).join("Gemfile"),
        project.path().join("Gemfile"),
    )
    .unwrap();
    fs::copy(
        Path::new(SOURCE_ENGINE_FIXTURE).join("src/work.rb"),
        project.path().join("src/work.rb"),
    )
    .unwrap();
    project
}

/// One kept candidate beside both nested-checkout shapes: an embedded clone
/// with a `.git` directory and a linked worktree with a `.git` file.
fn nested_checkout_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(project.path().join("kept.js"), "export const kept = 1;\n").unwrap();
    fs::create_dir_all(project.path().join("clone/.git")).unwrap();
    fs::write(
        project.path().join("clone/lost.js"),
        "export const lost = 1;\n",
    )
    .unwrap();
    fs::create_dir_all(project.path().join("worktree")).unwrap();
    fs::write(
        project.path().join("worktree/.git"),
        "gitdir: /elsewhere/.git/worktrees/pr-48\n",
    )
    .unwrap();
    fs::write(
        project.path().join("worktree/lost.js"),
        "export const lost = 1;\n",
    )
    .unwrap();
    project
}

/// One supported JavaScript file of 39 bytes beside one unsupported Swift file
/// of 65 bytes, so the unsupported byte share is exactly 625 permille.
fn unsupported_share_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("kept.js"),
        "export function kept() {\n  return 1;\n}\n",
    )
    .unwrap();
    fs::write(
        project.path().join("main.swift"),
        "// Swift\n\nlet message = \"debt\"\n\nfunc main() {\n  print(message)\n}\n",
    )
    .unwrap();
    project
}

fn static_architecture_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    for path in [
        "app/package.json",
        "app/main.js",
        "app/choice.js",
        "app/choice.ts",
        "app/helper.js",
        "core/package.json",
        "core/main.js",
        "native/Cargo.toml",
        "native/src/lib.rs",
        "native/src/helper.rs",
    ] {
        let source = Path::new(STATIC_ARCHITECTURE_FIXTURE).join(path);
        let target = project.path().join(path);
        fs::create_dir_all(target.parent().unwrap()).unwrap();
        fs::copy(source, target).unwrap();
    }
    project
}

fn long_responsive_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    let source_package = "very-long-source-package-name";
    let source_directory = "very-long-source-directory-name";
    let source_file = "very-long-source-file-name.js";
    let target_package = "very-long-target-package-name";
    let target_directory = "very-long-target-directory-name";
    let target_file = "very-long-target-file-name.js";
    let source_path = format!("{source_package}/{source_directory}/{source_file}");
    let target_path = format!("{target_package}/{target_directory}/{target_file}");
    for package in [source_package, target_package] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
    }
    fs::create_dir_all(project.path().join(source_package).join(source_directory)).unwrap();
    fs::create_dir_all(project.path().join(target_package).join(target_directory)).unwrap();
    let mut source = format!(
        "import target from '../../{target_package}/{target_directory}/{target_file}';\n\
         import choice from './choice';\n\
         import library from 'extremely-long-external-library-name';\n\
         const dynamicValue = require(dynamicModuleName);\n\
         export class ExtremelyLongContainerNameThatMustRemainRecognizable {{\n\
           extremelyLongMethodNameThatMustRemainRecognizable(input) {{\n"
    );
    for index in 0..55 {
        source.push_str(&format!("    const value{index} = input + {index};\n"));
    }
    source.push_str("    return target(choice + library + dynamicValue + value54);\n  }\n}\n");
    fs::write(project.path().join(&source_path), &source).unwrap();
    fs::write(
        project.path().join(&target_path),
        format!(
            "import source from '../../{source_package}/{source_directory}/{source_file}';\nexport default source;\n"
        ),
    )
    .unwrap();
    fs::write(
        project
            .path()
            .join(source_package)
            .join(source_directory)
            .join("choice.js"),
        // The long source file is configured as test source, so the primary
        // half of the package cycle has to come from a primary file: a verdict
        // graph carries primary relations only.
        format!(
            "import target from '../../{target_package}/{target_directory}/{target_file}';\nexport default target;\n"
        ),
    )
    .unwrap();
    fs::write(
        project
            .path()
            .join(source_package)
            .join(source_directory)
            .join("choice.ts"),
        "export default 2;\n",
    )
    .unwrap();
    let rust_package = "very-long-rust-ownership-package-name";
    fs::create_dir_all(project.path().join(rust_package).join("src")).unwrap();
    fs::write(
        project.path().join(rust_package).join("Cargo.toml"),
        "[package]\nname = 'long-owned'\nversion = '0.1.0'\n",
    )
    .unwrap();
    fs::write(
        project.path().join(rust_package).join("src/lib.rs"),
        "mod extremely_long_owned_module_name_that_stays_visible;\n",
    )
    .unwrap();
    fs::write(
        project
            .path()
            .join(rust_package)
            .join("src/extremely_long_owned_module_name_that_stays_visible.rs"),
        "pub fn owned() {}\n",
    )
    .unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        format!("[source_roles]\ntest = ['{source_path}']\n"),
    )
    .unwrap();
    git(project.path(), ["init", "-b", "main"]);
    commit_as(
        project.path(),
        "Responsive Test",
        "responsive@example.invalid",
        "initial",
    );
    source.push_str("// second activity commit\n");
    fs::write(project.path().join(&source_path), source).unwrap();
    commit_as(
        project.path(),
        "Responsive Test",
        "responsive@example.invalid",
        "activity",
    );
    project
}

fn git<const N: usize>(directory: &Path, arguments: [&str; N]) {
    let mut command = Command::new("git");
    hermetic_env(&mut command);
    let status = command
        .args(arguments)
        .env("GIT_AUTHOR_DATE", "2026-08-01T12:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-08-01T12:00:00Z")
        .current_dir(directory)
        .status()
        .unwrap();
    assert!(status.success());
}

fn evolutionary_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    fs::create_dir_all(project.path().join("a")).unwrap();
    fs::create_dir_all(project.path().join("b")).unwrap();
    fs::create_dir_all(project.path().join("c")).unwrap();
    fs::write(project.path().join("a/package.json"), "{}\n").unwrap();
    fs::write(project.path().join("b/package.json"), "{}\n").unwrap();
    fs::write(project.path().join("c/package.json"), "{}\n").unwrap();
    fs::write(project.path().join("a/old.js"), "export const a = 1;\n").unwrap();
    fs::write(project.path().join("b/main.js"), "export const b = 1;\n").unwrap();
    fs::write(project.path().join("c/main.js"), "export const c = 1;\n").unwrap();
    commit_as(
        project.path(),
        "Alice Example",
        "alice@example.invalid",
        "initial",
    );
    fs::rename(
        project.path().join("a/old.js"),
        project.path().join("a/main.js"),
    )
    .unwrap();
    fs::write(project.path().join("b/main.js"), "export const b = 2;\n").unwrap();
    commit_as(
        project.path(),
        "Alias Person",
        "alias@example.invalid",
        "rename together",
    );
    fs::write(
        project.path().join(".mailmap"),
        "Alice Example <alice@example.invalid> Alias Person <alias@example.invalid>\n",
    )
    .unwrap();
    fs::write(project.path().join("a/main.js"), "export const a = 3;\n").unwrap();
    fs::write(project.path().join("b/main.js"), "export const b = 3;\n").unwrap();
    commit_as(
        project.path(),
        "Bob Example",
        "bob@example.invalid",
        "together again",
    );
    fs::write(project.path().join("a/main.js"), "export const a = 4;\n").unwrap();
    commit_as(
        project.path(),
        "Alice Example",
        "alice@example.invalid",
        "a only one",
    );
    fs::write(project.path().join("a/main.js"), "export const a = 5;\n").unwrap();
    commit_as(
        project.path(),
        "Alice Example",
        "alice@example.invalid",
        "a only two",
    );
    fs::write(project.path().join("b/main.js"), "export const b = 6;\n").unwrap();
    commit_as(
        project.path(),
        "Bob Example",
        "bob@example.invalid",
        "b only",
    );
    project
}

fn shallow_evolutionary_fixture() -> tempfile::TempDir {
    let origin = evolutionary_fixture();
    fs::write(origin.path().join("a/main.js"), "export const a = 7;\n").unwrap();
    fs::write(origin.path().join("b/main.js"), "export const b = 7;\n").unwrap();
    commit_as(
        origin.path(),
        "Both Example",
        "both@example.invalid",
        "together at head",
    );
    let checkout = tempfile::tempdir().unwrap();
    let mut clone = Command::new("git");
    hermetic_env(&mut clone);
    let output = clone
        .args([
            "clone",
            "--depth",
            "6",
            &format!("file://{}", origin.path().display()),
            ".",
        ])
        .current_dir(checkout.path())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    checkout
}

/// A repository holding one file per frozen file pattern plus the history one
/// package needs to concentrate its knowledge.
///
/// Package `god` does too much and is broad both ways, package `hub` holds
/// both arms of the hub rule — one widely imported file that also changes
/// often beside the nine that import it, and one file that imports nine and
/// never changes — and package `hot` carries every commit after the first,
/// which makes its one file a hotspot and its package a single-author package.
fn problem_pattern_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[thresholds]\ncognitive = { watch = 2, high = 4 }\ncyclomatic = { watch = 2, high = 4 }\nfunction_lines = { watch = 20, high = 40 }\nfile_lines = { watch = 30, high = 200 }\n\n[hotspots]\nminimum_touches = 3\n",
    )
    .unwrap();
    for package in ["god", "hub", "hot"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(
            project.path().join(package).join("package.json"),
            format!("{{\"name\":\"{package}\",\"private\":true}}\n"),
        )
        .unwrap();
    }
    // One widely imported file with one Watch unit, and the nine files of its
    // own package that import it. Later commits touch it on its own, which is
    // the co-change proof a hub carrying debt needs before it is named by its
    // degree rather than by that debt.
    let pick = |version: u32| {
        format!(
            "export function pick(value) {{\n  if (value > {version}) {{\n    return 1;\n  }}\n  return 0;\n}}\n"
        )
    };
    fs::write(project.path().join("hub/hub.js"), pick(0)).unwrap();
    for index in 0..9 {
        fs::write(
            project.path().join(format!("hub/user-{index}.js")),
            format!(
                "import {{ pick }} from './hub';\n\nexport const user{index} = pick({index});\n"
            ),
        )
        .unwrap();
    }
    // One file that imports those nine and never changes: nothing corroborates
    // its breadth, so it is named by the Watch unit it holds rather than by
    // how many files it depends on.
    let mut spread = (0..9)
        .map(|index| format!("import {{ user{index} }} from './user-{index}';\n"))
        .collect::<String>();
    spread.push_str(
        "\nexport function spread(value) {\n  if (value) {\n    return user0 + user1 + user2 + user3 + user4 + user5 + user6 + user7 + user8;\n  }\n  return 0;\n}\n",
    );
    fs::write(project.path().join("hub/spread.js"), spread).unwrap();
    // Ten imports make the concentrated file broad without its length.
    let mut god = (0..9)
        .map(|index| format!("import user{index} from '../hub/user-{index}';\n"))
        .collect::<String>();
    god.push_str("import { pick } from '../hub/hub';\n\n");
    for name in ["first", "second", "third"] {
        god.push_str(&format!(
            "export function {name}(value) {{\n  if (value > 1) {{\n    if (value > 2) {{\n      if (value > 3) {{\n        return pick(value);\n      }}\n    }}\n  }}\n  return 0;\n}}\n\n"
        ));
    }
    god.push_str(
        "export const total = user0 + user1 + user2 + user3 + user4 + user5 + user6 + user7 + user8;\n",
    );
    fs::write(project.path().join("god/god.js"), god).unwrap();
    // One ordinary file no named pattern claims, which the fallback measures.
    fs::write(
        project.path().join("god/plain.js"),
        "export function plain(value) {\n  if (value) {\n    return 2;\n  }\n  return 0;\n}\n",
    )
    .unwrap();
    // One file whose recovery lands inside the function it measures, so its
    // findings are advisory: they cannot move the verdict and their card is
    // detail rather than default.
    fs::write(
        project.path().join("god/recovered.js"),
        "export function recovered(value) {\n  if (value > 1) {\n    if (value > 2) {\n      if (value > 3) {\n        return 1;\n      }\n    }\n  }\n  return 0 unterminated(;\n}\n\n// The break above sits inside the measured function.\n",
    )
    .unwrap();
    // One file whose only debt is its length, so its card heads on its size
    // finding rather than on a claimed source finding.
    let mut long = (0..40)
        .map(|line| format!("// a long file states its length and nothing else, line {line}\n"))
        .collect::<String>();
    long.push_str("export const length = 1;\n");
    fs::write(project.path().join("god/long.js"), long).unwrap();
    let churn = |version: u32| {
        format!(
            "export function churn(value) {{\n  if (value > {version}) {{\n    if (value > 2) {{\n      if (value > 3) {{\n        return {version};\n      }}\n    }}\n  }}\n  return 0;\n}}\n"
        )
    };
    fs::write(project.path().join("hot/hot.js"), churn(1)).unwrap();
    // Two files no grammar reads, so the grouped sentence that names them
    // states a plural subject with a plural verb and a plural object.
    for name in ["first", "second"] {
        fs::write(
            project.path().join(format!("hub/{name}.swift")),
            format!("// Swift\n\nfunc {name}() -> Int {{ return 1 }}\n"),
        )
        .unwrap();
    }
    commit_as(
        project.path(),
        "Pattern Test",
        "pattern@example.invalid",
        "initial",
    );
    // Every later commit touches one package only, so nothing couples and one
    // author owns that package's whole history.
    for version in 2..=11 {
        fs::write(project.path().join("hot/hot.js"), churn(version)).unwrap();
        commit_as(
            project.path(),
            "Pattern Test",
            "pattern@example.invalid",
            &format!("churn {version}"),
        );
    }
    // Three commits of its own make the widely imported file a hotspot without
    // coupling its package to another or concentrating its history, which
    // needs ten commits.
    for version in 1..=3 {
        fs::write(project.path().join("hub/hub.js"), pick(version)).unwrap();
        commit_as(
            project.path(),
            "Pattern Test",
            "pattern@example.invalid",
            &format!("pick {version}"),
        );
    }
    project
}

fn history_strength_order_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    for package in ["a", "b", "c", "d", "e"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
        fs::write(
            project.path().join(package).join("main.js"),
            format!("export const {package} = 0;\n"),
        )
        .unwrap();
    }
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "initial",
    );
    for (left, right, commits) in [("a", "b", 3), ("b", "c", 6), ("c", "d", 4), ("d", "e", 3)] {
        for version in 1..=commits {
            for package in [left, right] {
                fs::write(
                    project.path().join(package).join("main.js"),
                    format!("export const {package} = '{left}-{right}-{version}';\n"),
                )
                .unwrap();
            }
            commit_as(
                project.path(),
                "History Test",
                "history@example.invalid",
                &format!("{left} {right} {version}"),
            );
        }
    }
    project
}

fn contextual_history_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    for package in ["a", "b", "c"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
        fs::write(
            project.path().join(package).join("main.js"),
            format!("export const {package} = 1;\n"),
        )
        .unwrap();
    }
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[source_roles]\nfixture = ['b/main.js']\ngenerated = ['c/main.js']\n",
    )
    .unwrap();
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "initial",
    );
    for version in 2..=3 {
        for package in ["a", "b", "c"] {
            fs::write(
                project.path().join(package).join("main.js"),
                format!("export const {package} = {version};\n"),
            )
            .unwrap();
        }
        commit_as(
            project.path(),
            "History Test",
            "history@example.invalid",
            &format!("version {version}"),
        );
    }
    project
}

fn generated_heavy_history_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    for package in ["a", "b"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
        fs::write(
            project.path().join(package).join("main.js"),
            format!("export const {package} = 1;\n"),
        )
        .unwrap();
        fs::write(
            project.path().join(package).join("generated.js"),
            format!("export const generated_{package} = 1;\n"),
        )
        .unwrap();
    }
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[source_roles]\ngenerated = ['a/generated.js', 'b/generated.js']\n",
    )
    .unwrap();
    commit_as(
        project.path(),
        "Eligible History",
        "eligible@example.invalid",
        "initial eligible and context",
    );
    for version in 2..=3 {
        for package in ["a", "b"] {
            fs::write(
                project.path().join(package).join("main.js"),
                format!("export const {package} = {version};\n"),
            )
            .unwrap();
        }
        commit_as(
            project.path(),
            "Eligible History",
            "eligible@example.invalid",
            &format!("eligible {version}"),
        );
    }
    for version in 2..=8 {
        for package in ["a", "b"] {
            fs::write(
                project.path().join(package).join("generated.js"),
                format!("export const generated_{package} = {version};\n"),
            )
            .unwrap();
        }
        commit_as(
            project.path(),
            &format!("Generated {version}"),
            &format!("generated-{version}@example.invalid"),
            &format!("generated {version}"),
        );
    }
    project
}

fn generated_only_history_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    for package in ["a", "b"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
        fs::write(
            project.path().join(package).join("generated.js"),
            format!("export const generated_{package} = 1;\n"),
        )
        .unwrap();
    }
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[source_roles]\ngenerated = ['a/generated.js', 'b/generated.js']\n",
    )
    .unwrap();
    commit_as(
        project.path(),
        "Generated History",
        "generated@example.invalid",
        "generated one",
    );
    for version in 2..=3 {
        for package in ["a", "b"] {
            fs::write(
                project.path().join(package).join("generated.js"),
                format!("export const generated_{package} = {version};\n"),
            )
            .unwrap();
        }
        commit_as(
            project.path(),
            "Generated History",
            "generated@example.invalid",
            &format!("generated {version}"),
        );
    }
    project
}

fn eligible_role_history_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    fs::create_dir_all(project.path().join("a")).unwrap();
    fs::write(project.path().join("a/package.json"), "{}\n").unwrap();
    fs::write(project.path().join("a/main.js"), "export const main = 1;\n").unwrap();
    fs::write(project.path().join("a/test.js"), "export const test = 1;\n").unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[source_roles]\ntest = ['a/test.js']\n",
    )
    .unwrap();
    commit_as(
        project.path(),
        "Role History",
        "roles@example.invalid",
        "roles one",
    );
    fs::write(project.path().join("a/main.js"), "export const main = 2;\n").unwrap();
    fs::write(project.path().join("a/test.js"), "export const test = 2;\n").unwrap();
    commit_as(
        project.path(),
        "Role History",
        "roles@example.invalid",
        "roles two",
    );
    project
}

fn weak_history_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    git(project.path(), ["init", "-b", "main"]);
    for package in ["a", "b"] {
        fs::create_dir_all(project.path().join(package)).unwrap();
        fs::write(project.path().join(package).join("package.json"), "{}\n").unwrap();
        fs::write(
            project.path().join(package).join("main.js"),
            format!("export const {package} = 1;\n"),
        )
        .unwrap();
    }
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "together one",
    );
    for package in ["a", "b"] {
        fs::write(
            project.path().join(package).join("main.js"),
            format!("export const {package} = 2;\n"),
        )
        .unwrap();
    }
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "together two",
    );
    fs::write(project.path().join("a/main.js"), "export const a = 3;\n").unwrap();
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "a only",
    );
    fs::write(project.path().join("b/main.js"), "export const b = 3;\n").unwrap();
    commit_as(
        project.path(),
        "History Test",
        "history@example.invalid",
        "b only",
    );
    project
}

fn commit_as(directory: &Path, name: &str, email: &str, message: &str) {
    git(directory, ["add", "-A"]);
    let mut command = Command::new("git");
    hermetic_env(&mut command);
    let status = command
        .args([
            "-c",
            &format!("user.name={name}"),
            "-c",
            &format!("user.email={email}"),
            "commit",
            "-qm",
            message,
        ])
        .env("GIT_AUTHOR_DATE", "2026-08-01T12:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-08-01T12:00:00Z")
        .current_dir(directory)
        .status()
        .unwrap();
    assert!(status.success());
}

/// Commit with the landed (committer) and authored dates pinned to `date`, or
/// to the wall clock when no date is given, so window fixtures control the
/// instant history filters compare.
fn commit_landed(directory: &Path, date: Option<&str>, message: &str) {
    git(directory, ["add", "-A"]);
    let mut command = Command::new("git");
    hermetic_env(&mut command);
    command
        .args([
            "-c",
            "user.name=History Test",
            "-c",
            "user.email=history@example.invalid",
            "commit",
            "-qm",
            message,
        ])
        .current_dir(directory);
    if let Some(date) = date {
        command
            .env("GIT_AUTHOR_DATE", date)
            .env("GIT_COMMITTER_DATE", date);
    }
    let status = command.status().unwrap();
    assert!(status.success());
}

fn fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::create_dir(project.path().join("src")).unwrap();
    fs::write(
        project.path().join("Gemfile"),
        "source 'https://example.invalid'\n",
    )
    .unwrap();
    fs::write(
        project.path().join("src/work.rb"),
        "def work(items)\n  items.each { |item| ship(item) if item.ready? }\nend\n",
    )
    .unwrap();
    fs::write(
        project.path().join("src/view.vue"),
        "<template><ul><li v-for=\"item in items\" v-if=\"item.ready\">{{ item.name }}</li></ul></template>\n<script setup lang=\"ts\">\nconst ready = (item) => item.ready\n</script>\n<style>.ready { color: green; }</style>\n",
    )
    .unwrap();
    project
}

/// A repository whose worktree deletes one rated unit and writes another, so a
/// diff carries exactly one added and one removed comparison.
fn one_sided_diff_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("package.json"),
        "{\"name\":\"one-sided\",\"private\":true}\n",
    )
    .unwrap();
    fs::write(
        project.path().join(".smackdebt.toml"),
        "[thresholds.cognitive]\nwatch = 2\nhigh = 5\n\n[thresholds.cyclomatic]\nwatch = 2\nhigh = 5\n\n[thresholds.function_lines]\nwatch = 2\nhigh = 5\n",
    )
    .unwrap();
    fs::create_dir(project.path().join("src")).unwrap();
    fs::write(
        project.path().join("src/gone.js"),
        "export function gone(value, other) {\n  if (value) {\n    if (other) {\n      return value + other;\n    }\n  }\n  return 0;\n}\n",
    )
    .unwrap();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: one rated unit"]);
    fs::remove_file(project.path().join("src/gone.js")).unwrap();
    fs::write(
        project.path().join("src/fresh.js"),
        "export function fresh(value) {\n  if (value) {\n    if (value > 1) {\n      return value;\n    }\n  }\n  return 0;\n}\n",
    )
    .unwrap();
    project
}

fn anonymous_diff_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("package.json"),
        "{\"name\":\"anonymous-diff\",\"private\":true}\n",
    )
    .unwrap();
    fs::write(
        project.path().join("callbacks.js"),
        "watch('ready', () => work());\nrepeat(() => same());\ngone(() => old());\nold_only(() => retired());\nold_only(() => retired());\nconst steady = () => keep();\n",
    )
    .unwrap();
    for index in 0..100 {
        fs::write(
            project.path().join(format!("stable-{index}.js")),
            format!("export function stable{index}() {{ return {index}; }}\n"),
        )
        .unwrap();
    }
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: anonymous base"]);
    fs::write(
        project.path().join("callbacks.js"),
        "\nwatch('ready', () => { if (ready) work(); });\nrepeat(() => same());\nrepeat(() => same());\nonly(() => new_one());\nonly(() => new_one());\n\nconst steady = () => keep();\n",
    )
    .unwrap();
    project
}

/// A Grape resource whose one edited endpoint sits inside three enclosing
/// blocks, none of which declares a name.
fn ruby_dsl_diff_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("api.rb"),
        "class Api < Grape::API\n  resource :sessions do\n    desc \"Session auth\"\n    params do\n      requires :token, type: String\n    end\n    get do\n      session = Session.find_by(id: params[:id])\n      present session\n    end\n  end\nend\n",
    )
    .unwrap();
    commit_fixture(project.path(), "test: grape base");
    fs::write(
        project.path().join("api.rb"),
        "class Api < Grape::API\n  resource :sessions do\n    desc \"Session auth\"\n    params do\n      requires :token, type: String\n    end\n    get do\n      session = access.sessions.find_by(id: params[:id])\n      present session if session\n    end\n  end\nend\n",
    )
    .unwrap();
    project
}

/// One rated closure inside an array literal, which binds to no name and hangs
/// under no call. `watch` comes from four levels of nesting.
fn unpairable_handler(call: &str) -> String {
    format!("() => {{ if (a) {{ if (b) {{ if (c) {{ if (d) {{ {call}(); }} }} }} }} }}")
}

/// The one closure is rewritten so that no evidence pairs the two versions.
fn unpairable_anonymous_fixture() -> tempfile::TempDir {
    let project = unpairable_project(&unpairable_handler("work"));
    fs::write(
        project.path().join("handlers.js"),
        format!(
            "export const handlers = [{}];\n",
            unpairable_handler("rework")
        ),
    )
    .unwrap();
    project
}

/// The same rewrite, beside a second closure that is genuinely new.
fn unpairable_beside_a_new_unit_fixture() -> tempfile::TempDir {
    let project = unpairable_project(&unpairable_handler("work"));
    fs::write(
        project.path().join("handlers.js"),
        format!(
            "export const handlers = [{}, {}];\n",
            unpairable_handler("rework"),
            unpairable_handler("audit")
        ),
    )
    .unwrap();
    project
}

fn unpairable_project(handler: &str) -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("package.json"),
        "{\"name\":\"unpairable\",\"private\":true}\n",
    )
    .unwrap();
    fs::write(
        project.path().join("handlers.js"),
        format!("export const handlers = [{handler}];\n"),
    )
    .unwrap();
    commit_fixture(project.path(), "test: unpairable base");
    project
}

fn commit_fixture(path: &Path, message: &str) {
    git(path, ["init", "-b", "main"]);
    git(path, ["config", "user.name", "Smackdebt Test"]);
    git(path, ["config", "user.email", "smackdebt@example.invalid"]);
    git(path, ["add", "."]);
    git(path, ["commit", "-m", message]);
}

fn named_duplicate_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("duplicate.js"),
        "function same() { return 1; }\nfunction same() { return 2; }\n",
    )
    .unwrap();
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: duplicate names"]);
    fs::write(
        project.path().join("duplicate.js"),
        "function same() { return 1; }\nfunction same() { if (ready) return 2; }\n",
    )
    .unwrap();
    project
}

/// A repository whose debt lives in one area, so a selected clean area and the
/// repository answer differently.
fn split_debt_fixture() -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("Gemfile"),
        "source 'https://example.invalid'\n",
    )
    .unwrap();
    fs::create_dir(project.path().join("clean")).unwrap();
    fs::create_dir(project.path().join("messy")).unwrap();
    fs::write(
        project.path().join("clean/ship.rb"),
        "def ship(item)\n  item.ship\nend\n",
    )
    .unwrap();
    fs::write(
        project.path().join("clean/ready.rb"),
        "def ready?(item)\n  item.ready\nend\n",
    )
    .unwrap();
    for index in 0..4 {
        fs::write(
            project.path().join(format!("messy/tangle{index}.rb")),
            tangled_source(index),
        )
        .unwrap();
    }
    // A repository root is what makes a path selection a drill-down into one
    // report rather than a separate walk of a smaller tree.
    git(project.path(), ["init", "-b", "main"]);
    git(project.path(), ["config", "user.name", "Smackdebt Test"]);
    git(
        project.path(),
        ["config", "user.email", "smackdebt@example.invalid"],
    );
    git(project.path(), ["add", "."]);
    git(project.path(), ["commit", "-m", "test: split debt"]);
    project
}

/// A repository whose report outgrows one buffered write, so a reader that
/// stops reading has already left before the last write happens.
fn tangled_fixture(files: usize) -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("Gemfile"),
        "source 'https://example.invalid'\n",
    )
    .unwrap();
    fs::create_dir(project.path().join("src")).unwrap();
    for index in 0..files {
        fs::write(
            project.path().join(format!("src/tangle{index}.rb")),
            tangled_source(index),
        )
        .unwrap();
    }
    project
}

/// One deeply nested Ruby function, which every rated measurement objects to.
fn tangled_source(index: usize) -> String {
    let mut source = format!("def tangle{index}(items)\n");
    for depth in 0..8 {
        source.push_str(&"  ".repeat(depth + 1));
        source.push_str(&format!("if items[{depth}] && items[{depth}].ready?\n"));
    }
    source.push_str(&"  ".repeat(9));
    source.push_str("ship(items)\n");
    for depth in (0..8).rev() {
        source.push_str(&"  ".repeat(depth + 1));
        source.push_str("end\n");
    }
    source.push_str("end\n");
    source
}

fn mixed_fixture(files: usize) -> tempfile::TempDir {
    let project = tempfile::tempdir().unwrap();
    fs::write(
        project.path().join("Gemfile"),
        "source 'https://example.invalid'\n",
    )
    .unwrap();
    let samples = [
        ("rs", "fn work(value: bool) { if value { work(false); } }\n"),
        ("rb", "def work(value)\n  return 1 if value\n  0\nend\n"),
        (
            "js",
            "function work(value) { if (value) return 1; return 0; }\n",
        ),
        (
            "py",
            "def work(value):\n    if value:\n        return 1\n    return 0\n",
        ),
        (
            "java",
            "class Work { int work(boolean value) { if (value) return 1; return 0; } }\n",
        ),
        (
            "c",
            "int work(int value) { if (value) return 1; return 0; }\n",
        ),
        (
            "cpp",
            "int work(bool value) { if (value) return 1; return 0; }\n",
        ),
        (
            "ts",
            "function work(value: boolean): number { if (value) return 1; return 0; }\n",
        ),
        (
            "tsx",
            "function Work({ value }: { value: boolean }) { return value ? <b /> : <i />; }\n",
        ),
        (
            "vue",
            "<template><b v-if=\"value\">yes</b></template>\n<script setup>const value = true</script>\n",
        ),
    ];
    for index in 0..files {
        let (extension, source) = samples[index % samples.len()];
        fs::write(
            project
                .path()
                .join(format!("source-{index:03}.{extension}")),
            source,
        )
        .unwrap();
    }
    project
}