autumn-cli 0.8.0

CLI tool for the Autumn web framework
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
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
//! The rules: what counts as *widening* an app's security surface.
//!
//! Every finding is derived from two manifests, never from source. A route is
//! identified by `(path, method)`; anything cosmetic — the handler's name, the
//! file and line it lives on, the module it was moved into — is invisible here
//! by construction, because a refactor that flags the security gate is a gate
//! nobody keeps.
//!
//! Two rules hold everywhere below, and both are load-bearing:
//!
//! 1. **Every dimension is compared from both sides.** A fact that *disappears*
//!    from the head manifest is a fact that was lost. Walking only the head
//!    would miss it — and the manifest drops entries as well as changing them:
//!    adding `POST` to `security.csrf.safe_methods` turns CSRF validation off
//!    for every POST *and* deletes those routes from the csrf dimension.
//! 2. **Each finding carries a [`Finding::fingerprint`]**: the security-relevant
//!    delta, escaped, and the only field besides kind/method/path that reaches
//!    the acknowledgment digest. Human-facing `before`/`after` text stays out of
//!    it, so a later *narrowing* on an already-acknowledged route does not
//!    invalidate the acknowledgment, and no crafted route path can make one
//!    finding hash like two.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use super::model::{
    CAPTURE, CATCH_ALL, PostureManifest, RouteEntry, RouteKey, escape_field, escape_list,
    hex_digest, is_open, normalize_captures,
};

/// Which way a change moves the security surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// More reachable than before. Blocks until acknowledged.
    Widening,
    /// Changed, but not provably in either direction. Annotates only.
    Neutral,
    /// Less reachable than before. Annotates only.
    Narrowing,
}

impl Severity {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Widening => "widening",
            Self::Neutral => "neutral",
            Self::Narrowing => "narrowing",
        }
    }
}

/// One posture change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    /// Stable machine tag, e.g. `route_added_open`. Part of the acknowledgment
    /// digest, so renaming one invalidates existing acknowledgments — treat it
    /// as a wire format.
    pub kind: &'static str,
    pub severity: Severity,
    /// HTTP method, or `*` for a finding that is not about one route.
    pub method: String,
    /// Route path, header name, or `*`.
    pub path: String,
    /// Posture before, in the base manifest. Human-facing.
    pub before: String,
    /// Posture after, in the head manifest. Human-facing.
    pub after: String,
    /// The security-relevant delta this finding *is*, in a form that changes
    /// exactly when its security meaning changes: `class:gated->public`,
    /// `roles+editor`, `scopes-admin`. Part of the acknowledgment digest.
    pub fingerprint: String,
    /// One sentence naming what actually moved.
    pub detail: String,
}

impl Finding {
    /// The canonical line this finding contributes to the acknowledgment digest.
    ///
    /// Every field is escaped before being joined, so a route path containing a
    /// tab or a newline cannot forge extra fields or extra lines. Without that,
    /// one crafted route hashes identically to a set of ordinary ones — and an
    /// acknowledgment for the crafted set silently covers the ordinary ones.
    #[must_use]
    pub fn canonical(&self) -> String {
        format!(
            "{}\t{}\t{}\t{}",
            self.kind,
            escape_field(&self.method),
            // Normalized, like the routes and the manifest digest: a capture
            // rename is not a posture change, so it must not re-block a
            // widening a reviewer has already approved. The report still shows
            // the path as the author wrote it.
            escape_field(&normalize_captures(&self.path)),
            escape_field(&self.fingerprint)
        )
    }
}

/// Compare two manifests, newest posture last.
///
/// Findings come back in a stable order — widening first (that is what a
/// reviewer must read), then neutral, then narrowing, each sorted by path and
/// method — so the report and the acknowledgment digest are deterministic.
#[must_use]
pub fn diff(base: &PostureManifest, head: &PostureManifest) -> Vec<Finding> {
    let mut findings = Vec::new();
    diff_routes(base, head, &mut findings);
    diff_authorization_policies(base, head, &mut findings);
    diff_csrf(base, head, &mut findings);
    diff_headers(base, head, &mut findings);
    diff_mtls(base, head, &mut findings);
    bind_to_effective_posture(&mut findings, base, head);
    findings.sort_by(|a, b| {
        a.severity
            .cmp(&b.severity)
            .then_with(|| a.path.cmp(&b.path))
            .then_with(|| a.method.cmp(&b.method))
            .then_with(|| a.kind.cmp(b.kind))
            .then_with(|| a.fingerprint.cmp(&b.fingerprint))
    });
    findings
}

/// Fold the route's whole posture at head into every widening's identity.
///
/// A widening is not "the dimension that moved" — it is the state a reviewer
/// approved. Fingerprinting only the moved dimension let *any other* dimension
/// be loosened afterwards without disturbing the digest: roles widened behind a
/// new scope, then the scope dropped; a scope removed while roles narrowed,
/// then the roles restored; a new public route with CSRF, then without it. In
/// each the base-to-head diff still holds only the original finding.
///
/// Done here, once, rather than in each emitter. Six dimensions learned this
/// rule one review round at a time, and every one of those fixes was me
/// remembering a dimension rather than the code making it impossible to forget.
/// A finding kind added later is covered without anyone remembering anything.
fn bind_to_effective_posture(
    findings: &mut [Finding],
    base: &PostureManifest,
    head: &PostureManifest,
) {
    let routes = route_index(head);
    let csrf = csrf_index(head);
    let bindings = authz_index(head);
    let mtls = mtls_index(head);
    let base_keys = route_keys(base);
    let head_keys = route_keys(head);

    for finding in findings
        .iter_mut()
        .filter(|f| f.severity == Severity::Widening)
    {
        let key = (normalize_captures(&finding.path), finding.method.clone());
        let posture = match effective_posture(&key, &routes, &csrf, &bindings, &mtls) {
            Some(own) => own,
            // The route the finding names is gone at head. Its URLs went
            // somewhere, and *that* is what the reviewer is approving — so bind
            // to the routes answering them now. Without this the one case where
            // the whole posture moved wholesale was the one case it bound
            // nothing, and the replacement could shed a scope afterwards with
            // the finding's identity unmoved.
            None if base_keys.contains(&key) => {
                let mut inherited: Vec<String> = takers((&key.0, &key.1), &base_keys, &head_keys)
                    .iter()
                    .filter_map(|taker| {
                        effective_posture(taker, &routes, &csrf, &bindings, &mtls).map(|posture| {
                            escape_list(&[taker.1.clone(), taker.0.clone(), posture])
                        })
                    })
                    .collect();
                inherited.sort();
                // Nothing took the URLs: they 404 now, and there is no posture
                // to bind to. Left empty rather than folding in a constant, so
                // a plain deletion keeps the identity it had.
                if inherited.is_empty() {
                    String::new()
                } else {
                    escape_list(&inherited)
                }
            }
            // Findings that name no single route — a collapsed csrf finding, a
            // header, an exemption prefix — miss every lookup and keep the
            // identity they built for themselves.
            None => String::new(),
        };
        if !posture.is_empty() {
            finding.fingerprint = escape_list(&[finding.fingerprint.clone(), posture]);
        }
    }
}

/// One route's whole posture at head: its guards, its CSRF state, its checks.
///
/// `None` when the manifest does not mount the route, which is the caller's cue
/// that the question has to be asked of whatever inherited its URLs.
fn effective_posture(
    key: &RouteKey,
    routes: &BTreeMap<RouteKey, RouteEntry>,
    csrf: &BTreeMap<RouteKey, (bool, bool, String)>,
    bindings: &BTreeMap<AuthzKey, String>,
    mtls: &BTreeSet<RouteKey>,
) -> Option<String> {
    let entry = routes.get(key)?;
    let enforced = csrf
        .get(key)
        .map_or(
            "absent",
            |(enforced, ..)| {
                if *enforced { "csrf" } else { "no-csrf" }
            },
        )
        .to_owned();
    let mut parts = vec![
        posture_fingerprint(entry),
        enforced,
        escape_list(&checks_at(key, bindings)),
    ];
    // Appended only when the route requires mTLS (#1640), so an app that uses
    // none fingerprints byte-for-byte as it did before this dimension existed
    // and its acknowledgments survive the schema bump. Where it IS required,
    // dropping the requirement after an acknowledgment moves the digest.
    if mtls.contains(key) {
        parts.push("mtls".to_owned());
    }
    Some(escape_list(&parts))
}

/// The routes that demand a verified client certificate, by `(path, method)`.
fn mtls_index(m: &PostureManifest) -> BTreeSet<RouteKey> {
    m.dimensions
        .mtls
        .entries
        .iter()
        .filter(|e| e.mtls_required)
        .map(super::model::MtlsEntry::key)
        .collect()
}

/// The postures of every route that inherits a URL set, as one ordered string.
///
/// Route identity is kept alongside each posture for the same reason
/// `checks_on` keeps it: a losing route carrying the same guards would
/// otherwise mask a change in the one that actually serves the URL.
fn postures_of(
    keys: &[RouteKey],
    routes: &BTreeMap<RouteKey, RouteEntry>,
    csrf: &BTreeMap<RouteKey, (bool, bool, String)>,
    bindings: &BTreeMap<AuthzKey, String>,
    mtls: &BTreeSet<RouteKey>,
) -> String {
    let mut each: Vec<String> = keys
        .iter()
        .filter_map(|key| {
            effective_posture(key, routes, csrf, bindings, mtls)
                .map(|posture| escape_list(&[key.1.clone(), key.0.clone(), posture]))
        })
        .collect();
    each.sort();
    escape_list(&each)
}

/// The `#[authorize]` checks one route performs, sorted and deduplicated.
fn checks_at(key: &RouteKey, bindings: &BTreeMap<AuthzKey, String>) -> Vec<String> {
    let mut checks: Vec<String> = bindings
        .keys()
        .filter(|(path, method, _, _)| (path, method) == (&key.0, &key.1))
        .map(|(_, _, action, resource)| format!("{action} on {resource}"))
        .collect();
    checks.sort();
    checks.dedup();
    checks
}

/// Only the findings that block.
#[must_use]
pub fn widening(findings: &[Finding]) -> Vec<&Finding> {
    findings
        .iter()
        .filter(|f| f.severity == Severity::Widening)
        .collect()
}

/// Index routes by `(path, method)`, **merging** duplicate keys into the widest
/// posture their entries jointly describe.
///
/// A manifest should never carry the same key twice, but "should never" is not
/// a guarantee about a file on disk, and letting either entry win makes the
/// verdict depend on array order — with the order that hides the wider entry
/// being the one that passes.
///
/// Picking a winner cannot work, because two postures can be *incomparable*:
/// `roles: ["admin"]` and `roles: ["editor"]` neither contains the other, so
/// any ranking of them is arbitrary and one of the two orders hides a newly
/// admitted role. Merging has no such gap: the union of the two is at least as
/// wide as either, so the diff can only ever over-report.
fn route_index(m: &PostureManifest) -> BTreeMap<RouteKey, RouteEntry> {
    let mut index: BTreeMap<RouteKey, RouteEntry> = BTreeMap::new();
    for entry in &m.dimensions.routes.entries {
        index
            .entry(entry.key())
            .and_modify(|existing| *existing = widest_of(existing, entry))
            .or_insert_with(|| entry.clone());
    }
    index
}

/// The posture that admits every caller either of these two does, dimension by
/// dimension, in the direction the framework's own semantics give it.
fn widest_of(a: &RouteEntry, b: &RouteEntry) -> RouteEntry {
    // Roles are OR-ed, so the union admits at least as many principals — and an
    // *empty* list is widest of all, since `#[secured]` with no roles admits
    // every authenticated session.
    let roles = if a.roles.is_empty() || b.roles.is_empty() {
        Vec::new()
    } else {
        a.role_set().union(&b.role_set()).cloned().collect()
    };
    // Scopes are AND-ed, so requiring only what both require admits at least as
    // many tokens.
    let scopes = a
        .scope_set()
        .intersection(&b.scope_set())
        .cloned()
        .collect();
    RouteEntry {
        path: a.path.clone(),
        method: a.method.clone(),
        classification: if is_open(&a.classification) {
            a.classification.clone()
        } else {
            b.classification.clone()
        },
        roles,
        scopes,
        // A record-level check only holds if every entry claims it.
        policy: a.policy && b.policy,
    }
}

fn diff_routes(base: &PostureManifest, head: &PostureManifest, out: &mut Vec<Finding>) {
    let before = route_index(base);
    let after = route_index(head);
    let (keys_before, keys_after) = (route_keys(base), route_keys(head));

    for (key, entry) in &after {
        let Some(previous) = before.get(key) else {
            let open = is_open(&entry.classification);
            out.push(Finding {
                kind: if open {
                    "route_added_open"
                } else {
                    "route_added_gated"
                },
                severity: if open {
                    Severity::Widening
                } else {
                    Severity::Neutral
                },
                method: entry.method.clone(),
                path: entry.path.clone(),
                before: "absent".to_owned(),
                after: entry.posture_label(),
                fingerprint: format!("added:{}", entry.classification),
                detail: if open {
                    format!(
                        "new route reachable without a proven guard ({})",
                        entry.posture_label()
                    )
                } else {
                    "new guarded route".to_owned()
                },
            });
            if !open {
                report_displacement(key, entry, &before, (&keys_before, &keys_after), out);
            }
            continue;
        };
        compare_route(previous, entry, out);
    }

    for (key, entry) in &before {
        if !after.contains_key(key) {
            out.push(Finding {
                kind: "route_removed",
                severity: Severity::Narrowing,
                method: entry.method.clone(),
                path: entry.path.clone(),
                before: entry.posture_label(),
                after: "absent".to_owned(),
                fingerprint: "removed".to_owned(),
                detail: "route no longer mounted".to_owned(),
            });
            report_shadow_exposure(key, entry, &after, (&keys_before, &keys_after), out);
        }
    }
    report_path_exposure(base, head, &before, &after, out);
}

/// A path is a node, not a set of routes.
///
/// Autumn groups every method at one path into a single `MethodRouter`, so
/// while any method is mounted there the path answers 405 for the rest.
/// Removing the *last* route at a path takes the node away, and those
/// previously-405 requests start reaching a less specific route. Filtering by
/// method intersection first skipped that: the removed `GET` and the surviving
/// `POST` share nothing, yet `POST` on that URL went from 405 to served.
///
/// Newly reachable through an *open* route is a widening, exactly as a new open
/// route is; newly reachable through a guarded one annotates, exactly as a new
/// guarded route does.
fn report_path_exposure(
    base: &PostureManifest,
    head: &PostureManifest,
    before: &BTreeMap<RouteKey, RouteEntry>,
    after: &BTreeMap<RouteKey, RouteEntry>,
    out: &mut Vec<Finding>,
) {
    let keys_before = route_keys(base);
    let keys_after = route_keys(head);
    let paths_after: BTreeSet<&String> = keys_after.iter().map(|(path, _)| path).collect();

    // Every path the head no longer mounts at all, and the methods it answered.
    let mut vanished: BTreeMap<&String, BTreeSet<String>> = BTreeMap::new();
    for (path, method) in &keys_before {
        if !paths_after.contains(path) {
            vanished
                .entry(path)
                .or_default()
                .extend(answered_methods(method, path, &keys_before));
        }
    }

    for (path, served) in vanished {
        let candidates: Vec<&RouteKey> = keys_after
            .iter()
            .filter(|(p, _)| takes_precedence(path, p))
            .collect();
        for key in undominated(path, &candidates) {
            let Some(survivor) = after.get(key) else {
                continue;
            };
            let open = is_open(&survivor.classification);
            let (survivor_path, survivor_method) = key;
            let newly: Vec<String> = answered_methods(survivor_method, survivor_path, &keys_after)
                .difference(&served)
                .cloned()
                .collect();
            if newly.is_empty() {
                continue;
            }
            let written = before
                .iter()
                .find(|((p, _), _)| p == path)
                .map_or_else(|| path.clone(), |(_, entry)| entry.path.clone());
            out.push(Finding {
                kind: "route_path_exposed",
                // Newly reachable through an open route blocks, exactly as a
                // new open route does; through a guarded one it annotates,
                // exactly as a new guarded route does.
                severity: if open {
                    Severity::Widening
                } else {
                    Severity::Neutral
                },
                method: newly.join(", "),
                path: written.clone(),
                before: "405 (no handler at this path)".to_owned(),
                after: survivor.posture_label(),
                fingerprint: format!(
                    "path-exposed:{}",
                    escape_list(&[
                        escape_list(&newly),
                        survivor.method.clone(),
                        survivor.path.clone(),
                        posture_fingerprint(survivor),
                    ])
                ),
                detail: format!(
                    "nothing is mounted at this path any more, so {} on it no longer stops at a \
                     405 — `{} {}` answers it now ({})",
                    newly.join(", "),
                    survivor.method,
                    survivor.path,
                    survivor.posture_label()
                ),
            });
        }
    }
}

/// Adding a route does not always add a URL.
///
/// The mirror of [`report_shadow_exposure`]: a new route that is *more
/// specific* than an existing one takes that route's requests over. A
/// `/users/me` restricted to `editor`, mounted beside a `/users/{id}`
/// restricted to `admin`, hands `/users/me` to editors — while the dynamic
/// entry sits unchanged in both manifests, so the addition read as a neutral
/// new guarded route and nothing blocked.
fn report_displacement(
    (path, method): &RouteKey,
    added: &RouteEntry,
    before: &BTreeMap<RouteKey, RouteEntry>,
    (keys_before, keys_after): (&BTreeSet<RouteKey>, &BTreeSet<RouteKey>),
    out: &mut Vec<Finding>,
) {
    // What the new route takes over is whatever *was* serving those URLs, asked
    // of the base with the same predicate a removal asks of the head.
    for key in takers((path, method), keys_after, keys_before) {
        let Some(displaced) = before.get(&key) else {
            continue;
        };
        // What changed for those URLs is the posture they used to demand
        // against the one they demand now — decided, as everywhere else here,
        // by `compare_route` rather than by a second opinion.
        let mut probe = Vec::new();
        compare_route(displaced, added, &mut probe);
        if !probe.iter().any(|f| f.severity == Severity::Widening) {
            continue;
        }
        out.push(Finding {
            kind: "route_added_shadowing",
            severity: Severity::Widening,
            method: method.clone(),
            path: added.path.clone(),
            before: displaced.posture_label(),
            after: added.posture_label(),
            // Both postures, so an acknowledgment binds to the change it was
            // written for and not merely to the pair of paths.
            fingerprint: format!(
                "added-shadowing:{}",
                escape_list(&[
                    displaced.method.clone(),
                    displaced.path.clone(),
                    posture_fingerprint(displaced),
                    posture_fingerprint(added),
                ])
            ),
            detail: format!(
                "this route is more specific than `{} {}`, so it takes those requests over and \
                 admits callers that one refused ({} → {})",
                displaced.method,
                displaced.path,
                displaced.posture_label(),
                added.posture_label()
            ),
        });
    }
}

/// Deleting a route does not always remove the URL.
///
/// The router matches a static segment before a dynamic one and mounts both —
/// `/users/me` beside `/users/{id}` is not a conflict, per the conflict matrix
/// in `router.rs`. So deleting the gated static route hands its URL to whatever
/// still covers it. Read as a plain removal that is a narrowing, and the guard
/// is gone with nothing to acknowledge.
fn report_shadow_exposure(
    (path, method): &RouteKey,
    removed: &RouteEntry,
    after: &BTreeMap<RouteKey, RouteEntry>,
    (keys_before, keys_after): (&BTreeSet<RouteKey>, &BTreeSet<RouteKey>),
    out: &mut Vec<Finding>,
) {
    for key in takers((path, method), keys_before, keys_after) {
        let Some(survivor) = after.get(&key) else {
            continue;
        };
        // Only a survivor that admits callers the deleted route refused is a
        // widening — and "admits more" is decided by the same comparison the
        // rest of this module uses, so the two cannot drift apart.
        let mut probe = Vec::new();
        compare_route(removed, survivor, &mut probe);
        if !probe.iter().any(|f| f.severity == Severity::Widening) {
            continue;
        }
        out.push(Finding {
            kind: "route_shadow_exposed",
            severity: Severity::Widening,
            method: method.clone(),
            path: removed.path.clone(),
            before: removed.posture_label(),
            after: survivor.posture_label(),
            // The survivor's *posture* is part of what a reviewer acknowledged,
            // not just its path. When the same pull request removes the guarded
            // route and adds the one that now covers it, the survivor is absent
            // from the base — so loosening it later is only a neutral
            // `route_added_gated`, and a fingerprint naming the path alone left
            // the digest unmoved and the old acknowledgment standing.
            fingerprint: format!(
                "shadow-exposed:{}",
                escape_list(&[
                    survivor.method.clone(),
                    survivor.path.clone(),
                    posture_fingerprint(survivor),
                ])
            ),
            detail: format!(
                "removing this route does not remove the URL: `{} {}` still matches it and \
                 admits callers this route refused ({} → {})",
                survivor.method,
                survivor.path,
                removed.posture_label(),
                survivor.posture_label()
            ),
        });
    }
}

/// A route's posture, encoded so an acknowledgment binds to exactly it.
///
/// Nested `escape_list`s rather than a joined string: role and scope names are
/// unrestricted string literals, so any separator picked here is one a name can
/// contain — the same ambiguity the manifest digest already had to close.
fn posture_fingerprint(entry: &RouteEntry) -> String {
    let roles: Vec<String> = entry.role_set().into_iter().collect();
    let scopes: Vec<String> = entry.scope_set().into_iter().collect();
    escape_list(&[
        entry.classification.clone(),
        escape_list(&roles),
        escape_list(&scopes),
        entry.policy.to_string(),
    ])
}

/// The HTTP methods a declared method actually answers at runtime.
///
/// A route's declared method is not the set of requests it takes: the router
/// mounts `WS` as a plain `GET` (`routes_audit`'s own `effective_mount_method`
/// does the same), and axum serves `HEAD` through a `#[get]` handler. So a
/// surviving `GET` route picks up the `HEAD` and `WS` traffic of a deleted one
/// at the same URL, and comparing declared methods exactly skipped precisely
/// those survivors.
fn effective_methods(method: &str) -> BTreeSet<String> {
    let declared = method.to_ascii_uppercase();
    let mut answered = BTreeSet::new();
    // Only a *genuine* `GET` is also served for `HEAD`. A websocket upgrade is
    // not, which the router states in exactly those terms — so the `HEAD` alias
    // is added before the `WS` fold, never after it.
    if declared == "GET" {
        answered.insert("HEAD".to_owned());
    }
    answered.insert(if declared == "WS" {
        "GET".to_owned()
    } else {
        declared
    });
    answered
}

/// The methods a route answers *in the manifest it belongs to*.
///
/// Every comparison goes through here rather than through the declared method:
/// there is no context-free "do these two methods overlap" left, because the
/// answer always depended on what else the manifest mounts.
///
/// The `GET`→`HEAD` expansion is a **fallback**, not a takeover: axum keeps an
/// explicit `HEAD` handler mounted at the same path, so a `GET` there answers
/// `GET` alone. Without that, a new guarded `GET` read as displacing an
/// explicit `HEAD` that goes on answering exactly as it did.
fn answered_methods(method: &str, path: &str, routes: &BTreeSet<RouteKey>) -> BTreeSet<String> {
    let mut answered = effective_methods(method);
    if !method.eq_ignore_ascii_case("HEAD")
        && routes.contains(&(path.to_owned(), "HEAD".to_owned()))
    {
        answered.remove("HEAD");
    }
    answered
}

/// The routes on the other side of the change that answer `subject`'s URLs.
///
/// Every "which route does this URL go to" question in this module is this one,
/// and each site that answered it privately needed the same three corrections
/// in turn: the path node has to be accounted for, the methods have to actually
/// transfer, and the candidates have to be ranked per URL. So there is one
/// answer now, and it is symmetric — a removal asks it of the head, an addition
/// asks it of the base, and the reasoning is identical in both directions.
fn takers(
    (path, method): (&str, &str),
    subject_keys: &BTreeSet<RouteKey>,
    other_keys: &BTreeSet<RouteKey>,
) -> Vec<RouteKey> {
    let answered = answered_methods(method, path, subject_keys);
    // Within one path node the request never leaves the node, so whichever
    // handler *there* answers the method takes it. That covers the route
    // itself, and it covers an explicit `HEAD` trading places with a `GET`'s
    // `HEAD` fallback — a transfer inside the node, which a bare "the node
    // exists" test read as no transfer at all.
    let same_path: Vec<RouteKey> = other_keys
        .iter()
        .filter(|(p, m)| p == path && !answered.is_disjoint(&answered_methods(m, p, other_keys)))
        .cloned()
        .collect();
    if !same_path.is_empty() {
        return same_path;
    }
    // A path node the other side mounts owns that URL for every method — it
    // answers 405 where it has no handler rather than letting the request fall
    // through — so nothing passes to another path.
    if other_keys.iter().any(|(p, _)| p == path) {
        return Vec::new();
    }
    // Rank the *nodes* first, then dispatch the method at the ones that win.
    // The router picks the most specific node and answers there — a node
    // without the method returns 405 rather than yielding to a less specific
    // one — so filtering by method before ranking dropped the node that answers
    // and blamed one that never sees the request.
    let candidates: Vec<&RouteKey> = other_keys
        .iter()
        .filter(|(p, _)| takes_precedence(path, p))
        .collect();
    undominated(path, &candidates)
        .into_iter()
        .filter(|(p, m)| !answered.is_disjoint(&answered_methods(m, p, other_keys)))
        .cloned()
        .collect()
}

/// Every `(normalized path, method)` a manifest mounts.
fn route_keys(m: &PostureManifest) -> BTreeSet<RouteKey> {
    m.dimensions
        .routes
        .entries
        .iter()
        .map(RouteEntry::key)
        .collect()
}

/// Among the routes that could take `subject`'s URLs, the ones that actually
/// receive some of them.
///
/// Precedence ranks the takers, but it ranks them *per URL*: outranking a
/// candidate somewhere is not the same as taking everything it would have got.
/// Removing `/records/me/{id}`, the guarded `/records/{user}/private` wins
/// `/records/me/private` and nothing else — every other `/records/me/*` still
/// goes to a public `/records/{user}/{id}`, which a pairwise test discarded.
///
/// So a candidate drops out only when another one outranks it *and* covers
/// every URL it would have taken. Routes sharing a path never outrank each
/// other: they are the same node.
fn undominated<'a>(subject: &str, takers: &[&'a RouteKey]) -> Vec<&'a RouteKey> {
    takers
        .iter()
        .filter(|(path, _)| {
            let Some(share) = intersect(subject, path) else {
                return false;
            };
            !takers.iter().any(|(other, _)| {
                other != path && takes_precedence(other, path) && covers(other, &share)
            })
        })
        .copied()
        .collect()
}

/// The pattern matching exactly the URLs both patterns match, if any.
fn intersect(a: &str, b: &str) -> Option<String> {
    let a: Vec<&str> = a.split('/').collect();
    let b: Vec<&str> = b.split('/').collect();
    let mut out: Vec<String> = Vec::new();
    for i in 0..a.len().max(b.len()) {
        match (a.get(i), b.get(i)) {
            // A catch-all takes the other pattern's remaining segments.
            (Some(x), Some(_)) if x.contains(CATCH_ALL) => {
                out.extend(b[i..].iter().map(|s| (*s).to_owned()));
                return Some(out.join("/"));
            }
            (Some(_), Some(y)) if y.contains(CATCH_ALL) => {
                out.extend(a[i..].iter().map(|s| (*s).to_owned()));
                return Some(out.join("/"));
            }
            (Some(x), Some(y)) if segments_overlap(x, y) => {
                // The more specific segment is what both match.
                let narrower = if specificity(x) <= specificity(y) {
                    x
                } else {
                    y
                };
                out.push((*narrower).to_owned());
            }
            _ => return None,
        }
    }
    Some(out.join("/"))
}

/// Whether every URL `target` matches is also matched by `pattern`.
fn covers(pattern: &str, target: &str) -> bool {
    let pattern: Vec<&str> = pattern.split('/').collect();
    let target: Vec<&str> = target.split('/').collect();
    for i in 0..pattern.len().max(target.len()) {
        match (pattern.get(i), target.get(i)) {
            (Some(p), Some(_)) if p.contains(CATCH_ALL) => return true,
            (Some(p), Some(t)) => {
                // A capture covers anything in its position; a literal covers
                // only the identical literal, and never a capture.
                if p.contains(CAPTURE) {
                    if !segments_overlap(p, t) {
                        return false;
                    }
                } else if p != t {
                    return false;
                }
            }
            _ => return false,
        }
    }
    true
}

/// Whether `first` overlaps `second` *and* wins the overlap at the router.
///
/// Overlap alone is never the question, because the router has a precedence
/// rule: a static segment beats a capture, which beats a catch-all, decided at
/// the first position where the two differ. Both directions of the shadow
/// analysis are this one predicate.
///
/// - **A removal**: `takes_precedence(removed, survivor)` asks whether the
///   deleted route was the one serving the overlap, so the survivor inherits
///   it. Deleting a gated `/users/{id}` beside a public `/users/me` exposes
///   nothing — that URL was already going to `/users/me`.
/// - **An addition**: `takes_precedence(added, displaced)` asks whether the new
///   route takes the overlap away from an existing one. A new `/users/me` wins
///   that URL from `/users/{id}` the moment it is mounted.
fn takes_precedence(first: &str, second: &str) -> bool {
    if !shapes_overlap(first, second) {
        return false;
    }
    let first: Vec<&str> = first.split('/').collect();
    let second: Vec<&str> = second.split('/').collect();
    for i in 0..first.len().max(second.len()) {
        // A path that has run out of segments is the less specific of the two:
        // only a catch-all can be matching in its place.
        let mine = first.get(i).map_or(u8::MAX, |s| specificity(s));
        let theirs = second.get(i).map_or(u8::MAX, |s| specificity(s));
        if mine != theirs {
            return mine < theirs;
        }
    }
    // Equally specific the whole way down. The router rejects such a pair as a
    // conflict, so the manifest is malformed — report rather than stay quiet.
    true
}

/// How specific a normalized path segment is, lowest first, in the router's own
/// order: a static segment beats a capture, which beats a catch-all.
fn specificity(segment: &str) -> u8 {
    if segment.contains(CATCH_ALL) {
        2
    } else {
        u8::from(segment.contains(CAPTURE))
    }
}

/// Whether two route *shapes* can match the same URL.
///
/// Both paths arrive normalized, so a capture is `CAPTURE` and a catch-all is
/// `CATCH_ALL`. Overlap, not equality, is the question: the router mounts a
/// static route beside a dynamic one that covers it, so removing the static one
/// is only safe if nothing wider is left underneath.
fn shapes_overlap(a: &str, b: &str) -> bool {
    let a: Vec<&str> = a.split('/').collect();
    let b: Vec<&str> = b.split('/').collect();
    for i in 0..a.len().max(b.len()) {
        match (a.get(i), b.get(i)) {
            (Some(x), Some(y)) => {
                // A catch-all swallows every remaining segment.
                if x.contains(CATCH_ALL) || y.contains(CATCH_ALL) {
                    return true;
                }
                if !segments_overlap(x, y) {
                    return false;
                }
            }
            // One path ran out: the other still demands a segment, and a
            // capture matches text, never nothing.
            _ => return false,
        }
    }
    true
}

/// Whether one path segment can match the same text as another.
fn segments_overlap(a: &str, b: &str) -> bool {
    if !a.contains(CAPTURE) && !b.contains(CAPTURE) {
        return a == b;
    }
    // A capture matches any non-empty text in its position, but the literal
    // text around it still has to line up — `/file.{ext}` covers `/file.json`
    // and not `/other.json`.
    let (a_prefix, a_suffix) = literal_edges(a);
    let (b_prefix, b_suffix) = literal_edges(b);
    if !(a_prefix.starts_with(b_prefix) || b_prefix.starts_with(a_prefix)) {
        return false;
    }
    if !(a_suffix.ends_with(b_suffix) || b_suffix.ends_with(a_suffix)) {
        return false;
    }
    // A capture must consume at least one character — matchit 404s otherwise —
    // so a segment with L literal characters and n captures only matches text
    // of length >= L + n. A concrete segment shorter than the other's minimum
    // can share nothing with it: `/file.{ext}` never serves `/file.`, so the
    // old edge-only check invented a shadow there. The same comparison keeps
    // the two required edges from overlapping inside a concrete segment, since
    // L + n already covers both edge lengths. (#2499)
    if !a.contains(CAPTURE) && min_match_len(b) > a.chars().count() {
        return false;
    }
    if !b.contains(CAPTURE) && min_match_len(a) > b.chars().count() {
        return false;
    }
    true
}

/// The fewest characters a normalized segment can match.
///
/// Normalization collapses each capture to a single `CAPTURE` character, and
/// matchit requires every capture to consume at least one character — so the
/// minimum is the segment's own length: L literal characters plus n captures
/// match only text of length >= L + n. (Callers screen out catch-alls before
/// this predicate runs, so every character here is a literal or a capture.)
fn min_match_len(segment: &str) -> usize {
    segment.chars().count()
}

/// The literal text before the first capture and after the last one. A segment
/// with no capture is its own prefix and suffix.
fn literal_edges(segment: &str) -> (&str, &str) {
    match (segment.find(CAPTURE), segment.rfind(CAPTURE)) {
        (Some(first), Some(last)) => (&segment[..first], &segment[last + CAPTURE.len_utf8()..]),
        _ => (segment, segment),
    }
}

/// Compare one route that exists on both sides.
fn compare_route(before: &RouteEntry, after: &RouteEntry, out: &mut Vec<Finding>) {
    let label_before = before.posture_label();
    let label_after = after.posture_label();

    if before.classification != after.classification {
        let was_open = is_open(&before.classification);
        let now_open = is_open(&after.classification);
        let (kind, severity, detail) = match (was_open, now_open) {
            (false, true) => (
                "classification_downgraded",
                Severity::Widening,
                format!(
                    "guard removed: {} \u{2192} {}",
                    before.classification, after.classification
                ),
            ),
            (true, false) => (
                "classification_upgraded",
                Severity::Narrowing,
                format!(
                    "guard added: {} \u{2192} {}",
                    before.classification, after.classification
                ),
            ),
            _ => (
                "classification_changed",
                Severity::Neutral,
                format!(
                    "classification {} \u{2192} {}",
                    before.classification, after.classification
                ),
            ),
        };
        out.push(Finding {
            kind,
            severity,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.clone(),
            after: label_after.clone(),
            fingerprint: format!("class:{}->{}", before.classification, after.classification),
            detail,
        });
        // A route that stopped being gated has already been reported in the
        // strongest terms available; enumerating the roles it also lost would
        // add rows without adding information.
        if was_open != now_open {
            return;
        }
    }

    compare_roles(before, after, &label_before, &label_after, out);
    compare_scopes(before, after, &label_before, &label_after, out);

    if before.policy && !after.policy {
        out.push(Finding {
            kind: "policy_removed",
            severity: Severity::Widening,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before,
            after: label_after,
            // What still guards the route is part of what was acknowledged: a
            // constant identity let the record check go, then the scope that
            // replaced it, under one marker.
            fingerprint: format!("policy-removed:{}", posture_fingerprint(after)),
            detail: "record-level policy check removed".to_owned(),
        });
    } else if !before.policy && after.policy {
        out.push(Finding {
            kind: "policy_added",
            severity: Severity::Narrowing,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before,
            after: label_after,
            fingerprint: "policy-added".to_owned(),
            detail: "record-level policy check added".to_owned(),
        });
    }
}

/// Roles are OR-ed (`#[secured("a", "b")]` admits *either*), so **adding** one
/// admits more principals and **removing** one admits fewer — the opposite of
/// the intuition scopes create.
///
/// Two boundary cases run the other way, and both come from the same fact:
/// `#[secured]` with *no* roles admits every authenticated session. So emptying
/// a non-empty list is the widest move available, and putting the first role on
/// an empty list is a narrowing, not a widening.
fn compare_roles(
    before: &RouteEntry,
    after: &RouteEntry,
    label_before: &str,
    label_after: &str,
    out: &mut Vec<Finding>,
) {
    let was: BTreeSet<String> = before.role_set();
    let now: BTreeSet<String> = after.role_set();
    if was == now {
        return;
    }
    let added: Vec<String> = now.difference(&was).cloned().collect();
    let removed: Vec<String> = was.difference(&now).cloned().collect();

    if !was.is_empty() && now.is_empty() {
        out.push(Finding {
            kind: "roles_cleared",
            severity: Severity::Widening,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.to_owned(),
            after: label_after.to_owned(),
            fingerprint: format!("roles-cleared:{}", escape_list(&removed)),
            detail: format!(
                "role requirement dropped ({}) — any authenticated session now passes",
                removed.join(", ")
            ),
        });
        return;
    }
    if was.is_empty() {
        // The gate went from "any authenticated session" to "one of these
        // roles". Strictly fewer callers, however many roles were named.
        out.push(Finding {
            kind: "roles_narrowed",
            severity: Severity::Narrowing,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.to_owned(),
            after: label_after.to_owned(),
            fingerprint: format!("roles-first:{}", escape_list(&added)),
            detail: format!(
                "route now requires role{} {} — previously any authenticated session passed",
                plural(added.len()),
                added.join(", ")
            ),
        });
        return;
    }
    if !added.is_empty() {
        out.push(Finding {
            kind: "roles_widened",
            severity: Severity::Widening,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.to_owned(),
            after: label_after.to_owned(),
            fingerprint: format!("roles+{}", escape_list(&added)),
            detail: format!(
                "role{} {} now also admitted",
                plural(added.len()),
                added.join(", ")
            ),
        });
    }
    if !removed.is_empty() {
        out.push(Finding {
            kind: "roles_narrowed",
            severity: Severity::Narrowing,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.to_owned(),
            after: label_after.to_owned(),
            fingerprint: format!("roles-{}", escape_list(&removed)),
            detail: format!(
                "role{} {} no longer admitted",
                plural(removed.len()),
                removed.join(", ")
            ),
        });
    }
}

/// Scopes are AND-ed (`__check_secured_scopes` requires *all* of them), so
/// **removing** one lets more tokens through and **adding** one lets fewer.
fn compare_scopes(
    before: &RouteEntry,
    after: &RouteEntry,
    label_before: &str,
    label_after: &str,
    out: &mut Vec<Finding>,
) {
    let was: BTreeSet<String> = before.scope_set();
    let now: BTreeSet<String> = after.scope_set();
    if was == now {
        return;
    }
    let added: Vec<String> = now.difference(&was).cloned().collect();
    let removed: Vec<String> = was.difference(&now).cloned().collect();
    let now_sorted: Vec<String> = now.iter().cloned().collect();

    if !removed.is_empty() {
        out.push(Finding {
            kind: "scopes_widened",
            severity: Severity::Widening,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.to_owned(),
            after: label_after.to_owned(),
            // The scopes still required are part of what was acknowledged:
            // naming only the lost one let `{read}` → `{mfa}` → `{}` keep a
            // single identity, so the acknowledgment for the swap covered the
            // drop as well.
            fingerprint: format!(
                "scopes-{}",
                escape_list(&[escape_list(&removed), escape_list(&now_sorted)])
            ),
            detail: format!(
                "scope{} {} no longer required",
                plural(removed.len()),
                removed.join(", ")
            ),
        });
    }
    if !added.is_empty() {
        out.push(Finding {
            kind: "scopes_narrowed",
            severity: Severity::Narrowing,
            method: after.method.clone(),
            path: after.path.clone(),
            before: label_before.to_owned(),
            after: label_after.to_owned(),
            fingerprint: format!("scopes+{}", escape_list(&added)),
            detail: format!(
                "scope{} {} now required",
                plural(added.len()),
                added.join(", ")
            ),
        });
    }
}

const fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

/// `#[authorize("action", resource = Resource)]` bindings, keyed by route.
///
/// The path is normalized exactly as route identity is, so a renamed capture
/// does not put one untouched binding on both sides of the set difference —
/// which read as a removal, and blocked a pull request that changed nothing.
/// The path as the author wrote it is the value, for the finding's text.
type AuthzKey = (String, String, String, String);

fn authz_index(m: &PostureManifest) -> BTreeMap<AuthzKey, String> {
    m.dimensions
        .authorization_policies
        .entries
        .iter()
        .map(|e| {
            (
                (
                    normalize_captures(&e.path),
                    e.method.clone(),
                    e.action.clone(),
                    e.resource.clone(),
                ),
                e.path.clone(),
            )
        })
        .collect()
}

fn diff_authorization_policies(
    base: &PostureManifest,
    head: &PostureManifest,
    out: &mut Vec<Finding>,
) {
    let before = authz_index(base);
    let after = authz_index(head);
    let routes_before = route_keys(base);
    let routes_after = route_keys(head);

    // Bindings the same route *gained*, so a removal that is really half of a
    // rename can say so instead of reading as an unexplained loss.
    let gained_on: BTreeMap<RouteKey, Vec<String>> =
        after.keys().filter(|key| !before.contains_key(*key)).fold(
            BTreeMap::new(),
            |mut acc, (path, method, action, resource)| {
                acc.entry((path.clone(), method.clone()))
                    .or_default()
                    .push(format!("{action} on {resource}"));
                acc
            },
        );

    for (key, written_as) in &before {
        if after.contains_key(key) {
            continue;
        }
        let (path, method, action, resource) = key;
        // A binding that vanished because the whole route did is already
        // reported as `route_removed`, and that is a narrowing, not a widening
        // — but only when the URL went with it. A surviving route whose shape
        // and methods overlap still answers that URL, so the record-level check
        // really did disappear from something reachable.
        // Every route that answers this one's URLs after the change — none if
        // the path node is gone entirely, and none if it survives without this
        // method, since that is a 405 rather than a fall-through.
        let takers = takers((path, method), &routes_before, &routes_after);
        if takers.is_empty() {
            continue;
        }
        // ...unless the route that now answers it performs the very same
        // check, in which case nothing changed for that URL's callers. Both
        // routes being `gated` with a record-level check is not enough: the
        // route comparison cannot see *which* check, so `read_self` giving way
        // to `read_any` reads as no change at all up there.
        let fell_through = !routes_after.contains(&(path.clone(), method.clone()));
        // Preserved only if *every* taker performs the same check: one that
        // does not means some URL reaches a route without it. Asking whether
        // any taker carries it let a check survive on the route that loses.
        if fell_through
            && takers.iter().all(|(p, m)| {
                after.contains_key(&(p.clone(), m.clone(), action.clone(), resource.clone()))
            })
        {
            continue;
        }
        let mut detail =
            format!("record-level authorization `{action}` on `{resource}` no longer checked");
        if fell_through {
            detail.push_str(
                " (the route carrying it is gone, but the URL is not: another mounted route \
                 answers it now, without this check)",
            );
        }

        // A resource *rename* looks exactly like a removal plus an addition,
        // and nothing in the manifest can tell the two apart. Stay conservative
        // — this still blocks — but name the pairing so a reviewer who is
        // looking at a rename can acknowledge it in one step instead of
        // wondering what was lost.
        if let Some(gained) = gained_on.get(&(path.clone(), method.clone())) {
            let _ = write!(
                detail,
                " (the same route gained: {}; a renamed resource reads as a removal plus an \
                 addition, which a manifest cannot tell from a real one)",
                gained.join(", ")
            );
        }
        out.push(Finding {
            kind: "authorization_binding_removed",
            severity: Severity::Widening,
            method: method.clone(),
            path: written_as.clone(),
            before: format!("authorize({action}, {resource})"),
            after: "none".to_owned(),
            fingerprint: format!(
                "authz-removed:{}",
                escape_list(&[
                    action.clone(),
                    resource.clone(),
                    // Whatever checks these URLs now get, whether that is
                    // another route's after a fall-through or this route's own
                    // after a swap. Leaving the exact-route case out let
                    // `read_any` give way to `read_all` without moving the
                    // digest, so the acknowledgment for one stood for the
                    // other.
                    checks_on((path, method), &after, &routes_after, &routes_before),
                ])
            ),
            detail,
        });
    }
    report_displaced_bindings(base, head, &before, &after, out);
    for (key, written_as) in &after {
        if before.contains_key(key) {
            continue;
        }
        let (_, method, action, resource) = key;
        out.push(Finding {
            kind: "authorization_binding_added",
            severity: Severity::Narrowing,
            method: method.clone(),
            path: written_as.clone(),
            before: "none".to_owned(),
            after: format!("authorize({action}, {resource})"),
            fingerprint: format!(
                "authz-added:{}:{}",
                escape_field(action),
                escape_field(resource)
            ),
            detail: format!("record-level authorization `{action}` on `{resource}` now checked"),
        });
    }
}

/// Emit the routes that lost CSRF, collapsed into one finding or one each.
fn report_csrf_loss(
    lost: BTreeMap<RouteKey, (String, bool, Vec<RouteKey>)>,
    head_routes: &BTreeMap<RouteKey, RouteEntry>,
    head_csrf: &BTreeMap<RouteKey, (bool, bool, String)>,
    head_bindings: &BTreeMap<AuthzKey, String>,
    head_mtls: &BTreeSet<RouteKey>,
    collapse: bool,
    out: &mut Vec<Finding>,
) {
    if collapse {
        let routes: Vec<String> = lost
            .iter()
            .map(|((_, method), (written_as, ..))| format!("{method} {written_as}"))
            .collect();
        // The fingerprint names the *routes*, not the spellings: renaming a
        // capture changes neither the URL set that lost CSRF nor what a
        // reviewer acknowledged about it.
        // Each route *and what still guards it*, for the same reason the
        // per-route fingerprint carries it. The whole posture, not just the
        // `RouteEntry` half: this finding names `*`, so the pass that folds
        // head posture into every other widening skips it and a record check
        // swapped for a weaker one would be invisible behind `policy: true`.
        let guarded_keys: Vec<String> = lost
            .iter()
            .map(|((path, method), (_, _, inheritors))| {
                escape_list(&[
                    method.clone(),
                    path.clone(),
                    postures_of(inheritors, head_routes, head_csrf, head_bindings, head_mtls),
                ])
            })
            .collect();
        out.push(Finding {
            kind: "csrf_disabled",
            severity: Severity::Widening,
            method: "*".to_owned(),
            path: "*".to_owned(),
            before: "csrf enforced".to_owned(),
            after: format!("csrf not enforced on {} routes", routes.len()),
            // The collapsed finding must still say *which* routes lost it, or
            // an acknowledgment for one set would silently cover another.
            fingerprint: format!(
                "csrf-disabled:{}",
                &hex_digest(escape_list(&guarded_keys).as_bytes())[..16]
            ),
            detail: format!(
                "CSRF enforcement lost on all {} mutating routes: {}",
                routes.len(),
                routes.join(", ")
            ),
        });
    } else {
        for (key, (path, exempt, inheritors)) in lost {
            let guard = postures_of(
                &inheritors,
                head_routes,
                head_csrf,
                head_bindings,
                head_mtls,
            );
            let (_, method) = key;
            out.push(Finding {
                kind: "csrf_enforcement_removed",
                severity: Severity::Widening,
                method,
                path,
                before: "csrf enforced".to_owned(),
                after: "csrf not enforced".to_owned(),
                fingerprint: format!("csrf-removed:{guard}"),
                detail: if exempt {
                    "CSRF enforcement lost: this route now matches a configured exempt prefix"
                        .to_owned()
                } else {
                    "CSRF enforcement lost".to_owned()
                },
            });
        }
    }
}

/// Whether `prefix` exempts `path`, spelled exactly as the CSRF middleware
/// spells it — so "is this prefix already covered by that one" is asked in the
/// same terms the runtime will answer it in.
fn exempts(prefix: &str, path: &str) -> bool {
    if path == prefix {
        return true;
    }
    path.strip_prefix(prefix)
        .is_some_and(|rest| prefix.ends_with('/') || rest.starts_with('/'))
}

/// Whether any URL a route template matches falls under an exemption prefix.
///
/// The prefix is a concrete URL prefix and the template is a shape, so the
/// question is whether the two intersect — `/api/me` exempts `/api/{id}` for
/// exactly the request `/api/me`, which is the whole reason the per-route row
/// keeps saying "enforced" while those requests stop being validated. Either
/// the prefix names the route's own URLs or it sits above them, hence the
/// catch-all form.
fn exempts_shape(prefix: &str, template: &str) -> bool {
    let prefix = normalize_captures(prefix);
    intersect(template, &prefix).is_some()
        || intersect(template, &format!("{prefix}/{CATCH_ALL}")).is_some()
}

/// Configured exemption prefixes, which the per-route rows cannot show.
///
/// The audit asks whether a route *template* matches a prefix; the runtime asks
/// it of the concrete request path. Exempting `/users/me` therefore leaves
/// `POST /users/{id}` recorded as enforced while those requests stop being
/// validated — a widening with no row to carry it. Compared conservatively: any
/// prefix that was not there before can only exempt more URLs.
fn diff_csrf_exemptions(base: &PostureManifest, head: &PostureManifest, out: &mut Vec<Finding>) {
    let before: BTreeSet<&String> = base.dimensions.csrf.exempt_paths.iter().collect();
    let after: BTreeSet<&String> = head.dimensions.csrf.exempt_paths.iter().collect();

    // Coverage, not spelling. Replacing `/api` with `/api/private` exempts a
    // strict subset of what was exempt before, so calling the new prefix a
    // widening blocks a change that restores CSRF for most of `/api`.
    let added: Vec<String> = after
        .iter()
        .filter(|p| !before.iter().any(|old| exempts(old, p)))
        .map(|p| (*p).clone())
        .collect();
    let removed: Vec<String> = before
        .iter()
        .filter(|p| !after.iter().any(|new| exempts(new, p)))
        .map(|p| (*p).clone())
        .collect();

    if !added.is_empty() {
        // And what those URLs are still checked by. An exemption acknowledgment
        // says "I accept that these skip CSRF", which is a statement about the
        // rest of their posture — and no per-route row can show the exemption,
        // so loosening the routes it covers moves nothing else in the diff.
        let routes = route_index(head);
        let csrf = csrf_index(head);
        let bindings = authz_index(head);
        let mtls = mtls_index(head);
        let mut guards: Vec<String> = routes
            .keys()
            .filter(|(path, _)| added.iter().any(|prefix| exempts_shape(prefix, path)))
            .filter_map(|key| {
                effective_posture(key, &routes, &csrf, &bindings, &mtls)
                    .map(|posture| escape_list(&[key.1.clone(), key.0.clone(), posture]))
            })
            .collect();
        guards.sort();
        out.push(Finding {
            kind: "csrf_exemption_added",
            severity: Severity::Widening,
            method: "*".to_owned(),
            path: "*".to_owned(),
            before: "not exempt".to_owned(),
            after: added.join(", "),
            fingerprint: format!(
                "csrf-exempt-added:{}",
                escape_list(&[escape_list(&added), escape_list(&guards)])
            ),
            detail: format!(
                "CSRF validation is now skipped for {}, which the per-route rows cannot show: \
                 the audit matches a prefix against a route template, the runtime against the \
                 request path",
                added.join(", ")
            ),
        });
    }
    if !removed.is_empty() {
        out.push(Finding {
            kind: "csrf_exemption_removed",
            severity: Severity::Narrowing,
            method: "*".to_owned(),
            path: "*".to_owned(),
            before: removed.join(", "),
            after: "not exempt".to_owned(),
            fingerprint: format!("csrf-exempt-removed:{}", escape_list(&removed)),
            detail: format!(
                "CSRF validation is enforced again for {}",
                removed.join(", ")
            ),
        });
    }
}

/// The checks a manifest performs on the URLs a route answers, as one string.
///
/// What an acknowledgment of a fall-through or a displacement actually says is
/// "I accept that this URL is checked by *that* instead" — so weakening what it
/// is checked by has to invalidate it. The replacing route is absent from the
/// base, so its binding reads only as a neutral addition; without this in the
/// fingerprint the digest never moved.
fn checks_on(
    (path, method): (&str, &str),
    bindings: &BTreeMap<AuthzKey, String>,
    routes: &BTreeSet<RouteKey>,
    from_routes: &BTreeSet<RouteKey>,
) -> String {
    let mut per_route: Vec<String> = takers((path, method), from_routes, routes)
        .into_iter()
        .map(|(p, m)| {
            // Route identity is kept, not just the union of checks: a losing
            // route carrying the same names would otherwise mask a change in
            // the one that actually serves the URL.
            let mut checks: Vec<String> = bindings
                .keys()
                .filter(|(bp, bm, _, _)| *bp == p && *bm == m)
                .map(|(_, _, action, resource)| format!("{action} on {resource}"))
                .collect();
            checks.sort();
            checks.dedup();
            escape_list(&[m, p, escape_list(&checks)])
        })
        .collect();
    per_route.sort();
    escape_list(&per_route)
}

/// Bindings the URLs of a displaced route lose to a new, more specific one.
///
/// The mirror of the fall-through case, and just as invisible: a displacement
/// can change the record-level check while nothing the route comparison sees
/// has moved — same roles, both `policy: true` — and the binding dimension sees
/// only an *added* binding, which is a narrowing. The URLs `/records/me` took
/// over went from `read_self` to `read_any` all the same.
fn report_displaced_bindings(
    base: &PostureManifest,
    head: &PostureManifest,
    before: &BTreeMap<AuthzKey, String>,
    after: &BTreeMap<AuthzKey, String>,
    out: &mut Vec<Finding>,
) {
    let keys_before = route_keys(base);
    let keys_after = route_keys(head);
    let head_routes = route_index(head);
    let mut reported: BTreeSet<(RouteKey, String, String)> = BTreeSet::new();

    for added_key in keys_after.difference(&keys_before) {
        let (added_path, added_method) = added_key;
        for displaced_key in takers((added_path, added_method), &keys_after, &keys_before) {
            let (displaced_path, displaced_method) = &displaced_key;
            for ((path, method, action, resource), written_as) in before {
                if path != displaced_path || method != displaced_method {
                    continue;
                }
                // The new route performing the very same check changes nothing
                // for the URLs it took over.
                let carried = (
                    added_path.clone(),
                    added_method.clone(),
                    action.clone(),
                    resource.clone(),
                );
                if after.contains_key(&carried)
                    || !reported.insert((added_key.clone(), action.clone(), resource.clone()))
                {
                    continue;
                }
                let written_added = head_routes
                    .get(added_key)
                    .map_or_else(|| added_path.clone(), |r| r.path.clone());
                out.push(Finding {
                    kind: "authorization_binding_displaced",
                    severity: Severity::Widening,
                    method: added_method.clone(),
                    path: written_added.clone(),
                    before: format!("authorize({action}, {resource})"),
                    after: "none".to_owned(),
                    fingerprint: format!(
                        "authz-displaced:{}",
                        escape_list(&[
                            written_as.clone(),
                            displaced_method.clone(),
                            action.clone(),
                            resource.clone(),
                            checks_on((added_path, added_method), after, &keys_after, &keys_before),
                        ])
                    ),
                    detail: format!(
                        "this route is more specific than `{displaced_method} {written_as}`, so it \
                         takes those requests over — and it does not perform that route's \
                         record-level `{action}` check on `{resource}`"
                    ),
                });
            }
        }
    }
}

/// `(normalized path, method) -> (enforced, exempt, path as written)`.
///
/// Keyed the way routes are. Raw paths let a renamed capture hide a CSRF loss
/// outright: the head entry matched no base entry, and the disappearance check
/// below could not catch it either, because `routes_after` holds normalized
/// keys. The path as the author wrote it rides along for the finding's text.
fn csrf_index(m: &PostureManifest) -> BTreeMap<RouteKey, (bool, bool, String)> {
    let mut index: BTreeMap<RouteKey, (bool, bool, String)> = BTreeMap::new();
    for e in &m.dimensions.csrf.entries {
        let key = (normalize_captures(&e.path), e.method.clone());
        index
            .entry(key)
            .and_modify(|(enforced, exempt, _)| {
                // Two entries for one route shape merge to the *widest* of
                // them, exactly as duplicate route entries do: whichever sorts
                // last must not get to declare the route protected.
                *enforced = *enforced && e.csrf_enforced;
                *exempt = *exempt || e.exempt;
            })
            .or_insert_with(|| (e.csrf_enforced, e.exempt, e.path.clone()));
    }
    index
}

fn diff_csrf(base: &PostureManifest, head: &PostureManifest, out: &mut Vec<Finding>) {
    diff_csrf_exemptions(base, head, out);
    // What still guards each route, for the fingerprints below: losing CSRF
    // behind a newly required scope is not the same decision as losing it with
    // that scope gone again.
    let head_routes = route_index(head);
    let before = csrf_index(base);
    let after = csrf_index(head);
    let routes_before = route_keys(base);
    let routes_after = route_keys(head);

    // Keyed rather than pushed, so the two passes below cannot report the same
    // route twice and the order is the key order either way.
    // Each lost route with the path it was written as, whether an exemption is
    // why, and the key of the route that answers those URLs now — not always
    // the one that left: a `WS` row gives way to a `GET` at the same path, and
    // the guard posture has to come from the route that inherits it.
    let mut lost: BTreeMap<RouteKey, (String, bool, Vec<RouteKey>)> = BTreeMap::new();
    let mut gained: Vec<(RouteKey, String)> = Vec::new();
    for (key, (enforced_now, exempt_now, written_as)) in &after {
        match before.get(key).map(|(enforced, ..)| *enforced) {
            Some(true) if !enforced_now => {
                lost.insert(
                    key.clone(),
                    (written_as.clone(), *exempt_now, vec![key.clone()]),
                );
            }
            Some(false) if *enforced_now => gained.push((key.clone(), written_as.clone())),
            _ => {}
        }
    }
    // The other direction: an entry that *left* the dimension entirely. The
    // csrf dimension holds only mutating routes, so widening
    // `security.csrf.safe_methods` deletes entries rather than flipping them —
    // and at runtime those requests stop being validated.
    for (key, (enforced_before, _, written_as)) in &before {
        if !*enforced_before || after.contains_key(key) {
            continue;
        }
        // Reachable by the same rule the route findings use, not by an exact
        // key: a `WS` route and a `GET` route at one path are the same runtime
        // handler, so replacing an enforced `WS /x` with a `GET /x` that does
        // not enforce is a lost check, however the manifest spells the method.
        let (path, method) = key;
        // Every non-enforcing taker, not the first. A removed route's URLs
        // split: deleting `/records/me/{id}` sends `/records/me/private` to
        // `/records/{user}/private` and the rest to `/records/{user}/{id}`, and
        // `undominated` returns both because neither covers the other's share.
        // Naming one let the other be weakened after the acknowledgment.
        let inheritors: Vec<RouteKey> = takers((path, method), &routes_before, &routes_after)
            .into_iter()
            .filter(|taker| after.get(taker).is_none_or(|(enforced, ..)| !enforced))
            .collect();
        if !inheritors.is_empty() {
            lost.entry(key.clone())
                .or_insert_with(|| (written_as.clone(), false, inheritors));
        }
    }

    // One collapsed finding when CSRF went off everywhere: an app that flips
    // `security.csrf.enabled` produces one row per mutating route otherwise,
    // and a 200-row table is a table nobody reads.
    let collapse = after.values().all(|(enforced, ..)| !enforced)
        && before.values().any(|entry| entry.0)
        && lost.len() > 1;
    report_csrf_loss(
        lost,
        &head_routes,
        &after,
        &authz_index(head),
        &mtls_index(head),
        collapse,
        out,
    );

    for ((_, method), path) in gained {
        out.push(Finding {
            kind: "csrf_enforcement_added",
            severity: Severity::Narrowing,
            method,
            path,
            before: "csrf not enforced".to_owned(),
            after: "csrf enforced".to_owned(),
            fingerprint: "csrf-added".to_owned(),
            detail: "CSRF enforcement gained".to_owned(),
        });
    }
}

/// Compare the mTLS dimension (#1640).
///
/// Two things can weaken it, and both block:
/// - a route that demanded a verified client certificate stops demanding one —
///   the regression this dimension exists to catch;
/// - the listener mode itself weakens (`required` → `optional` → `off`), which
///   no per-route row shows on its own.
///
/// A route that merely *left* the manifest is not reported here: it is already
/// a route finding, and reporting the lost requirement too would double-count
/// one deletion.
fn diff_mtls(base: &PostureManifest, head: &PostureManifest, out: &mut Vec<Finding>) {
    diff_mtls_mode(base, head, out);
    diff_mtls_required_paths(base, head, out);

    let before = mtls_index(base);
    let after = mtls_index(head);
    let head_routes = route_index(head);
    let head_csrf = csrf_index(head);
    let head_bindings = authz_index(head);

    for key in before.difference(&after) {
        // Still mounted, but no longer requiring a certificate. A route that is
        // gone entirely is the route dimension's finding, not this one's.
        if !head_routes.contains_key(key) {
            continue;
        }
        let (path, method) = key;
        out.push(Finding {
            kind: "mtls_requirement_removed",
            severity: Severity::Widening,
            method: method.clone(),
            path: path.clone(),
            before: "mtls required".to_owned(),
            after: "mtls not required".to_owned(),
            // What still guards the route, for the same reason every other
            // widening carries it: losing mTLS behind a newly required scope is
            // not the decision that losing it with the scope gone again is.
            fingerprint: format!(
                "mtls-removed:{}",
                postures_of(
                    std::slice::from_ref(key),
                    &head_routes,
                    &head_csrf,
                    &head_bindings,
                    &after,
                )
            ),
            detail: "this route no longer requires a verified client certificate".to_owned(),
        });
    }

    for key in after.difference(&before) {
        let (path, method) = key;
        out.push(Finding {
            kind: "mtls_requirement_added",
            severity: Severity::Narrowing,
            method: method.clone(),
            path: path.clone(),
            before: "mtls not required".to_owned(),
            after: "mtls required".to_owned(),
            fingerprint: "mtls-added".to_owned(),
            detail: "this route now requires a verified client certificate".to_owned(),
        });
    }
}

/// Compare the configured `required_paths` themselves, not just the per-route
/// rows they produce.
///
/// The rows answer whether a route TEMPLATE matches a prefix; the runtime
/// answers it of the concrete request path. A prefix that protects only part of
/// a parameterized route — `/users/admin` against a route mounted at
/// `/users/{id}` — therefore flags no row in either manifest, so dropping it
/// moves nothing the per-route pass can see while the live listener stops
/// protecting `/users/admin`. The `csrf` dimension carries `exempt_paths` for
/// exactly this reason; this is the same rule in the opposite direction.
///
/// Coverage, not spelling: replacing `/internal` with `/internal/keys` still
/// requires a certificate for everything the narrower prefix names, so only the
/// coverage the narrower set LOSES is reported.
fn diff_mtls_required_paths(
    base: &PostureManifest,
    head: &PostureManifest,
    out: &mut Vec<Finding>,
) {
    // A listener that stopped requesting certificates has already been reported
    // by `diff_mtls_mode` in the strongest terms available; enumerating the
    // prefixes it also stopped honouring would add a row without adding
    // information.
    if !base.dimensions.mtls.requests_certificate() {
        return;
    }
    let head_requests = head.dimensions.mtls.requests_certificate();
    let before: BTreeSet<&String> = base.dimensions.mtls.required_paths.iter().collect();
    let after: BTreeSet<&String> = head.dimensions.mtls.required_paths.iter().collect();

    // Dropped when the head no longer requests certificates at all (every
    // prefix is then uncovered), or when no remaining prefix covers it.
    let dropped: Vec<String> = before
        .iter()
        .filter(|p| !head_requests || !after.iter().any(|new| covers_prefix(new, p)))
        .map(|p| (*p).clone())
        .collect();
    let added: Vec<String> = after
        .iter()
        .filter(|p| !before.iter().any(|old| covers_prefix(old, p)))
        .map(|p| (*p).clone())
        .collect();

    if !dropped.is_empty() {
        // The fingerprint carries the surviving prefixes too. Narrowing
        // `/internal` to `/internal/admin` leaves `added` empty, so `dropped`
        // and `added` alone hash the same as a later swap to
        // `/internal/public` — and one acknowledgment would then cover two
        // different sets of URLs.
        let mut surviving: Vec<String> = after.iter().map(|p| (*p).clone()).collect();
        surviving.sort();
        out.push(Finding {
            kind: "mtls_required_path_removed",
            severity: Severity::Widening,
            method: "*".to_owned(),
            path: "*".to_owned(),
            before: dropped.join(", "),
            after: if surviving.is_empty() {
                "not required".to_owned()
            } else {
                format!("still required: {}", surviving.join(", "))
            },
            fingerprint: format!(
                "mtls-required-path-removed:{}",
                escape_list(&[
                    escape_list(&dropped),
                    escape_list(&added),
                    escape_list(&surviving),
                ])
            ),
            detail: format!(
                "a verified client certificate is no longer required for {}, which the \
                 per-route rows cannot show: the audit matches a prefix against a route \
                 template, the runtime against the request path",
                dropped.join(", ")
            ),
        });
    }
    if !added.is_empty() {
        out.push(Finding {
            kind: "mtls_required_path_added",
            severity: Severity::Narrowing,
            method: "*".to_owned(),
            path: "*".to_owned(),
            before: "not required".to_owned(),
            after: added.join(", "),
            fingerprint: format!("mtls-required-path-added:{}", escape_list(&added)),
            detail: format!(
                "a verified client certificate is now required for {}",
                added.join(", ")
            ),
        });
    }
}

/// Whether requirement prefix `outer` covers everything `inner` does.
///
/// The runtime's rule (`client_auth::path_matches_any`): a trailing slash is
/// stripped before matching, and the boundary must be a segment break — so
/// `/internal` covers `/internal/keys` but not `/internal-tools`.
fn covers_prefix(outer: &str, inner: &str) -> bool {
    let outer = outer.strip_suffix('/').unwrap_or(outer);
    let inner = inner.strip_suffix('/').unwrap_or(inner);
    inner == outer
        || inner
            .strip_prefix(outer)
            .is_some_and(|r| r.starts_with('/'))
}

/// Compare the listener-wide mTLS mode.
///
/// Ranked `off` < `optional` < `required`: dropping a rank means the listener
/// asks for less than it did, which no per-route row reports.
fn diff_mtls_mode(base: &PostureManifest, head: &PostureManifest, out: &mut Vec<Finding>) {
    let before = mtls_mode_rank(&base.dimensions.mtls.mode);
    let after = mtls_mode_rank(&head.dimensions.mtls.mode);
    if before == after {
        return;
    }
    let label = |m: &str| {
        if m.is_empty() {
            "off".to_owned()
        } else {
            m.to_owned()
        }
    };
    let (before_label, after_label) = (
        label(&base.dimensions.mtls.mode),
        label(&head.dimensions.mtls.mode),
    );
    let (kind, severity, detail) = if after < before {
        (
            "mtls_mode_weakened",
            Severity::Widening,
            format!(
                "the listener's client-certificate mode weakened from `{before_label}` to \
                 `{after_label}`"
            ),
        )
    } else {
        (
            "mtls_mode_strengthened",
            Severity::Narrowing,
            format!(
                "the listener's client-certificate mode strengthened from `{before_label}` to \
                 `{after_label}`"
            ),
        )
    };
    out.push(Finding {
        kind,
        severity,
        method: "*".to_owned(),
        path: "*".to_owned(),
        before: before_label,
        after: after_label.clone(),
        fingerprint: format!("mtls-mode:{after_label}"),
        detail,
    });
}

/// Rank an mTLS mode by how much it demands. An empty or unknown spelling ranks
/// as `off`: a manifest that predates this dimension asks for nothing, and an
/// unreadable mode must never be treated as protection.
fn mtls_mode_rank(mode: &str) -> u8 {
    match mode {
        "required" => 2,
        "optional" => 1,
        _ => 0,
    }
}

fn headers_index(m: &PostureManifest) -> BTreeMap<&str, (bool, &str)> {
    m.dimensions
        .security_headers
        .entries
        .iter()
        .map(|e| (e.header.as_str(), (e.emitted, e.value.as_str())))
        .collect()
}

fn diff_headers(base: &PostureManifest, head: &PostureManifest, out: &mut Vec<Finding>) {
    let before = headers_index(base);
    let after = headers_index(head);

    // What the app still emits, folded into every removal's identity.
    //
    // The last constant fingerprints in the module, and the argument for
    // leaving them — a header is emitted or it is not, so there is no third
    // state — was about the *value* and beside the point. Losing HSTS while
    // gaining CSP is a decision about the set that results: the addition is a
    // narrowing, so dropping it later leaves the diff holding the identical
    // HSTS removal and the old acknowledgment covering a posture with neither.
    //
    // Values as well as names, since `security_header_value_changed` is
    // deliberately neutral — weakening a CSP after the fact would otherwise
    // reach exactly as far. The cost is the one `bind_to_effective_posture`
    // already pays and #2497 tracks: a cosmetic header edit re-asks.
    let emitted: Vec<String> = after
        .iter()
        .filter(|(_, (emitted, _))| *emitted)
        .map(|(header, (_, value))| escape_list(&[(*header).to_owned(), (*value).to_owned()]))
        .collect();
    // Already ordered by header: `after` is a `BTreeMap` keyed on the name.
    let remaining = escape_list(&emitted);

    let removed = |header: &str, value_before: &str| Finding {
        kind: "security_header_removed",
        severity: Severity::Widening,
        method: "*".to_owned(),
        path: header.to_owned(),
        before: value_before.to_owned(),
        after: "not emitted".to_owned(),
        fingerprint: escape_list(&["header-removed".to_owned(), remaining.clone()]),
        detail: format!("security header `{header}` is no longer emitted"),
    };

    for (header, (emitted_now, value_now)) in &after {
        match before.get(header) {
            None => {
                if *emitted_now {
                    out.push(Finding {
                        kind: "security_header_added",
                        severity: Severity::Narrowing,
                        method: "*".to_owned(),
                        path: (*header).to_owned(),
                        before: "not emitted".to_owned(),
                        after: (*value_now).to_owned(),
                        fingerprint: "header-added".to_owned(),
                        detail: format!("security header `{header}` is now emitted"),
                    });
                }
            }
            Some((emitted_before, value_before)) => {
                if *emitted_before && !*emitted_now {
                    out.push(removed(header, value_before));
                } else if !*emitted_before && *emitted_now {
                    out.push(Finding {
                        kind: "security_header_added",
                        severity: Severity::Narrowing,
                        method: "*".to_owned(),
                        path: (*header).to_owned(),
                        before: "not emitted".to_owned(),
                        after: (*value_now).to_owned(),
                        fingerprint: "header-added".to_owned(),
                        detail: format!("security header `{header}` is now emitted"),
                    });
                } else if value_before != value_now {
                    // Deliberately neutral. Whether one CSP is weaker than
                    // another is not decidable from the strings, and a gate
                    // that blocks on "the CSP changed" is a gate teams turn
                    // off. It is reported so a human can look, never so a robot
                    // can refuse.
                    out.push(Finding {
                        kind: "security_header_value_changed",
                        severity: Severity::Neutral,
                        method: "*".to_owned(),
                        path: (*header).to_owned(),
                        before: (*value_before).to_owned(),
                        after: (*value_now).to_owned(),
                        fingerprint: "header-value-changed".to_owned(),
                        detail: format!("security header `{header}` value changed — review by eye"),
                    });
                }
            }
        }
    }
    // A header entry that left the manifest entirely is the same loss as one
    // flipped to `emitted: false`.
    for (header, (emitted_before, value_before)) in &before {
        if *emitted_before && !after.contains_key(header) {
            out.push(removed(header, value_before));
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::posture::model::PostureManifest;

    /// Build a manifest from route entries plus optional other dimensions.
    fn manifest(routes: &str, csrf: &str, headers: &str, authz: &str) -> PostureManifest {
        let json = format!(
            r#"{{"schema_version":3,"dimensions":{{
                 "routes":{{"provenance":"provable","source":"m","entries":[{routes}]}},
                 "csrf":{{"provenance":"declared","source":"c","exempt_paths":[],"entries":[{csrf}]}},
                 "security_headers":{{"provenance":"declared","source":"c","entries":[{headers}]}},
                 "authorization_policies":{{"provenance":"provable","source":"m","runtime_caveat":"x","entries":[{authz}]}}
               }},"excluded":[]}}"#
        );
        PostureManifest::parse(&json, "test.json").expect("fixture parses")
    }

    fn routes_only(routes: &str) -> PostureManifest {
        manifest(routes, "", "", "")
    }

    /// A manifest whose csrf dimension carries configured exemption prefixes.
    fn manifest_exempt(routes: &str, csrf: &str, exempt: &[&str]) -> PostureManifest {
        let exempt = exempt
            .iter()
            .map(|p| format!("\"{p}\""))
            .collect::<Vec<_>>()
            .join(",");
        let json = format!(
            r#"{{"schema_version":3,"dimensions":{{
                 "routes":{{"provenance":"provable","source":"m","entries":[{routes}]}},
                 "csrf":{{"provenance":"declared","source":"c","exempt_paths":[{exempt}],"entries":[{csrf}]}},
                 "security_headers":{{"provenance":"declared","source":"c","entries":[]}},
                 "authorization_policies":{{"provenance":"provable","source":"m","runtime_caveat":"x","entries":[]}}
               }},"excluded":[]}}"#
        );
        PostureManifest::parse(&json, "test.json").expect("fixture parses")
    }

    /// One route entry, spelled the way the manifest spells it.
    fn route(
        path: &str,
        method: &str,
        classification: &str,
        roles: &[&str],
        scopes: &[&str],
        policy: bool,
    ) -> String {
        let roles = roles
            .iter()
            .map(|r| format!("\"{r}\""))
            .collect::<Vec<_>>()
            .join(",");
        let scopes = scopes
            .iter()
            .map(|s| format!("\"{s}\""))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            r#"{{"path":"{path}","method":"{method}","name":"h","classification":"{classification}",
                 "roles":[{roles}],"scopes":[{scopes}],"policy":{policy},"source":"user",
                 "location":"src/routes.rs:1","provenance":"provable"}}"#
        )
    }

    fn kinds(findings: &[Finding]) -> Vec<&'static str> {
        findings.iter().map(|f| f.kind).collect()
    }

    fn only(findings: Vec<Finding>) -> Finding {
        assert_eq!(
            findings.len(),
            1,
            "expected exactly one finding: {findings:#?}"
        );
        findings.into_iter().next().expect("one finding")
    }

    /// A manifest carrying an `mtls` dimension (schema v4, #1640).
    fn manifest_mtls(
        routes: &str,
        mode: &str,
        required_paths: &[&str],
        mtls: &str,
    ) -> PostureManifest {
        let required = required_paths
            .iter()
            .map(|p| format!("\"{p}\""))
            .collect::<Vec<_>>()
            .join(",");
        let json = format!(
            r#"{{"schema_version":4,"dimensions":{{
                 "routes":{{"provenance":"provable","source":"m","entries":[{routes}]}},
                 "csrf":{{"provenance":"declared","source":"c","exempt_paths":[],"entries":[]}},
                 "security_headers":{{"provenance":"declared","source":"c","entries":[]}},
                 "authorization_policies":{{"provenance":"provable","source":"m","runtime_caveat":"x","entries":[]}},
                 "mtls":{{"provenance":"declared","source":"config:server.tls.client_auth",
                          "mode":"{mode}","required_paths":[{required}],"entries":[{mtls}]}}
               }},"excluded":[]}}"#
        );
        PostureManifest::parse(&json, "test.json").expect("fixture parses")
    }

    /// One mTLS entry.
    fn mtls_entry(path: &str, method: &str, required: bool) -> String {
        format!(r#"{{"path":"{path}","method":"{method}","mtls_required":{required}}}"#)
    }

    // ── mtls dimension (#1640) ──────────────────────────────────────────────

    /// The regression this dimension exists to catch: a route silently drops
    /// its mTLS requirement.
    #[test]
    fn a_route_dropping_its_mtls_requirement_is_a_widening_that_names_it() {
        let routes = route("/internal/keys", "GET", "gated", &["admin"], &[], false);
        let base = manifest_mtls(
            &routes,
            "optional",
            &["/internal/"],
            &mtls_entry("/internal/keys", "GET", true),
        );
        let head = manifest_mtls(
            &routes,
            "optional",
            &[],
            &mtls_entry("/internal/keys", "GET", false),
        );

        // Two findings, deliberately: the route row that lost its requirement,
        // and the configured prefix that stopped being honoured. They catch
        // different regressions — see `diff_mtls_required_paths`.
        let findings = diff(&base, &head);
        let finding = findings
            .iter()
            .find(|f| f.kind == "mtls_requirement_removed")
            .unwrap_or_else(|| panic!("expected a per-route finding: {findings:#?}"));
        assert_eq!(finding.severity, Severity::Widening);
        assert_eq!(finding.path, "/internal/keys");
        assert_eq!(finding.method, "GET");
        assert!(kinds(&findings).contains(&"mtls_required_path_removed"));
    }

    #[test]
    fn adding_an_mtls_requirement_is_narrowing() {
        let routes = route("/internal/keys", "GET", "gated", &[], &[], false);
        let base = manifest_mtls(
            &routes,
            "optional",
            &[],
            &mtls_entry("/internal/keys", "GET", false),
        );
        let head = manifest_mtls(
            &routes,
            "optional",
            &["/internal/"],
            &mtls_entry("/internal/keys", "GET", true),
        );

        let findings = diff(&base, &head);
        let finding = findings
            .iter()
            .find(|f| f.kind == "mtls_requirement_added")
            .unwrap_or_else(|| panic!("expected a per-route finding: {findings:#?}"));
        assert_eq!(finding.severity, Severity::Narrowing);
        assert!(kinds(&findings).contains(&"mtls_required_path_added"));
    }

    #[test]
    fn weakening_the_listener_mode_is_a_widening() {
        let routes = route("/a", "GET", "public", &[], &[], false);
        let base = manifest_mtls(&routes, "required", &[], &mtls_entry("/a", "GET", false));
        let head = manifest_mtls(&routes, "optional", &[], &mtls_entry("/a", "GET", false));

        let finding = only(diff(&base, &head));
        assert_eq!(finding.kind, "mtls_mode_weakened");
        assert_eq!(finding.severity, Severity::Widening);
        assert_eq!(finding.before, "required");
        assert_eq!(finding.after, "optional");
    }

    #[test]
    fn strengthening_the_listener_mode_is_narrowing() {
        let routes = route("/a", "GET", "public", &[], &[], false);
        let base = manifest_mtls(&routes, "optional", &[], &mtls_entry("/a", "GET", false));
        let head = manifest_mtls(&routes, "required", &[], &mtls_entry("/a", "GET", false));

        let finding = only(diff(&base, &head));
        assert_eq!(finding.kind, "mtls_mode_strengthened");
        assert_eq!(finding.severity, Severity::Narrowing);
    }

    /// A deleted route is the route dimension's finding. Reporting its lost
    /// mTLS requirement too would double-count one deletion.
    #[test]
    fn deleting_a_route_does_not_also_report_a_lost_mtls_requirement() {
        let base = manifest_mtls(
            &route("/internal/keys", "GET", "gated", &[], &[], false),
            "optional",
            &["/internal/"],
            &mtls_entry("/internal/keys", "GET", true),
        );
        let head = manifest_mtls("", "optional", &["/internal/"], "");

        assert!(
            !kinds(&diff(&base, &head)).contains(&"mtls_requirement_removed"),
            "a removed route must not raise a second, mTLS-shaped finding"
        );
    }

    /// The per-route rows answer whether a route TEMPLATE matches a prefix; the
    /// runtime answers it of the request path. A prefix protecting part of a
    /// parameterized route flags no row in either manifest, so only comparing
    /// the configured prefixes catches it being dropped.
    #[test]
    fn dropping_a_required_prefix_that_matches_no_route_template_is_a_widening() {
        let routes = route("/users/{id}", "GET", "gated", &[], &[], false);
        let entry = mtls_entry("/users/{id}", "GET", false);
        let base = manifest_mtls(&routes, "optional", &["/users/admin"], &entry);
        let head = manifest_mtls(&routes, "optional", &[], &entry);

        let finding = only(diff(&base, &head));
        assert_eq!(finding.kind, "mtls_required_path_removed");
        assert_eq!(finding.severity, Severity::Widening);
        assert!(finding.before.contains("/users/admin"), "{finding:?}");
    }

    #[test]
    fn narrowing_a_required_prefix_reports_only_the_coverage_lost() {
        let routes = route("/a", "GET", "public", &[], &[], false);
        let entry = mtls_entry("/a", "GET", false);
        // `/internal/keys` still requires a certificate, so replacing
        // `/internal/keys` with the WIDER `/internal` loses nothing.
        let widened = diff(
            &manifest_mtls(&routes, "optional", &["/internal/keys"], &entry),
            &manifest_mtls(&routes, "optional", &["/internal"], &entry),
        );
        assert!(
            !kinds(&widened).contains(&"mtls_required_path_removed"),
            "widening a prefix loses no coverage: {widened:#?}"
        );

        // The reverse DOES lose coverage: everything under `/internal` that is
        // not under `/internal/keys` stops requiring one.
        let narrowed = diff(
            &manifest_mtls(&routes, "optional", &["/internal"], &entry),
            &manifest_mtls(&routes, "optional", &["/internal/keys"], &entry),
        );
        assert!(kinds(&narrowed).contains(&"mtls_required_path_removed"));
    }

    /// Replacing a broad prefix with a narrower one leaves `added` empty (the
    /// old prefix already covered the replacement), so the fingerprint has to
    /// carry what SURVIVES or two different narrowings hash alike and the first
    /// acknowledgment silently covers the second.
    #[test]
    fn two_different_narrowings_of_one_prefix_do_not_share_a_fingerprint() {
        let routes = route("/internal/{id}", "GET", "gated", &[], &[], false);
        let entry = mtls_entry("/internal/{id}", "GET", false);
        let base = manifest_mtls(&routes, "optional", &["/internal"], &entry);

        let fingerprint = |head_prefix: &str| {
            let head = manifest_mtls(&routes, "optional", &[head_prefix], &entry);
            let found = diff(&base, &head)
                .into_iter()
                .find(|f| f.kind == "mtls_required_path_removed");
            let Some(finding) = found else {
                panic!("expected a removal finding for {head_prefix}");
            };
            finding.fingerprint
        };

        assert_ne!(
            fingerprint("/internal/admin"),
            fingerprint("/internal/public"),
            "two narrowings protecting different URLs must not share an acknowledgment"
        );
    }

    #[test]
    fn a_trailing_slash_is_not_a_prefix_change() {
        // The runtime strips it before matching, so the two spellings cover the
        // same URLs and must not raise a finding either way.
        let routes = route("/a", "GET", "public", &[], &[], false);
        let entry = mtls_entry("/a", "GET", false);
        let findings = diff(
            &manifest_mtls(&routes, "optional", &["/internal"], &entry),
            &manifest_mtls(&routes, "optional", &["/internal/"], &entry),
        );
        assert!(findings.is_empty(), "{findings:#?}");
    }

    #[test]
    fn turning_the_listener_off_does_not_double_report_every_prefix() {
        // `mtls_mode_weakened` already says it in the strongest terms.
        let routes = route("/a", "GET", "public", &[], &[], false);
        let entry = mtls_entry("/a", "GET", false);
        let findings = diff(
            &manifest_mtls(&routes, "required", &["/internal"], &entry),
            &manifest_mtls(&routes, "off", &[], &entry),
        );
        let kinds = kinds(&findings);
        assert!(kinds.contains(&"mtls_mode_weakened"), "{findings:#?}");
        assert!(
            kinds.contains(&"mtls_required_path_removed"),
            "the prefixes it stopped honouring are still named: {findings:#?}"
        );
    }

    /// The v3→v4 bump adds a dimension and changes nothing else, so an app that
    /// uses no client auth must diff — and hash — exactly as it did before.
    #[test]
    fn the_schema_bump_alone_is_not_a_posture_change() {
        let routes = route("/a", "GET", "public", &[], &[], false);
        let v3 = routes_only(&routes);
        let v4 = manifest_mtls(&routes, "off", &[], &mtls_entry("/a", "GET", false));

        assert!(
            diff(&v3, &v4).is_empty(),
            "reading a v3 manifest against a v4 one with client auth off must be a no-op: {:#?}",
            diff(&v3, &v4)
        );
        assert_eq!(
            v3.posture_digest(),
            v4.posture_digest(),
            "an app with no client auth must keep its posture digest across the bump"
        );
    }

    /// An acknowledgment of some *other* widening must not survive the mTLS
    /// requirement being dropped in the same change.
    #[test]
    fn dropping_mtls_moves_the_fingerprint_of_a_coincident_widening() {
        let locked = |classification: &str| {
            manifest_mtls(
                &route("/internal/keys", "GET", classification, &[], &[], false),
                "optional",
                &["/internal/"],
                &mtls_entry("/internal/keys", "GET", true),
            )
        };
        let unlocked = manifest_mtls(
            &route("/internal/keys", "GET", "public", &[], &[], false),
            "optional",
            &[],
            &mtls_entry("/internal/keys", "GET", false),
        );

        // Same class widening, once with the mTLS requirement intact and once
        // with it dropped alongside.
        let with_mtls = diff(&locked("gated"), &locked("public"));
        let without = diff(&locked("gated"), &unlocked);
        let class_change = |findings: &[Finding]| {
            findings
                .iter()
                .find(|f| f.kind == "classification_downgraded")
                .map(|f| f.fingerprint.clone())
        };
        assert_ne!(
            class_change(&with_mtls),
            class_change(&without),
            "an acknowledgment of the class change must not also cover losing mTLS"
        );
    }

    // ── the falsifiability trio from the issue ──────────────────────────────

    /// AC-7 (red): a role-gated route flipped to public is a widening finding
    /// that names the route.
    #[test]
    fn flipping_a_role_gated_route_to_public_is_a_widening_that_names_it() {
        let base = routes_only(&route(
            "/admin/users",
            "GET",
            "gated",
            &["admin"],
            &[],
            false,
        ));
        let head = routes_only(&route("/admin/users", "GET", "public", &[], &[], false));

        let findings = diff(&base, &head);
        let f = only(findings.clone());
        assert_eq!(f.kind, "classification_downgraded");
        assert_eq!(f.severity, Severity::Widening);
        assert_eq!(f.path, "/admin/users");
        assert_eq!(f.method, "GET");
        assert!(f.before.contains("gated"), "{f:?}");
        assert!(f.before.contains("admin"), "{f:?}");
        assert_eq!(f.after, "public");
        assert_eq!(widening(&findings).len(), 1);
    }

    /// AC-7 (green): the same handler renamed and moved to another file is not
    /// a posture change at all.
    #[test]
    fn a_cosmetic_refactor_produces_no_finding() {
        let base = routes_only(
            r#"{"path":"/admin/users","method":"GET","name":"list_users","classification":"gated",
                "roles":["admin"],"scopes":[],"policy":false,"source":"user",
                "location":"src/routes/admin.rs:12","module":"routes::admin","provenance":"provable"}"#,
        );
        let head = routes_only(
            r#"{"path":"/admin/users","method":"GET","name":"index","classification":"gated",
                "roles":["admin"],"scopes":[],"policy":false,"source":"user",
                "location":"src/routes/admin/users.rs:88","module":"routes::admin::users","provenance":"provable"}"#,
        );
        assert!(diff(&base, &head).is_empty(), "{:#?}", diff(&base, &head));
    }

    /// A PR that changes nothing at all is silent.
    #[test]
    fn an_identical_manifest_produces_no_finding() {
        let m = manifest(
            &route("/a", "GET", "gated", &["admin"], &[], false),
            r#"{"path":"/a","method":"POST","csrf_enforced":true,"exempt":false}"#,
            r#"{"header":"x_frame_options","value":"DENY","emitted":true}"#,
            r#"{"path":"/a","method":"GET","name":"h","action":"read","resource":"Post","provenance":"provable"}"#,
        );
        let m2 = manifest(
            &route("/a", "GET", "gated", &["admin"], &[], false),
            r#"{"path":"/a","method":"POST","csrf_enforced":true,"exempt":false}"#,
            r#"{"header":"x_frame_options","value":"DENY","emitted":true}"#,
            r#"{"path":"/a","method":"GET","name":"h","action":"read","resource":"Post","provenance":"provable"}"#,
        );
        assert!(diff(&m, &m2).is_empty());
    }

    // ── added / removed routes ──────────────────────────────────────────────

    #[test]
    fn a_new_public_route_is_widening() {
        let base = routes_only("");
        let head = routes_only(&route("/signup", "POST", "public", &[], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "route_added_open");
        assert_eq!(f.severity, Severity::Widening);
        assert_eq!(f.before, "absent");
    }

    #[test]
    fn a_new_unclassified_route_is_widening_too() {
        let base = routes_only("");
        let head = routes_only(&route("/oops", "POST", "unclassified", &[], &[], false));
        assert_eq!(only(diff(&base, &head)).severity, Severity::Widening);
    }

    #[test]
    fn a_new_gated_route_never_blocks() {
        let base = routes_only("");
        let head = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "route_added_gated");
        assert_eq!(f.severity, Severity::Neutral);
        assert!(widening(&diff(&base, &head)).is_empty());
    }

    #[test]
    fn a_new_framework_route_never_blocks() {
        let base = routes_only("");
        let head = routes_only(&route(
            "/actuator/health",
            "GET",
            "framework",
            &[],
            &[],
            false,
        ));
        assert_eq!(only(diff(&base, &head)).severity, Severity::Neutral);
    }

    #[test]
    fn a_removed_route_is_narrowing() {
        let base = routes_only(&route("/old", "GET", "public", &[], &[], false));
        let head = routes_only("");
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "route_removed");
        assert_eq!(f.severity, Severity::Narrowing);
    }

    #[test]
    fn the_same_path_on_a_different_method_is_a_different_route() {
        let base = routes_only(&route("/posts", "GET", "public", &[], &[], false));
        let head = routes_only(&format!(
            "{},{}",
            route("/posts", "GET", "public", &[], &[], false),
            route("/posts", "DELETE", "public", &[], &[], false)
        ));
        let f = only(diff(&base, &head));
        assert_eq!(f.method, "DELETE");
        assert_eq!(f.severity, Severity::Widening);
    }

    // ── gates ───────────────────────────────────────────────────────────────

    #[test]
    fn dropping_the_role_requirement_is_widening() {
        let base = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let head = routes_only(&route("/admin", "GET", "gated", &[], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "roles_cleared");
        assert_eq!(f.severity, Severity::Widening);
        assert!(f.detail.contains("admin"), "{f:?}");
    }

    /// Roles are OR-ed, so an extra role admits *more* people.
    #[test]
    fn adding_a_role_is_widening_because_roles_are_or_ed() {
        let base = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let head = routes_only(&route(
            "/admin",
            "GET",
            "gated",
            &["admin", "editor"],
            &[],
            false,
        ));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "roles_widened");
        assert_eq!(f.severity, Severity::Widening);
        assert!(f.detail.contains("editor"), "{f:?}");
    }

    #[test]
    fn removing_one_of_several_roles_is_narrowing() {
        let base = routes_only(&route(
            "/admin",
            "GET",
            "gated",
            &["admin", "editor"],
            &[],
            false,
        ));
        let head = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "roles_narrowed");
        assert_eq!(f.severity, Severity::Narrowing);
    }

    #[test]
    fn reordering_roles_is_not_a_change() {
        let base = routes_only(&route(
            "/admin",
            "GET",
            "gated",
            &["admin", "editor"],
            &[],
            false,
        ));
        let head = routes_only(&route(
            "/admin",
            "GET",
            "gated",
            &["editor", "admin"],
            &[],
            false,
        ));
        assert!(diff(&base, &head).is_empty());
    }

    /// Scopes are AND-ed, so dropping one lets *more* tokens through.
    #[test]
    fn removing_a_scope_is_widening_because_scopes_are_and_ed() {
        let base = routes_only(&route(
            "/api",
            "POST",
            "gated",
            &[],
            &["posts:write", "admin"],
            false,
        ));
        let head = routes_only(&route(
            "/api",
            "POST",
            "gated",
            &[],
            &["posts:write"],
            false,
        ));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "scopes_widened");
        assert_eq!(f.severity, Severity::Widening);
        assert!(f.detail.contains("admin"), "{f:?}");
    }

    #[test]
    fn adding_a_scope_is_narrowing() {
        let base = routes_only(&route(
            "/api",
            "POST",
            "gated",
            &[],
            &["posts:write"],
            false,
        ));
        let head = routes_only(&route(
            "/api",
            "POST",
            "gated",
            &[],
            &["posts:write", "admin"],
            false,
        ));
        assert_eq!(only(diff(&base, &head)).kind, "scopes_narrowed");
    }

    #[test]
    fn removing_the_policy_check_is_widening() {
        let base = routes_only(&route("/posts/1", "PUT", "gated", &["user"], &[], true));
        let head = routes_only(&route("/posts/1", "PUT", "gated", &["user"], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "policy_removed");
        assert_eq!(f.severity, Severity::Widening);
    }

    #[test]
    fn adding_the_policy_check_is_narrowing() {
        let base = routes_only(&route("/posts/1", "PUT", "gated", &["user"], &[], false));
        let head = routes_only(&route("/posts/1", "PUT", "gated", &["user"], &[], true));
        assert_eq!(only(diff(&base, &head)).severity, Severity::Narrowing);
    }

    #[test]
    fn gating_a_public_route_is_narrowing() {
        let base = routes_only(&route("/admin", "GET", "public", &[], &[], false));
        let head = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "classification_upgraded");
        assert_eq!(f.severity, Severity::Narrowing);
    }

    /// Losing the guard is reported once, in the strongest terms — not once for
    /// the classification and again for every role it took with it.
    #[test]
    fn a_route_that_loses_its_guard_reports_one_finding_not_three() {
        let base = routes_only(&route(
            "/admin",
            "GET",
            "gated",
            &["admin", "editor"],
            &["s"],
            true,
        ));
        let head = routes_only(&route("/admin", "GET", "public", &[], &[], false));
        let findings = diff(&base, &head);
        assert_eq!(kinds(&findings), vec!["classification_downgraded"]);
    }

    // ── authorization bindings ──────────────────────────────────────────────

    #[test]
    fn removing_an_authorize_binding_is_widening() {
        let r = route("/posts/1", "PUT", "gated", &["user"], &[], true);
        let base = manifest(
            &r,
            "",
            "",
            r#"{"path":"/posts/1","method":"PUT","name":"h","action":"update","resource":"Post","provenance":"provable"}"#,
        );
        let head = manifest(&r, "", "", "");
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "authorization_binding_removed");
        assert_eq!(f.severity, Severity::Widening);
        assert!(f.detail.contains("update"), "{f:?}");
        assert!(f.detail.contains("Post"), "{f:?}");
    }

    #[test]
    fn adding_an_authorize_binding_is_narrowing() {
        let r = route("/posts/1", "PUT", "gated", &["user"], &[], true);
        let base = manifest(&r, "", "", "");
        let head = manifest(
            &r,
            "",
            "",
            r#"{"path":"/posts/1","method":"PUT","name":"h","action":"update","resource":"Post","provenance":"provable"}"#,
        );
        assert_eq!(only(diff(&base, &head)).severity, Severity::Narrowing);
    }

    /// A binding that disappeared because the route did is not a second,
    /// widening finding — the route removal already says everything.
    #[test]
    fn a_binding_that_left_with_its_route_is_not_a_widening() {
        let base = manifest(
            &route("/posts/1", "DELETE", "gated", &["user"], &[], true),
            "",
            "",
            r#"{"path":"/posts/1","method":"DELETE","name":"h","action":"destroy","resource":"Post","provenance":"provable"}"#,
        );
        let head = manifest("", "", "", "");
        let findings = diff(&base, &head);
        assert_eq!(kinds(&findings), vec!["route_removed"]);
        assert!(widening(&findings).is_empty());
    }

    // ── CSRF ────────────────────────────────────────────────────────────────

    #[test]
    fn losing_csrf_enforcement_on_a_route_is_widening() {
        let base = manifest(
            "",
            r#"{"path":"/pay","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let head = manifest(
            "",
            r#"{"path":"/pay","method":"POST","csrf_enforced":false,"exempt":true}"#,
            "",
            "",
        );
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "csrf_enforcement_removed");
        assert_eq!(f.severity, Severity::Widening);
    }

    #[test]
    fn gaining_csrf_enforcement_is_narrowing() {
        let base = manifest(
            "",
            r#"{"path":"/pay","method":"POST","csrf_enforced":false,"exempt":true}"#,
            "",
            "",
        );
        let head = manifest(
            "",
            r#"{"path":"/pay","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        assert_eq!(only(diff(&base, &head)).severity, Severity::Narrowing);
    }

    #[test]
    fn disabling_csrf_everywhere_collapses_into_one_finding() {
        let on = (0..5)
            .map(|i| {
                format!(r#"{{"path":"/r{i}","method":"POST","csrf_enforced":true,"exempt":false}}"#)
            })
            .collect::<Vec<_>>()
            .join(",");
        let off = (0..5)
            .map(|i| {
                format!(
                    r#"{{"path":"/r{i}","method":"POST","csrf_enforced":false,"exempt":false}}"#
                )
            })
            .collect::<Vec<_>>()
            .join(",");
        let f = only(diff(
            &manifest("", &on, "", ""),
            &manifest("", &off, "", ""),
        ));
        assert_eq!(f.kind, "csrf_disabled");
        assert_eq!(f.severity, Severity::Widening);
        assert!(f.detail.contains('5'), "{f:?}");
    }

    // ── security headers ────────────────────────────────────────────────────

    #[test]
    fn dropping_a_security_header_is_widening() {
        let base = manifest(
            "",
            "",
            r#"{"header":"x_frame_options","value":"DENY","emitted":true}"#,
            "",
        );
        let head = manifest(
            "",
            "",
            r#"{"header":"x_frame_options","value":"","emitted":false}"#,
            "",
        );
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "security_header_removed");
        assert_eq!(f.severity, Severity::Widening);
    }

    #[test]
    fn adding_a_security_header_is_narrowing() {
        let base = manifest(
            "",
            "",
            r#"{"header":"referrer_policy","value":"","emitted":false}"#,
            "",
        );
        let head = manifest(
            "",
            "",
            r#"{"header":"referrer_policy","value":"no-referrer","emitted":true}"#,
            "",
        );
        assert_eq!(only(diff(&base, &head)).severity, Severity::Narrowing);
    }

    /// Whether one CSP is weaker than another is not decidable from the
    /// strings, so a value change annotates and never blocks.
    #[test]
    fn changing_a_security_header_value_is_neutral_not_widening() {
        let base = manifest(
            "",
            "",
            r#"{"header":"content_security_policy","value":"default-src 'self'","emitted":true}"#,
            "",
        );
        let head = manifest(
            "",
            "",
            r#"{"header":"content_security_policy","value":"default-src *","emitted":true}"#,
            "",
        );
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "security_header_value_changed");
        assert_eq!(f.severity, Severity::Neutral);
        assert!(widening(&diff(&base, &head)).is_empty());
    }

    // ── security regressions (review findings) ──────────────────────────────

    /// A fact that vanishes from the head manifest is still a fact that was
    /// lost. Adding `POST` to `security.csrf.safe_methods` turns CSRF
    /// validation off for every POST *and* removes those routes from the
    /// manifest's csrf dimension, so a head-only walk sees nothing at all.
    #[test]
    fn csrf_entries_that_disappear_from_the_manifest_are_still_widening() {
        // The route is still mounted on both sides — only its csrf entry is
        // gone, which is exactly what widening `security.csrf.safe_methods`
        // does: the route stays, its CSRF validation does not.
        let r = route("/pay", "POST", "public", &[], &[], false);
        let base = manifest(
            &r,
            r#"{"path":"/pay","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let head = manifest(&r, "", "", "");
        let f = only(diff(&base, &head));
        assert_eq!(f.severity, Severity::Widening, "{f:?}");
        assert_eq!(f.path, "/pay");
    }

    /// Same shape for headers: an entry that stops being emitted *by vanishing*
    /// is the same loss as one flipped to `emitted: false`.
    #[test]
    fn security_headers_that_disappear_from_the_manifest_are_still_widening() {
        let base = manifest(
            "",
            "",
            r#"{"header":"x_frame_options","value":"DENY","emitted":true}"#,
            "",
        );
        let head = manifest("", "", "", "");
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "security_header_removed");
        assert_eq!(f.severity, Severity::Widening);
    }

    /// A header that was never emitted and then vanishes is not a loss.
    #[test]
    fn a_header_that_was_not_emitted_and_then_vanishes_is_not_a_finding() {
        let base = manifest(
            "",
            "",
            r#"{"header":"referrer_policy","value":"","emitted":false}"#,
            "",
        );
        let head = manifest("", "", "", "");
        assert!(diff(&base, &head).is_empty());
    }

    /// A CSRF entry that vanished because its route did is already reported as
    /// `route_removed`; reporting it twice — once as a narrowing and once as a
    /// widening — would block a PR for deleting a route.
    #[test]
    fn a_csrf_entry_that_left_with_its_route_is_not_a_widening() {
        let base = manifest(
            &route("/pay", "POST", "public", &[], &[], false),
            r#"{"path":"/pay","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let head = manifest("", "", "", "");
        let findings = diff(&base, &head);
        assert_eq!(kinds(&findings), vec!["route_removed"]);
    }

    /// `#[secured]` with no roles admits every authenticated session, so
    /// *adding* the first role narrows the surface — the one case where an
    /// added role is not a widening.
    #[test]
    fn adding_the_first_role_to_an_unrestricted_gate_is_narrowing() {
        let base = routes_only(&route("/admin", "GET", "gated", &[], &[], false));
        let head = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "roles_narrowed");
        assert_eq!(f.severity, Severity::Narrowing);
    }

    /// The canonical form a finding contributes to the acknowledgment digest is
    /// delimiter-separated, and route paths and role names are app-controlled.
    /// If they are not escaped, one crafted route forges the digest of a
    /// two-finding set — and a stale acknowledgment then covers a widening
    /// nobody approved.
    #[test]
    fn a_crafted_path_cannot_forge_the_canonical_form_of_two_findings() {
        let smuggled = Finding {
            kind: "route_added_open",
            severity: Severity::Widening,
            method: "GET".to_owned(),
            path: "/a\tabsent\tpublic\nroute_added_open\tGET\t/admin".to_owned(),
            before: "absent".to_owned(),
            after: "public".to_owned(),
            fingerprint: "added:public".to_owned(),
            detail: String::new(),
        };
        let plain_a = Finding {
            path: "/a".to_owned(),
            ..smuggled.clone()
        };
        let plain_b = Finding {
            path: "/admin".to_owned(),
            ..smuggled.clone()
        };
        assert_ne!(
            smuggled.canonical(),
            format!("{}\n{}", plain_a.canonical(), plain_b.canonical()),
            "a tab or newline inside a field must not read as a field separator"
        );
        assert!(
            !smuggled.canonical().contains('\n'),
            "the canonical form of one finding is one line"
        );
    }

    /// A manifest should never carry the same `(path, method)` twice, but "should
    /// never" is not a guarantee about a file on disk. If the last entry won,
    /// the verdict would depend on array order — and the order that hides a
    /// public route would be the one that passes.
    #[test]
    fn a_duplicate_route_key_merges_to_the_most_open_posture_either_way() {
        let base = routes_only(&route("/a", "GET", "gated", &["admin"], &[], false));
        let gated = route("/a", "GET", "gated", &["admin"], &[], false);
        let public = route("/a", "GET", "public", &[], &[], false);

        let gated_first = routes_only(&format!("{gated},{public}"));
        let public_first = routes_only(&format!("{public},{gated}"));

        for head in [&gated_first, &public_first] {
            let f = only(diff(&base, head));
            assert_eq!(
                f.kind, "classification_downgraded",
                "a duplicate key must not let the open entry hide behind the gated one"
            );
        }
        assert_eq!(diff(&base, &gated_first), diff(&base, &public_first));
    }

    /// Two duplicate `gated` entries differing only in roles must not let array
    /// order decide: an empty role list admits every authenticated session,
    /// so it is the wider of the two and has to win either way.
    #[test]
    fn a_duplicate_route_key_merges_roles_too() {
        let base = routes_only(&route("/a", "GET", "gated", &["admin"], &[], false));
        let with_role = route("/a", "GET", "gated", &["admin"], &[], false);
        let no_roles = route("/a", "GET", "gated", &[], &[], false);

        let role_first = routes_only(&format!("{with_role},{no_roles}"));
        let none_first = routes_only(&format!("{no_roles},{with_role}"));

        for head in [&role_first, &none_first] {
            let f = only(diff(&base, head));
            assert_eq!(
                f.kind, "roles_cleared",
                "the entry admitting every authenticated session must win"
            );
            assert_eq!(f.severity, Severity::Widening);
        }
        assert_eq!(diff(&base, &role_first), diff(&base, &none_first));
    }

    /// The router matches on shape, not on what the author called a capture:
    /// `/users/{id}` and `/users/{user_id}` accept the same URLs. Keying on the
    /// raw string let a rename read as one route removed (narrowing) plus one
    /// guarded route added (neutral) — so renaming the capture in the same
    /// change that loosened the guard slipped the widening past entirely.
    #[test]
    fn renaming_a_capture_does_not_hide_a_loosened_guard() {
        let base = routes_only(&route(
            "/users/{id}",
            "GET",
            "gated",
            &["admin"],
            &[],
            false,
        ));
        let head = routes_only(&route("/users/{user_id}", "GET", "public", &[], &[], false));

        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "classification_downgraded");
        assert_eq!(f.severity, Severity::Widening);
    }

    /// A pure rename, with the guard untouched, is not a change at all.
    #[test]
    fn renaming_a_capture_alone_produces_no_finding() {
        let base = routes_only(&route("/a/{id}", "GET", "gated", &["admin"], &[], false));
        let head = routes_only(&route("/a/{ident}", "GET", "gated", &["admin"], &[], false));
        assert!(diff(&base, &head).is_empty());
    }

    /// Capture *kinds* still differ: one segment is not the rest of the path,
    /// so those are genuinely different URL sets and must not collapse.
    #[test]
    fn a_segment_capture_and_a_wildcard_are_not_the_same_route() {
        let base = routes_only(&route("/f/{name}", "GET", "gated", &["admin"], &[], false));
        let head = routes_only(&route("/f/{*rest}", "GET", "public", &[], &[], false));

        let findings = diff(&base, &head);
        assert!(
            findings.iter().any(|f| f.kind == "route_added_open"),
            "the wildcard is a new, wider route, not an edit of the old one: {findings:?}"
        );
    }

    /// The router matches a static segment before a dynamic one and mounts
    /// both — `/users/me` beside `/users/{id}` is not a conflict, per the
    /// conflict matrix in `router.rs`. So deleting the gated static route does
    /// not remove the URL; it hands it to the public dynamic one. Read as a
    /// plain removal, that is a *narrowing*, and authentication vanishes from
    /// `/users/me` with nothing to acknowledge.
    #[test]
    fn removing_a_route_that_a_public_one_still_covers_is_a_widening() {
        let public_by_id = route("/users/{id}", "GET", "public", &[], &[], false);
        let gated_me = route("/users/me", "GET", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{public_by_id},{gated_me}"));
        let head = routes_only(&public_by_id);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_shadow_exposed");
        assert_eq!(widening[0].path, "/users/me");
        assert!(
            widening[0].detail.contains("/users/{id}"),
            "the finding must name the route that now serves the URL: {:?}",
            widening[0]
        );
    }

    /// A path is a node, not a set of routes. Autumn groups every method at
    /// one path into a single `MethodRouter`, so while any method is mounted
    /// there the path answers 405 for the rest. Delete the *last* route at
    /// `/users/me` and the node goes with it — `POST /users/me`, previously a
    /// 405, now reaches the public `POST /users/{id}`. Filtering by method
    /// intersection first skipped that entirely.
    #[test]
    fn removing_the_last_route_at_a_path_exposes_its_other_methods() {
        let removed = route("/users/me", "GET", "gated", &["user"], &[], false);
        let survivor = route("/users/{id}", "POST", "public", &[], &[], false);
        let base = routes_only(&format!("{removed},{survivor}"));
        let head = routes_only(&survivor);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_path_exposed");
        assert!(widening[0].method.contains("POST"), "{:?}", widening[0]);
    }

    /// Newly reachable but *guarded* is the same verdict as a new gated route:
    /// annotate, do not block.
    #[test]
    fn a_guarded_survivor_taking_a_vanished_path_is_not_a_widening() {
        let removed = route("/users/me", "GET", "gated", &["user"], &[], false);
        let survivor = route("/users/{id}", "POST", "gated", &["admin"], &[], false);
        let base = routes_only(&format!("{removed},{survivor}"));
        let head = routes_only(&survivor);

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "{:#?}",
            diff(&base, &head)
        );
    }

    /// Pairwise domination is not per-URL domination. Removing gated
    /// `/records/me/{id}`, the guarded `/records/{user}/private` wins only
    /// `/records/me/private` — every other `/records/me/*` goes to the public
    /// `/records/{user}/{id}`. Dropping a candidate because *some* other
    /// candidate outranks it discarded the public fallback entirely.
    #[test]
    fn a_taker_that_keeps_part_of_the_urls_is_not_dominated() {
        let removed = route("/records/me/{id}", "GET", "gated", &["user"], &[], false);
        let narrow = route(
            "/records/{user}/private",
            "GET",
            "gated",
            &["user"],
            &[],
            false,
        );
        let public_rest = route("/records/{user}/{id}", "GET", "public", &[], &[], false);

        let base = routes_only(&format!("{removed},{narrow},{public_rest}"));
        let head = routes_only(&format!("{narrow},{public_rest}"));

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_shadow_exposed");
        assert!(
            widening[0].detail.contains("/records/{user}/{id}"),
            "the public route takes every URL the narrow one does not: {:?}",
            widening[0]
        );
    }

    /// While *any* method stays mounted at a path, that path node answers the
    /// request — with a 405 — rather than letting it fall through. Removing
    /// `GET /users/me` beside a surviving `POST /users/me` exposes nothing.
    #[test]
    fn a_surviving_method_at_the_same_path_blocks_the_fallthrough() {
        let removed = route("/users/me", "GET", "gated", &["user"], &[], false);
        let same_path = route("/users/me", "POST", "gated", &["user"], &[], false);
        let dynamic = route("/users/{id}", "GET", "public", &[], &[], false);

        let base = routes_only(&format!("{removed},{same_path},{dynamic}"));
        let head = routes_only(&format!("{same_path},{dynamic}"));

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "the path node still answers, with a 405: {findings:#?}"
        );
    }

    /// Newly reachable but guarded annotates — which is what the function and
    /// the guide both say, and what the code did not do: it dropped the change
    /// entirely rather than reporting it as neutral.
    #[test]
    fn a_guarded_route_inheriting_a_vanished_path_is_annotated() {
        let removed = route("/users/me", "GET", "gated", &["user"], &[], false);
        let survivor = route("/users/{id}", "POST", "gated", &["admin"], &[], false);
        let base = routes_only(&format!("{removed},{survivor}"));
        let head = routes_only(&survivor);

        let findings = diff(&base, &head);
        assert!(widening(&findings).is_empty(), "{findings:#?}");
        let exposed = findings
            .iter()
            .find(|f| f.kind == "route_path_exposed")
            .expect("newly reachable, so it is reported");
        assert_eq!(exposed.severity, Severity::Neutral);
    }

    /// A route that another taker outranks never receives the URL, so it is not
    /// the fall-through target. `/records/me/{id}` wins `/records/me/private`
    /// over `/records/{user}/private`, so the latter being public exposes
    /// nothing.
    #[test]
    fn a_survivor_outranked_by_another_taker_is_not_the_fallthrough() {
        let gated = |path: &str| route(path, "GET", "gated", &["user"], &[], false);
        let removed = gated("/records/me/private");
        let wins = gated("/records/me/{id}");
        let public_loser = route("/records/{user}/private", "GET", "public", &[], &[], false);

        let base = routes_only(&format!("{removed},{wins},{public_loser}"));
        let head = routes_only(&format!("{wins},{public_loser}"));

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "the public route never sees that URL: {:#?}",
            diff(&base, &head)
        );
    }

    /// Several routes can take a deleted route's URLs, and precedence sends
    /// different URLs to different ones. Accepting the check from *any* of them
    /// suppressed the finding when the route that actually wins does not carry
    /// it: removing bound `/records/me/private`, `/records/me/{id}` wins over
    /// `/records/{user}/private`, so a check only the latter performs is gone
    /// from the URLs that matter.
    #[test]
    fn a_binding_only_some_takers_perform_is_still_a_widening() {
        let gated = |path: &str| route(path, "GET", "gated", &["user"], &[], true);
        let binding = |path: &str| {
            format!(
                r#"{{"path":"{path}","method":"GET","action":"read_self","resource":"Record"}}"#
            )
        };
        let removed = gated("/records/me/private");
        let wins = gated("/records/me/{id}");
        let also_takes = gated("/records/{user}/private");

        let base = manifest(
            &format!("{removed},{wins},{also_takes}"),
            "",
            "",
            &format!(
                "{},{}",
                binding("/records/me/private"),
                // Only the route that does *not* win carries the same check.
                binding("/records/{user}/private")
            ),
        );
        let head = manifest(
            &format!("{wins},{also_takes}"),
            "",
            "",
            &binding("/records/{user}/private"),
        );

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "authorization_binding_removed");
    }

    /// A widening's identity is the route's whole posture at head, not the one
    /// dimension that moved. Three ways the same gap shows up, one per
    /// dimension a reviewer could see loosened *after* acknowledging:
    ///
    /// - roles widen while a scope is added, then the scope goes;
    /// - a scope is dropped while roles narrow, then the roles come back;
    /// - a new public route enforces CSRF, then stops.
    ///
    /// In each the base-to-head diff still contains only the original finding,
    /// so a per-dimension fingerprint never moved and the old marker stood.
    #[test]
    fn a_widening_acknowledgment_binds_to_the_whole_posture_at_head() {
        let admin_read = route("/a", "POST", "gated", &["admin"], &["read"], false);

        let roles_then = |scopes: &[&str]| {
            let head = route("/a", "POST", "gated", &["admin", "editor"], scopes, false);
            diff(&routes_only(&admin_read), &routes_only(&head))
                .into_iter()
                .find(|f| f.kind == "roles_widened")
                .expect("admitting editor is a widening")
                .canonical()
        };
        assert_ne!(
            roles_then(&["read", "mfa"]),
            roles_then(&["read"]),
            "editor behind `mfa` is not editor without it"
        );

        let scopes_then = |roles: &[&str]| {
            let head = route("/a", "POST", "gated", roles, &[], false);
            diff(&routes_only(&admin_read), &routes_only(&head))
                .into_iter()
                .find(|f| f.kind == "scopes_widened")
                .expect("losing `read` is a widening")
                .canonical()
        };
        assert_ne!(
            scopes_then(&["admin"]),
            scopes_then(&["admin", "editor"]),
            "dropping the scope for admins is not dropping it for editors too"
        );

        let added_with_csrf = |enforced: bool| {
            let head = route("/new", "POST", "public", &[], &[], false);
            let entry = format!(
                r#"{{"path":"/new","method":"POST","csrf_enforced":{enforced},"exempt":false}}"#
            );
            diff(&routes_only(""), &manifest(&head, &entry, "", ""))
                .into_iter()
                .find(|f| f.kind == "route_added_open")
                .expect("a new public route is a widening")
                .canonical()
        };
        assert_ne!(
            added_with_csrf(true),
            added_with_csrf(false),
            "a new public POST with CSRF is not the same endpoint without it"
        );
    }

    /// The router picks the most specific *node* and then dispatches the
    /// method there — it does not skip a node because that node lacks the
    /// method. Removing `POST /users/me/42` while `HEAD /users/me/{id}` and a
    /// public `POST /users/{*rest}` survive is a 405 at the specific node, not
    /// a fall-through to the catch-all; filtering by method before ranking
    /// dropped the node that answers and blamed the one that never sees it.
    #[test]
    fn a_more_specific_node_returns_405_rather_than_yielding_to_a_catch_all() {
        let removed = route("/users/me/42", "POST", "gated", &["user"], &[], false);
        let specific = route("/users/me/{id}", "HEAD", "gated", &["user"], &[], false);
        let catch_all = route("/users/{*rest}", "POST", "public", &[], &[], false);

        let base = routes_only(&format!("{removed},{specific},{catch_all}"));
        let head = routes_only(&format!("{specific},{catch_all}"));

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "the specific node answers that URL, with a 405: {findings:#?}"
        );
    }

    /// The CSRF loss has to name the route that inherits the URL, not the one
    /// that left. A `WS`→`GET` replacement is found through `takers`, but the
    /// guard posture was looked up under the departed `WS` key and came back
    /// empty — so a later push could weaken the replacement without moving the
    /// digest.
    #[test]
    fn a_transferred_csrf_loss_fingerprints_the_route_that_inherits_it() {
        let base = manifest(
            &route("/x", "WS", "gated", &["admin"], &[], false),
            r#"{"path":"/x","method":"WS","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let replaced_by = |scopes: &[&str]| {
            diff(
                &base,
                &manifest(
                    &route("/x", "GET", "gated", &["admin"], scopes, false),
                    "",
                    "",
                    "",
                ),
            )
            .into_iter()
            .find(|f| f.kind == "csrf_enforcement_removed")
            .expect("the lost CSRF is a widening")
            .canonical()
        };

        assert_ne!(replaced_by(&["mfa"]), replaced_by(&[]));
    }

    /// A `WS` route and a `GET` route at one path are the same runtime handler,
    /// and the csrf rows are keyed by the *declared* method. Replacing an
    /// enforced `WS /x` with a `GET /x` that does not enforce left the base row
    /// under a key the head does not have, and the exact-key disappearance
    /// check skipped it — while the route diff saw an equally guarded
    /// replacement, so nothing reported the lost CSRF at all.
    #[test]
    fn csrf_lost_when_a_ws_route_becomes_a_get_is_still_a_widening() {
        let base = manifest(
            &route("/x", "WS", "gated", &["user"], &[], false),
            r#"{"path":"/x","method":"WS","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let head = manifest(
            &route("/x", "GET", "gated", &["user"], &[], false),
            "",
            "",
            "",
        );

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "csrf_enforcement_removed");
    }

    /// And the CSRF acknowledgment binds to what still guards the route, like
    /// every other dimension: losing CSRF behind a new `mfa` scope is not the
    /// same decision as losing it with the scope gone again.
    #[test]
    fn a_csrf_acknowledgment_binds_to_what_still_guards_the_route() {
        let entry = |enforced: bool| {
            format!(
                r#"{{"path":"/pay","method":"POST","csrf_enforced":{enforced},"exempt":false}}"#
            )
        };
        let base = manifest(
            &route("/pay", "POST", "gated", &["admin"], &[], false),
            &entry(true),
            "",
            "",
        );
        let guarded_by = |scopes: &[&str]| {
            diff(
                &base,
                &manifest(
                    &route("/pay", "POST", "gated", &["admin"], scopes, false),
                    &entry(false),
                    "",
                    "",
                ),
            )
            .into_iter()
            .find(|f| f.kind == "csrf_enforcement_removed")
            .expect("losing CSRF is a widening")
            .canonical()
        };

        assert_ne!(guarded_by(&["mfa"]), guarded_by(&[]));
    }

    /// A policy acknowledgment has the same duty. Removing the record check
    /// while adding an `mfa` scope is a widening the reviewer weighs against
    /// what still guards the route; dropping `mfa` later leaves the same
    /// finding with a constant fingerprint, so the old marker covered a route
    /// less constrained than the one that was reviewed.
    #[test]
    fn a_policy_acknowledgment_binds_to_what_still_guards_the_route() {
        let base = routes_only(&route("/a", "PUT", "gated", &["user"], &[], true));
        let guarded_by = |scopes: &[&str]| {
            diff(
                &base,
                &routes_only(&route("/a", "PUT", "gated", &["user"], scopes, false)),
            )
            .into_iter()
            .find(|f| f.kind == "policy_removed")
            .expect("losing the record check is a widening")
            .canonical()
        };

        assert_ne!(guarded_by(&["mfa"]), guarded_by(&[]));
    }

    /// The acknowledgment digest keys on the same shape everything else does.
    /// A capture rename is not a posture change, so it must not re-block a
    /// widening a reviewer has already approved.
    #[test]
    fn renaming_a_capture_does_not_invalidate_an_acknowledgment() {
        let widened = |path: &str| {
            let base = routes_only(&route(path, "GET", "gated", &["admin"], &[], false));
            let head = routes_only(&route(
                path,
                "GET",
                "gated",
                &["admin", "editor"],
                &[],
                false,
            ));
            only(diff(&base, &head)).canonical()
        };

        assert_eq!(widened("/users/{id}"), widened("/users/{user_id}"));
    }

    /// A scope acknowledgment has to bind to the constraint that replaced the
    /// one it approved. Going from `{read}` to `{mfa}` is a widening whose
    /// fingerprint named only the lost `read`; a later push dropping `mfa`
    /// leaves the route requiring no scope at all, and neither the finding nor
    /// the digest moved, so the acknowledgment for one covered the other.
    #[test]
    fn a_scope_acknowledgment_binds_to_the_scope_that_replaced_it() {
        let base = routes_only(&route("/a", "GET", "gated", &["user"], &["read"], false));
        let now_requiring = |scopes: &[&str]| {
            diff(
                &base,
                &routes_only(&route("/a", "GET", "gated", &["user"], scopes, false)),
            )
            .into_iter()
            .find(|f| f.kind == "scopes_widened")
            .expect("losing `read` is a widening")
            .canonical()
        };

        assert_ne!(
            now_requiring(&["mfa"]),
            now_requiring(&[]),
            "acknowledging a swap to `mfa` must not authorize dropping it too"
        );
    }

    /// The replacement checks must come from the route that actually serves
    /// the URL. Collecting them from every overlapping route let a losing
    /// dynamic route's bindings mask the winner's: with `/records/{id}`
    /// carrying both `read_any` and `read_all`, the flattened set never moved
    /// when the exact route swapped one for the other.
    #[test]
    fn replacement_checks_come_only_from_the_route_that_serves_the_url() {
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let losing = format!(
            "{},{}",
            binding("/records/{id}", "read_any"),
            binding("/records/{id}", "read_all")
        );
        let base = manifest(
            &format!("{me},{by_id}"),
            "",
            "",
            &format!("{},{losing}", binding("/records/me", "read_self")),
        );
        let swapped_to = |action: &str| {
            diff(
                &base,
                &manifest(
                    &format!("{me},{by_id}"),
                    "",
                    "",
                    &format!("{},{losing}", binding("/records/me", action)),
                ),
            )
            .into_iter()
            .find(|f| f.kind == "authorization_binding_removed" && f.path == "/records/me")
            .expect("losing `read_self` is a widening")
            .canonical()
        };

        assert_ne!(swapped_to("read_any"), swapped_to("read_all"));
    }

    /// The reverse of the guarded-`GET` case, and it happens *inside* one path
    /// node. A `GET` answers `HEAD` by fallback until an explicit `HEAD` is
    /// mounted beside it, so adding an editor-only `HEAD /x` beside an
    /// admin-only `GET /x` hands that method to editors. Stopping at "the node
    /// already exists" made it a neutral new handler.
    #[test]
    fn an_explicit_head_takes_the_fallback_from_a_get_at_the_same_path() {
        let get = route("/x", "GET", "gated", &["admin"], &[], false);
        let head_route = route("/x", "HEAD", "gated", &["editor"], &[], false);
        let base = routes_only(&get);
        let head = routes_only(&format!("{get},{head_route}"));

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_added_shadowing");
    }

    /// And the same trade in the other direction: removing the explicit `HEAD`
    /// hands that method back to the `GET`'s fallback.
    #[test]
    fn removing_an_explicit_head_hands_it_to_the_get_at_the_same_path() {
        let get = route("/x", "GET", "gated", &["editor"], &[], false);
        let head_route = route("/x", "HEAD", "gated", &["admin"], &[], false);
        let base = routes_only(&format!("{get},{head_route}"));
        let head = routes_only(&get);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_shadow_exposed");
    }

    /// A path node the base already mounts owns that URL for every method, so
    /// adding another method there displaces nothing — it is an ordinary new
    /// guarded handler on a node that was already answering.
    #[test]
    fn adding_a_method_to_an_existing_path_node_displaces_nothing() {
        let existing = route("/users/me", "POST", "gated", &["user"], &[], false);
        let dynamic = route("/users/{id}", "GET", "gated", &["admin"], &[], false);
        let added = route("/users/me", "GET", "gated", &["editor"], &[], false);

        let base = routes_only(&format!("{existing},{dynamic}"));
        let head = routes_only(&format!("{existing},{dynamic},{added}"));

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "the node already owned that URL: {findings:#?}"
        );
    }

    /// And the binding dimension stops at a surviving node too: removing a
    /// bound `GET /records/me` while `POST /records/me` stays mounted makes
    /// that URL a 405, not a fall-through.
    #[test]
    fn a_binding_does_not_fall_through_a_surviving_path_node() {
        let bound = route("/records/me", "GET", "gated", &["user"], &[], true);
        let same_path = route("/records/me", "POST", "gated", &["user"], &[], true);
        let dynamic = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let binding =
            r#"{"path":"/records/me","method":"GET","action":"read","resource":"Record"}"#;

        let base = manifest(&format!("{bound},{same_path},{dynamic}"), "", "", binding);
        let head = manifest(&format!("{same_path},{dynamic}"), "", "", "");

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "`GET /records/me` is not reachable at all now: {findings:#?}"
        );
    }

    /// The replacement binding matters when the route *stays* mounted too. A
    /// route that swaps `read_self` for `read_any` keeps its key, so nothing
    /// fell through — and with the replacement left out of the fingerprint, a
    /// later push to `read_all` moved neither the removal finding nor the
    /// digest, and the acknowledgment for `read_any` still stood.
    #[test]
    fn an_exact_route_acknowledgment_binds_to_its_replacement_check() {
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let binding = |action: &str| {
            format!(
                r#"{{"path":"/records/{{id}}","method":"GET","action":"{action}","resource":"Record"}}"#
            )
        };
        let base = manifest(&by_id, "", "", &binding("read_self"));
        let replaced_by = |action: &str| {
            diff(&base, &manifest(&by_id, "", "", &binding(action)))
                .into_iter()
                .find(|f| f.kind == "authorization_binding_removed")
                .expect("losing `read_self` is a widening")
                .canonical()
        };

        assert_ne!(replaced_by("read_any"), replaced_by("read_all"));
    }

    /// Ranking reaches the binding displacement too: a base route that never
    /// served the URL cannot have its check "lost" by the route that takes it.
    #[test]
    fn a_displaced_binding_is_compared_against_the_prior_winner() {
        let gated = |path: &str| route(path, "GET", "gated", &["user"], &[], true);
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let prior_owner = gated("/records/me/{id}");
        let never_served = gated("/records/{user}/private");
        let added = gated("/records/me/private");

        let base = manifest(
            &format!("{prior_owner},{never_served}"),
            "",
            "",
            &format!(
                "{},{}",
                binding("/records/me/{id}", "read_self"),
                binding("/records/{user}/private", "read_other")
            ),
        );
        let head = manifest(
            &format!("{prior_owner},{never_served},{added}"),
            "",
            "",
            &format!(
                "{},{},{}",
                binding("/records/me/{id}", "read_self"),
                binding("/records/{user}/private", "read_other"),
                // The new route carries the check the prior owner performed.
                binding("/records/me/private", "read_self")
            ),
        );

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "`read_other` never applied to that URL: {findings:#?}"
        );
    }

    /// The round-15 lesson, retrofitted to the binding findings. An
    /// acknowledgment of a fall-through says "I accept that this URL is now
    /// checked by *that* instead" — so weakening what it is now checked by has
    /// to invalidate it. The survivor is absent from the base, so its binding
    /// reads only as an addition, and a fingerprint naming the lost check alone
    /// left the digest unmoved.
    #[test]
    fn a_fallthrough_acknowledgment_binds_to_the_checks_that_replace_it() {
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let base = manifest(
            &format!("{me},{by_id}"),
            "",
            "",
            &format!(
                "{},{}",
                binding("/records/me", "read_self"),
                binding("/records/{id}", "read_any")
            ),
        );
        let lost_to = |action: &str| {
            diff(
                &base,
                &manifest(&by_id, "", "", &binding("/records/{id}", action)),
            )
            .into_iter()
            .find(|f| f.kind == "authorization_binding_removed" && f.path == "/records/me")
            .expect("the fall-through is a widening")
            .canonical()
        };

        assert_ne!(
            lost_to("read_any"),
            lost_to("read_weak"),
            "acknowledging a fall-through to `read_any` must not authorize one to `read_weak`"
        );
    }

    /// And the displacement side, which has the same shape.
    #[test]
    fn a_displaced_binding_acknowledgment_binds_to_the_replacing_checks() {
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let base = manifest(&by_id, "", "", &binding("/records/{id}", "read_self"));
        let displaced_by = |action: &str| {
            diff(
                &base,
                &manifest(
                    &format!("{by_id},{me}"),
                    "",
                    "",
                    &format!(
                        "{},{}",
                        binding("/records/{id}", "read_self"),
                        binding("/records/me", action)
                    ),
                ),
            )
            .into_iter()
            .find(|f| f.kind == "authorization_binding_displaced")
            .expect("the displacement is a widening")
            .canonical()
        };

        assert_ne!(displaced_by("read_any"), displaced_by("read_weak"));
    }

    /// The same explicit-`HEAD` lesson, in the binding dimension. With base
    /// `GET /x` (bound) and `HEAD /x` both mounted, deleting only the `GET`
    /// takes its URL away — the explicit `HEAD` owned `HEAD` all along and
    /// gains nothing. Reading the alias unconditionally reported the binding as
    /// lost from a still-reachable URL and blocked.
    #[test]
    fn a_binding_removed_beside_an_explicit_head_is_not_a_widening() {
        let get = route("/x", "GET", "gated", &["user"], &[], true);
        let head_route = route("/x", "HEAD", "gated", &["user"], &[], true);
        let binding = r#"{"path":"/x","method":"GET","action":"read","resource":"Thing"}"#;
        let base = manifest(&format!("{get},{head_route}"), "", "", binding);
        let head = manifest(&head_route, "", "", "");

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "the GET URL left with the route: {findings:#?}"
        );
    }

    /// Narrowing an exemption is not adding one. Every URL `/api/private`
    /// exempts was already exempt under `/api`, so replacing the broad prefix
    /// with the narrow one restores CSRF for most of `/api` — a literal set
    /// difference called the new spelling a widening and blocked it.
    #[test]
    fn narrowing_a_csrf_exemption_prefix_is_not_a_widening() {
        let route = route("/api/{rest}", "POST", "gated", &["user"], &[], false);
        let entry = r#"{"path":"/api/{rest}","method":"POST","csrf_enforced":false,"exempt":true}"#;
        let base = manifest_exempt(&route, entry, &["/api"]);
        let head = manifest_exempt(&route, entry, &["/api/private"]);

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "every URL still exempt was already exempt: {findings:#?}"
        );
        assert!(
            findings.iter().any(|f| f.kind == "csrf_exemption_removed"),
            "and the narrowing is still reported: {findings:#?}"
        );
    }

    /// Broadening one still blocks.
    #[test]
    fn broadening_a_csrf_exemption_prefix_is_a_widening() {
        let route = route("/api/{rest}", "POST", "gated", &["user"], &[], false);
        let entry = r#"{"path":"/api/{rest}","method":"POST","csrf_enforced":false,"exempt":true}"#;
        let base = manifest_exempt(&route, entry, &["/api/private"]);
        let head = manifest_exempt(&route, entry, &["/api"]);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "csrf_exemption_added");
    }

    /// An exemption prefix is the one CSRF widening the per-route entries
    /// cannot show. `path_is_exempt` compares the route *template*, so
    /// `/users/{id}` stays `enforced` in the manifest, while the runtime
    /// compares the concrete request path and skips CSRF for `POST /users/me`.
    /// With `exempt_paths` dropped on parse, neither the digest nor the diff
    /// moved at all.
    #[test]
    fn adding_a_csrf_exemption_prefix_is_a_widening() {
        let route = route("/users/{id}", "POST", "gated", &["user"], &[], false);
        let entry = r#"{"path":"/users/{id}","method":"POST","csrf_enforced":true,"exempt":false}"#;
        let base = manifest_exempt(&route, entry, &[]);
        let head = manifest_exempt(&route, entry, &["/users/me"]);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "csrf_exemption_added");
        assert!(
            widening[0].detail.contains("/users/me"),
            "{:?}",
            widening[0]
        );
    }

    /// Withdrawing one protects more, so it annotates rather than blocks.
    #[test]
    fn removing_a_csrf_exemption_prefix_is_a_narrowing() {
        let route = route("/users/{id}", "POST", "gated", &["user"], &[], false);
        let entry = r#"{"path":"/users/{id}","method":"POST","csrf_enforced":true,"exempt":false}"#;
        let base = manifest_exempt(&route, entry, &["/users/me"]);
        let head = manifest_exempt(&route, entry, &[]);

        let findings = diff(&base, &head);
        assert_eq!(
            kinds(&findings),
            vec!["csrf_exemption_removed"],
            "{findings:#?}"
        );
        assert!(widening(&findings).is_empty());
    }

    /// An explicit `HEAD` handler is kept by axum even when a `GET` is mounted
    /// at the same path — the `GET`'s automatic `HEAD` support is a *fallback*,
    /// not a takeover. Treating the alias as unconditional made a new guarded
    /// `GET` displace an explicit `HEAD` that keeps answering exactly as before.
    #[test]
    fn a_new_get_does_not_displace_an_explicit_head() {
        let explicit_head = route("/x", "HEAD", "gated", &["admin"], &[], false);
        let added_get = route("/x", "GET", "gated", &["editor"], &[], false);
        let base = routes_only(&explicit_head);
        let head = routes_only(&format!("{explicit_head},{added_get}"));

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "the explicit HEAD still answers HEAD: {findings:#?}"
        );
    }

    /// A displacement can change the record-level check without moving
    /// anything the route comparison sees: same roles, both `policy: true`,
    /// and the binding differ sees only an *added* binding, which is a
    /// narrowing. The URLs `/records/me` took over went from `read_self` to
    /// `read_any` all the same.
    #[test]
    fn a_binding_displaced_by_a_more_specific_route_is_a_widening() {
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let base = manifest(&by_id, "", "", &binding("/records/{id}", "read_self"));
        let head = manifest(
            &format!("{by_id},{me}"),
            "",
            "",
            &format!(
                "{},{}",
                binding("/records/{id}", "read_self"),
                binding("/records/me", "read_any")
            ),
        );

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "authorization_binding_displaced");
        assert!(
            widening[0].detail.contains("read_self"),
            "{:?}",
            widening[0]
        );
    }

    /// The same check carried onto the new route changes nothing.
    #[test]
    fn a_binding_carried_onto_the_displacing_route_is_not_a_widening() {
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str| {
            format!(
                r#"{{"path":"{path}","method":"GET","action":"read_self","resource":"Record"}}"#
            )
        };
        let base = manifest(&by_id, "", "", &binding("/records/{id}"));
        let head = manifest(
            &format!("{by_id},{me}"),
            "",
            "",
            &format!("{},{}", binding("/records/{id}"), binding("/records/me")),
        );

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "{:#?}",
            diff(&base, &head)
        );
    }

    /// The mirror of the removal case. Adding a route that is *more specific*
    /// than an existing one takes that route's requests over: with a base
    /// `/users/{id}` restricted to `admin`, a new `/users/me` restricted to
    /// `editor` wins `/users/me` outright, and editors reach what needed
    /// `admin` a moment ago. The dynamic entry never moved, so the new route
    /// was filed as a neutral `route_added_gated` and nothing blocked.
    #[test]
    fn adding_a_more_specific_route_that_admits_more_is_a_widening() {
        let by_id = route("/users/{id}", "GET", "gated", &["admin"], &[], false);
        let me = route("/users/me", "GET", "gated", &["editor"], &[], false);
        let base = routes_only(&by_id);
        let head = routes_only(&format!("{by_id},{me}"));

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_added_shadowing");
        assert_eq!(widening[0].path, "/users/me");
        assert!(
            widening[0].detail.contains("/users/{id}"),
            "the finding must name the route whose requests it takes: {:?}",
            widening[0]
        );
    }

    /// Ranking applies to the displacement side too: what a new route takes
    /// over is whatever *was* serving those URLs, which is the most specific
    /// base route overlapping them. Comparing against every overlapping base
    /// route blamed a stricter handler that never served the URL.
    #[test]
    fn a_displacement_compares_against_the_route_that_was_serving_the_url() {
        let prior_owner = route("/records/me/{id}", "GET", "gated", &["user"], &[], false);
        let never_served = route(
            "/records/{user}/private",
            "GET",
            "gated",
            &["admin"],
            &[],
            false,
        );
        let added = route("/records/me/private", "GET", "gated", &["user"], &[], false);

        let base = routes_only(&format!("{prior_owner},{never_served}"));
        let head = routes_only(&format!("{prior_owner},{never_served},{added}"));

        let findings = diff(&base, &head);
        assert!(
            widening(&findings).is_empty(),
            "the route that was serving that URL has the same guard: {findings:#?}"
        );
    }

    /// The same shape, admitting no one new, is the ordinary neutral addition.
    #[test]
    fn adding_a_more_specific_route_with_the_same_guard_is_neutral() {
        let by_id = route("/users/{id}", "GET", "gated", &["admin"], &[], false);
        let me = route("/users/me", "GET", "gated", &["admin"], &[], false);
        let base = routes_only(&by_id);
        let head = routes_only(&format!("{by_id},{me}"));

        let findings = diff(&base, &head);
        assert_eq!(kinds(&findings), vec!["route_added_gated"], "{findings:#?}");
    }

    /// And carving a *guarded* route out of a public one narrows those URLs.
    #[test]
    fn adding_a_guard_over_part_of_a_public_route_is_not_a_widening() {
        let by_id = route("/users/{id}", "GET", "public", &[], &[], false);
        let me = route("/users/me", "GET", "gated", &["admin"], &[], false);
        let base = routes_only(&by_id);
        let head = routes_only(&format!("{by_id},{me}"));

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "{:#?}",
            diff(&base, &head)
        );
    }

    /// Same lesson as the fall-through fingerprint: the acknowledgment binds to
    /// the posture it was given for, on both sides of the displacement.
    #[test]
    fn a_displacement_acknowledgment_does_not_survive_a_looser_route() {
        let by_id = route("/users/{id}", "GET", "gated", &["admin"], &[], false);
        let base = routes_only(&by_id);
        let added_with = |roles: &[&str]| {
            let me = route("/users/me", "GET", "gated", roles, &[], false);
            diff(&base, &routes_only(&format!("{by_id},{me}")))
                .into_iter()
                .find(|f| f.kind == "route_added_shadowing")
                .expect("the displacement is a widening")
                .canonical()
        };

        assert_ne!(added_with(&["editor"]), added_with(&["guest"]));
    }

    /// Overlap is not enough: the router matches a static segment before a
    /// dynamic one, so a surviving `/users/me` was *already* answering that URL
    /// before the gated `/users/{id}` was deleted. Nothing falls through to it;
    /// the deletion only takes the remaining dynamic URLs away. Reporting it
    /// blocked a pull request over an exposure that cannot happen.
    #[test]
    fn a_more_specific_survivor_gains_nothing_and_is_not_exposure() {
        let survivor = route("/users/me", "GET", "public", &[], &[], false);
        let removed = route("/users/{id}", "GET", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{survivor},{removed}"));
        let head = routes_only(&survivor);

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "{:#?}",
            diff(&base, &head)
        );
    }

    /// Precedence decides it position by position, so a survivor that is less
    /// specific only where it matters still gains the overlap. `/a/x/{id}` beat
    /// `/a/{key}/b` at `/a/x/b` while it existed; now it does not.
    #[test]
    fn a_survivor_that_wins_the_overlap_only_after_the_deletion_is_exposure() {
        let survivor = route("/a/{key}/b", "GET", "public", &[], &[], false);
        let removed = route("/a/x/{id}", "GET", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{survivor},{removed}"));
        let head = routes_only(&survivor);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_shadow_exposed");
    }

    /// A binding is the same story: the URLs `/records/{id}` served are gone,
    /// and the static route that survives was already answering its own.
    #[test]
    fn a_binding_whose_urls_left_with_it_is_not_a_widening() {
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let base = manifest(
            &format!("{me},{by_id}"),
            "",
            "",
            &format!(
                "{},{}",
                binding("/records/me", "read_self"),
                binding("/records/{id}", "read_any")
            ),
        );
        let head = manifest(&me, "", "", &binding("/records/me", "read_self"));

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "{:#?}",
            diff(&base, &head)
        );
    }

    /// The survivor has to actually admit more. Deleting a gated route while an
    /// equally gated dynamic route covers it loses no guard.
    #[test]
    fn removing_a_route_a_gated_one_covers_is_not_a_widening() {
        let by_id = route("/users/{id}", "GET", "gated", &["user"], &[], false);
        let me = route("/users/me", "GET", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{by_id},{me}"));
        let head = routes_only(&by_id);

        let findings = diff(&base, &head);
        assert!(widening(&findings).is_empty(), "{findings:#?}");
    }

    /// And a route nothing covers is an ordinary removal.
    #[test]
    fn removing_an_uncovered_route_stays_a_narrowing() {
        let base = routes_only(&format!(
            "{},{}",
            route("/health", "GET", "public", &[], &[], false),
            route("/admin/me", "GET", "gated", &["admin"], &[], false)
        ));
        let head = routes_only(&route("/health", "GET", "public", &[], &[], false));

        let findings = diff(&base, &head);
        assert_eq!(kinds(&findings), vec!["route_removed"], "{findings:#?}");
    }

    /// A catch-all covers everything below it, so deleting a guarded route that
    /// sits under one is the same exposure.
    #[test]
    fn a_catch_all_that_swallows_a_removed_route_is_a_widening() {
        let catch_all = route("/files/{*path}", "GET", "public", &[], &[], false);
        let secret = route("/files/secret", "GET", "gated", &["admin"], &[], false);
        let base = routes_only(&format!("{catch_all},{secret}"));
        let head = routes_only(&catch_all);

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "route_shadow_exposed");
    }

    /// A capture must consume at least one character: `/file.{ext}` never
    /// serves `/file.` — matchit 404s there — so the two segments do not
    /// overlap, while `/file.json` still does. (#2499)
    #[test]
    #[allow(clippy::literal_string_with_formatting_args)]
    fn a_capture_must_consume_a_character_so_a_bare_prefix_does_not_overlap() {
        let ext = normalize_captures("file.{ext}");
        assert!(!segments_overlap(&ext, "file."));
        assert!(!segments_overlap("file.", &ext));
        assert!(segments_overlap(&ext, "file.json"));
        assert!(segments_overlap("file.json", &ext));
    }

    /// The same minimum-length rule flows through `intersect` and `covers`:
    /// `/file.{ext}` and `/file.` share no URL, while `/file.json` is inside
    /// the capture's range. (#2499)
    #[test]
    #[allow(clippy::literal_string_with_formatting_args)]
    fn the_capture_minimum_length_reaches_intersect_and_covers() {
        let ext = normalize_captures("/file.{ext}");
        assert_eq!(intersect(&ext, "/file."), None);
        assert_eq!(intersect("/file.", &ext), None);
        assert!(intersect(&ext, "/file.json").is_some());
        assert!(!covers(&ext, "/file."));
        assert!(covers(&ext, "/file.json"));
    }

    /// Deleting a guarded `/file.` beside a public `/file.{ext}` is not a
    /// shadow exposure: a request for `/file.` 404s against `/file.{ext}`
    /// because the capture must consume a character, so the survivor inherits
    /// no URL the deleted route served. (#2499)
    #[test]
    fn deleting_a_guarded_bare_prefix_beside_a_public_capture_is_not_a_shadow() {
        let survivor = route("/file.{ext}", "GET", "public", &[], &[], false);
        let removed = route("/file.", "GET", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{survivor},{removed}"));
        let head = routes_only(&survivor);

        let findings = diff(&base, &head);
        assert!(
            !findings.iter().any(|f| f.kind == "route_shadow_exposed"),
            "a capture cannot serve the bare prefix: {findings:#?}"
        );
    }

    /// A route's declared method is not the set of requests it answers: the
    /// router mounts `WS` as a plain `GET`, and axum serves `HEAD` through a
    /// `#[get]` handler. So a public `GET /users/{id}` picks up the `HEAD` and
    /// `WS` traffic of a deleted guarded route at the same path, and comparing
    /// declared methods exactly skipped exactly those survivors.
    #[test]
    fn a_survivor_shadows_the_methods_it_actually_answers() {
        for removed_method in ["HEAD", "WS", "GET"] {
            let survivor = route("/users/{id}", "GET", "public", &[], &[], false);
            let guarded = route("/users/me", removed_method, "gated", &["user"], &[], false);
            let base = routes_only(&format!("{survivor},{guarded}"));
            let head = routes_only(&survivor);

            let findings = diff(&base, &head);
            assert!(
                findings.iter().any(|f| f.kind == "route_shadow_exposed"),
                "a GET survivor answers {removed_method} at that URL: {findings:#?}"
            );
        }
    }

    /// A websocket upgrade is not served for `HEAD`. The router says so in
    /// those words — only a genuine `GET` expands, "not the WS→GET alias" — so
    /// folding `WS` to `GET` and *then* adding `HEAD` invented an overlap and
    /// blocked a pull request over traffic the survivor never answers.
    #[test]
    fn a_websocket_survivor_does_not_answer_head() {
        let survivor = route("/live/{id}", "WS", "public", &[], &[], false);
        let guarded = route("/live/me", "HEAD", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{survivor},{guarded}"));
        let head = routes_only(&survivor);

        let findings = diff(&base, &head);
        assert!(
            !findings.iter().any(|f| f.kind == "route_shadow_exposed"),
            "a websocket upgrade is not served for HEAD: {findings:#?}"
        );
    }

    /// An acknowledgment of a fall-through has to bind to the posture it was
    /// given for. When the same pull request removes a guarded route and adds
    /// the route that now covers it, the new route is absent from the base — so
    /// loosening it later is only a neutral `route_added_gated`, and with the
    /// survivor's posture out of the fingerprint the digest never moved and the
    /// old acknowledgment still stood.
    #[test]
    fn a_shadow_acknowledgment_does_not_survive_a_looser_survivor() {
        let base = routes_only(&route("/users/me", "GET", "gated", &["admin"], &[], false));
        let shadowed_by = |roles: &[&str]| {
            let findings = diff(
                &base,
                &routes_only(&route("/users/{id}", "GET", "gated", roles, &[], false)),
            );
            let shadow = findings
                .into_iter()
                .find(|f| f.kind == "route_shadow_exposed")
                .expect("the fall-through is a widening");
            shadow.canonical()
        };

        assert_ne!(
            shadowed_by(&["editor"]),
            shadowed_by(&["guest"]),
            "acknowledging a fall-through to `editor` must not authorize one to `guest`"
        );
    }

    /// The other direction: while the survivor itself is untouched, the digest
    /// must not move. An acknowledgment that a later, unrelated push
    /// invalidates is an escape hatch nobody can use.
    #[test]
    fn a_shadow_fingerprint_survives_an_unrelated_push() {
        let base = routes_only(&route("/users/me", "GET", "gated", &["admin"], &[], false));
        let survivor = route("/users/{id}", "GET", "gated", &["editor"], &[], false);
        let elsewhere = route("/reports", "GET", "gated", &["admin"], &[], false);

        let shadow = |routes: &str| {
            diff(&base, &routes_only(routes))
                .into_iter()
                .find(|f| f.kind == "route_shadow_exposed")
                .expect("the fall-through is a widening")
                .canonical()
        };

        assert_eq!(
            shadow(&survivor),
            shadow(&format!("{survivor},{elsewhere}"))
        );
    }

    /// And a method the survivor genuinely does not answer is not *shadowed* by
    /// it: the deleted `POST` handler has no `GET` successor to inherit its
    /// guard. The path node vanishing is a separate finding, covered by
    /// `removing_the_last_route_at_a_path_exposes_its_other_methods`.
    #[test]
    fn a_survivor_does_not_shadow_a_method_it_never_answers() {
        let survivor = route("/users/{id}", "GET", "public", &[], &[], false);
        let guarded = route("/users/me", "POST", "gated", &["user"], &[], false);
        let base = routes_only(&format!("{survivor},{guarded}"));
        let head = routes_only(&survivor);

        let findings = diff(&base, &head);
        assert!(
            !findings.iter().any(|f| f.kind == "route_shadow_exposed"),
            "{findings:#?}"
        );
    }

    /// The same fall-through, one dimension over. Both routes are `gated` with
    /// a record-level check, so the route comparison sees no widening — but the
    /// URL now resolves to a route that checks something *else*, and the
    /// binding dimension suppressed the loss because the exact route key was
    /// gone.
    #[test]
    fn a_binding_lost_to_fallthrough_is_still_a_widening() {
        let routes = |extra: &str| {
            let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
            if extra.is_empty() {
                by_id
            } else {
                format!("{by_id},{extra}")
            }
        };
        let binding = |path: &str, action: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"{action}","resource":"Record"}}"#)
        };
        let base = manifest(
            &routes(&route("/records/me", "GET", "gated", &["user"], &[], true)),
            "",
            "",
            &format!(
                "{},{}",
                binding("/records/{id}", "read_any"),
                binding("/records/me", "read_self")
            ),
        );
        let head = manifest(&routes(""), "", "", &binding("/records/{id}", "read_any"));

        let findings = diff(&base, &head);
        let widening = widening(&findings);
        assert_eq!(widening.len(), 1, "{findings:#?}");
        assert_eq!(widening[0].kind, "authorization_binding_removed");
        assert!(
            widening[0].detail.contains("read_self"),
            "{:?}",
            widening[0]
        );
    }

    /// But if the route that now serves the URL performs the very same check,
    /// nothing changed for its callers.
    #[test]
    fn a_binding_the_surviving_route_still_performs_is_not_a_widening() {
        let by_id = route("/records/{id}", "GET", "gated", &["user"], &[], true);
        let me = route("/records/me", "GET", "gated", &["user"], &[], true);
        let binding = |path: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"read","resource":"Record"}}"#)
        };
        let base = manifest(
            &format!("{by_id},{me}"),
            "",
            "",
            &format!("{},{}", binding("/records/{id}"), binding("/records/me")),
        );
        let head = manifest(&by_id, "", "", &binding("/records/{id}"));

        assert!(
            widening(&diff(&base, &head)).is_empty(),
            "{:#?}",
            diff(&base, &head)
        );
    }

    /// Axum writes a literal brace as `{{`, so `/{{foo}}` and `/{{bar}}` are two
    /// different URLs and the conflict matrix mounts both. Reading each escape
    /// as a capture collapsed them into one key, so adding a second public
    /// literal-brace route produced no `route_added_open` at all.
    #[test]
    fn escaped_literal_braces_are_not_captures() {
        let foo = route("/{{foo}}", "GET", "public", &[], &[], false);
        let bar = route("/{{bar}}", "GET", "public", &[], &[], false);
        let base = routes_only(&foo);
        let head = routes_only(&format!("{foo},{bar}"));

        let findings = diff(&base, &head);
        assert_eq!(kinds(&findings), vec!["route_added_open"], "{findings:#?}");
        assert_eq!(findings[0].path, "/{{bar}}");
    }

    /// Normalizing the key widens the class of entries that can collide, so
    /// two csrf entries for the same route shape must merge to the *widest*
    /// reading — as duplicate route entries already do — rather than letting
    /// whichever sorts last decide whether the route is protected.
    #[test]
    fn duplicate_csrf_entries_merge_to_the_widest() {
        let routes = route("/pay/{id}", "POST", "gated", &["user"], &[], false);
        let base = manifest(
            &routes,
            r#"{"path":"/pay/{id}","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let off = r#"{"path":"/pay/{id}","method":"POST","csrf_enforced":false,"exempt":true}"#;
        let on = r#"{"path":"/pay/{other}","method":"POST","csrf_enforced":true,"exempt":false}"#;

        for entries in [format!("{off},{on}"), format!("{on},{off}")] {
            let head = manifest(&routes, &entries, "", "");
            let findings = diff(&base, &head);
            assert_eq!(
                kinds(&findings),
                vec!["csrf_enforcement_removed"],
                "one entry says the route is unprotected, so it is: {findings:#?}"
            );
        }
    }

    /// The same rename, one dimension over. CSRF entries were keyed on the raw
    /// path, so renaming the capture in the change that turned CSRF off left
    /// the head entry unable to match the base entry — and the disappearance
    /// check could not save it either, since `routes_after` holds normalized
    /// keys. The result was a payment route losing CSRF with nothing to
    /// acknowledge.
    #[test]
    fn renaming_a_capture_does_not_hide_a_csrf_loss() {
        let base = manifest(
            &route("/pay/{id}", "POST", "gated", &["user"], &[], false),
            r#"{"path":"/pay/{id}","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        let head = manifest(
            &route("/pay/{payment_id}", "POST", "gated", &["user"], &[], false),
            r#"{"path":"/pay/{payment_id}","method":"POST","csrf_enforced":false,"exempt":true}"#,
            "",
            "",
        );

        let findings = diff(&base, &head);
        let f = only(findings.clone());
        assert_eq!(f.kind, "csrf_enforcement_removed");
        assert_eq!(f.severity, Severity::Widening);
        assert_eq!(widening(&findings).len(), 1);
    }

    /// And the same rename with CSRF *untouched* must stay silent: a route
    /// keyed two different ways would otherwise read as one entry lost and one
    /// gained.
    #[test]
    fn renaming_a_capture_alone_is_not_a_csrf_change() {
        let entry = |path: &str| {
            format!(r#"{{"path":"{path}","method":"POST","csrf_enforced":true,"exempt":false}}"#)
        };
        let base = manifest(
            &route("/pay/{id}", "POST", "gated", &["user"], &[], false),
            &entry("/pay/{id}"),
            "",
            "",
        );
        let head = manifest(
            &route("/pay/{payment_id}", "POST", "gated", &["user"], &[], false),
            &entry("/pay/{payment_id}"),
            "",
            "",
        );
        assert!(diff(&base, &head).is_empty(), "{:#?}", diff(&base, &head));
    }

    /// Authorization bindings, third dimension, same key. Here the raw path
    /// cost a false *block* rather than a miss: the binding appeared in both
    /// set differences, so an untouched `#[authorize]` read as a removal.
    #[test]
    fn renaming_a_capture_alone_is_not_an_authorization_change() {
        let binding = |path: &str| {
            format!(r#"{{"path":"{path}","method":"GET","action":"read","resource":"Note"}}"#)
        };
        let base = manifest(
            &route("/notes/{id}", "GET", "gated", &["user"], &[], true),
            "",
            "",
            &binding("/notes/{id}"),
        );
        let head = manifest(
            &route("/notes/{note_id}", "GET", "gated", &["user"], &[], true),
            "",
            "",
            &binding("/notes/{note_id}"),
        );
        assert!(diff(&base, &head).is_empty(), "{:#?}", diff(&base, &head));
    }

    /// Two duplicate entries can be *incomparable*: `["admin"]` and `["editor"]`
    /// neither contains the other, so no ranking of them is principled and one
    /// of the two array orders would hide the newly admitted role. Merging the
    /// sets has no such gap.
    #[test]
    fn incomparable_duplicate_roles_merge_instead_of_racing() {
        let base = routes_only(&route("/a", "GET", "gated", &["admin"], &[], false));
        let admin = route("/a", "GET", "gated", &["admin"], &[], false);
        let editor = route("/a", "GET", "gated", &["editor"], &[], false);

        let admin_first = routes_only(&format!("{admin},{editor}"));
        let editor_first = routes_only(&format!("{editor},{admin}"));

        for head in [&admin_first, &editor_first] {
            let f = only(diff(&base, head));
            assert_eq!(f.kind, "roles_widened");
            assert!(
                f.detail.contains("editor"),
                "the newly admitted role must be named whichever order it appears in: {f:?}"
            );
        }
        assert_eq!(diff(&base, &admin_first), diff(&base, &editor_first));
    }

    /// The same, for the AND-ed dimension: requiring only what both entries
    /// require is the wider reading.
    #[test]
    fn duplicate_scope_sets_merge_to_what_both_require() {
        let base = routes_only(&route(
            "/a",
            "POST",
            "gated",
            &[],
            &["read", "write"],
            false,
        ));
        let read = route("/a", "POST", "gated", &[], &["read"], false);
        let write = route("/a", "POST", "gated", &[], &["write"], false);

        let read_first = routes_only(&format!("{read},{write}"));
        let write_first = routes_only(&format!("{write},{read}"));

        for head in [&read_first, &write_first] {
            let f = only(diff(&base, head));
            assert_eq!(f.kind, "scopes_widened");
            assert_eq!(f.severity, Severity::Widening);
        }
        assert_eq!(diff(&base, &read_first), diff(&base, &write_first));
    }

    /// The acknowledgment digest must describe the *set* of widenings, not the
    /// order the manifest happened to list its entries in.
    #[test]
    fn findings_do_not_depend_on_manifest_entry_order() {
        let base = routes_only(&format!(
            "{},{}",
            route("/a", "GET", "gated", &["admin"], &[], false),
            route("/b", "GET", "gated", &["admin"], &[], false)
        ));
        let forward = routes_only(&format!(
            "{},{}",
            route("/a", "GET", "public", &[], &[], false),
            route("/b", "GET", "public", &[], &[], false)
        ));
        let reversed = routes_only(&format!(
            "{},{}",
            route("/b", "GET", "public", &[], &[], false),
            route("/a", "GET", "public", &[], &[], false)
        ));
        assert_eq!(diff(&base, &forward), diff(&base, &reversed));
    }

    /// Two different sets of routes losing CSRF must not share one
    /// acknowledgment digest — otherwise an ack for the first push silently
    /// covers a later push that disabled CSRF somewhere else entirely.
    #[test]
    fn the_collapsed_csrf_finding_still_identifies_its_routes() {
        let entries = |paths: &[&str], enforced: bool| {
            paths
                .iter()
                .map(|p| {
                    format!(
                        r#"{{"path":"{p}","method":"POST","csrf_enforced":{enforced},"exempt":false}}"#
                    )
                })
                .collect::<Vec<_>>()
                .join(",")
        };
        let first = diff(
            &manifest("", &entries(&["/r0", "/r1", "/r2"], true), "", ""),
            &manifest("", &entries(&["/r0", "/r1", "/r2"], false), "", ""),
        );
        let second = diff(
            &manifest("", &entries(&["/x0", "/x1", "/x2"], true), "", ""),
            &manifest("", &entries(&["/x0", "/x1", "/x2"], false), "", ""),
        );
        assert_eq!(only(first.clone()).kind, "csrf_disabled");
        assert_eq!(only(second.clone()).kind, "csrf_disabled");
        assert_ne!(
            only(first).canonical(),
            only(second).canonical(),
            "different routes, different acknowledgment"
        );
    }

    /// `#[ws]` routes are listed with the synthetic `WS` method on both sides,
    /// so they key up like any other route.
    #[test]
    fn a_websocket_route_is_compared_like_any_other() {
        let base = routes_only(&route("/live", "WS", "gated", &["member"], &[], false));
        let head = routes_only(&route("/live", "WS", "public", &[], &[], false));
        let f = only(diff(&base, &head));
        assert_eq!(f.method, "WS");
        assert_eq!(f.severity, Severity::Widening);
    }

    /// A header key that only one side knows about: added-and-emitted narrows,
    /// and (covered above) vanished-while-emitted widens.
    #[test]
    fn a_header_present_only_in_the_head_manifest_is_reported() {
        let base = manifest("", "", "", "");
        let head = manifest(
            "",
            "",
            r#"{"header":"referrer_policy","value":"no-referrer","emitted":true}"#,
            "",
        );
        let f = only(diff(&base, &head));
        assert_eq!(f.kind, "security_header_added");
        assert_eq!(f.severity, Severity::Narrowing);
    }

    /// A resource rename is a removal plus an addition, and no manifest can tell
    /// it from a real loss — so it still blocks, but the report says why the two
    /// rows belong together.
    #[test]
    fn a_renamed_authorize_resource_blocks_but_explains_the_pairing() {
        let r = route("/posts/{id}", "PUT", "gated", &["user"], &[], true);
        let binding = |resource: &str| {
            format!(
                r#"{{"path":"/posts/{{id}}","method":"PUT","name":"h","action":"update","resource":"{resource}","provenance":"provable"}}"#
            )
        };
        let findings = diff(
            &manifest(&r, "", "", &binding("Post")),
            &manifest(&r, "", "", &binding("Article")),
        );
        let removed = findings
            .iter()
            .find(|f| f.kind == "authorization_binding_removed")
            .expect("still reported");
        assert_eq!(removed.severity, Severity::Widening);
        assert!(
            removed.detail.contains("Article"),
            "the paired addition is named so a rename can be acknowledged in one step: {removed:?}"
        );
    }

    /// **Any** later change to the route's posture re-asks for the
    /// acknowledgment, including one that narrows it.
    ///
    /// This asserted the opposite until the whole-posture binding landed, and
    /// the reversal is deliberate rather than a broken test. The two properties
    /// cannot both hold under a digest compared for equality: an acknowledgment
    /// must not survive a constraint being *removed* after it was given, and
    /// the digest is a function of the head posture alone, so it cannot tell a
    /// constraint that appeared from one that vanished. Something has to give,
    /// and re-asking after a narrowing costs a reviewer one comment on a diff
    /// that shows exactly why, while the alternative loses a widening in
    /// silence.
    ///
    /// Expressing "no wider than what I approved" needs the marker to carry the
    /// approved posture ordinally rather than as a hash — a change to the
    /// acknowledgment format, tracked in #2497.
    #[test]
    fn any_later_posture_change_re_asks_for_the_acknowledgment() {
        let base = routes_only(&route("/admin", "GET", "gated", &["admin"], &[], false));
        let first = routes_only(&route("/admin", "GET", "public", &[], &[], false));
        // The follow-up commit adds a record-level policy check: strictly
        // narrower, and the gate asks again all the same.
        let second = routes_only(&route("/admin", "GET", "public", &[], &[], true));

        let a = only(diff(&base, &first));
        let b = diff(&base, &second)
            .into_iter()
            .find(|f| f.kind == "classification_downgraded")
            .expect("still the same widening");
        assert_ne!(a.canonical(), b.canonical());
    }

    // ── ordering ────────────────────────────────────────────────────────────

    #[test]
    fn widening_findings_are_listed_first_and_ordering_is_deterministic() {
        let base = routes_only(&format!(
            "{},{}",
            route("/keep", "GET", "gated", &["admin"], &[], false),
            route("/gone", "GET", "public", &[], &[], false)
        ));
        let head = routes_only(&format!(
            "{},{}",
            route("/keep", "GET", "public", &[], &[], false),
            route("/new", "GET", "public", &[], &[], false)
        ));
        let findings = diff(&base, &head);
        assert_eq!(findings[0].severity, Severity::Widening);
        assert_eq!(findings.last().unwrap().severity, Severity::Narrowing);
        // Same inputs, same order, every time — and see
        // `findings_do_not_depend_on_manifest_entry_order` for the property
        // that actually matters.
        assert_eq!(findings, diff(&base, &head));
    }
    /// A finding names the route the *base* had. When that route is gone at
    /// head, the whole-posture binding found nothing to fold in — precisely the
    /// case where the reviewer most needs it, because everything about the
    /// route they approved now lives on a different one. `checks_on` already
    /// carried the replacement's `#[authorize]` bindings, so the gap was the
    /// rest of its posture: the replacement could shed a scope afterwards
    /// without moving the digest.
    #[test]
    fn a_transferred_finding_binds_to_the_route_that_inherits_the_urls() {
        let base = manifest(
            &format!(
                "{},{}",
                route("/records/me", "POST", "gated", &["admin"], &[], true),
                route("/records/{id}", "POST", "gated", &["admin"], &[], true),
            ),
            "",
            "",
            r#"{"path":"/records/me","method":"POST","name":"h","action":"read_self","resource":"Record","provenance":"provable"}"#,
        );
        let replacement_requiring = |scopes: &[&str]| {
            diff(
                &base,
                &manifest(
                    &route("/records/{id}", "POST", "gated", &["admin"], scopes, true),
                    "",
                    "",
                    r#"{"path":"/records/{id}","method":"POST","name":"h","action":"read_any","resource":"Record","provenance":"provable"}"#,
                ),
            )
            .into_iter()
            .filter(|f| f.severity == Severity::Widening)
            .map(|f| f.canonical())
            .collect::<Vec<_>>()
        };

        assert_ne!(
            replacement_requiring(&["mfa"]),
            replacement_requiring(&[]),
            "dropping the replacement's scope has to re-ask"
        );
    }

    /// The collapsed CSRF finding names no route, so the whole-posture pass
    /// skips it and its own fingerprint has to carry everything. It carried
    /// each route's `RouteEntry` posture — in which a record check is the bare
    /// `policy: true` — so swapping one `#[authorize]` check for another left
    /// the digest still.
    #[test]
    fn the_collapsed_csrf_fingerprint_carries_each_routes_bindings() {
        let base = manifest(
            &format!(
                "{},{}",
                route("/a", "POST", "gated", &["admin"], &[], true),
                route("/b", "POST", "gated", &["admin"], &[], true),
            ),
            r#"{"path":"/a","method":"POST","csrf_enforced":true,"exempt":false},
               {"path":"/b","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            r#"{"path":"/a","method":"POST","name":"h","action":"read","resource":"Record","provenance":"provable"}"#,
        );
        let checked_by = |action: &str| {
            diff(
                &base,
                &manifest(
                    &format!(
                        "{},{}",
                        route("/a", "POST", "gated", &["admin"], &[], true),
                        route("/b", "POST", "gated", &["admin"], &[], true),
                    ),
                    r#"{"path":"/a","method":"POST","csrf_enforced":false,"exempt":false},
                       {"path":"/b","method":"POST","csrf_enforced":false,"exempt":false}"#,
                    "",
                    &format!(
                        r#"{{"path":"/a","method":"POST","name":"h","action":"{action}","resource":"Record","provenance":"provable"}}"#
                    ),
                ),
            )
            .into_iter()
            .find(|f| f.kind == "csrf_disabled")
            .expect("csrf off everywhere collapses")
            .canonical()
        };

        assert_ne!(checked_by("read"), checked_by("read_any"));
    }

    /// An exemption acknowledgment says "I accept that these URLs skip CSRF" —
    /// which is a statement about what still guards them. The per-route rows
    /// cannot show the exemption at all (that is why the finding exists), so
    /// nothing else in the diff moves when the routes it covers are loosened
    /// afterwards.
    #[test]
    fn an_exemption_acknowledgment_binds_to_the_routes_it_exempts() {
        let base = manifest_exempt(
            &route("/api/{id}", "POST", "gated", &["admin"], &["mfa"], false),
            r#"{"path":"/api/{id}","method":"POST","csrf_enforced":true,"exempt":false}"#,
            &[],
        );
        let exempting_with = |scopes: &[&str]| {
            diff(
                &base,
                &manifest_exempt(
                    &route("/api/{id}", "POST", "gated", &["admin"], scopes, false),
                    r#"{"path":"/api/{id}","method":"POST","csrf_enforced":true,"exempt":false}"#,
                    &["/api/me"],
                ),
            )
            .into_iter()
            .find(|f| f.kind == "csrf_exemption_added")
            .expect("a new exemption is a widening")
            .canonical()
        };

        assert_ne!(exempting_with(&["mfa"]), exempting_with(&[]));
    }
    /// The header findings were the last constant fingerprints, and I said two
    /// rounds ago that they were fine because a header is emitted or it is not
    /// — true of the *value*, and beside the point. The identity has to carry
    /// the rest of the header posture for the same reason every route
    /// dimension does: removing HSTS while adding CSP is a decision about the
    /// set that results, and dropping CSP afterwards leaves the diff holding
    /// the identical HSTS removal.
    #[test]
    fn a_header_removal_acknowledgment_binds_to_the_headers_that_remain() {
        let base = manifest(
            "",
            "",
            r#"{"header":"strict_transport_security","value":"max-age=63072000","emitted":true}"#,
            "",
        );
        let alongside = |remaining: &str| {
            diff(&base, &manifest("", "", remaining, ""))
                .into_iter()
                .find(|f| f.kind == "security_header_removed")
                .expect("losing HSTS is a widening")
                .canonical()
        };

        assert_ne!(
            alongside(
                r#"{"header":"content_security_policy","value":"default-src 'self'","emitted":true}"#
            ),
            alongside(""),
            "dropping the compensating header has to re-ask"
        );
    }
    /// A removed route's URLs do not always go to one place: deleting
    /// `/records/me/{id}` sends `/records/me/private` to a guarded
    /// `/records/{user}/private` and everything else to `/records/{user}/{id}`,
    /// and `undominated` returns both because neither covers the other's share.
    /// Recording the first meant the collapsed finding — the one identity the
    /// whole-posture pass cannot reach, since its path is `*` — spoke for only
    /// one of them.
    #[test]
    fn a_collapsed_csrf_loss_fingerprints_every_inheritor() {
        let base = manifest(
            &format!(
                "{},{},{},{}",
                route("/records/me/{id}", "POST", "gated", &["admin"], &[], false),
                route(
                    "/records/{user}/private",
                    "POST",
                    "gated",
                    &["admin"],
                    &[],
                    false
                ),
                route(
                    "/records/{user}/{id}",
                    "POST",
                    "gated",
                    &["admin"],
                    &[],
                    false
                ),
                route("/other", "POST", "gated", &["admin"], &[], false),
            ),
            r#"{"path":"/records/me/{id}","method":"POST","csrf_enforced":true,"exempt":false},
               {"path":"/other","method":"POST","csrf_enforced":true,"exempt":false}"#,
            "",
            "",
        );
        // The *second* taker in key order, so the `.find` that recorded one
        // inheritor never selected it.
        let unselected_requiring = |scopes: &[&str]| {
            let finding = diff(
                &base,
                &manifest(
                    &format!(
                        "{},{},{}",
                        route(
                            "/records/{user}/private",
                            "POST",
                            "gated",
                            &["admin"],
                            scopes,
                            false
                        ),
                        route(
                            "/records/{user}/{id}",
                            "POST",
                            "gated",
                            &["admin"],
                            &[],
                            false
                        ),
                        route("/other", "POST", "gated", &["admin"], &[], false),
                    ),
                    r#"{"path":"/other","method":"POST","csrf_enforced":false,"exempt":false}"#,
                    "",
                    "",
                ),
            )
            .into_iter()
            .find(|f| f.kind == "csrf_disabled")
            .expect("csrf off everywhere collapses");
            finding.canonical()
        };

        assert_ne!(
            unselected_requiring(&["mfa"]),
            unselected_requiring(&[]),
            "the inheritor that was not selected still has to move the digest"
        );
    }
}